diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..4522d57dc7d6a100de8c39a6039a4a125ac61c4d --- /dev/null +++ b/.dockerignore @@ -0,0 +1,17 @@ +# The .dockerignore file excludes files from the container build process. +# +# https://docs.docker.com/engine/reference/builder/#dockerignore-file + +# Exclude Git files +.git +.github +.gitignore + +# Exclude Python cache files +__pycache__ +.mypy_cache +.pytest_cache +.ruff_cache + +# Exclude Python virtual environment +/venv diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..2036cc5e400d33657f862b703fcdc8f11666131f --- /dev/null +++ b/.gitattributes @@ -0,0 +1,13 @@ +*.jpg filter=lfs diff=lfs merge=lfs -text +*.jpeg filter=lfs diff=lfs merge=lfs -text +*.mp4 filter=lfs diff=lfs merge=lfs -text +*.png filter=lfs diff=lfs merge=lfs -text +*.xml filter=lfs diff=lfs merge=lfs -text +*.zip filter=lfs diff=lfs merge=lfs -text +*.pdf filter=lfs diff=lfs merge=lfs -text +*.mp3 filter=lfs diff=lfs merge=lfs -text +*.wav filter=lfs diff=lfs merge=lfs -text +*.mpg filter=lfs diff=lfs merge=lfs -text +*.webp filter=lfs diff=lfs merge=lfs -text +*.webm filter=lfs diff=lfs merge=lfs -text +*.gif filter=lfs diff=lfs merge=lfs -text diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..ee89744a4abc2b0907096f7d7db1a1c0fbe1ed11 --- /dev/null +++ b/.gitignore @@ -0,0 +1,31 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +**/__pycache__/ +*.py[cod] +**/*.py[cod] +*$py.class + +# Model weights +**/*.pth +**/*.onnx + +# Ipython notebook +*.ipynb + +# Temporary files or benchmark resources +animations/* +tmp/* + +# more ignores +.DS_Store +*.log +.idea/ +.vscode/ +*.pyc +.ipynb_checkpoints +results/ +data/audio/*.wav +data/video/*.mp4 +ffmpeg-7.0-amd64-static +venv/ +.cog/ diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e37074ec26864bc0d63ae978d58bbd2c379ee7cd --- /dev/null +++ b/Dockerfile @@ -0,0 +1,67 @@ +FROM nvidia/cuda:12.4.0-devel-ubuntu22.04 + +ARG DEBIAN_FRONTEND=noninteractive + +ENV PYTHONUNBUFFERED=1 + +RUN apt-get update && apt-get install --no-install-recommends -y \ + build-essential \ + python3.11 \ + python3-pip \ + python3-dev \ + git \ + curl \ + ffmpeg \ + libglib2.0-0 \ + libsm6 \ + libxrender1 \ + libxext6 \ + && apt-get clean && rm -rf /var/lib/apt/lists/* + +WORKDIR /code + +COPY ./requirements.txt /code/requirements.txt + +# Install pget as root +RUN echo "Installing pget" && \ + curl -o /usr/local/bin/pget -L 'https://github.com/replicate/pget/releases/download/v0.2.1/pget' && \ + chmod +x /usr/local/bin/pget + +# Set up a new user named "user" with user ID 1000 +RUN useradd -m -u 1000 user +# Switch to the "user" user +USER user +# Set home to the user's home directory +ENV HOME=/home/user \ + PATH=/home/user/.local/bin:$PATH + + +# Set home to the user's home directory +ENV PYTHONPATH=$HOME/app \ + PYTHONUNBUFFERED=1 \ + DATA_ROOT=/tmp/data + +RUN echo "Installing requirements.txt" +RUN pip3 install --no-cache-dir --upgrade -r /code/requirements.txt + +# yeah.. this is manual for now +#RUN cd client +#RUN bun i +#RUN bun build ./src/index.tsx --outdir ../public/ + +RUN echo "Installing openmim and mim dependencies" +RUN pip3 install --no-cache-dir -U openmim +RUN mim install mmengine +RUN mim install "mmcv>=2.0.1" +RUN mim install "mmdet>=3.3.0" +RUN mim install "mmpose>=1.3.2" + +WORKDIR $HOME/app + +COPY --chown=user . $HOME/app + +EXPOSE 8080 + +ENV PORT 8080 + +CMD python3 app.py diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..e251a69d97bd1e640bb375911bf771487f90da2d --- /dev/null +++ b/LICENSE @@ -0,0 +1,56 @@ +## For FacePoke (the modifications I made + the server itself) + +MIT License + +Copyright (c) 2024 Julian Bilcke + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +## For LivePortrait + +MIT License + +Copyright (c) 2024 Kuaishou Visual Generation and Interaction Center + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +--- + +The code of InsightFace is released under the MIT License. +The models of InsightFace are for non-commercial research purposes only. + +If you want to use the LivePortrait project for commercial purposes, you +should remove and replace InsightFace’s detection models to fully comply with +the MIT license. diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e61cf4a4069b5309e8ff8bafbe10f0cbfbaa989b --- /dev/null +++ b/README.md @@ -0,0 +1,119 @@ +--- +title: FacePoke +emoji: 💬 +colorFrom: yellow +colorTo: red +sdk: docker +pinned: true +license: mit +header: mini +app_file: app.py +app_port: 8080 +--- + +# FacePoke + + + +## Table of Contents + +- [Introduction](#introduction) +- [Acknowledgements](#acknowledgements) +- [Installation](#installation) + - [Local Setup](#local-setup) + - [Docker Deployment](#docker-deployment) +- [Development](#development) +- [Contributing](#contributing) +- [License](#license) + +## Introduction + +A real-time head transformation app. + +For best performance please run the app from your own machine (local or in the cloud). + +**Repository**: [GitHub - jbilcke-hf/FacePoke](https://github.com/jbilcke-hf/FacePoke) + +You can try the demo but it is a shared space, latency may be high if there are multiple users or if you live far from the datacenter hosting the Hugging Face Space. + +**Live Demo**: [FacePoke on Hugging Face Spaces](https://huggingface.co/spaces/jbilcke-hf/FacePoke) + +## Acknowledgements + +This project is based on LivePortrait: https://arxiv.org/abs/2407.03168 + +It uses the face transformation routines from https://github.com/PowerHouseMan/ComfyUI-AdvancedLivePortrait + +## Installation + +### Local Setup + +1. Clone the repository: + ```bash + git clone https://github.com/jbilcke-hf/FacePoke.git + cd FacePoke + ``` + +2. Install Python dependencies: + ```bash + pip install -r requirements.txt + ``` + +3. Install frontend dependencies: + ```bash + cd client + bun install + ``` + +4. Build the frontend: + ```bash + bun build ./src/index.tsx --outdir ../public/ + ``` + +5. Start the backend server: + ```bash + python app.py + ``` + +6. Open `http://localhost:8080` in your web browser. + +### Docker Deployment + +1. Build the Docker image: + ```bash + docker build -t facepoke . + ``` + +2. Run the container: + ```bash + docker run -p 8080:8080 facepoke + ``` + +3. To deploy to Hugging Face Spaces: + - Fork the repository on GitHub. + - Create a new Space on Hugging Face. + - Connect your GitHub repository to the Space. + - Configure the Space to use the Docker runtime. + +## Development + +The project structure is organized as follows: + +- `app.py`: Main backend server handling WebSocket connections. +- `engine.py`: Core logic. +- `loader.py`: Initializes and loads AI models. +- `client/`: Frontend React application. + - `src/`: TypeScript source files. + - `public/`: Static assets and built files. + +## Contributing + +Contributions to FacePoke are welcome! Please read our [Contributing Guidelines](CONTRIBUTING.md) for details on how to submit pull requests, report issues, or request features. + +## License + +FacePoke is released under the MIT License. See the [LICENSE](LICENSE) file for details. + +--- + +Developed with ❤️ by Julian Bilcke at Hugging Face diff --git a/app.py b/app.py new file mode 100644 index 0000000000000000000000000000000000000000..5499d985b6adf21810d1c80781b681d5ce87ccbc --- /dev/null +++ b/app.py @@ -0,0 +1,264 @@ +""" +FacePoke API + +Author: Julian Bilcke +Date: September 30, 2024 +""" + +import sys +import asyncio +import hashlib +from aiohttp import web, WSMsgType +import json +import uuid +import logging +import os +import zipfile +import signal +from typing import Dict, Any, List, Optional +import base64 +import io +from PIL import Image +import numpy as np + +# Configure logging +logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') +logger = logging.getLogger(__name__) + +# Set asyncio logger to DEBUG level +logging.getLogger("asyncio").setLevel(logging.DEBUG) + +logger.debug(f"Python version: {sys.version}") + +# SIGSEGV handler +def SIGSEGV_signal_arises(signalNum, stack): + logger.critical(f"{signalNum} : SIGSEGV arises") + logger.critical(f"Stack trace: {stack}") + +signal.signal(signal.SIGSEGV, SIGSEGV_signal_arises) + +from loader import initialize_models +from engine import Engine, base64_data_uri_to_PIL_Image, create_engine + +# Global constants +DATA_ROOT = os.environ.get('DATA_ROOT', '/tmp/data') +MODELS_DIR = os.path.join(DATA_ROOT, "models") + +image_cache: Dict[str, Image.Image] = {} + +async def websocket_handler(request: web.Request) -> web.WebSocketResponse: + """ + Handle WebSocket connections for the FacePoke application. + + Args: + request (web.Request): The incoming request object. + + Returns: + web.WebSocketResponse: The WebSocket response object. + """ + ws = web.WebSocketResponse() + await ws.prepare(request) + + session: Optional[FacePokeSession] = None + try: + logger.info("New WebSocket connection established") + + while True: + msg = await ws.receive() + + if msg.type == WSMsgType.TEXT: + data = json.loads(msg.data) + + # let's not log user requests, they are heavy + #logger.debug(f"Received message: {data}") + + if data['type'] == 'modify_image': + uuid = data.get('uuid') + if not uuid: + logger.warning("Received message without UUID") + + await handle_modify_image(request, ws, data, uuid) + + + elif msg.type in (WSMsgType.CLOSE, WSMsgType.ERROR): + logger.warning(f"WebSocket connection closed: {msg.type}") + break + + except Exception as e: + logger.error(f"Error in websocket_handler: {str(e)}") + logger.exception("Full traceback:") + finally: + if session: + await session.stop() + del active_sessions[session.session_id] + logger.info("WebSocket connection closed") + return ws + +async def handle_modify_image(request: web.Request, ws: web.WebSocketResponse, msg: Dict[str, Any], uuid: str): + """ + Handle the 'modify_image' request. + + Args: + request (web.Request): The incoming request object. + ws (web.WebSocketResponse): The WebSocket response object. + msg (Dict[str, Any]): The message containing the image or image_hash and modification parameters. + uuid: A unique identifier for the request. + """ + logger.info("Received modify_image request") + try: + engine = request.app['engine'] + image_hash = msg.get('image_hash') + + if image_hash: + image_or_hash = image_hash + else: + image_data = msg['image'] + image_or_hash = image_data + + modified_image_base64 = await engine.modify_image(image_or_hash, msg['params']) + + await ws.send_json({ + "type": "modified_image", + "image": modified_image_base64, + "image_hash": engine.get_image_hash(image_or_hash), + "success": True, + "uuid": uuid # Include the UUID in the response + }) + logger.info("Successfully sent modified image") + except Exception as e: + logger.error(f"Error in modify_image: {str(e)}") + await ws.send_json({ + "type": "modified_image", + "success": False, + "error": str(e), + "uuid": uuid # Include the UUID even in error responses + }) + +async def index(request: web.Request) -> web.Response: + """Serve the index.html file""" + content = open(os.path.join(os.path.dirname(__file__), "public", "index.html"), "r").read() + return web.Response(content_type="text/html", text=content) + +async def js_index(request: web.Request) -> web.Response: + """Serve the index.js file""" + content = open(os.path.join(os.path.dirname(__file__), "public", "index.js"), "r").read() + return web.Response(content_type="application/javascript", text=content) + +async def hf_logo(request: web.Request) -> web.Response: + """Serve the hf-logo.svg file""" + content = open(os.path.join(os.path.dirname(__file__), "public", "hf-logo.svg"), "r").read() + return web.Response(content_type="image/svg+xml", text=content) + +async def on_shutdown(app: web.Application): + """Cleanup function to be called on server shutdown.""" + logger.info("Server shutdown initiated, cleaning up resources...") + for session in list(active_sessions.values()): + await session.stop() + active_sessions.clear() + logger.info("All active sessions have been closed") + + if 'engine' in app: + await app['engine'].cleanup() + logger.info("Engine instance cleaned up") + + logger.info("Server shutdown complete") + +async def initialize_app() -> web.Application: + """Initialize and configure the web application.""" + try: + logger.info("Initializing application...") + models = await initialize_models() + logger.info("🚀 Creating Engine instance...") + engine = create_engine(models) + logger.info("✅ Engine instance created.") + + app = web.Application() + app['engine'] = engine + + app.on_shutdown.append(on_shutdown) + + # Configure routes + app.router.add_get("/", index) + app.router.add_get("/index.js", js_index) + app.router.add_get("/hf-logo.svg", hf_logo) + app.router.add_get("/ws", websocket_handler) + + logger.info("Application routes configured") + + return app + except Exception as e: + logger.error(f"🚨 Error during application initialization: {str(e)}") + logger.exception("Full traceback:") + raise + +async def start_background_tasks(app: web.Application): + """ + Start background tasks for the application. + + Args: + app (web.Application): The web application instance. + """ + app['cleanup_task'] = asyncio.create_task(periodic_cleanup(app)) + +async def cleanup_background_tasks(app: web.Application): + """ + Clean up background tasks when the application is shutting down. + + Args: + app (web.Application): The web application instance. + """ + app['cleanup_task'].cancel() + await app['cleanup_task'] + +async def periodic_cleanup(app: web.Application): + """ + Perform periodic cleanup tasks for the application. + + Args: + app (web.Application): The web application instance. + """ + while True: + try: + await asyncio.sleep(3600) # Run cleanup every hour + await cleanup_inactive_sessions(app) + except asyncio.CancelledError: + break + except Exception as e: + logger.error(f"Error in periodic cleanup: {str(e)}") + logger.exception("Full traceback:") + +async def cleanup_inactive_sessions(app: web.Application): + """ + Clean up inactive sessions. + + Args: + app (web.Application): The web application instance. + """ + logger.info("Starting cleanup of inactive sessions") + inactive_sessions = [ + session_id for session_id, session in active_sessions.items() + if not session.is_running.is_set() + ] + for session_id in inactive_sessions: + session = active_sessions.pop(session_id) + await session.stop() + logger.info(f"Cleaned up inactive session: {session_id}") + logger.info(f"Cleaned up {len(inactive_sessions)} inactive sessions") + +def main(): + """ + Main function to start the FacePoke application. + """ + try: + logger.info("Starting FacePoke application") + app = asyncio.run(initialize_app()) + app.on_startup.append(start_background_tasks) + app.on_cleanup.append(cleanup_background_tasks) + logger.info("Application initialized, starting web server") + web.run_app(app, host="0.0.0.0", port=8080) + except Exception as e: + logger.critical(f"🚨 FATAL: Failed to start the app: {str(e)}") + logger.exception("Full traceback:") + +if __name__ == "__main__": + main() diff --git a/build.sh b/build.sh new file mode 100644 index 0000000000000000000000000000000000000000..0d88a73562f0262957177921f17c456fce8cc3de --- /dev/null +++ b/build.sh @@ -0,0 +1,3 @@ +cd client +bun i +bun build ./src/index.tsx --outdir ../public/ diff --git a/client/.gitignore b/client/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..9b1ee42e8482ee945f6adc02615ef33db69a0c2f --- /dev/null +++ b/client/.gitignore @@ -0,0 +1,175 @@ +# Based on https://raw.githubusercontent.com/github/gitignore/main/Node.gitignore + +# Logs + +logs +_.log +npm-debug.log_ +yarn-debug.log* +yarn-error.log* +lerna-debug.log* +.pnpm-debug.log* + +# Caches + +.cache + +# Diagnostic reports (https://nodejs.org/api/report.html) + +report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json + +# Runtime data + +pids +_.pid +_.seed +*.pid.lock + +# Directory for instrumented libs generated by jscoverage/JSCover + +lib-cov + +# Coverage directory used by tools like istanbul + +coverage +*.lcov + +# nyc test coverage + +.nyc_output + +# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) + +.grunt + +# Bower dependency directory (https://bower.io/) + +bower_components + +# node-waf configuration + +.lock-wscript + +# Compiled binary addons (https://nodejs.org/api/addons.html) + +build/Release + +# Dependency directories + +node_modules/ +jspm_packages/ + +# Snowpack dependency directory (https://snowpack.dev/) + +web_modules/ + +# TypeScript cache + +*.tsbuildinfo + +# Optional npm cache directory + +.npm + +# Optional eslint cache + +.eslintcache + +# Optional stylelint cache + +.stylelintcache + +# Microbundle cache + +.rpt2_cache/ +.rts2_cache_cjs/ +.rts2_cache_es/ +.rts2_cache_umd/ + +# Optional REPL history + +.node_repl_history + +# Output of 'npm pack' + +*.tgz + +# Yarn Integrity file + +.yarn-integrity + +# dotenv environment variable files + +.env +.env.development.local +.env.test.local +.env.production.local +.env.local + +# parcel-bundler cache (https://parceljs.org/) + +.parcel-cache + +# Next.js build output + +.next +out + +# Nuxt.js build / generate output + +.nuxt +dist + +# Gatsby files + +# Comment in the public line in if your project uses Gatsby and not Next.js + +# https://nextjs.org/blog/next-9-1#public-directory-support + +# public + +# vuepress build output + +.vuepress/dist + +# vuepress v2.x temp and cache directory + +.temp + +# Docusaurus cache and generated files + +.docusaurus + +# Serverless directories + +.serverless/ + +# FuseBox cache + +.fusebox/ + +# DynamoDB Local files + +.dynamodb/ + +# TernJS port file + +.tern-port + +# Stores VSCode versions used for testing VSCode extensions + +.vscode-test + +# yarn v2 + +.yarn/cache +.yarn/unplugged +.yarn/build-state.yml +.yarn/install-state.gz +.pnp.* + +# IntelliJ based IDEs +.idea + +# Finder (MacOS) folder config +.DS_Store diff --git a/client/README.md b/client/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b4dabd8f19d2545c23550eeb8e11595ad86f3955 --- /dev/null +++ b/client/README.md @@ -0,0 +1,13 @@ +# FacePoke.js + +To install dependencies: + +```bash +bun i +``` + +To build: + +```bash +bun build ./src/index.tsx --outdir ../public +``` diff --git a/client/bun.lockb b/client/bun.lockb new file mode 100755 index 0000000000000000000000000000000000000000..2d76d6e717ba59a69fa2fa05f97da435a3fddcbd Binary files /dev/null and b/client/bun.lockb differ diff --git a/client/package.json b/client/package.json new file mode 100644 index 0000000000000000000000000000000000000000..3d3c437d70b7ab1b1201806616b5e52e01b205cc --- /dev/null +++ b/client/package.json @@ -0,0 +1,35 @@ +{ + "name": "@aitube/facepoke", + "module": "src/index.ts", + "type": "module", + "scripts": { + "build": "bun build ./src/index.tsx --outdir ../public/" + }, + "devDependencies": { + "@types/bun": "latest" + }, + "peerDependencies": { + "typescript": "^5.0.0" + }, + "dependencies": { + "@mediapipe/tasks-vision": "^0.10.16", + "@radix-ui/react-icons": "^1.3.0", + "@types/lodash": "^4.17.10", + "@types/react": "^18.3.9", + "@types/react-dom": "^18.3.0", + "@types/uuid": "^10.0.0", + "beautiful-react-hooks": "^5.0.2", + "class-variance-authority": "^0.7.0", + "clsx": "^2.1.1", + "lodash": "^4.17.21", + "lucide-react": "^0.446.0", + "react": "^18.3.1", + "react-dom": "^18.3.1", + "tailwind-merge": "^2.5.2", + "tailwindcss": "^3.4.13", + "tailwindcss-animate": "^1.0.7", + "usehooks-ts": "^3.1.0", + "uuid": "^10.0.0", + "zustand": "^5.0.0-rc.2" + } +} diff --git a/client/src/app.tsx b/client/src/app.tsx new file mode 100644 index 0000000000000000000000000000000000000000..f7ea7b827f1f3724fed5309befa8b93c82536dd2 --- /dev/null +++ b/client/src/app.tsx @@ -0,0 +1,190 @@ +import React, { useState, useEffect, useRef, useCallback, useMemo } from 'react'; +import { RotateCcw } from 'lucide-react'; + +import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'; +import { truncateFileName } from './lib/utils'; +import { useFaceLandmarkDetection } from './hooks/useFaceLandmarkDetection'; +import { PoweredBy } from './components/PoweredBy'; +import { Spinner } from './components/Spinner'; +import { DoubleCard } from './components/DoubleCard'; +import { useFacePokeAPI } from './hooks/useFacePokeAPI'; +import { Layout } from './layout'; +import { useMainStore } from './hooks/useMainStore'; +import { convertImageToBase64 } from './lib/convertImageToBase64'; + +export function App() { + const error = useMainStore(s => s.error); + const setError = useMainStore(s => s.setError); + const imageFile = useMainStore(s => s.imageFile); + const setImageFile = useMainStore(s => s.setImageFile); + const originalImage = useMainStore(s => s.originalImage); + const setOriginalImage = useMainStore(s => s.setOriginalImage); + const previewImage = useMainStore(s => s.previewImage); + const setPreviewImage = useMainStore(s => s.setPreviewImage); + const resetImage = useMainStore(s => s.resetImage); + + const { + status, + setStatus, + isDebugMode, + setIsDebugMode, + interruptMessage, + } = useFacePokeAPI() + + // State for face detection + const { + canvasRef, + canvasRefCallback, + mediaPipeRef, + faceLandmarks, + isMediaPipeReady, + blendShapes, + + setFaceLandmarks, + setBlendShapes, + + handleMouseDown, + handleMouseUp, + handleMouseMove, + handleMouseEnter, + handleMouseLeave, + currentOpacity + } = useFaceLandmarkDetection() + + // Refs + const videoRef = useRef<HTMLDivElement>(null); + + // Handle file change + const handleFileChange = useCallback(async (event: React.ChangeEvent<HTMLInputElement>) => { + const files = event.target.files; + if (files && files[0]) { + setImageFile(files[0]); + setStatus(`File selected: ${truncateFileName(files[0].name, 16)}`); + + try { + const image = await convertImageToBase64(files[0]); + setPreviewImage(image); + setOriginalImage(image); + } catch (err) { + console.log(`failed to convert the image: `, err); + setImageFile(null); + setStatus(''); + setPreviewImage(''); + setOriginalImage(''); + setFaceLandmarks([]); + setBlendShapes([]); + } + } else { + setImageFile(null); + setStatus(''); + setPreviewImage(''); + setOriginalImage(''); + setFaceLandmarks([]); + setBlendShapes([]); + } + }, [isMediaPipeReady, setImageFile, setPreviewImage, setOriginalImage, setFaceLandmarks, setBlendShapes, setStatus]); + + const canDisplayBlendShapes = false + + // Display blend shapes + const displayBlendShapes = useMemo(() => ( + <div className="mt-4"> + <h3 className="text-lg font-semibold mb-2">Blend Shapes</h3> + <ul className="space-y-1"> + {(blendShapes?.[0]?.categories || []).map((shape, index) => ( + <li key={index} className="flex items-center"> + <span className="w-32 text-sm">{shape.categoryName || shape.displayName}</span> + <div className="w-full bg-gray-200 rounded-full h-2.5"> + <div + className="bg-blue-600 h-2.5 rounded-full" + style={{ width: `${shape.score * 100}%` }} + ></div> + </div> + <span className="ml-2 text-sm">{shape.score.toFixed(2)}</span> + </li> + ))} + </ul> + </div> + ), [JSON.stringify(blendShapes)]) + + // JSX + return ( + <Layout> + {error && ( + <Alert variant="destructive"> + <AlertTitle>Error</AlertTitle> + <AlertDescription>{error}</AlertDescription> + </Alert> + )} + {interruptMessage && ( + <Alert> + <AlertTitle>Notice</AlertTitle> + <AlertDescription>{interruptMessage}</AlertDescription> + </Alert> + )} + <div className="mb-5 relative"> + <div className="flex flex-row items-center justify-between w-full"> + <div className="relative"> + <input + id="imageInput" + type="file" + accept="image/*" + onChange={handleFileChange} + className="hidden" + disabled={!isMediaPipeReady} + /> + <label + htmlFor="imageInput" + className={`cursor-pointer inline-flex items-center px-3 py-1.5 border border-transparent text-sm font-medium rounded-md text-white ${ + isMediaPipeReady ? 'bg-gray-600 hover:bg-gray-500' : 'bg-gray-500 cursor-not-allowed' + } focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500 shadow-xl`} + > + <Spinner /> + {imageFile ? truncateFileName(imageFile.name, 32) : (isMediaPipeReady ? 'Choose an image' : 'Initializing...')} + </label> + </div> + {previewImage && <label className="mt-4 flex items-center"> + <input + type="checkbox" + checked={isDebugMode} + onChange={(e) => setIsDebugMode(e.target.checked)} + className="mr-2" + /> + Show face landmarks on hover + </label>} + </div> + {previewImage && ( + <div className="mt-5 relative shadow-2xl rounded-xl overflow-hidden"> + <img + src={previewImage} + alt="Preview" + className="w-full" + /> + <canvas + ref={canvasRefCallback} + className="absolute top-0 left-0 w-full h-full select-none" + onMouseEnter={handleMouseEnter} + onMouseLeave={handleMouseLeave} + onMouseDown={handleMouseDown} + onMouseUp={handleMouseUp} + onMouseMove={handleMouseMove} + style={{ + position: 'absolute', + top: 0, + left: 0, + width: '100%', + height: '100%', + opacity: isDebugMode ? currentOpacity : 0.0, + transition: 'opacity 0.2s ease-in-out' + }} + + /> + </div> + )} + {canDisplayBlendShapes && displayBlendShapes} + </div> + <PoweredBy /> + + </Layout> + ); +} diff --git a/client/src/components/DoubleCard.tsx b/client/src/components/DoubleCard.tsx new file mode 100644 index 0000000000000000000000000000000000000000..247ecc959f78b2f26602bd3e437fabd7e69e7b3f --- /dev/null +++ b/client/src/components/DoubleCard.tsx @@ -0,0 +1,18 @@ +import React, { type ReactNode } from 'react'; + +export function DoubleCard({ children }: { children: ReactNode }) { + return ( + <> + <div className="absolute inset-0 bg-gradient-to-r from-cyan-200 to-sky-300 shadow-2xl transform -skew-y-6 sm:skew-y-0 sm:-rotate-6 sm:rounded-3xl" style={{ borderTop: "solid 2px rgba(255, 255, 255, 0.2)" }}></div> + <div className="relative px-5 py-8 bg-gradient-to-r from-cyan-100 to-sky-200 shadow-2xl sm:rounded-3xl sm:p-12" style={{ borderTop: "solid 2px #ffffff33" }}> + <div className="max-w-lg mx-auto"> + <div className="divide-y divide-gray-200"> + <div className="text-lg leading-7 space-y-5 text-gray-700 sm:text-xl sm:leading-8"> + {children} + </div> + </div> + </div> + </div> + </> + ); +} diff --git a/client/src/components/PoweredBy.tsx b/client/src/components/PoweredBy.tsx new file mode 100644 index 0000000000000000000000000000000000000000..5dddccb160a223a9851bc80eec2881ae0c9b59d7 --- /dev/null +++ b/client/src/components/PoweredBy.tsx @@ -0,0 +1,17 @@ +export function PoweredBy() { + return ( + <div className="flex flex-row items-center justify-center font-sans mt-4 w-full"> + {/*<span className="text-neutral-900 text-sm" + style={{ textShadow: "rgb(255 255 255 / 80%) 0px 0px 2px" }}> + Best hosted on + </span>*/} + <span className="ml-2 mr-1"> + <img src="/hf-logo.svg" alt="Hugging Face" className="w-5 h-5" /> + </span> + <span className="text-neutral-900 text-sm font-semibold" + style={{ textShadow: "rgb(255 255 255 / 80%) 0px 0px 2px" }}> + Hugging Face + </span> + </div> + ) +} diff --git a/client/src/components/Spinner.tsx b/client/src/components/Spinner.tsx new file mode 100644 index 0000000000000000000000000000000000000000..008f9a394aedcc4e7e77430279cead8f373bcfdc --- /dev/null +++ b/client/src/components/Spinner.tsx @@ -0,0 +1,7 @@ +export function Spinner() { + return ( + <svg className="mr-3 h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"> + <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" /> + </svg> + ) +} diff --git a/client/src/components/Title.tsx b/client/src/components/Title.tsx new file mode 100644 index 0000000000000000000000000000000000000000..408a6c71b525a593407465890262b3a17635b22c --- /dev/null +++ b/client/src/components/Title.tsx @@ -0,0 +1,8 @@ +export function Title() { + return ( + <h2 className="bg-gradient-to-bl from-sky-500 to-sky-800 bg-clip-text text-5xl font-extrabold text-transparent leading-normal text-center" + style={{ textShadow: "rgb(176 229 255 / 61%) 0px 0px 2px" }}> + 💬 FacePoke + </h2> + ) +} diff --git a/client/src/components/ui/alert.tsx b/client/src/components/ui/alert.tsx new file mode 100644 index 0000000000000000000000000000000000000000..41fa7e0561a3fdb5f986c1213a35e563de740e96 --- /dev/null +++ b/client/src/components/ui/alert.tsx @@ -0,0 +1,59 @@ +import * as React from "react" +import { cva, type VariantProps } from "class-variance-authority" + +import { cn } from "@/lib/utils" + +const alertVariants = cva( + "relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground", + { + variants: { + variant: { + default: "bg-background text-foreground", + destructive: + "border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive", + }, + }, + defaultVariants: { + variant: "default", + }, + } +) + +const Alert = React.forwardRef< + HTMLDivElement, + React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof alertVariants> +>(({ className, variant, ...props }, ref) => ( + <div + ref={ref} + role="alert" + className={cn(alertVariants({ variant }), className)} + {...props} + /> +)) +Alert.displayName = "Alert" + +const AlertTitle = React.forwardRef< + HTMLParagraphElement, + React.HTMLAttributes<HTMLHeadingElement> +>(({ className, ...props }, ref) => ( + <h5 + ref={ref} + className={cn("mb-1 font-medium leading-none tracking-tight", className)} + {...props} + /> +)) +AlertTitle.displayName = "AlertTitle" + +const AlertDescription = React.forwardRef< + HTMLParagraphElement, + React.HTMLAttributes<HTMLParagraphElement> +>(({ className, ...props }, ref) => ( + <div + ref={ref} + className={cn("text-sm [&_p]:leading-relaxed", className)} + {...props} + /> +)) +AlertDescription.displayName = "AlertDescription" + +export { Alert, AlertTitle, AlertDescription } diff --git a/client/src/hooks/landmarks.ts b/client/src/hooks/landmarks.ts new file mode 100644 index 0000000000000000000000000000000000000000..e8b30c694925b4f7d8b890a1959daa5a3a6cc14b --- /dev/null +++ b/client/src/hooks/landmarks.ts @@ -0,0 +1,520 @@ +import * as vision from '@mediapipe/tasks-vision'; + +// Define unique colors for each landmark group +export const landmarkColors: { [key: string]: string } = { + lips: '#FF0000', + leftEye: '#00FF00', + leftEyebrow: '#0000FF', + leftIris: '#FFFF00', + rightEye: '#FF00FF', + rightEyebrow: '#00FFFF', + rightIris: '#FFA500', + faceOval: '#800080', + tesselation: '#C0C0C0', +}; + +// Define landmark groups with their semantic names +export const landmarkGroups: { [key: string]: any } = { + lips: vision.FaceLandmarker.FACE_LANDMARKS_LIPS, + leftEye: vision.FaceLandmarker.FACE_LANDMARKS_LEFT_EYE, + leftEyebrow: vision.FaceLandmarker.FACE_LANDMARKS_LEFT_EYEBROW, + leftIris: vision.FaceLandmarker.FACE_LANDMARKS_LEFT_IRIS, + rightEye: vision.FaceLandmarker.FACE_LANDMARKS_RIGHT_EYE, + rightEyebrow: vision.FaceLandmarker.FACE_LANDMARKS_RIGHT_EYEBROW, + rightIris: vision.FaceLandmarker.FACE_LANDMARKS_RIGHT_IRIS, + faceOval: vision.FaceLandmarker.FACE_LANDMARKS_FACE_OVAL, + // tesselation: vision.FaceLandmarker.FACE_LANDMARKS_TESSELATION, +}; + +export const FACEMESH_LIPS = Object.freeze(new Set([[61, 146], [146, 91], [91, 181], [181, 84], [84, 17], + [17, 314], [314, 405], [405, 321], [321, 375], + [375, 291], [61, 185], [185, 40], [40, 39], [39, 37], + [37, 0], [0, 267], + [267, 269], [269, 270], [270, 409], [409, 291], + [78, 95], [95, 88], [88, 178], [178, 87], [87, 14], + [14, 317], [317, 402], [402, 318], [318, 324], + [324, 308], [78, 191], [191, 80], [80, 81], [81, 82], + [82, 13], [13, 312], [312, 311], [311, 310], + [310, 415], [415, 308]])) + +export const FACEMESH_LEFT_EYE = Object.freeze(new Set([[263, 249], [249, 390], [390, 373], [373, 374], + [374, 380], [380, 381], [381, 382], [382, 362], + [263, 466], [466, 388], [388, 387], [387, 386], + [386, 385], [385, 384], [384, 398], [398, 362]])) + +export const FACEMESH_LEFT_IRIS = Object.freeze(new Set([[474, 475], [475, 476], [476, 477], + [477, 474]])) + +export const FACEMESH_LEFT_EYEBROW = Object.freeze(new Set([[276, 283], [283, 282], [282, 295], + [295, 285], [300, 293], [293, 334], + [334, 296], [296, 336]])) + +export const FACEMESH_RIGHT_EYE = Object.freeze(new Set([[33, 7], [7, 163], [163, 144], [144, 145], + [145, 153], [153, 154], [154, 155], [155, 133], + [33, 246], [246, 161], [161, 160], [160, 159], + [159, 158], [158, 157], [157, 173], [173, 133]])) + +export const FACEMESH_RIGHT_EYEBROW = Object.freeze(new Set([[46, 53], [53, 52], [52, 65], [65, 55], + [70, 63], [63, 105], [105, 66], [66, 107]])) + +export const FACEMESH_RIGHT_IRIS = Object.freeze(new Set([[469, 470], [470, 471], [471, 472], + [472, 469]])) + +export const FACEMESH_FACE_OVAL = Object.freeze(new Set([[10, 338], [338, 297], [297, 332], [332, 284], + [284, 251], [251, 389], [389, 356], [356, 454], + [454, 323], [323, 361], [361, 288], [288, 397], + [397, 365], [365, 379], [379, 378], [378, 400], + [400, 377], [377, 152], [152, 148], [148, 176], + [176, 149], [149, 150], [150, 136], [136, 172], + [172, 58], [58, 132], [132, 93], [93, 234], + [234, 127], [127, 162], [162, 21], [21, 54], + [54, 103], [103, 67], [67, 109], [109, 10]])) + +export const FACEMESH_NOSE = Object.freeze(new Set([[168, 6], [6, 197], [197, 195], [195, 5], + [5, 4], [4, 1], [1, 19], [19, 94], [94, 2], [98, 97], + [97, 2], [2, 326], [326, 327], [327, 294], + [294, 278], [278, 344], [344, 440], [440, 275], + [275, 4], [4, 45], [45, 220], [220, 115], [115, 48], + [48, 64], [64, 98]])) + +export const FACEMESH_CONTOURS = Object.freeze(new Set([ + ...FACEMESH_LIPS, + ...FACEMESH_LEFT_EYE, + ...FACEMESH_LEFT_EYEBROW, + ...FACEMESH_RIGHT_EYE, + ...FACEMESH_RIGHT_EYEBROW, + ...FACEMESH_FACE_OVAL +])); + +export const FACEMESH_IRISES = Object.freeze(new Set([ + ...FACEMESH_LEFT_IRIS, + ...FACEMESH_RIGHT_IRIS +])); + +export const FACEMESH_TESSELATION = Object.freeze(new Set([ + [127, 34], [34, 139], [139, 127], [11, 0], [0, 37], [37, 11], + [232, 231], [231, 120], [120, 232], [72, 37], [37, 39], [39, 72], + [128, 121], [121, 47], [47, 128], [232, 121], [121, 128], [128, 232], + [104, 69], [69, 67], [67, 104], [175, 171], [171, 148], [148, 175], + [118, 50], [50, 101], [101, 118], [73, 39], [39, 40], [40, 73], + [9, 151], [151, 108], [108, 9], [48, 115], [115, 131], [131, 48], + [194, 204], [204, 211], [211, 194], [74, 40], [40, 185], [185, 74], + [80, 42], [42, 183], [183, 80], [40, 92], [92, 186], [186, 40], + [230, 229], [229, 118], [118, 230], [202, 212], [212, 214], [214, 202], + [83, 18], [18, 17], [17, 83], [76, 61], [61, 146], [146, 76], + [160, 29], [29, 30], [30, 160], [56, 157], [157, 173], [173, 56], + [106, 204], [204, 194], [194, 106], [135, 214], [214, 192], [192, 135], + [203, 165], [165, 98], [98, 203], [21, 71], [71, 68], [68, 21], + [51, 45], [45, 4], [4, 51], [144, 24], [24, 23], [23, 144], + [77, 146], [146, 91], [91, 77], [205, 50], [50, 187], [187, 205], + [201, 200], [200, 18], [18, 201], [91, 106], [106, 182], [182, 91], + [90, 91], [91, 181], [181, 90], [85, 84], [84, 17], [17, 85], + [206, 203], [203, 36], [36, 206], [148, 171], [171, 140], [140, 148], + [92, 40], [40, 39], [39, 92], [193, 189], [189, 244], [244, 193], + [159, 158], [158, 28], [28, 159], [247, 246], [246, 161], [161, 247], + [236, 3], [3, 196], [196, 236], [54, 68], [68, 104], [104, 54], + [193, 168], [168, 8], [8, 193], [117, 228], [228, 31], [31, 117], + [189, 193], [193, 55], [55, 189], [98, 97], [97, 99], [99, 98], + [126, 47], [47, 100], [100, 126], [166, 79], [79, 218], [218, 166], + [155, 154], [154, 26], [26, 155], [209, 49], [49, 131], [131, 209], + [135, 136], [136, 150], [150, 135], [47, 126], [126, 217], [217, 47], + [223, 52], [52, 53], [53, 223], [45, 51], [51, 134], [134, 45], + [211, 170], [170, 140], [140, 211], [67, 69], [69, 108], [108, 67], + [43, 106], [106, 91], [91, 43], [230, 119], [119, 120], [120, 230], + [226, 130], [130, 247], [247, 226], [63, 53], [53, 52], [52, 63], + [238, 20], [20, 242], [242, 238], [46, 70], [70, 156], [156, 46], + [78, 62], [62, 96], [96, 78], [46, 53], [53, 63], [63, 46], + [143, 34], [34, 227], [227, 143], [123, 117], [117, 111], [111, 123], + [44, 125], [125, 19], [19, 44], [236, 134], [134, 51], [51, 236], + [216, 206], [206, 205], [205, 216], [154, 153], [153, 22], [22, 154], + [39, 37], [37, 167], [167, 39], [200, 201], [201, 208], [208, 200], + [36, 142], [142, 100], [100, 36], [57, 212], [212, 202], [202, 57], + [20, 60], [60, 99], [99, 20], [28, 158], [158, 157], [157, 28], + [35, 226], [226, 113], [113, 35], [160, 159], [159, 27], [27, 160], + [204, 202], [202, 210], [210, 204], [113, 225], [225, 46], [46, 113], + [43, 202], [202, 204], [204, 43], [62, 76], [76, 77], [77, 62], + [137, 123], [123, 116], [116, 137], [41, 38], [38, 72], [72, 41], + [203, 129], [129, 142], [142, 203], [64, 98], [98, 240], [240, 64], + [49, 102], [102, 64], [64, 49], [41, 73], [73, 74], [74, 41], + [212, 216], [216, 207], [207, 212], [42, 74], [74, 184], [184, 42], + [169, 170], [170, 211], [211, 169], [170, 149], [149, 176], [176, 170], + [105, 66], [66, 69], [69, 105], [122, 6], [6, 168], [168, 122], + [123, 147], [147, 187], [187, 123], [96, 77], [77, 90], [90, 96], + [65, 55], [55, 107], [107, 65], [89, 90], [90, 180], [180, 89], + [101, 100], [100, 120], [120, 101], [63, 105], [105, 104], [104, 63], + [93, 137], [137, 227], [227, 93], [15, 86], [86, 85], [85, 15], + [129, 102], [102, 49], [49, 129], [14, 87], [87, 86], [86, 14], + [55, 8], [8, 9], [9, 55], [100, 47], [47, 121], [121, 100], + [145, 23], [23, 22], [22, 145], [88, 89], [89, 179], [179, 88], + [6, 122], [122, 196], [196, 6], [88, 95], [95, 96], [96, 88], + [138, 172], [172, 136], [136, 138], [215, 58], [58, 172], [172, 215], + [115, 48], [48, 219], [219, 115], [42, 80], [80, 81], [81, 42], + [195, 3], [3, 51], [51, 195], [43, 146], [146, 61], [61, 43], + [171, 175], [175, 199], [199, 171], [81, 82], [82, 38], [38, 81], + [53, 46], [46, 225], [225, 53], [144, 163], [163, 110], [110, 144], + [52, 65], [65, 66], [66, 52], [229, 228], [228, 117], [117, 229], + [34, 127], [127, 234], [234, 34], [107, 108], [108, 69], [69, 107], + [109, 108], [108, 151], [151, 109], [48, 64], [64, 235], [235, 48], + [62, 78], [78, 191], [191, 62], [129, 209], [209, 126], [126, 129], + [111, 35], [35, 143], [143, 111], [117, 123], [123, 50], [50, 117], + [222, 65], [65, 52], [52, 222], [19, 125], [125, 141], [141, 19], + [221, 55], [55, 65], [65, 221], [3, 195], [195, 197], [197, 3], + [25, 7], [7, 33], [33, 25], [220, 237], [237, 44], [44, 220], + [70, 71], [71, 139], [139, 70], [122, 193], [193, 245], [245, 122], + [247, 130], [130, 33], [33, 247], [71, 21], [21, 162], [162, 71], + [170, 169], [169, 150], [150, 170], [188, 174], [174, 196], [196, 188], + [216, 186], [186, 92], [92, 216], [2, 97], [97, 167], [167, 2], + [141, 125], [125, 241], [241, 141], [164, 167], [167, 37], [37, 164], + [72, 38], [38, 12], [12, 72], [38, 82], [82, 13], [13, 38], + [63, 68], [68, 71], [71, 63], [226, 35], [35, 111], [111, 226], + [101, 50], [50, 205], [205, 101], [206, 92], [92, 165], [165, 206], + [209, 198], [198, 217], [217, 209], [165, 167], [167, 97], [97, 165], + [220, 115], [115, 218], [218, 220], [133, 112], [112, 243], [243, 133], + [239, 238], [238, 241], [241, 239], [214, 135], [135, 169], [169, 214], + [190, 173], [173, 133], [133, 190], [171, 208], [208, 32], [32, 171], + [125, 44], [44, 237], [237, 125], [86, 87], [87, 178], [178, 86], + [85, 86], [86, 179], [179, 85], [84, 85], [85, 180], [180, 84], + [83, 84], [84, 181], [181, 83], [201, 83], [83, 182], [182, 201], + [137, 93], [93, 132], [132, 137], [76, 62], [62, 183], [183, 76], + [61, 76], [76, 184], [184, 61], [57, 61], [61, 185], [185, 57], + [212, 57], [57, 186], [186, 212], [214, 207], [207, 187], [187, 214], + [34, 143], [143, 156], [156, 34], [79, 239], [239, 237], [237, 79], + [123, 137], [137, 177], [177, 123], [44, 1], [1, 4], [4, 44], + [201, 194], [194, 32], [32, 201], [64, 102], [102, 129], [129, 64], + [213, 215], [215, 138], [138, 213], [59, 166], [166, 219], [219, 59], + [242, 99], [99, 97], [97, 242], [2, 94], [94, 141], [141, 2], + [75, 59], [59, 235], [235, 75], [24, 110], [110, 228], [228, 24], + [25, 130], [130, 226], [226, 25], [23, 24], [24, 229], [229, 23], + [22, 23], [23, 230], [230, 22], [26, 22], [22, 231], [231, 26], + [112, 26], [26, 232], [232, 112], [189, 190], [190, 243], [243, 189], + [221, 56], [56, 190], [190, 221], [28, 56], [56, 221], [221, 28], + [27, 28], [28, 222], [222, 27], [29, 27], [27, 223], [223, 29], + [30, 29], [29, 224], [224, 30], [247, 30], [30, 225], [225, 247], + [238, 79], [79, 20], [20, 238], [166, 59], [59, 75], [75, 166], + [60, 75], [75, 240], [240, 60], [147, 177], [177, 215], [215, 147], + [20, 79], [79, 166], [166, 20], [187, 147], [147, 213], [213, 187], + [112, 233], [233, 244], [244, 112], [233, 128], [128, 245], [245, 233], + [128, 114], [114, 188], [188, 128], [114, 217], [217, 174], [174, 114], + [131, 115], [115, 220], [220, 131], [217, 198], [198, 236], [236, 217], + [198, 131], [131, 134], [134, 198], [177, 132], [132, 58], [58, 177], + [143, 35], [35, 124], [124, 143], [110, 163], [163, 7], [7, 110], + [228, 110], [110, 25], [25, 228], [356, 389], [389, 368], [368, 356], + [11, 302], [302, 267], [267, 11], [452, 350], [350, 349], [349, 452], + [302, 303], [303, 269], [269, 302], [357, 343], [343, 277], [277, 357], + [452, 453], [453, 357], [357, 452], [333, 332], [332, 297], [297, 333], + [175, 152], [152, 377], [377, 175], [347, 348], [348, 330], [330, 347], + [303, 304], [304, 270], [270, 303], [9, 336], [336, 337], [337, 9], + [278, 279], [279, 360], [360, 278], [418, 262], [262, 431], [431, 418], + [304, 408], [408, 409], [409, 304], [310, 415], [415, 407], [407, 310], + [270, 409], [409, 410], [410, 270], [450, 348], [348, 347], [347, 450], + [422, 430], [430, 434], [434, 422], [313, 314], [314, 17], [17, 313], + [306, 307], [307, 375], [375, 306], [387, 388], [388, 260], [260, 387], + [286, 414], [414, 398], [398, 286], [335, 406], [406, 418], [418, 335], + [364, 367], [367, 416], [416, 364], [423, 358], [358, 327], [327, 423], + [251, 284], [284, 298], [298, 251], [281, 5], [5, 4], [4, 281], + [373, 374], [374, 253], [253, 373], [307, 320], [320, 321], [321, 307], + [425, 427], [427, 411], [411, 425], [421, 313], [313, 18], [18, 421], + [321, 405], [405, 406], [406, 321], [320, 404], [404, 405], [405, 320], + [315, 16], [16, 17], [17, 315], [426, 425], [425, 266], [266, 426], + [377, 400], [400, 369], [369, 377], [322, 391], [391, 269], [269, 322], + [417, 465], [465, 464], [464, 417], [386, 257], [257, 258], [258, 386], + [466, 260], [260, 388], [388, 466], [456, 399], [399, 419], [419, 456], + [284, 332], [332, 333], [333, 284], [417, 285], [285, 8], [8, 417], + [346, 340], [340, 261], [261, 346], [413, 441], [441, 285], [285, 413], + [327, 460], [460, 328], [328, 327], [355, 371], [371, 329], [329, 355], + [392, 439], [439, 438], [438, 392], [382, 341], [341, 256], [256, 382], + [429, 420], [420, 360], [360, 429], [364, 394], [394, 379], [379, 364], + [277, 343], [343, 437], [437, 277], [443, 444], [444, 283], [283, 443], + [275, 440], [440, 363], [363, 275], [431, 262], [262, 369], [369, 431], + [297, 338], [338, 337], [337, 297], [273, 375], [375, 321], [321, 273], + [450, 451], [451, 349], [349, 450], [446, 342], [342, 467], [467, 446], + [293, 334], [334, 282], [282, 293], [458, 461], [461, 462], [462, 458], + [276, 353], [353, 383], [383, 276], [308, 324], [324, 325], [325, 308], + [276, 300], [300, 293], [293, 276], [372, 345], [345, 447], [447, 372], + [352, 345], [345, 340], [340, 352], [274, 1], [1, 19], [19, 274], + [456, 248], [248, 281], [281, 456], [436, 427], [427, 425], [425, 436], + [381, 256], [256, 252], [252, 381], [269, 391], [391, 393], [393, 269], + [200, 199], [199, 428], [428, 200], [266, 330], [330, 329], [329, 266], + [287, 273], [273, 422], [422, 287], [250, 462], [462, 328], [328, 250], + [258, 286], [286, 384], [384, 258], [265, 353], [353, 342], [342, 265], + [387, 259], [259, 257], [257, 387], [424, 431], [431, 430], [430, 424], + [342, 353], [353, 276], [276, 342], [273, 335], [335, 424], [424, 273], + [292, 325], [325, 307], [307, 292], [366, 447], [447, 345], [345, 366], + [271, 303], [303, 302], [302, 271], [423, 266], [266, 371], [371, 423], + [294, 455], [455, 460], [460, 294], [279, 278], [278, 294], [294, 279], + [271, 272], [272, 304], [304, 271], [432, 434], [434, 427], [427, 432], + [272, 407], [407, 408], [408, 272], [394, 430], [430, 431], [431, 394], + [395, 369], [369, 400], [400, 395], [334, 333], [333, 299], [299, 334], + [351, 417], [417, 168], [168, 351], [352, 280], [280, 411], [411, 352], + [325, 319], [319, 320], [320, 325], [295, 296], [296, 336], [336, 295], + [319, 403], [403, 404], [404, 319], [330, 348], [348, 349], [349, 330], + [293, 298], [298, 333], [333, 293], [323, 454], [454, 447], [447, 323], + [15, 16], [16, 315], [315, 15], [358, 429], [429, 279], [279, 358], + [14, 15], [15, 316], [316, 14], [285, 336], [336, 9], [9, 285], + [329, 349], [349, 350], [350, 329], [374, 380], [380, 252], [252, 374], + [318, 402], [402, 403], [403, 318], [6, 197], [197, 419], [419, 6], + [318, 319], [319, 325], [325, 318], [367, 364], [364, 365], [365, 367], + [435, 367], [367, 397], [397, 435], [344, 438], [438, 439], [439, 344], + [272, 271], [271, 311], [311, 272], [195, 5], [5, 281], [281, 195], + [273, 287], [287, 291], [291, 273], [396, 428], [428, 199], [199, 396], + [311, 271], [271, 268], [268, 311], [283, 444], [444, 445], [445, 283], + [373, 254], [254, 339], [339, 373], [282, 334], [334, 296], [296, 282], + [449, 347], [347, 346], [346, 449], [264, 447], [447, 454], [454, 264], + [336, 296], [296, 299], [299, 336], [338, 10], [10, 151], [151, 338], + [278, 439], [439, 455], [455, 278], [292, 407], [407, 415], [415, 292], + [358, 371], [371, 355], [355, 358], [340, 345], [345, 372], [372, 340], + [346, 347], [347, 280], [280, 346], [442, 443], [443, 282], [282, 442], + [19, 94], [94, 370], [370, 19], [441, 442], [442, 295], [295, 441], + [248, 419], [419, 197], [197, 248], [263, 255], [255, 359], [359, 263], + [440, 275], [275, 274], [274, 440], [300, 383], [383, 368], [368, 300], + [351, 412], [412, 465], [465, 351], [263, 467], [467, 466], [466, 263], + [301, 368], [368, 389], [389, 301], [395, 378], [378, 379], [379, 395], + [412, 351], [351, 419], [419, 412], [436, 426], [426, 322], [322, 436], + [2, 164], [164, 393], [393, 2], [370, 462], [462, 461], [461, 370], + [164, 0], [0, 267], [267, 164], [302, 11], [11, 12], [12, 302], + [268, 12], [12, 13], [13, 268], [293, 300], [300, 301], [301, 293], + [446, 261], [261, 340], [340, 446], [330, 266], [266, 425], [425, 330], + [426, 423], [423, 391], [391, 426], [429, 355], [355, 437], [437, 429], + [391, 327], [327, 326], [326, 391], [440, 457], [457, 438], [438, 440], + [341, 382], [382, 362], [362, 341], [459, 457], [457, 461], [461, 459], + [434, 430], [430, 394], [394, 434], [414, 463], [463, 362], [362, 414], + [396, 369], [369, 262], [262, 396], [354, 461], [461, 457], [457, 354], + [316, 403], [403, 402], [402, 316], [315, 404], [404, 403], [403, 315], + [314, 405], [405, 404], [404, 314], [313, 406], [406, 405], [405, 313], + [421, 418], [418, 406], [406, 421], [366, 401], [401, 361], [361, 366], + [306, 408], [408, 407], [407, 306], [291, 409], [409, 408], [408, 291], + [287, 410], [410, 409], [409, 287], [432, 436], [436, 410], [410, 432], + [434, 416], [416, 411], [411, 434], [264, 368], [368, 383], [383, 264], + [309, 438], [438, 457], [457, 309], [352, 376], [376, 401], [401, 352], + [274, 275], [275, 4], [4, 274], [421, 428], [428, 262], [262, 421], + [294, 327], [327, 358], [358, 294], [433, 416], [416, 367], [367, 433], + [289, 455], [455, 439], [439, 289], [462, 370], [370, 326], [326, 462], + [2, 326], [326, 370], [370, 2], [305, 460], [460, 455], [455, 305], + [254, 449], [449, 448], [448, 254], [255, 261], [261, 446], [446, 255], + [253, 450], [450, 449], [449, 253], [252, 451], [451, 450], [450, 252], + [256, 452], [452, 451], [451, 256], [341, 453], [453, 452], [452, 341], + [413, 464], [464, 463], [463, 413], [441, 413], [413, 414], [414, 441], + [258, 442], [442, 441], [441, 258], [257, 443], [443, 442], [442, 257], + [259, 444], [444, 443], [443, 259], [260, 445], [445, 444], [444, 260], + [467, 342], [342, 445], [445, 467], [459, 458], [458, 250], [250, 459], + [289, 392], [392, 290], [290, 289], [290, 328], [328, 460], [460, 290], + [376, 433], [433, 435], [435, 376], [250, 290], [290, 392], [392, 250], + [411, 416], [416, 433], [433, 411], [341, 463], [463, 464], [464, 341], + [453, 464], [464, 465], [465, 453], [357, 465], [465, 412], [412, 357], + [343, 412], [412, 399], [399, 343], [360, 363], [363, 440], [440, 360], + [437, 399], [399, 456], [456, 437], [420, 456], [456, 363], [363, 420], + [401, 435], [435, 288], [288, 401], [372, 383], [383, 353], [353, 372], + [339, 255], [255, 249], [249, 339], [448, 261], [261, 255], [255, 448], + [133, 243], [243, 190], [190, 133], [133, 155], [155, 112], [112, 133], + [33, 246], [246, 247], [247, 33], [33, 130], [130, 25], [25, 33], + [398, 384], [384, 286], [286, 398], [362, 398], [398, 414], [414, 362], + [362, 463], [463, 341], [341, 362], [263, 359], [359, 467], [467, 263], + [263, 249], [249, 255], [255, 263], [466, 467], [467, 260], [260, 466], + [75, 60], [60, 166], [166, 75], [238, 239], [239, 79], [79, 238], + [162, 127], [127, 139], [139, 162], [72, 11], [11, 37], [37, 72], + [121, 232], [232, 120], [120, 121], [73, 72], [72, 39], [39, 73], + [114, 128], [128, 47], [47, 114], [233, 232], [232, 128], [128, 233], + [103, 104], [104, 67], [67, 103], [152, 175], [175, 148], [148, 152], + [119, 118], [118, 101], [101, 119], [74, 73], [73, 40], [40, 74], + [107, 9], [9, 108], [108, 107], [49, 48], [48, 131], [131, 49], + [32, 194], [194, 211], [211, 32], [184, 74], [74, 185], [185, 184], + [191, 80], [80, 183], [183, 191], [185, 40], [40, 186], [186, 185], + [119, 230], [230, 118], [118, 119], [210, 202], [202, 214], [214, 210], + [84, 83], [83, 17], [17, 84], [77, 76], [76, 146], [146, 77], + [161, 160], [160, 30], [30, 161], [190, 56], [56, 173], [173, 190], + [182, 106], [106, 194], [194, 182], [138, 135], [135, 192], [192, 138], + [129, 203], [203, 98], [98, 129], [54, 21], [21, 68], [68, 54], + [5, 51], [51, 4], [4, 5], [145, 144], [144, 23], [23, 145], + [90, 77], [77, 91], [91, 90], [207, 205], [205, 187], [187, 207], + [83, 201], [201, 18], [18, 83], [181, 91], [91, 182], [182, 181], + [180, 90], [90, 181], [181, 180], [16, 85], [85, 17], [17, 16], + [205, 206], [206, 36], [36, 205], [176, 148], [148, 140], [140, 176], + [165, 92], [92, 39], [39, 165], [245, 193], [193, 244], [244, 245], + [27, 159], [159, 28], [28, 27], [30, 247], [247, 161], [161, 30], + [174, 236], [236, 196], [196, 174], [103, 54], [54, 104], [104, 103], + [55, 193], [193, 8], [8, 55], [111, 117], [117, 31], [31, 111], + [221, 189], [189, 55], [55, 221], [240, 98], [98, 99], [99, 240], + [142, 126], [126, 100], [100, 142], [219, 166], [166, 218], [218, 219], + [112, 155], [155, 26], [26, 112], [198, 209], [209, 131], [131, 198], + [169, 135], [135, 150], [150, 169], [114, 47], [47, 217], [217, 114], + [224, 223], [223, 53], [53, 224], [220, 45], [45, 134], [134, 220], + [32, 211], [211, 140], [140, 32], [109, 67], [67, 108], [108, 109], + [146, 43], [43, 91], [91, 146], [231, 230], [230, 120], [120, 231], + [113, 226], [226, 247], [247, 113], [105, 63], [63, 52], [52, 105], + [241, 238], [238, 242], [242, 241], [124, 46], [46, 156], [156, 124], + [95, 78], [78, 96], [96, 95], [70, 46], [46, 63], [63, 70], + [116, 143], [143, 227], [227, 116], [116, 123], [123, 111], [111, 116], + [1, 44], [44, 19], [19, 1], [3, 236], [236, 51], [51, 3], + [207, 216], [216, 205], [205, 207], [26, 154], [154, 22], [22, 26], + [165, 39], [39, 167], [167, 165], [199, 200], [200, 208], [208, 199], + [101, 36], [36, 100], [100, 101], [43, 57], [57, 202], [202, 43], + [242, 20], [20, 99], [99, 242], [56, 28], [28, 157], [157, 56], + [124, 35], [35, 113], [113, 124], [29, 160], [160, 27], [27, 29], + [211, 204], [204, 210], [210, 211], [124, 113], [113, 46], [46, 124], + [106, 43], [43, 204], [204, 106], [96, 62], [62, 77], [77, 96], + [227, 137], [137, 116], [116, 227], [73, 41], [41, 72], [72, 73], + [36, 203], [203, 142], [142, 36], [235, 64], [64, 240], [240, 235], + [48, 49], [49, 64], [64, 48], [42, 41], [41, 74], [74, 42], + [214, 212], [212, 207], [207, 214], [183, 42], [42, 184], [184, 183], + [210, 169], [169, 211], [211, 210], [140, 170], [170, 176], [176, 140], + [104, 105], [105, 69], [69, 104], [193, 122], [122, 168], [168, 193], + [50, 123], [123, 187], [187, 50], [89, 96], [96, 90], [90, 89], + [66, 65], [65, 107], [107, 66], [179, 89], [89, 180], [180, 179], + [119, 101], [101, 120], [120, 119], [68, 63], [63, 104], [104, 68], + [234, 93], [93, 227], [227, 234], [16, 15], [15, 85], [85, 16], + [209, 129], [129, 49], [49, 209], [15, 14], [14, 86], [86, 15], + [107, 55], [55, 9], [9, 107], [120, 100], [100, 121], [121, 120], + [153, 145], [145, 22], [22, 153], [178, 88], [88, 179], [179, 178], + [197, 6], [6, 196], [196, 197], [89, 88], [88, 96], [96, 89], + [135, 138], [138, 136], [136, 135], [138, 215], [215, 172], [172, 138], + [218, 115], [115, 219], [219, 218], [41, 42], [42, 81], [81, 41], + [5, 195], [195, 51], [51, 5], [57, 43], [43, 61], [61, 57], + [208, 171], [171, 199], [199, 208], [41, 81], [81, 38], [38, 41], + [224, 53], [53, 225], [225, 224], [24, 144], [144, 110], [110, 24], + [105, 52], [52, 66], [66, 105], [118, 229], [229, 117], [117, 118], + [227, 34], [34, 234], [234, 227], [66, 107], [107, 69], [69, 66], + [10, 109], [109, 151], [151, 10], [219, 48], [48, 235], [235, 219], + [183, 62], [62, 191], [191, 183], [142, 129], [129, 126], [126, 142], + [116, 111], [111, 143], [143, 116], [118, 117], [117, 50], [50, 118], + [223, 222], [222, 52], [52, 223], [94, 19], [19, 141], [141, 94], + [222, 221], [221, 65], [65, 222], [196, 3], [3, 197], [197, 196], + [45, 220], [220, 44], [44, 45], [156, 70], [70, 139], [139, 156], + [188, 122], [122, 245], [245, 188], [139, 71], [71, 162], [162, 139], + [149, 170], [170, 150], [150, 149], [122, 188], [188, 196], [196, 122], + [206, 216], [216, 92], [92, 206], [164, 2], [2, 167], [167, 164], + [242, 141], [141, 241], [241, 242], [0, 164], [164, 37], [37, 0], + [11, 72], [72, 12], [12, 11], [12, 38], [38, 13], [13, 12], + [70, 63], [63, 71], [71, 70], [31, 226], [226, 111], [111, 31], + [36, 101], [101, 205], [205, 36], [203, 206], [206, 165], [165, 203], + [126, 209], [209, 217], [217, 126], [98, 165], [165, 97], [97, 98], + [237, 220], [220, 218], [218, 237], [237, 239], [239, 241], [241, 237], + [210, 214], [214, 169], [169, 210], [140, 171], [171, 32], [32, 140], + [241, 125], [125, 237], [237, 241], [179, 86], [86, 178], [178, 179], + [180, 85], [85, 179], [179, 180], [181, 84], [84, 180], [180, 181], + [182, 83], [83, 181], [181, 182], [194, 201], [201, 182], [182, 194], + [177, 137], [137, 132], [132, 177], [184, 76], [76, 183], [183, 184], + [185, 61], [61, 184], [184, 185], [186, 57], [57, 185], [185, 186], + [216, 212], [212, 186], [186, 216], [192, 214], [214, 187], [187, 192], + [139, 34], [34, 156], [156, 139], [218, 79], [79, 237], [237, 218], + [147, 123], [123, 177], [177, 147], [45, 44], [44, 4], [4, 45], + [208, 201], [201, 32], [32, 208], [98, 64], [64, 129], [129, 98], + [192, 213], [213, 138], [138, 192], [235, 59], [59, 219], [219, 235], + [141, 242], [242, 97], [97, 141], [97, 2], [2, 141], [141, 97], + [240, 75], [75, 235], [235, 240], [229, 24], [24, 228], [228, 229], + [31, 25], [25, 226], [226, 31], [230, 23], [23, 229], [229, 230], + [231, 22], [22, 230], [230, 231], [232, 26], [26, 231], [231, 232], + [233, 112], [112, 232], [232, 233], [244, 189], [189, 243], [243, 244], + [189, 221], [221, 190], [190, 189], [222, 28], [28, 221], [221, 222], + [223, 27], [27, 222], [222, 223], [224, 29], [29, 223], [223, 224], + [225, 30], [30, 224], [224, 225], [113, 247], [247, 225], [225, 113], + [99, 60], [60, 240], [240, 99], [213, 147], [147, 215], [215, 213], + [60, 20], [20, 166], [166, 60], [192, 187], [187, 213], [213, 192], + [243, 112], [112, 244], [244, 243], [244, 233], [233, 245], [245, 244], + [245, 128], [128, 188], [188, 245], [188, 114], [114, 174], [174, 188], + [134, 131], [131, 220], [220, 134], [174, 217], [217, 236], [236, 174], + [236, 198], [198, 134], [134, 236], [215, 177], [177, 58], [58, 215], + [156, 143], [143, 124], [124, 156], [25, 110], [110, 7], [7, 25], + [31, 228], [228, 25], [25, 31], [264, 356], [356, 368], [368, 264], + [0, 11], [11, 267], [267, 0], [451, 452], [452, 349], [349, 451], + [267, 302], [302, 269], [269, 267], [350, 357], [357, 277], [277, 350], + [350, 452], [452, 357], [357, 350], [299, 333], [333, 297], [297, 299], + [396, 175], [175, 377], [377, 396], [280, 347], [347, 330], [330, 280], + [269, 303], [303, 270], [270, 269], [151, 9], [9, 337], [337, 151], + [344, 278], [278, 360], [360, 344], [424, 418], [418, 431], [431, 424], + [270, 304], [304, 409], [409, 270], [272, 310], [310, 407], [407, 272], + [322, 270], [270, 410], [410, 322], [449, 450], [450, 347], [347, 449], + [432, 422], [422, 434], [434, 432], [18, 313], [313, 17], [17, 18], + [291, 306], [306, 375], [375, 291], [259, 387], [387, 260], [260, 259], + [424, 335], [335, 418], [418, 424], [434, 364], [364, 416], [416, 434], + [391, 423], [423, 327], [327, 391], [301, 251], [251, 298], [298, 301], + [275, 281], [281, 4], [4, 275], [254, 373], [373, 253], [253, 254], + [375, 307], [307, 321], [321, 375], [280, 425], [425, 411], [411, 280], + [200, 421], [421, 18], [18, 200], [335, 321], [321, 406], [406, 335], + [321, 320], [320, 405], [405, 321], [314, 315], [315, 17], [17, 314], + [423, 426], [426, 266], [266, 423], [396, 377], [377, 369], [369, 396], + [270, 322], [322, 269], [269, 270], [413, 417], [417, 464], [464, 413], + [385, 386], [386, 258], [258, 385], [248, 456], [456, 419], [419, 248], + [298, 284], [284, 333], [333, 298], [168, 417], [417, 8], [8, 168], + [448, 346], [346, 261], [261, 448], [417, 413], [413, 285], [285, 417], + [326, 327], [327, 328], [328, 326], [277, 355], [355, 329], [329, 277], + [309, 392], [392, 438], [438, 309], [381, 382], [382, 256], [256, 381], + [279, 429], [429, 360], [360, 279], [365, 364], [364, 379], [379, 365], + [355, 277], [277, 437], [437, 355], [282, 443], [443, 283], [283, 282], + [281, 275], [275, 363], [363, 281], [395, 431], [431, 369], [369, 395], + [299, 297], [297, 337], [337, 299], [335, 273], [273, 321], [321, 335], + [348, 450], [450, 349], [349, 348], [359, 446], [446, 467], [467, 359], + [283, 293], [293, 282], [282, 283], [250, 458], [458, 462], [462, 250], + [300, 276], [276, 383], [383, 300], [292, 308], [308, 325], [325, 292], + [283, 276], [276, 293], [293, 283], [264, 372], [372, 447], [447, 264], + [346, 352], [352, 340], [340, 346], [354, 274], [274, 19], [19, 354], + [363, 456], [456, 281], [281, 363], [426, 436], [436, 425], [425, 426], + [380, 381], [381, 252], [252, 380], [267, 269], [269, 393], [393, 267], + [421, 200], [200, 428], [428, 421], [371, 266], [266, 329], [329, 371], + [432, 287], [287, 422], [422, 432], [290, 250], [250, 328], [328, 290], + [385, 258], [258, 384], [384, 385], [446, 265], [265, 342], [342, 446], + [386, 387], [387, 257], [257, 386], [422, 424], [424, 430], [430, 422], + [445, 342], [342, 276], [276, 445], [422, 273], [273, 424], [424, 422], + [306, 292], [292, 307], [307, 306], [352, 366], [366, 345], [345, 352], + [268, 271], [271, 302], [302, 268], [358, 423], [423, 371], [371, 358], + [327, 294], [294, 460], [460, 327], [331, 279], [279, 294], [294, 331], + [303, 271], [271, 304], [304, 303], [436, 432], [432, 427], [427, 436], + [304, 272], [272, 408], [408, 304], [395, 394], [394, 431], [431, 395], + [378, 395], [395, 400], [400, 378], [296, 334], [334, 299], [299, 296], + [6, 351], [351, 168], [168, 6], [376, 352], [352, 411], [411, 376], + [307, 325], [325, 320], [320, 307], [285, 295], [295, 336], [336, 285], + [320, 319], [319, 404], [404, 320], [329, 330], [330, 349], [349, 329], + [334, 293], [293, 333], [333, 334], [366, 323], [323, 447], [447, 366], + [316, 15], [15, 315], [315, 316], [331, 358], [358, 279], [279, 331], + [317, 14], [14, 316], [316, 317], [8, 285], [285, 9], [9, 8], + [277, 329], [329, 350], [350, 277], [253, 374], [374, 252], [252, 253], + [319, 318], [318, 403], [403, 319], [351, 6], [6, 419], [419, 351], + [324, 318], [318, 325], [325, 324], [397, 367], [367, 365], [365, 397], + [288, 435], [435, 397], [397, 288], [278, 344], [344, 439], [439, 278], + [310, 272], [272, 311], [311, 310], [248, 195], [195, 281], [281, 248], + [375, 273], [273, 291], [291, 375], [175, 396], [396, 199], [199, 175], + [312, 311], [311, 268], [268, 312], [276, 283], [283, 445], [445, 276], + [390, 373], [373, 339], [339, 390], [295, 282], [282, 296], [296, 295], + [448, 449], [449, 346], [346, 448], [356, 264], [264, 454], [454, 356], + [337, 336], [336, 299], [299, 337], [337, 338], [338, 151], [151, 337], + [294, 278], [278, 455], [455, 294], [308, 292], [292, 415], [415, 308], + [429, 358], [358, 355], [355, 429], [265, 340], [340, 372], [372, 265], + [352, 346], [346, 280], [280, 352], [295, 442], [442, 282], [282, 295], + [354, 19], [19, 370], [370, 354], [285, 441], [441, 295], [295, 285], + [195, 248], [248, 197], [197, 195], [457, 440], [440, 274], [274, 457], + [301, 300], [300, 368], [368, 301], [417, 351], [351, 465], [465, 417], + [251, 301], [301, 389], [389, 251], [394, 395], [395, 379], [379, 394], + [399, 412], [412, 419], [419, 399], [410, 436], [436, 322], [322, 410], + [326, 2], [2, 393], [393, 326], [354, 370], [370, 461], [461, 354], + [393, 164], [164, 267], [267, 393], [268, 302], [302, 12], [12, 268], + [312, 268], [268, 13], [13, 312], [298, 293], [293, 301], [301, 298], + [265, 446], [446, 340], [340, 265], [280, 330], [330, 425], [425, 280], + [322, 426], [426, 391], [391, 322], [420, 429], [429, 437], [437, 420], + [393, 391], [391, 326], [326, 393], [344, 440], [440, 438], [438, 344], + [458, 459], [459, 461], [461, 458], [364, 434], [434, 394], [394, 364], + [428, 396], [396, 262], [262, 428], [274, 354], [354, 457], [457, 274], + [317, 316], [316, 402], [402, 317], [316, 315], [315, 403], [403, 316], + [315, 314], [314, 404], [404, 315], [314, 313], [313, 405], [405, 314], + [313, 421], [421, 406], [406, 313], [323, 366], [366, 361], [361, 323], + [292, 306], [306, 407], [407, 292], [306, 291], [291, 408], [408, 306], + [291, 287], [287, 409], [409, 291], [287, 432], [432, 410], [410, 287], + [427, 434], [434, 411], [411, 427], [372, 264], [264, 383], [383, 372], + [459, 309], [309, 457], [457, 459], [366, 352], [352, 401], [401, 366], + [1, 274], [274, 4], [4, 1], [418, 421], [421, 262], [262, 418], + [331, 294], [294, 358], [358, 331], [435, 433], [433, 367], [367, 435], + [392, 289], [289, 439], [439, 392], [328, 462], [462, 326], [326, 328], + [94, 2], [2, 370], [370, 94], [289, 305], [305, 455], [455, 289], + [339, 254], [254, 448], [448, 339], [359, 255], [255, 446], [446, 359], + [254, 253], [253, 449], [449, 254], [253, 252], [252, 450], [450, 253], + [252, 256], [256, 451], [451, 252], [256, 341], [341, 452], [452, 256], + [414, 413], [413, 463], [463, 414], [286, 441], [441, 414], [414, 286], + [286, 258], [258, 441], [441, 286], [258, 257], [257, 442], [442, 258], + [257, 259], [259, 443], [443, 257], [259, 260], [260, 444], [444, 259], + [260, 467], [467, 445], [445, 260], [309, 459], [459, 250], [250, 309], + [305, 289], [289, 290], [290, 305], [305, 290], [290, 460], [460, 305], + [401, 376], [376, 435], [435, 401], [309, 250], [250, 392], [392, 309], + [376, 411], [411, 433], [433, 376], [453, 341], [341, 464], [464, 453], + [357, 453], [453, 465], [465, 357], [343, 357], [357, 412], [412, 343], + [437, 343], [343, 399], [399, 437], [344, 360], [360, 440], [440, 344], + [420, 437], [437, 456], [456, 420], [360, 420], [420, 363], [363, 360], + [361, 401], [401, 288], [288, 361], [265, 372], [372, 353], [353, 265], + [390, 339], [339, 249], [249, 390], [339, 448], [448, 255], [255, 339]])) diff --git a/client/src/hooks/useFaceLandmarkDetection.tsx b/client/src/hooks/useFaceLandmarkDetection.tsx new file mode 100644 index 0000000000000000000000000000000000000000..ace35a6cc0ca01e55c1aa39948cb23227f9d0aab --- /dev/null +++ b/client/src/hooks/useFaceLandmarkDetection.tsx @@ -0,0 +1,632 @@ +import React, { useState, useEffect, useRef, useCallback } from 'react'; +import * as vision from '@mediapipe/tasks-vision'; + +import { facePoke } from '@/lib/facePoke'; +import { useMainStore } from './useMainStore'; +import useThrottledCallback from 'beautiful-react-hooks/useThrottledCallback'; + +import { landmarkGroups, FACEMESH_LIPS, FACEMESH_LEFT_EYE, FACEMESH_LEFT_EYEBROW, FACEMESH_RIGHT_EYE, FACEMESH_RIGHT_EYEBROW, FACEMESH_FACE_OVAL } from './landmarks'; + +// New types for improved type safety +export type LandmarkGroup = 'lips' | 'leftEye' | 'leftEyebrow' | 'rightEye' | 'rightEyebrow' | 'faceOval' | 'background'; +export type LandmarkCenter = { x: number; y: number; z: number }; +export type ClosestLandmark = { group: LandmarkGroup; distance: number; vector: { x: number; y: number; z: number } }; + +export type MediaPipeResources = { + faceLandmarker: vision.FaceLandmarker | null; + drawingUtils: vision.DrawingUtils | null; +}; + +export function useFaceLandmarkDetection() { + const error = useMainStore(s => s.error); + const setError = useMainStore(s => s.setError); + const imageFile = useMainStore(s => s.imageFile); + const setImageFile = useMainStore(s => s.setImageFile); + const originalImage = useMainStore(s => s.originalImage); + const originalImageHash = useMainStore(s => s.originalImageHash); + const setOriginalImageHash = useMainStore(s => s.setOriginalImageHash); + const previewImage = useMainStore(s => s.previewImage); + const setPreviewImage = useMainStore(s => s.setPreviewImage); + const resetImage = useMainStore(s => s.resetImage); + + ;(window as any).debugJuju = useMainStore; + //////////////////////////////////////////////////////////////////////// + // ok so apparently I cannot vary the latency, or else there is a bug + // const averageLatency = useMainStore(s => s.averageLatency); + const averageLatency = 220 + //////////////////////////////////////////////////////////////////////// + + // State for face detection + const [faceLandmarks, setFaceLandmarks] = useState<vision.NormalizedLandmark[][]>([]); + const [isMediaPipeReady, setIsMediaPipeReady] = useState(false); + const [isDrawingUtilsReady, setIsDrawingUtilsReady] = useState(false); + const [blendShapes, setBlendShapes] = useState<vision.Classifications[]>([]); + + // State for mouse interaction + const [dragStart, setDragStart] = useState<{ x: number; y: number } | null>(null); + const [dragEnd, setDragEnd] = useState<{ x: number; y: number } | null>(null); + + const [isDragging, setIsDragging] = useState(false); + const [isWaitingForResponse, setIsWaitingForResponse] = useState(false); + const dragStartRef = useRef<{ x: number; y: number } | null>(null); + const currentMousePosRef = useRef<{ x: number; y: number } | null>(null); + const lastModifiedImageHashRef = useRef<string | null>(null); + + const [currentLandmark, setCurrentLandmark] = useState<ClosestLandmark | null>(null); + const [previousLandmark, setPreviousLandmark] = useState<ClosestLandmark | null>(null); + const [currentOpacity, setCurrentOpacity] = useState(0); + const [previousOpacity, setPreviousOpacity] = useState(0); + + const [isHovering, setIsHovering] = useState(false); + + // Refs + const canvasRef = useRef<HTMLCanvasElement>(null); + const mediaPipeRef = useRef<MediaPipeResources>({ + faceLandmarker: null, + drawingUtils: null, + }); + + const setActiveLandmark = useCallback((newLandmark: ClosestLandmark | undefined) => { + //if (newLandmark && (!currentLandmark || newLandmark.group !== currentLandmark.group)) { + setPreviousLandmark(currentLandmark || null); + setCurrentLandmark(newLandmark || null); + setCurrentOpacity(0); + setPreviousOpacity(1); + //} + }, [currentLandmark, setPreviousLandmark, setCurrentLandmark, setCurrentOpacity, setPreviousOpacity]); + + // Initialize MediaPipe + useEffect(() => { + console.log('Initializing MediaPipe...'); + let isMounted = true; + + const initializeMediaPipe = async () => { + const { FaceLandmarker, FilesetResolver, DrawingUtils } = vision; + + try { + console.log('Initializing FilesetResolver...'); + const filesetResolver = await FilesetResolver.forVisionTasks( + "https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.3/wasm" + ); + + console.log('Creating FaceLandmarker...'); + const faceLandmarker = await FaceLandmarker.createFromOptions(filesetResolver, { + baseOptions: { + modelAssetPath: `https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/1/face_landmarker.task`, + delegate: "GPU" + }, + outputFaceBlendshapes: true, + runningMode: "IMAGE", + numFaces: 1 + }); + + if (isMounted) { + console.log('FaceLandmarker created successfully.'); + mediaPipeRef.current.faceLandmarker = faceLandmarker; + setIsMediaPipeReady(true); + } else { + faceLandmarker.close(); + } + } catch (error) { + console.error('Error during MediaPipe initialization:', error); + setError('Failed to initialize face detection. Please try refreshing the page.'); + } + }; + + initializeMediaPipe(); + + + return () => { + isMounted = false; + if (mediaPipeRef.current.faceLandmarker) { + mediaPipeRef.current.faceLandmarker.close(); + } + }; + }, []); + + // New state for storing landmark centers + const [landmarkCenters, setLandmarkCenters] = useState<Record<LandmarkGroup, LandmarkCenter>>({} as Record<LandmarkGroup, LandmarkCenter>); + + // Function to compute the center of each landmark group + const computeLandmarkCenters = useCallback((landmarks: vision.NormalizedLandmark[]) => { + const centers: Record<LandmarkGroup, LandmarkCenter> = {} as Record<LandmarkGroup, LandmarkCenter>; + + const computeGroupCenter = (group: Readonly<Set<number[]>>): LandmarkCenter => { + let sumX = 0, sumY = 0, sumZ = 0, count = 0; + group.forEach(([index]) => { + if (landmarks[index]) { + sumX += landmarks[index].x; + sumY += landmarks[index].y; + sumZ += landmarks[index].z || 0; + count++; + } + }); + return { x: sumX / count, y: sumY / count, z: sumZ / count }; + }; + + centers.lips = computeGroupCenter(FACEMESH_LIPS); + centers.leftEye = computeGroupCenter(FACEMESH_LEFT_EYE); + centers.leftEyebrow = computeGroupCenter(FACEMESH_LEFT_EYEBROW); + centers.rightEye = computeGroupCenter(FACEMESH_RIGHT_EYE); + centers.rightEyebrow = computeGroupCenter(FACEMESH_RIGHT_EYEBROW); + centers.faceOval = computeGroupCenter(FACEMESH_FACE_OVAL); + centers.background = { x: 0.5, y: 0.5, z: 0 }; + + setLandmarkCenters(centers); + // console.log('Landmark centers computed:', centers); + }, []); + + // Function to find the closest landmark to the mouse position + const findClosestLandmark = useCallback((mouseX: number, mouseY: number, isGroup?: LandmarkGroup): ClosestLandmark => { + const defaultLandmark: ClosestLandmark = { + group: 'background', + distance: 0, + vector: { + x: mouseX, + y: mouseY, + z: 0 + } + } + + if (Object.keys(landmarkCenters).length === 0) { + console.warn('Landmark centers not computed yet'); + return defaultLandmark; + } + + let closestGroup: LandmarkGroup | null = null; + let minDistance = Infinity; + let closestVector = { x: 0, y: 0, z: 0 }; + let faceOvalDistance = Infinity; + let faceOvalVector = { x: 0, y: 0, z: 0 }; + + Object.entries(landmarkCenters).forEach(([group, center]) => { + const dx = mouseX - center.x; + const dy = mouseY - center.y; + const distance = Math.sqrt(dx * dx + dy * dy); + + if (group === 'faceOval') { + faceOvalDistance = distance; + faceOvalVector = { x: dx, y: dy, z: 0 }; + } + + // filter to keep the group if it is belonging to `ofGroup` + if (isGroup) { + if (group !== isGroup) { + return + } + } + + if (distance < minDistance) { + minDistance = distance; + closestGroup = group as LandmarkGroup; + closestVector = { x: dx, y: dy, z: 0 }; // Z is 0 as mouse interaction is 2D + } + }); + + // Fallback to faceOval if no group found or distance is too large + if (minDistance > 0.05) { + // console.log('Distance is too high, so we use the faceOval group'); + closestGroup = 'background'; + minDistance = faceOvalDistance; + closestVector = faceOvalVector; + } + + if (closestGroup) { + // console.log(`Closest landmark: ${closestGroup}, distance: ${minDistance.toFixed(4)}`); + return { group: closestGroup, distance: minDistance, vector: closestVector }; + } else { + // console.log('No group found, returning fallback'); + return defaultLandmark + } + }, [landmarkCenters]); + + // Detect face landmarks + const detectFaceLandmarks = useCallback(async (imageDataUrl: string) => { + // console.log('Attempting to detect face landmarks...'); + if (!isMediaPipeReady) { + console.log('MediaPipe not ready. Skipping detection.'); + return; + } + + const faceLandmarker = mediaPipeRef.current.faceLandmarker; + + if (!faceLandmarker) { + console.error('FaceLandmarker is not initialized.'); + return; + } + + const drawingUtils = mediaPipeRef.current.drawingUtils; + + const image = new Image(); + image.src = imageDataUrl; + await new Promise((resolve) => { image.onload = resolve; }); + + const faceLandmarkerResult = faceLandmarker.detect(image); + // console.log("Face landmarks detected:", faceLandmarkerResult); + + setFaceLandmarks(faceLandmarkerResult.faceLandmarks); + setBlendShapes(faceLandmarkerResult.faceBlendshapes || []); + + if (faceLandmarkerResult.faceLandmarks && faceLandmarkerResult.faceLandmarks[0]) { + computeLandmarkCenters(faceLandmarkerResult.faceLandmarks[0]); + } + + if (canvasRef.current && drawingUtils) { + drawLandmarks(faceLandmarkerResult.faceLandmarks[0], canvasRef.current, drawingUtils); + } + }, [isMediaPipeReady, isDrawingUtilsReady, computeLandmarkCenters]); + + const drawLandmarks = useCallback(( + landmarks: vision.NormalizedLandmark[], + canvas: HTMLCanvasElement, + drawingUtils: vision.DrawingUtils + ) => { + const ctx = canvas.getContext('2d'); + if (!ctx) return; + + ctx.clearRect(0, 0, canvas.width, canvas.height); + + if (canvasRef.current && previewImage) { + const img = new Image(); + img.onload = () => { + canvas.width = img.width; + canvas.height = img.height; + + const drawLandmarkGroup = (landmark: ClosestLandmark | null, opacity: number) => { + if (!landmark) return; + const connections = landmarkGroups[landmark.group]; + if (connections) { + ctx.globalAlpha = opacity; + drawingUtils.drawConnectors( + landmarks, + connections, + { color: 'orange', lineWidth: 4 } + ); + } + }; + + drawLandmarkGroup(previousLandmark, previousOpacity); + drawLandmarkGroup(currentLandmark, currentOpacity); + + ctx.globalAlpha = 1; + }; + img.src = previewImage; + } + }, [previewImage, currentLandmark, previousLandmark, currentOpacity, previousOpacity]); + + useEffect(() => { + if (isMediaPipeReady && isDrawingUtilsReady && faceLandmarks.length > 0 && canvasRef.current && mediaPipeRef.current.drawingUtils) { + drawLandmarks(faceLandmarks[0], canvasRef.current, mediaPipeRef.current.drawingUtils); + } + }, [isMediaPipeReady, isDrawingUtilsReady, faceLandmarks, currentLandmark, previousLandmark, currentOpacity, previousOpacity, drawLandmarks]); + useEffect(() => { + let animationFrame: number; + const animate = () => { + setCurrentOpacity((prev) => Math.min(prev + 0.2, 1)); + setPreviousOpacity((prev) => Math.max(prev - 0.2, 0)); + + if (currentOpacity < 1 || previousOpacity > 0) { + animationFrame = requestAnimationFrame(animate); + } + }; + animationFrame = requestAnimationFrame(animate); + return () => cancelAnimationFrame(animationFrame); + }, [currentLandmark]); + + // Canvas ref callback + const canvasRefCallback = useCallback((node: HTMLCanvasElement | null) => { + if (node !== null) { + const ctx = node.getContext('2d'); + if (ctx) { + // Get device pixel ratio + const pixelRatio = window.devicePixelRatio || 1; + + // Scale canvas based on the pixel ratio + node.width = node.clientWidth * pixelRatio; + node.height = node.clientHeight * pixelRatio; + ctx.scale(pixelRatio, pixelRatio); + + mediaPipeRef.current.drawingUtils = new vision.DrawingUtils(ctx); + setIsDrawingUtilsReady(true); + } else { + console.error('Failed to get 2D context from canvas.'); + } + canvasRef.current = node; + } + }, []); + + + useEffect(() => { + if (!isMediaPipeReady) { + console.log('MediaPipe not ready. Skipping landmark detection.'); + return + } + if (!previewImage) { + console.log('Preview image not ready. Skipping landmark detection.'); + return + } + if (!isDrawingUtilsReady) { + console.log('DrawingUtils not ready. Skipping landmark detection.'); + return + } + detectFaceLandmarks(previewImage); + }, [isMediaPipeReady, isDrawingUtilsReady, previewImage]) + + + + const modifyImage = useCallback(({ landmark, vector }: { + landmark: ClosestLandmark + vector: { x: number; y: number; z: number } + }) => { + + const { + originalImage, + originalImageHash, + params: previousParams, + setParams, + setError + } = useMainStore.getState() + + + if (!originalImage) { + console.error('Image file or facePoke not available'); + return; + } + + const params = { + ...previousParams + } + + const minX = -0.50; + const maxX = 0.50; + const minY = -0.50; + const maxY = 0.50; + + // Function to map a value from one range to another + const mapRange = (value: number, inMin: number, inMax: number, outMin: number, outMax: number): number => { + return Math.min(outMax, Math.max(outMin, ((value - inMin) * (outMax - outMin)) / (inMax - inMin) + outMin)); + }; + + console.log("modifyImage:", { + originalImage, + originalImageHash, + landmark, + vector, + minX, + maxX, + minY, + maxY, + }) + + // Map landmarks to ImageModificationParams + switch (landmark.group) { + case 'leftEye': + case 'rightEye': + // eyebrow (min: -20, max: 5, default: 0) + const eyesMin = 210 + const eyesMax = 5 + params.eyes = mapRange(vector.x, minX, maxX, eyesMin, eyesMax); + + break; + case 'leftEyebrow': + case 'rightEyebrow': + // moving the mouse vertically for the eyebrow + // should make them up/down + // eyebrow (min: -10, max: 15, default: 0) + const eyebrowMin = -10 + const eyebrowMax = 15 + params.eyebrow = mapRange(vector.y, minY, maxY, eyebrowMin, eyebrowMax); + + break; + case 'lips': + // aaa (min: -30, max: 120, default: 0) + //const aaaMin = -30 + //const aaaMax = 120 + //params.aaa = mapRange(vector.x, minY, maxY, aaaMin, aaaMax); + + // eee (min: -20, max: 15, default: 0) + const eeeMin = -20 + const eeeMax = 15 + params.eee = mapRange(vector.y, minY, maxY, eeeMin, eeeMax); + + + // woo (min: -20, max: 15, default: 0) + const wooMin = -20 + const wooMax = 15 + params.woo = mapRange(vector.x, minX, maxX, wooMin, wooMax); + + break; + case 'faceOval': + // displacing the face horizontally by moving the mouse on the X axis + // should perform a yaw rotation + // rotate_roll (min: -20, max: 20, default: 0) + const rollMin = -40 + const rollMax = 40 + + // note: we invert the axis here + params.rotate_roll = mapRange(vector.x, minX, maxX, rollMin, rollMax); + break; + + case 'background': + // displacing the face horizontally by moving the mouse on the X axis + // should perform a yaw rotation + // rotate_yaw (min: -20, max: 20, default: 0) + const yawMin = -40 + const yawMax = 40 + + // note: we invert the axis here + params.rotate_yaw = mapRange(-vector.x, minX, maxX, yawMin, yawMax); + + // displacing the face vertically by moving the mouse on the Y axis + // should perform a pitch rotation + // rotate_pitch (min: -20, max: 20, default: 0) + const pitchMin = -40 + const pitchMax = 40 + params.rotate_pitch = mapRange(vector.y, minY, maxY, pitchMin, pitchMax); + break; + default: + return + } + + for (const [key, value] of Object.entries(params)) { + if (isNaN(value as any) || !isFinite(value as any)) { + console.log(`${key} is NaN, aborting`) + return + } + } + console.log(`PITCH=${params.rotate_pitch || 0}, YAW=${params.rotate_yaw || 0}, ROLL=${params.rotate_roll || 0}`); + + setParams(params) + try { + // For the first request or when the image file changes, send the full image + if (!lastModifiedImageHashRef.current || lastModifiedImageHashRef.current !== originalImageHash) { + lastModifiedImageHashRef.current = originalImageHash; + facePoke.modifyImage(originalImage, null, params); + } else { + // For subsequent requests, send only the hash + facePoke.modifyImage(null, lastModifiedImageHashRef.current, params); + } + } catch (error) { + // console.error('Error modifying image:', error); + setError('Failed to modify image'); + } + }, []); + + // this is throttled by our average latency + const modifyImageWithRateLimit = useThrottledCallback((params: { + landmark: ClosestLandmark + vector: { x: number; y: number; z: number } + }) => { + modifyImage(params); + }, [modifyImage], averageLatency); + + const handleMouseEnter = useCallback(() => { + setIsHovering(true); + }, []); + + const handleMouseLeave = useCallback(() => { + setIsHovering(false); + }, []); + + // Update mouse event handlers + const handleMouseDown = useCallback((event: React.MouseEvent<HTMLCanvasElement>) => { + if (!canvasRef.current) return; + + const rect = canvasRef.current.getBoundingClientRect(); + const x = (event.clientX - rect.left) / rect.width; + const y = (event.clientY - rect.top) / rect.height; + + const landmark = findClosestLandmark(x, y); + console.log(`Mouse down on ${landmark.group}`); + setActiveLandmark(landmark); + setDragStart({ x, y }); + dragStartRef.current = { x, y }; + }, [findClosestLandmark, setActiveLandmark, setDragStart]); + + const handleMouseMove = useCallback((event: React.MouseEvent<HTMLCanvasElement>) => { + if (!canvasRef.current) return; + + const rect = canvasRef.current.getBoundingClientRect(); + const x = (event.clientX - rect.left) / rect.width; + const y = (event.clientY - rect.top) / rect.height; + + // only send an API request to modify the image if we are actively dragging + if (dragStart && dragStartRef.current) { + + const landmark = findClosestLandmark(x, y, currentLandmark?.group); + + console.log(`Dragging mouse (was over ${currentLandmark?.group || 'nothing'}, now over ${landmark.group})`); + + // Compute the vector from the landmark center to the current mouse position + modifyImageWithRateLimit({ + landmark: currentLandmark || landmark, // this will still use the initially selected landmark + vector: { + x: x - landmarkCenters[landmark.group].x, + y: y - landmarkCenters[landmark.group].y, + z: 0 // Z is 0 as mouse interaction is 2D + } + }); + setIsDragging(true); + } else { + const landmark = findClosestLandmark(x, y); + + //console.log(`Moving mouse over ${landmark.group}`); + // console.log(`Simple mouse move over ${landmark.group}`); + + // we need to be careful here, we don't want to change the active + // landmark dynamically if we are busy dragging + + if (!currentLandmark || (currentLandmark?.group !== landmark?.group)) { + // console.log("setting activeLandmark to ", landmark); + setActiveLandmark(landmark); + } + setIsHovering(true); // Ensure hovering state is maintained during movement + } + }, [currentLandmark, dragStart, setIsHovering, setActiveLandmark, setIsDragging, modifyImageWithRateLimit, landmarkCenters]); + + const handleMouseUp = useCallback((event: React.MouseEvent<HTMLCanvasElement>) => { + if (!canvasRef.current) return; + + const rect = canvasRef.current.getBoundingClientRect(); + const x = (event.clientX - rect.left) / rect.width; + const y = (event.clientY - rect.top) / rect.height; + + // only send an API request to modify the image if we are actively dragging + if (dragStart && dragStartRef.current) { + + const landmark = findClosestLandmark(x, y, currentLandmark?.group); + + console.log(`Mouse up (was over ${currentLandmark?.group || 'nothing'}, now over ${landmark.group})`); + + // Compute the vector from the landmark center to the current mouse position + modifyImageWithRateLimit({ + landmark: currentLandmark || landmark, // this will still use the initially selected landmark + vector: { + x: x - landmarkCenters[landmark.group].x, + y: y - landmarkCenters[landmark.group].y, + z: 0 // Z is 0 as mouse interaction is 2D + } + }); + } + + setIsDragging(false); + dragStartRef.current = null; + setActiveLandmark(undefined); + }, [currentLandmark, isDragging, modifyImageWithRateLimit, findClosestLandmark, setActiveLandmark, landmarkCenters, modifyImageWithRateLimit, setIsDragging]); + + useEffect(() => { + facePoke.setOnModifiedImage((image: string, image_hash: string) => { + if (image) { + setPreviewImage(image); + } + setOriginalImageHash(image_hash); + lastModifiedImageHashRef.current = image_hash; + }); + }, [setPreviewImage, setOriginalImageHash]); + + return { + canvasRef, + canvasRefCallback, + mediaPipeRef, + faceLandmarks, + isMediaPipeReady, + isDrawingUtilsReady, + blendShapes, + + //dragStart, + //setDragStart, + //dragEnd, + //setDragEnd, + setFaceLandmarks, + setBlendShapes, + + handleMouseDown, + handleMouseUp, + handleMouseMove, + handleMouseEnter, + handleMouseLeave, + + currentLandmark, + currentOpacity, + } +} diff --git a/client/src/hooks/useFacePokeAPI.ts b/client/src/hooks/useFacePokeAPI.ts new file mode 100644 index 0000000000000000000000000000000000000000..5ebad7fc096da5b813df54d28ddeed9dd6c95936 --- /dev/null +++ b/client/src/hooks/useFacePokeAPI.ts @@ -0,0 +1,44 @@ +import { useEffect, useState } from "react"; + +import { facePoke } from "../lib/facePoke"; +import { useMainStore } from "./useMainStore"; + +export function useFacePokeAPI() { + + // State for FacePoke + const [status, setStatus] = useState(''); + const [isDebugMode, setIsDebugMode] = useState(false); + const [interruptMessage, setInterruptMessage] = useState<string | null>(null); + + const [isLoading, setIsLoading] = useState(false); + + // Initialize FacePoke + useEffect(() => { + const urlParams = new URLSearchParams(window.location.search); + setIsDebugMode(urlParams.get('debug') === 'true'); + }, []); + + // Handle WebSocket interruptions + useEffect(() => { + const handleInterruption = (event: CustomEvent) => { + setInterruptMessage(event.detail.message); + }; + + window.addEventListener('websocketInterruption' as any, handleInterruption); + + return () => { + window.removeEventListener('websocketInterruption' as any, handleInterruption); + }; + }, []); + + return { + facePoke, + status, + setStatus, + isDebugMode, + setIsDebugMode, + interruptMessage, + isLoading, + setIsLoading, + } +} diff --git a/client/src/hooks/useMainStore.ts b/client/src/hooks/useMainStore.ts new file mode 100644 index 0000000000000000000000000000000000000000..6c973a00c20f540c13d54b4a470b14f86c583f8d --- /dev/null +++ b/client/src/hooks/useMainStore.ts @@ -0,0 +1,58 @@ +import { create } from 'zustand' +import type { ClosestLandmark } from './useFaceLandmarkDetection' +import type { ImageModificationParams } from '@/lib/facePoke' + +interface ImageState { + error: string + imageFile: File | null + originalImage: string + previewImage: string + originalImageHash: string + minLatency: number + averageLatency: number + maxLatency: number + activeLandmark?: ClosestLandmark + params: Partial<ImageModificationParams> + setError: (error?: string) => void + setImageFile: (file: File | null) => void + setOriginalImage: (url: string) => void + setOriginalImageHash: (hash: string) => void + setPreviewImage: (url: string) => void + resetImage: () => void + setAverageLatency: (averageLatency: number) => void + setActiveLandmark: (activeLandmark?: ClosestLandmark) => void + setParams: (params: Partial<ImageModificationParams>) => void +} + +export const useMainStore = create<ImageState>((set, get) => ({ + error: '', + imageFile: null, + originalImage: '', + originalImageHash: '', + previewImage: '', + minLatency: 20, // min time between requests + averageLatency: 190, // this should be the average for most people + maxLatency: 4000, // max time between requests + activeLandmark: undefined, + params: {}, + setError: (error: string = '') => set({ error }), + setImageFile: (file) => set({ imageFile: file }), + setOriginalImage: (url) => set({ originalImage: url }), + setOriginalImageHash: (originalImageHash) => set({ originalImageHash }), + setPreviewImage: (url) => set({ previewImage: url }), + resetImage: () => { + const { originalImage } = get() + if (originalImage) { + set({ previewImage: originalImage }) + } + }, + setAverageLatency: (averageLatency: number) => set({ averageLatency }), + setActiveLandmark: (activeLandmark?: ClosestLandmark) => set({ activeLandmark }), + setParams: (params: Partial<ImageModificationParams>) => { + const {params: previousParams } = get() + set({ params: { + ...previousParams, + ...params + }}) + }, +})) diff --git a/client/src/index.tsx b/client/src/index.tsx new file mode 100644 index 0000000000000000000000000000000000000000..460767af6b3be1b6c158d7bd82971aab7349d245 --- /dev/null +++ b/client/src/index.tsx @@ -0,0 +1,6 @@ +import { createRoot } from 'react-dom/client'; + +import { App } from './app'; + +const root = createRoot(document.getElementById('root')!); +root.render(<App />); diff --git a/client/src/layout.tsx b/client/src/layout.tsx new file mode 100644 index 0000000000000000000000000000000000000000..396a91da985257878db9ece6dbbe1649676233d4 --- /dev/null +++ b/client/src/layout.tsx @@ -0,0 +1,14 @@ +import React, { type ReactNode } from 'react'; + +export function Layout({ children }: { children: ReactNode }) { + return ( + <div className="fixed min-h-screen w-full flex items-center justify-center bg-gradient-to-br from-gray-300 to-stone-300" + style={{ boxShadow: "inset 0 0 10vh 0 rgb(0 0 0 / 30%)" }}> + <div className="min-h-screen w-full py-8 flex flex-col justify-center"> + <div className="relative p-4 sm:max-w-5xl sm:mx-auto"> + {children} + </div> + </div> + </div> + ); +} diff --git a/client/src/lib/circularBuffer.ts b/client/src/lib/circularBuffer.ts new file mode 100644 index 0000000000000000000000000000000000000000..d368caad7767242b494bbfc8baa21a88c8d097cd --- /dev/null +++ b/client/src/lib/circularBuffer.ts @@ -0,0 +1,31 @@ + + +/** + * Circular buffer for storing and managing response times. + */ +export class CircularBuffer<T> { + private buffer: T[]; + private pointer: number; + + constructor(private capacity: number) { + this.buffer = new Array<T>(capacity); + this.pointer = 0; + } + + /** + * Adds an item to the buffer, overwriting the oldest item if full. + * @param item - The item to add to the buffer. + */ + push(item: T): void { + this.buffer[this.pointer] = item; + this.pointer = (this.pointer + 1) % this.capacity; + } + + /** + * Retrieves all items currently in the buffer. + * @returns An array of all items in the buffer. + */ + getAll(): T[] { + return this.buffer.filter(item => item !== undefined); + } +} diff --git a/client/src/lib/convertImageToBase64.ts b/client/src/lib/convertImageToBase64.ts new file mode 100644 index 0000000000000000000000000000000000000000..9c260075dcebf75efc3ac4f596f038a1e339573f --- /dev/null +++ b/client/src/lib/convertImageToBase64.ts @@ -0,0 +1,19 @@ +export async function convertImageToBase64(imageFile: File): Promise<string> { + return new Promise((resolve, reject) => { + const reader = new FileReader(); + + reader.onload = () => { + if (typeof reader.result === 'string') { + resolve(reader.result); + } else { + reject(new Error('Failed to convert image to base64')); + } + }; + + reader.onerror = () => { + reject(new Error('Error reading file')); + }; + + reader.readAsDataURL(imageFile); + }); +} diff --git a/client/src/lib/facePoke.ts b/client/src/lib/facePoke.ts new file mode 100644 index 0000000000000000000000000000000000000000..14aaacacf46d5911b774b0d1e5e45ea2f8e3648e --- /dev/null +++ b/client/src/lib/facePoke.ts @@ -0,0 +1,398 @@ +import { v4 as uuidv4 } from 'uuid'; +import { CircularBuffer } from './circularBuffer'; +import { useMainStore } from '@/hooks/useMainStore'; + +/** + * Represents a tracked request with its UUID and timestamp. + */ +export interface TrackedRequest { + uuid: string; + timestamp: number; +} + +/** + * Represents the parameters for image modification. + */ +export interface ImageModificationParams { + eyes: number; + eyebrow: number; + wink: number; + pupil_x: number; + pupil_y: number; + aaa: number; + eee: number; + woo: number; + smile: number; + rotate_pitch: number; + rotate_yaw: number; + rotate_roll: number; +} + +/** + * Represents a message to modify an image. + */ +export interface ModifyImageMessage { + type: 'modify_image'; + image?: string; + image_hash?: string; + params: Partial<ImageModificationParams>; +} + + +/** + * Callback type for handling modified images. + */ +type OnModifiedImage = (image: string, image_hash: string) => void; + +/** + * Enum representing the different states of a WebSocket connection. + */ +enum WebSocketState { + CONNECTING = 0, + OPEN = 1, + CLOSING = 2, + CLOSED = 3 +} + +/** + * FacePoke class manages the WebSocket connection + */ +export class FacePoke { + private ws: WebSocket | null = null; + private readonly connectionId: string = uuidv4(); + private isUnloading: boolean = false; + private onModifiedImage: OnModifiedImage = () => {}; + private reconnectAttempts: number = 0; + private readonly maxReconnectAttempts: number = 5; + private readonly reconnectDelay: number = 5000; + private readonly eventListeners: Map<string, Set<Function>> = new Map(); + + private requestTracker: Map<string, TrackedRequest> = new Map(); + private responseTimeBuffer: CircularBuffer<number>; + private readonly MAX_TRACKED_TIMES = 5; // Number of recent response times to track + + /** + * Creates an instance of FacePoke. + * Initializes the WebSocket connection. + */ + constructor() { + console.log(`[FacePoke] Initializing FacePoke instance with connection ID: ${this.connectionId}`); + this.initializeWebSocket(); + this.setupUnloadHandler(); + + this.responseTimeBuffer = new CircularBuffer<number>(this.MAX_TRACKED_TIMES); + console.log(`[FacePoke] Initialized response time tracker with capacity: ${this.MAX_TRACKED_TIMES}`); + } + + + /** + * Generates a unique UUID for a request and starts tracking it. + * @returns The generated UUID for the request. + */ + private trackRequest(): string { + const uuid = uuidv4(); + this.requestTracker.set(uuid, { uuid, timestamp: Date.now() }); + // console.log(`[FacePoke] Started tracking request with UUID: ${uuid}`); + return uuid; + } + + /** + * Completes tracking for a request and updates response time statistics. + * @param uuid - The UUID of the completed request. + */ + private completeRequest(uuid: string): void { + const request = this.requestTracker.get(uuid); + if (request) { + const responseTime = Date.now() - request.timestamp; + this.responseTimeBuffer.push(responseTime); + this.requestTracker.delete(uuid); + this.updateThrottleTime(); + console.log(`[FacePoke] Completed request ${uuid}. Response time: ${responseTime}ms`); + } else { + console.warn(`[FacePoke] Attempted to complete unknown request: ${uuid}`); + } + } + + /** + * Calculates the average response time from recent requests. + * @returns The average response time in milliseconds. + */ + private calculateAverageResponseTime(): number { + const times = this.responseTimeBuffer.getAll(); + + const averageLatency = useMainStore.getState().averageLatency; + + if (times.length === 0) return averageLatency; + const sum = times.reduce((acc, time) => acc + time, 0); + return sum / times.length; + } + + /** + * Updates the throttle time based on recent response times. + */ + private updateThrottleTime(): void { + const { minLatency, maxLatency, averageLatency, setAverageLatency } = useMainStore.getState(); + const avgResponseTime = this.calculateAverageResponseTime(); + const newLatency = Math.min(minLatency, Math.max(minLatency, avgResponseTime)); + + if (newLatency !== averageLatency) { + setAverageLatency(newLatency) + console.log(`[FacePoke] Updated throttle time (latency is ${newLatency}ms)`); + } + } + + /** + * Sets the callback function for handling modified images. + * @param handler - The function to be called when a modified image is received. + */ + public setOnModifiedImage(handler: OnModifiedImage): void { + this.onModifiedImage = handler; + console.log(`[FacePoke] onModifiedImage handler set`); + } + + /** + * Starts or restarts the WebSocket connection. + */ + public async startWebSocket(): Promise<void> { + console.log(`[FacePoke] Starting WebSocket connection.`); + if (!this.ws || this.ws.readyState !== WebSocketState.OPEN) { + await this.initializeWebSocket(); + } + } + + /** + * Initializes the WebSocket connection. + * Implements exponential backoff for reconnection attempts. + */ + private async initializeWebSocket(): Promise<void> { + console.log(`[FacePoke][${this.connectionId}] Initializing WebSocket connection`); + + const connect = () => { + this.ws = new WebSocket(`wss://${window.location.host}/ws`); + + this.ws.onopen = this.handleWebSocketOpen.bind(this); + this.ws.onmessage = this.handleWebSocketMessage.bind(this); + this.ws.onclose = this.handleWebSocketClose.bind(this); + this.ws.onerror = this.handleWebSocketError.bind(this); + }; + + // const debouncedConnect = debounce(connect, this.reconnectDelay, { leading: true, trailing: false }); + + connect(); // Initial connection attempt + } + + /** + * Handles the WebSocket open event. + */ + private handleWebSocketOpen(): void { + console.log(`[FacePoke][${this.connectionId}] WebSocket connection opened`); + this.reconnectAttempts = 0; // Reset reconnect attempts on successful connection + this.emitEvent('websocketOpen'); + } + + // Update handleWebSocketMessage to complete request tracking + private handleWebSocketMessage(event: MessageEvent): void { + try { + const data = JSON.parse(event.data); + // console.log(`[FacePoke][${this.connectionId}] Received JSON data:`, data); + + if (data.uuid) { + this.completeRequest(data.uuid); + } + + if (data.type === 'modified_image') { + if (data?.image) { + this.onModifiedImage(data.image, data.image_hash); + } + } + + this.emitEvent('message', data); + } catch (error) { + console.error(`[FacePoke][${this.connectionId}] Error parsing WebSocket message:`, error); + } + } + + /** + * Handles WebSocket close events. + * Implements reconnection logic with exponential backoff. + * @param event - The CloseEvent containing close information. + */ + private handleWebSocketClose(event: CloseEvent): void { + if (event.wasClean) { + console.log(`[FacePoke][${this.connectionId}] WebSocket connection closed cleanly, code=${event.code}, reason=${event.reason}`); + } else { + console.warn(`[FacePoke][${this.connectionId}] WebSocket connection abruptly closed`); + } + + this.emitEvent('websocketClose', event); + + // Attempt to reconnect after a delay, unless the page is unloading or max attempts reached + if (!this.isUnloading && this.reconnectAttempts < this.maxReconnectAttempts) { + this.reconnectAttempts++; + const delay = Math.min(1000 * (2 ** this.reconnectAttempts), 30000); // Exponential backoff, max 30 seconds + console.log(`[FacePoke][${this.connectionId}] Attempting to reconnect in ${delay}ms (Attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts})...`); + setTimeout(() => this.initializeWebSocket(), delay); + } else if (this.reconnectAttempts >= this.maxReconnectAttempts) { + console.error(`[FacePoke][${this.connectionId}] Max reconnect attempts reached. Please refresh the page.`); + this.emitEvent('maxReconnectAttemptsReached'); + } + } + + /** + * Handles WebSocket errors. + * @param error - The error event. + */ + private handleWebSocketError(error: Event): void { + console.error(`[FacePoke][${this.connectionId}] WebSocket error:`, error); + this.emitEvent('websocketError', error); + } + + /** + * Handles interruption messages from the server. + * @param message - The interruption message. + */ + private handleInterruption(message: string): void { + console.warn(`[FacePoke] Interruption: ${message}`); + this.emitEvent('interruption', message); + } + + /** + * Toggles the microphone on or off. + * @param isOn - Whether to turn the microphone on (true) or off (false). + */ + public async toggleMicrophone(isOn: boolean): Promise<void> { + console.log(`[FacePoke] Attempting to ${isOn ? 'start' : 'stop'} microphone`); + try { + if (isOn) { + await this.startMicrophone(); + } else { + this.stopMicrophone(); + } + this.emitEvent('microphoneToggled', isOn); + } catch (error) { + console.error(`[FacePoke] Error toggling microphone:`, error); + this.emitEvent('microphoneError', error); + throw error; + } + } + + +/** + * Cleans up resources and closes connections. + */ +public cleanup(): void { + console.log('[FacePoke] Starting cleanup process'); + if (this.ws) { + this.ws.close(); + this.ws = null; + } + this.eventListeners.clear(); + console.log('[FacePoke] Cleanup completed'); + this.emitEvent('cleanup'); +} + + /** + * Modifies an image based on the provided parameters + * @param image - The data-uri base64 image to modify. + * @param imageHash - The hash of the image to modify. + * @param params - The parameters for image modification. + */ + public modifyImage(image: string | null, imageHash: string | null, params: Partial<ImageModificationParams>): void { + try { + const message: ModifyImageMessage = { + type: 'modify_image', + params: params + }; + + if (image) { + message.image = image; + } else if (imageHash) { + message.image_hash = imageHash; + } else { + throw new Error('Either image or imageHash must be provided'); + } + + this.sendJsonMessage(message); + // console.log(`[FacePoke] Sent modify image request with UUID: ${uuid}`); + } catch (err) { + console.error(`[FacePoke] Failed to modify the image:`, err); + } + } + + /** + * Sends a JSON message through the WebSocket connection with request tracking. + * @param message - The message to send. + * @throws Error if the WebSocket is not open. + */ + private sendJsonMessage<T>(message: T): void { + if (!this.ws || this.ws.readyState !== WebSocketState.OPEN) { + const error = new Error('WebSocket connection is not open'); + console.error('[FacePoke] Error sending JSON message:', error); + this.emitEvent('sendJsonMessageError', error); + throw error; + } + + const uuid = this.trackRequest(); + const messageWithUuid = { ...message, uuid }; + // console.log(`[FacePoke] Sending JSON message with UUID ${uuid}:`, messageWithUuid); + this.ws.send(JSON.stringify(messageWithUuid)); + } + +/** + * Sets up the unload handler to clean up resources when the page is unloading. + */ +private setupUnloadHandler(): void { + window.addEventListener('beforeunload', () => { + console.log('[FacePoke] Page is unloading, cleaning up resources'); + this.isUnloading = true; + if (this.ws) { + this.ws.close(1000, 'Page is unloading'); + } + this.cleanup(); + }); +} + +/** + * Adds an event listener for a specific event type. + * @param eventType - The type of event to listen for. + * @param listener - The function to be called when the event is emitted. + */ +public addEventListener(eventType: string, listener: Function): void { + if (!this.eventListeners.has(eventType)) { + this.eventListeners.set(eventType, new Set()); + } + this.eventListeners.get(eventType)!.add(listener); + console.log(`[FacePoke] Added event listener for '${eventType}'`); +} + +/** + * Removes an event listener for a specific event type. + * @param eventType - The type of event to remove the listener from. + * @param listener - The function to be removed from the listeners. + */ +public removeEventListener(eventType: string, listener: Function): void { + const listeners = this.eventListeners.get(eventType); + if (listeners) { + listeners.delete(listener); + console.log(`[FacePoke] Removed event listener for '${eventType}'`); + } +} + +/** + * Emits an event to all registered listeners for that event type. + * @param eventType - The type of event to emit. + * @param data - Optional data to pass to the event listeners. + */ +private emitEvent(eventType: string, data?: any): void { + const listeners = this.eventListeners.get(eventType); + if (listeners) { + console.log(`[FacePoke] Emitting event '${eventType}' with data:`, data); + listeners.forEach(listener => listener(data)); + } +} +} + +/** +* Singleton instance of the FacePoke class. +*/ +export const facePoke = new FacePoke(); diff --git a/client/src/lib/throttle.ts b/client/src/lib/throttle.ts new file mode 100644 index 0000000000000000000000000000000000000000..70a7dd34ec33d85c0e8383a10dac86a9244dcfc4 --- /dev/null +++ b/client/src/lib/throttle.ts @@ -0,0 +1,32 @@ + +/** + * Custom throttle function that allows the first call to go through immediately + * and then limits subsequent calls. + * @param func - The function to throttle. + * @param limit - The minimum time between function calls in milliseconds. + * @returns A throttled version of the function. + */ +export function throttle<T extends (...args: any[]) => any>(func: T, limit: number): T { + let lastCall = 0; + let timeoutId: NodeJS.Timer | null = null; + + return function (this: any, ...args: Parameters<T>) { + const context = this; + const now = Date.now(); + + if (now - lastCall >= limit) { + if (timeoutId !== null) { + clearTimeout(timeoutId); + timeoutId = null; + } + lastCall = now; + return func.apply(context, args); + } else if (!timeoutId) { + timeoutId = setTimeout(() => { + lastCall = Date.now(); + timeoutId = null; + func.apply(context, args); + }, limit - (now - lastCall)); + } + } as T; +} diff --git a/client/src/lib/utils.ts b/client/src/lib/utils.ts new file mode 100644 index 0000000000000000000000000000000000000000..a4eb975048cbdbf4ea12e4c2dc55da20d7181486 --- /dev/null +++ b/client/src/lib/utils.ts @@ -0,0 +1,15 @@ +import { clsx, type ClassValue } from "clsx" +import { twMerge } from "tailwind-merge" + +export function cn(...inputs: ClassValue[]) { + return twMerge(clsx(inputs)) +} + +export function truncateFileName(fileName: string, maxLength: number = 16) { + if (fileName.length <= maxLength) return fileName; + + const start = fileName.slice(0, maxLength / 2 - 1); + const end = fileName.slice(-maxLength / 2 + 2); + + return `${start}...${end}`; +}; diff --git a/client/src/styles/globals.css b/client/src/styles/globals.css new file mode 100644 index 0000000000000000000000000000000000000000..95d8cab145debb5c4214ff5a53fb71977f58504b --- /dev/null +++ b/client/src/styles/globals.css @@ -0,0 +1,81 @@ +@tailwind base; +@tailwind components; +@tailwind utilities; + +@layer base { + :root { + --background: 0 0% 100%; + --foreground: 222.2 47.4% 11.2%; + + --muted: 210 40% 96.1%; + --muted-foreground: 215.4 16.3% 46.9%; + + --popover: 0 0% 100%; + --popover-foreground: 222.2 47.4% 11.2%; + + --border: 214.3 31.8% 91.4%; + --input: 214.3 31.8% 91.4%; + + --card: 0 0% 100%; + --card-foreground: 222.2 47.4% 11.2%; + + --primary: 222.2 47.4% 11.2%; + --primary-foreground: 210 40% 98%; + + --secondary: 210 40% 96.1%; + --secondary-foreground: 222.2 47.4% 11.2%; + + --accent: 210 40% 96.1%; + --accent-foreground: 222.2 47.4% 11.2%; + + --destructive: 0 100% 50%; + --destructive-foreground: 210 40% 98%; + + --ring: 215 20.2% 65.1%; + + --radius: 0.5rem; + } + + .dark { + --background: 224 71% 4%; + --foreground: 213 31% 91%; + + --muted: 223 47% 11%; + --muted-foreground: 215.4 16.3% 56.9%; + + --accent: 216 34% 17%; + --accent-foreground: 210 40% 98%; + + --popover: 224 71% 4%; + --popover-foreground: 215 20.2% 65.1%; + + --border: 216 34% 17%; + --input: 216 34% 17%; + + --card: 224 71% 4%; + --card-foreground: 213 31% 91%; + + --primary: 210 40% 98%; + --primary-foreground: 222.2 47.4% 1.2%; + + --secondary: 222.2 47.4% 11.2%; + --secondary-foreground: 210 40% 98%; + + --destructive: 0 63% 31%; + --destructive-foreground: 210 40% 98%; + + --ring: 216 34% 17%; + + --radius: 0.5rem; + } +} + +@layer base { + * { + @apply border-border; + } + body { + @apply bg-background text-foreground; + font-feature-settings: "rlig" 1, "calt" 1; + } +} diff --git a/client/tailwind.config.js b/client/tailwind.config.js new file mode 100644 index 0000000000000000000000000000000000000000..ab1e406f32370649581dbf771427e5c88946796c --- /dev/null +++ b/client/tailwind.config.js @@ -0,0 +1,86 @@ +const { fontFamily } = require("tailwindcss/defaultTheme") + +/** @type {import('tailwindcss').Config} */ +module.exports = { + darkMode: ["class"], + content: [ + "app/**/*.{ts,tsx}", + "components/**/*.{ts,tsx}", + '../public/index.html' + ], + theme: { + container: { + center: true, + padding: "2rem", + screens: { + "2xl": "1400px", + }, + }, + extend: { + colors: { + border: "hsl(var(--border))", + input: "hsl(var(--input))", + ring: "hsl(var(--ring))", + background: "hsl(var(--background))", + foreground: "hsl(var(--foreground))", + primary: { + DEFAULT: "hsl(var(--primary))", + foreground: "hsl(var(--primary-foreground))", + }, + secondary: { + DEFAULT: "hsl(var(--secondary))", + foreground: "hsl(var(--secondary-foreground))", + }, + destructive: { + DEFAULT: "hsl(var(--destructive))", + foreground: "hsl(var(--destructive-foreground))", + }, + muted: { + DEFAULT: "hsl(var(--muted))", + foreground: "hsl(var(--muted-foreground))", + }, + accent: { + DEFAULT: "hsl(var(--accent))", + foreground: "hsl(var(--accent-foreground))", + }, + popover: { + DEFAULT: "hsl(var(--popover))", + foreground: "hsl(var(--popover-foreground))", + }, + card: { + DEFAULT: "hsl(var(--card))", + foreground: "hsl(var(--card-foreground))", + }, + }, + borderRadius: { + lg: `var(--radius)`, + md: `calc(var(--radius) - 2px)`, + sm: "calc(var(--radius) - 4px)", + }, + fontFamily: { + sans: ["var(--font-sans)", ...fontFamily.sans], + }, + fontSize: { + "5xs": "8px", + "4xs": "9px", + "3xs": "10px", + "2xs": "11px" + }, + keyframes: { + "accordion-down": { + from: { height: "0" }, + to: { height: "var(--radix-accordion-content-height)" }, + }, + "accordion-up": { + from: { height: "var(--radix-accordion-content-height)" }, + to: { height: "0" }, + }, + }, + animation: { + "accordion-down": "accordion-down 0.2s ease-out", + "accordion-up": "accordion-up 0.2s ease-out", + }, + }, + }, + plugins: [require("tailwindcss-animate")], +} diff --git a/client/tsconfig.json b/client/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..66823aa62486477bfce85e0c79a06a2665b2fd3a --- /dev/null +++ b/client/tsconfig.json @@ -0,0 +1,32 @@ +{ + "compilerOptions": { + // Enable latest features + "lib": ["ESNext", "DOM", "DOM.Iterable"], + "target": "ESNext", + "module": "ESNext", + "moduleDetection": "force", + "jsx": "react-jsx", + "allowJs": true, + + // Bundler mode + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "verbatimModuleSyntax": true, + "noEmit": true, + + "baseUrl": ".", + "paths": { + "@/*": ["./src/*"] + }, + + // Best practices + "strict": true, + "skipLibCheck": true, + "noFallthroughCasesInSwitch": true, + + // Some stricter flags (disabled by default) + "noUnusedLocals": false, + "noUnusedParameters": false, + "noPropertyAccessFromIndexSignature": false + } +} diff --git a/engine.py b/engine.py new file mode 100644 index 0000000000000000000000000000000000000000..04af6f7bbd70a1f132d52ee83fdab0693b57e10d --- /dev/null +++ b/engine.py @@ -0,0 +1,300 @@ +import time +import logging +import hashlib +import uuid +import os +import io +import shutil +import asyncio +import base64 +from concurrent.futures import ThreadPoolExecutor +from queue import Queue +from typing import Dict, Any, List, Optional, AsyncGenerator, Tuple, Union +from functools import lru_cache +import av +import numpy as np +import cv2 +import torch +import torch.nn.functional as F +from PIL import Image + +from liveportrait.config.argument_config import ArgumentConfig +from liveportrait.utils.camera import get_rotation_matrix +from liveportrait.utils.io import load_image_rgb, load_driving_info, resize_to_limit +from liveportrait.utils.crop import prepare_paste_back, paste_back + +# Configure logging +logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') +logger = logging.getLogger(__name__) + +# Global constants +DATA_ROOT = os.environ.get('DATA_ROOT', '/tmp/data') +MODELS_DIR = os.path.join(DATA_ROOT, "models") + +def base64_data_uri_to_PIL_Image(base64_string: str) -> Image.Image: + """ + Convert a base64 data URI to a PIL Image. + + Args: + base64_string (str): The base64 encoded image data. + + Returns: + Image.Image: The decoded PIL Image. + """ + if ',' in base64_string: + base64_string = base64_string.split(',')[1] + img_data = base64.b64decode(base64_string) + return Image.open(io.BytesIO(img_data)) + +class Engine: + """ + The main engine class for FacePoke + """ + + def __init__(self, live_portrait): + """ + Initialize the FacePoke engine with necessary models and processors. + + Args: + live_portrait (LivePortraitPipeline): The LivePortrait model for video generation. + """ + self.live_portrait = live_portrait + + self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + + # cache for the "modify image" workflow + self.image_cache = {} # Stores the original images + self.processed_cache = {} # Stores the processed image data + + logger.info("✅ FacePoke Engine initialized successfully.") + + def get_image_hash(self, image: Union[Image.Image, str, bytes]) -> str: + """ + Compute or retrieve the hash for an image. + + Args: + image (Union[Image.Image, str, bytes]): The input image, either as a PIL Image, + base64 string, or bytes. + + Returns: + str: The computed hash of the image. + """ + if isinstance(image, str): + # Assume it's already a hash if it's a string of the right length + if len(image) == 32: + return image + # Otherwise, assume it's a base64 string + image = base64_data_uri_to_PIL_Image(image) + + if isinstance(image, Image.Image): + return hashlib.md5(image.tobytes()).hexdigest() + elif isinstance(image, bytes): + return hashlib.md5(image).hexdigest() + else: + raise ValueError("Unsupported image type") + + @lru_cache(maxsize=128) + def _process_image(self, image_hash: str) -> Dict[str, Any]: + """ + Process the input image and cache the results. + + Args: + image_hash (str): Hash of the input image. + + Returns: + Dict[str, Any]: Processed image data. + """ + logger.info(f"Processing image with hash: {image_hash}") + if image_hash not in self.image_cache: + raise ValueError(f"Image with hash {image_hash} not found in cache") + + image = self.image_cache[image_hash] + img_rgb = np.array(image) + + inference_cfg = self.live_portrait.live_portrait_wrapper.cfg + img_rgb = resize_to_limit(img_rgb, inference_cfg.ref_max_shape, inference_cfg.ref_shape_n) + crop_info = self.live_portrait.cropper.crop_single_image(img_rgb) + img_crop_256x256 = crop_info['img_crop_256x256'] + + I_s = self.live_portrait.live_portrait_wrapper.prepare_source(img_crop_256x256) + x_s_info = self.live_portrait.live_portrait_wrapper.get_kp_info(I_s) + f_s = self.live_portrait.live_portrait_wrapper.extract_feature_3d(I_s) + x_s = self.live_portrait.live_portrait_wrapper.transform_keypoint(x_s_info) + + processed_data = { + 'img_rgb': img_rgb, + 'crop_info': crop_info, + 'x_s_info': x_s_info, + 'f_s': f_s, + 'x_s': x_s, + 'inference_cfg': inference_cfg + } + + self.processed_cache[image_hash] = processed_data + + return processed_data + + async def modify_image(self, image_or_hash: Union[Image.Image, str, bytes], params: Dict[str, float]) -> str: + """ + Modify the input image based on the provided parameters, using caching for efficiency + and outputting the result as a WebP image. + + Args: + image_or_hash (Union[Image.Image, str, bytes]): Input image as a PIL Image, base64-encoded string, + image bytes, or a hash string. + params (Dict[str, float]): Parameters for face transformation. + + Returns: + str: Modified image as a base64-encoded WebP data URI. + + Raises: + ValueError: If there's an error modifying the image or WebP is not supported. + """ + logger.info("Starting image modification") + logger.debug(f"Modification parameters: {params}") + + try: + image_hash = self.get_image_hash(image_or_hash) + + # If we don't have the image in cache yet, add it + if image_hash not in self.image_cache: + if isinstance(image_or_hash, (Image.Image, bytes)): + self.image_cache[image_hash] = image_or_hash + elif isinstance(image_or_hash, str) and len(image_or_hash) != 32: + # It's a base64 string, not a hash + self.image_cache[image_hash] = base64_data_uri_to_PIL_Image(image_or_hash) + else: + raise ValueError("Image not found in cache and no valid image provided") + + # Process the image (this will use the cache if available) + if image_hash not in self.processed_cache: + processed_data = await asyncio.to_thread(self._process_image, image_hash) + else: + processed_data = self.processed_cache[image_hash] + + # Apply modifications based on params + x_d_new = processed_data['x_s_info']['kp'].clone() + await self._apply_facial_modifications(x_d_new, params) + + # Apply rotation + R_new = get_rotation_matrix( + processed_data['x_s_info']['pitch'] + params.get('rotate_pitch', 0), + processed_data['x_s_info']['yaw'] + params.get('rotate_yaw', 0), + processed_data['x_s_info']['roll'] + params.get('rotate_roll', 0) + ) + x_d_new = processed_data['x_s_info']['scale'] * (x_d_new @ R_new) + processed_data['x_s_info']['t'] + + # Apply stitching + x_d_new = await asyncio.to_thread(self.live_portrait.live_portrait_wrapper.stitching, processed_data['x_s'], x_d_new) + + # Generate the output + out = await asyncio.to_thread(self.live_portrait.live_portrait_wrapper.warp_decode, processed_data['f_s'], processed_data['x_s'], x_d_new) + I_p = self.live_portrait.live_portrait_wrapper.parse_output(out['out'])[0] + + # Paste back to full size + mask_ori = await asyncio.to_thread( + prepare_paste_back, + processed_data['inference_cfg'].mask_crop, processed_data['crop_info']['M_c2o'], + dsize=(processed_data['img_rgb'].shape[1], processed_data['img_rgb'].shape[0]) + ) + I_p_to_ori_blend = await asyncio.to_thread( + paste_back, + I_p, processed_data['crop_info']['M_c2o'], processed_data['img_rgb'], mask_ori + ) + + # Convert the result to a PIL Image + result_image = Image.fromarray(I_p_to_ori_blend) + + # Save as WebP + buffered = io.BytesIO() + result_image.save(buffered, format="WebP", quality=85) # Adjust quality as needed + modified_image_base64 = base64.b64encode(buffered.getvalue()).decode('utf-8') + + logger.info("Image modification completed successfully") + return f"data:image/webp;base64,{modified_image_base64}" + + except Exception as e: + logger.error(f"Error in modify_image: {str(e)}") + logger.exception("Full traceback:") + raise ValueError(f"Failed to modify image: {str(e)}") + + async def _apply_facial_modifications(self, x_d_new: torch.Tensor, params: Dict[str, float]) -> None: + """ + Apply facial modifications to the keypoints based on the provided parameters. + + Args: + x_d_new (torch.Tensor): Tensor of facial keypoints to be modified. + params (Dict[str, float]): Parameters for face transformation. + """ + modifications = [ + ('smile', [ + (0, 20, 1, -0.01), (0, 14, 1, -0.02), (0, 17, 1, 0.0065), (0, 17, 2, 0.003), + (0, 13, 1, -0.00275), (0, 16, 1, -0.00275), (0, 3, 1, -0.0035), (0, 7, 1, -0.0035) + ]), + ('aaa', [ + (0, 19, 1, 0.001), (0, 19, 2, 0.0001), (0, 17, 1, -0.0001) + ]), + ('eee', [ + (0, 20, 2, -0.001), (0, 20, 1, -0.001), (0, 14, 1, -0.001) + ]), + ('woo', [ + (0, 14, 1, 0.001), (0, 3, 1, -0.0005), (0, 7, 1, -0.0005), (0, 17, 2, -0.0005) + ]), + ('wink', [ + (0, 11, 1, 0.001), (0, 13, 1, -0.0003), (0, 17, 0, 0.0003), + (0, 17, 1, 0.0003), (0, 3, 1, -0.0003) + ]), + ('pupil_x', [ + (0, 11, 0, 0.0007 if params.get('pupil_x', 0) > 0 else 0.001), + (0, 15, 0, 0.001 if params.get('pupil_x', 0) > 0 else 0.0007) + ]), + ('pupil_y', [ + (0, 11, 1, -0.001), (0, 15, 1, -0.001) + ]), + ('eyes', [ + (0, 11, 1, -0.001), (0, 13, 1, 0.0003), (0, 15, 1, -0.001), (0, 16, 1, 0.0003), + (0, 1, 1, -0.00025), (0, 2, 1, 0.00025) + ]), + ('eyebrow', [ + (0, 1, 1, 0.001 if params.get('eyebrow', 0) > 0 else 0.0003), + (0, 2, 1, -0.001 if params.get('eyebrow', 0) > 0 else -0.0003), + (0, 1, 0, -0.001 if params.get('eyebrow', 0) <= 0 else 0), + (0, 2, 0, 0.001 if params.get('eyebrow', 0) <= 0 else 0) + ]) + ] + + for param_name, adjustments in modifications: + param_value = params.get(param_name, 0) + for i, j, k, factor in adjustments: + x_d_new[i, j, k] += param_value * factor + + # Special case for pupil_y affecting eyes + x_d_new[0, 11, 1] -= params.get('pupil_y', 0) * 0.001 + x_d_new[0, 15, 1] -= params.get('pupil_y', 0) * 0.001 + params['eyes'] = params.get('eyes', 0) - params.get('pupil_y', 0) / 2. + + async def cleanup(self): + """ + Perform cleanup operations for the Engine. + This method should be called when shutting down the application. + """ + logger.info("Starting Engine cleanup") + try: + # TODO: Add any additional cleanup operations here + logger.info("Engine cleanup completed successfully") + except Exception as e: + logger.error(f"Error during Engine cleanup: {str(e)}") + logger.exception("Full traceback:") + +def create_engine(models): + logger.info("Creating Engine instance...") + + live_portrait = models + + engine = Engine( + live_portrait=live_portrait, + # we might have more in the future + ) + + logger.info("Engine instance created successfully") + return engine diff --git a/liveportrait/config/__init__.py b/liveportrait/config/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/liveportrait/config/argument_config.py b/liveportrait/config/argument_config.py new file mode 100644 index 0000000000000000000000000000000000000000..043162742ce65227076501c834289fda8d24a0cf --- /dev/null +++ b/liveportrait/config/argument_config.py @@ -0,0 +1,44 @@ +# coding: utf-8 + +""" +config for user +""" + +import os.path as osp +from dataclasses import dataclass +import tyro +from typing_extensions import Annotated +from .base_config import PrintableConfig, make_abs_path + + +@dataclass(repr=False) # use repr from PrintableConfig +class ArgumentConfig(PrintableConfig): + ########## input arguments ########## + source_image: Annotated[str, tyro.conf.arg(aliases=["-s"])] = make_abs_path('../../assets/examples/source/s6.jpg') # path to the source portrait + driving_info: Annotated[str, tyro.conf.arg(aliases=["-d"])] = make_abs_path('../../assets/examples/driving/d0.mp4') # path to driving video or template (.pkl format) + output_dir: Annotated[str, tyro.conf.arg(aliases=["-o"])] = 'animations/' # directory to save output video + ##################################### + + ########## inference arguments ########## + device_id: int = 0 + flag_lip_zero : bool = True # whether let the lip to close state before animation, only take effect when flag_eye_retargeting and flag_lip_retargeting is False + flag_eye_retargeting: bool = False + flag_lip_retargeting: bool = False + flag_stitching: bool = True # we recommend setting it to True! + flag_relative: bool = True # whether to use relative motion + flag_pasteback: bool = True # whether to paste-back/stitch the animated face cropping from the face-cropping space to the original image space + flag_do_crop: bool = True # whether to crop the source portrait to the face-cropping space + flag_do_rot: bool = True # whether to conduct the rotation when flag_do_crop is True + ######################################### + + ########## crop arguments ########## + dsize: int = 512 + scale: float = 2.3 + vx_ratio: float = 0 # vx ratio + vy_ratio: float = -0.125 # vy ratio +up, -down + #################################### + + ########## gradio arguments ########## + server_port: Annotated[int, tyro.conf.arg(aliases=["-p"])] = 8890 + share: bool = True + server_name: str = "0.0.0.0" diff --git a/liveportrait/config/base_config.py b/liveportrait/config/base_config.py new file mode 100644 index 0000000000000000000000000000000000000000..216b8be50aecc8af4b9d1d2a9401e034dd7769e4 --- /dev/null +++ b/liveportrait/config/base_config.py @@ -0,0 +1,29 @@ +# coding: utf-8 + +""" +pretty printing class +""" + +from __future__ import annotations +import os.path as osp +from typing import Tuple + + +def make_abs_path(fn): + return osp.join(osp.dirname(osp.realpath(__file__)), fn) + + +class PrintableConfig: # pylint: disable=too-few-public-methods + """Printable Config defining str function""" + + def __repr__(self): + lines = [self.__class__.__name__ + ":"] + for key, val in vars(self).items(): + if isinstance(val, Tuple): + flattened_val = "[" + for item in val: + flattened_val += str(item) + "\n" + flattened_val = flattened_val.rstrip("\n") + val = flattened_val + "]" + lines += f"{key}: {str(val)}".split("\n") + return "\n ".join(lines) diff --git a/liveportrait/config/crop_config.py b/liveportrait/config/crop_config.py new file mode 100644 index 0000000000000000000000000000000000000000..d3c79be214ec6018ef4af298e306c47bd2a187f8 --- /dev/null +++ b/liveportrait/config/crop_config.py @@ -0,0 +1,18 @@ +# coding: utf-8 + +""" +parameters used for crop faces +""" + +import os.path as osp +from dataclasses import dataclass +from typing import Union, List +from .base_config import PrintableConfig + + +@dataclass(repr=False) # use repr from PrintableConfig +class CropConfig(PrintableConfig): + dsize: int = 512 # crop size + scale: float = 2.3 # scale factor + vx_ratio: float = 0 # vx ratio + vy_ratio: float = -0.125 # vy ratio +up, -down diff --git a/liveportrait/config/inference_config.py b/liveportrait/config/inference_config.py new file mode 100644 index 0000000000000000000000000000000000000000..0a384458fe709befa9f7b0ae73fdbdd4e576a44b --- /dev/null +++ b/liveportrait/config/inference_config.py @@ -0,0 +1,53 @@ +# coding: utf-8 + +""" +config dataclass used for inference +""" + +import os +import os.path as osp +from dataclasses import dataclass +from typing import Literal, Tuple +from .base_config import PrintableConfig, make_abs_path + +# Configuration +DATA_ROOT = os.environ.get('DATA_ROOT', '/tmp/data') +MODELS_DIR = os.path.join(DATA_ROOT, "models") + +@dataclass(repr=False) # use repr from PrintableConfig +class InferenceConfig(PrintableConfig): + models_config: str = make_abs_path('./models.yaml') # portrait animation config + checkpoint_F = os.path.join(MODELS_DIR, "liveportrait", "appearance_feature_extractor.pth") + checkpoint_M = os.path.join(MODELS_DIR, "liveportrait", "motion_extractor.pth") + checkpoint_W = os.path.join(MODELS_DIR, "liveportrait", "warping_module.pth") + checkpoint_G = os.path.join(MODELS_DIR, "liveportrait", "spade_generator.pth") + checkpoint_S = os.path.join(MODELS_DIR, "liveportrait", "stitching_retargeting_module.pth") + + flag_use_half_precision: bool = True # whether to use half precision + + flag_lip_zero: bool = True # whether let the lip to close state before animation, only take effect when flag_eye_retargeting and flag_lip_retargeting is False + lip_zero_threshold: float = 0.03 + + flag_eye_retargeting: bool = False + flag_lip_retargeting: bool = False + flag_stitching: bool = True # we recommend setting it to True! + + flag_relative: bool = True # whether to use relative motion + anchor_frame: int = 0 # set this value if find_best_frame is True + + input_shape: Tuple[int, int] = (256, 256) # input shape + output_format: Literal['mp4', 'gif'] = 'mp4' # output video format + output_fps: int = 25 # MuseTalk prefers 25 fps, so we use 25 as default fps for output video + crf: int = 15 # crf for output video + + flag_write_result: bool = True # whether to write output video + flag_pasteback: bool = True # whether to paste-back/stitch the animated face cropping from the face-cropping space to the original image space + mask_crop = None + flag_write_gif: bool = False + size_gif: int = 256 + ref_max_shape: int = 1280 + ref_shape_n: int = 2 + + device_id: int = 0 + flag_do_crop: bool = False # whether to crop the source portrait to the face-cropping space + flag_do_rot: bool = True # whether to conduct the rotation when flag_do_crop is True diff --git a/liveportrait/config/models.yaml b/liveportrait/config/models.yaml new file mode 100644 index 0000000000000000000000000000000000000000..131d1c65025c31e37af9239e211ea14454128a2e --- /dev/null +++ b/liveportrait/config/models.yaml @@ -0,0 +1,43 @@ +model_params: + appearance_feature_extractor_params: # the F in the paper + image_channel: 3 + block_expansion: 64 + num_down_blocks: 2 + max_features: 512 + reshape_channel: 32 + reshape_depth: 16 + num_resblocks: 6 + motion_extractor_params: # the M in the paper + num_kp: 21 + backbone: convnextv2_tiny + warping_module_params: # the W in the paper + num_kp: 21 + block_expansion: 64 + max_features: 512 + num_down_blocks: 2 + reshape_channel: 32 + estimate_occlusion_map: True + dense_motion_params: + block_expansion: 32 + max_features: 1024 + num_blocks: 5 + reshape_depth: 16 + compress: 4 + spade_generator_params: # the G in the paper + upscale: 2 # represents upsample factor 256x256 -> 512x512 + block_expansion: 64 + max_features: 512 + num_down_blocks: 2 + stitching_retargeting_module_params: # the S in the paper + stitching: + input_size: 126 # (21*3)*2 + hidden_sizes: [128, 128, 64] + output_size: 65 # (21*3)+2(tx,ty) + lip: + input_size: 65 # (21*3)+2 + hidden_sizes: [128, 128, 64] + output_size: 63 # (21*3) + eye: + input_size: 66 # (21*3)+3 + hidden_sizes: [256, 256, 128, 128, 64] + output_size: 63 # (21*3) diff --git a/liveportrait/gradio_pipeline.py b/liveportrait/gradio_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..c717897483380d69b4cd4622cf15eccde14a2eb0 --- /dev/null +++ b/liveportrait/gradio_pipeline.py @@ -0,0 +1,140 @@ +# coding: utf-8 + +""" +Pipeline for gradio +""" +import gradio as gr +from .config.argument_config import ArgumentConfig +from .live_portrait_pipeline import LivePortraitPipeline +from .utils.io import load_img_online +from .utils.rprint import rlog as log +from .utils.crop import prepare_paste_back, paste_back +from .utils.camera import get_rotation_matrix +from .utils.retargeting_utils import calc_eye_close_ratio, calc_lip_close_ratio + +def update_args(args, user_args): + """update the args according to user inputs + """ + for k, v in user_args.items(): + if hasattr(args, k): + setattr(args, k, v) + return args + +class GradioPipeline(LivePortraitPipeline): + + def __init__(self, inference_cfg, crop_cfg, args: ArgumentConfig): + super().__init__(inference_cfg, crop_cfg) + # self.live_portrait_wrapper = self.live_portrait_wrapper + self.args = args + # for single image retargeting + self.start_prepare = False + self.f_s_user = None + self.x_c_s_info_user = None + self.x_s_user = None + self.source_lmk_user = None + self.mask_ori = None + self.img_rgb = None + self.crop_M_c2o = None + + + def execute_video( + self, + input_image_path, + input_video_path, + flag_relative_input, + flag_do_crop_input, + flag_remap_input, + ): + """ for video driven potrait animation + """ + if input_image_path is not None and input_video_path is not None: + args_user = { + 'source_image': input_image_path, + 'driving_info': input_video_path, + 'flag_relative': flag_relative_input, + 'flag_do_crop': flag_do_crop_input, + 'flag_pasteback': flag_remap_input, + } + # update config from user input + self.args = update_args(self.args, args_user) + self.live_portrait_wrapper.update_config(self.args.__dict__) + self.cropper.update_config(self.args.__dict__) + # video driven animation + video_path, video_path_concat = self.execute(self.args) + gr.Info("Run successfully!", duration=2) + return video_path, video_path_concat, + else: + raise gr.Error("The input source portrait or driving video hasn't been prepared yet 💥!", duration=5) + + def execute_image(self, input_eye_ratio: float, input_lip_ratio: float): + """ for single image retargeting + """ + if input_eye_ratio is None or input_eye_ratio is None: + raise gr.Error("Invalid ratio input 💥!", duration=5) + elif self.f_s_user is None: + if self.start_prepare: + raise gr.Error( + "The source portrait is under processing 💥! Please wait for a second.", + duration=5 + ) + else: + raise gr.Error( + "The source portrait hasn't been prepared yet 💥! Please scroll to the top of the page to upload.", + duration=5 + ) + else: + # ∆_eyes,i = R_eyes(x_s; c_s,eyes, c_d,eyes,i) + combined_eye_ratio_tensor = self.live_portrait_wrapper.calc_combined_eye_ratio([[input_eye_ratio]], self.source_lmk_user) + eyes_delta = self.live_portrait_wrapper.retarget_eye(self.x_s_user, combined_eye_ratio_tensor) + # ∆_lip,i = R_lip(x_s; c_s,lip, c_d,lip,i) + combined_lip_ratio_tensor = self.live_portrait_wrapper.calc_combined_lip_ratio([[input_lip_ratio]], self.source_lmk_user) + lip_delta = self.live_portrait_wrapper.retarget_lip(self.x_s_user, combined_lip_ratio_tensor) + num_kp = self.x_s_user.shape[1] + # default: use x_s + x_d_new = self.x_s_user + eyes_delta.reshape(-1, num_kp, 3) + lip_delta.reshape(-1, num_kp, 3) + # D(W(f_s; x_s, x′_d)) + out = self.live_portrait_wrapper.warp_decode(self.f_s_user, self.x_s_user, x_d_new) + out = self.live_portrait_wrapper.parse_output(out['out'])[0] + out_to_ori_blend = paste_back(out, self.crop_M_c2o, self.img_rgb, self.mask_ori) + gr.Info("Run successfully!", duration=2) + return out, out_to_ori_blend + + + def prepare_retargeting(self, input_image_path, flag_do_crop = True): + """ for single image retargeting + """ + if input_image_path is not None: + gr.Info("Upload successfully!", duration=2) + self.start_prepare = True + inference_cfg = self.live_portrait_wrapper.cfg + ######## process source portrait ######## + img_rgb = load_img_online(input_image_path, mode='rgb', max_dim=1280, n=16) + log(f"Load source image from {input_image_path}.") + crop_info = self.cropper.crop_single_image(img_rgb) + if flag_do_crop: + I_s = self.live_portrait_wrapper.prepare_source(crop_info['img_crop_256x256']) + else: + I_s = self.live_portrait_wrapper.prepare_source(img_rgb) + x_s_info = self.live_portrait_wrapper.get_kp_info(I_s) + R_s = get_rotation_matrix(x_s_info['pitch'], x_s_info['yaw'], x_s_info['roll']) + ############################################ + + # record global info for next time use + self.f_s_user = self.live_portrait_wrapper.extract_feature_3d(I_s) + self.x_s_user = self.live_portrait_wrapper.transform_keypoint(x_s_info) + self.x_s_info_user = x_s_info + self.source_lmk_user = crop_info['lmk_crop'] + self.img_rgb = img_rgb + self.crop_M_c2o = crop_info['M_c2o'] + self.mask_ori = prepare_paste_back(inference_cfg.mask_crop, crop_info['M_c2o'], dsize=(img_rgb.shape[1], img_rgb.shape[0])) + # update slider + eye_close_ratio = calc_eye_close_ratio(self.source_lmk_user[None]) + eye_close_ratio = float(eye_close_ratio.squeeze(0).mean()) + lip_close_ratio = calc_lip_close_ratio(self.source_lmk_user[None]) + lip_close_ratio = float(lip_close_ratio.squeeze(0).mean()) + # for vis + self.I_s_vis = self.live_portrait_wrapper.parse_output(I_s)[0] + return eye_close_ratio, lip_close_ratio, self.I_s_vis + else: + # when press the clear button, go here + return 0.8, 0.8, self.I_s_vis diff --git a/liveportrait/live_portrait_pipeline.py b/liveportrait/live_portrait_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..76a27d1e8d984de2b14eafc0ce1fe0aab90ecf29 --- /dev/null +++ b/liveportrait/live_portrait_pipeline.py @@ -0,0 +1,193 @@ +# coding: utf-8 + +""" +Pipeline of LivePortrait +""" + +# TODO: +# 1. 当前假定所有的模板都是已经裁好的,需要修改下 +# 2. pick样例图 source + driving + +import cv2 +import numpy as np +import pickle +import os.path as osp +from rich.progress import track + +from .config.argument_config import ArgumentConfig +from .config.inference_config import InferenceConfig +from .config.crop_config import CropConfig +from .utils.cropper import Cropper +from .utils.camera import get_rotation_matrix +from .utils.video import images2video, concat_frames +from .utils.crop import _transform_img, prepare_paste_back, paste_back +from .utils.retargeting_utils import calc_lip_close_ratio +from .utils.io import load_image_rgb, load_driving_info, resize_to_limit +from .utils.helper import mkdir, basename, dct2cuda, is_video, is_template +from .utils.rprint import rlog as log +from .live_portrait_wrapper import LivePortraitWrapper + + +def make_abs_path(fn): + return osp.join(osp.dirname(osp.realpath(__file__)), fn) + + +class LivePortraitPipeline(object): + + def __init__(self, inference_cfg: InferenceConfig, crop_cfg: CropConfig): + self.live_portrait_wrapper: LivePortraitWrapper = LivePortraitWrapper(cfg=inference_cfg) + self.cropper = Cropper(crop_cfg=crop_cfg) + + def execute(self, args: ArgumentConfig): + inference_cfg = self.live_portrait_wrapper.cfg # for convenience + ######## process source portrait ######## + img_rgb = load_image_rgb(args.source_image) + img_rgb = resize_to_limit(img_rgb, inference_cfg.ref_max_shape, inference_cfg.ref_shape_n) + log(f"Load source image from {args.source_image}") + crop_info = self.cropper.crop_single_image(img_rgb) + source_lmk = crop_info['lmk_crop'] + img_crop, img_crop_256x256 = crop_info['img_crop'], crop_info['img_crop_256x256'] + if inference_cfg.flag_do_crop: + I_s = self.live_portrait_wrapper.prepare_source(img_crop_256x256) + else: + I_s = self.live_portrait_wrapper.prepare_source(img_rgb) + x_s_info = self.live_portrait_wrapper.get_kp_info(I_s) + x_c_s = x_s_info['kp'] + R_s = get_rotation_matrix(x_s_info['pitch'], x_s_info['yaw'], x_s_info['roll']) + f_s = self.live_portrait_wrapper.extract_feature_3d(I_s) + x_s = self.live_portrait_wrapper.transform_keypoint(x_s_info) + + if inference_cfg.flag_lip_zero: + # let lip-open scalar to be 0 at first + c_d_lip_before_animation = [0.] + combined_lip_ratio_tensor_before_animation = self.live_portrait_wrapper.calc_combined_lip_ratio(c_d_lip_before_animation, source_lmk) + if combined_lip_ratio_tensor_before_animation[0][0] < inference_cfg.lip_zero_threshold: + inference_cfg.flag_lip_zero = False + else: + lip_delta_before_animation = self.live_portrait_wrapper.retarget_lip(x_s, combined_lip_ratio_tensor_before_animation) + ############################################ + + ######## process driving info ######## + if is_video(args.driving_info): + log(f"Load from video file (mp4 mov avi etc...): {args.driving_info}") + # TODO: 这里track一下驱动视频 -> 构建模板 + driving_rgb_lst = load_driving_info(args.driving_info) + driving_rgb_lst_256 = [cv2.resize(_, (256, 256)) for _ in driving_rgb_lst] + I_d_lst = self.live_portrait_wrapper.prepare_driving_videos(driving_rgb_lst_256) + n_frames = I_d_lst.shape[0] + if inference_cfg.flag_eye_retargeting or inference_cfg.flag_lip_retargeting: + driving_lmk_lst = self.cropper.get_retargeting_lmk_info(driving_rgb_lst) + input_eye_ratio_lst, input_lip_ratio_lst = self.live_portrait_wrapper.calc_retargeting_ratio(source_lmk, driving_lmk_lst) + elif is_template(args.driving_info): + log(f"Load from video templates {args.driving_info}") + with open(args.driving_info, 'rb') as f: + template_lst, driving_lmk_lst = pickle.load(f) + n_frames = template_lst[0]['n_frames'] + input_eye_ratio_lst, input_lip_ratio_lst = self.live_portrait_wrapper.calc_retargeting_ratio(source_lmk, driving_lmk_lst) + else: + raise Exception("Unsupported driving types!") + ######################################### + + ######## prepare for pasteback ######## + if inference_cfg.flag_pasteback: + mask_ori = prepare_paste_back(inference_cfg.mask_crop, crop_info['M_c2o'], dsize=(img_rgb.shape[1], img_rgb.shape[0])) + I_p_paste_lst = [] + ######################################### + + I_p_lst = [] + R_d_0, x_d_0_info = None, None + for i in track(range(n_frames), description='Animating...', total=n_frames): + if is_video(args.driving_info): + # extract kp info by M + I_d_i = I_d_lst[i] + x_d_i_info = self.live_portrait_wrapper.get_kp_info(I_d_i) + R_d_i = get_rotation_matrix(x_d_i_info['pitch'], x_d_i_info['yaw'], x_d_i_info['roll']) + else: + # from template + x_d_i_info = template_lst[i] + x_d_i_info = dct2cuda(x_d_i_info, inference_cfg.device_id) + R_d_i = x_d_i_info['R_d'] + + if i == 0: + R_d_0 = R_d_i + x_d_0_info = x_d_i_info + + if inference_cfg.flag_relative: + R_new = (R_d_i @ R_d_0.permute(0, 2, 1)) @ R_s + delta_new = x_s_info['exp'] + (x_d_i_info['exp'] - x_d_0_info['exp']) + scale_new = x_s_info['scale'] * (x_d_i_info['scale'] / x_d_0_info['scale']) + t_new = x_s_info['t'] + (x_d_i_info['t'] - x_d_0_info['t']) + else: + R_new = R_d_i + delta_new = x_d_i_info['exp'] + scale_new = x_s_info['scale'] + t_new = x_d_i_info['t'] + + t_new[..., 2].fill_(0) # zero tz + x_d_i_new = scale_new * (x_c_s @ R_new + delta_new) + t_new + + # Algorithm 1: + if not inference_cfg.flag_stitching and not inference_cfg.flag_eye_retargeting and not inference_cfg.flag_lip_retargeting: + # without stitching or retargeting + if inference_cfg.flag_lip_zero: + x_d_i_new += lip_delta_before_animation.reshape(-1, x_s.shape[1], 3) + else: + pass + elif inference_cfg.flag_stitching and not inference_cfg.flag_eye_retargeting and not inference_cfg.flag_lip_retargeting: + # with stitching and without retargeting + if inference_cfg.flag_lip_zero: + x_d_i_new = self.live_portrait_wrapper.stitching(x_s, x_d_i_new) + lip_delta_before_animation.reshape(-1, x_s.shape[1], 3) + else: + x_d_i_new = self.live_portrait_wrapper.stitching(x_s, x_d_i_new) + else: + eyes_delta, lip_delta = None, None + if inference_cfg.flag_eye_retargeting: + c_d_eyes_i = input_eye_ratio_lst[i] + combined_eye_ratio_tensor = self.live_portrait_wrapper.calc_combined_eye_ratio(c_d_eyes_i, source_lmk) + # ∆_eyes,i = R_eyes(x_s; c_s,eyes, c_d,eyes,i) + eyes_delta = self.live_portrait_wrapper.retarget_eye(x_s, combined_eye_ratio_tensor) + if inference_cfg.flag_lip_retargeting: + c_d_lip_i = input_lip_ratio_lst[i] + combined_lip_ratio_tensor = self.live_portrait_wrapper.calc_combined_lip_ratio(c_d_lip_i, source_lmk) + # ∆_lip,i = R_lip(x_s; c_s,lip, c_d,lip,i) + lip_delta = self.live_portrait_wrapper.retarget_lip(x_s, combined_lip_ratio_tensor) + + if inference_cfg.flag_relative: # use x_s + x_d_i_new = x_s + \ + (eyes_delta.reshape(-1, x_s.shape[1], 3) if eyes_delta is not None else 0) + \ + (lip_delta.reshape(-1, x_s.shape[1], 3) if lip_delta is not None else 0) + else: # use x_d,i + x_d_i_new = x_d_i_new + \ + (eyes_delta.reshape(-1, x_s.shape[1], 3) if eyes_delta is not None else 0) + \ + (lip_delta.reshape(-1, x_s.shape[1], 3) if lip_delta is not None else 0) + + if inference_cfg.flag_stitching: + x_d_i_new = self.live_portrait_wrapper.stitching(x_s, x_d_i_new) + + out = self.live_portrait_wrapper.warp_decode(f_s, x_s, x_d_i_new) + I_p_i = self.live_portrait_wrapper.parse_output(out['out'])[0] + I_p_lst.append(I_p_i) + + if inference_cfg.flag_pasteback: + I_p_i_to_ori_blend = paste_back(I_p_i, crop_info['M_c2o'], img_rgb, mask_ori) + I_p_paste_lst.append(I_p_i_to_ori_blend) + + mkdir(args.output_dir) + wfp_concat = None + + # note by @jbilcke-hf: + # I have disabled this block, since we don't need to debug it + #if is_video(args.driving_info): + # frames_concatenated = concat_frames(I_p_lst, driving_rgb_lst, img_crop_256x256) + # # save (driving frames, source image, drived frames) result + # wfp_concat = osp.join(args.output_dir, f'{basename(args.source_image)}--{basename(args.driving_info)}_concat.mp4') + # images2video(frames_concatenated, wfp=wfp_concat)# + + # save drived result + wfp = osp.join(args.output_dir, f'{basename(args.source_image)}--{basename(args.driving_info)}.mp4') + if inference_cfg.flag_pasteback: + images2video(I_p_paste_lst, wfp=wfp) + else: + images2video(I_p_lst, wfp=wfp) + + return wfp, wfp_concat diff --git a/liveportrait/live_portrait_wrapper.py b/liveportrait/live_portrait_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..d96156c257f43a7e77a052af80ebb088a165db92 --- /dev/null +++ b/liveportrait/live_portrait_wrapper.py @@ -0,0 +1,307 @@ +# coding: utf-8 + +""" +Wrapper for LivePortrait core functions +""" + +import os.path as osp +import numpy as np +import cv2 +import torch +import yaml + +from .utils.timer import Timer +from .utils.helper import load_model, concat_feat +from .utils.camera import headpose_pred_to_degree, get_rotation_matrix +from .utils.retargeting_utils import calc_eye_close_ratio, calc_lip_close_ratio +from .config.inference_config import InferenceConfig +from .utils.rprint import rlog as log + + +class LivePortraitWrapper(object): + + def __init__(self, cfg: InferenceConfig): + + model_config = yaml.load(open(cfg.models_config, 'r'), Loader=yaml.SafeLoader) + + # init F + self.appearance_feature_extractor = load_model(cfg.checkpoint_F, model_config, cfg.device_id, 'appearance_feature_extractor') + #log(f'Load appearance_feature_extractor done.') + # init M + self.motion_extractor = load_model(cfg.checkpoint_M, model_config, cfg.device_id, 'motion_extractor') + #log(f'Load motion_extractor done.') + # init W + self.warping_module = load_model(cfg.checkpoint_W, model_config, cfg.device_id, 'warping_module') + #log(f'Load warping_module done.') + # init G + self.spade_generator = load_model(cfg.checkpoint_G, model_config, cfg.device_id, 'spade_generator') + #log(f'Load spade_generator done.') + # init S and R + if cfg.checkpoint_S is not None and osp.exists(cfg.checkpoint_S): + self.stitching_retargeting_module = load_model(cfg.checkpoint_S, model_config, cfg.device_id, 'stitching_retargeting_module') + #log(f'Load stitching_retargeting_module done.') + else: + self.stitching_retargeting_module = None + + self.cfg = cfg + self.device_id = cfg.device_id + self.timer = Timer() + + def update_config(self, user_args): + for k, v in user_args.items(): + if hasattr(self.cfg, k): + setattr(self.cfg, k, v) + + def prepare_source(self, img: np.ndarray) -> torch.Tensor: + """ construct the input as standard + img: HxWx3, uint8, 256x256 + """ + h, w = img.shape[:2] + if h != self.cfg.input_shape[0] or w != self.cfg.input_shape[1]: + x = cv2.resize(img, (self.cfg.input_shape[0], self.cfg.input_shape[1])) + else: + x = img.copy() + + if x.ndim == 3: + x = x[np.newaxis].astype(np.float32) / 255. # HxWx3 -> 1xHxWx3, normalized to 0~1 + elif x.ndim == 4: + x = x.astype(np.float32) / 255. # BxHxWx3, normalized to 0~1 + else: + raise ValueError(f'img ndim should be 3 or 4: {x.ndim}') + x = np.clip(x, 0, 1) # clip to 0~1 + x = torch.from_numpy(x).permute(0, 3, 1, 2) # 1xHxWx3 -> 1x3xHxW + x = x.cuda(self.device_id) + return x + + def prepare_driving_videos(self, imgs) -> torch.Tensor: + """ construct the input as standard + imgs: NxBxHxWx3, uint8 + """ + if isinstance(imgs, list): + _imgs = np.array(imgs)[..., np.newaxis] # TxHxWx3x1 + elif isinstance(imgs, np.ndarray): + _imgs = imgs + else: + raise ValueError(f'imgs type error: {type(imgs)}') + + y = _imgs.astype(np.float32) / 255. + y = np.clip(y, 0, 1) # clip to 0~1 + y = torch.from_numpy(y).permute(0, 4, 3, 1, 2) # TxHxWx3x1 -> Tx1x3xHxW + y = y.cuda(self.device_id) + + return y + + def extract_feature_3d(self, x: torch.Tensor) -> torch.Tensor: + """ get the appearance feature of the image by F + x: Bx3xHxW, normalized to 0~1 + """ + with torch.no_grad(): + with torch.autocast(device_type='cuda', dtype=torch.float16, enabled=self.cfg.flag_use_half_precision): + feature_3d = self.appearance_feature_extractor(x) + + return feature_3d.float() + + def get_kp_info(self, x: torch.Tensor, **kwargs) -> dict: + """ get the implicit keypoint information + x: Bx3xHxW, normalized to 0~1 + flag_refine_info: whether to trandform the pose to degrees and the dimention of the reshape + return: A dict contains keys: 'pitch', 'yaw', 'roll', 't', 'exp', 'scale', 'kp' + """ + with torch.no_grad(): + with torch.autocast(device_type='cuda', dtype=torch.float16, enabled=self.cfg.flag_use_half_precision): + kp_info = self.motion_extractor(x) + + if self.cfg.flag_use_half_precision: + # float the dict + for k, v in kp_info.items(): + if isinstance(v, torch.Tensor): + kp_info[k] = v.float() + + flag_refine_info: bool = kwargs.get('flag_refine_info', True) + if flag_refine_info: + bs = kp_info['kp'].shape[0] + kp_info['pitch'] = headpose_pred_to_degree(kp_info['pitch'])[:, None] # Bx1 + kp_info['yaw'] = headpose_pred_to_degree(kp_info['yaw'])[:, None] # Bx1 + kp_info['roll'] = headpose_pred_to_degree(kp_info['roll'])[:, None] # Bx1 + kp_info['kp'] = kp_info['kp'].reshape(bs, -1, 3) # BxNx3 + kp_info['exp'] = kp_info['exp'].reshape(bs, -1, 3) # BxNx3 + + return kp_info + + def get_pose_dct(self, kp_info: dict) -> dict: + pose_dct = dict( + pitch=headpose_pred_to_degree(kp_info['pitch']).item(), + yaw=headpose_pred_to_degree(kp_info['yaw']).item(), + roll=headpose_pred_to_degree(kp_info['roll']).item(), + ) + return pose_dct + + def get_fs_and_kp_info(self, source_prepared, driving_first_frame): + + # get the canonical keypoints of source image by M + source_kp_info = self.get_kp_info(source_prepared, flag_refine_info=True) + source_rotation = get_rotation_matrix(source_kp_info['pitch'], source_kp_info['yaw'], source_kp_info['roll']) + + # get the canonical keypoints of first driving frame by M + driving_first_frame_kp_info = self.get_kp_info(driving_first_frame, flag_refine_info=True) + driving_first_frame_rotation = get_rotation_matrix( + driving_first_frame_kp_info['pitch'], + driving_first_frame_kp_info['yaw'], + driving_first_frame_kp_info['roll'] + ) + + # get feature volume by F + source_feature_3d = self.extract_feature_3d(source_prepared) + + return source_kp_info, source_rotation, source_feature_3d, driving_first_frame_kp_info, driving_first_frame_rotation + + def transform_keypoint(self, kp_info: dict): + """ + transform the implicit keypoints with the pose, shift, and expression deformation + kp: BxNx3 + """ + kp = kp_info['kp'] # (bs, k, 3) + pitch, yaw, roll = kp_info['pitch'], kp_info['yaw'], kp_info['roll'] + + t, exp = kp_info['t'], kp_info['exp'] + scale = kp_info['scale'] + + pitch = headpose_pred_to_degree(pitch) + yaw = headpose_pred_to_degree(yaw) + roll = headpose_pred_to_degree(roll) + + bs = kp.shape[0] + if kp.ndim == 2: + num_kp = kp.shape[1] // 3 # Bx(num_kpx3) + else: + num_kp = kp.shape[1] # Bxnum_kpx3 + + rot_mat = get_rotation_matrix(pitch, yaw, roll) # (bs, 3, 3) + + # Eqn.2: s * (R * x_c,s + exp) + t + kp_transformed = kp.view(bs, num_kp, 3) @ rot_mat + exp.view(bs, num_kp, 3) + kp_transformed *= scale[..., None] # (bs, k, 3) * (bs, 1, 1) = (bs, k, 3) + kp_transformed[:, :, 0:2] += t[:, None, 0:2] # remove z, only apply tx ty + + return kp_transformed + + def retarget_eye(self, kp_source: torch.Tensor, eye_close_ratio: torch.Tensor) -> torch.Tensor: + """ + kp_source: BxNx3 + eye_close_ratio: Bx3 + Return: Bx(3*num_kp+2) + """ + feat_eye = concat_feat(kp_source, eye_close_ratio) + + with torch.no_grad(): + delta = self.stitching_retargeting_module['eye'](feat_eye) + + return delta + + def retarget_lip(self, kp_source: torch.Tensor, lip_close_ratio: torch.Tensor) -> torch.Tensor: + """ + kp_source: BxNx3 + lip_close_ratio: Bx2 + """ + feat_lip = concat_feat(kp_source, lip_close_ratio) + + with torch.no_grad(): + delta = self.stitching_retargeting_module['lip'](feat_lip) + + return delta + + def stitch(self, kp_source: torch.Tensor, kp_driving: torch.Tensor) -> torch.Tensor: + """ + kp_source: BxNx3 + kp_driving: BxNx3 + Return: Bx(3*num_kp+2) + """ + feat_stiching = concat_feat(kp_source, kp_driving) + + with torch.no_grad(): + delta = self.stitching_retargeting_module['stitching'](feat_stiching) + + return delta + + def stitching(self, kp_source: torch.Tensor, kp_driving: torch.Tensor) -> torch.Tensor: + """ conduct the stitching + kp_source: Bxnum_kpx3 + kp_driving: Bxnum_kpx3 + """ + + if self.stitching_retargeting_module is not None: + + bs, num_kp = kp_source.shape[:2] + + kp_driving_new = kp_driving.clone() + delta = self.stitch(kp_source, kp_driving_new) + + delta_exp = delta[..., :3*num_kp].reshape(bs, num_kp, 3) # 1x20x3 + delta_tx_ty = delta[..., 3*num_kp:3*num_kp+2].reshape(bs, 1, 2) # 1x1x2 + + kp_driving_new += delta_exp + kp_driving_new[..., :2] += delta_tx_ty + + return kp_driving_new + + return kp_driving + + def warp_decode(self, feature_3d: torch.Tensor, kp_source: torch.Tensor, kp_driving: torch.Tensor) -> torch.Tensor: + """ get the image after the warping of the implicit keypoints + feature_3d: Bx32x16x64x64, feature volume + kp_source: BxNx3 + kp_driving: BxNx3 + """ + # The line 18 in Algorithm 1: D(W(f_s; x_s, x′_d,i)) + with torch.no_grad(): + with torch.autocast(device_type='cuda', dtype=torch.float16, enabled=self.cfg.flag_use_half_precision): + # get decoder input + ret_dct = self.warping_module(feature_3d, kp_source=kp_source, kp_driving=kp_driving) + # decode + ret_dct['out'] = self.spade_generator(feature=ret_dct['out']) + + # float the dict + if self.cfg.flag_use_half_precision: + for k, v in ret_dct.items(): + if isinstance(v, torch.Tensor): + ret_dct[k] = v.float() + + return ret_dct + + def parse_output(self, out: torch.Tensor) -> np.ndarray: + """ construct the output as standard + return: 1xHxWx3, uint8 + """ + out = np.transpose(out.data.cpu().numpy(), [0, 2, 3, 1]) # 1x3xHxW -> 1xHxWx3 + out = np.clip(out, 0, 1) # clip to 0~1 + out = np.clip(out * 255, 0, 255).astype(np.uint8) # 0~1 -> 0~255 + + return out + + def calc_retargeting_ratio(self, source_lmk, driving_lmk_lst): + input_eye_ratio_lst = [] + input_lip_ratio_lst = [] + for lmk in driving_lmk_lst: + # for eyes retargeting + input_eye_ratio_lst.append(calc_eye_close_ratio(lmk[None])) + # for lip retargeting + input_lip_ratio_lst.append(calc_lip_close_ratio(lmk[None])) + return input_eye_ratio_lst, input_lip_ratio_lst + + def calc_combined_eye_ratio(self, input_eye_ratio, source_lmk): + eye_close_ratio = calc_eye_close_ratio(source_lmk[None]) + eye_close_ratio_tensor = torch.from_numpy(eye_close_ratio).float().cuda(self.device_id) + input_eye_ratio_tensor = torch.Tensor([input_eye_ratio[0][0]]).reshape(1, 1).cuda(self.device_id) + # [c_s,eyes, c_d,eyes,i] + combined_eye_ratio_tensor = torch.cat([eye_close_ratio_tensor, input_eye_ratio_tensor], dim=1) + return combined_eye_ratio_tensor + + def calc_combined_lip_ratio(self, input_lip_ratio, source_lmk): + lip_close_ratio = calc_lip_close_ratio(source_lmk[None]) + lip_close_ratio_tensor = torch.from_numpy(lip_close_ratio).float().cuda(self.device_id) + # [c_s,lip, c_d,lip,i] + input_lip_ratio_tensor = torch.Tensor([input_lip_ratio[0]]).cuda(self.device_id) + if input_lip_ratio_tensor.shape != [1, 1]: + input_lip_ratio_tensor = input_lip_ratio_tensor.reshape(1, 1) + combined_lip_ratio_tensor = torch.cat([lip_close_ratio_tensor, input_lip_ratio_tensor], dim=1) + return combined_lip_ratio_tensor diff --git a/liveportrait/modules/__init__.py b/liveportrait/modules/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/liveportrait/modules/appearance_feature_extractor.py b/liveportrait/modules/appearance_feature_extractor.py new file mode 100644 index 0000000000000000000000000000000000000000..8d89e4f18a2fbe58447f52ab4c5e3f2011a4ec80 --- /dev/null +++ b/liveportrait/modules/appearance_feature_extractor.py @@ -0,0 +1,48 @@ +# coding: utf-8 + +""" +Appearance extractor(F) defined in paper, which maps the source image s to a 3D appearance feature volume. +""" + +import torch +from torch import nn +from .util import SameBlock2d, DownBlock2d, ResBlock3d + + +class AppearanceFeatureExtractor(nn.Module): + + def __init__(self, image_channel, block_expansion, num_down_blocks, max_features, reshape_channel, reshape_depth, num_resblocks): + super(AppearanceFeatureExtractor, self).__init__() + self.image_channel = image_channel + self.block_expansion = block_expansion + self.num_down_blocks = num_down_blocks + self.max_features = max_features + self.reshape_channel = reshape_channel + self.reshape_depth = reshape_depth + + self.first = SameBlock2d(image_channel, block_expansion, kernel_size=(3, 3), padding=(1, 1)) + + down_blocks = [] + for i in range(num_down_blocks): + in_features = min(max_features, block_expansion * (2 ** i)) + out_features = min(max_features, block_expansion * (2 ** (i + 1))) + down_blocks.append(DownBlock2d(in_features, out_features, kernel_size=(3, 3), padding=(1, 1))) + self.down_blocks = nn.ModuleList(down_blocks) + + self.second = nn.Conv2d(in_channels=out_features, out_channels=max_features, kernel_size=1, stride=1) + + self.resblocks_3d = torch.nn.Sequential() + for i in range(num_resblocks): + self.resblocks_3d.add_module('3dr' + str(i), ResBlock3d(reshape_channel, kernel_size=3, padding=1)) + + def forward(self, source_image): + out = self.first(source_image) # Bx3x256x256 -> Bx64x256x256 + + for i in range(len(self.down_blocks)): + out = self.down_blocks[i](out) + out = self.second(out) + bs, c, h, w = out.shape # ->Bx512x64x64 + + f_s = out.view(bs, self.reshape_channel, self.reshape_depth, h, w) # ->Bx32x16x64x64 + f_s = self.resblocks_3d(f_s) # ->Bx32x16x64x64 + return f_s diff --git a/liveportrait/modules/convnextv2.py b/liveportrait/modules/convnextv2.py new file mode 100644 index 0000000000000000000000000000000000000000..83ea12662b607854915df8c7abb160b588d330b1 --- /dev/null +++ b/liveportrait/modules/convnextv2.py @@ -0,0 +1,149 @@ +# coding: utf-8 + +""" +This moudle is adapted to the ConvNeXtV2 version for the extraction of implicit keypoints, poses, and expression deformation. +""" + +import torch +import torch.nn as nn +# from timm.models.layers import trunc_normal_, DropPath +from .util import LayerNorm, DropPath, trunc_normal_, GRN + +__all__ = ['convnextv2_tiny'] + + +class Block(nn.Module): + """ ConvNeXtV2 Block. + + Args: + dim (int): Number of input channels. + drop_path (float): Stochastic depth rate. Default: 0.0 + """ + + def __init__(self, dim, drop_path=0.): + super().__init__() + self.dwconv = nn.Conv2d(dim, dim, kernel_size=7, padding=3, groups=dim) # depthwise conv + self.norm = LayerNorm(dim, eps=1e-6) + self.pwconv1 = nn.Linear(dim, 4 * dim) # pointwise/1x1 convs, implemented with linear layers + self.act = nn.GELU() + self.grn = GRN(4 * dim) + self.pwconv2 = nn.Linear(4 * dim, dim) + self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() + + def forward(self, x): + input = x + x = self.dwconv(x) + x = x.permute(0, 2, 3, 1) # (N, C, H, W) -> (N, H, W, C) + x = self.norm(x) + x = self.pwconv1(x) + x = self.act(x) + x = self.grn(x) + x = self.pwconv2(x) + x = x.permute(0, 3, 1, 2) # (N, H, W, C) -> (N, C, H, W) + + x = input + self.drop_path(x) + return x + + +class ConvNeXtV2(nn.Module): + """ ConvNeXt V2 + + Args: + in_chans (int): Number of input image channels. Default: 3 + num_classes (int): Number of classes for classification head. Default: 1000 + depths (tuple(int)): Number of blocks at each stage. Default: [3, 3, 9, 3] + dims (int): Feature dimension at each stage. Default: [96, 192, 384, 768] + drop_path_rate (float): Stochastic depth rate. Default: 0. + head_init_scale (float): Init scaling value for classifier weights and biases. Default: 1. + """ + + def __init__( + self, + in_chans=3, + depths=[3, 3, 9, 3], + dims=[96, 192, 384, 768], + drop_path_rate=0., + **kwargs + ): + super().__init__() + self.depths = depths + self.downsample_layers = nn.ModuleList() # stem and 3 intermediate downsampling conv layers + stem = nn.Sequential( + nn.Conv2d(in_chans, dims[0], kernel_size=4, stride=4), + LayerNorm(dims[0], eps=1e-6, data_format="channels_first") + ) + self.downsample_layers.append(stem) + for i in range(3): + downsample_layer = nn.Sequential( + LayerNorm(dims[i], eps=1e-6, data_format="channels_first"), + nn.Conv2d(dims[i], dims[i+1], kernel_size=2, stride=2), + ) + self.downsample_layers.append(downsample_layer) + + self.stages = nn.ModuleList() # 4 feature resolution stages, each consisting of multiple residual blocks + dp_rates = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] + cur = 0 + for i in range(4): + stage = nn.Sequential( + *[Block(dim=dims[i], drop_path=dp_rates[cur + j]) for j in range(depths[i])] + ) + self.stages.append(stage) + cur += depths[i] + + self.norm = nn.LayerNorm(dims[-1], eps=1e-6) # final norm layer + + # NOTE: the output semantic items + num_bins = kwargs.get('num_bins', 66) + num_kp = kwargs.get('num_kp', 24) # the number of implicit keypoints + self.fc_kp = nn.Linear(dims[-1], 3 * num_kp) # implicit keypoints + + # print('dims[-1]: ', dims[-1]) + self.fc_scale = nn.Linear(dims[-1], 1) # scale + self.fc_pitch = nn.Linear(dims[-1], num_bins) # pitch bins + self.fc_yaw = nn.Linear(dims[-1], num_bins) # yaw bins + self.fc_roll = nn.Linear(dims[-1], num_bins) # roll bins + self.fc_t = nn.Linear(dims[-1], 3) # translation + self.fc_exp = nn.Linear(dims[-1], 3 * num_kp) # expression / delta + + def _init_weights(self, m): + if isinstance(m, (nn.Conv2d, nn.Linear)): + trunc_normal_(m.weight, std=.02) + nn.init.constant_(m.bias, 0) + + def forward_features(self, x): + for i in range(4): + x = self.downsample_layers[i](x) + x = self.stages[i](x) + return self.norm(x.mean([-2, -1])) # global average pooling, (N, C, H, W) -> (N, C) + + def forward(self, x): + x = self.forward_features(x) + + # implicit keypoints + kp = self.fc_kp(x) + + # pose and expression deformation + pitch = self.fc_pitch(x) + yaw = self.fc_yaw(x) + roll = self.fc_roll(x) + t = self.fc_t(x) + exp = self.fc_exp(x) + scale = self.fc_scale(x) + + ret_dct = { + 'pitch': pitch, + 'yaw': yaw, + 'roll': roll, + 't': t, + 'exp': exp, + 'scale': scale, + + 'kp': kp, # canonical keypoint + } + + return ret_dct + + +def convnextv2_tiny(**kwargs): + model = ConvNeXtV2(depths=[3, 3, 9, 3], dims=[96, 192, 384, 768], **kwargs) + return model diff --git a/liveportrait/modules/dense_motion.py b/liveportrait/modules/dense_motion.py new file mode 100644 index 0000000000000000000000000000000000000000..0eec0c46345f8854b125a51eaee730bd4ee77f7d --- /dev/null +++ b/liveportrait/modules/dense_motion.py @@ -0,0 +1,104 @@ +# coding: utf-8 + +""" +The module that predicting a dense motion from sparse motion representation given by kp_source and kp_driving +""" + +from torch import nn +import torch.nn.functional as F +import torch +from .util import Hourglass, make_coordinate_grid, kp2gaussian + + +class DenseMotionNetwork(nn.Module): + def __init__(self, block_expansion, num_blocks, max_features, num_kp, feature_channel, reshape_depth, compress, estimate_occlusion_map=True): + super(DenseMotionNetwork, self).__init__() + self.hourglass = Hourglass(block_expansion=block_expansion, in_features=(num_kp+1)*(compress+1), max_features=max_features, num_blocks=num_blocks) # ~60+G + + self.mask = nn.Conv3d(self.hourglass.out_filters, num_kp + 1, kernel_size=7, padding=3) # 65G! NOTE: computation cost is large + self.compress = nn.Conv3d(feature_channel, compress, kernel_size=1) # 0.8G + self.norm = nn.BatchNorm3d(compress, affine=True) + self.num_kp = num_kp + self.flag_estimate_occlusion_map = estimate_occlusion_map + + if self.flag_estimate_occlusion_map: + self.occlusion = nn.Conv2d(self.hourglass.out_filters*reshape_depth, 1, kernel_size=7, padding=3) + else: + self.occlusion = None + + def create_sparse_motions(self, feature, kp_driving, kp_source): + bs, _, d, h, w = feature.shape # (bs, 4, 16, 64, 64) + identity_grid = make_coordinate_grid((d, h, w), ref=kp_source) # (16, 64, 64, 3) + identity_grid = identity_grid.view(1, 1, d, h, w, 3) # (1, 1, d=16, h=64, w=64, 3) + coordinate_grid = identity_grid - kp_driving.view(bs, self.num_kp, 1, 1, 1, 3) + + k = coordinate_grid.shape[1] + + # NOTE: there lacks an one-order flow + driving_to_source = coordinate_grid + kp_source.view(bs, self.num_kp, 1, 1, 1, 3) # (bs, num_kp, d, h, w, 3) + + # adding background feature + identity_grid = identity_grid.repeat(bs, 1, 1, 1, 1, 1) + sparse_motions = torch.cat([identity_grid, driving_to_source], dim=1) # (bs, 1+num_kp, d, h, w, 3) + return sparse_motions + + def create_deformed_feature(self, feature, sparse_motions): + bs, _, d, h, w = feature.shape + feature_repeat = feature.unsqueeze(1).unsqueeze(1).repeat(1, self.num_kp+1, 1, 1, 1, 1, 1) # (bs, num_kp+1, 1, c, d, h, w) + feature_repeat = feature_repeat.view(bs * (self.num_kp+1), -1, d, h, w) # (bs*(num_kp+1), c, d, h, w) + sparse_motions = sparse_motions.view((bs * (self.num_kp+1), d, h, w, -1)) # (bs*(num_kp+1), d, h, w, 3) + sparse_deformed = F.grid_sample(feature_repeat, sparse_motions, align_corners=False) + sparse_deformed = sparse_deformed.view((bs, self.num_kp+1, -1, d, h, w)) # (bs, num_kp+1, c, d, h, w) + + return sparse_deformed + + def create_heatmap_representations(self, feature, kp_driving, kp_source): + spatial_size = feature.shape[3:] # (d=16, h=64, w=64) + gaussian_driving = kp2gaussian(kp_driving, spatial_size=spatial_size, kp_variance=0.01) # (bs, num_kp, d, h, w) + gaussian_source = kp2gaussian(kp_source, spatial_size=spatial_size, kp_variance=0.01) # (bs, num_kp, d, h, w) + heatmap = gaussian_driving - gaussian_source # (bs, num_kp, d, h, w) + + # adding background feature + zeros = torch.zeros(heatmap.shape[0], 1, spatial_size[0], spatial_size[1], spatial_size[2]).type(heatmap.type()).to(heatmap.device) + heatmap = torch.cat([zeros, heatmap], dim=1) + heatmap = heatmap.unsqueeze(2) # (bs, 1+num_kp, 1, d, h, w) + return heatmap + + def forward(self, feature, kp_driving, kp_source): + bs, _, d, h, w = feature.shape # (bs, 32, 16, 64, 64) + + feature = self.compress(feature) # (bs, 4, 16, 64, 64) + feature = self.norm(feature) # (bs, 4, 16, 64, 64) + feature = F.relu(feature) # (bs, 4, 16, 64, 64) + + out_dict = dict() + + # 1. deform 3d feature + sparse_motion = self.create_sparse_motions(feature, kp_driving, kp_source) # (bs, 1+num_kp, d, h, w, 3) + deformed_feature = self.create_deformed_feature(feature, sparse_motion) # (bs, 1+num_kp, c=4, d=16, h=64, w=64) + + # 2. (bs, 1+num_kp, d, h, w) + heatmap = self.create_heatmap_representations(deformed_feature, kp_driving, kp_source) # (bs, 1+num_kp, 1, d, h, w) + + input = torch.cat([heatmap, deformed_feature], dim=2) # (bs, 1+num_kp, c=5, d=16, h=64, w=64) + input = input.view(bs, -1, d, h, w) # (bs, (1+num_kp)*c=105, d=16, h=64, w=64) + + prediction = self.hourglass(input) + + mask = self.mask(prediction) + mask = F.softmax(mask, dim=1) # (bs, 1+num_kp, d=16, h=64, w=64) + out_dict['mask'] = mask + mask = mask.unsqueeze(2) # (bs, num_kp+1, 1, d, h, w) + sparse_motion = sparse_motion.permute(0, 1, 5, 2, 3, 4) # (bs, num_kp+1, 3, d, h, w) + deformation = (sparse_motion * mask).sum(dim=1) # (bs, 3, d, h, w) mask take effect in this place + deformation = deformation.permute(0, 2, 3, 4, 1) # (bs, d, h, w, 3) + + out_dict['deformation'] = deformation + + if self.flag_estimate_occlusion_map: + bs, _, d, h, w = prediction.shape + prediction_reshape = prediction.view(bs, -1, h, w) + occlusion_map = torch.sigmoid(self.occlusion(prediction_reshape)) # Bx1x64x64 + out_dict['occlusion_map'] = occlusion_map + + return out_dict diff --git a/liveportrait/modules/motion_extractor.py b/liveportrait/modules/motion_extractor.py new file mode 100644 index 0000000000000000000000000000000000000000..b2982e53c52d9ec1e0bec0453cc05edb51a15d23 --- /dev/null +++ b/liveportrait/modules/motion_extractor.py @@ -0,0 +1,35 @@ +# coding: utf-8 + +""" +Motion extractor(M), which directly predicts the canonical keypoints, head pose and expression deformation of the input image +""" + +from torch import nn +import torch + +from .convnextv2 import convnextv2_tiny +from .util import filter_state_dict + +model_dict = { + 'convnextv2_tiny': convnextv2_tiny, +} + + +class MotionExtractor(nn.Module): + def __init__(self, **kwargs): + super(MotionExtractor, self).__init__() + + # default is convnextv2_base + backbone = kwargs.get('backbone', 'convnextv2_tiny') + self.detector = model_dict.get(backbone)(**kwargs) + + def load_pretrained(self, init_path: str): + if init_path not in (None, ''): + state_dict = torch.load(init_path, map_location=lambda storage, loc: storage)['model'] + state_dict = filter_state_dict(state_dict, remove_name='head') + ret = self.detector.load_state_dict(state_dict, strict=False) + print(f'Load pretrained model from {init_path}, ret: {ret}') + + def forward(self, x): + out = self.detector(x) + return out diff --git a/liveportrait/modules/spade_generator.py b/liveportrait/modules/spade_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..147a9aed0c7707fe6ae3d59ce1a30154ef75afcc --- /dev/null +++ b/liveportrait/modules/spade_generator.py @@ -0,0 +1,59 @@ +# coding: utf-8 + +""" +Spade decoder(G) defined in the paper, which input the warped feature to generate the animated image. +""" + +import torch +from torch import nn +import torch.nn.functional as F +from .util import SPADEResnetBlock + + +class SPADEDecoder(nn.Module): + def __init__(self, upscale=1, max_features=256, block_expansion=64, out_channels=64, num_down_blocks=2): + for i in range(num_down_blocks): + input_channels = min(max_features, block_expansion * (2 ** (i + 1))) + self.upscale = upscale + super().__init__() + norm_G = 'spadespectralinstance' + label_num_channels = input_channels # 256 + + self.fc = nn.Conv2d(input_channels, 2 * input_channels, 3, padding=1) + self.G_middle_0 = SPADEResnetBlock(2 * input_channels, 2 * input_channels, norm_G, label_num_channels) + self.G_middle_1 = SPADEResnetBlock(2 * input_channels, 2 * input_channels, norm_G, label_num_channels) + self.G_middle_2 = SPADEResnetBlock(2 * input_channels, 2 * input_channels, norm_G, label_num_channels) + self.G_middle_3 = SPADEResnetBlock(2 * input_channels, 2 * input_channels, norm_G, label_num_channels) + self.G_middle_4 = SPADEResnetBlock(2 * input_channels, 2 * input_channels, norm_G, label_num_channels) + self.G_middle_5 = SPADEResnetBlock(2 * input_channels, 2 * input_channels, norm_G, label_num_channels) + self.up_0 = SPADEResnetBlock(2 * input_channels, input_channels, norm_G, label_num_channels) + self.up_1 = SPADEResnetBlock(input_channels, out_channels, norm_G, label_num_channels) + self.up = nn.Upsample(scale_factor=2) + + if self.upscale is None or self.upscale <= 1: + self.conv_img = nn.Conv2d(out_channels, 3, 3, padding=1) + else: + self.conv_img = nn.Sequential( + nn.Conv2d(out_channels, 3 * (2 * 2), kernel_size=3, padding=1), + nn.PixelShuffle(upscale_factor=2) + ) + + def forward(self, feature): + seg = feature # Bx256x64x64 + x = self.fc(feature) # Bx512x64x64 + x = self.G_middle_0(x, seg) + x = self.G_middle_1(x, seg) + x = self.G_middle_2(x, seg) + x = self.G_middle_3(x, seg) + x = self.G_middle_4(x, seg) + x = self.G_middle_5(x, seg) + + x = self.up(x) # Bx512x64x64 -> Bx512x128x128 + x = self.up_0(x, seg) # Bx512x128x128 -> Bx256x128x128 + x = self.up(x) # Bx256x128x128 -> Bx256x256x256 + x = self.up_1(x, seg) # Bx256x256x256 -> Bx64x256x256 + + x = self.conv_img(F.leaky_relu(x, 2e-1)) # Bx64x256x256 -> Bx3xHxW + x = torch.sigmoid(x) # Bx3xHxW + + return x \ No newline at end of file diff --git a/liveportrait/modules/stitching_retargeting_network.py b/liveportrait/modules/stitching_retargeting_network.py new file mode 100644 index 0000000000000000000000000000000000000000..5f50b7cf5a21cd71c70a7bbaaa4b6b68b4762ea3 --- /dev/null +++ b/liveportrait/modules/stitching_retargeting_network.py @@ -0,0 +1,38 @@ +# coding: utf-8 + +""" +Stitching module(S) and two retargeting modules(R) defined in the paper. + +- The stitching module pastes the animated portrait back into the original image space without pixel misalignment, such as in +the stitching region. + +- The eyes retargeting module is designed to address the issue of incomplete eye closure during cross-id reenactment, especially +when a person with small eyes drives a person with larger eyes. + +- The lip retargeting module is designed similarly to the eye retargeting module, and can also normalize the input by ensuring that +the lips are in a closed state, which facilitates better animation driving. +""" +from torch import nn + + +class StitchingRetargetingNetwork(nn.Module): + def __init__(self, input_size, hidden_sizes, output_size): + super(StitchingRetargetingNetwork, self).__init__() + layers = [] + for i in range(len(hidden_sizes)): + if i == 0: + layers.append(nn.Linear(input_size, hidden_sizes[i])) + else: + layers.append(nn.Linear(hidden_sizes[i - 1], hidden_sizes[i])) + layers.append(nn.ReLU(inplace=True)) + layers.append(nn.Linear(hidden_sizes[-1], output_size)) + self.mlp = nn.Sequential(*layers) + + def initialize_weights_to_zero(self): + for m in self.modules(): + if isinstance(m, nn.Linear): + nn.init.zeros_(m.weight) + nn.init.zeros_(m.bias) + + def forward(self, x): + return self.mlp(x) diff --git a/liveportrait/modules/util.py b/liveportrait/modules/util.py new file mode 100644 index 0000000000000000000000000000000000000000..f83980b24372bee38779ceeb3349fca91735e56e --- /dev/null +++ b/liveportrait/modules/util.py @@ -0,0 +1,441 @@ +# coding: utf-8 + +""" +This file defines various neural network modules and utility functions, including convolutional and residual blocks, +normalizations, and functions for spatial transformation and tensor manipulation. +""" + +from torch import nn +import torch.nn.functional as F +import torch +import torch.nn.utils.spectral_norm as spectral_norm +import math +import warnings + + +def kp2gaussian(kp, spatial_size, kp_variance): + """ + Transform a keypoint into gaussian like representation + """ + mean = kp + + coordinate_grid = make_coordinate_grid(spatial_size, mean) + number_of_leading_dimensions = len(mean.shape) - 1 + shape = (1,) * number_of_leading_dimensions + coordinate_grid.shape + coordinate_grid = coordinate_grid.view(*shape) + repeats = mean.shape[:number_of_leading_dimensions] + (1, 1, 1, 1) + coordinate_grid = coordinate_grid.repeat(*repeats) + + # Preprocess kp shape + shape = mean.shape[:number_of_leading_dimensions] + (1, 1, 1, 3) + mean = mean.view(*shape) + + mean_sub = (coordinate_grid - mean) + + out = torch.exp(-0.5 * (mean_sub ** 2).sum(-1) / kp_variance) + + return out + + +def make_coordinate_grid(spatial_size, ref, **kwargs): + d, h, w = spatial_size + x = torch.arange(w).type(ref.dtype).to(ref.device) + y = torch.arange(h).type(ref.dtype).to(ref.device) + z = torch.arange(d).type(ref.dtype).to(ref.device) + + # NOTE: must be right-down-in + x = (2 * (x / (w - 1)) - 1) # the x axis faces to the right + y = (2 * (y / (h - 1)) - 1) # the y axis faces to the bottom + z = (2 * (z / (d - 1)) - 1) # the z axis faces to the inner + + yy = y.view(1, -1, 1).repeat(d, 1, w) + xx = x.view(1, 1, -1).repeat(d, h, 1) + zz = z.view(-1, 1, 1).repeat(1, h, w) + + meshed = torch.cat([xx.unsqueeze_(3), yy.unsqueeze_(3), zz.unsqueeze_(3)], 3) + + return meshed + + +class ConvT2d(nn.Module): + """ + Upsampling block for use in decoder. + """ + + def __init__(self, in_features, out_features, kernel_size=3, stride=2, padding=1, output_padding=1): + super(ConvT2d, self).__init__() + + self.convT = nn.ConvTranspose2d(in_features, out_features, kernel_size=kernel_size, stride=stride, + padding=padding, output_padding=output_padding) + self.norm = nn.InstanceNorm2d(out_features) + + def forward(self, x): + out = self.convT(x) + out = self.norm(out) + out = F.leaky_relu(out) + return out + + +class ResBlock3d(nn.Module): + """ + Res block, preserve spatial resolution. + """ + + def __init__(self, in_features, kernel_size, padding): + super(ResBlock3d, self).__init__() + self.conv1 = nn.Conv3d(in_channels=in_features, out_channels=in_features, kernel_size=kernel_size, padding=padding) + self.conv2 = nn.Conv3d(in_channels=in_features, out_channels=in_features, kernel_size=kernel_size, padding=padding) + self.norm1 = nn.BatchNorm3d(in_features, affine=True) + self.norm2 = nn.BatchNorm3d(in_features, affine=True) + + def forward(self, x): + out = self.norm1(x) + out = F.relu(out) + out = self.conv1(out) + out = self.norm2(out) + out = F.relu(out) + out = self.conv2(out) + out += x + return out + + +class UpBlock3d(nn.Module): + """ + Upsampling block for use in decoder. + """ + + def __init__(self, in_features, out_features, kernel_size=3, padding=1, groups=1): + super(UpBlock3d, self).__init__() + + self.conv = nn.Conv3d(in_channels=in_features, out_channels=out_features, kernel_size=kernel_size, + padding=padding, groups=groups) + self.norm = nn.BatchNorm3d(out_features, affine=True) + + def forward(self, x): + out = F.interpolate(x, scale_factor=(1, 2, 2)) + out = self.conv(out) + out = self.norm(out) + out = F.relu(out) + return out + + +class DownBlock2d(nn.Module): + """ + Downsampling block for use in encoder. + """ + + def __init__(self, in_features, out_features, kernel_size=3, padding=1, groups=1): + super(DownBlock2d, self).__init__() + self.conv = nn.Conv2d(in_channels=in_features, out_channels=out_features, kernel_size=kernel_size, padding=padding, groups=groups) + self.norm = nn.BatchNorm2d(out_features, affine=True) + self.pool = nn.AvgPool2d(kernel_size=(2, 2)) + + def forward(self, x): + out = self.conv(x) + out = self.norm(out) + out = F.relu(out) + out = self.pool(out) + return out + + +class DownBlock3d(nn.Module): + """ + Downsampling block for use in encoder. + """ + + def __init__(self, in_features, out_features, kernel_size=3, padding=1, groups=1): + super(DownBlock3d, self).__init__() + ''' + self.conv = nn.Conv3d(in_channels=in_features, out_channels=out_features, kernel_size=kernel_size, + padding=padding, groups=groups, stride=(1, 2, 2)) + ''' + self.conv = nn.Conv3d(in_channels=in_features, out_channels=out_features, kernel_size=kernel_size, + padding=padding, groups=groups) + self.norm = nn.BatchNorm3d(out_features, affine=True) + self.pool = nn.AvgPool3d(kernel_size=(1, 2, 2)) + + def forward(self, x): + out = self.conv(x) + out = self.norm(out) + out = F.relu(out) + out = self.pool(out) + return out + + +class SameBlock2d(nn.Module): + """ + Simple block, preserve spatial resolution. + """ + + def __init__(self, in_features, out_features, groups=1, kernel_size=3, padding=1, lrelu=False): + super(SameBlock2d, self).__init__() + self.conv = nn.Conv2d(in_channels=in_features, out_channels=out_features, kernel_size=kernel_size, padding=padding, groups=groups) + self.norm = nn.BatchNorm2d(out_features, affine=True) + if lrelu: + self.ac = nn.LeakyReLU() + else: + self.ac = nn.ReLU() + + def forward(self, x): + out = self.conv(x) + out = self.norm(out) + out = self.ac(out) + return out + + +class Encoder(nn.Module): + """ + Hourglass Encoder + """ + + def __init__(self, block_expansion, in_features, num_blocks=3, max_features=256): + super(Encoder, self).__init__() + + down_blocks = [] + for i in range(num_blocks): + down_blocks.append(DownBlock3d(in_features if i == 0 else min(max_features, block_expansion * (2 ** i)), min(max_features, block_expansion * (2 ** (i + 1))), kernel_size=3, padding=1)) + self.down_blocks = nn.ModuleList(down_blocks) + + def forward(self, x): + outs = [x] + for down_block in self.down_blocks: + outs.append(down_block(outs[-1])) + return outs + + +class Decoder(nn.Module): + """ + Hourglass Decoder + """ + + def __init__(self, block_expansion, in_features, num_blocks=3, max_features=256): + super(Decoder, self).__init__() + + up_blocks = [] + + for i in range(num_blocks)[::-1]: + in_filters = (1 if i == num_blocks - 1 else 2) * min(max_features, block_expansion * (2 ** (i + 1))) + out_filters = min(max_features, block_expansion * (2 ** i)) + up_blocks.append(UpBlock3d(in_filters, out_filters, kernel_size=3, padding=1)) + + self.up_blocks = nn.ModuleList(up_blocks) + self.out_filters = block_expansion + in_features + + self.conv = nn.Conv3d(in_channels=self.out_filters, out_channels=self.out_filters, kernel_size=3, padding=1) + self.norm = nn.BatchNorm3d(self.out_filters, affine=True) + + def forward(self, x): + out = x.pop() + for up_block in self.up_blocks: + out = up_block(out) + skip = x.pop() + out = torch.cat([out, skip], dim=1) + out = self.conv(out) + out = self.norm(out) + out = F.relu(out) + return out + + +class Hourglass(nn.Module): + """ + Hourglass architecture. + """ + + def __init__(self, block_expansion, in_features, num_blocks=3, max_features=256): + super(Hourglass, self).__init__() + self.encoder = Encoder(block_expansion, in_features, num_blocks, max_features) + self.decoder = Decoder(block_expansion, in_features, num_blocks, max_features) + self.out_filters = self.decoder.out_filters + + def forward(self, x): + return self.decoder(self.encoder(x)) + + +class SPADE(nn.Module): + def __init__(self, norm_nc, label_nc): + super().__init__() + + self.param_free_norm = nn.InstanceNorm2d(norm_nc, affine=False) + nhidden = 128 + + self.mlp_shared = nn.Sequential( + nn.Conv2d(label_nc, nhidden, kernel_size=3, padding=1), + nn.ReLU()) + self.mlp_gamma = nn.Conv2d(nhidden, norm_nc, kernel_size=3, padding=1) + self.mlp_beta = nn.Conv2d(nhidden, norm_nc, kernel_size=3, padding=1) + + def forward(self, x, segmap): + normalized = self.param_free_norm(x) + segmap = F.interpolate(segmap, size=x.size()[2:], mode='nearest') + actv = self.mlp_shared(segmap) + gamma = self.mlp_gamma(actv) + beta = self.mlp_beta(actv) + out = normalized * (1 + gamma) + beta + return out + + +class SPADEResnetBlock(nn.Module): + def __init__(self, fin, fout, norm_G, label_nc, use_se=False, dilation=1): + super().__init__() + # Attributes + self.learned_shortcut = (fin != fout) + fmiddle = min(fin, fout) + self.use_se = use_se + # create conv layers + self.conv_0 = nn.Conv2d(fin, fmiddle, kernel_size=3, padding=dilation, dilation=dilation) + self.conv_1 = nn.Conv2d(fmiddle, fout, kernel_size=3, padding=dilation, dilation=dilation) + if self.learned_shortcut: + self.conv_s = nn.Conv2d(fin, fout, kernel_size=1, bias=False) + # apply spectral norm if specified + if 'spectral' in norm_G: + self.conv_0 = spectral_norm(self.conv_0) + self.conv_1 = spectral_norm(self.conv_1) + if self.learned_shortcut: + self.conv_s = spectral_norm(self.conv_s) + # define normalization layers + self.norm_0 = SPADE(fin, label_nc) + self.norm_1 = SPADE(fmiddle, label_nc) + if self.learned_shortcut: + self.norm_s = SPADE(fin, label_nc) + + def forward(self, x, seg1): + x_s = self.shortcut(x, seg1) + dx = self.conv_0(self.actvn(self.norm_0(x, seg1))) + dx = self.conv_1(self.actvn(self.norm_1(dx, seg1))) + out = x_s + dx + return out + + def shortcut(self, x, seg1): + if self.learned_shortcut: + x_s = self.conv_s(self.norm_s(x, seg1)) + else: + x_s = x + return x_s + + def actvn(self, x): + return F.leaky_relu(x, 2e-1) + + +def filter_state_dict(state_dict, remove_name='fc'): + new_state_dict = {} + for key in state_dict: + if remove_name in key: + continue + new_state_dict[key] = state_dict[key] + return new_state_dict + + +class GRN(nn.Module): + """ GRN (Global Response Normalization) layer + """ + + def __init__(self, dim): + super().__init__() + self.gamma = nn.Parameter(torch.zeros(1, 1, 1, dim)) + self.beta = nn.Parameter(torch.zeros(1, 1, 1, dim)) + + def forward(self, x): + Gx = torch.norm(x, p=2, dim=(1, 2), keepdim=True) + Nx = Gx / (Gx.mean(dim=-1, keepdim=True) + 1e-6) + return self.gamma * (x * Nx) + self.beta + x + + +class LayerNorm(nn.Module): + r""" LayerNorm that supports two data formats: channels_last (default) or channels_first. + The ordering of the dimensions in the inputs. channels_last corresponds to inputs with + shape (batch_size, height, width, channels) while channels_first corresponds to inputs + with shape (batch_size, channels, height, width). + """ + + def __init__(self, normalized_shape, eps=1e-6, data_format="channels_last"): + super().__init__() + self.weight = nn.Parameter(torch.ones(normalized_shape)) + self.bias = nn.Parameter(torch.zeros(normalized_shape)) + self.eps = eps + self.data_format = data_format + if self.data_format not in ["channels_last", "channels_first"]: + raise NotImplementedError + self.normalized_shape = (normalized_shape, ) + + def forward(self, x): + if self.data_format == "channels_last": + return F.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.eps) + elif self.data_format == "channels_first": + u = x.mean(1, keepdim=True) + s = (x - u).pow(2).mean(1, keepdim=True) + x = (x - u) / torch.sqrt(s + self.eps) + x = self.weight[:, None, None] * x + self.bias[:, None, None] + return x + + +def _no_grad_trunc_normal_(tensor, mean, std, a, b): + # Cut & paste from PyTorch official master until it's in a few official releases - RW + # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf + def norm_cdf(x): + # Computes standard normal cumulative distribution function + return (1. + math.erf(x / math.sqrt(2.))) / 2. + + if (mean < a - 2 * std) or (mean > b + 2 * std): + warnings.warn("mean is more than 2 std from [a, b] in nn.init.trunc_normal_. " + "The distribution of values may be incorrect.", + stacklevel=2) + + with torch.no_grad(): + # Values are generated by using a truncated uniform distribution and + # then using the inverse CDF for the normal distribution. + # Get upper and lower cdf values + l = norm_cdf((a - mean) / std) + u = norm_cdf((b - mean) / std) + + # Uniformly fill tensor with values from [l, u], then translate to + # [2l-1, 2u-1]. + tensor.uniform_(2 * l - 1, 2 * u - 1) + + # Use inverse cdf transform for normal distribution to get truncated + # standard normal + tensor.erfinv_() + + # Transform to proper mean, std + tensor.mul_(std * math.sqrt(2.)) + tensor.add_(mean) + + # Clamp to ensure it's in the proper range + tensor.clamp_(min=a, max=b) + return tensor + + +def drop_path(x, drop_prob=0., training=False, scale_by_keep=True): + """ Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). + + This is the same as the DropConnect impl I created for EfficientNet, etc networks, however, + the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper... + See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for + changing the layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use + 'survival rate' as the argument. + + """ + if drop_prob == 0. or not training: + return x + keep_prob = 1 - drop_prob + shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets + random_tensor = x.new_empty(shape).bernoulli_(keep_prob) + if keep_prob > 0.0 and scale_by_keep: + random_tensor.div_(keep_prob) + return x * random_tensor + + +class DropPath(nn.Module): + """ Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). + """ + + def __init__(self, drop_prob=None, scale_by_keep=True): + super(DropPath, self).__init__() + self.drop_prob = drop_prob + self.scale_by_keep = scale_by_keep + + def forward(self, x): + return drop_path(x, self.drop_prob, self.training, self.scale_by_keep) + + +def trunc_normal_(tensor, mean=0., std=1., a=-2., b=2.): + return _no_grad_trunc_normal_(tensor, mean, std, a, b) diff --git a/liveportrait/modules/warping_network.py b/liveportrait/modules/warping_network.py new file mode 100644 index 0000000000000000000000000000000000000000..9191a197055a954272ee8ed86c5e34f3f33f9ad5 --- /dev/null +++ b/liveportrait/modules/warping_network.py @@ -0,0 +1,77 @@ +# coding: utf-8 + +""" +Warping field estimator(W) defined in the paper, which generates a warping field using the implicit +keypoint representations x_s and x_d, and employs this flow field to warp the source feature volume f_s. +""" + +from torch import nn +import torch.nn.functional as F +from .util import SameBlock2d +from .dense_motion import DenseMotionNetwork + + +class WarpingNetwork(nn.Module): + def __init__( + self, + num_kp, + block_expansion, + max_features, + num_down_blocks, + reshape_channel, + estimate_occlusion_map=False, + dense_motion_params=None, + **kwargs + ): + super(WarpingNetwork, self).__init__() + + self.upscale = kwargs.get('upscale', 1) + self.flag_use_occlusion_map = kwargs.get('flag_use_occlusion_map', True) + + if dense_motion_params is not None: + self.dense_motion_network = DenseMotionNetwork( + num_kp=num_kp, + feature_channel=reshape_channel, + estimate_occlusion_map=estimate_occlusion_map, + **dense_motion_params + ) + else: + self.dense_motion_network = None + + self.third = SameBlock2d(max_features, block_expansion * (2 ** num_down_blocks), kernel_size=(3, 3), padding=(1, 1), lrelu=True) + self.fourth = nn.Conv2d(in_channels=block_expansion * (2 ** num_down_blocks), out_channels=block_expansion * (2 ** num_down_blocks), kernel_size=1, stride=1) + + self.estimate_occlusion_map = estimate_occlusion_map + + def deform_input(self, inp, deformation): + return F.grid_sample(inp, deformation, align_corners=False) + + def forward(self, feature_3d, kp_driving, kp_source): + if self.dense_motion_network is not None: + # Feature warper, Transforming feature representation according to deformation and occlusion + dense_motion = self.dense_motion_network( + feature=feature_3d, kp_driving=kp_driving, kp_source=kp_source + ) + if 'occlusion_map' in dense_motion: + occlusion_map = dense_motion['occlusion_map'] # Bx1x64x64 + else: + occlusion_map = None + + deformation = dense_motion['deformation'] # Bx16x64x64x3 + out = self.deform_input(feature_3d, deformation) # Bx32x16x64x64 + + bs, c, d, h, w = out.shape # Bx32x16x64x64 + out = out.view(bs, c * d, h, w) # -> Bx512x64x64 + out = self.third(out) # -> Bx256x64x64 + out = self.fourth(out) # -> Bx256x64x64 + + if self.flag_use_occlusion_map and (occlusion_map is not None): + out = out * occlusion_map + + ret_dct = { + 'occlusion_map': occlusion_map, + 'deformation': deformation, + 'out': out, + } + + return ret_dct diff --git a/liveportrait/template_maker.py b/liveportrait/template_maker.py new file mode 100644 index 0000000000000000000000000000000000000000..7f3ce06201d6f9db98a299346a3324364196fad1 --- /dev/null +++ b/liveportrait/template_maker.py @@ -0,0 +1,65 @@ +# coding: utf-8 + +""" +Make video template +""" + +import os +import cv2 +import numpy as np +import pickle +from rich.progress import track +from .utils.cropper import Cropper + +from .utils.io import load_driving_info +from .utils.camera import get_rotation_matrix +from .utils.helper import mkdir, basename +from .utils.rprint import rlog as log +from .config.crop_config import CropConfig +from .config.inference_config import InferenceConfig +from .live_portrait_wrapper import LivePortraitWrapper + +class TemplateMaker: + + def __init__(self, inference_cfg: InferenceConfig, crop_cfg: CropConfig): + self.live_portrait_wrapper: LivePortraitWrapper = LivePortraitWrapper(cfg=inference_cfg) + self.cropper = Cropper(crop_cfg=crop_cfg) + + def make_motion_template(self, video_fp: str, output_path: str, **kwargs): + """ make video template (.pkl format) + video_fp: driving video file path + output_path: where to save the pickle file + """ + + driving_rgb_lst = load_driving_info(video_fp) + driving_rgb_lst = [cv2.resize(_, (256, 256)) for _ in driving_rgb_lst] + driving_lmk_lst = self.cropper.get_retargeting_lmk_info(driving_rgb_lst) + I_d_lst = self.live_portrait_wrapper.prepare_driving_videos(driving_rgb_lst) + + n_frames = I_d_lst.shape[0] + + templates = [] + + + for i in track(range(n_frames), description='Making templates...', total=n_frames): + I_d_i = I_d_lst[i] + x_d_i_info = self.live_portrait_wrapper.get_kp_info(I_d_i) + R_d_i = get_rotation_matrix(x_d_i_info['pitch'], x_d_i_info['yaw'], x_d_i_info['roll']) + # collect s_d, R_d, δ_d and t_d for inference + template_dct = { + 'n_frames': n_frames, + 'frames_index': i, + } + template_dct['scale'] = x_d_i_info['scale'].cpu().numpy().astype(np.float32) + template_dct['R_d'] = R_d_i.cpu().numpy().astype(np.float32) + template_dct['exp'] = x_d_i_info['exp'].cpu().numpy().astype(np.float32) + template_dct['t'] = x_d_i_info['t'].cpu().numpy().astype(np.float32) + + templates.append(template_dct) + + mkdir(output_path) + # Save the dictionary as a pickle file + pickle_fp = os.path.join(output_path, f'{basename(video_fp)}.pkl') + with open(pickle_fp, 'wb') as f: + pickle.dump([templates, driving_lmk_lst], f) + log(f"Template saved at {pickle_fp}") diff --git a/liveportrait/utils/__init__.py b/liveportrait/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/liveportrait/utils/camera.py b/liveportrait/utils/camera.py new file mode 100644 index 0000000000000000000000000000000000000000..8bbfc90ac87e99caf09bee69982761fdde753527 --- /dev/null +++ b/liveportrait/utils/camera.py @@ -0,0 +1,75 @@ +# coding: utf-8 + +""" +functions for processing and transforming 3D facial keypoints +""" + +import numpy as np +import torch +import torch.nn.functional as F + +PI = np.pi + + +def headpose_pred_to_degree(pred): + """ + pred: (bs, 66) or (bs, 1) or others + """ + if pred.ndim > 1 and pred.shape[1] == 66: + # NOTE: note that the average is modified to 97.5 + device = pred.device + idx_tensor = [idx for idx in range(0, 66)] + idx_tensor = torch.FloatTensor(idx_tensor).to(device) + pred = F.softmax(pred, dim=1) + degree = torch.sum(pred*idx_tensor, axis=1) * 3 - 97.5 + + return degree + + return pred + + +def get_rotation_matrix(pitch_, yaw_, roll_): + """ the input is in degree + """ + # calculate the rotation matrix: vps @ rot + + # transform to radian + pitch = pitch_ / 180 * PI + yaw = yaw_ / 180 * PI + roll = roll_ / 180 * PI + + device = pitch.device + + if pitch.ndim == 1: + pitch = pitch.unsqueeze(1) + if yaw.ndim == 1: + yaw = yaw.unsqueeze(1) + if roll.ndim == 1: + roll = roll.unsqueeze(1) + + # calculate the euler matrix + bs = pitch.shape[0] + ones = torch.ones([bs, 1]).to(device) + zeros = torch.zeros([bs, 1]).to(device) + x, y, z = pitch, yaw, roll + + rot_x = torch.cat([ + ones, zeros, zeros, + zeros, torch.cos(x), -torch.sin(x), + zeros, torch.sin(x), torch.cos(x) + ], dim=1).reshape([bs, 3, 3]) + + rot_y = torch.cat([ + torch.cos(y), zeros, torch.sin(y), + zeros, ones, zeros, + -torch.sin(y), zeros, torch.cos(y) + ], dim=1).reshape([bs, 3, 3]) + + rot_z = torch.cat([ + torch.cos(z), -torch.sin(z), zeros, + torch.sin(z), torch.cos(z), zeros, + zeros, zeros, ones + ], dim=1).reshape([bs, 3, 3]) + + rot = rot_z @ rot_y @ rot_x + return rot.permute(0, 2, 1) # transpose diff --git a/liveportrait/utils/crop.py b/liveportrait/utils/crop.py new file mode 100644 index 0000000000000000000000000000000000000000..8f233639fae332c502623e9a0e695af69379dc57 --- /dev/null +++ b/liveportrait/utils/crop.py @@ -0,0 +1,412 @@ +# coding: utf-8 + +""" +cropping function and the related preprocess functions for cropping +""" + +import numpy as np +import os.path as osp +from math import sin, cos, acos, degrees +import cv2; cv2.setNumThreads(0); cv2.ocl.setUseOpenCL(False) # NOTE: enforce single thread +from .rprint import rprint as print + +DTYPE = np.float32 +CV2_INTERP = cv2.INTER_LINEAR + +def make_abs_path(fn): + return osp.join(osp.dirname(osp.realpath(__file__)), fn) + +def _transform_img(img, M, dsize, flags=CV2_INTERP, borderMode=None): + """ conduct similarity or affine transformation to the image, do not do border operation! + img: + M: 2x3 matrix or 3x3 matrix + dsize: target shape (width, height) + """ + if isinstance(dsize, tuple) or isinstance(dsize, list): + _dsize = tuple(dsize) + else: + _dsize = (dsize, dsize) + + if borderMode is not None: + return cv2.warpAffine(img, M[:2, :], dsize=_dsize, flags=flags, borderMode=borderMode, borderValue=(0, 0, 0)) + else: + return cv2.warpAffine(img, M[:2, :], dsize=_dsize, flags=flags) + + +def _transform_pts(pts, M): + """ conduct similarity or affine transformation to the pts + pts: Nx2 ndarray + M: 2x3 matrix or 3x3 matrix + return: Nx2 + """ + return pts @ M[:2, :2].T + M[:2, 2] + + +def parse_pt2_from_pt101(pt101, use_lip=True): + """ + parsing the 2 points according to the 101 points, which cancels the roll + """ + # the former version use the eye center, but it is not robust, now use interpolation + pt_left_eye = np.mean(pt101[[39, 42, 45, 48]], axis=0) # left eye center + pt_right_eye = np.mean(pt101[[51, 54, 57, 60]], axis=0) # right eye center + + if use_lip: + # use lip + pt_center_eye = (pt_left_eye + pt_right_eye) / 2 + pt_center_lip = (pt101[75] + pt101[81]) / 2 + pt2 = np.stack([pt_center_eye, pt_center_lip], axis=0) + else: + pt2 = np.stack([pt_left_eye, pt_right_eye], axis=0) + return pt2 + + +def parse_pt2_from_pt106(pt106, use_lip=True): + """ + parsing the 2 points according to the 106 points, which cancels the roll + """ + pt_left_eye = np.mean(pt106[[33, 35, 40, 39]], axis=0) # left eye center + pt_right_eye = np.mean(pt106[[87, 89, 94, 93]], axis=0) # right eye center + + if use_lip: + # use lip + pt_center_eye = (pt_left_eye + pt_right_eye) / 2 + pt_center_lip = (pt106[52] + pt106[61]) / 2 + pt2 = np.stack([pt_center_eye, pt_center_lip], axis=0) + else: + pt2 = np.stack([pt_left_eye, pt_right_eye], axis=0) + return pt2 + + +def parse_pt2_from_pt203(pt203, use_lip=True): + """ + parsing the 2 points according to the 203 points, which cancels the roll + """ + pt_left_eye = np.mean(pt203[[0, 6, 12, 18]], axis=0) # left eye center + pt_right_eye = np.mean(pt203[[24, 30, 36, 42]], axis=0) # right eye center + if use_lip: + # use lip + pt_center_eye = (pt_left_eye + pt_right_eye) / 2 + pt_center_lip = (pt203[48] + pt203[66]) / 2 + pt2 = np.stack([pt_center_eye, pt_center_lip], axis=0) + else: + pt2 = np.stack([pt_left_eye, pt_right_eye], axis=0) + return pt2 + + +def parse_pt2_from_pt68(pt68, use_lip=True): + """ + parsing the 2 points according to the 68 points, which cancels the roll + """ + lm_idx = np.array([31, 37, 40, 43, 46, 49, 55], dtype=np.int32) - 1 + if use_lip: + pt5 = np.stack([ + np.mean(pt68[lm_idx[[1, 2]], :], 0), # left eye + np.mean(pt68[lm_idx[[3, 4]], :], 0), # right eye + pt68[lm_idx[0], :], # nose + pt68[lm_idx[5], :], # lip + pt68[lm_idx[6], :] # lip + ], axis=0) + + pt2 = np.stack([ + (pt5[0] + pt5[1]) / 2, + (pt5[3] + pt5[4]) / 2 + ], axis=0) + else: + pt2 = np.stack([ + np.mean(pt68[lm_idx[[1, 2]], :], 0), # left eye + np.mean(pt68[lm_idx[[3, 4]], :], 0), # right eye + ], axis=0) + + return pt2 + + +def parse_pt2_from_pt5(pt5, use_lip=True): + """ + parsing the 2 points according to the 5 points, which cancels the roll + """ + if use_lip: + pt2 = np.stack([ + (pt5[0] + pt5[1]) / 2, + (pt5[3] + pt5[4]) / 2 + ], axis=0) + else: + pt2 = np.stack([ + pt5[0], + pt5[1] + ], axis=0) + return pt2 + + +def parse_pt2_from_pt_x(pts, use_lip=True): + if pts.shape[0] == 101: + pt2 = parse_pt2_from_pt101(pts, use_lip=use_lip) + elif pts.shape[0] == 106: + pt2 = parse_pt2_from_pt106(pts, use_lip=use_lip) + elif pts.shape[0] == 68: + pt2 = parse_pt2_from_pt68(pts, use_lip=use_lip) + elif pts.shape[0] == 5: + pt2 = parse_pt2_from_pt5(pts, use_lip=use_lip) + elif pts.shape[0] == 203: + pt2 = parse_pt2_from_pt203(pts, use_lip=use_lip) + elif pts.shape[0] > 101: + # take the first 101 points + pt2 = parse_pt2_from_pt101(pts[:101], use_lip=use_lip) + else: + raise Exception(f'Unknow shape: {pts.shape}') + + if not use_lip: + # NOTE: to compile with the latter code, need to rotate the pt2 90 degrees clockwise manually + v = pt2[1] - pt2[0] + pt2[1, 0] = pt2[0, 0] - v[1] + pt2[1, 1] = pt2[0, 1] + v[0] + + return pt2 + + +def parse_rect_from_landmark( + pts, + scale=1.5, + need_square=True, + vx_ratio=0, + vy_ratio=0, + use_deg_flag=False, + **kwargs +): + """parsing center, size, angle from 101/68/5/x landmarks + vx_ratio: the offset ratio along the pupil axis x-axis, multiplied by size + vy_ratio: the offset ratio along the pupil axis y-axis, multiplied by size, which is used to contain more forehead area + + judge with pts.shape + """ + pt2 = parse_pt2_from_pt_x(pts, use_lip=kwargs.get('use_lip', True)) + + uy = pt2[1] - pt2[0] + l = np.linalg.norm(uy) + if l <= 1e-3: + uy = np.array([0, 1], dtype=DTYPE) + else: + uy /= l + ux = np.array((uy[1], -uy[0]), dtype=DTYPE) + + # the rotation degree of the x-axis, the clockwise is positive, the counterclockwise is negative (image coordinate system) + # print(uy) + # print(ux) + angle = acos(ux[0]) + if ux[1] < 0: + angle = -angle + + # rotation matrix + M = np.array([ux, uy]) + + # calculate the size which contains the angle degree of the bbox, and the center + center0 = np.mean(pts, axis=0) + rpts = (pts - center0) @ M.T # (M @ P.T).T = P @ M.T + lt_pt = np.min(rpts, axis=0) + rb_pt = np.max(rpts, axis=0) + center1 = (lt_pt + rb_pt) / 2 + + size = rb_pt - lt_pt + if need_square: + m = max(size[0], size[1]) + size[0] = m + size[1] = m + + size *= scale # scale size + center = center0 + ux * center1[0] + uy * center1[1] # counterclockwise rotation, equivalent to M.T @ center1.T + center = center + ux * (vx_ratio * size) + uy * \ + (vy_ratio * size) # considering the offset in vx and vy direction + + if use_deg_flag: + angle = degrees(angle) + + return center, size, angle + + +def parse_bbox_from_landmark(pts, **kwargs): + center, size, angle = parse_rect_from_landmark(pts, **kwargs) + cx, cy = center + w, h = size + + # calculate the vertex positions before rotation + bbox = np.array([ + [cx-w/2, cy-h/2], # left, top + [cx+w/2, cy-h/2], + [cx+w/2, cy+h/2], # right, bottom + [cx-w/2, cy+h/2] + ], dtype=DTYPE) + + # construct rotation matrix + bbox_rot = bbox.copy() + R = np.array([ + [np.cos(angle), -np.sin(angle)], + [np.sin(angle), np.cos(angle)] + ], dtype=DTYPE) + + # calculate the relative position of each vertex from the rotation center, then rotate these positions, and finally add the coordinates of the rotation center + bbox_rot = (bbox_rot - center) @ R.T + center + + return { + 'center': center, # 2x1 + 'size': size, # scalar + 'angle': angle, # rad, counterclockwise + 'bbox': bbox, # 4x2 + 'bbox_rot': bbox_rot, # 4x2 + } + + +def crop_image_by_bbox(img, bbox, lmk=None, dsize=512, angle=None, flag_rot=False, **kwargs): + left, top, right, bot = bbox + if int(right - left) != int(bot - top): + print(f'right-left {right-left} != bot-top {bot-top}') + size = right - left + + src_center = np.array([(left + right) / 2, (top + bot) / 2], dtype=DTYPE) + tgt_center = np.array([dsize / 2, dsize / 2], dtype=DTYPE) + + s = dsize / size # scale + if flag_rot and angle is not None: + costheta, sintheta = cos(angle), sin(angle) + cx, cy = src_center[0], src_center[1] # ori center + tcx, tcy = tgt_center[0], tgt_center[1] # target center + # need to infer + M_o2c = np.array( + [[s * costheta, s * sintheta, tcx - s * (costheta * cx + sintheta * cy)], + [-s * sintheta, s * costheta, tcy - s * (-sintheta * cx + costheta * cy)]], + dtype=DTYPE + ) + else: + M_o2c = np.array( + [[s, 0, tgt_center[0] - s * src_center[0]], + [0, s, tgt_center[1] - s * src_center[1]]], + dtype=DTYPE + ) + + if flag_rot and angle is None: + print('angle is None, but flag_rotate is True', style="bold yellow") + + img_crop = _transform_img(img, M_o2c, dsize=dsize, borderMode=kwargs.get('borderMode', None)) + + lmk_crop = _transform_pts(lmk, M_o2c) if lmk is not None else None + + M_o2c = np.vstack([M_o2c, np.array([0, 0, 1], dtype=DTYPE)]) + M_c2o = np.linalg.inv(M_o2c) + + # cv2.imwrite('crop.jpg', img_crop) + + return { + 'img_crop': img_crop, + 'lmk_crop': lmk_crop, + 'M_o2c': M_o2c, + 'M_c2o': M_c2o, + } + + +def _estimate_similar_transform_from_pts( + pts, + dsize, + scale=1.5, + vx_ratio=0, + vy_ratio=-0.1, + flag_do_rot=True, + **kwargs +): + """ calculate the affine matrix of the cropped image from sparse points, the original image to the cropped image, the inverse is the cropped image to the original image + pts: landmark, 101 or 68 points or other points, Nx2 + scale: the larger scale factor, the smaller face ratio + vx_ratio: x shift + vy_ratio: y shift, the smaller the y shift, the lower the face region + rot_flag: if it is true, conduct correction + """ + center, size, angle = parse_rect_from_landmark( + pts, scale=scale, vx_ratio=vx_ratio, vy_ratio=vy_ratio, + use_lip=kwargs.get('use_lip', True) + ) + + s = dsize / size[0] # scale + tgt_center = np.array([dsize / 2, dsize / 2], dtype=DTYPE) # center of dsize + + if flag_do_rot: + costheta, sintheta = cos(angle), sin(angle) + cx, cy = center[0], center[1] # ori center + tcx, tcy = tgt_center[0], tgt_center[1] # target center + # need to infer + M_INV = np.array( + [[s * costheta, s * sintheta, tcx - s * (costheta * cx + sintheta * cy)], + [-s * sintheta, s * costheta, tcy - s * (-sintheta * cx + costheta * cy)]], + dtype=DTYPE + ) + else: + M_INV = np.array( + [[s, 0, tgt_center[0] - s * center[0]], + [0, s, tgt_center[1] - s * center[1]]], + dtype=DTYPE + ) + + M_INV_H = np.vstack([M_INV, np.array([0, 0, 1])]) + M = np.linalg.inv(M_INV_H) + + # M_INV is from the original image to the cropped image, M is from the cropped image to the original image + return M_INV, M[:2, ...] + + +def crop_image(img, pts: np.ndarray, **kwargs): + dsize = kwargs.get('dsize', 224) + scale = kwargs.get('scale', 1.5) # 1.5 | 1.6 + vy_ratio = kwargs.get('vy_ratio', -0.1) # -0.0625 | -0.1 + + M_INV, _ = _estimate_similar_transform_from_pts( + pts, + dsize=dsize, + scale=scale, + vy_ratio=vy_ratio, + flag_do_rot=kwargs.get('flag_do_rot', True), + ) + + if img is None: + M_INV_H = np.vstack([M_INV, np.array([0, 0, 1], dtype=DTYPE)]) + M = np.linalg.inv(M_INV_H) + ret_dct = { + 'M': M[:2, ...], # from the original image to the cropped image + 'M_o2c': M[:2, ...], # from the cropped image to the original image + 'img_crop': None, + 'pt_crop': None, + } + return ret_dct + + img_crop = _transform_img(img, M_INV, dsize) # origin to crop + pt_crop = _transform_pts(pts, M_INV) + + M_o2c = np.vstack([M_INV, np.array([0, 0, 1], dtype=DTYPE)]) + M_c2o = np.linalg.inv(M_o2c) + + ret_dct = { + 'M_o2c': M_o2c, # from the original image to the cropped image 3x3 + 'M_c2o': M_c2o, # from the cropped image to the original image 3x3 + 'img_crop': img_crop, # the cropped image + 'pt_crop': pt_crop, # the landmarks of the cropped image + } + + return ret_dct + +def average_bbox_lst(bbox_lst): + if len(bbox_lst) == 0: + return None + bbox_arr = np.array(bbox_lst) + return np.mean(bbox_arr, axis=0).tolist() + +def prepare_paste_back(mask_crop, crop_M_c2o, dsize): + """prepare mask for later image paste back + """ + if mask_crop is None: + mask_crop = cv2.imread(make_abs_path('./resources/mask_template.png'), cv2.IMREAD_COLOR) + mask_ori = _transform_img(mask_crop, crop_M_c2o, dsize) + mask_ori = mask_ori.astype(np.float32) / 255. + return mask_ori + +def paste_back(image_to_processed, crop_M_c2o, rgb_ori, mask_ori): + """paste back the image + """ + dsize = (rgb_ori.shape[1], rgb_ori.shape[0]) + result = _transform_img(image_to_processed, crop_M_c2o, dsize=dsize) + result = np.clip(mask_ori * result + (1 - mask_ori) * rgb_ori, 0, 255).astype(np.uint8) + return result \ No newline at end of file diff --git a/liveportrait/utils/cropper.py b/liveportrait/utils/cropper.py new file mode 100644 index 0000000000000000000000000000000000000000..7800ed83873eee08cafa17741cfe47d7b2a6af3b --- /dev/null +++ b/liveportrait/utils/cropper.py @@ -0,0 +1,150 @@ +# coding: utf-8 + +import gradio as gr +import numpy as np +import os +import os.path as osp +from typing import List, Union, Tuple +from dataclasses import dataclass, field +import cv2; cv2.setNumThreads(0); cv2.ocl.setUseOpenCL(False) + +from .landmark_runner import LandmarkRunner +from .face_analysis_diy import FaceAnalysisDIY +from .helper import prefix +from .crop import crop_image, crop_image_by_bbox, parse_bbox_from_landmark, average_bbox_lst +from .timer import Timer +from .rprint import rlog as log +from .io import load_image_rgb +from .video import VideoWriter, get_fps, change_video_fps + +import os + +DATA_ROOT = os.environ.get('DATA_ROOT', '/tmp/data') +MODELS_DIR = os.path.join(DATA_ROOT, "models") + +def make_abs_path(fn): + return osp.join(osp.dirname(osp.realpath(__file__)), fn) + + +@dataclass +class Trajectory: + start: int = -1 # 起始帧 闭区间 + end: int = -1 # 结束帧 闭区间 + lmk_lst: Union[Tuple, List, np.ndarray] = field(default_factory=list) # lmk list + bbox_lst: Union[Tuple, List, np.ndarray] = field(default_factory=list) # bbox list + frame_rgb_lst: Union[Tuple, List, np.ndarray] = field(default_factory=list) # frame list + frame_rgb_crop_lst: Union[Tuple, List, np.ndarray] = field(default_factory=list) # frame crop list + + +class Cropper(object): + def __init__(self, **kwargs) -> None: + device_id = kwargs.get('device_id', 0) + self.landmark_runner = LandmarkRunner( + ckpt_path=make_abs_path(os.path.join(MODELS_DIR, "liveportrait", "landmark.onnx")), + onnx_provider='cuda', + device_id=device_id + ) + self.landmark_runner.warmup() + + self.face_analysis_wrapper = FaceAnalysisDIY( + name='buffalo_l', + root=make_abs_path(os.path.join(MODELS_DIR, "insightface")), + providers=["CUDAExecutionProvider"] + ) + self.face_analysis_wrapper.prepare(ctx_id=device_id, det_size=(512, 512)) + self.face_analysis_wrapper.warmup() + + self.crop_cfg = kwargs.get('crop_cfg', None) + + def update_config(self, user_args): + for k, v in user_args.items(): + if hasattr(self.crop_cfg, k): + setattr(self.crop_cfg, k, v) + + def crop_single_image(self, obj, **kwargs): + direction = kwargs.get('direction', 'large-small') + + # crop and align a single image + if isinstance(obj, str): + img_rgb = load_image_rgb(obj) + elif isinstance(obj, np.ndarray): + img_rgb = obj + + src_face = self.face_analysis_wrapper.get( + img_rgb, + flag_do_landmark_2d_106=True, + direction=direction + ) + + if len(src_face) == 0: + log('No face detected in the source image.') + raise gr.Error("No face detected in the source image 💥!", duration=5) + raise Exception("No face detected in the source image!") + elif len(src_face) > 1: + log(f'More than one face detected in the image, only pick one face by rule {direction}.') + + src_face = src_face[0] + pts = src_face.landmark_2d_106 + + # crop the face + ret_dct = crop_image( + img_rgb, # ndarray + pts, # 106x2 or Nx2 + dsize=kwargs.get('dsize', 512), + scale=kwargs.get('scale', 2.3), + vy_ratio=kwargs.get('vy_ratio', -0.15), + ) + # update a 256x256 version for network input or else + ret_dct['img_crop_256x256'] = cv2.resize(ret_dct['img_crop'], (256, 256), interpolation=cv2.INTER_AREA) + ret_dct['pt_crop_256x256'] = ret_dct['pt_crop'] * 256 / kwargs.get('dsize', 512) + + recon_ret = self.landmark_runner.run(img_rgb, pts) + lmk = recon_ret['pts'] + ret_dct['lmk_crop'] = lmk + + return ret_dct + + def get_retargeting_lmk_info(self, driving_rgb_lst): + # TODO: implement a tracking-based version + driving_lmk_lst = [] + for driving_image in driving_rgb_lst: + ret_dct = self.crop_single_image(driving_image) + driving_lmk_lst.append(ret_dct['lmk_crop']) + return driving_lmk_lst + + def make_video_clip(self, driving_rgb_lst, output_path, output_fps=30, **kwargs): + trajectory = Trajectory() + direction = kwargs.get('direction', 'large-small') + for idx, driving_image in enumerate(driving_rgb_lst): + if idx == 0 or trajectory.start == -1: + src_face = self.face_analysis_wrapper.get( + driving_image, + flag_do_landmark_2d_106=True, + direction=direction + ) + if len(src_face) == 0: + # No face detected in the driving_image + continue + elif len(src_face) > 1: + log(f'More than one face detected in the driving frame_{idx}, only pick one face by rule {direction}.') + src_face = src_face[0] + pts = src_face.landmark_2d_106 + lmk_203 = self.landmark_runner(driving_image, pts)['pts'] + trajectory.start, trajectory.end = idx, idx + else: + lmk_203 = self.face_recon_wrapper(driving_image, trajectory.lmk_lst[-1])['pts'] + trajectory.end = idx + + trajectory.lmk_lst.append(lmk_203) + ret_bbox = parse_bbox_from_landmark(lmk_203, scale=self.crop_cfg.globalscale, vy_ratio=elf.crop_cfg.vy_ratio)['bbox'] + bbox = [ret_bbox[0, 0], ret_bbox[0, 1], ret_bbox[2, 0], ret_bbox[2, 1]] # 4, + trajectory.bbox_lst.append(bbox) # bbox + trajectory.frame_rgb_lst.append(driving_image) + + global_bbox = average_bbox_lst(trajectory.bbox_lst) + for idx, (frame_rgb, lmk) in enumerate(zip(trajectory.frame_rgb_lst, trajectory.lmk_lst)): + ret_dct = crop_image_by_bbox( + frame_rgb, global_bbox, lmk=lmk, + dsize=self.video_crop_cfg.dsize, flag_rot=self.video_crop_cfg.flag_rot, borderValue=self.video_crop_cfg.borderValue + ) + frame_rgb_crop = ret_dct['img_crop'] diff --git a/liveportrait/utils/dependencies/insightface/__init__.py b/liveportrait/utils/dependencies/insightface/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1680083da47850b31da10803c7d255e67dda619a --- /dev/null +++ b/liveportrait/utils/dependencies/insightface/__init__.py @@ -0,0 +1,20 @@ +# coding: utf-8 +# pylint: disable=wrong-import-position +"""InsightFace: A Face Analysis Toolkit.""" +from __future__ import absolute_import + +try: + #import mxnet as mx + import onnxruntime +except ImportError: + raise ImportError( + "Unable to import dependency onnxruntime. " + ) + +__version__ = '0.7.3' + +from . import model_zoo +from . import utils +from . import app +from . import data + diff --git a/liveportrait/utils/dependencies/insightface/app/__init__.py b/liveportrait/utils/dependencies/insightface/app/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cc574616885290489798bac5c682e7aaa65a5dad --- /dev/null +++ b/liveportrait/utils/dependencies/insightface/app/__init__.py @@ -0,0 +1 @@ +from .face_analysis import * diff --git a/liveportrait/utils/dependencies/insightface/app/common.py b/liveportrait/utils/dependencies/insightface/app/common.py new file mode 100644 index 0000000000000000000000000000000000000000..82ca987aeede35510b3aef72b4edf2390ad84e65 --- /dev/null +++ b/liveportrait/utils/dependencies/insightface/app/common.py @@ -0,0 +1,49 @@ +import numpy as np +from numpy.linalg import norm as l2norm +#from easydict import EasyDict + +class Face(dict): + + def __init__(self, d=None, **kwargs): + if d is None: + d = {} + if kwargs: + d.update(**kwargs) + for k, v in d.items(): + setattr(self, k, v) + # Class attributes + #for k in self.__class__.__dict__.keys(): + # if not (k.startswith('__') and k.endswith('__')) and not k in ('update', 'pop'): + # setattr(self, k, getattr(self, k)) + + def __setattr__(self, name, value): + if isinstance(value, (list, tuple)): + value = [self.__class__(x) + if isinstance(x, dict) else x for x in value] + elif isinstance(value, dict) and not isinstance(value, self.__class__): + value = self.__class__(value) + super(Face, self).__setattr__(name, value) + super(Face, self).__setitem__(name, value) + + __setitem__ = __setattr__ + + def __getattr__(self, name): + return None + + @property + def embedding_norm(self): + if self.embedding is None: + return None + return l2norm(self.embedding) + + @property + def normed_embedding(self): + if self.embedding is None: + return None + return self.embedding / self.embedding_norm + + @property + def sex(self): + if self.gender is None: + return None + return 'M' if self.gender==1 else 'F' diff --git a/liveportrait/utils/dependencies/insightface/app/face_analysis.py b/liveportrait/utils/dependencies/insightface/app/face_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..aa5128b3f5e02c2c19e7df195cc1c1e7fcf36c4d --- /dev/null +++ b/liveportrait/utils/dependencies/insightface/app/face_analysis.py @@ -0,0 +1,110 @@ +# -*- coding: utf-8 -*- +# @Organization : insightface.ai +# @Author : Jia Guo +# @Time : 2021-05-04 +# @Function : + + +from __future__ import division + +import glob +import os.path as osp + +import numpy as np +import onnxruntime +from numpy.linalg import norm + +from ..model_zoo import model_zoo +from ..utils import ensure_available +from .common import Face + + +DEFAULT_MP_NAME = 'buffalo_l' +__all__ = ['FaceAnalysis'] + +class FaceAnalysis: + def __init__(self, name=DEFAULT_MP_NAME, root='~/.insightface', allowed_modules=None, **kwargs): + onnxruntime.set_default_logger_severity(3) + self.models = {} + self.model_dir = ensure_available('models', name, root=root) + onnx_files = glob.glob(osp.join(self.model_dir, '*.onnx')) + onnx_files = sorted(onnx_files) + for onnx_file in onnx_files: + model = model_zoo.get_model(onnx_file, **kwargs) + if model is None: + print('model not recognized:', onnx_file) + elif allowed_modules is not None and model.taskname not in allowed_modules: + print('model ignore:', onnx_file, model.taskname) + del model + elif model.taskname not in self.models and (allowed_modules is None or model.taskname in allowed_modules): + # print('find model:', onnx_file, model.taskname, model.input_shape, model.input_mean, model.input_std) + self.models[model.taskname] = model + else: + print('duplicated model task type, ignore:', onnx_file, model.taskname) + del model + assert 'detection' in self.models + self.det_model = self.models['detection'] + + + def prepare(self, ctx_id, det_thresh=0.5, det_size=(640, 640)): + self.det_thresh = det_thresh + assert det_size is not None + # print('set det-size:', det_size) + self.det_size = det_size + for taskname, model in self.models.items(): + if taskname=='detection': + model.prepare(ctx_id, input_size=det_size, det_thresh=det_thresh) + else: + model.prepare(ctx_id) + + def get(self, img, max_num=0): + bboxes, kpss = self.det_model.detect(img, + max_num=max_num, + metric='default') + if bboxes.shape[0] == 0: + return [] + ret = [] + for i in range(bboxes.shape[0]): + bbox = bboxes[i, 0:4] + det_score = bboxes[i, 4] + kps = None + if kpss is not None: + kps = kpss[i] + face = Face(bbox=bbox, kps=kps, det_score=det_score) + for taskname, model in self.models.items(): + if taskname=='detection': + continue + model.get(img, face) + ret.append(face) + return ret + + def draw_on(self, img, faces): + import cv2 + dimg = img.copy() + for i in range(len(faces)): + face = faces[i] + box = face.bbox.astype(np.int) + color = (0, 0, 255) + cv2.rectangle(dimg, (box[0], box[1]), (box[2], box[3]), color, 2) + if face.kps is not None: + kps = face.kps.astype(np.int) + #print(landmark.shape) + for l in range(kps.shape[0]): + color = (0, 0, 255) + if l == 0 or l == 3: + color = (0, 255, 0) + cv2.circle(dimg, (kps[l][0], kps[l][1]), 1, color, + 2) + if face.gender is not None and face.age is not None: + cv2.putText(dimg,'%s,%d'%(face.sex,face.age), (box[0]-1, box[1]-4),cv2.FONT_HERSHEY_COMPLEX,0.7,(0,255,0),1) + + #for key, value in face.items(): + # if key.startswith('landmark_3d'): + # print(key, value.shape) + # print(value[0:10,:]) + # lmk = np.round(value).astype(np.int) + # for l in range(lmk.shape[0]): + # color = (255, 0, 0) + # cv2.circle(dimg, (lmk[l][0], lmk[l][1]), 1, color, + # 2) + return dimg diff --git a/liveportrait/utils/dependencies/insightface/data/__init__.py b/liveportrait/utils/dependencies/insightface/data/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..665c59ec99b6ebf12822015e0350969c7903e243 --- /dev/null +++ b/liveportrait/utils/dependencies/insightface/data/__init__.py @@ -0,0 +1,2 @@ +from .image import get_image +from .pickle_object import get_object diff --git a/liveportrait/utils/dependencies/insightface/data/image.py b/liveportrait/utils/dependencies/insightface/data/image.py new file mode 100644 index 0000000000000000000000000000000000000000..6d32c4bcb1b13d33bcb0d840cf7b8c08d183b3ea --- /dev/null +++ b/liveportrait/utils/dependencies/insightface/data/image.py @@ -0,0 +1,27 @@ +import cv2 +import os +import os.path as osp +from pathlib import Path + +class ImageCache: + data = {} + +def get_image(name, to_rgb=False): + key = (name, to_rgb) + if key in ImageCache.data: + return ImageCache.data[key] + images_dir = osp.join(Path(__file__).parent.absolute(), 'images') + ext_names = ['.jpg', '.png', '.jpeg'] + image_file = None + for ext_name in ext_names: + _image_file = osp.join(images_dir, "%s%s"%(name, ext_name)) + if osp.exists(_image_file): + image_file = _image_file + break + assert image_file is not None, '%s not found'%name + img = cv2.imread(image_file) + if to_rgb: + img = img[:,:,::-1] + ImageCache.data[key] = img + return img + diff --git a/liveportrait/utils/dependencies/insightface/data/images/Tom_Hanks_54745.png b/liveportrait/utils/dependencies/insightface/data/images/Tom_Hanks_54745.png new file mode 100644 index 0000000000000000000000000000000000000000..83387c3572e335441b617d0ba1f6a7f897b87f37 --- /dev/null +++ b/liveportrait/utils/dependencies/insightface/data/images/Tom_Hanks_54745.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8545da294e8c7c79911169c3915fed8528f1960cd0ed99b92453788ca4275083 +size 12123 diff --git a/liveportrait/utils/dependencies/insightface/data/images/mask_black.jpg b/liveportrait/utils/dependencies/insightface/data/images/mask_black.jpg new file mode 100644 index 0000000000000000000000000000000000000000..68233a29abd20c692a151143e22abcd62461ce2b --- /dev/null +++ b/liveportrait/utils/dependencies/insightface/data/images/mask_black.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d81c40c77a0e38717dc7e1d4ca994e2bc58efa804465ff8d09d915daeddf2c83 +size 21308 diff --git a/liveportrait/utils/dependencies/insightface/data/images/mask_blue.jpg b/liveportrait/utils/dependencies/insightface/data/images/mask_blue.jpg new file mode 100644 index 0000000000000000000000000000000000000000..37a029125e7a6257d59cf2201be4b3409564d33e --- /dev/null +++ b/liveportrait/utils/dependencies/insightface/data/images/mask_blue.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a55ec2b181de4143af27c441852ebb4bbd364fb0e0b9c46bb17631c59bc4c840 +size 44728 diff --git a/liveportrait/utils/dependencies/insightface/data/images/mask_green.jpg b/liveportrait/utils/dependencies/insightface/data/images/mask_green.jpg new file mode 100644 index 0000000000000000000000000000000000000000..8ed0111375d6c189f2a071ec6fcbcbdb8607b4fb --- /dev/null +++ b/liveportrait/utils/dependencies/insightface/data/images/mask_green.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:79526b5a31ef75cb7fe51227abc69d589e4b7ba39dbbf51e79147da577a3f154 +size 6116 diff --git a/liveportrait/utils/dependencies/insightface/data/images/mask_white.jpg b/liveportrait/utils/dependencies/insightface/data/images/mask_white.jpg new file mode 100644 index 0000000000000000000000000000000000000000..e6c92ec3c5dfadc36e8de5bc1c91572d602f2ce3 --- /dev/null +++ b/liveportrait/utils/dependencies/insightface/data/images/mask_white.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3adee6ba6680d26197bbea95deb9d335252d01c2c51ead23e01af9784c310aa6 +size 78905 diff --git a/liveportrait/utils/dependencies/insightface/data/images/t1.jpg b/liveportrait/utils/dependencies/insightface/data/images/t1.jpg new file mode 100644 index 0000000000000000000000000000000000000000..8fd6427a177bd01650c0150e9d02457c3a5dcddd --- /dev/null +++ b/liveportrait/utils/dependencies/insightface/data/images/t1.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:47f682e945b659f93a9e490b9c9c4a2a864abe64dace9e1a2893845ddfd69489 +size 128824 diff --git a/liveportrait/utils/dependencies/insightface/data/objects/meanshape_68.pkl b/liveportrait/utils/dependencies/insightface/data/objects/meanshape_68.pkl new file mode 100644 index 0000000000000000000000000000000000000000..2af4d76020057e90528756c62d8833aaf0e0a5c8 Binary files /dev/null and b/liveportrait/utils/dependencies/insightface/data/objects/meanshape_68.pkl differ diff --git a/liveportrait/utils/dependencies/insightface/data/pickle_object.py b/liveportrait/utils/dependencies/insightface/data/pickle_object.py new file mode 100644 index 0000000000000000000000000000000000000000..fbd87030ea15e1d01af1cd4cff1be2bc54cc82dd --- /dev/null +++ b/liveportrait/utils/dependencies/insightface/data/pickle_object.py @@ -0,0 +1,17 @@ +import cv2 +import os +import os.path as osp +from pathlib import Path +import pickle + +def get_object(name): + objects_dir = osp.join(Path(__file__).parent.absolute(), 'objects') + if not name.endswith('.pkl'): + name = name+".pkl" + filepath = osp.join(objects_dir, name) + if not osp.exists(filepath): + return None + with open(filepath, 'rb') as f: + obj = pickle.load(f) + return obj + diff --git a/liveportrait/utils/dependencies/insightface/data/rec_builder.py b/liveportrait/utils/dependencies/insightface/data/rec_builder.py new file mode 100644 index 0000000000000000000000000000000000000000..e02abc969da2f882639326f5bad3c7e8d08c1fde --- /dev/null +++ b/liveportrait/utils/dependencies/insightface/data/rec_builder.py @@ -0,0 +1,71 @@ +import pickle +import numpy as np +import os +import os.path as osp +import sys +import mxnet as mx + + +class RecBuilder(): + def __init__(self, path, image_size=(112, 112)): + self.path = path + self.image_size = image_size + self.widx = 0 + self.wlabel = 0 + self.max_label = -1 + assert not osp.exists(path), '%s exists' % path + os.makedirs(path) + self.writer = mx.recordio.MXIndexedRecordIO(os.path.join(path, 'train.idx'), + os.path.join(path, 'train.rec'), + 'w') + self.meta = [] + + def add(self, imgs): + #!!! img should be BGR!!!! + #assert label >= 0 + #assert label > self.last_label + assert len(imgs) > 0 + label = self.wlabel + for img in imgs: + idx = self.widx + image_meta = {'image_index': idx, 'image_classes': [label]} + header = mx.recordio.IRHeader(0, label, idx, 0) + if isinstance(img, np.ndarray): + s = mx.recordio.pack_img(header,img,quality=95,img_fmt='.jpg') + else: + s = mx.recordio.pack(header, img) + self.writer.write_idx(idx, s) + self.meta.append(image_meta) + self.widx += 1 + self.max_label = label + self.wlabel += 1 + + + def add_image(self, img, label): + #!!! img should be BGR!!!! + #assert label >= 0 + #assert label > self.last_label + idx = self.widx + header = mx.recordio.IRHeader(0, label, idx, 0) + if isinstance(label, list): + idlabel = label[0] + else: + idlabel = label + image_meta = {'image_index': idx, 'image_classes': [idlabel]} + if isinstance(img, np.ndarray): + s = mx.recordio.pack_img(header,img,quality=95,img_fmt='.jpg') + else: + s = mx.recordio.pack(header, img) + self.writer.write_idx(idx, s) + self.meta.append(image_meta) + self.widx += 1 + self.max_label = max(self.max_label, idlabel) + + def close(self): + with open(osp.join(self.path, 'train.meta'), 'wb') as pfile: + pickle.dump(self.meta, pfile, protocol=pickle.HIGHEST_PROTOCOL) + print('stat:', self.widx, self.wlabel) + with open(os.path.join(self.path, 'property'), 'w') as f: + f.write("%d,%d,%d\n" % (self.max_label+1, self.image_size[0], self.image_size[1])) + f.write("%d\n" % (self.widx)) + diff --git a/liveportrait/utils/dependencies/insightface/model_zoo/__init__.py b/liveportrait/utils/dependencies/insightface/model_zoo/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..225623d6142c968b4040f391039bfab88bdd1b2a --- /dev/null +++ b/liveportrait/utils/dependencies/insightface/model_zoo/__init__.py @@ -0,0 +1,6 @@ +from .model_zoo import get_model +from .arcface_onnx import ArcFaceONNX +from .retinaface import RetinaFace +from .scrfd import SCRFD +from .landmark import Landmark +from .attribute import Attribute diff --git a/liveportrait/utils/dependencies/insightface/model_zoo/arcface_onnx.py b/liveportrait/utils/dependencies/insightface/model_zoo/arcface_onnx.py new file mode 100644 index 0000000000000000000000000000000000000000..b537ce2ee15d4a1834d54e185f34e336aab30a77 --- /dev/null +++ b/liveportrait/utils/dependencies/insightface/model_zoo/arcface_onnx.py @@ -0,0 +1,92 @@ +# -*- coding: utf-8 -*- +# @Organization : insightface.ai +# @Author : Jia Guo +# @Time : 2021-05-04 +# @Function : + +from __future__ import division +import numpy as np +import cv2 +import onnx +import onnxruntime +from ..utils import face_align + +__all__ = [ + 'ArcFaceONNX', +] + + +class ArcFaceONNX: + def __init__(self, model_file=None, session=None): + assert model_file is not None + self.model_file = model_file + self.session = session + self.taskname = 'recognition' + find_sub = False + find_mul = False + model = onnx.load(self.model_file) + graph = model.graph + for nid, node in enumerate(graph.node[:8]): + #print(nid, node.name) + if node.name.startswith('Sub') or node.name.startswith('_minus'): + find_sub = True + if node.name.startswith('Mul') or node.name.startswith('_mul'): + find_mul = True + if find_sub and find_mul: + #mxnet arcface model + input_mean = 0.0 + input_std = 1.0 + else: + input_mean = 127.5 + input_std = 127.5 + self.input_mean = input_mean + self.input_std = input_std + #print('input mean and std:', self.input_mean, self.input_std) + if self.session is None: + self.session = onnxruntime.InferenceSession(self.model_file, None) + input_cfg = self.session.get_inputs()[0] + input_shape = input_cfg.shape + input_name = input_cfg.name + self.input_size = tuple(input_shape[2:4][::-1]) + self.input_shape = input_shape + outputs = self.session.get_outputs() + output_names = [] + for out in outputs: + output_names.append(out.name) + self.input_name = input_name + self.output_names = output_names + assert len(self.output_names)==1 + self.output_shape = outputs[0].shape + + def prepare(self, ctx_id, **kwargs): + if ctx_id<0: + self.session.set_providers(['CPUExecutionProvider']) + + def get(self, img, face): + aimg = face_align.norm_crop(img, landmark=face.kps, image_size=self.input_size[0]) + face.embedding = self.get_feat(aimg).flatten() + return face.embedding + + def compute_sim(self, feat1, feat2): + from numpy.linalg import norm + feat1 = feat1.ravel() + feat2 = feat2.ravel() + sim = np.dot(feat1, feat2) / (norm(feat1) * norm(feat2)) + return sim + + def get_feat(self, imgs): + if not isinstance(imgs, list): + imgs = [imgs] + input_size = self.input_size + + blob = cv2.dnn.blobFromImages(imgs, 1.0 / self.input_std, input_size, + (self.input_mean, self.input_mean, self.input_mean), swapRB=True) + net_out = self.session.run(self.output_names, {self.input_name: blob})[0] + return net_out + + def forward(self, batch_data): + blob = (batch_data - self.input_mean) / self.input_std + net_out = self.session.run(self.output_names, {self.input_name: blob})[0] + return net_out + + diff --git a/liveportrait/utils/dependencies/insightface/model_zoo/attribute.py b/liveportrait/utils/dependencies/insightface/model_zoo/attribute.py new file mode 100644 index 0000000000000000000000000000000000000000..40c34de3f0995499448cf5779004cc1e5f3564fb --- /dev/null +++ b/liveportrait/utils/dependencies/insightface/model_zoo/attribute.py @@ -0,0 +1,94 @@ +# -*- coding: utf-8 -*- +# @Organization : insightface.ai +# @Author : Jia Guo +# @Time : 2021-06-19 +# @Function : + +from __future__ import division +import numpy as np +import cv2 +import onnx +import onnxruntime +from ..utils import face_align + +__all__ = [ + 'Attribute', +] + + +class Attribute: + def __init__(self, model_file=None, session=None): + assert model_file is not None + self.model_file = model_file + self.session = session + find_sub = False + find_mul = False + model = onnx.load(self.model_file) + graph = model.graph + for nid, node in enumerate(graph.node[:8]): + #print(nid, node.name) + if node.name.startswith('Sub') or node.name.startswith('_minus'): + find_sub = True + if node.name.startswith('Mul') or node.name.startswith('_mul'): + find_mul = True + if nid<3 and node.name=='bn_data': + find_sub = True + find_mul = True + if find_sub and find_mul: + #mxnet arcface model + input_mean = 0.0 + input_std = 1.0 + else: + input_mean = 127.5 + input_std = 128.0 + self.input_mean = input_mean + self.input_std = input_std + #print('input mean and std:', model_file, self.input_mean, self.input_std) + if self.session is None: + self.session = onnxruntime.InferenceSession(self.model_file, None) + input_cfg = self.session.get_inputs()[0] + input_shape = input_cfg.shape + input_name = input_cfg.name + self.input_size = tuple(input_shape[2:4][::-1]) + self.input_shape = input_shape + outputs = self.session.get_outputs() + output_names = [] + for out in outputs: + output_names.append(out.name) + self.input_name = input_name + self.output_names = output_names + assert len(self.output_names)==1 + output_shape = outputs[0].shape + #print('init output_shape:', output_shape) + if output_shape[1]==3: + self.taskname = 'genderage' + else: + self.taskname = 'attribute_%d'%output_shape[1] + + def prepare(self, ctx_id, **kwargs): + if ctx_id<0: + self.session.set_providers(['CPUExecutionProvider']) + + def get(self, img, face): + bbox = face.bbox + w, h = (bbox[2] - bbox[0]), (bbox[3] - bbox[1]) + center = (bbox[2] + bbox[0]) / 2, (bbox[3] + bbox[1]) / 2 + rotate = 0 + _scale = self.input_size[0] / (max(w, h)*1.5) + #print('param:', img.shape, bbox, center, self.input_size, _scale, rotate) + aimg, M = face_align.transform(img, center, self.input_size[0], _scale, rotate) + input_size = tuple(aimg.shape[0:2][::-1]) + #assert input_size==self.input_size + blob = cv2.dnn.blobFromImage(aimg, 1.0/self.input_std, input_size, (self.input_mean, self.input_mean, self.input_mean), swapRB=True) + pred = self.session.run(self.output_names, {self.input_name : blob})[0][0] + if self.taskname=='genderage': + assert len(pred)==3 + gender = np.argmax(pred[:2]) + age = int(np.round(pred[2]*100)) + face['gender'] = gender + face['age'] = age + return gender, age + else: + return pred + + diff --git a/liveportrait/utils/dependencies/insightface/model_zoo/inswapper.py b/liveportrait/utils/dependencies/insightface/model_zoo/inswapper.py new file mode 100644 index 0000000000000000000000000000000000000000..f321c627ee66cceddcab98b561b997441dd4f768 --- /dev/null +++ b/liveportrait/utils/dependencies/insightface/model_zoo/inswapper.py @@ -0,0 +1,114 @@ +import time +import numpy as np +import onnxruntime +import cv2 +import onnx +from onnx import numpy_helper +from ..utils import face_align + + + + +class INSwapper(): + def __init__(self, model_file=None, session=None): + self.model_file = model_file + self.session = session + model = onnx.load(self.model_file) + graph = model.graph + self.emap = numpy_helper.to_array(graph.initializer[-1]) + self.input_mean = 0.0 + self.input_std = 255.0 + #print('input mean and std:', model_file, self.input_mean, self.input_std) + if self.session is None: + self.session = onnxruntime.InferenceSession(self.model_file, None) + inputs = self.session.get_inputs() + self.input_names = [] + for inp in inputs: + self.input_names.append(inp.name) + outputs = self.session.get_outputs() + output_names = [] + for out in outputs: + output_names.append(out.name) + self.output_names = output_names + assert len(self.output_names)==1 + output_shape = outputs[0].shape + input_cfg = inputs[0] + input_shape = input_cfg.shape + self.input_shape = input_shape + # print('inswapper-shape:', self.input_shape) + self.input_size = tuple(input_shape[2:4][::-1]) + + def forward(self, img, latent): + img = (img - self.input_mean) / self.input_std + pred = self.session.run(self.output_names, {self.input_names[0]: img, self.input_names[1]: latent})[0] + return pred + + def get(self, img, target_face, source_face, paste_back=True): + face_mask = np.zeros((img.shape[0], img.shape[1]), np.uint8) + cv2.fillPoly(face_mask, np.array([target_face.landmark_2d_106[[1,9,10,11,12,13,14,15,16,2,3,4,5,6,7,8,0,24,23,22,21,20,19,18,32,31,30,29,28,27,26,25,17,101,105,104,103,51,49,48,43]].astype('int64')]), 1) + aimg, M = face_align.norm_crop2(img, target_face.kps, self.input_size[0]) + blob = cv2.dnn.blobFromImage(aimg, 1.0 / self.input_std, self.input_size, + (self.input_mean, self.input_mean, self.input_mean), swapRB=True) + latent = source_face.normed_embedding.reshape((1,-1)) + latent = np.dot(latent, self.emap) + latent /= np.linalg.norm(latent) + pred = self.session.run(self.output_names, {self.input_names[0]: blob, self.input_names[1]: latent})[0] + #print(latent.shape, latent.dtype, pred.shape) + img_fake = pred.transpose((0,2,3,1))[0] + bgr_fake = np.clip(255 * img_fake, 0, 255).astype(np.uint8)[:,:,::-1] + if not paste_back: + return bgr_fake, M + else: + target_img = img + fake_diff = bgr_fake.astype(np.float32) - aimg.astype(np.float32) + fake_diff = np.abs(fake_diff).mean(axis=2) + fake_diff[:2,:] = 0 + fake_diff[-2:,:] = 0 + fake_diff[:,:2] = 0 + fake_diff[:,-2:] = 0 + IM = cv2.invertAffineTransform(M) + img_white = np.full((aimg.shape[0],aimg.shape[1]), 255, dtype=np.float32) + bgr_fake = cv2.warpAffine(bgr_fake, IM, (target_img.shape[1], target_img.shape[0]), borderValue=0.0) + img_white = cv2.warpAffine(img_white, IM, (target_img.shape[1], target_img.shape[0]), borderValue=0.0) + fake_diff = cv2.warpAffine(fake_diff, IM, (target_img.shape[1], target_img.shape[0]), borderValue=0.0) + img_white[img_white>20] = 255 + fthresh = 10 + fake_diff[fake_diff<fthresh] = 0 + fake_diff[fake_diff>=fthresh] = 255 + img_mask = img_white + mask_h_inds, mask_w_inds = np.where(img_mask==255) + mask_h = np.max(mask_h_inds) - np.min(mask_h_inds) + mask_w = np.max(mask_w_inds) - np.min(mask_w_inds) + mask_size = int(np.sqrt(mask_h*mask_w)) + k = max(mask_size//10, 10) + #k = max(mask_size//20, 6) + #k = 6 + kernel = np.ones((k,k),np.uint8) + img_mask = cv2.erode(img_mask,kernel,iterations = 1) + kernel = np.ones((2,2),np.uint8) + fake_diff = cv2.dilate(fake_diff,kernel,iterations = 1) + + face_mask = cv2.erode(face_mask,np.ones((11,11),np.uint8),iterations = 1) + fake_diff[face_mask==1] = 255 + + k = max(mask_size//20, 5) + #k = 3 + #k = 3 + kernel_size = (k, k) + blur_size = tuple(2*i+1 for i in kernel_size) + img_mask = cv2.GaussianBlur(img_mask, blur_size, 0) + k = 5 + kernel_size = (k, k) + blur_size = tuple(2*i+1 for i in kernel_size) + fake_diff = cv2.blur(fake_diff, (11,11), 0) + ##fake_diff = cv2.GaussianBlur(fake_diff, blur_size, 0) + # print('blur_size: ', blur_size) + # fake_diff = cv2.blur(fake_diff, (21, 21), 0) # blur_size + img_mask /= 255 + fake_diff /= 255 + # img_mask = fake_diff + img_mask = img_mask*fake_diff + img_mask = np.reshape(img_mask, [img_mask.shape[0],img_mask.shape[1],1]) + fake_merged = img_mask * bgr_fake + (1-img_mask) * target_img.astype(np.float32) + fake_merged = fake_merged.astype(np.uint8) + return fake_merged diff --git a/liveportrait/utils/dependencies/insightface/model_zoo/landmark.py b/liveportrait/utils/dependencies/insightface/model_zoo/landmark.py new file mode 100644 index 0000000000000000000000000000000000000000..598b4b29a2d0674d8bb25b681f921c61460d101c --- /dev/null +++ b/liveportrait/utils/dependencies/insightface/model_zoo/landmark.py @@ -0,0 +1,114 @@ +# -*- coding: utf-8 -*- +# @Organization : insightface.ai +# @Author : Jia Guo +# @Time : 2021-05-04 +# @Function : + +from __future__ import division +import numpy as np +import cv2 +import onnx +import onnxruntime +from ..utils import face_align +from ..utils import transform +from ..data import get_object + +__all__ = [ + 'Landmark', +] + + +class Landmark: + def __init__(self, model_file=None, session=None): + assert model_file is not None + self.model_file = model_file + self.session = session + find_sub = False + find_mul = False + model = onnx.load(self.model_file) + graph = model.graph + for nid, node in enumerate(graph.node[:8]): + #print(nid, node.name) + if node.name.startswith('Sub') or node.name.startswith('_minus'): + find_sub = True + if node.name.startswith('Mul') or node.name.startswith('_mul'): + find_mul = True + if nid<3 and node.name=='bn_data': + find_sub = True + find_mul = True + if find_sub and find_mul: + #mxnet arcface model + input_mean = 0.0 + input_std = 1.0 + else: + input_mean = 127.5 + input_std = 128.0 + self.input_mean = input_mean + self.input_std = input_std + #print('input mean and std:', model_file, self.input_mean, self.input_std) + if self.session is None: + self.session = onnxruntime.InferenceSession(self.model_file, None) + input_cfg = self.session.get_inputs()[0] + input_shape = input_cfg.shape + input_name = input_cfg.name + self.input_size = tuple(input_shape[2:4][::-1]) + self.input_shape = input_shape + outputs = self.session.get_outputs() + output_names = [] + for out in outputs: + output_names.append(out.name) + self.input_name = input_name + self.output_names = output_names + assert len(self.output_names)==1 + output_shape = outputs[0].shape + self.require_pose = False + #print('init output_shape:', output_shape) + if output_shape[1]==3309: + self.lmk_dim = 3 + self.lmk_num = 68 + self.mean_lmk = get_object('meanshape_68.pkl') + self.require_pose = True + else: + self.lmk_dim = 2 + self.lmk_num = output_shape[1]//self.lmk_dim + self.taskname = 'landmark_%dd_%d'%(self.lmk_dim, self.lmk_num) + + def prepare(self, ctx_id, **kwargs): + if ctx_id<0: + self.session.set_providers(['CPUExecutionProvider']) + + def get(self, img, face): + bbox = face.bbox + w, h = (bbox[2] - bbox[0]), (bbox[3] - bbox[1]) + center = (bbox[2] + bbox[0]) / 2, (bbox[3] + bbox[1]) / 2 + rotate = 0 + _scale = self.input_size[0] / (max(w, h)*1.5) + #print('param:', img.shape, bbox, center, self.input_size, _scale, rotate) + aimg, M = face_align.transform(img, center, self.input_size[0], _scale, rotate) + input_size = tuple(aimg.shape[0:2][::-1]) + #assert input_size==self.input_size + blob = cv2.dnn.blobFromImage(aimg, 1.0/self.input_std, input_size, (self.input_mean, self.input_mean, self.input_mean), swapRB=True) + pred = self.session.run(self.output_names, {self.input_name : blob})[0][0] + if pred.shape[0] >= 3000: + pred = pred.reshape((-1, 3)) + else: + pred = pred.reshape((-1, 2)) + if self.lmk_num < pred.shape[0]: + pred = pred[self.lmk_num*-1:,:] + pred[:, 0:2] += 1 + pred[:, 0:2] *= (self.input_size[0] // 2) + if pred.shape[1] == 3: + pred[:, 2] *= (self.input_size[0] // 2) + + IM = cv2.invertAffineTransform(M) + pred = face_align.trans_points(pred, IM) + face[self.taskname] = pred + if self.require_pose: + P = transform.estimate_affine_matrix_3d23d(self.mean_lmk, pred) + s, R, t = transform.P2sRt(P) + rx, ry, rz = transform.matrix2angle(R) + pose = np.array( [rx, ry, rz], dtype=np.float32 ) + face['pose'] = pose #pitch, yaw, roll + return pred + + diff --git a/liveportrait/utils/dependencies/insightface/model_zoo/model_store.py b/liveportrait/utils/dependencies/insightface/model_zoo/model_store.py new file mode 100644 index 0000000000000000000000000000000000000000..50bb85d314f5b7a0ea8211d2cd21186e32791592 --- /dev/null +++ b/liveportrait/utils/dependencies/insightface/model_zoo/model_store.py @@ -0,0 +1,103 @@ +""" +This code file mainly comes from https://github.com/dmlc/gluon-cv/blob/master/gluoncv/model_zoo/model_store.py +""" +from __future__ import print_function + +__all__ = ['get_model_file'] +import os +import zipfile +import glob + +from ..utils import download, check_sha1 + +_model_sha1 = { + name: checksum + for checksum, name in [ + ('95be21b58e29e9c1237f229dae534bd854009ce0', 'arcface_r100_v1'), + ('', 'arcface_mfn_v1'), + ('39fd1e087a2a2ed70a154ac01fecaa86c315d01b', 'retinaface_r50_v1'), + ('2c9de8116d1f448fd1d4661f90308faae34c990a', 'retinaface_mnet025_v1'), + ('0db1d07921d005e6c9a5b38e059452fc5645e5a4', 'retinaface_mnet025_v2'), + ('7dd8111652b7aac2490c5dcddeb268e53ac643e6', 'genderage_v1'), + ] +} + +base_repo_url = 'https://insightface.ai/files/' +_url_format = '{repo_url}models/{file_name}.zip' + + +def short_hash(name): + if name not in _model_sha1: + raise ValueError( + 'Pretrained model for {name} is not available.'.format(name=name)) + return _model_sha1[name][:8] + + +def find_params_file(dir_path): + if not os.path.exists(dir_path): + return None + paths = glob.glob("%s/*.params" % dir_path) + if len(paths) == 0: + return None + paths = sorted(paths) + return paths[-1] + + +def get_model_file(name, root=os.path.join('~', '.insightface', 'models')): + r"""Return location for the pretrained on local file system. + + This function will download from online model zoo when model cannot be found or has mismatch. + The root directory will be created if it doesn't exist. + + Parameters + ---------- + name : str + Name of the model. + root : str, default '~/.mxnet/models' + Location for keeping the model parameters. + + Returns + ------- + file_path + Path to the requested pretrained model file. + """ + + file_name = name + root = os.path.expanduser(root) + dir_path = os.path.join(root, name) + file_path = find_params_file(dir_path) + #file_path = os.path.join(root, file_name + '.params') + sha1_hash = _model_sha1[name] + if file_path is not None: + if check_sha1(file_path, sha1_hash): + return file_path + else: + print( + 'Mismatch in the content of model file detected. Downloading again.' + ) + else: + print('Model file is not found. Downloading.') + + if not os.path.exists(root): + os.makedirs(root) + if not os.path.exists(dir_path): + os.makedirs(dir_path) + + zip_file_path = os.path.join(root, file_name + '.zip') + repo_url = base_repo_url + if repo_url[-1] != '/': + repo_url = repo_url + '/' + download(_url_format.format(repo_url=repo_url, file_name=file_name), + path=zip_file_path, + overwrite=True) + with zipfile.ZipFile(zip_file_path) as zf: + zf.extractall(dir_path) + os.remove(zip_file_path) + file_path = find_params_file(dir_path) + + if check_sha1(file_path, sha1_hash): + return file_path + else: + raise ValueError( + 'Downloaded file has different hash. Please try again.') + diff --git a/liveportrait/utils/dependencies/insightface/model_zoo/model_zoo.py b/liveportrait/utils/dependencies/insightface/model_zoo/model_zoo.py new file mode 100644 index 0000000000000000000000000000000000000000..d8366e2a5461d5d6688f23e102a40944330084a4 --- /dev/null +++ b/liveportrait/utils/dependencies/insightface/model_zoo/model_zoo.py @@ -0,0 +1,97 @@ +# -*- coding: utf-8 -*- +# @Organization : insightface.ai +# @Author : Jia Guo +# @Time : 2021-05-04 +# @Function : + +import os +import os.path as osp +import glob +import onnxruntime +from .arcface_onnx import * +from .retinaface import * +#from .scrfd import * +from .landmark import * +from .attribute import Attribute +from .inswapper import INSwapper +from ..utils import download_onnx + +__all__ = ['get_model'] + + +class PickableInferenceSession(onnxruntime.InferenceSession): + # This is a wrapper to make the current InferenceSession class pickable. + def __init__(self, model_path, **kwargs): + super().__init__(model_path, **kwargs) + self.model_path = model_path + + def __getstate__(self): + return {'model_path': self.model_path} + + def __setstate__(self, values): + model_path = values['model_path'] + self.__init__(model_path) + +class ModelRouter: + def __init__(self, onnx_file): + self.onnx_file = onnx_file + + def get_model(self, **kwargs): + session = PickableInferenceSession(self.onnx_file, **kwargs) + # print(f'Applied providers: {session._providers}, with options: {session._provider_options}') + inputs = session.get_inputs() + input_cfg = inputs[0] + input_shape = input_cfg.shape + outputs = session.get_outputs() + + if len(outputs)>=5: + return RetinaFace(model_file=self.onnx_file, session=session) + elif input_shape[2]==192 and input_shape[3]==192: + return Landmark(model_file=self.onnx_file, session=session) + elif input_shape[2]==96 and input_shape[3]==96: + return Attribute(model_file=self.onnx_file, session=session) + elif len(inputs)==2 and input_shape[2]==128 and input_shape[3]==128: + return INSwapper(model_file=self.onnx_file, session=session) + elif input_shape[2]==input_shape[3] and input_shape[2]>=112 and input_shape[2]%16==0: + return ArcFaceONNX(model_file=self.onnx_file, session=session) + else: + #raise RuntimeError('error on model routing') + return None + +def find_onnx_file(dir_path): + if not os.path.exists(dir_path): + return None + paths = glob.glob("%s/*.onnx" % dir_path) + if len(paths) == 0: + return None + paths = sorted(paths) + return paths[-1] + +def get_default_providers(): + return ['CUDAExecutionProvider', 'CPUExecutionProvider'] + +def get_default_provider_options(): + return None + +def get_model(name, **kwargs): + root = kwargs.get('root', '~/.insightface') + root = os.path.expanduser(root) + model_root = osp.join(root, 'models') + allow_download = kwargs.get('download', False) + download_zip = kwargs.get('download_zip', False) + if not name.endswith('.onnx'): + model_dir = os.path.join(model_root, name) + model_file = find_onnx_file(model_dir) + if model_file is None: + return None + else: + model_file = name + if not osp.exists(model_file) and allow_download: + model_file = download_onnx('models', model_file, root=root, download_zip=download_zip) + assert osp.exists(model_file), 'model_file %s should exist'%model_file + assert osp.isfile(model_file), 'model_file %s should be a file'%model_file + router = ModelRouter(model_file) + providers = kwargs.get('providers', get_default_providers()) + provider_options = kwargs.get('provider_options', get_default_provider_options()) + model = router.get_model(providers=providers, provider_options=provider_options) + return model diff --git a/liveportrait/utils/dependencies/insightface/model_zoo/retinaface.py b/liveportrait/utils/dependencies/insightface/model_zoo/retinaface.py new file mode 100644 index 0000000000000000000000000000000000000000..fc4ad91ed70688b38503127137e928dc7e5433e1 --- /dev/null +++ b/liveportrait/utils/dependencies/insightface/model_zoo/retinaface.py @@ -0,0 +1,301 @@ +# -*- coding: utf-8 -*- +# @Organization : insightface.ai +# @Author : Jia Guo +# @Time : 2021-09-18 +# @Function : + +from __future__ import division +import datetime +import numpy as np +import onnx +import onnxruntime +import os +import os.path as osp +import cv2 +import sys + +def softmax(z): + assert len(z.shape) == 2 + s = np.max(z, axis=1) + s = s[:, np.newaxis] # necessary step to do broadcasting + e_x = np.exp(z - s) + div = np.sum(e_x, axis=1) + div = div[:, np.newaxis] # dito + return e_x / div + +def distance2bbox(points, distance, max_shape=None): + """Decode distance prediction to bounding box. + + Args: + points (Tensor): Shape (n, 2), [x, y]. + distance (Tensor): Distance from the given point to 4 + boundaries (left, top, right, bottom). + max_shape (tuple): Shape of the image. + + Returns: + Tensor: Decoded bboxes. + """ + x1 = points[:, 0] - distance[:, 0] + y1 = points[:, 1] - distance[:, 1] + x2 = points[:, 0] + distance[:, 2] + y2 = points[:, 1] + distance[:, 3] + if max_shape is not None: + x1 = x1.clamp(min=0, max=max_shape[1]) + y1 = y1.clamp(min=0, max=max_shape[0]) + x2 = x2.clamp(min=0, max=max_shape[1]) + y2 = y2.clamp(min=0, max=max_shape[0]) + return np.stack([x1, y1, x2, y2], axis=-1) + +def distance2kps(points, distance, max_shape=None): + """Decode distance prediction to bounding box. + + Args: + points (Tensor): Shape (n, 2), [x, y]. + distance (Tensor): Distance from the given point to 4 + boundaries (left, top, right, bottom). + max_shape (tuple): Shape of the image. + + Returns: + Tensor: Decoded bboxes. + """ + preds = [] + for i in range(0, distance.shape[1], 2): + px = points[:, i%2] + distance[:, i] + py = points[:, i%2+1] + distance[:, i+1] + if max_shape is not None: + px = px.clamp(min=0, max=max_shape[1]) + py = py.clamp(min=0, max=max_shape[0]) + preds.append(px) + preds.append(py) + return np.stack(preds, axis=-1) + +class RetinaFace: + def __init__(self, model_file=None, session=None): + import onnxruntime + self.model_file = model_file + self.session = session + self.taskname = 'detection' + if self.session is None: + assert self.model_file is not None + assert osp.exists(self.model_file) + self.session = onnxruntime.InferenceSession(self.model_file, None) + self.center_cache = {} + self.nms_thresh = 0.4 + self.det_thresh = 0.5 + self._init_vars() + + def _init_vars(self): + input_cfg = self.session.get_inputs()[0] + input_shape = input_cfg.shape + #print(input_shape) + if isinstance(input_shape[2], str): + self.input_size = None + else: + self.input_size = tuple(input_shape[2:4][::-1]) + #print('image_size:', self.image_size) + input_name = input_cfg.name + self.input_shape = input_shape + outputs = self.session.get_outputs() + output_names = [] + for o in outputs: + output_names.append(o.name) + self.input_name = input_name + self.output_names = output_names + self.input_mean = 127.5 + self.input_std = 128.0 + #print(self.output_names) + #assert len(outputs)==10 or len(outputs)==15 + self.use_kps = False + self._anchor_ratio = 1.0 + self._num_anchors = 1 + if len(outputs)==6: + self.fmc = 3 + self._feat_stride_fpn = [8, 16, 32] + self._num_anchors = 2 + elif len(outputs)==9: + self.fmc = 3 + self._feat_stride_fpn = [8, 16, 32] + self._num_anchors = 2 + self.use_kps = True + elif len(outputs)==10: + self.fmc = 5 + self._feat_stride_fpn = [8, 16, 32, 64, 128] + self._num_anchors = 1 + elif len(outputs)==15: + self.fmc = 5 + self._feat_stride_fpn = [8, 16, 32, 64, 128] + self._num_anchors = 1 + self.use_kps = True + + def prepare(self, ctx_id, **kwargs): + if ctx_id<0: + self.session.set_providers(['CPUExecutionProvider']) + nms_thresh = kwargs.get('nms_thresh', None) + if nms_thresh is not None: + self.nms_thresh = nms_thresh + det_thresh = kwargs.get('det_thresh', None) + if det_thresh is not None: + self.det_thresh = det_thresh + input_size = kwargs.get('input_size', None) + if input_size is not None: + if self.input_size is not None: + print('warning: det_size is already set in detection model, ignore') + else: + self.input_size = input_size + + def forward(self, img, threshold): + scores_list = [] + bboxes_list = [] + kpss_list = [] + input_size = tuple(img.shape[0:2][::-1]) + blob = cv2.dnn.blobFromImage(img, 1.0/self.input_std, input_size, (self.input_mean, self.input_mean, self.input_mean), swapRB=True) + net_outs = self.session.run(self.output_names, {self.input_name : blob}) + + input_height = blob.shape[2] + input_width = blob.shape[3] + fmc = self.fmc + for idx, stride in enumerate(self._feat_stride_fpn): + scores = net_outs[idx] + bbox_preds = net_outs[idx+fmc] + bbox_preds = bbox_preds * stride + if self.use_kps: + kps_preds = net_outs[idx+fmc*2] * stride + height = input_height // stride + width = input_width // stride + K = height * width + key = (height, width, stride) + if key in self.center_cache: + anchor_centers = self.center_cache[key] + else: + #solution-1, c style: + #anchor_centers = np.zeros( (height, width, 2), dtype=np.float32 ) + #for i in range(height): + # anchor_centers[i, :, 1] = i + #for i in range(width): + # anchor_centers[:, i, 0] = i + + #solution-2: + #ax = np.arange(width, dtype=np.float32) + #ay = np.arange(height, dtype=np.float32) + #xv, yv = np.meshgrid(np.arange(width), np.arange(height)) + #anchor_centers = np.stack([xv, yv], axis=-1).astype(np.float32) + + #solution-3: + anchor_centers = np.stack(np.mgrid[:height, :width][::-1], axis=-1).astype(np.float32) + #print(anchor_centers.shape) + + anchor_centers = (anchor_centers * stride).reshape( (-1, 2) ) + if self._num_anchors>1: + anchor_centers = np.stack([anchor_centers]*self._num_anchors, axis=1).reshape( (-1,2) ) + if len(self.center_cache)<100: + self.center_cache[key] = anchor_centers + + pos_inds = np.where(scores>=threshold)[0] + bboxes = distance2bbox(anchor_centers, bbox_preds) + pos_scores = scores[pos_inds] + pos_bboxes = bboxes[pos_inds] + scores_list.append(pos_scores) + bboxes_list.append(pos_bboxes) + if self.use_kps: + kpss = distance2kps(anchor_centers, kps_preds) + #kpss = kps_preds + kpss = kpss.reshape( (kpss.shape[0], -1, 2) ) + pos_kpss = kpss[pos_inds] + kpss_list.append(pos_kpss) + return scores_list, bboxes_list, kpss_list + + def detect(self, img, input_size = None, max_num=0, metric='default'): + assert input_size is not None or self.input_size is not None + input_size = self.input_size if input_size is None else input_size + + im_ratio = float(img.shape[0]) / img.shape[1] + model_ratio = float(input_size[1]) / input_size[0] + if im_ratio>model_ratio: + new_height = input_size[1] + new_width = int(new_height / im_ratio) + else: + new_width = input_size[0] + new_height = int(new_width * im_ratio) + det_scale = float(new_height) / img.shape[0] + resized_img = cv2.resize(img, (new_width, new_height)) + det_img = np.zeros( (input_size[1], input_size[0], 3), dtype=np.uint8 ) + det_img[:new_height, :new_width, :] = resized_img + + scores_list, bboxes_list, kpss_list = self.forward(det_img, self.det_thresh) + + scores = np.vstack(scores_list) + scores_ravel = scores.ravel() + order = scores_ravel.argsort()[::-1] + bboxes = np.vstack(bboxes_list) / det_scale + if self.use_kps: + kpss = np.vstack(kpss_list) / det_scale + pre_det = np.hstack((bboxes, scores)).astype(np.float32, copy=False) + pre_det = pre_det[order, :] + keep = self.nms(pre_det) + det = pre_det[keep, :] + if self.use_kps: + kpss = kpss[order,:,:] + kpss = kpss[keep,:,:] + else: + kpss = None + if max_num > 0 and det.shape[0] > max_num: + area = (det[:, 2] - det[:, 0]) * (det[:, 3] - + det[:, 1]) + img_center = img.shape[0] // 2, img.shape[1] // 2 + offsets = np.vstack([ + (det[:, 0] + det[:, 2]) / 2 - img_center[1], + (det[:, 1] + det[:, 3]) / 2 - img_center[0] + ]) + offset_dist_squared = np.sum(np.power(offsets, 2.0), 0) + if metric=='max': + values = area + else: + values = area - offset_dist_squared * 2.0 # some extra weight on the centering + bindex = np.argsort( + values)[::-1] # some extra weight on the centering + bindex = bindex[0:max_num] + det = det[bindex, :] + if kpss is not None: + kpss = kpss[bindex, :] + return det, kpss + + def nms(self, dets): + thresh = self.nms_thresh + x1 = dets[:, 0] + y1 = dets[:, 1] + x2 = dets[:, 2] + y2 = dets[:, 3] + scores = dets[:, 4] + + areas = (x2 - x1 + 1) * (y2 - y1 + 1) + order = scores.argsort()[::-1] + + keep = [] + while order.size > 0: + i = order[0] + keep.append(i) + xx1 = np.maximum(x1[i], x1[order[1:]]) + yy1 = np.maximum(y1[i], y1[order[1:]]) + xx2 = np.minimum(x2[i], x2[order[1:]]) + yy2 = np.minimum(y2[i], y2[order[1:]]) + + w = np.maximum(0.0, xx2 - xx1 + 1) + h = np.maximum(0.0, yy2 - yy1 + 1) + inter = w * h + ovr = inter / (areas[i] + areas[order[1:]] - inter) + + inds = np.where(ovr <= thresh)[0] + order = order[inds + 1] + + return keep + +def get_retinaface(name, download=False, root='~/.insightface/models', **kwargs): + if not download: + assert os.path.exists(name) + return RetinaFace(name) + else: + from .model_store import get_model_file + _file = get_model_file("retinaface_%s" % name, root=root) + return retinaface(_file) + + diff --git a/liveportrait/utils/dependencies/insightface/model_zoo/scrfd.py b/liveportrait/utils/dependencies/insightface/model_zoo/scrfd.py new file mode 100644 index 0000000000000000000000000000000000000000..674db4bba761157592dfb95c5d1638da1099f89c --- /dev/null +++ b/liveportrait/utils/dependencies/insightface/model_zoo/scrfd.py @@ -0,0 +1,348 @@ +# -*- coding: utf-8 -*- +# @Organization : insightface.ai +# @Author : Jia Guo +# @Time : 2021-05-04 +# @Function : + +from __future__ import division +import datetime +import numpy as np +import onnx +import onnxruntime +import os +import os.path as osp +import cv2 +import sys + +def softmax(z): + assert len(z.shape) == 2 + s = np.max(z, axis=1) + s = s[:, np.newaxis] # necessary step to do broadcasting + e_x = np.exp(z - s) + div = np.sum(e_x, axis=1) + div = div[:, np.newaxis] # dito + return e_x / div + +def distance2bbox(points, distance, max_shape=None): + """Decode distance prediction to bounding box. + + Args: + points (Tensor): Shape (n, 2), [x, y]. + distance (Tensor): Distance from the given point to 4 + boundaries (left, top, right, bottom). + max_shape (tuple): Shape of the image. + + Returns: + Tensor: Decoded bboxes. + """ + x1 = points[:, 0] - distance[:, 0] + y1 = points[:, 1] - distance[:, 1] + x2 = points[:, 0] + distance[:, 2] + y2 = points[:, 1] + distance[:, 3] + if max_shape is not None: + x1 = x1.clamp(min=0, max=max_shape[1]) + y1 = y1.clamp(min=0, max=max_shape[0]) + x2 = x2.clamp(min=0, max=max_shape[1]) + y2 = y2.clamp(min=0, max=max_shape[0]) + return np.stack([x1, y1, x2, y2], axis=-1) + +def distance2kps(points, distance, max_shape=None): + """Decode distance prediction to bounding box. + + Args: + points (Tensor): Shape (n, 2), [x, y]. + distance (Tensor): Distance from the given point to 4 + boundaries (left, top, right, bottom). + max_shape (tuple): Shape of the image. + + Returns: + Tensor: Decoded bboxes. + """ + preds = [] + for i in range(0, distance.shape[1], 2): + px = points[:, i%2] + distance[:, i] + py = points[:, i%2+1] + distance[:, i+1] + if max_shape is not None: + px = px.clamp(min=0, max=max_shape[1]) + py = py.clamp(min=0, max=max_shape[0]) + preds.append(px) + preds.append(py) + return np.stack(preds, axis=-1) + +class SCRFD: + def __init__(self, model_file=None, session=None): + import onnxruntime + self.model_file = model_file + self.session = session + self.taskname = 'detection' + self.batched = False + if self.session is None: + assert self.model_file is not None + assert osp.exists(self.model_file) + self.session = onnxruntime.InferenceSession(self.model_file, None) + self.center_cache = {} + self.nms_thresh = 0.4 + self.det_thresh = 0.5 + self._init_vars() + + def _init_vars(self): + input_cfg = self.session.get_inputs()[0] + input_shape = input_cfg.shape + #print(input_shape) + if isinstance(input_shape[2], str): + self.input_size = None + else: + self.input_size = tuple(input_shape[2:4][::-1]) + #print('image_size:', self.image_size) + input_name = input_cfg.name + self.input_shape = input_shape + outputs = self.session.get_outputs() + if len(outputs[0].shape) == 3: + self.batched = True + output_names = [] + for o in outputs: + output_names.append(o.name) + self.input_name = input_name + self.output_names = output_names + self.input_mean = 127.5 + self.input_std = 128.0 + #print(self.output_names) + #assert len(outputs)==10 or len(outputs)==15 + self.use_kps = False + self._anchor_ratio = 1.0 + self._num_anchors = 1 + if len(outputs)==6: + self.fmc = 3 + self._feat_stride_fpn = [8, 16, 32] + self._num_anchors = 2 + elif len(outputs)==9: + self.fmc = 3 + self._feat_stride_fpn = [8, 16, 32] + self._num_anchors = 2 + self.use_kps = True + elif len(outputs)==10: + self.fmc = 5 + self._feat_stride_fpn = [8, 16, 32, 64, 128] + self._num_anchors = 1 + elif len(outputs)==15: + self.fmc = 5 + self._feat_stride_fpn = [8, 16, 32, 64, 128] + self._num_anchors = 1 + self.use_kps = True + + def prepare(self, ctx_id, **kwargs): + if ctx_id<0: + self.session.set_providers(['CPUExecutionProvider']) + nms_thresh = kwargs.get('nms_thresh', None) + if nms_thresh is not None: + self.nms_thresh = nms_thresh + det_thresh = kwargs.get('det_thresh', None) + if det_thresh is not None: + self.det_thresh = det_thresh + input_size = kwargs.get('input_size', None) + if input_size is not None: + if self.input_size is not None: + print('warning: det_size is already set in scrfd model, ignore') + else: + self.input_size = input_size + + def forward(self, img, threshold): + scores_list = [] + bboxes_list = [] + kpss_list = [] + input_size = tuple(img.shape[0:2][::-1]) + blob = cv2.dnn.blobFromImage(img, 1.0/self.input_std, input_size, (self.input_mean, self.input_mean, self.input_mean), swapRB=True) + net_outs = self.session.run(self.output_names, {self.input_name : blob}) + + input_height = blob.shape[2] + input_width = blob.shape[3] + fmc = self.fmc + for idx, stride in enumerate(self._feat_stride_fpn): + # If model support batch dim, take first output + if self.batched: + scores = net_outs[idx][0] + bbox_preds = net_outs[idx + fmc][0] + bbox_preds = bbox_preds * stride + if self.use_kps: + kps_preds = net_outs[idx + fmc * 2][0] * stride + # If model doesn't support batching take output as is + else: + scores = net_outs[idx] + bbox_preds = net_outs[idx + fmc] + bbox_preds = bbox_preds * stride + if self.use_kps: + kps_preds = net_outs[idx + fmc * 2] * stride + + height = input_height // stride + width = input_width // stride + K = height * width + key = (height, width, stride) + if key in self.center_cache: + anchor_centers = self.center_cache[key] + else: + #solution-1, c style: + #anchor_centers = np.zeros( (height, width, 2), dtype=np.float32 ) + #for i in range(height): + # anchor_centers[i, :, 1] = i + #for i in range(width): + # anchor_centers[:, i, 0] = i + + #solution-2: + #ax = np.arange(width, dtype=np.float32) + #ay = np.arange(height, dtype=np.float32) + #xv, yv = np.meshgrid(np.arange(width), np.arange(height)) + #anchor_centers = np.stack([xv, yv], axis=-1).astype(np.float32) + + #solution-3: + anchor_centers = np.stack(np.mgrid[:height, :width][::-1], axis=-1).astype(np.float32) + #print(anchor_centers.shape) + + anchor_centers = (anchor_centers * stride).reshape( (-1, 2) ) + if self._num_anchors>1: + anchor_centers = np.stack([anchor_centers]*self._num_anchors, axis=1).reshape( (-1,2) ) + if len(self.center_cache)<100: + self.center_cache[key] = anchor_centers + + pos_inds = np.where(scores>=threshold)[0] + bboxes = distance2bbox(anchor_centers, bbox_preds) + pos_scores = scores[pos_inds] + pos_bboxes = bboxes[pos_inds] + scores_list.append(pos_scores) + bboxes_list.append(pos_bboxes) + if self.use_kps: + kpss = distance2kps(anchor_centers, kps_preds) + #kpss = kps_preds + kpss = kpss.reshape( (kpss.shape[0], -1, 2) ) + pos_kpss = kpss[pos_inds] + kpss_list.append(pos_kpss) + return scores_list, bboxes_list, kpss_list + + def detect(self, img, input_size = None, max_num=0, metric='default'): + assert input_size is not None or self.input_size is not None + input_size = self.input_size if input_size is None else input_size + + im_ratio = float(img.shape[0]) / img.shape[1] + model_ratio = float(input_size[1]) / input_size[0] + if im_ratio>model_ratio: + new_height = input_size[1] + new_width = int(new_height / im_ratio) + else: + new_width = input_size[0] + new_height = int(new_width * im_ratio) + det_scale = float(new_height) / img.shape[0] + resized_img = cv2.resize(img, (new_width, new_height)) + det_img = np.zeros( (input_size[1], input_size[0], 3), dtype=np.uint8 ) + det_img[:new_height, :new_width, :] = resized_img + + scores_list, bboxes_list, kpss_list = self.forward(det_img, self.det_thresh) + + scores = np.vstack(scores_list) + scores_ravel = scores.ravel() + order = scores_ravel.argsort()[::-1] + bboxes = np.vstack(bboxes_list) / det_scale + if self.use_kps: + kpss = np.vstack(kpss_list) / det_scale + pre_det = np.hstack((bboxes, scores)).astype(np.float32, copy=False) + pre_det = pre_det[order, :] + keep = self.nms(pre_det) + det = pre_det[keep, :] + if self.use_kps: + kpss = kpss[order,:,:] + kpss = kpss[keep,:,:] + else: + kpss = None + if max_num > 0 and det.shape[0] > max_num: + area = (det[:, 2] - det[:, 0]) * (det[:, 3] - + det[:, 1]) + img_center = img.shape[0] // 2, img.shape[1] // 2 + offsets = np.vstack([ + (det[:, 0] + det[:, 2]) / 2 - img_center[1], + (det[:, 1] + det[:, 3]) / 2 - img_center[0] + ]) + offset_dist_squared = np.sum(np.power(offsets, 2.0), 0) + if metric=='max': + values = area + else: + values = area - offset_dist_squared * 2.0 # some extra weight on the centering + bindex = np.argsort( + values)[::-1] # some extra weight on the centering + bindex = bindex[0:max_num] + det = det[bindex, :] + if kpss is not None: + kpss = kpss[bindex, :] + return det, kpss + + def nms(self, dets): + thresh = self.nms_thresh + x1 = dets[:, 0] + y1 = dets[:, 1] + x2 = dets[:, 2] + y2 = dets[:, 3] + scores = dets[:, 4] + + areas = (x2 - x1 + 1) * (y2 - y1 + 1) + order = scores.argsort()[::-1] + + keep = [] + while order.size > 0: + i = order[0] + keep.append(i) + xx1 = np.maximum(x1[i], x1[order[1:]]) + yy1 = np.maximum(y1[i], y1[order[1:]]) + xx2 = np.minimum(x2[i], x2[order[1:]]) + yy2 = np.minimum(y2[i], y2[order[1:]]) + + w = np.maximum(0.0, xx2 - xx1 + 1) + h = np.maximum(0.0, yy2 - yy1 + 1) + inter = w * h + ovr = inter / (areas[i] + areas[order[1:]] - inter) + + inds = np.where(ovr <= thresh)[0] + order = order[inds + 1] + + return keep + +def get_scrfd(name, download=False, root='~/.insightface/models', **kwargs): + if not download: + assert os.path.exists(name) + return SCRFD(name) + else: + from .model_store import get_model_file + _file = get_model_file("scrfd_%s" % name, root=root) + return SCRFD(_file) + + +def scrfd_2p5gkps(**kwargs): + return get_scrfd("2p5gkps", download=True, **kwargs) + + +if __name__ == '__main__': + import glob + detector = SCRFD(model_file='./det.onnx') + detector.prepare(-1) + img_paths = ['tests/data/t1.jpg'] + for img_path in img_paths: + img = cv2.imread(img_path) + + for _ in range(1): + ta = datetime.datetime.now() + #bboxes, kpss = detector.detect(img, 0.5, input_size = (640, 640)) + bboxes, kpss = detector.detect(img, 0.5) + tb = datetime.datetime.now() + print('all cost:', (tb-ta).total_seconds()*1000) + print(img_path, bboxes.shape) + if kpss is not None: + print(kpss.shape) + for i in range(bboxes.shape[0]): + bbox = bboxes[i] + x1,y1,x2,y2,score = bbox.astype(np.int) + cv2.rectangle(img, (x1,y1) , (x2,y2) , (255,0,0) , 2) + if kpss is not None: + kps = kpss[i] + for kp in kps: + kp = kp.astype(np.int) + cv2.circle(img, tuple(kp) , 1, (0,0,255) , 2) + filename = img_path.split('/')[-1] + print('output:', filename) + cv2.imwrite('./outputs/%s'%filename, img) + diff --git a/liveportrait/utils/dependencies/insightface/utils/__init__.py b/liveportrait/utils/dependencies/insightface/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6960431b1bd6db38890e391c4c94dd2182f2e1fd --- /dev/null +++ b/liveportrait/utils/dependencies/insightface/utils/__init__.py @@ -0,0 +1,6 @@ +from __future__ import absolute_import + +from .storage import download, ensure_available, download_onnx +from .filesystem import get_model_dir +from .filesystem import makedirs, try_import_dali +from .constant import * diff --git a/liveportrait/utils/dependencies/insightface/utils/constant.py b/liveportrait/utils/dependencies/insightface/utils/constant.py new file mode 100644 index 0000000000000000000000000000000000000000..8860ff077ae7227235591edfc84c0cdc227a6432 --- /dev/null +++ b/liveportrait/utils/dependencies/insightface/utils/constant.py @@ -0,0 +1,3 @@ + +DEFAULT_MP_NAME = 'buffalo_l' + diff --git a/liveportrait/utils/dependencies/insightface/utils/download.py b/liveportrait/utils/dependencies/insightface/utils/download.py new file mode 100644 index 0000000000000000000000000000000000000000..5cda84dede45b81dcd99161d87792b6c409fa279 --- /dev/null +++ b/liveportrait/utils/dependencies/insightface/utils/download.py @@ -0,0 +1,95 @@ +""" +This code file mainly comes from https://github.com/dmlc/gluon-cv/blob/master/gluoncv/utils/download.py +""" +import os +import hashlib +import requests +from tqdm import tqdm + + +def check_sha1(filename, sha1_hash): + """Check whether the sha1 hash of the file content matches the expected hash. + Parameters + ---------- + filename : str + Path to the file. + sha1_hash : str + Expected sha1 hash in hexadecimal digits. + Returns + ------- + bool + Whether the file content matches the expected hash. + """ + sha1 = hashlib.sha1() + with open(filename, 'rb') as f: + while True: + data = f.read(1048576) + if not data: + break + sha1.update(data) + + sha1_file = sha1.hexdigest() + l = min(len(sha1_file), len(sha1_hash)) + return sha1.hexdigest()[0:l] == sha1_hash[0:l] + + +def download_file(url, path=None, overwrite=False, sha1_hash=None): + """Download an given URL + Parameters + ---------- + url : str + URL to download + path : str, optional + Destination path to store downloaded file. By default stores to the + current directory with same name as in url. + overwrite : bool, optional + Whether to overwrite destination file if already exists. + sha1_hash : str, optional + Expected sha1 hash in hexadecimal digits. Will ignore existing file when hash is specified + but doesn't match. + Returns + ------- + str + The file path of the downloaded file. + """ + if path is None: + fname = url.split('/')[-1] + else: + path = os.path.expanduser(path) + if os.path.isdir(path): + fname = os.path.join(path, url.split('/')[-1]) + else: + fname = path + + if overwrite or not os.path.exists(fname) or ( + sha1_hash and not check_sha1(fname, sha1_hash)): + dirname = os.path.dirname(os.path.abspath(os.path.expanduser(fname))) + if not os.path.exists(dirname): + os.makedirs(dirname) + + print('Downloading %s from %s...' % (fname, url)) + r = requests.get(url, stream=True) + if r.status_code != 200: + raise RuntimeError("Failed downloading url %s" % url) + total_length = r.headers.get('content-length') + with open(fname, 'wb') as f: + if total_length is None: # no content length header + for chunk in r.iter_content(chunk_size=1024): + if chunk: # filter out keep-alive new chunks + f.write(chunk) + else: + total_length = int(total_length) + for chunk in tqdm(r.iter_content(chunk_size=1024), + total=int(total_length / 1024. + 0.5), + unit='KB', + unit_scale=False, + dynamic_ncols=True): + f.write(chunk) + + if sha1_hash and not check_sha1(fname, sha1_hash): + raise UserWarning('File {} is downloaded but the content hash does not match. ' \ + 'The repo may be outdated or download may be incomplete. ' \ + 'If the "repo_url" is overridden, consider switching to ' \ + 'the default repo.'.format(fname)) + + return fname diff --git a/liveportrait/utils/dependencies/insightface/utils/face_align.py b/liveportrait/utils/dependencies/insightface/utils/face_align.py new file mode 100644 index 0000000000000000000000000000000000000000..226628b39cf743947df230feffbb97bf5c585e1d --- /dev/null +++ b/liveportrait/utils/dependencies/insightface/utils/face_align.py @@ -0,0 +1,103 @@ +import cv2 +import numpy as np +from skimage import transform as trans + + +arcface_dst = np.array( + [[38.2946, 51.6963], [73.5318, 51.5014], [56.0252, 71.7366], + [41.5493, 92.3655], [70.7299, 92.2041]], + dtype=np.float32) + +def estimate_norm(lmk, image_size=112,mode='arcface'): + assert lmk.shape == (5, 2) + assert image_size%112==0 or image_size%128==0 + if image_size%112==0: + ratio = float(image_size)/112.0 + diff_x = 0 + else: + ratio = float(image_size)/128.0 + diff_x = 8.0*ratio + dst = arcface_dst * ratio + dst[:,0] += diff_x + tform = trans.SimilarityTransform() + tform.estimate(lmk, dst) + M = tform.params[0:2, :] + return M + +def norm_crop(img, landmark, image_size=112, mode='arcface'): + M = estimate_norm(landmark, image_size, mode) + warped = cv2.warpAffine(img, M, (image_size, image_size), borderValue=0.0) + return warped + +def norm_crop2(img, landmark, image_size=112, mode='arcface'): + M = estimate_norm(landmark, image_size, mode) + warped = cv2.warpAffine(img, M, (image_size, image_size), borderValue=0.0) + return warped, M + +def square_crop(im, S): + if im.shape[0] > im.shape[1]: + height = S + width = int(float(im.shape[1]) / im.shape[0] * S) + scale = float(S) / im.shape[0] + else: + width = S + height = int(float(im.shape[0]) / im.shape[1] * S) + scale = float(S) / im.shape[1] + resized_im = cv2.resize(im, (width, height)) + det_im = np.zeros((S, S, 3), dtype=np.uint8) + det_im[:resized_im.shape[0], :resized_im.shape[1], :] = resized_im + return det_im, scale + + +def transform(data, center, output_size, scale, rotation): + scale_ratio = scale + rot = float(rotation) * np.pi / 180.0 + #translation = (output_size/2-center[0]*scale_ratio, output_size/2-center[1]*scale_ratio) + t1 = trans.SimilarityTransform(scale=scale_ratio) + cx = center[0] * scale_ratio + cy = center[1] * scale_ratio + t2 = trans.SimilarityTransform(translation=(-1 * cx, -1 * cy)) + t3 = trans.SimilarityTransform(rotation=rot) + t4 = trans.SimilarityTransform(translation=(output_size / 2, + output_size / 2)) + t = t1 + t2 + t3 + t4 + M = t.params[0:2] + cropped = cv2.warpAffine(data, + M, (output_size, output_size), + borderValue=0.0) + return cropped, M + + +def trans_points2d(pts, M): + new_pts = np.zeros(shape=pts.shape, dtype=np.float32) + for i in range(pts.shape[0]): + pt = pts[i] + new_pt = np.array([pt[0], pt[1], 1.], dtype=np.float32) + new_pt = np.dot(M, new_pt) + #print('new_pt', new_pt.shape, new_pt) + new_pts[i] = new_pt[0:2] + + return new_pts + + +def trans_points3d(pts, M): + scale = np.sqrt(M[0][0] * M[0][0] + M[0][1] * M[0][1]) + #print(scale) + new_pts = np.zeros(shape=pts.shape, dtype=np.float32) + for i in range(pts.shape[0]): + pt = pts[i] + new_pt = np.array([pt[0], pt[1], 1.], dtype=np.float32) + new_pt = np.dot(M, new_pt) + #print('new_pt', new_pt.shape, new_pt) + new_pts[i][0:2] = new_pt[0:2] + new_pts[i][2] = pts[i][2] * scale + + return new_pts + + +def trans_points(pts, M): + if pts.shape[1] == 2: + return trans_points2d(pts, M) + else: + return trans_points3d(pts, M) + diff --git a/liveportrait/utils/dependencies/insightface/utils/filesystem.py b/liveportrait/utils/dependencies/insightface/utils/filesystem.py new file mode 100644 index 0000000000000000000000000000000000000000..01e3851975bdcbbf7f5eeb7e68e70a36dc040535 --- /dev/null +++ b/liveportrait/utils/dependencies/insightface/utils/filesystem.py @@ -0,0 +1,157 @@ +""" +This code file mainly comes from https://github.com/dmlc/gluon-cv/blob/master/gluoncv/utils/filesystem.py +""" +import os +import os.path as osp +import errno + + +def get_model_dir(name, root='~/.insightface'): + root = os.path.expanduser(root) + model_dir = osp.join(root, 'models', name) + return model_dir + +def makedirs(path): + """Create directory recursively if not exists. + Similar to `makedir -p`, you can skip checking existence before this function. + + Parameters + ---------- + path : str + Path of the desired dir + """ + try: + os.makedirs(path) + except OSError as exc: + if exc.errno != errno.EEXIST: + raise + + +def try_import(package, message=None): + """Try import specified package, with custom message support. + + Parameters + ---------- + package : str + The name of the targeting package. + message : str, default is None + If not None, this function will raise customized error message when import error is found. + + + Returns + ------- + module if found, raise ImportError otherwise + + """ + try: + return __import__(package) + except ImportError as e: + if not message: + raise e + raise ImportError(message) + + +def try_import_cv2(): + """Try import cv2 at runtime. + + Returns + ------- + cv2 module if found. Raise ImportError otherwise + + """ + msg = "cv2 is required, you can install by package manager, e.g. 'apt-get', \ + or `pip install opencv-python --user` (note that this is unofficial PYPI package)." + + return try_import('cv2', msg) + + +def try_import_mmcv(): + """Try import mmcv at runtime. + + Returns + ------- + mmcv module if found. Raise ImportError otherwise + + """ + msg = "mmcv is required, you can install by first `pip install Cython --user` \ + and then `pip install mmcv --user` (note that this is unofficial PYPI package)." + + return try_import('mmcv', msg) + + +def try_import_rarfile(): + """Try import rarfile at runtime. + + Returns + ------- + rarfile module if found. Raise ImportError otherwise + + """ + msg = "rarfile is required, you can install by first `sudo apt-get install unrar` \ + and then `pip install rarfile --user` (note that this is unofficial PYPI package)." + + return try_import('rarfile', msg) + + +def import_try_install(package, extern_url=None): + """Try import the specified package. + If the package not installed, try use pip to install and import if success. + + Parameters + ---------- + package : str + The name of the package trying to import. + extern_url : str or None, optional + The external url if package is not hosted on PyPI. + For example, you can install a package using: + "pip install git+http://github.com/user/repo/tarball/master/egginfo=xxx". + In this case, you can pass the url to the extern_url. + + Returns + ------- + <class 'Module'> + The imported python module. + + """ + try: + return __import__(package) + except ImportError: + try: + from pip import main as pipmain + except ImportError: + from pip._internal import main as pipmain + + # trying to install package + url = package if extern_url is None else extern_url + pipmain(['install', '--user', + url]) # will raise SystemExit Error if fails + + # trying to load again + try: + return __import__(package) + except ImportError: + import sys + import site + user_site = site.getusersitepackages() + if user_site not in sys.path: + sys.path.append(user_site) + return __import__(package) + return __import__(package) + + +def try_import_dali(): + """Try import NVIDIA DALI at runtime. + """ + try: + dali = __import__('nvidia.dali', fromlist=['pipeline', 'ops', 'types']) + dali.Pipeline = dali.pipeline.Pipeline + except ImportError: + + class dali: + class Pipeline: + def __init__(self): + raise NotImplementedError( + "DALI not found, please check if you installed it correctly." + ) + + return dali diff --git a/liveportrait/utils/dependencies/insightface/utils/storage.py b/liveportrait/utils/dependencies/insightface/utils/storage.py new file mode 100644 index 0000000000000000000000000000000000000000..5bf37e2d17b28dee2a8839484778815f87fc4a9c --- /dev/null +++ b/liveportrait/utils/dependencies/insightface/utils/storage.py @@ -0,0 +1,52 @@ + +import os +import os.path as osp +import zipfile +from .download import download_file + +BASE_REPO_URL = 'https://github.com/deepinsight/insightface/releases/download/v0.7' + +def download(sub_dir, name, force=False, root='~/.insightface'): + _root = os.path.expanduser(root) + dir_path = os.path.join(_root, sub_dir, name) + if osp.exists(dir_path) and not force: + return dir_path + print('download_path:', dir_path) + zip_file_path = os.path.join(_root, sub_dir, name + '.zip') + model_url = "%s/%s.zip"%(BASE_REPO_URL, name) + download_file(model_url, + path=zip_file_path, + overwrite=True) + if not os.path.exists(dir_path): + os.makedirs(dir_path) + with zipfile.ZipFile(zip_file_path) as zf: + zf.extractall(dir_path) + #os.remove(zip_file_path) + return dir_path + +def ensure_available(sub_dir, name, root='~/.insightface'): + return download(sub_dir, name, force=False, root=root) + +def download_onnx(sub_dir, model_file, force=False, root='~/.insightface', download_zip=False): + _root = os.path.expanduser(root) + model_root = osp.join(_root, sub_dir) + new_model_file = osp.join(model_root, model_file) + if osp.exists(new_model_file) and not force: + return new_model_file + if not osp.exists(model_root): + os.makedirs(model_root) + print('download_path:', new_model_file) + if not download_zip: + model_url = "%s/%s"%(BASE_REPO_URL, model_file) + download_file(model_url, + path=new_model_file, + overwrite=True) + else: + model_url = "%s/%s.zip"%(BASE_REPO_URL, model_file) + zip_file_path = new_model_file+".zip" + download_file(model_url, + path=zip_file_path, + overwrite=True) + with zipfile.ZipFile(zip_file_path) as zf: + zf.extractall(model_root) + return new_model_file diff --git a/liveportrait/utils/dependencies/insightface/utils/transform.py b/liveportrait/utils/dependencies/insightface/utils/transform.py new file mode 100644 index 0000000000000000000000000000000000000000..06531d257b694211a0b9a09c9d741b9b2ff53bfe --- /dev/null +++ b/liveportrait/utils/dependencies/insightface/utils/transform.py @@ -0,0 +1,116 @@ +import cv2 +import math +import numpy as np +from skimage import transform as trans + + +def transform(data, center, output_size, scale, rotation): + scale_ratio = scale + rot = float(rotation) * np.pi / 180.0 + #translation = (output_size/2-center[0]*scale_ratio, output_size/2-center[1]*scale_ratio) + t1 = trans.SimilarityTransform(scale=scale_ratio) + cx = center[0] * scale_ratio + cy = center[1] * scale_ratio + t2 = trans.SimilarityTransform(translation=(-1 * cx, -1 * cy)) + t3 = trans.SimilarityTransform(rotation=rot) + t4 = trans.SimilarityTransform(translation=(output_size / 2, + output_size / 2)) + t = t1 + t2 + t3 + t4 + M = t.params[0:2] + cropped = cv2.warpAffine(data, + M, (output_size, output_size), + borderValue=0.0) + return cropped, M + + +def trans_points2d(pts, M): + new_pts = np.zeros(shape=pts.shape, dtype=np.float32) + for i in range(pts.shape[0]): + pt = pts[i] + new_pt = np.array([pt[0], pt[1], 1.], dtype=np.float32) + new_pt = np.dot(M, new_pt) + #print('new_pt', new_pt.shape, new_pt) + new_pts[i] = new_pt[0:2] + + return new_pts + + +def trans_points3d(pts, M): + scale = np.sqrt(M[0][0] * M[0][0] + M[0][1] * M[0][1]) + #print(scale) + new_pts = np.zeros(shape=pts.shape, dtype=np.float32) + for i in range(pts.shape[0]): + pt = pts[i] + new_pt = np.array([pt[0], pt[1], 1.], dtype=np.float32) + new_pt = np.dot(M, new_pt) + #print('new_pt', new_pt.shape, new_pt) + new_pts[i][0:2] = new_pt[0:2] + new_pts[i][2] = pts[i][2] * scale + + return new_pts + + +def trans_points(pts, M): + if pts.shape[1] == 2: + return trans_points2d(pts, M) + else: + return trans_points3d(pts, M) + +def estimate_affine_matrix_3d23d(X, Y): + ''' Using least-squares solution + Args: + X: [n, 3]. 3d points(fixed) + Y: [n, 3]. corresponding 3d points(moving). Y = PX + Returns: + P_Affine: (3, 4). Affine camera matrix (the third row is [0, 0, 0, 1]). + ''' + X_homo = np.hstack((X, np.ones([X.shape[0],1]))) #n x 4 + P = np.linalg.lstsq(X_homo, Y)[0].T # Affine matrix. 3 x 4 + return P + +def P2sRt(P): + ''' decompositing camera matrix P + Args: + P: (3, 4). Affine Camera Matrix. + Returns: + s: scale factor. + R: (3, 3). rotation matrix. + t: (3,). translation. + ''' + t = P[:, 3] + R1 = P[0:1, :3] + R2 = P[1:2, :3] + s = (np.linalg.norm(R1) + np.linalg.norm(R2))/2.0 + r1 = R1/np.linalg.norm(R1) + r2 = R2/np.linalg.norm(R2) + r3 = np.cross(r1, r2) + + R = np.concatenate((r1, r2, r3), 0) + return s, R, t + +def matrix2angle(R): + ''' get three Euler angles from Rotation Matrix + Args: + R: (3,3). rotation matrix + Returns: + x: pitch + y: yaw + z: roll + ''' + sy = math.sqrt(R[0,0] * R[0,0] + R[1,0] * R[1,0]) + + singular = sy < 1e-6 + + if not singular : + x = math.atan2(R[2,1] , R[2,2]) + y = math.atan2(-R[2,0], sy) + z = math.atan2(R[1,0], R[0,0]) + else : + x = math.atan2(-R[1,2], R[1,1]) + y = math.atan2(-R[2,0], sy) + z = 0 + + # rx, ry, rz = np.rad2deg(x), np.rad2deg(y), np.rad2deg(z) + rx, ry, rz = x*180/np.pi, y*180/np.pi, z*180/np.pi + return rx, ry, rz + diff --git a/liveportrait/utils/face_analysis_diy.py b/liveportrait/utils/face_analysis_diy.py new file mode 100644 index 0000000000000000000000000000000000000000..5fa2986df93db39e81aaf55765bc46bad9e05546 --- /dev/null +++ b/liveportrait/utils/face_analysis_diy.py @@ -0,0 +1,79 @@ +# coding: utf-8 + +""" +face detectoin and alignment using InsightFace +""" + +import numpy as np +from .rprint import rlog as log +from .dependencies.insightface.app import FaceAnalysis +from .dependencies.insightface.app.common import Face +from .timer import Timer + + +def sort_by_direction(faces, direction: str = 'large-small', face_center=None): + if len(faces) <= 0: + return faces + + if direction == 'left-right': + return sorted(faces, key=lambda face: face['bbox'][0]) + if direction == 'right-left': + return sorted(faces, key=lambda face: face['bbox'][0], reverse=True) + if direction == 'top-bottom': + return sorted(faces, key=lambda face: face['bbox'][1]) + if direction == 'bottom-top': + return sorted(faces, key=lambda face: face['bbox'][1], reverse=True) + if direction == 'small-large': + return sorted(faces, key=lambda face: (face['bbox'][2] - face['bbox'][0]) * (face['bbox'][3] - face['bbox'][1])) + if direction == 'large-small': + return sorted(faces, key=lambda face: (face['bbox'][2] - face['bbox'][0]) * (face['bbox'][3] - face['bbox'][1]), reverse=True) + if direction == 'distance-from-retarget-face': + return sorted(faces, key=lambda face: (((face['bbox'][2]+face['bbox'][0])/2-face_center[0])**2+((face['bbox'][3]+face['bbox'][1])/2-face_center[1])**2)**0.5) + return faces + + +class FaceAnalysisDIY(FaceAnalysis): + def __init__(self, name='buffalo_l', root='~/.insightface', allowed_modules=None, **kwargs): + super().__init__(name=name, root=root, allowed_modules=allowed_modules, **kwargs) + + self.timer = Timer() + + def get(self, img_bgr, **kwargs): + max_num = kwargs.get('max_num', 0) # the number of the detected faces, 0 means no limit + flag_do_landmark_2d_106 = kwargs.get('flag_do_landmark_2d_106', True) # whether to do 106-point detection + direction = kwargs.get('direction', 'large-small') # sorting direction + face_center = None + + bboxes, kpss = self.det_model.detect(img_bgr, max_num=max_num, metric='default') + if bboxes.shape[0] == 0: + return [] + ret = [] + for i in range(bboxes.shape[0]): + bbox = bboxes[i, 0:4] + det_score = bboxes[i, 4] + kps = None + if kpss is not None: + kps = kpss[i] + face = Face(bbox=bbox, kps=kps, det_score=det_score) + for taskname, model in self.models.items(): + if taskname == 'detection': + continue + + if (not flag_do_landmark_2d_106) and taskname == 'landmark_2d_106': + continue + + # print(f'taskname: {taskname}') + model.get(img_bgr, face) + ret.append(face) + + ret = sort_by_direction(ret, direction, face_center) + return ret + + def warmup(self): + self.timer.tic() + + img_bgr = np.zeros((512, 512, 3), dtype=np.uint8) + self.get(img_bgr) + + elapse = self.timer.toc() + #log(f'FaceAnalysisDIY warmup time: {elapse:.3f}s') diff --git a/liveportrait/utils/helper.py b/liveportrait/utils/helper.py new file mode 100644 index 0000000000000000000000000000000000000000..9854563734a41bd217842311b9093b95e8f11e6d --- /dev/null +++ b/liveportrait/utils/helper.py @@ -0,0 +1,154 @@ +# coding: utf-8 + +""" +utility functions and classes to handle feature extraction and model loading +""" + +import os +import os.path as osp +import torch +from collections import OrderedDict + +from ..modules.spade_generator import SPADEDecoder +from ..modules.warping_network import WarpingNetwork +from ..modules.motion_extractor import MotionExtractor +from ..modules.appearance_feature_extractor import AppearanceFeatureExtractor +from ..modules.stitching_retargeting_network import StitchingRetargetingNetwork + + +def suffix(filename): + """a.jpg -> jpg""" + pos = filename.rfind(".") + if pos == -1: + return "" + return filename[pos + 1:] + + +def prefix(filename): + """a.jpg -> a""" + pos = filename.rfind(".") + if pos == -1: + return filename + return filename[:pos] + + +def basename(filename): + """a/b/c.jpg -> c""" + return prefix(osp.basename(filename)) + + +def is_video(file_path): + if file_path.lower().endswith((".mp4", ".mov", ".avi", ".webm")) or osp.isdir(file_path): + return True + return False + + +def is_template(file_path): + if file_path.endswith(".pkl"): + return True + return False + + +def mkdir(d, log=False): + # return self-assined `d`, for one line code + if not osp.exists(d): + os.makedirs(d, exist_ok=True) + if log: + print(f"Make dir: {d}") + return d + + +def squeeze_tensor_to_numpy(tensor): + out = tensor.data.squeeze(0).cpu().numpy() + return out + + +def dct2cuda(dct: dict, device_id: int): + for key in dct: + dct[key] = torch.tensor(dct[key]).cuda(device_id) + return dct + + +def concat_feat(kp_source: torch.Tensor, kp_driving: torch.Tensor) -> torch.Tensor: + """ + kp_source: (bs, k, 3) + kp_driving: (bs, k, 3) + Return: (bs, 2k*3) + """ + bs_src = kp_source.shape[0] + bs_dri = kp_driving.shape[0] + assert bs_src == bs_dri, 'batch size must be equal' + + feat = torch.cat([kp_source.view(bs_src, -1), kp_driving.view(bs_dri, -1)], dim=1) + return feat + + +def remove_ddp_dumplicate_key(state_dict): + state_dict_new = OrderedDict() + for key in state_dict.keys(): + state_dict_new[key.replace('module.', '')] = state_dict[key] + return state_dict_new + + +def load_model(ckpt_path, model_config, device, model_type): + model_params = model_config['model_params'][f'{model_type}_params'] + + if model_type == 'appearance_feature_extractor': + model = AppearanceFeatureExtractor(**model_params).cuda(device) + elif model_type == 'motion_extractor': + model = MotionExtractor(**model_params).cuda(device) + elif model_type == 'warping_module': + model = WarpingNetwork(**model_params).cuda(device) + elif model_type == 'spade_generator': + model = SPADEDecoder(**model_params).cuda(device) + elif model_type == 'stitching_retargeting_module': + # Special handling for stitching and retargeting module + config = model_config['model_params']['stitching_retargeting_module_params'] + checkpoint = torch.load(ckpt_path, weights_only=True, map_location=lambda storage, loc: storage) + + stitcher = StitchingRetargetingNetwork(**config.get('stitching')) + stitcher.load_state_dict(remove_ddp_dumplicate_key(checkpoint['retarget_shoulder'])) + stitcher = stitcher.cuda(device) + stitcher.eval() + + retargetor_lip = StitchingRetargetingNetwork(**config.get('lip')) + retargetor_lip.load_state_dict(remove_ddp_dumplicate_key(checkpoint['retarget_mouth'])) + retargetor_lip = retargetor_lip.cuda(device) + retargetor_lip.eval() + + retargetor_eye = StitchingRetargetingNetwork(**config.get('eye')) + retargetor_eye.load_state_dict(remove_ddp_dumplicate_key(checkpoint['retarget_eye'])) + retargetor_eye = retargetor_eye.cuda(device) + retargetor_eye.eval() + + return { + 'stitching': stitcher, + 'lip': retargetor_lip, + 'eye': retargetor_eye + } + else: + raise ValueError(f"Unknown model type: {model_type}") + + model.load_state_dict(torch.load(ckpt_path, weights_only=True, map_location=lambda storage, loc: storage)) + model.eval() + return model + + +# get coefficients of Eqn. 7 +def calculate_transformation(config, s_kp_info, t_0_kp_info, t_i_kp_info, R_s, R_t_0, R_t_i): + if config.relative: + new_rotation = (R_t_i @ R_t_0.permute(0, 2, 1)) @ R_s + new_expression = s_kp_info['exp'] + (t_i_kp_info['exp'] - t_0_kp_info['exp']) + else: + new_rotation = R_t_i + new_expression = t_i_kp_info['exp'] + new_translation = s_kp_info['t'] + (t_i_kp_info['t'] - t_0_kp_info['t']) + new_translation[..., 2].fill_(0) # Keep the z-axis unchanged + new_scale = s_kp_info['scale'] * (t_i_kp_info['scale'] / t_0_kp_info['scale']) + return new_rotation, new_expression, new_translation, new_scale + + +def load_description(fp): + with open(fp, 'r', encoding='utf-8') as f: + content = f.read() + return content diff --git a/liveportrait/utils/io.py b/liveportrait/utils/io.py new file mode 100644 index 0000000000000000000000000000000000000000..29a7e008759ec8428171a18ac65960fc14397fdc --- /dev/null +++ b/liveportrait/utils/io.py @@ -0,0 +1,97 @@ +# coding: utf-8 + +import os +from glob import glob +import os.path as osp +import imageio +import numpy as np +import cv2; cv2.setNumThreads(0); cv2.ocl.setUseOpenCL(False) + + +def load_image_rgb(image_path: str): + if not osp.exists(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + img = cv2.imread(image_path, cv2.IMREAD_COLOR) + return cv2.cvtColor(img, cv2.COLOR_BGR2RGB) + + +def load_driving_info(driving_info): + driving_video_ori = [] + + def load_images_from_directory(directory): + image_paths = sorted(glob(osp.join(directory, '*.png')) + glob(osp.join(directory, '*.jpg'))) + return [load_image_rgb(im_path) for im_path in image_paths] + + def load_images_from_video(file_path): + reader = imageio.get_reader(file_path) + return [image for idx, image in enumerate(reader)] + + if osp.isdir(driving_info): + driving_video_ori = load_images_from_directory(driving_info) + elif osp.isfile(driving_info): + driving_video_ori = load_images_from_video(driving_info) + + return driving_video_ori + + +def contiguous(obj): + if not obj.flags.c_contiguous: + obj = obj.copy(order="C") + return obj + + +def resize_to_limit(img: np.ndarray, max_dim=1920, n=2): + """ + ajust the size of the image so that the maximum dimension does not exceed max_dim, and the width and the height of the image are multiples of n. + :param img: the image to be processed. + :param max_dim: the maximum dimension constraint. + :param n: the number that needs to be multiples of. + :return: the adjusted image. + """ + h, w = img.shape[:2] + + # ajust the size of the image according to the maximum dimension + if max_dim > 0 and max(h, w) > max_dim: + if h > w: + new_h = max_dim + new_w = int(w * (max_dim / h)) + else: + new_w = max_dim + new_h = int(h * (max_dim / w)) + img = cv2.resize(img, (new_w, new_h)) + + # ensure that the image dimensions are multiples of n + n = max(n, 1) + new_h = img.shape[0] - (img.shape[0] % n) + new_w = img.shape[1] - (img.shape[1] % n) + + if new_h == 0 or new_w == 0: + # when the width or height is less than n, no need to process + return img + + if new_h != img.shape[0] or new_w != img.shape[1]: + img = img[:new_h, :new_w] + + return img + + +def load_img_online(obj, mode="bgr", **kwargs): + max_dim = kwargs.get("max_dim", 1920) + n = kwargs.get("n", 2) + if isinstance(obj, str): + if mode.lower() == "gray": + img = cv2.imread(obj, cv2.IMREAD_GRAYSCALE) + else: + img = cv2.imread(obj, cv2.IMREAD_COLOR) + else: + img = obj + + # Resize image to satisfy constraints + img = resize_to_limit(img, max_dim=max_dim, n=n) + + if mode.lower() == "bgr": + return contiguous(img) + elif mode.lower() == "rgb": + return contiguous(img[..., ::-1]) + else: + raise Exception(f"Unknown mode {mode}") diff --git a/liveportrait/utils/landmark_runner.py b/liveportrait/utils/landmark_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..75bf5c254f7eb32f3096bd667fcacfe190da6bc4 --- /dev/null +++ b/liveportrait/utils/landmark_runner.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +import os.path as osp +import cv2; cv2.setNumThreads(0); cv2.ocl.setUseOpenCL(False) +import torch +import numpy as np +import onnxruntime +from .timer import Timer +from .rprint import rlog +from .crop import crop_image, _transform_pts + + +def make_abs_path(fn): + return osp.join(osp.dirname(osp.realpath(__file__)), fn) + + +def to_ndarray(obj): + if isinstance(obj, torch.Tensor): + return obj.cpu().numpy() + elif isinstance(obj, np.ndarray): + return obj + else: + return np.array(obj) + + +class LandmarkRunner(object): + """landmark runner""" + def __init__(self, **kwargs): + ckpt_path = kwargs.get('ckpt_path') + onnx_provider = kwargs.get('onnx_provider', 'cuda') # 默认用cuda + device_id = kwargs.get('device_id', 0) + self.dsize = kwargs.get('dsize', 224) + self.timer = Timer() + + if onnx_provider.lower() == 'cuda': + self.session = onnxruntime.InferenceSession( + ckpt_path, providers=[ + ('CUDAExecutionProvider', {'device_id': device_id}) + ] + ) + else: + opts = onnxruntime.SessionOptions() + opts.intra_op_num_threads = 4 # 默认线程数为 4 + self.session = onnxruntime.InferenceSession( + ckpt_path, providers=['CPUExecutionProvider'], + sess_options=opts + ) + + def _run(self, inp): + out = self.session.run(None, {'input': inp}) + return out + + def run(self, img_rgb: np.ndarray, lmk=None): + if lmk is not None: + crop_dct = crop_image(img_rgb, lmk, dsize=self.dsize, scale=1.5, vy_ratio=-0.1) + img_crop_rgb = crop_dct['img_crop'] + else: + img_crop_rgb = cv2.resize(img_rgb, (self.dsize, self.dsize)) + scale = max(img_rgb.shape[:2]) / self.dsize + crop_dct = { + 'M_c2o': np.array([ + [scale, 0., 0.], + [0., scale, 0.], + [0., 0., 1.], + ], dtype=np.float32), + } + + inp = (img_crop_rgb.astype(np.float32) / 255.).transpose(2, 0, 1)[None, ...] # HxWx3 (BGR) -> 1x3xHxW (RGB!) + + out_lst = self._run(inp) + out_pts = out_lst[2] + + pts = to_ndarray(out_pts[0]).reshape(-1, 2) * self.dsize # scale to 0-224 + pts = _transform_pts(pts, M=crop_dct['M_c2o']) + + return { + 'pts': pts, # 2d landmarks 203 points + } + + def warmup(self): + # 构造dummy image进行warmup + self.timer.tic() + + dummy_image = np.zeros((1, 3, self.dsize, self.dsize), dtype=np.float32) + + _ = self._run(dummy_image) + + elapse = self.timer.toc() + #rlog(f'LandmarkRunner warmup time: {elapse:.3f}s') diff --git a/liveportrait/utils/resources/mask_template.png b/liveportrait/utils/resources/mask_template.png new file mode 100644 index 0000000000000000000000000000000000000000..d3522210825b8fe128210f261d32e80a7ca02a80 --- /dev/null +++ b/liveportrait/utils/resources/mask_template.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4c53e64a07ae3056af2b38548ae5b6cceb04d5c3e6514c7a8d2c3aff9da1ee76 +size 3470 diff --git a/liveportrait/utils/retargeting_utils.py b/liveportrait/utils/retargeting_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..20a1bdd37a05f8140124db2a1be568683e917653 --- /dev/null +++ b/liveportrait/utils/retargeting_utils.py @@ -0,0 +1,54 @@ + +""" +Functions to compute distance ratios between specific pairs of facial landmarks +""" + +import numpy as np + + +def calculate_distance_ratio(lmk: np.ndarray, idx1: int, idx2: int, idx3: int, idx4: int, eps: float = 1e-6) -> np.ndarray: + """ + Calculate the ratio of the distance between two pairs of landmarks. + + Parameters: + lmk (np.ndarray): Landmarks array of shape (B, N, 2). + idx1, idx2, idx3, idx4 (int): Indices of the landmarks. + eps (float): Small value to avoid division by zero. + + Returns: + np.ndarray: Calculated distance ratio. + """ + return (np.linalg.norm(lmk[:, idx1] - lmk[:, idx2], axis=1, keepdims=True) / + (np.linalg.norm(lmk[:, idx3] - lmk[:, idx4], axis=1, keepdims=True) + eps)) + + +def calc_eye_close_ratio(lmk: np.ndarray, target_eye_ratio: np.ndarray = None) -> np.ndarray: + """ + Calculate the eye-close ratio for left and right eyes. + + Parameters: + lmk (np.ndarray): Landmarks array of shape (B, N, 2). + target_eye_ratio (np.ndarray, optional): Additional target eye ratio array to include. + + Returns: + np.ndarray: Concatenated eye-close ratios. + """ + lefteye_close_ratio = calculate_distance_ratio(lmk, 6, 18, 0, 12) + righteye_close_ratio = calculate_distance_ratio(lmk, 30, 42, 24, 36) + if target_eye_ratio is not None: + return np.concatenate([lefteye_close_ratio, righteye_close_ratio, target_eye_ratio], axis=1) + else: + return np.concatenate([lefteye_close_ratio, righteye_close_ratio], axis=1) + + +def calc_lip_close_ratio(lmk: np.ndarray) -> np.ndarray: + """ + Calculate the lip-close ratio. + + Parameters: + lmk (np.ndarray): Landmarks array of shape (B, N, 2). + + Returns: + np.ndarray: Calculated lip-close ratio. + """ + return calculate_distance_ratio(lmk, 90, 102, 48, 66) diff --git a/liveportrait/utils/rprint.py b/liveportrait/utils/rprint.py new file mode 100644 index 0000000000000000000000000000000000000000..c43a42f9855bbb019725e6c2b6c6c50e6fa4d0c5 --- /dev/null +++ b/liveportrait/utils/rprint.py @@ -0,0 +1,16 @@ +# coding: utf-8 + +""" +custom print and log functions +""" + +__all__ = ['rprint', 'rlog'] + +try: + from rich.console import Console + console = Console() + rprint = console.print + rlog = console.log +except: + rprint = print + rlog = print diff --git a/liveportrait/utils/timer.py b/liveportrait/utils/timer.py new file mode 100644 index 0000000000000000000000000000000000000000..3570fa45d3ff36376471b82a5b3c02efe46eed98 --- /dev/null +++ b/liveportrait/utils/timer.py @@ -0,0 +1,29 @@ +# coding: utf-8 + +""" +tools to measure elapsed time +""" + +import time + +class Timer(object): + """A simple timer.""" + + def __init__(self): + self.total_time = 0. + self.calls = 0 + self.start_time = 0. + self.diff = 0. + + def tic(self): + # using time.time instead of time.clock because time time.clock + # does not normalize for multithreading + self.start_time = time.time() + + def toc(self, average=True): + self.diff = time.time() - self.start_time + return self.diff + + def clear(self): + self.start_time = 0. + self.diff = 0. diff --git a/liveportrait/utils/video.py b/liveportrait/utils/video.py new file mode 100644 index 0000000000000000000000000000000000000000..555122f728a1d8956d5532104c1f9c930e529925 --- /dev/null +++ b/liveportrait/utils/video.py @@ -0,0 +1,140 @@ +# coding: utf-8 + +""" +functions for processing video +""" + +import os.path as osp +import numpy as np +import subprocess +import imageio +import cv2 + +from rich.progress import track +from .helper import prefix +from .rprint import rprint as print + + +def exec_cmd(cmd): + subprocess.run(cmd, shell=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + + +def images2video(images, wfp, **kwargs): + fps = kwargs.get('fps', 25) # MuseTalk prefers 25 fps by default + video_format = kwargs.get('format', 'mp4') # default is mp4 format + codec = kwargs.get('codec', 'libx264') # default is libx264 encoding + quality = kwargs.get('quality') # video quality + pixelformat = kwargs.get('pixelformat', 'yuv420p') # video pixel format + image_mode = kwargs.get('image_mode', 'rgb') + macro_block_size = kwargs.get('macro_block_size', 2) + ffmpeg_params = ['-crf', str(kwargs.get('crf', 18))] + + writer = imageio.get_writer( + wfp, fps=fps, format=video_format, + codec=codec, quality=quality, ffmpeg_params=ffmpeg_params, pixelformat=pixelformat, macro_block_size=macro_block_size + ) + + n = len(images) + for i in track(range(n), description='writing', transient=True): + if image_mode.lower() == 'bgr': + writer.append_data(images[i][..., ::-1]) + else: + writer.append_data(images[i]) + + writer.close() + + # print(f':smiley: Dump to {wfp}\n', style="bold green") + print(f'Dump to {wfp}\n') + + +# useTalk prefers 25 fps by default +def video2gif(video_fp, fps=25, size=256): + if osp.exists(video_fp): + d = osp.split(video_fp)[0] + fn = prefix(osp.basename(video_fp)) + palette_wfp = osp.join(d, 'palette.png') + gif_wfp = osp.join(d, f'{fn}.gif') + # generate the palette + cmd = f'ffmpeg -i {video_fp} -vf "fps={fps},scale={size}:-1:flags=lanczos,palettegen" {palette_wfp} -y' + exec_cmd(cmd) + # use the palette to generate the gif + cmd = f'ffmpeg -i {video_fp} -i {palette_wfp} -filter_complex "fps={fps},scale={size}:-1:flags=lanczos[x];[x][1:v]paletteuse" {gif_wfp} -y' + exec_cmd(cmd) + else: + print(f'video_fp: {video_fp} not exists!') + + +def merge_audio_video(video_fp, audio_fp, wfp): + if osp.exists(video_fp) and osp.exists(audio_fp): + cmd = f'ffmpeg -i {video_fp} -i {audio_fp} -c:v copy -c:a aac {wfp} -y' + exec_cmd(cmd) + print(f'merge {video_fp} and {audio_fp} to {wfp}') + else: + print(f'video_fp: {video_fp} or audio_fp: {audio_fp} not exists!') + + +def blend(img: np.ndarray, mask: np.ndarray, background_color=(255, 255, 255)): + mask_float = mask.astype(np.float32) / 255. + background_color = np.array(background_color).reshape([1, 1, 3]) + bg = np.ones_like(img) * background_color + img = np.clip(mask_float * img + (1 - mask_float) * bg, 0, 255).astype(np.uint8) + return img + + +def concat_frames(I_p_lst, driving_rgb_lst, img_rgb): + # TODO: add more concat style, e.g., left-down corner driving + out_lst = [] + for idx, _ in track(enumerate(I_p_lst), total=len(I_p_lst), description='Concatenating result...'): + source_image_drived = I_p_lst[idx] + image_drive = driving_rgb_lst[idx] + + # resize images to match source_image_drived shape + h, w, _ = source_image_drived.shape + image_drive_resized = cv2.resize(image_drive, (w, h)) + img_rgb_resized = cv2.resize(img_rgb, (w, h)) + + # concatenate images horizontally + frame = np.concatenate((image_drive_resized, img_rgb_resized, source_image_drived), axis=1) + out_lst.append(frame) + return out_lst + + +class VideoWriter: + def __init__(self, **kwargs): + self.fps = kwargs.get('fps', 25) # MuseTalk prefers 25 fps by default + self.wfp = kwargs.get('wfp', 'video.mp4') + self.video_format = kwargs.get('format', 'mp4') + self.codec = kwargs.get('codec', 'libx264') + self.quality = kwargs.get('quality') + self.pixelformat = kwargs.get('pixelformat', 'yuv420p') + self.image_mode = kwargs.get('image_mode', 'rgb') + self.ffmpeg_params = kwargs.get('ffmpeg_params') + + self.writer = imageio.get_writer( + self.wfp, fps=self.fps, format=self.video_format, + codec=self.codec, quality=self.quality, + ffmpeg_params=self.ffmpeg_params, pixelformat=self.pixelformat + ) + + def write(self, image): + if self.image_mode.lower() == 'bgr': + self.writer.append_data(image[..., ::-1]) + else: + self.writer.append_data(image) + + def close(self): + if self.writer is not None: + self.writer.close() + + +def change_video_fps(input_file, output_file, fps=25, codec='libx264', crf=5): + cmd = f"ffmpeg -i {input_file} -c:v {codec} -crf {crf} -r {fps} {output_file} -y" + exec_cmd(cmd) + + +def get_fps(filepath): + import ffmpeg + probe = ffmpeg.probe(filepath) + video_stream = next((stream for stream in probe['streams'] if stream['codec_type'] == 'video'), None) + fps = eval(video_stream['avg_frame_rate']) + return fps diff --git a/loader.py b/loader.py new file mode 100644 index 0000000000000000000000000000000000000000..0172b81a01e1bfe58ed674c5f74032e66a25cc12 --- /dev/null +++ b/loader.py @@ -0,0 +1,156 @@ +import os +import logging +import torch +import asyncio +import aiohttp +import requests +from huggingface_hub import hf_hub_download +import sentencepiece + + +# Configure logging +logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s') +logger = logging.getLogger(__name__) + +# Configuration +DATA_ROOT = os.environ.get('DATA_ROOT', '/tmp/data') +MODELS_DIR = os.path.join(DATA_ROOT, "models") +DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu") + +# Hugging Face repository information +HF_REPO_ID = "jbilcke-hf/model-cocktail" + +# Model files to download +MODEL_FILES = [ + "dwpose/dw-ll_ucoco_384.pth", + "face-detector/s3fd-619a316812.pth", + "liveportrait/spade_generator.pth", + "liveportrait/warping_module.pth", + "liveportrait/motion_extractor.pth", + "liveportrait/stitching_retargeting_module.pth", + "liveportrait/appearance_feature_extractor.pth", + "liveportrait/landmark.onnx", + + # this is a hack, instead we should probably try to + # fix liveportrait/utils/dependencies/insightface/utils/storage.py + "insightface/models/buffalo_l.zip", + + "insightface/buffalo_l/det_10g.onnx", + "insightface/buffalo_l/2d106det.onnx", + "sd-vae-ft-mse/diffusion_pytorch_model.bin", + "sd-vae-ft-mse/diffusion_pytorch_model.safetensors", + "sd-vae-ft-mse/config.json", + + # we don't use those yet + #"flux-dev/flux-dev-fp8.safetensors", + #"flux-dev/flux_dev_quantization_map.json", + #"pulid-flux/pulid_flux_v0.9.0.safetensors", + #"pulid-flux/pulid_v1.bin" +] + +def create_directory(directory): + """Create a directory if it doesn't exist and log its status.""" + if not os.path.exists(directory): + os.makedirs(directory) + logger.info(f" Directory created: {directory}") + else: + logger.info(f" Directory already exists: {directory}") + +def print_directory_structure(startpath): + """Print the directory structure starting from the given path.""" + for root, dirs, files in os.walk(startpath): + level = root.replace(startpath, '').count(os.sep) + indent = ' ' * 4 * level + logger.info(f"{indent}{os.path.basename(root)}/") + subindent = ' ' * 4 * (level + 1) + for f in files: + logger.info(f"{subindent}{f}") + +async def download_hf_file(filename: str) -> None: + """Download a file from Hugging Face to the models directory.""" + dest = os.path.join(MODELS_DIR, filename) + os.makedirs(os.path.dirname(dest), exist_ok=True) + if os.path.exists(dest): + # this is really for debugging purposes only + logger.debug(f" ✅ {filename}") + return + + logger.info(f" ⏳ Downloading {HF_REPO_ID}/{filename}") + + try: + await asyncio.get_event_loop().run_in_executor( + None, + lambda: hf_hub_download( + repo_id=HF_REPO_ID, + filename=filename, + local_dir=MODELS_DIR + ) + ) + logger.info(f" ✅ Downloaded {filename}") + except Exception as e: + logger.error(f"🚨 Error downloading file from Hugging Face: {e}") + if os.path.exists(dest): + os.remove(dest) + raise + +async def download_all_models(): + """Download all required models from the Hugging Face repository.""" + logger.info(" 🔎 Looking for models...") + tasks = [download_hf_file(filename) for filename in MODEL_FILES] + await asyncio.gather(*tasks) + logger.info(" ✅ All models are available") + + # are you looking to debug the app and verify that models are downloaded properly? + # then un-comment the two following lines: + #logger.info("💡 Printing directory structure of models:") + #print_directory_structure(MODELS_DIR) + +class ModelLoader: + """A class responsible for loading and initializing all required models.""" + + def __init__(self): + self.device = DEVICE + self.models_dir = MODELS_DIR + + async def load_live_portrait(self): + """Load LivePortrait models.""" + from liveportrait.config.inference_config import InferenceConfig + from liveportrait.config.crop_config import CropConfig + from liveportrait.live_portrait_pipeline import LivePortraitPipeline + + logger.info(" ⏳ Loading LivePortrait models...") + live_portrait_pipeline = await asyncio.to_thread( + LivePortraitPipeline, + inference_cfg=InferenceConfig( + # default values + flag_stitching=True, # we recommend setting it to True! + flag_relative=True, # whether to use relative motion + flag_pasteback=True, # whether to paste-back/stitch the animated face cropping from the face-cropping space to the original image space + flag_do_crop= True, # whether to crop the source portrait to the face-cropping space + flag_do_rot=True, # whether to conduct the rotation when flag_do_crop is True + ), + crop_cfg=CropConfig() + ) + logger.info(" ✅ LivePortrait models loaded successfully.") + return live_portrait_pipeline + +async def initialize_models(): + """Initialize and load all required models.""" + logger.info("🚀 Starting model initialization...") + + # Ensure all required models are downloaded + await download_all_models() + + # Initialize the ModelLoader + loader = ModelLoader() + + # Load LivePortrait models + live_portrait = await loader.load_live_portrait() + + logger.info("✅ Model initialization completed.") + return live_portrait + +# Initial setup +logger.info("🚀 Setting up storage directories...") +create_directory(MODELS_DIR) +logger.info("✅ Storage directories setup completed.") diff --git a/public/hf-logo.svg b/public/hf-logo.svg new file mode 100644 index 0000000000000000000000000000000000000000..43c5d3c0c97a9150b19d10bc68f4c9042c5034cd --- /dev/null +++ b/public/hf-logo.svg @@ -0,0 +1,37 @@ +<svg xmlns="http://www.w3.org/2000/svg" width="95" height="88" fill="none"> + <path fill="#FFD21E" d="M47.21 76.5a34.75 34.75 0 1 0 0-69.5 34.75 34.75 0 0 0 0 69.5Z" /> + <path + fill="#FF9D0B" + d="M81.96 41.75a34.75 34.75 0 1 0-69.5 0 34.75 34.75 0 0 0 69.5 0Zm-73.5 0a38.75 38.75 0 1 1 77.5 0 38.75 38.75 0 0 1-77.5 0Z" + /> + <path + fill="#3A3B45" + d="M58.5 32.3c1.28.44 1.78 3.06 3.07 2.38a5 5 0 1 0-6.76-2.07c.61 1.15 2.55-.72 3.7-.32ZM34.95 32.3c-1.28.44-1.79 3.06-3.07 2.38a5 5 0 1 1 6.76-2.07c-.61 1.15-2.56-.72-3.7-.32Z" + /> + <path + fill="#FF323D" + d="M46.96 56.29c9.83 0 13-8.76 13-13.26 0-2.34-1.57-1.6-4.09-.36-2.33 1.15-5.46 2.74-8.9 2.74-7.19 0-13-6.88-13-2.38s3.16 13.26 13 13.26Z" + /> + <path + fill="#3A3B45" + fill-rule="evenodd" + d="M39.43 54a8.7 8.7 0 0 1 5.3-4.49c.4-.12.81.57 1.24 1.28.4.68.82 1.37 1.24 1.37.45 0 .9-.68 1.33-1.35.45-.7.89-1.38 1.32-1.25a8.61 8.61 0 0 1 5 4.17c3.73-2.94 5.1-7.74 5.1-10.7 0-2.34-1.57-1.6-4.09-.36l-.14.07c-2.31 1.15-5.39 2.67-8.77 2.67s-6.45-1.52-8.77-2.67c-2.6-1.29-4.23-2.1-4.23.29 0 3.05 1.46 8.06 5.47 10.97Z" + clip-rule="evenodd" + /> + <path + fill="#FF9D0B" + d="M70.71 37a3.25 3.25 0 1 0 0-6.5 3.25 3.25 0 0 0 0 6.5ZM24.21 37a3.25 3.25 0 1 0 0-6.5 3.25 3.25 0 0 0 0 6.5ZM17.52 48c-1.62 0-3.06.66-4.07 1.87a5.97 5.97 0 0 0-1.33 3.76 7.1 7.1 0 0 0-1.94-.3c-1.55 0-2.95.59-3.94 1.66a5.8 5.8 0 0 0-.8 7 5.3 5.3 0 0 0-1.79 2.82c-.24.9-.48 2.8.8 4.74a5.22 5.22 0 0 0-.37 5.02c1.02 2.32 3.57 4.14 8.52 6.1 3.07 1.22 5.89 2 5.91 2.01a44.33 44.33 0 0 0 10.93 1.6c5.86 0 10.05-1.8 12.46-5.34 3.88-5.69 3.33-10.9-1.7-15.92-2.77-2.78-4.62-6.87-5-7.77-.78-2.66-2.84-5.62-6.25-5.62a5.7 5.7 0 0 0-4.6 2.46c-1-1.26-1.98-2.25-2.86-2.82A7.4 7.4 0 0 0 17.52 48Zm0 4c.51 0 1.14.22 1.82.65 2.14 1.36 6.25 8.43 7.76 11.18.5.92 1.37 1.31 2.14 1.31 1.55 0 2.75-1.53.15-3.48-3.92-2.93-2.55-7.72-.68-8.01.08-.02.17-.02.24-.02 1.7 0 2.45 2.93 2.45 2.93s2.2 5.52 5.98 9.3c3.77 3.77 3.97 6.8 1.22 10.83-1.88 2.75-5.47 3.58-9.16 3.58-3.81 0-7.73-.9-9.92-1.46-.11-.03-13.45-3.8-11.76-7 .28-.54.75-.76 1.34-.76 2.38 0 6.7 3.54 8.57 3.54.41 0 .7-.17.83-.6.79-2.85-12.06-4.05-10.98-8.17.2-.73.71-1.02 1.44-1.02 3.14 0 10.2 5.53 11.68 5.53.11 0 .2-.03.24-.1.74-1.2.33-2.04-4.9-5.2-5.21-3.16-8.88-5.06-6.8-7.33.24-.26.58-.38 1-.38 3.17 0 10.66 6.82 10.66 6.82s2.02 2.1 3.25 2.1c.28 0 .52-.1.68-.38.86-1.46-8.06-8.22-8.56-11.01-.34-1.9.24-2.85 1.31-2.85Z" + /> + <path + fill="#FFD21E" + d="M38.6 76.69c2.75-4.04 2.55-7.07-1.22-10.84-3.78-3.77-5.98-9.3-5.98-9.3s-.82-3.2-2.69-2.9c-1.87.3-3.24 5.08.68 8.01 3.91 2.93-.78 4.92-2.29 2.17-1.5-2.75-5.62-9.82-7.76-11.18-2.13-1.35-3.63-.6-3.13 2.2.5 2.79 9.43 9.55 8.56 11-.87 1.47-3.93-1.71-3.93-1.71s-9.57-8.71-11.66-6.44c-2.08 2.27 1.59 4.17 6.8 7.33 5.23 3.16 5.64 4 4.9 5.2-.75 1.2-12.28-8.53-13.36-4.4-1.08 4.11 11.77 5.3 10.98 8.15-.8 2.85-9.06-5.38-10.74-2.18-1.7 3.21 11.65 6.98 11.76 7.01 4.3 1.12 15.25 3.49 19.08-2.12Z" + /> + <path + fill="#FF9D0B" + d="M77.4 48c1.62 0 3.07.66 4.07 1.87a5.97 5.97 0 0 1 1.33 3.76 7.1 7.1 0 0 1 1.95-.3c1.55 0 2.95.59 3.94 1.66a5.8 5.8 0 0 1 .8 7 5.3 5.3 0 0 1 1.78 2.82c.24.9.48 2.8-.8 4.74a5.22 5.22 0 0 1 .37 5.02c-1.02 2.32-3.57 4.14-8.51 6.1-3.08 1.22-5.9 2-5.92 2.01a44.33 44.33 0 0 1-10.93 1.6c-5.86 0-10.05-1.8-12.46-5.34-3.88-5.69-3.33-10.9 1.7-15.92 2.78-2.78 4.63-6.87 5.01-7.77.78-2.66 2.83-5.62 6.24-5.62a5.7 5.7 0 0 1 4.6 2.46c1-1.26 1.98-2.25 2.87-2.82A7.4 7.4 0 0 1 77.4 48Zm0 4c-.51 0-1.13.22-1.82.65-2.13 1.36-6.25 8.43-7.76 11.18a2.43 2.43 0 0 1-2.14 1.31c-1.54 0-2.75-1.53-.14-3.48 3.91-2.93 2.54-7.72.67-8.01a1.54 1.54 0 0 0-.24-.02c-1.7 0-2.45 2.93-2.45 2.93s-2.2 5.52-5.97 9.3c-3.78 3.77-3.98 6.8-1.22 10.83 1.87 2.75 5.47 3.58 9.15 3.58 3.82 0 7.73-.9 9.93-1.46.1-.03 13.45-3.8 11.76-7-.29-.54-.75-.76-1.34-.76-2.38 0-6.71 3.54-8.57 3.54-.42 0-.71-.17-.83-.6-.8-2.85 12.05-4.05 10.97-8.17-.19-.73-.7-1.02-1.44-1.02-3.14 0-10.2 5.53-11.68 5.53-.1 0-.19-.03-.23-.1-.74-1.2-.34-2.04 4.88-5.2 5.23-3.16 8.9-5.06 6.8-7.33-.23-.26-.57-.38-.98-.38-3.18 0-10.67 6.82-10.67 6.82s-2.02 2.1-3.24 2.1a.74.74 0 0 1-.68-.38c-.87-1.46 8.05-8.22 8.55-11.01.34-1.9-.24-2.85-1.31-2.85Z" + /> + <path + fill="#FFD21E" + d="M56.33 76.69c-2.75-4.04-2.56-7.07 1.22-10.84 3.77-3.77 5.97-9.3 5.97-9.3s.82-3.2 2.7-2.9c1.86.3 3.23 5.08-.68 8.01-3.92 2.93.78 4.92 2.28 2.17 1.51-2.75 5.63-9.82 7.76-11.18 2.13-1.35 3.64-.6 3.13 2.2-.5 2.79-9.42 9.55-8.55 11 .86 1.47 3.92-1.71 3.92-1.71s9.58-8.71 11.66-6.44c2.08 2.27-1.58 4.17-6.8 7.33-5.23 3.16-5.63 4-4.9 5.2.75 1.2 12.28-8.53 13.36-4.4 1.08 4.11-11.76 5.3-10.97 8.15.8 2.85 9.05-5.38 10.74-2.18 1.69 3.21-11.65 6.98-11.76 7.01-4.31 1.12-15.26 3.49-19.08-2.12Z" + /> +</svg> diff --git a/public/index.html b/public/index.html new file mode 100644 index 0000000000000000000000000000000000000000..1f41cf6fdbb89ce439c948a8b816056c06b0555b --- /dev/null +++ b/public/index.html @@ -0,0 +1,13 @@ +<!DOCTYPE html> +<html lang="en"> +<head> + <meta charset="UTF-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0"> + <title>FacePoke by @jbilcke-hf</title> + <script src="https://cdn.tailwindcss.com"></script> +</head> +<body> + <div id="root"></div> + <script src="index.js"></script> +</body> +</html> diff --git a/public/index.js b/public/index.js new file mode 100644 index 0000000000000000000000000000000000000000..ef702b3385ec524aaad921114acc60aa3258289e --- /dev/null +++ b/public/index.js @@ -0,0 +1,33512 @@ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getProtoOf = Object.getPrototypeOf; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __toESM = (mod, isNodeMode, target) => { + target = mod != null ? __create(__getProtoOf(mod)) : {}; + const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target; + for (let key of __getOwnPropNames(mod)) + if (!__hasOwnProp.call(to, key)) + __defProp(to, key, { + get: () => mod[key], + enumerable: true + }); + return to; +}; +var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { + get: all[name], + enumerable: true, + configurable: true, + set: (newValue) => all[name] = () => newValue + }); +}; + +// node_modules/react/cjs/react.development.js +var require_react_development = __commonJS((exports, module) => { + if (true) { + (function() { + if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === "function") { + __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error); + } + var ReactVersion = "18.3.1"; + 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_OFFSCREEN_TYPE = Symbol.for("react.offscreen"); + 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; + } + var ReactCurrentDispatcher = { + current: null + }; + var ReactCurrentBatchConfig = { + transition: null + }; + var ReactCurrentActQueue = { + current: null, + isBatchingLegacy: false, + didScheduleLegacyUpdate: false + }; + var ReactCurrentOwner = { + current: null + }; + var ReactDebugCurrentFrame = {}; + var currentExtraStackFrame = null; + function setExtraStackFrame(stack) { + { + currentExtraStackFrame = stack; + } + } + { + ReactDebugCurrentFrame.setExtraStackFrame = function(stack) { + { + currentExtraStackFrame = stack; + } + }; + ReactDebugCurrentFrame.getCurrentStack = null; + ReactDebugCurrentFrame.getStackAddendum = function() { + var stack = ""; + if (currentExtraStackFrame) { + stack += currentExtraStackFrame; + } + var impl = ReactDebugCurrentFrame.getCurrentStack; + if (impl) { + stack += impl() || ""; + } + return stack; + }; + } + var enableScopeAPI = false; + var enableCacheElement = false; + var enableTransitionTracing = false; + var enableLegacyHidden = false; + var enableDebugTracing = false; + var ReactSharedInternals = { + ReactCurrentDispatcher, + ReactCurrentBatchConfig, + ReactCurrentOwner + }; + { + ReactSharedInternals.ReactDebugCurrentFrame = ReactDebugCurrentFrame; + ReactSharedInternals.ReactCurrentActQueue = ReactCurrentActQueue; + } + function warn(format) { + { + { + 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) { + { + { + 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) { + { + var ReactDebugCurrentFrame2 = ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame2.getStackAddendum(); + if (stack !== "") { + format += "%s"; + args = args.concat([stack]); + } + var argsWithFormat = args.map(function(item) { + return String(item); + }); + argsWithFormat.unshift("Warning: " + format); + Function.prototype.apply.call(console[level], console, argsWithFormat); + } + } + var didWarnStateUpdateForUnmountedComponent = {}; + function warnNoop(publicInstance, callerName) { + { + var _constructor = publicInstance.constructor; + var componentName = _constructor && (_constructor.displayName || _constructor.name) || "ReactClass"; + var warningKey = componentName + "." + callerName; + if (didWarnStateUpdateForUnmountedComponent[warningKey]) { + return; + } + error("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.", callerName, componentName); + didWarnStateUpdateForUnmountedComponent[warningKey] = true; + } + } + var ReactNoopUpdateQueue = { + isMounted: function(publicInstance) { + return false; + }, + enqueueForceUpdate: function(publicInstance, callback, callerName) { + warnNoop(publicInstance, "forceUpdate"); + }, + enqueueReplaceState: function(publicInstance, completeState, callback, callerName) { + warnNoop(publicInstance, "replaceState"); + }, + enqueueSetState: function(publicInstance, partialState, callback, callerName) { + warnNoop(publicInstance, "setState"); + } + }; + var assign = Object.assign; + var emptyObject = {}; + { + Object.freeze(emptyObject); + } + function Component(props, context, updater) { + this.props = props; + this.context = context; + this.refs = emptyObject; + this.updater = updater || ReactNoopUpdateQueue; + } + Component.prototype.isReactComponent = {}; + Component.prototype.setState = function(partialState, callback) { + if (typeof partialState !== "object" && typeof partialState !== "function" && partialState != null) { + throw new Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables."); + } + this.updater.enqueueSetState(this, partialState, callback, "setState"); + }; + Component.prototype.forceUpdate = function(callback) { + this.updater.enqueueForceUpdate(this, callback, "forceUpdate"); + }; + { + var deprecatedAPIs = { + isMounted: ["isMounted", "Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."], + replaceState: ["replaceState", "Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."] + }; + var defineDeprecationWarning = function(methodName, info) { + Object.defineProperty(Component.prototype, methodName, { + get: function() { + warn("%s(...) is deprecated in plain JavaScript React classes. %s", info[0], info[1]); + return; + } + }); + }; + for (var fnName in deprecatedAPIs) { + if (deprecatedAPIs.hasOwnProperty(fnName)) { + defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); + } + } + } + function ComponentDummy() { + } + ComponentDummy.prototype = Component.prototype; + function PureComponent(props, context, updater) { + this.props = props; + this.context = context; + this.refs = emptyObject; + this.updater = updater || ReactNoopUpdateQueue; + } + var pureComponentPrototype = PureComponent.prototype = new ComponentDummy; + pureComponentPrototype.constructor = PureComponent; + assign(pureComponentPrototype, Component.prototype); + pureComponentPrototype.isPureReactComponent = true; + function createRef() { + var refObject = { + current: null + }; + { + Object.seal(refObject); + } + return refObject; + } + var isArrayImpl = Array.isArray; + function isArray(a) { + return isArrayImpl(a); + } + function typeName(value) { + { + var hasToStringTag = typeof Symbol === "function" && Symbol.toStringTag; + var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object"; + return type; + } + } + function willCoercionThrow(value) { + { + try { + testStringCoercion(value); + return false; + } catch (e) { + return true; + } + } + } + function testStringCoercion(value) { + 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); + } + } + } + function getWrappedName(outerType, innerType, wrapperName) { + var displayName = outerType.displayName; + if (displayName) { + return displayName; + } + var functionName = innerType.displayName || innerType.name || ""; + return functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName; + } + function getContextName(type) { + return type.displayName || "Context"; + } + function getComponentNameFromType(type) { + if (type == null) { + 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; + } + } + } + } + return null; + } + var hasOwnProperty = Object.prototype.hasOwnProperty; + var RESERVED_PROPS = { + key: true, + ref: true, + __self: true, + __source: true + }; + var specialPropKeyWarningShown, specialPropRefWarningShown, didWarnAboutStringRefs; + { + didWarnAboutStringRefs = {}; + } + function hasValidRef(config) { + { + if (hasOwnProperty.call(config, "ref")) { + var getter = Object.getOwnPropertyDescriptor(config, "ref").get; + if (getter && getter.isReactWarning) { + return false; + } + } + } + return config.ref !== undefined; + } + function hasValidKey(config) { + { + if (hasOwnProperty.call(config, "key")) { + var getter = Object.getOwnPropertyDescriptor(config, "key").get; + if (getter && getter.isReactWarning) { + return false; + } + } + } + return config.key !== undefined; + } + function defineKeyPropWarningGetter(props, displayName) { + var warnAboutAccessingKey = function() { + { + if (!specialPropKeyWarningShown) { + specialPropKeyWarningShown = true; + error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName); + } + } + }; + warnAboutAccessingKey.isReactWarning = true; + Object.defineProperty(props, "key", { + get: warnAboutAccessingKey, + configurable: true + }); + } + function defineRefPropWarningGetter(props, displayName) { + var warnAboutAccessingRef = function() { + { + if (!specialPropRefWarningShown) { + specialPropRefWarningShown = true; + error("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName); + } + } + }; + warnAboutAccessingRef.isReactWarning = true; + Object.defineProperty(props, "ref", { + get: warnAboutAccessingRef, + configurable: true + }); + } + function warnIfStringRefCannotBeAutoConverted(config) { + { + if (typeof config.ref === "string" && ReactCurrentOwner.current && config.__self && ReactCurrentOwner.current.stateNode !== config.__self) { + var componentName = getComponentNameFromType(ReactCurrentOwner.current.type); + if (!didWarnAboutStringRefs[componentName]) { + error('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. This case cannot be automatically converted to an arrow function. We ask you to manually fix this case by using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref', componentName, config.ref); + didWarnAboutStringRefs[componentName] = true; + } + } + } + } + var ReactElement = function(type, key, ref, self2, source, owner, props) { + var element = { + $$typeof: REACT_ELEMENT_TYPE, + type, + key, + ref, + props, + _owner: owner + }; + { + element._store = {}; + Object.defineProperty(element._store, "validated", { + configurable: false, + enumerable: false, + writable: true, + value: false + }); + Object.defineProperty(element, "_self", { + configurable: false, + enumerable: false, + writable: false, + value: self2 + }); + Object.defineProperty(element, "_source", { + configurable: false, + enumerable: false, + writable: false, + value: source + }); + if (Object.freeze) { + Object.freeze(element.props); + Object.freeze(element); + } + } + return element; + }; + function createElement(type, config, children) { + var propName; + var props = {}; + var key = null; + var ref = null; + var self2 = null; + var source = null; + if (config != null) { + if (hasValidRef(config)) { + ref = config.ref; + { + warnIfStringRefCannotBeAutoConverted(config); + } + } + if (hasValidKey(config)) { + { + checkKeyStringCoercion(config.key); + } + key = "" + config.key; + } + self2 = config.__self === undefined ? null : config.__self; + source = config.__source === undefined ? null : config.__source; + for (propName in config) { + if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { + props[propName] = config[propName]; + } + } + } + var childrenLength = arguments.length - 2; + if (childrenLength === 1) { + props.children = children; + } else if (childrenLength > 1) { + var childArray = Array(childrenLength); + for (var i = 0;i < childrenLength; i++) { + childArray[i] = arguments[i + 2]; + } + { + if (Object.freeze) { + Object.freeze(childArray); + } + } + props.children = childArray; + } + if (type && type.defaultProps) { + var defaultProps = type.defaultProps; + for (propName in defaultProps) { + if (props[propName] === undefined) { + props[propName] = defaultProps[propName]; + } + } + } + { + if (key || ref) { + var displayName = typeof type === "function" ? type.displayName || type.name || "Unknown" : type; + if (key) { + defineKeyPropWarningGetter(props, displayName); + } + if (ref) { + defineRefPropWarningGetter(props, displayName); + } + } + } + return ReactElement(type, key, ref, self2, source, ReactCurrentOwner.current, props); + } + function cloneAndReplaceKey(oldElement, newKey) { + var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props); + return newElement; + } + function cloneElement(element, config, children) { + if (element === null || element === undefined) { + throw new Error("React.cloneElement(...): The argument must be a React element, but you passed " + element + "."); + } + var propName; + var props = assign({}, element.props); + var key = element.key; + var ref = element.ref; + var self2 = element._self; + var source = element._source; + var owner = element._owner; + if (config != null) { + if (hasValidRef(config)) { + ref = config.ref; + owner = ReactCurrentOwner.current; + } + if (hasValidKey(config)) { + { + checkKeyStringCoercion(config.key); + } + key = "" + config.key; + } + var defaultProps; + if (element.type && element.type.defaultProps) { + defaultProps = element.type.defaultProps; + } + for (propName in config) { + if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { + if (config[propName] === undefined && defaultProps !== undefined) { + props[propName] = defaultProps[propName]; + } else { + props[propName] = config[propName]; + } + } + } + } + var childrenLength = arguments.length - 2; + if (childrenLength === 1) { + props.children = children; + } else if (childrenLength > 1) { + var childArray = Array(childrenLength); + for (var i = 0;i < childrenLength; i++) { + childArray[i] = arguments[i + 2]; + } + props.children = childArray; + } + return ReactElement(element.type, key, ref, self2, source, owner, props); + } + function isValidElement(object) { + return typeof object === "object" && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; + } + var SEPARATOR = "."; + var SUBSEPARATOR = ":"; + function escape(key) { + var escapeRegex = /[=:]/g; + var escaperLookup = { + "=": "=0", + ":": "=2" + }; + var escapedString = key.replace(escapeRegex, function(match) { + return escaperLookup[match]; + }); + return "$" + escapedString; + } + var didWarnAboutMaps = false; + var userProvidedKeyEscapeRegex = /\/+/g; + function escapeUserProvidedKey(text) { + return text.replace(userProvidedKeyEscapeRegex, "$&/"); + } + function getElementKey(element, index) { + if (typeof element === "object" && element !== null && element.key != null) { + { + checkKeyStringCoercion(element.key); + } + return escape("" + element.key); + } + return index.toString(36); + } + function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) { + var type = typeof children; + if (type === "undefined" || type === "boolean") { + children = null; + } + var invokeCallback = false; + if (children === null) { + invokeCallback = true; + } else { + switch (type) { + case "string": + case "number": + invokeCallback = true; + break; + case "object": + switch (children.$$typeof) { + case REACT_ELEMENT_TYPE: + case REACT_PORTAL_TYPE: + invokeCallback = true; + } + } + } + if (invokeCallback) { + var _child = children; + var mappedChild = callback(_child); + var childKey = nameSoFar === "" ? SEPARATOR + getElementKey(_child, 0) : nameSoFar; + if (isArray(mappedChild)) { + var escapedChildKey = ""; + if (childKey != null) { + escapedChildKey = escapeUserProvidedKey(childKey) + "/"; + } + mapIntoArray(mappedChild, array, escapedChildKey, "", function(c) { + return c; + }); + } else if (mappedChild != null) { + if (isValidElement(mappedChild)) { + { + if (mappedChild.key && (!_child || _child.key !== mappedChild.key)) { + checkKeyStringCoercion(mappedChild.key); + } + } + mappedChild = cloneAndReplaceKey(mappedChild, escapedPrefix + (mappedChild.key && (!_child || _child.key !== mappedChild.key) ? escapeUserProvidedKey("" + mappedChild.key) + "/" : "") + childKey); + } + array.push(mappedChild); + } + return 1; + } + var child; + var nextName; + var subtreeCount = 0; + var nextNamePrefix = nameSoFar === "" ? SEPARATOR : nameSoFar + SUBSEPARATOR; + if (isArray(children)) { + for (var i = 0;i < children.length; i++) { + child = children[i]; + nextName = nextNamePrefix + getElementKey(child, i); + subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback); + } + } else { + var iteratorFn = getIteratorFn(children); + if (typeof iteratorFn === "function") { + var iterableChildren = children; + { + if (iteratorFn === iterableChildren.entries) { + if (!didWarnAboutMaps) { + warn("Using Maps as children is not supported. Use an array of keyed ReactElements instead."); + } + didWarnAboutMaps = true; + } + } + var iterator = iteratorFn.call(iterableChildren); + var step; + var ii = 0; + while (!(step = iterator.next()).done) { + child = step.value; + nextName = nextNamePrefix + getElementKey(child, ii++); + subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback); + } + } else if (type === "object") { + var childrenString = String(children); + throw new Error("Objects are not valid as a React child (found: " + (childrenString === "[object Object]" ? "object with keys {" + Object.keys(children).join(", ") + "}" : childrenString) + "). If you meant to render a collection of children, use an array instead."); + } + } + return subtreeCount; + } + function mapChildren(children, func, context) { + if (children == null) { + return children; + } + var result = []; + var count = 0; + mapIntoArray(children, result, "", "", function(child) { + return func.call(context, child, count++); + }); + return result; + } + function countChildren(children) { + var n = 0; + mapChildren(children, function() { + n++; + }); + return n; + } + function forEachChildren(children, forEachFunc, forEachContext) { + mapChildren(children, function() { + forEachFunc.apply(this, arguments); + }, forEachContext); + } + function toArray(children) { + return mapChildren(children, function(child) { + return child; + }) || []; + } + function onlyChild(children) { + if (!isValidElement(children)) { + throw new Error("React.Children.only expected to receive a single React element child."); + } + return children; + } + function createContext(defaultValue) { + var context = { + $$typeof: REACT_CONTEXT_TYPE, + _currentValue: defaultValue, + _currentValue2: defaultValue, + _threadCount: 0, + Provider: null, + Consumer: null, + _defaultValue: null, + _globalName: null + }; + context.Provider = { + $$typeof: REACT_PROVIDER_TYPE, + _context: context + }; + var hasWarnedAboutUsingNestedContextConsumers = false; + var hasWarnedAboutUsingConsumerProvider = false; + var hasWarnedAboutDisplayNameOnConsumer = false; + { + var Consumer = { + $$typeof: REACT_CONTEXT_TYPE, + _context: context + }; + Object.defineProperties(Consumer, { + Provider: { + get: function() { + if (!hasWarnedAboutUsingConsumerProvider) { + hasWarnedAboutUsingConsumerProvider = true; + error("Rendering <Context.Consumer.Provider> is not supported and will be removed in a future major release. Did you mean to render <Context.Provider> instead?"); + } + return context.Provider; + }, + set: function(_Provider) { + context.Provider = _Provider; + } + }, + _currentValue: { + get: function() { + return context._currentValue; + }, + set: function(_currentValue) { + context._currentValue = _currentValue; + } + }, + _currentValue2: { + get: function() { + return context._currentValue2; + }, + set: function(_currentValue2) { + context._currentValue2 = _currentValue2; + } + }, + _threadCount: { + get: function() { + return context._threadCount; + }, + set: function(_threadCount) { + context._threadCount = _threadCount; + } + }, + Consumer: { + get: function() { + if (!hasWarnedAboutUsingNestedContextConsumers) { + hasWarnedAboutUsingNestedContextConsumers = true; + error("Rendering <Context.Consumer.Consumer> is not supported and will be removed in a future major release. Did you mean to render <Context.Consumer> instead?"); + } + return context.Consumer; + } + }, + displayName: { + get: function() { + return context.displayName; + }, + set: function(displayName) { + if (!hasWarnedAboutDisplayNameOnConsumer) { + warn("Setting `displayName` on Context.Consumer has no effect. You should set it directly on the context with Context.displayName = '%s'.", displayName); + hasWarnedAboutDisplayNameOnConsumer = true; + } + } + } + }); + context.Consumer = Consumer; + } + { + context._currentRenderer = null; + context._currentRenderer2 = null; + } + return context; + } + var Uninitialized = -1; + var Pending = 0; + var Resolved = 1; + var Rejected = 2; + function lazyInitializer(payload) { + if (payload._status === Uninitialized) { + var ctor = payload._result; + var thenable = ctor(); + thenable.then(function(moduleObject2) { + if (payload._status === Pending || payload._status === Uninitialized) { + var resolved = payload; + resolved._status = Resolved; + resolved._result = moduleObject2; + } + }, function(error2) { + if (payload._status === Pending || payload._status === Uninitialized) { + var rejected = payload; + rejected._status = Rejected; + rejected._result = error2; + } + }); + if (payload._status === Uninitialized) { + var pending = payload; + pending._status = Pending; + pending._result = thenable; + } + } + if (payload._status === Resolved) { + var moduleObject = payload._result; + { + if (moduleObject === undefined) { + error("lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n const MyComponent = lazy(() => import('./MyComponent'))\n\nDid you accidentally put curly braces around the import?", moduleObject); + } + } + { + if (!("default" in moduleObject)) { + error("lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n const MyComponent = lazy(() => import('./MyComponent'))", moduleObject); + } + } + return moduleObject.default; + } else { + throw payload._result; + } + } + function lazy(ctor) { + var payload = { + _status: Uninitialized, + _result: ctor + }; + var lazyType = { + $$typeof: REACT_LAZY_TYPE, + _payload: payload, + _init: lazyInitializer + }; + { + var defaultProps; + var propTypes; + Object.defineProperties(lazyType, { + defaultProps: { + configurable: true, + get: function() { + return defaultProps; + }, + set: function(newDefaultProps) { + error("React.lazy(...): It is not supported to assign `defaultProps` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it."); + defaultProps = newDefaultProps; + Object.defineProperty(lazyType, "defaultProps", { + enumerable: true + }); + } + }, + propTypes: { + configurable: true, + get: function() { + return propTypes; + }, + set: function(newPropTypes) { + error("React.lazy(...): It is not supported to assign `propTypes` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it."); + propTypes = newPropTypes; + Object.defineProperty(lazyType, "propTypes", { + enumerable: true + }); + } + } + }); + } + return lazyType; + } + function forwardRef(render) { + { + if (render != null && render.$$typeof === REACT_MEMO_TYPE) { + error("forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))."); + } else if (typeof render !== "function") { + error("forwardRef requires a render function but was given %s.", render === null ? "null" : typeof render); + } else { + if (render.length !== 0 && render.length !== 2) { + error("forwardRef render functions accept exactly two parameters: props and ref. %s", render.length === 1 ? "Did you forget to use the ref parameter?" : "Any additional parameter will be undefined."); + } + } + if (render != null) { + if (render.defaultProps != null || render.propTypes != null) { + error("forwardRef render functions do not support propTypes or defaultProps. Did you accidentally pass a React component?"); + } + } + } + var elementType = { + $$typeof: REACT_FORWARD_REF_TYPE, + render + }; + { + var ownName; + Object.defineProperty(elementType, "displayName", { + enumerable: false, + configurable: true, + get: function() { + return ownName; + }, + set: function(name) { + ownName = name; + if (!render.name && !render.displayName) { + render.displayName = name; + } + } + }); + } + return elementType; + } + var REACT_MODULE_REFERENCE; + { + REACT_MODULE_REFERENCE = Symbol.for("react.module.reference"); + } + function isValidElementType(type) { + if (typeof type === "string" || typeof type === "function") { + return true; + } + if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing) { + return true; + } + if (typeof type === "object" && type !== null) { + if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) { + return true; + } + } + return false; + } + function memo(type, compare) { + { + if (!isValidElementType(type)) { + error("memo: The first argument must be a component. Instead received: %s", type === null ? "null" : typeof type); + } + } + var elementType = { + $$typeof: REACT_MEMO_TYPE, + type, + compare: compare === undefined ? null : compare + }; + { + var ownName; + Object.defineProperty(elementType, "displayName", { + enumerable: false, + configurable: true, + get: function() { + return ownName; + }, + set: function(name) { + ownName = name; + if (!type.name && !type.displayName) { + type.displayName = name; + } + } + }); + } + return elementType; + } + function resolveDispatcher() { + var dispatcher = ReactCurrentDispatcher.current; + { + if (dispatcher === null) { + 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:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem."); + } + } + return dispatcher; + } + function useContext(Context) { + var dispatcher = resolveDispatcher(); + { + if (Context._context !== undefined) { + var realContext = Context._context; + if (realContext.Consumer === Context) { + error("Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be removed in a future major release. Did you mean to call useContext(Context) instead?"); + } else if (realContext.Provider === Context) { + error("Calling useContext(Context.Provider) is not supported. Did you mean to call useContext(Context) instead?"); + } + } + } + return dispatcher.useContext(Context); + } + function useState(initialState) { + var dispatcher = resolveDispatcher(); + return dispatcher.useState(initialState); + } + function useReducer(reducer, initialArg, init) { + var dispatcher = resolveDispatcher(); + return dispatcher.useReducer(reducer, initialArg, init); + } + function useRef(initialValue) { + var dispatcher = resolveDispatcher(); + return dispatcher.useRef(initialValue); + } + function useEffect(create, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useEffect(create, deps); + } + function useInsertionEffect(create, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useInsertionEffect(create, deps); + } + function useLayoutEffect(create, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useLayoutEffect(create, deps); + } + function useCallback(callback, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useCallback(callback, deps); + } + function useMemo(create, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useMemo(create, deps); + } + function useImperativeHandle(ref, create, deps) { + var dispatcher = resolveDispatcher(); + return dispatcher.useImperativeHandle(ref, create, deps); + } + function useDebugValue(value, formatterFn) { + { + var dispatcher = resolveDispatcher(); + return dispatcher.useDebugValue(value, formatterFn); + } + } + function useTransition() { + var dispatcher = resolveDispatcher(); + return dispatcher.useTransition(); + } + function useDeferredValue(value) { + var dispatcher = resolveDispatcher(); + return dispatcher.useDeferredValue(value); + } + function useId() { + var dispatcher = resolveDispatcher(); + return dispatcher.useId(); + } + function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { + var dispatcher = resolveDispatcher(); + return dispatcher.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); + } + 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) { + prevLog = console.log; + prevInfo = console.info; + prevWarn = console.warn; + prevError = console.error; + prevGroup = console.group; + prevGroupCollapsed = console.groupCollapsed; + prevGroupEnd = console.groupEnd; + var props = { + configurable: true, + enumerable: true, + value: disabledLog, + writable: true + }; + Object.defineProperties(console, { + info: props, + log: props, + warn: props, + error: props, + group: props, + groupCollapsed: props, + groupEnd: props + }); + } + disabledDepth++; + } + } + function reenableLogs() { + { + disabledDepth--; + if (disabledDepth === 0) { + var props = { + configurable: true, + enumerable: true, + writable: true + }; + 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 + }) + }); + } + if (disabledDepth < 0) { + error("disabledDepth fell below zero. This is a bug in React. Please file an issue."); + } + } + } + var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher; + var prefix; + function describeBuiltInComponentFrame(name, source, ownerFn) { + { + if (prefix === undefined) { + try { + throw Error(); + } catch (x) { + var match = x.stack.trim().match(/\n( *(at )?)/); + prefix = match && match[1] || ""; + } + } + return "\n" + prefix + name; + } + } + var reentry = false; + var componentFrameCache; + { + var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map; + componentFrameCache = new PossiblyWeakMap; + } + function describeNativeComponentFrame(fn, construct) { + if (!fn || reentry) { + return ""; + } + { + var frame = componentFrameCache.get(fn); + if (frame !== undefined) { + return frame; + } + } + var control; + reentry = true; + var previousPrepareStackTrace = Error.prepareStackTrace; + Error.prepareStackTrace = undefined; + var previousDispatcher; + { + previousDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = null; + disableLogs(); + } + try { + if (construct) { + var Fake = function() { + throw Error(); + }; + Object.defineProperty(Fake.prototype, "props", { + set: function() { + throw Error(); + } + }); + if (typeof Reflect === "object" && Reflect.construct) { + 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) { + if (sample && control && typeof sample.stack === "string") { + 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]) { + c--; + } + for (;s >= 1 && c >= 0; s--, c--) { + if (sampleLines[s] !== controlLines[c]) { + if (s !== 1 || c !== 1) { + do { + s--; + c--; + if (c < 0 || sampleLines[s] !== controlLines[c]) { + var _frame = "\n" + sampleLines[s].replace(" at new ", " at "); + if (fn.displayName && _frame.includes("<anonymous>")) { + _frame = _frame.replace("<anonymous>", fn.displayName); + } + { + if (typeof fn === "function") { + componentFrameCache.set(fn, _frame); + } + } + return _frame; + } + } while (s >= 1 && c >= 0); + } + break; + } + } + } + } finally { + reentry = false; + { + ReactCurrentDispatcher$1.current = previousDispatcher; + reenableLogs(); + } + Error.prepareStackTrace = previousPrepareStackTrace; + } + var name = fn ? fn.displayName || fn.name : ""; + var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ""; + { + if (typeof fn === "function") { + componentFrameCache.set(fn, syntheticFrame); + } + } + return syntheticFrame; + } + function describeFunctionComponentFrame(fn, source, ownerFn) { + { + return describeNativeComponentFrame(fn, false); + } + } + function shouldConstruct(Component2) { + var prototype = Component2.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: + return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); + case REACT_LAZY_TYPE: { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + try { + return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); + } catch (x) { + } + } + } + } + return ""; + } + var loggedTypeFailures = {}; + var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; + function setCurrentlyValidatingElement(element) { + { + if (element) { + var owner = element._owner; + var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); + ReactDebugCurrentFrame$1.setExtraStackFrame(stack); + } else { + ReactDebugCurrentFrame$1.setExtraStackFrame(null); + } + } + } + function checkPropTypes(typeSpecs, values, location, componentName, element) { + { + var has = Function.call.bind(hasOwnProperty); + for (var typeSpecName in typeSpecs) { + if (has(typeSpecs, typeSpecName)) { + var error$1 = undefined; + try { + if (typeof typeSpecs[typeSpecName] !== "function") { + 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)) { + loggedTypeFailures[error$1.message] = true; + setCurrentlyValidatingElement(element); + error("Failed %s type: %s", location, error$1.message); + setCurrentlyValidatingElement(null); + } + } + } + } + } + function setCurrentlyValidatingElement$1(element) { + { + if (element) { + var owner = element._owner; + var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); + setExtraStackFrame(stack); + } else { + setExtraStackFrame(null); + } + } + } + var propTypesMisspellWarningShown; + { + propTypesMisspellWarningShown = false; + } + function getDeclarationErrorAddendum() { + if (ReactCurrentOwner.current) { + var name = getComponentNameFromType(ReactCurrentOwner.current.type); + if (name) { + return "\n\nCheck the render method of `" + name + "`."; + } + } + return ""; + } + function getSourceInfoErrorAddendum(source) { + if (source !== undefined) { + var fileName = source.fileName.replace(/^.*[\\\/]/, ""); + var lineNumber = source.lineNumber; + return "\n\nCheck your code at " + fileName + ":" + lineNumber + "."; + } + return ""; + } + function getSourceInfoErrorAddendumForProps(elementProps) { + if (elementProps !== null && elementProps !== undefined) { + return getSourceInfoErrorAddendum(elementProps.__source); + } + return ""; + } + var ownerHasKeyUseWarning = {}; + function getCurrentComponentErrorInfo(parentType) { + var info = getDeclarationErrorAddendum(); + if (!info) { + var parentName = typeof parentType === "string" ? parentType : parentType.displayName || parentType.name; + if (parentName) { + info = "\n\nCheck the top-level render call using <" + parentName + ">."; + } + } + return info; + } + function validateExplicitKey(element, parentType) { + if (!element._store || element._store.validated || element.key != null) { + return; + } + element._store.validated = true; + var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); + if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { + return; + } + ownerHasKeyUseWarning[currentComponentErrorInfo] = true; + var childOwner = ""; + if (element && element._owner && element._owner !== ReactCurrentOwner.current) { + childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + "."; + } + { + setCurrentlyValidatingElement$1(element); + error('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner); + setCurrentlyValidatingElement$1(null); + } + } + function validateChildKeys(node, parentType) { + if (typeof node !== "object") { + return; + } + if (isArray(node)) { + for (var i = 0;i < node.length; i++) { + var child = node[i]; + if (isValidElement(child)) { + validateExplicitKey(child, parentType); + } + } + } else if (isValidElement(node)) { + if (node._store) { + node._store.validated = true; + } + } else if (node) { + var iteratorFn = getIteratorFn(node); + if (typeof iteratorFn === "function") { + if (iteratorFn !== node.entries) { + var iterator = iteratorFn.call(node); + var step; + while (!(step = iterator.next()).done) { + if (isValidElement(step.value)) { + validateExplicitKey(step.value, parentType); + } + } + } + } + } + } + function validatePropTypes(element) { + { + var type = element.type; + if (type === null || type === undefined || typeof type === "string") { + return; + } + var propTypes; + if (typeof type === "function") { + propTypes = type.propTypes; + } else if (typeof type === "object" && (type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_MEMO_TYPE)) { + propTypes = type.propTypes; + } else { + return; + } + if (propTypes) { + var name = getComponentNameFromType(type); + checkPropTypes(propTypes, element.props, "prop", name, element); + } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) { + propTypesMisspellWarningShown = true; + var _name = getComponentNameFromType(type); + error("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?", _name || "Unknown"); + } + if (typeof type.getDefaultProps === "function" && !type.getDefaultProps.isReactClassApproved) { + error("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead."); + } + } + } + function validateFragmentProps(fragment) { + { + var keys = Object.keys(fragment.props); + for (var i = 0;i < keys.length; i++) { + var key = keys[i]; + if (key !== "children" && key !== "key") { + setCurrentlyValidatingElement$1(fragment); + error("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.", key); + setCurrentlyValidatingElement$1(null); + break; + } + } + if (fragment.ref !== null) { + setCurrentlyValidatingElement$1(fragment); + error("Invalid attribute `ref` supplied to `React.Fragment`."); + setCurrentlyValidatingElement$1(null); + } + } + } + function createElementWithValidation(type, props, children) { + var validType = isValidElementType(type); + if (!validType) { + 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 sourceInfo = getSourceInfoErrorAddendumForProps(props); + if (sourceInfo) { + info += sourceInfo; + } else { + info += getDeclarationErrorAddendum(); + } + var typeString; + if (type === null) { + typeString = "null"; + } else if (isArray(type)) { + typeString = "array"; + } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) { + typeString = "<" + (getComponentNameFromType(type.type) || "Unknown") + " />"; + info = " Did you accidentally export a JSX literal instead of a component?"; + } else { + typeString = typeof type; + } + { + error("React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s", typeString, info); + } + } + var element = createElement.apply(this, arguments); + if (element == null) { + return element; + } + if (validType) { + for (var i = 2;i < arguments.length; i++) { + validateChildKeys(arguments[i], type); + } + } + if (type === REACT_FRAGMENT_TYPE) { + validateFragmentProps(element); + } else { + validatePropTypes(element); + } + return element; + } + var didWarnAboutDeprecatedCreateFactory = false; + function createFactoryWithValidation(type) { + var validatedFactory = createElementWithValidation.bind(null, type); + validatedFactory.type = type; + { + if (!didWarnAboutDeprecatedCreateFactory) { + didWarnAboutDeprecatedCreateFactory = true; + warn("React.createFactory() is deprecated and will be removed in a future major release. Consider using JSX or use React.createElement() directly instead."); + } + Object.defineProperty(validatedFactory, "type", { + enumerable: false, + get: function() { + warn("Factory.type is deprecated. Access the class directly before passing it to createFactory."); + Object.defineProperty(this, "type", { + value: type + }); + return type; + } + }); + } + return validatedFactory; + } + function cloneElementWithValidation(element, props, children) { + var newElement = cloneElement.apply(this, arguments); + for (var i = 2;i < arguments.length; i++) { + validateChildKeys(arguments[i], newElement.type); + } + validatePropTypes(newElement); + return newElement; + } + function startTransition(scope, options) { + var prevTransition = ReactCurrentBatchConfig.transition; + ReactCurrentBatchConfig.transition = {}; + var currentTransition = ReactCurrentBatchConfig.transition; + { + ReactCurrentBatchConfig.transition._updatedFibers = new Set; + } + try { + scope(); + } finally { + ReactCurrentBatchConfig.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(); + } + } + } + } + var didWarnAboutMessageChannel = false; + var enqueueTaskImpl = null; + function enqueueTask(task) { + if (enqueueTaskImpl === null) { + try { + var requireString = ("require" + Math.random()).slice(0, 7); + var nodeRequire = module && module[requireString]; + enqueueTaskImpl = nodeRequire.call(module, "timers").setImmediate; + } catch (_err) { + enqueueTaskImpl = function(callback) { + { + if (didWarnAboutMessageChannel === false) { + didWarnAboutMessageChannel = true; + if (typeof MessageChannel === "undefined") { + error("This browser does not have a MessageChannel implementation, so enqueuing tasks via await act(async () => ...) will fail. Please file an issue at https://github.com/facebook/react/issues if you encounter this warning."); + } + } + } + var channel = new MessageChannel; + channel.port1.onmessage = callback; + channel.port2.postMessage(undefined); + }; + } + } + return enqueueTaskImpl(task); + } + var actScopeDepth = 0; + var didWarnNoAwaitAct = false; + function act(callback) { + { + var prevActScopeDepth = actScopeDepth; + actScopeDepth++; + if (ReactCurrentActQueue.current === null) { + ReactCurrentActQueue.current = []; + } + var prevIsBatchingLegacy = ReactCurrentActQueue.isBatchingLegacy; + var result; + try { + ReactCurrentActQueue.isBatchingLegacy = true; + result = callback(); + if (!prevIsBatchingLegacy && ReactCurrentActQueue.didScheduleLegacyUpdate) { + var queue = ReactCurrentActQueue.current; + if (queue !== null) { + ReactCurrentActQueue.didScheduleLegacyUpdate = false; + flushActQueue(queue); + } + } + } catch (error2) { + popActScope(prevActScopeDepth); + throw error2; + } finally { + ReactCurrentActQueue.isBatchingLegacy = prevIsBatchingLegacy; + } + if (result !== null && typeof result === "object" && typeof result.then === "function") { + var thenableResult = result; + var wasAwaited = false; + var thenable = { + then: function(resolve, reject) { + wasAwaited = true; + thenableResult.then(function(returnValue2) { + popActScope(prevActScopeDepth); + if (actScopeDepth === 0) { + recursivelyFlushAsyncActWork(returnValue2, resolve, reject); + } else { + resolve(returnValue2); + } + }, function(error2) { + popActScope(prevActScopeDepth); + reject(error2); + }); + } + }; + { + if (!didWarnNoAwaitAct && typeof Promise !== "undefined") { + Promise.resolve().then(function() { + }).then(function() { + if (!wasAwaited) { + didWarnNoAwaitAct = true; + error("You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);"); + } + }); + } + } + return thenable; + } else { + var returnValue = result; + popActScope(prevActScopeDepth); + if (actScopeDepth === 0) { + var _queue = ReactCurrentActQueue.current; + if (_queue !== null) { + flushActQueue(_queue); + ReactCurrentActQueue.current = null; + } + var _thenable = { + then: function(resolve, reject) { + if (ReactCurrentActQueue.current === null) { + ReactCurrentActQueue.current = []; + recursivelyFlushAsyncActWork(returnValue, resolve, reject); + } else { + resolve(returnValue); + } + } + }; + return _thenable; + } else { + var _thenable2 = { + then: function(resolve, reject) { + resolve(returnValue); + } + }; + return _thenable2; + } + } + } + } + function popActScope(prevActScopeDepth) { + { + if (prevActScopeDepth !== actScopeDepth - 1) { + error("You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. "); + } + actScopeDepth = prevActScopeDepth; + } + } + function recursivelyFlushAsyncActWork(returnValue, resolve, reject) { + { + var queue = ReactCurrentActQueue.current; + if (queue !== null) { + try { + flushActQueue(queue); + enqueueTask(function() { + if (queue.length === 0) { + ReactCurrentActQueue.current = null; + resolve(returnValue); + } else { + recursivelyFlushAsyncActWork(returnValue, resolve, reject); + } + }); + } catch (error2) { + reject(error2); + } + } else { + resolve(returnValue); + } + } + } + var isFlushing = false; + function flushActQueue(queue) { + { + if (!isFlushing) { + isFlushing = true; + var i = 0; + try { + for (;i < queue.length; i++) { + var callback = queue[i]; + do { + callback = callback(true); + } while (callback !== null); + } + queue.length = 0; + } catch (error2) { + queue = queue.slice(i + 1); + throw error2; + } finally { + isFlushing = false; + } + } + } + } + var createElement$1 = createElementWithValidation; + var cloneElement$1 = cloneElementWithValidation; + var createFactory = createFactoryWithValidation; + var Children = { + map: mapChildren, + forEach: forEachChildren, + count: countChildren, + toArray, + only: onlyChild + }; + exports.Children = Children; + exports.Component = Component; + exports.Fragment = REACT_FRAGMENT_TYPE; + exports.Profiler = REACT_PROFILER_TYPE; + exports.PureComponent = PureComponent; + exports.StrictMode = REACT_STRICT_MODE_TYPE; + exports.Suspense = REACT_SUSPENSE_TYPE; + exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactSharedInternals; + exports.act = act; + exports.cloneElement = cloneElement$1; + exports.createContext = createContext; + exports.createElement = createElement$1; + exports.createFactory = createFactory; + exports.createRef = createRef; + exports.forwardRef = forwardRef; + exports.isValidElement = isValidElement; + exports.lazy = lazy; + exports.memo = memo; + exports.startTransition = startTransition; + exports.unstable_act = act; + exports.useCallback = useCallback; + exports.useContext = useContext; + exports.useDebugValue = useDebugValue; + exports.useDeferredValue = useDeferredValue; + exports.useEffect = useEffect; + exports.useId = useId; + exports.useImperativeHandle = useImperativeHandle; + exports.useInsertionEffect = useInsertionEffect; + exports.useLayoutEffect = useLayoutEffect; + exports.useMemo = useMemo; + exports.useReducer = useReducer; + exports.useRef = useRef; + exports.useState = useState; + exports.useSyncExternalStore = useSyncExternalStore; + exports.useTransition = useTransition; + exports.version = ReactVersion; + if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === "function") { + __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error); + } + })(); + } +}); + +// node_modules/react/index.js +var require_react = __commonJS((exports, module) => { + var react_development = __toESM(require_react_development(), 1); + if (false) { + } else { + module.exports = react_development; + } +}); + +// node_modules/scheduler/cjs/scheduler.development.js +var require_scheduler_development = __commonJS((exports) => { + if (true) { + (function() { + 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) { + heap[parentIndex] = node; + heap[index] = parent; + index = parentIndex; + } else { + 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 (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 { + return; + } + } + } + function compare(a, b) { + var diff = a.sortIndex - b.sortIndex; + return diff !== 0 ? diff : a.id - b.id; + } + var ImmediatePriority = 1; + var UserBlockingPriority = 2; + var NormalPriority = 3; + var LowPriority = 4; + var IdlePriority = 5; + function markTaskErrored(task, ms) { + } + 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; + }; + } + var maxSigned31BitInt = 1073741823; + var IMMEDIATE_PRIORITY_TIMEOUT = -1; + var USER_BLOCKING_PRIORITY_TIMEOUT = 250; + var NORMAL_PRIORITY_TIMEOUT = 5000; + var LOW_PRIORITY_TIMEOUT = 1e4; + var IDLE_PRIORITY_TIMEOUT = maxSigned31BitInt; + var taskQueue = []; + var timerQueue = []; + var taskIdCounter = 1; + var currentTask = null; + var currentPriorityLevel = NormalPriority; + var isPerformingWork = false; + var isHostCallbackScheduled = false; + var isHostTimeoutScheduled = false; + var localSetTimeout = typeof setTimeout === "function" ? setTimeout : null; + var localClearTimeout = typeof clearTimeout === "function" ? clearTimeout : null; + var localSetImmediate = typeof setImmediate !== "undefined" ? setImmediate : null; + var isInputPending = typeof navigator !== "undefined" && navigator.scheduling !== undefined && navigator.scheduling.isInputPending !== undefined ? navigator.scheduling.isInputPending.bind(navigator.scheduling) : null; + function advanceTimers(currentTime) { + var timer = peek(timerQueue); + while (timer !== null) { + if (timer.callback === null) { + pop(timerQueue); + } else if (timer.startTime <= currentTime) { + pop(timerQueue); + timer.sortIndex = timer.expirationTime; + push(taskQueue, timer); + } else { + 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, initialTime2) { + isHostCallbackScheduled = false; + if (isHostTimeoutScheduled) { + isHostTimeoutScheduled = false; + cancelHostTimeout(); + } + isPerformingWork = true; + var previousPriorityLevel = currentPriorityLevel; + try { + if (enableProfiling) { + try { + return workLoop(hasTimeRemaining, initialTime2); + } catch (error) { + if (currentTask !== null) { + var currentTime = exports.unstable_now(); + markTaskErrored(currentTask, currentTime); + currentTask.isQueued = false; + } + throw error; + } + } else { + return workLoop(hasTimeRemaining, initialTime2); + } + } finally { + currentTask = null; + currentPriorityLevel = previousPriorityLevel; + isPerformingWork = false; + } + } + function workLoop(hasTimeRemaining, initialTime2) { + var currentTime = initialTime2; + advanceTimers(currentTime); + currentTask = peek(taskQueue); + while (currentTask !== null && !enableSchedulerDebugging) { + if (currentTask.expirationTime > currentTime && (!hasTimeRemaining || shouldYieldToHost())) { + 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); + } + 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: + priorityLevel = NormalPriority; + break; + default: + priorityLevel = currentPriorityLevel; + break; + } + var previousPriorityLevel = currentPriorityLevel; + currentPriorityLevel = priorityLevel; + try { + return eventHandler(); + } finally { + currentPriorityLevel = previousPriorityLevel; + } + } + function unstable_wrapCallback(callback) { + var parentPriorityLevel = currentPriorityLevel; + return function() { + 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 startTime2; + if (typeof options === "object" && options !== null) { + var delay = options.delay; + if (typeof delay === "number" && delay > 0) { + startTime2 = currentTime + delay; + } else { + startTime2 = currentTime; + } + } else { + startTime2 = 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 = startTime2 + timeout; + var newTask = { + id: taskIdCounter++, + callback, + priorityLevel, + startTime: startTime2, + expirationTime, + sortIndex: -1 + }; + if (startTime2 > currentTime) { + newTask.sortIndex = startTime2; + push(timerQueue, newTask); + if (peek(taskQueue) === null && newTask === peek(timerQueue)) { + if (isHostTimeoutScheduled) { + cancelHostTimeout(); + } else { + isHostTimeoutScheduled = true; + } + requestHostTimeout(handleTimeout, startTime2 - currentTime); + } + } else { + newTask.sortIndex = expirationTime; + push(taskQueue, newTask); + 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) { + task.callback = null; + } + function unstable_getCurrentPriorityLevel() { + return currentPriorityLevel; + } + var isMessageLoopRunning = false; + var scheduledHostCallback = null; + var taskTimeoutID = -1; + var frameInterval = frameYieldMs; + var startTime = -1; + function shouldYieldToHost() { + var timeElapsed = exports.unstable_now() - startTime; + if (timeElapsed < frameInterval) { + return false; + } + return true; + } + function requestPaint() { + } + function forceFrameRate(fps) { + if (fps < 0 || fps > 125) { + 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 { + frameInterval = frameYieldMs; + } + } + var performWorkUntilDeadline = function() { + if (scheduledHostCallback !== null) { + var currentTime = exports.unstable_now(); + startTime = currentTime; + var hasTimeRemaining = true; + var hasMoreWork = true; + try { + hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime); + } finally { + if (hasMoreWork) { + schedulePerformWorkUntilDeadline(); + } else { + isMessageLoopRunning = false; + scheduledHostCallback = null; + } + } + } else { + isMessageLoopRunning = false; + } + }; + var schedulePerformWorkUntilDeadline; + if (typeof localSetImmediate === "function") { + schedulePerformWorkUntilDeadline = function() { + localSetImmediate(performWorkUntilDeadline); + }; + } else if (typeof MessageChannel !== "undefined") { + var channel = new MessageChannel; + var port = channel.port2; + channel.port1.onmessage = performWorkUntilDeadline; + schedulePerformWorkUntilDeadline = function() { + port.postMessage(null); + }; + } else { + 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; + if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === "function") { + __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error); + } + })(); + } +}); + +// node_modules/scheduler/index.js +var require_scheduler = __commonJS((exports, module) => { + var scheduler_development = __toESM(require_scheduler_development(), 1); + if (false) { + } else { + module.exports = scheduler_development; + } +}); + +// node_modules/react-dom/cjs/react-dom.development.js +var require_react_dom_development = __commonJS((exports) => { + var React = __toESM(require_react(), 1); + var Scheduler = __toESM(require_scheduler(), 1); + if (true) { + (function() { + if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === "function") { + __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error); + } + var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; + var suppressWarning = false; + function setSuppressWarning(newSuppressWarning) { + { + suppressWarning = newSuppressWarning; + } + } + 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) { + { + var ReactDebugCurrentFrame2 = ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame2.getStackAddendum(); + if (stack !== "") { + format += "%s"; + args = args.concat([stack]); + } + var argsWithFormat = args.map(function(item) { + return String(item); + }); + argsWithFormat.unshift("Warning: " + format); + Function.prototype.apply.call(console[level], console, argsWithFormat); + } + } + var FunctionComponent = 0; + var ClassComponent = 1; + var IndeterminateComponent = 2; + var HostRoot = 3; + var HostPortal = 4; + 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 enableClientRenderFallbackOnTextMismatch = true; + var enableNewReconciler = false; + var enableLazyContextPropagation = false; + var enableLegacyHidden = false; + var enableSuspenseAvoidThisFallback = false; + var disableCommentsAsDOMContainers = true; + var enableCustomElementPropertySupport = false; + var warnAboutStringRefs = true; + var enableSchedulingProfiler = true; + var enableProfilerTimer = true; + var enableProfilerCommitHooks = true; + var allNativeEvents = new Set; + var registrationNameDependencies = {}; + var possibleRegistrationNames = {}; + function registerTwoPhaseEvent(registrationName, dependencies) { + registerDirectEvent(registrationName, dependencies); + registerDirectEvent(registrationName + "Capture", dependencies); + } + function registerDirectEvent(registrationName, dependencies) { + { + if (registrationNameDependencies[registrationName]) { + error("EventRegistry: More than one plugin attempted to publish the same registration name, `%s`.", registrationName); + } + } + registrationNameDependencies[registrationName] = dependencies; + { + var lowerCasedName = registrationName.toLowerCase(); + possibleRegistrationNames[lowerCasedName] = registrationName; + if (registrationName === "onDoubleClick") { + possibleRegistrationNames.ondblclick = registrationName; + } + } + for (var i = 0;i < dependencies.length; i++) { + allNativeEvents.add(dependencies[i]); + } + } + var canUseDOM = !!(typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined"); + var hasOwnProperty = Object.prototype.hasOwnProperty; + function typeName(value) { + { + var hasToStringTag = typeof Symbol === "function" && Symbol.toStringTag; + var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object"; + return type; + } + } + function willCoercionThrow(value) { + { + try { + testStringCoercion(value); + return false; + } catch (e) { + return true; + } + } + } + function testStringCoercion(value) { + return "" + value; + } + function checkAttributeStringCoercion(value, attributeName) { + { + if (willCoercionThrow(value)) { + error("The provided `%s` attribute is an unsupported type %s. This value must be coerced to a string before before using it here.", attributeName, typeName(value)); + return testStringCoercion(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); + } + } + } + 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); + } + } + } + function checkCSSPropertyStringCoercion(value, propName) { + { + if (willCoercionThrow(value)) { + error("The provided `%s` CSS property is an unsupported type %s. This value must be coerced to a string before before using it here.", propName, typeName(value)); + return testStringCoercion(value); + } + } + } + function checkHtmlStringCoercion(value) { + { + if (willCoercionThrow(value)) { + error("The provided HTML markup uses a value of unsupported type %s. This value must be coerced to a string before before using it here.", typeName(value)); + return testStringCoercion(value); + } + } + } + function checkFormFieldValueStringCoercion(value) { + { + if (willCoercionThrow(value)) { + error("Form field values (value, checked, defaultValue, or defaultChecked props) must be strings, not %s. This value must be coerced to a string before before using it here.", typeName(value)); + return testStringCoercion(value); + } + } + } + var RESERVED = 0; + var STRING = 1; + var BOOLEANISH_STRING = 2; + var BOOLEAN = 3; + var OVERLOADED_BOOLEAN = 4; + var NUMERIC = 5; + var POSITIVE_NUMERIC = 6; + var ATTRIBUTE_NAME_START_CHAR = ":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD"; + var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + "\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040"; + var VALID_ATTRIBUTE_NAME_REGEX = new RegExp("^[" + ATTRIBUTE_NAME_START_CHAR + "][" + ATTRIBUTE_NAME_CHAR + "]*$"); + var illegalAttributeNameCache = {}; + var validatedAttributeNameCache = {}; + function isAttributeNameSafe(attributeName) { + if (hasOwnProperty.call(validatedAttributeNameCache, attributeName)) { + return true; + } + if (hasOwnProperty.call(illegalAttributeNameCache, attributeName)) { + return false; + } + if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) { + validatedAttributeNameCache[attributeName] = true; + return true; + } + illegalAttributeNameCache[attributeName] = true; + { + error("Invalid attribute name: `%s`", attributeName); + } + return false; + } + function shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag) { + if (propertyInfo !== null) { + return propertyInfo.type === RESERVED; + } + if (isCustomComponentTag) { + return false; + } + if (name.length > 2 && (name[0] === "o" || name[0] === "O") && (name[1] === "n" || name[1] === "N")) { + return true; + } + return false; + } + function shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) { + if (propertyInfo !== null && propertyInfo.type === RESERVED) { + return false; + } + switch (typeof value) { + case "function": + case "symbol": + return true; + case "boolean": { + if (isCustomComponentTag) { + return false; + } + if (propertyInfo !== null) { + return !propertyInfo.acceptsBooleans; + } else { + var prefix2 = name.toLowerCase().slice(0, 5); + return prefix2 !== "data-" && prefix2 !== "aria-"; + } + } + default: + return false; + } + } + function shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag) { + if (value === null || typeof value === "undefined") { + return true; + } + if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag)) { + return true; + } + if (isCustomComponentTag) { + return false; + } + if (propertyInfo !== null) { + switch (propertyInfo.type) { + case BOOLEAN: + return !value; + case OVERLOADED_BOOLEAN: + return value === false; + case NUMERIC: + return isNaN(value); + case POSITIVE_NUMERIC: + return isNaN(value) || value < 1; + } + } + return false; + } + function getPropertyInfo(name) { + return properties.hasOwnProperty(name) ? properties[name] : null; + } + function PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace, sanitizeURL2, removeEmptyString) { + this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN; + this.attributeName = attributeName; + this.attributeNamespace = attributeNamespace; + this.mustUseProperty = mustUseProperty; + this.propertyName = name; + this.type = type; + this.sanitizeURL = sanitizeURL2; + this.removeEmptyString = removeEmptyString; + } + var properties = {}; + var reservedProps = [ + "children", + "dangerouslySetInnerHTML", + "defaultValue", + "defaultChecked", + "innerHTML", + "suppressContentEditableWarning", + "suppressHydrationWarning", + "style" + ]; + reservedProps.forEach(function(name) { + properties[name] = new PropertyInfoRecord(name, RESERVED, false, name, null, false, false); + }); + [["acceptCharset", "accept-charset"], ["className", "class"], ["htmlFor", "for"], ["httpEquiv", "http-equiv"]].forEach(function(_ref) { + var name = _ref[0], attributeName = _ref[1]; + properties[name] = new PropertyInfoRecord(name, STRING, false, attributeName, null, false, false); + }); + ["contentEditable", "draggable", "spellCheck", "value"].forEach(function(name) { + properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, name.toLowerCase(), null, false, false); + }); + ["autoReverse", "externalResourcesRequired", "focusable", "preserveAlpha"].forEach(function(name) { + properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, name, null, false, false); + }); + [ + "allowFullScreen", + "async", + "autoFocus", + "autoPlay", + "controls", + "default", + "defer", + "disabled", + "disablePictureInPicture", + "disableRemotePlayback", + "formNoValidate", + "hidden", + "loop", + "noModule", + "noValidate", + "open", + "playsInline", + "readOnly", + "required", + "reversed", + "scoped", + "seamless", + "itemScope" + ].forEach(function(name) { + properties[name] = new PropertyInfoRecord(name, BOOLEAN, false, name.toLowerCase(), null, false, false); + }); + [ + "checked", + "multiple", + "muted", + "selected" + ].forEach(function(name) { + properties[name] = new PropertyInfoRecord(name, BOOLEAN, true, name, null, false, false); + }); + [ + "capture", + "download" + ].forEach(function(name) { + properties[name] = new PropertyInfoRecord(name, OVERLOADED_BOOLEAN, false, name, null, false, false); + }); + [ + "cols", + "rows", + "size", + "span" + ].forEach(function(name) { + properties[name] = new PropertyInfoRecord(name, POSITIVE_NUMERIC, false, name, null, false, false); + }); + ["rowSpan", "start"].forEach(function(name) { + properties[name] = new PropertyInfoRecord(name, NUMERIC, false, name.toLowerCase(), null, false, false); + }); + var CAMELIZE = /[\-\:]([a-z])/g; + var capitalize = function(token) { + return token[1].toUpperCase(); + }; + [ + "accent-height", + "alignment-baseline", + "arabic-form", + "baseline-shift", + "cap-height", + "clip-path", + "clip-rule", + "color-interpolation", + "color-interpolation-filters", + "color-profile", + "color-rendering", + "dominant-baseline", + "enable-background", + "fill-opacity", + "fill-rule", + "flood-color", + "flood-opacity", + "font-family", + "font-size", + "font-size-adjust", + "font-stretch", + "font-style", + "font-variant", + "font-weight", + "glyph-name", + "glyph-orientation-horizontal", + "glyph-orientation-vertical", + "horiz-adv-x", + "horiz-origin-x", + "image-rendering", + "letter-spacing", + "lighting-color", + "marker-end", + "marker-mid", + "marker-start", + "overline-position", + "overline-thickness", + "paint-order", + "panose-1", + "pointer-events", + "rendering-intent", + "shape-rendering", + "stop-color", + "stop-opacity", + "strikethrough-position", + "strikethrough-thickness", + "stroke-dasharray", + "stroke-dashoffset", + "stroke-linecap", + "stroke-linejoin", + "stroke-miterlimit", + "stroke-opacity", + "stroke-width", + "text-anchor", + "text-decoration", + "text-rendering", + "underline-position", + "underline-thickness", + "unicode-bidi", + "unicode-range", + "units-per-em", + "v-alphabetic", + "v-hanging", + "v-ideographic", + "v-mathematical", + "vector-effect", + "vert-adv-y", + "vert-origin-x", + "vert-origin-y", + "word-spacing", + "writing-mode", + "xmlns:xlink", + "x-height" + ].forEach(function(attributeName) { + var name = attributeName.replace(CAMELIZE, capitalize); + properties[name] = new PropertyInfoRecord(name, STRING, false, attributeName, null, false, false); + }); + [ + "xlink:actuate", + "xlink:arcrole", + "xlink:role", + "xlink:show", + "xlink:title", + "xlink:type" + ].forEach(function(attributeName) { + var name = attributeName.replace(CAMELIZE, capitalize); + properties[name] = new PropertyInfoRecord(name, STRING, false, attributeName, "http://www.w3.org/1999/xlink", false, false); + }); + [ + "xml:base", + "xml:lang", + "xml:space" + ].forEach(function(attributeName) { + var name = attributeName.replace(CAMELIZE, capitalize); + properties[name] = new PropertyInfoRecord(name, STRING, false, attributeName, "http://www.w3.org/XML/1998/namespace", false, false); + }); + ["tabIndex", "crossOrigin"].forEach(function(attributeName) { + properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, attributeName.toLowerCase(), null, false, false); + }); + var xlinkHref = "xlinkHref"; + properties[xlinkHref] = new PropertyInfoRecord("xlinkHref", STRING, false, "xlink:href", "http://www.w3.org/1999/xlink", true, false); + ["src", "href", "action", "formAction"].forEach(function(attributeName) { + properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, attributeName.toLowerCase(), null, true, true); + }); + var isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i; + var didWarn = false; + function sanitizeURL(url) { + { + if (!didWarn && isJavaScriptProtocol.test(url)) { + didWarn = true; + error("A future version of React will block javascript: URLs as a security precaution. Use event handlers instead if you can. If you need to generate unsafe HTML try using dangerouslySetInnerHTML instead. React was passed %s.", JSON.stringify(url)); + } + } + } + function getValueForProperty(node, name, expected, propertyInfo) { + { + if (propertyInfo.mustUseProperty) { + var propertyName = propertyInfo.propertyName; + return node[propertyName]; + } else { + { + checkAttributeStringCoercion(expected, name); + } + if (propertyInfo.sanitizeURL) { + sanitizeURL("" + expected); + } + var attributeName = propertyInfo.attributeName; + var stringValue = null; + if (propertyInfo.type === OVERLOADED_BOOLEAN) { + if (node.hasAttribute(attributeName)) { + var value = node.getAttribute(attributeName); + if (value === "") { + return true; + } + if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { + return value; + } + if (value === "" + expected) { + return expected; + } + return value; + } + } else if (node.hasAttribute(attributeName)) { + if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { + return node.getAttribute(attributeName); + } + if (propertyInfo.type === BOOLEAN) { + return expected; + } + stringValue = node.getAttribute(attributeName); + } + if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { + return stringValue === null ? expected : stringValue; + } else if (stringValue === "" + expected) { + return expected; + } else { + return stringValue; + } + } + } + } + function getValueForAttribute(node, name, expected, isCustomComponentTag) { + { + if (!isAttributeNameSafe(name)) { + return; + } + if (!node.hasAttribute(name)) { + return expected === undefined ? undefined : null; + } + var value = node.getAttribute(name); + { + checkAttributeStringCoercion(expected, name); + } + if (value === "" + expected) { + return expected; + } + return value; + } + } + function setValueForProperty(node, name, value, isCustomComponentTag) { + var propertyInfo = getPropertyInfo(name); + if (shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag)) { + return; + } + if (shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag)) { + value = null; + } + if (isCustomComponentTag || propertyInfo === null) { + if (isAttributeNameSafe(name)) { + var _attributeName = name; + if (value === null) { + node.removeAttribute(_attributeName); + } else { + { + checkAttributeStringCoercion(value, name); + } + node.setAttribute(_attributeName, "" + value); + } + } + return; + } + var mustUseProperty = propertyInfo.mustUseProperty; + if (mustUseProperty) { + var propertyName = propertyInfo.propertyName; + if (value === null) { + var type = propertyInfo.type; + node[propertyName] = type === BOOLEAN ? false : ""; + } else { + node[propertyName] = value; + } + return; + } + var { attributeName, attributeNamespace } = propertyInfo; + if (value === null) { + node.removeAttribute(attributeName); + } else { + var _type = propertyInfo.type; + var attributeValue; + if (_type === BOOLEAN || _type === OVERLOADED_BOOLEAN && value === true) { + attributeValue = ""; + } else { + { + { + checkAttributeStringCoercion(value, attributeName); + } + attributeValue = "" + value; + } + if (propertyInfo.sanitizeURL) { + sanitizeURL(attributeValue.toString()); + } + } + if (attributeNamespace) { + node.setAttributeNS(attributeNamespace, attributeName, attributeValue); + } else { + node.setAttribute(attributeName, attributeValue); + } + } + } + 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; + } + var assign = Object.assign; + 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) { + prevLog = console.log; + prevInfo = console.info; + prevWarn = console.warn; + prevError = console.error; + prevGroup = console.group; + prevGroupCollapsed = console.groupCollapsed; + prevGroupEnd = console.groupEnd; + var props = { + configurable: true, + enumerable: true, + value: disabledLog, + writable: true + }; + Object.defineProperties(console, { + info: props, + log: props, + warn: props, + error: props, + group: props, + groupCollapsed: props, + groupEnd: props + }); + } + disabledDepth++; + } + } + function reenableLogs() { + { + disabledDepth--; + if (disabledDepth === 0) { + var props = { + configurable: true, + enumerable: true, + writable: true + }; + 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 + }) + }); + } + 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) { + try { + throw Error(); + } catch (x) { + var match = x.stack.trim().match(/\n( *(at )?)/); + prefix = match && match[1] || ""; + } + } + return "\n" + prefix + name; + } + } + var reentry = false; + var componentFrameCache; + { + var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map; + componentFrameCache = new PossiblyWeakMap; + } + function describeNativeComponentFrame(fn, construct) { + if (!fn || reentry) { + return ""; + } + { + var frame = componentFrameCache.get(fn); + if (frame !== undefined) { + return frame; + } + } + var control; + reentry = true; + var previousPrepareStackTrace = Error.prepareStackTrace; + Error.prepareStackTrace = undefined; + var previousDispatcher; + { + previousDispatcher = ReactCurrentDispatcher.current; + ReactCurrentDispatcher.current = null; + disableLogs(); + } + try { + if (construct) { + var Fake = function() { + throw Error(); + }; + Object.defineProperty(Fake.prototype, "props", { + set: function() { + throw Error(); + } + }); + if (typeof Reflect === "object" && Reflect.construct) { + 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) { + if (sample && control && typeof sample.stack === "string") { + 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]) { + c--; + } + for (;s >= 1 && c >= 0; s--, c--) { + if (sampleLines[s] !== controlLines[c]) { + if (s !== 1 || c !== 1) { + do { + s--; + c--; + if (c < 0 || sampleLines[s] !== controlLines[c]) { + var _frame = "\n" + sampleLines[s].replace(" at new ", " at "); + if (fn.displayName && _frame.includes("<anonymous>")) { + _frame = _frame.replace("<anonymous>", fn.displayName); + } + { + if (typeof fn === "function") { + componentFrameCache.set(fn, _frame); + } + } + return _frame; + } + } while (s >= 1 && c >= 0); + } + break; + } + } + } + } finally { + reentry = false; + { + ReactCurrentDispatcher.current = previousDispatcher; + reenableLogs(); + } + Error.prepareStackTrace = previousPrepareStackTrace; + } + 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: + return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); + case REACT_LAZY_TYPE: { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + try { + return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); + } catch (x) { + } + } + } + } + return ""; + } + function describeFiber(fiber) { + var owner = fiber._debugOwner ? fiber._debugOwner.type : null; + var source = 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(workInProgress2) { + try { + var info = ""; + var node = workInProgress2; + do { + info += describeFiber(node); + node = node.return; + } while (node); + return info; + } catch (x) { + return "\nError generating stack: " + x.message + "\n" + x.stack; + } + } + function getWrappedName(outerType, innerType, wrapperName) { + var displayName = outerType.displayName; + if (displayName) { + return displayName; + } + var functionName = innerType.displayName || innerType.name || ""; + return functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName; + } + function getContextName(type) { + return type.displayName || "Context"; + } + function getComponentNameFromType(type) { + if (type == null) { + 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; + } + } + } + } + return null; + } + function getWrappedName$1(outerType, innerType, wrapperName) { + var functionName = innerType.displayName || innerType.name || ""; + return outerType.displayName || (functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName); + } + function getContextName$1(type) { + return type.displayName || "Context"; + } + function getComponentNameFromFiber(fiber) { + var { tag, type } = fiber; + 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: + return type; + case HostPortal: + return "Portal"; + case HostRoot: + return "Root"; + case HostText: + return "Text"; + case LazyComponent: + return getComponentNameFromType(type); + case Mode: + if (type === REACT_STRICT_MODE_TYPE) { + 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"; + 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; + } + var ReactDebugCurrentFrame = 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 ""; + } + return getStackByFiberInDevAndProd(current); + } + } + function resetCurrentFiber() { + { + ReactDebugCurrentFrame.getCurrentStack = null; + current = null; + isRendering = false; + } + } + function setCurrentFiber(fiber) { + { + ReactDebugCurrentFrame.getCurrentStack = fiber === null ? null : getCurrentFiberStackInDev; + current = fiber; + isRendering = false; + } + } + function getCurrentFiber() { + { + return current; + } + } + function setIsRendering(rendering) { + { + isRendering = rendering; + } + } + function toString(value) { + return "" + value; + } + function getToStringValue(value) { + switch (typeof value) { + case "boolean": + case "number": + case "string": + case "undefined": + return value; + case "object": + { + checkFormFieldValueStringCoercion(value); + } + return value; + default: + return ""; + } + } + var hasReadOnlyValue = { + button: true, + checkbox: true, + image: true, + hidden: true, + radio: true, + reset: true, + submit: true + }; + function checkControlledValueProps(tagName, props) { + { + if (!(hasReadOnlyValue[props.type] || props.onChange || props.onInput || props.readOnly || props.disabled || props.value == null)) { + error("You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`."); + } + if (!(props.onChange || props.readOnly || props.disabled || props.checked == null)) { + error("You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`."); + } + } + } + function isCheckable(elem) { + var type = elem.type; + var nodeName = elem.nodeName; + return nodeName && nodeName.toLowerCase() === "input" && (type === "checkbox" || type === "radio"); + } + function getTracker(node) { + return node._valueTracker; + } + function detachTracker(node) { + node._valueTracker = null; + } + function getValueFromNode(node) { + var value = ""; + if (!node) { + return value; + } + if (isCheckable(node)) { + value = node.checked ? "true" : "false"; + } else { + value = node.value; + } + return value; + } + function trackValueOnNode(node) { + var valueField = isCheckable(node) ? "checked" : "value"; + var descriptor = Object.getOwnPropertyDescriptor(node.constructor.prototype, valueField); + { + checkFormFieldValueStringCoercion(node[valueField]); + } + var currentValue = "" + node[valueField]; + if (node.hasOwnProperty(valueField) || typeof descriptor === "undefined" || typeof descriptor.get !== "function" || typeof descriptor.set !== "function") { + return; + } + var { get: get2, set: set2 } = descriptor; + Object.defineProperty(node, valueField, { + configurable: true, + get: function() { + return get2.call(this); + }, + set: function(value) { + { + checkFormFieldValueStringCoercion(value); + } + currentValue = "" + value; + set2.call(this, value); + } + }); + Object.defineProperty(node, valueField, { + enumerable: descriptor.enumerable + }); + var tracker = { + getValue: function() { + return currentValue; + }, + setValue: function(value) { + { + checkFormFieldValueStringCoercion(value); + } + currentValue = "" + value; + }, + stopTracking: function() { + detachTracker(node); + delete node[valueField]; + } + }; + return tracker; + } + function track(node) { + if (getTracker(node)) { + return; + } + node._valueTracker = trackValueOnNode(node); + } + function updateValueIfChanged(node) { + if (!node) { + return false; + } + var tracker = getTracker(node); + if (!tracker) { + return true; + } + var lastValue = tracker.getValue(); + var nextValue = getValueFromNode(node); + if (nextValue !== lastValue) { + tracker.setValue(nextValue); + return true; + } + return false; + } + function getActiveElement(doc) { + doc = doc || (typeof document !== "undefined" ? document : undefined); + if (typeof doc === "undefined") { + return null; + } + try { + return doc.activeElement || doc.body; + } catch (e) { + return doc.body; + } + } + var didWarnValueDefaultValue = false; + var didWarnCheckedDefaultChecked = false; + var didWarnControlledToUncontrolled = false; + var didWarnUncontrolledToControlled = false; + function isControlled(props) { + var usesChecked = props.type === "checkbox" || props.type === "radio"; + return usesChecked ? props.checked != null : props.value != null; + } + function getHostProps(element, props) { + var node = element; + var checked = props.checked; + var hostProps = assign({}, props, { + defaultChecked: undefined, + defaultValue: undefined, + value: undefined, + checked: checked != null ? checked : node._wrapperState.initialChecked + }); + return hostProps; + } + function initWrapperState(element, props) { + { + checkControlledValueProps("input", props); + if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnCheckedDefaultChecked) { + error("%s contains an input of type %s with both checked and defaultChecked props. Input elements must be either controlled or uncontrolled (specify either the checked prop, or the defaultChecked prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props. More info: https://reactjs.org/link/controlled-components", getCurrentFiberOwnerNameInDevOrNull() || "A component", props.type); + didWarnCheckedDefaultChecked = true; + } + if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) { + error("%s contains an input of type %s with both value and defaultValue props. Input elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props. More info: https://reactjs.org/link/controlled-components", getCurrentFiberOwnerNameInDevOrNull() || "A component", props.type); + didWarnValueDefaultValue = true; + } + } + var node = element; + var defaultValue = props.defaultValue == null ? "" : props.defaultValue; + node._wrapperState = { + initialChecked: props.checked != null ? props.checked : props.defaultChecked, + initialValue: getToStringValue(props.value != null ? props.value : defaultValue), + controlled: isControlled(props) + }; + } + function updateChecked(element, props) { + var node = element; + var checked = props.checked; + if (checked != null) { + setValueForProperty(node, "checked", checked, false); + } + } + function updateWrapper(element, props) { + var node = element; + { + var controlled = isControlled(props); + if (!node._wrapperState.controlled && controlled && !didWarnUncontrolledToControlled) { + error("A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components"); + didWarnUncontrolledToControlled = true; + } + if (node._wrapperState.controlled && !controlled && !didWarnControlledToUncontrolled) { + error("A component is changing a controlled input to be uncontrolled. This is likely caused by the value changing from a defined to undefined, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components"); + didWarnControlledToUncontrolled = true; + } + } + updateChecked(element, props); + var value = getToStringValue(props.value); + var type = props.type; + if (value != null) { + if (type === "number") { + if (value === 0 && node.value === "" || node.value != value) { + node.value = toString(value); + } + } else if (node.value !== toString(value)) { + node.value = toString(value); + } + } else if (type === "submit" || type === "reset") { + node.removeAttribute("value"); + return; + } + { + if (props.hasOwnProperty("value")) { + setDefaultValue(node, props.type, value); + } else if (props.hasOwnProperty("defaultValue")) { + setDefaultValue(node, props.type, getToStringValue(props.defaultValue)); + } + } + { + if (props.checked == null && props.defaultChecked != null) { + node.defaultChecked = !!props.defaultChecked; + } + } + } + function postMountWrapper(element, props, isHydrating2) { + var node = element; + if (props.hasOwnProperty("value") || props.hasOwnProperty("defaultValue")) { + var type = props.type; + var isButton = type === "submit" || type === "reset"; + if (isButton && (props.value === undefined || props.value === null)) { + return; + } + var initialValue = toString(node._wrapperState.initialValue); + if (!isHydrating2) { + { + if (initialValue !== node.value) { + node.value = initialValue; + } + } + } + { + node.defaultValue = initialValue; + } + } + var name = node.name; + if (name !== "") { + node.name = ""; + } + { + node.defaultChecked = !node.defaultChecked; + node.defaultChecked = !!node._wrapperState.initialChecked; + } + if (name !== "") { + node.name = name; + } + } + function restoreControlledState(element, props) { + var node = element; + updateWrapper(node, props); + updateNamedCousins(node, props); + } + function updateNamedCousins(rootNode, props) { + var name = props.name; + if (props.type === "radio" && name != null) { + var queryRoot = rootNode; + while (queryRoot.parentNode) { + queryRoot = queryRoot.parentNode; + } + { + checkAttributeStringCoercion(name, "name"); + } + var group = queryRoot.querySelectorAll("input[name=" + JSON.stringify("" + name) + '][type="radio"]'); + for (var i = 0;i < group.length; i++) { + var otherNode = group[i]; + if (otherNode === rootNode || otherNode.form !== rootNode.form) { + continue; + } + var otherProps = getFiberCurrentPropsFromNode(otherNode); + if (!otherProps) { + throw new Error("ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported."); + } + updateValueIfChanged(otherNode); + updateWrapper(otherNode, otherProps); + } + } + } + function setDefaultValue(node, type, value) { + if (type !== "number" || getActiveElement(node.ownerDocument) !== node) { + if (value == null) { + node.defaultValue = toString(node._wrapperState.initialValue); + } else if (node.defaultValue !== toString(value)) { + node.defaultValue = toString(value); + } + } + } + var didWarnSelectedSetOnOption = false; + var didWarnInvalidChild = false; + var didWarnInvalidInnerHTML = false; + function validateProps(element, props) { + { + if (props.value == null) { + if (typeof props.children === "object" && props.children !== null) { + React.Children.forEach(props.children, function(child) { + if (child == null) { + return; + } + if (typeof child === "string" || typeof child === "number") { + return; + } + if (!didWarnInvalidChild) { + didWarnInvalidChild = true; + error("Cannot infer the option value of complex children. Pass a `value` prop or use a plain string as children to <option>."); + } + }); + } else if (props.dangerouslySetInnerHTML != null) { + if (!didWarnInvalidInnerHTML) { + didWarnInvalidInnerHTML = true; + error("Pass a `value` prop if you set dangerouslyInnerHTML so React knows which value should be selected."); + } + } + } + if (props.selected != null && !didWarnSelectedSetOnOption) { + error("Use the `defaultValue` or `value` props on <select> instead of setting `selected` on <option>."); + didWarnSelectedSetOnOption = true; + } + } + } + function postMountWrapper$1(element, props) { + if (props.value != null) { + element.setAttribute("value", toString(getToStringValue(props.value))); + } + } + var isArrayImpl = Array.isArray; + function isArray(a) { + return isArrayImpl(a); + } + var didWarnValueDefaultValue$1; + { + didWarnValueDefaultValue$1 = false; + } + function getDeclarationErrorAddendum() { + var ownerName = getCurrentFiberOwnerNameInDevOrNull(); + if (ownerName) { + return "\n\nCheck the render method of `" + ownerName + "`."; + } + return ""; + } + var valuePropNames = ["value", "defaultValue"]; + function checkSelectPropTypes(props) { + { + checkControlledValueProps("select", props); + for (var i = 0;i < valuePropNames.length; i++) { + var propName = valuePropNames[i]; + if (props[propName] == null) { + continue; + } + var propNameIsArray = isArray(props[propName]); + if (props.multiple && !propNameIsArray) { + error("The `%s` prop supplied to <select> must be an array if `multiple` is true.%s", propName, getDeclarationErrorAddendum()); + } else if (!props.multiple && propNameIsArray) { + error("The `%s` prop supplied to <select> must be a scalar value if `multiple` is false.%s", propName, getDeclarationErrorAddendum()); + } + } + } + } + function updateOptions(node, multiple, propValue, setDefaultSelected) { + var options2 = node.options; + if (multiple) { + var selectedValues = propValue; + var selectedValue = {}; + for (var i = 0;i < selectedValues.length; i++) { + selectedValue["$" + selectedValues[i]] = true; + } + for (var _i = 0;_i < options2.length; _i++) { + var selected = selectedValue.hasOwnProperty("$" + options2[_i].value); + if (options2[_i].selected !== selected) { + options2[_i].selected = selected; + } + if (selected && setDefaultSelected) { + options2[_i].defaultSelected = true; + } + } + } else { + var _selectedValue = toString(getToStringValue(propValue)); + var defaultSelected = null; + for (var _i2 = 0;_i2 < options2.length; _i2++) { + if (options2[_i2].value === _selectedValue) { + options2[_i2].selected = true; + if (setDefaultSelected) { + options2[_i2].defaultSelected = true; + } + return; + } + if (defaultSelected === null && !options2[_i2].disabled) { + defaultSelected = options2[_i2]; + } + } + if (defaultSelected !== null) { + defaultSelected.selected = true; + } + } + } + function getHostProps$1(element, props) { + return assign({}, props, { + value: undefined + }); + } + function initWrapperState$1(element, props) { + var node = element; + { + checkSelectPropTypes(props); + } + node._wrapperState = { + wasMultiple: !!props.multiple + }; + { + if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue$1) { + error("Select elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled select element and remove one of these props. More info: https://reactjs.org/link/controlled-components"); + didWarnValueDefaultValue$1 = true; + } + } + } + function postMountWrapper$2(element, props) { + var node = element; + node.multiple = !!props.multiple; + var value = props.value; + if (value != null) { + updateOptions(node, !!props.multiple, value, false); + } else if (props.defaultValue != null) { + updateOptions(node, !!props.multiple, props.defaultValue, true); + } + } + function postUpdateWrapper(element, props) { + var node = element; + var wasMultiple = node._wrapperState.wasMultiple; + node._wrapperState.wasMultiple = !!props.multiple; + var value = props.value; + if (value != null) { + updateOptions(node, !!props.multiple, value, false); + } else if (wasMultiple !== !!props.multiple) { + if (props.defaultValue != null) { + updateOptions(node, !!props.multiple, props.defaultValue, true); + } else { + updateOptions(node, !!props.multiple, props.multiple ? [] : "", false); + } + } + } + function restoreControlledState$1(element, props) { + var node = element; + var value = props.value; + if (value != null) { + updateOptions(node, !!props.multiple, value, false); + } + } + var didWarnValDefaultVal = false; + function getHostProps$2(element, props) { + var node = element; + if (props.dangerouslySetInnerHTML != null) { + throw new Error("`dangerouslySetInnerHTML` does not make sense on <textarea>."); + } + var hostProps = assign({}, props, { + value: undefined, + defaultValue: undefined, + children: toString(node._wrapperState.initialValue) + }); + return hostProps; + } + function initWrapperState$2(element, props) { + var node = element; + { + checkControlledValueProps("textarea", props); + if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValDefaultVal) { + error("%s contains a textarea with both value and defaultValue props. Textarea elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled textarea and remove one of these props. More info: https://reactjs.org/link/controlled-components", getCurrentFiberOwnerNameInDevOrNull() || "A component"); + didWarnValDefaultVal = true; + } + } + var initialValue = props.value; + if (initialValue == null) { + var { children, defaultValue } = props; + if (children != null) { + { + error("Use the `defaultValue` or `value` props instead of setting children on <textarea>."); + } + { + if (defaultValue != null) { + throw new Error("If you supply `defaultValue` on a <textarea>, do not pass children."); + } + if (isArray(children)) { + if (children.length > 1) { + throw new Error("<textarea> can only have at most one child."); + } + children = children[0]; + } + defaultValue = children; + } + } + if (defaultValue == null) { + defaultValue = ""; + } + initialValue = defaultValue; + } + node._wrapperState = { + initialValue: getToStringValue(initialValue) + }; + } + function updateWrapper$1(element, props) { + var node = element; + var value = getToStringValue(props.value); + var defaultValue = getToStringValue(props.defaultValue); + if (value != null) { + var newValue = toString(value); + if (newValue !== node.value) { + node.value = newValue; + } + if (props.defaultValue == null && node.defaultValue !== newValue) { + node.defaultValue = newValue; + } + } + if (defaultValue != null) { + node.defaultValue = toString(defaultValue); + } + } + function postMountWrapper$3(element, props) { + var node = element; + var textContent = node.textContent; + if (textContent === node._wrapperState.initialValue) { + if (textContent !== "" && textContent !== null) { + node.value = textContent; + } + } + } + function restoreControlledState$2(element, props) { + updateWrapper$1(element, props); + } + var HTML_NAMESPACE = "http://www.w3.org/1999/xhtml"; + var MATH_NAMESPACE = "http://www.w3.org/1998/Math/MathML"; + var SVG_NAMESPACE = "http://www.w3.org/2000/svg"; + function getIntrinsicNamespace(type) { + switch (type) { + case "svg": + return SVG_NAMESPACE; + case "math": + return MATH_NAMESPACE; + default: + return HTML_NAMESPACE; + } + } + function getChildNamespace(parentNamespace, type) { + if (parentNamespace == null || parentNamespace === HTML_NAMESPACE) { + return getIntrinsicNamespace(type); + } + if (parentNamespace === SVG_NAMESPACE && type === "foreignObject") { + return HTML_NAMESPACE; + } + return parentNamespace; + } + var createMicrosoftUnsafeLocalFunction = function(func) { + if (typeof MSApp !== "undefined" && MSApp.execUnsafeLocalFunction) { + return function(arg0, arg1, arg2, arg3) { + MSApp.execUnsafeLocalFunction(function() { + return func(arg0, arg1, arg2, arg3); + }); + }; + } else { + return func; + } + }; + var reusableSVGContainer; + var setInnerHTML = createMicrosoftUnsafeLocalFunction(function(node, html) { + if (node.namespaceURI === SVG_NAMESPACE) { + if (!("innerHTML" in node)) { + reusableSVGContainer = reusableSVGContainer || document.createElement("div"); + reusableSVGContainer.innerHTML = "<svg>" + html.valueOf().toString() + "</svg>"; + var svgNode = reusableSVGContainer.firstChild; + while (node.firstChild) { + node.removeChild(node.firstChild); + } + while (svgNode.firstChild) { + node.appendChild(svgNode.firstChild); + } + return; + } + } + node.innerHTML = html; + }); + var ELEMENT_NODE = 1; + var TEXT_NODE = 3; + var COMMENT_NODE = 8; + var DOCUMENT_NODE = 9; + var DOCUMENT_FRAGMENT_NODE = 11; + var setTextContent = function(node, text) { + if (text) { + var firstChild = node.firstChild; + if (firstChild && firstChild === node.lastChild && firstChild.nodeType === TEXT_NODE) { + firstChild.nodeValue = text; + return; + } + } + node.textContent = text; + }; + var shorthandToLonghand = { + animation: ["animationDelay", "animationDirection", "animationDuration", "animationFillMode", "animationIterationCount", "animationName", "animationPlayState", "animationTimingFunction"], + background: ["backgroundAttachment", "backgroundClip", "backgroundColor", "backgroundImage", "backgroundOrigin", "backgroundPositionX", "backgroundPositionY", "backgroundRepeat", "backgroundSize"], + backgroundPosition: ["backgroundPositionX", "backgroundPositionY"], + border: ["borderBottomColor", "borderBottomStyle", "borderBottomWidth", "borderImageOutset", "borderImageRepeat", "borderImageSlice", "borderImageSource", "borderImageWidth", "borderLeftColor", "borderLeftStyle", "borderLeftWidth", "borderRightColor", "borderRightStyle", "borderRightWidth", "borderTopColor", "borderTopStyle", "borderTopWidth"], + borderBlockEnd: ["borderBlockEndColor", "borderBlockEndStyle", "borderBlockEndWidth"], + borderBlockStart: ["borderBlockStartColor", "borderBlockStartStyle", "borderBlockStartWidth"], + borderBottom: ["borderBottomColor", "borderBottomStyle", "borderBottomWidth"], + borderColor: ["borderBottomColor", "borderLeftColor", "borderRightColor", "borderTopColor"], + borderImage: ["borderImageOutset", "borderImageRepeat", "borderImageSlice", "borderImageSource", "borderImageWidth"], + borderInlineEnd: ["borderInlineEndColor", "borderInlineEndStyle", "borderInlineEndWidth"], + borderInlineStart: ["borderInlineStartColor", "borderInlineStartStyle", "borderInlineStartWidth"], + borderLeft: ["borderLeftColor", "borderLeftStyle", "borderLeftWidth"], + borderRadius: ["borderBottomLeftRadius", "borderBottomRightRadius", "borderTopLeftRadius", "borderTopRightRadius"], + borderRight: ["borderRightColor", "borderRightStyle", "borderRightWidth"], + borderStyle: ["borderBottomStyle", "borderLeftStyle", "borderRightStyle", "borderTopStyle"], + borderTop: ["borderTopColor", "borderTopStyle", "borderTopWidth"], + borderWidth: ["borderBottomWidth", "borderLeftWidth", "borderRightWidth", "borderTopWidth"], + columnRule: ["columnRuleColor", "columnRuleStyle", "columnRuleWidth"], + columns: ["columnCount", "columnWidth"], + flex: ["flexBasis", "flexGrow", "flexShrink"], + flexFlow: ["flexDirection", "flexWrap"], + font: ["fontFamily", "fontFeatureSettings", "fontKerning", "fontLanguageOverride", "fontSize", "fontSizeAdjust", "fontStretch", "fontStyle", "fontVariant", "fontVariantAlternates", "fontVariantCaps", "fontVariantEastAsian", "fontVariantLigatures", "fontVariantNumeric", "fontVariantPosition", "fontWeight", "lineHeight"], + fontVariant: ["fontVariantAlternates", "fontVariantCaps", "fontVariantEastAsian", "fontVariantLigatures", "fontVariantNumeric", "fontVariantPosition"], + gap: ["columnGap", "rowGap"], + grid: ["gridAutoColumns", "gridAutoFlow", "gridAutoRows", "gridTemplateAreas", "gridTemplateColumns", "gridTemplateRows"], + gridArea: ["gridColumnEnd", "gridColumnStart", "gridRowEnd", "gridRowStart"], + gridColumn: ["gridColumnEnd", "gridColumnStart"], + gridColumnGap: ["columnGap"], + gridGap: ["columnGap", "rowGap"], + gridRow: ["gridRowEnd", "gridRowStart"], + gridRowGap: ["rowGap"], + gridTemplate: ["gridTemplateAreas", "gridTemplateColumns", "gridTemplateRows"], + listStyle: ["listStyleImage", "listStylePosition", "listStyleType"], + margin: ["marginBottom", "marginLeft", "marginRight", "marginTop"], + marker: ["markerEnd", "markerMid", "markerStart"], + mask: ["maskClip", "maskComposite", "maskImage", "maskMode", "maskOrigin", "maskPositionX", "maskPositionY", "maskRepeat", "maskSize"], + maskPosition: ["maskPositionX", "maskPositionY"], + outline: ["outlineColor", "outlineStyle", "outlineWidth"], + overflow: ["overflowX", "overflowY"], + padding: ["paddingBottom", "paddingLeft", "paddingRight", "paddingTop"], + placeContent: ["alignContent", "justifyContent"], + placeItems: ["alignItems", "justifyItems"], + placeSelf: ["alignSelf", "justifySelf"], + textDecoration: ["textDecorationColor", "textDecorationLine", "textDecorationStyle"], + textEmphasis: ["textEmphasisColor", "textEmphasisStyle"], + transition: ["transitionDelay", "transitionDuration", "transitionProperty", "transitionTimingFunction"], + wordWrap: ["overflowWrap"] + }; + var isUnitlessNumber = { + animationIterationCount: true, + aspectRatio: true, + borderImageOutset: true, + borderImageSlice: true, + borderImageWidth: true, + boxFlex: true, + boxFlexGroup: true, + boxOrdinalGroup: true, + columnCount: true, + columns: true, + flex: true, + flexGrow: true, + flexPositive: true, + flexShrink: true, + flexNegative: true, + flexOrder: true, + gridArea: true, + gridRow: true, + gridRowEnd: true, + gridRowSpan: true, + gridRowStart: true, + gridColumn: true, + gridColumnEnd: true, + gridColumnSpan: true, + gridColumnStart: true, + fontWeight: true, + lineClamp: true, + lineHeight: true, + opacity: true, + order: true, + orphans: true, + tabSize: true, + widows: true, + zIndex: true, + zoom: true, + fillOpacity: true, + floodOpacity: true, + stopOpacity: true, + strokeDasharray: true, + strokeDashoffset: true, + strokeMiterlimit: true, + strokeOpacity: true, + strokeWidth: true + }; + function prefixKey(prefix2, key) { + return prefix2 + key.charAt(0).toUpperCase() + key.substring(1); + } + var prefixes = ["Webkit", "ms", "Moz", "O"]; + Object.keys(isUnitlessNumber).forEach(function(prop) { + prefixes.forEach(function(prefix2) { + isUnitlessNumber[prefixKey(prefix2, prop)] = isUnitlessNumber[prop]; + }); + }); + function dangerousStyleValue(name, value, isCustomProperty) { + var isEmpty = value == null || typeof value === "boolean" || value === ""; + if (isEmpty) { + return ""; + } + if (!isCustomProperty && typeof value === "number" && value !== 0 && !(isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name])) { + return value + "px"; + } + { + checkCSSPropertyStringCoercion(value, name); + } + return ("" + value).trim(); + } + var uppercasePattern = /([A-Z])/g; + var msPattern = /^ms-/; + function hyphenateStyleName(name) { + return name.replace(uppercasePattern, "-$1").toLowerCase().replace(msPattern, "-ms-"); + } + var warnValidStyle = function() { + }; + { + var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/; + var msPattern$1 = /^-ms-/; + var hyphenPattern = /-(.)/g; + var badStyleValueWithSemicolonPattern = /;\s*$/; + var warnedStyleNames = {}; + var warnedStyleValues = {}; + var warnedForNaNValue = false; + var warnedForInfinityValue = false; + var camelize = function(string) { + return string.replace(hyphenPattern, function(_, character) { + return character.toUpperCase(); + }); + }; + var warnHyphenatedStyleName = function(name) { + if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { + return; + } + warnedStyleNames[name] = true; + error("Unsupported style property %s. Did you mean %s?", name, camelize(name.replace(msPattern$1, "ms-"))); + }; + var warnBadVendoredStyleName = function(name) { + if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { + return; + } + warnedStyleNames[name] = true; + error("Unsupported vendor-prefixed style property %s. Did you mean %s?", name, name.charAt(0).toUpperCase() + name.slice(1)); + }; + var warnStyleValueWithSemicolon = function(name, value) { + if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) { + return; + } + warnedStyleValues[value] = true; + error(`Style property values shouldn't contain a semicolon. Try "%s: %s" instead.`, name, value.replace(badStyleValueWithSemicolonPattern, "")); + }; + var warnStyleValueIsNaN = function(name, value) { + if (warnedForNaNValue) { + return; + } + warnedForNaNValue = true; + error("`NaN` is an invalid value for the `%s` css style property.", name); + }; + var warnStyleValueIsInfinity = function(name, value) { + if (warnedForInfinityValue) { + return; + } + warnedForInfinityValue = true; + error("`Infinity` is an invalid value for the `%s` css style property.", name); + }; + warnValidStyle = function(name, value) { + if (name.indexOf("-") > -1) { + warnHyphenatedStyleName(name); + } else if (badVendoredStyleNamePattern.test(name)) { + warnBadVendoredStyleName(name); + } else if (badStyleValueWithSemicolonPattern.test(value)) { + warnStyleValueWithSemicolon(name, value); + } + if (typeof value === "number") { + if (isNaN(value)) { + warnStyleValueIsNaN(name, value); + } else if (!isFinite(value)) { + warnStyleValueIsInfinity(name, value); + } + } + }; + } + var warnValidStyle$1 = warnValidStyle; + function createDangerousStringForStyles(styles) { + { + var serialized = ""; + var delimiter = ""; + for (var styleName in styles) { + if (!styles.hasOwnProperty(styleName)) { + continue; + } + var styleValue = styles[styleName]; + if (styleValue != null) { + var isCustomProperty = styleName.indexOf("--") === 0; + serialized += delimiter + (isCustomProperty ? styleName : hyphenateStyleName(styleName)) + ":"; + serialized += dangerousStyleValue(styleName, styleValue, isCustomProperty); + delimiter = ";"; + } + } + return serialized || null; + } + } + function setValueForStyles(node, styles) { + var style2 = node.style; + for (var styleName in styles) { + if (!styles.hasOwnProperty(styleName)) { + continue; + } + var isCustomProperty = styleName.indexOf("--") === 0; + { + if (!isCustomProperty) { + warnValidStyle$1(styleName, styles[styleName]); + } + } + var styleValue = dangerousStyleValue(styleName, styles[styleName], isCustomProperty); + if (styleName === "float") { + styleName = "cssFloat"; + } + if (isCustomProperty) { + style2.setProperty(styleName, styleValue); + } else { + style2[styleName] = styleValue; + } + } + } + function isValueEmpty(value) { + return value == null || typeof value === "boolean" || value === ""; + } + function expandShorthandMap(styles) { + var expanded = {}; + for (var key in styles) { + var longhands = shorthandToLonghand[key] || [key]; + for (var i = 0;i < longhands.length; i++) { + expanded[longhands[i]] = key; + } + } + return expanded; + } + function validateShorthandPropertyCollisionInDev(styleUpdates, nextStyles) { + { + if (!nextStyles) { + return; + } + var expandedUpdates = expandShorthandMap(styleUpdates); + var expandedStyles = expandShorthandMap(nextStyles); + var warnedAbout = {}; + for (var key in expandedUpdates) { + var originalKey = expandedUpdates[key]; + var correctOriginalKey = expandedStyles[key]; + if (correctOriginalKey && originalKey !== correctOriginalKey) { + var warningKey = originalKey + "," + correctOriginalKey; + if (warnedAbout[warningKey]) { + continue; + } + warnedAbout[warningKey] = true; + error("%s a style property during rerender (%s) when a conflicting property is set (%s) can lead to styling bugs. To avoid this, don't mix shorthand and non-shorthand properties for the same value; instead, replace the shorthand with separate values.", isValueEmpty(styleUpdates[originalKey]) ? "Removing" : "Updating", originalKey, correctOriginalKey); + } + } + } + } + var omittedCloseTags = { + area: true, + base: true, + br: true, + col: true, + embed: true, + hr: true, + img: true, + input: true, + keygen: true, + link: true, + meta: true, + param: true, + source: true, + track: true, + wbr: true + }; + var voidElementTags = assign({ + menuitem: true + }, omittedCloseTags); + var HTML = "__html"; + function assertValidProps(tag, props) { + if (!props) { + return; + } + if (voidElementTags[tag]) { + if (props.children != null || props.dangerouslySetInnerHTML != null) { + throw new Error(tag + " is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`."); + } + } + if (props.dangerouslySetInnerHTML != null) { + if (props.children != null) { + throw new Error("Can only set one of `children` or `props.dangerouslySetInnerHTML`."); + } + if (typeof props.dangerouslySetInnerHTML !== "object" || !(HTML in props.dangerouslySetInnerHTML)) { + throw new Error("`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://reactjs.org/link/dangerously-set-inner-html for more information."); + } + } + { + if (!props.suppressContentEditableWarning && props.contentEditable && props.children != null) { + error("A component is `contentEditable` and contains `children` managed by React. It is now your responsibility to guarantee that none of those nodes are unexpectedly modified or duplicated. This is probably not intentional."); + } + } + if (props.style != null && typeof props.style !== "object") { + throw new Error("The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX."); + } + } + function isCustomComponent(tagName, props) { + if (tagName.indexOf("-") === -1) { + return typeof props.is === "string"; + } + switch (tagName) { + case "annotation-xml": + case "color-profile": + case "font-face": + case "font-face-src": + case "font-face-uri": + case "font-face-format": + case "font-face-name": + case "missing-glyph": + return false; + default: + return true; + } + } + var possibleStandardNames = { + accept: "accept", + acceptcharset: "acceptCharset", + "accept-charset": "acceptCharset", + accesskey: "accessKey", + action: "action", + allowfullscreen: "allowFullScreen", + alt: "alt", + as: "as", + async: "async", + autocapitalize: "autoCapitalize", + autocomplete: "autoComplete", + autocorrect: "autoCorrect", + autofocus: "autoFocus", + autoplay: "autoPlay", + autosave: "autoSave", + capture: "capture", + cellpadding: "cellPadding", + cellspacing: "cellSpacing", + challenge: "challenge", + charset: "charSet", + checked: "checked", + children: "children", + cite: "cite", + class: "className", + classid: "classID", + classname: "className", + cols: "cols", + colspan: "colSpan", + content: "content", + contenteditable: "contentEditable", + contextmenu: "contextMenu", + controls: "controls", + controlslist: "controlsList", + coords: "coords", + crossorigin: "crossOrigin", + dangerouslysetinnerhtml: "dangerouslySetInnerHTML", + data: "data", + datetime: "dateTime", + default: "default", + defaultchecked: "defaultChecked", + defaultvalue: "defaultValue", + defer: "defer", + dir: "dir", + disabled: "disabled", + disablepictureinpicture: "disablePictureInPicture", + disableremoteplayback: "disableRemotePlayback", + download: "download", + draggable: "draggable", + enctype: "encType", + enterkeyhint: "enterKeyHint", + for: "htmlFor", + form: "form", + formmethod: "formMethod", + formaction: "formAction", + formenctype: "formEncType", + formnovalidate: "formNoValidate", + formtarget: "formTarget", + frameborder: "frameBorder", + headers: "headers", + height: "height", + hidden: "hidden", + high: "high", + href: "href", + hreflang: "hrefLang", + htmlfor: "htmlFor", + httpequiv: "httpEquiv", + "http-equiv": "httpEquiv", + icon: "icon", + id: "id", + imagesizes: "imageSizes", + imagesrcset: "imageSrcSet", + innerhtml: "innerHTML", + inputmode: "inputMode", + integrity: "integrity", + is: "is", + itemid: "itemID", + itemprop: "itemProp", + itemref: "itemRef", + itemscope: "itemScope", + itemtype: "itemType", + keyparams: "keyParams", + keytype: "keyType", + kind: "kind", + label: "label", + lang: "lang", + list: "list", + loop: "loop", + low: "low", + manifest: "manifest", + marginwidth: "marginWidth", + marginheight: "marginHeight", + max: "max", + maxlength: "maxLength", + media: "media", + mediagroup: "mediaGroup", + method: "method", + min: "min", + minlength: "minLength", + multiple: "multiple", + muted: "muted", + name: "name", + nomodule: "noModule", + nonce: "nonce", + novalidate: "noValidate", + open: "open", + optimum: "optimum", + pattern: "pattern", + placeholder: "placeholder", + playsinline: "playsInline", + poster: "poster", + preload: "preload", + profile: "profile", + radiogroup: "radioGroup", + readonly: "readOnly", + referrerpolicy: "referrerPolicy", + rel: "rel", + required: "required", + reversed: "reversed", + role: "role", + rows: "rows", + rowspan: "rowSpan", + sandbox: "sandbox", + scope: "scope", + scoped: "scoped", + scrolling: "scrolling", + seamless: "seamless", + selected: "selected", + shape: "shape", + size: "size", + sizes: "sizes", + span: "span", + spellcheck: "spellCheck", + src: "src", + srcdoc: "srcDoc", + srclang: "srcLang", + srcset: "srcSet", + start: "start", + step: "step", + style: "style", + summary: "summary", + tabindex: "tabIndex", + target: "target", + title: "title", + type: "type", + usemap: "useMap", + value: "value", + width: "width", + wmode: "wmode", + wrap: "wrap", + about: "about", + accentheight: "accentHeight", + "accent-height": "accentHeight", + accumulate: "accumulate", + additive: "additive", + alignmentbaseline: "alignmentBaseline", + "alignment-baseline": "alignmentBaseline", + allowreorder: "allowReorder", + alphabetic: "alphabetic", + amplitude: "amplitude", + arabicform: "arabicForm", + "arabic-form": "arabicForm", + ascent: "ascent", + attributename: "attributeName", + attributetype: "attributeType", + autoreverse: "autoReverse", + azimuth: "azimuth", + basefrequency: "baseFrequency", + baselineshift: "baselineShift", + "baseline-shift": "baselineShift", + baseprofile: "baseProfile", + bbox: "bbox", + begin: "begin", + bias: "bias", + by: "by", + calcmode: "calcMode", + capheight: "capHeight", + "cap-height": "capHeight", + clip: "clip", + clippath: "clipPath", + "clip-path": "clipPath", + clippathunits: "clipPathUnits", + cliprule: "clipRule", + "clip-rule": "clipRule", + color: "color", + colorinterpolation: "colorInterpolation", + "color-interpolation": "colorInterpolation", + colorinterpolationfilters: "colorInterpolationFilters", + "color-interpolation-filters": "colorInterpolationFilters", + colorprofile: "colorProfile", + "color-profile": "colorProfile", + colorrendering: "colorRendering", + "color-rendering": "colorRendering", + contentscripttype: "contentScriptType", + contentstyletype: "contentStyleType", + cursor: "cursor", + cx: "cx", + cy: "cy", + d: "d", + datatype: "datatype", + decelerate: "decelerate", + descent: "descent", + diffuseconstant: "diffuseConstant", + direction: "direction", + display: "display", + divisor: "divisor", + dominantbaseline: "dominantBaseline", + "dominant-baseline": "dominantBaseline", + dur: "dur", + dx: "dx", + dy: "dy", + edgemode: "edgeMode", + elevation: "elevation", + enablebackground: "enableBackground", + "enable-background": "enableBackground", + end: "end", + exponent: "exponent", + externalresourcesrequired: "externalResourcesRequired", + fill: "fill", + fillopacity: "fillOpacity", + "fill-opacity": "fillOpacity", + fillrule: "fillRule", + "fill-rule": "fillRule", + filter: "filter", + filterres: "filterRes", + filterunits: "filterUnits", + floodopacity: "floodOpacity", + "flood-opacity": "floodOpacity", + floodcolor: "floodColor", + "flood-color": "floodColor", + focusable: "focusable", + fontfamily: "fontFamily", + "font-family": "fontFamily", + fontsize: "fontSize", + "font-size": "fontSize", + fontsizeadjust: "fontSizeAdjust", + "font-size-adjust": "fontSizeAdjust", + fontstretch: "fontStretch", + "font-stretch": "fontStretch", + fontstyle: "fontStyle", + "font-style": "fontStyle", + fontvariant: "fontVariant", + "font-variant": "fontVariant", + fontweight: "fontWeight", + "font-weight": "fontWeight", + format: "format", + from: "from", + fx: "fx", + fy: "fy", + g1: "g1", + g2: "g2", + glyphname: "glyphName", + "glyph-name": "glyphName", + glyphorientationhorizontal: "glyphOrientationHorizontal", + "glyph-orientation-horizontal": "glyphOrientationHorizontal", + glyphorientationvertical: "glyphOrientationVertical", + "glyph-orientation-vertical": "glyphOrientationVertical", + glyphref: "glyphRef", + gradienttransform: "gradientTransform", + gradientunits: "gradientUnits", + hanging: "hanging", + horizadvx: "horizAdvX", + "horiz-adv-x": "horizAdvX", + horizoriginx: "horizOriginX", + "horiz-origin-x": "horizOriginX", + ideographic: "ideographic", + imagerendering: "imageRendering", + "image-rendering": "imageRendering", + in2: "in2", + in: "in", + inlist: "inlist", + intercept: "intercept", + k1: "k1", + k2: "k2", + k3: "k3", + k4: "k4", + k: "k", + kernelmatrix: "kernelMatrix", + kernelunitlength: "kernelUnitLength", + kerning: "kerning", + keypoints: "keyPoints", + keysplines: "keySplines", + keytimes: "keyTimes", + lengthadjust: "lengthAdjust", + letterspacing: "letterSpacing", + "letter-spacing": "letterSpacing", + lightingcolor: "lightingColor", + "lighting-color": "lightingColor", + limitingconeangle: "limitingConeAngle", + local: "local", + markerend: "markerEnd", + "marker-end": "markerEnd", + markerheight: "markerHeight", + markermid: "markerMid", + "marker-mid": "markerMid", + markerstart: "markerStart", + "marker-start": "markerStart", + markerunits: "markerUnits", + markerwidth: "markerWidth", + mask: "mask", + maskcontentunits: "maskContentUnits", + maskunits: "maskUnits", + mathematical: "mathematical", + mode: "mode", + numoctaves: "numOctaves", + offset: "offset", + opacity: "opacity", + operator: "operator", + order: "order", + orient: "orient", + orientation: "orientation", + origin: "origin", + overflow: "overflow", + overlineposition: "overlinePosition", + "overline-position": "overlinePosition", + overlinethickness: "overlineThickness", + "overline-thickness": "overlineThickness", + paintorder: "paintOrder", + "paint-order": "paintOrder", + panose1: "panose1", + "panose-1": "panose1", + pathlength: "pathLength", + patterncontentunits: "patternContentUnits", + patterntransform: "patternTransform", + patternunits: "patternUnits", + pointerevents: "pointerEvents", + "pointer-events": "pointerEvents", + points: "points", + pointsatx: "pointsAtX", + pointsaty: "pointsAtY", + pointsatz: "pointsAtZ", + prefix: "prefix", + preservealpha: "preserveAlpha", + preserveaspectratio: "preserveAspectRatio", + primitiveunits: "primitiveUnits", + property: "property", + r: "r", + radius: "radius", + refx: "refX", + refy: "refY", + renderingintent: "renderingIntent", + "rendering-intent": "renderingIntent", + repeatcount: "repeatCount", + repeatdur: "repeatDur", + requiredextensions: "requiredExtensions", + requiredfeatures: "requiredFeatures", + resource: "resource", + restart: "restart", + result: "result", + results: "results", + rotate: "rotate", + rx: "rx", + ry: "ry", + scale: "scale", + security: "security", + seed: "seed", + shaperendering: "shapeRendering", + "shape-rendering": "shapeRendering", + slope: "slope", + spacing: "spacing", + specularconstant: "specularConstant", + specularexponent: "specularExponent", + speed: "speed", + spreadmethod: "spreadMethod", + startoffset: "startOffset", + stddeviation: "stdDeviation", + stemh: "stemh", + stemv: "stemv", + stitchtiles: "stitchTiles", + stopcolor: "stopColor", + "stop-color": "stopColor", + stopopacity: "stopOpacity", + "stop-opacity": "stopOpacity", + strikethroughposition: "strikethroughPosition", + "strikethrough-position": "strikethroughPosition", + strikethroughthickness: "strikethroughThickness", + "strikethrough-thickness": "strikethroughThickness", + string: "string", + stroke: "stroke", + strokedasharray: "strokeDasharray", + "stroke-dasharray": "strokeDasharray", + strokedashoffset: "strokeDashoffset", + "stroke-dashoffset": "strokeDashoffset", + strokelinecap: "strokeLinecap", + "stroke-linecap": "strokeLinecap", + strokelinejoin: "strokeLinejoin", + "stroke-linejoin": "strokeLinejoin", + strokemiterlimit: "strokeMiterlimit", + "stroke-miterlimit": "strokeMiterlimit", + strokewidth: "strokeWidth", + "stroke-width": "strokeWidth", + strokeopacity: "strokeOpacity", + "stroke-opacity": "strokeOpacity", + suppresscontenteditablewarning: "suppressContentEditableWarning", + suppresshydrationwarning: "suppressHydrationWarning", + surfacescale: "surfaceScale", + systemlanguage: "systemLanguage", + tablevalues: "tableValues", + targetx: "targetX", + targety: "targetY", + textanchor: "textAnchor", + "text-anchor": "textAnchor", + textdecoration: "textDecoration", + "text-decoration": "textDecoration", + textlength: "textLength", + textrendering: "textRendering", + "text-rendering": "textRendering", + to: "to", + transform: "transform", + typeof: "typeof", + u1: "u1", + u2: "u2", + underlineposition: "underlinePosition", + "underline-position": "underlinePosition", + underlinethickness: "underlineThickness", + "underline-thickness": "underlineThickness", + unicode: "unicode", + unicodebidi: "unicodeBidi", + "unicode-bidi": "unicodeBidi", + unicoderange: "unicodeRange", + "unicode-range": "unicodeRange", + unitsperem: "unitsPerEm", + "units-per-em": "unitsPerEm", + unselectable: "unselectable", + valphabetic: "vAlphabetic", + "v-alphabetic": "vAlphabetic", + values: "values", + vectoreffect: "vectorEffect", + "vector-effect": "vectorEffect", + version: "version", + vertadvy: "vertAdvY", + "vert-adv-y": "vertAdvY", + vertoriginx: "vertOriginX", + "vert-origin-x": "vertOriginX", + vertoriginy: "vertOriginY", + "vert-origin-y": "vertOriginY", + vhanging: "vHanging", + "v-hanging": "vHanging", + videographic: "vIdeographic", + "v-ideographic": "vIdeographic", + viewbox: "viewBox", + viewtarget: "viewTarget", + visibility: "visibility", + vmathematical: "vMathematical", + "v-mathematical": "vMathematical", + vocab: "vocab", + widths: "widths", + wordspacing: "wordSpacing", + "word-spacing": "wordSpacing", + writingmode: "writingMode", + "writing-mode": "writingMode", + x1: "x1", + x2: "x2", + x: "x", + xchannelselector: "xChannelSelector", + xheight: "xHeight", + "x-height": "xHeight", + xlinkactuate: "xlinkActuate", + "xlink:actuate": "xlinkActuate", + xlinkarcrole: "xlinkArcrole", + "xlink:arcrole": "xlinkArcrole", + xlinkhref: "xlinkHref", + "xlink:href": "xlinkHref", + xlinkrole: "xlinkRole", + "xlink:role": "xlinkRole", + xlinkshow: "xlinkShow", + "xlink:show": "xlinkShow", + xlinktitle: "xlinkTitle", + "xlink:title": "xlinkTitle", + xlinktype: "xlinkType", + "xlink:type": "xlinkType", + xmlbase: "xmlBase", + "xml:base": "xmlBase", + xmllang: "xmlLang", + "xml:lang": "xmlLang", + xmlns: "xmlns", + "xml:space": "xmlSpace", + xmlnsxlink: "xmlnsXlink", + "xmlns:xlink": "xmlnsXlink", + xmlspace: "xmlSpace", + y1: "y1", + y2: "y2", + y: "y", + ychannelselector: "yChannelSelector", + z: "z", + zoomandpan: "zoomAndPan" + }; + var ariaProperties = { + "aria-current": 0, + "aria-description": 0, + "aria-details": 0, + "aria-disabled": 0, + "aria-hidden": 0, + "aria-invalid": 0, + "aria-keyshortcuts": 0, + "aria-label": 0, + "aria-roledescription": 0, + "aria-autocomplete": 0, + "aria-checked": 0, + "aria-expanded": 0, + "aria-haspopup": 0, + "aria-level": 0, + "aria-modal": 0, + "aria-multiline": 0, + "aria-multiselectable": 0, + "aria-orientation": 0, + "aria-placeholder": 0, + "aria-pressed": 0, + "aria-readonly": 0, + "aria-required": 0, + "aria-selected": 0, + "aria-sort": 0, + "aria-valuemax": 0, + "aria-valuemin": 0, + "aria-valuenow": 0, + "aria-valuetext": 0, + "aria-atomic": 0, + "aria-busy": 0, + "aria-live": 0, + "aria-relevant": 0, + "aria-dropeffect": 0, + "aria-grabbed": 0, + "aria-activedescendant": 0, + "aria-colcount": 0, + "aria-colindex": 0, + "aria-colspan": 0, + "aria-controls": 0, + "aria-describedby": 0, + "aria-errormessage": 0, + "aria-flowto": 0, + "aria-labelledby": 0, + "aria-owns": 0, + "aria-posinset": 0, + "aria-rowcount": 0, + "aria-rowindex": 0, + "aria-rowspan": 0, + "aria-setsize": 0 + }; + var warnedProperties = {}; + var rARIA = new RegExp("^(aria)-[" + ATTRIBUTE_NAME_CHAR + "]*$"); + var rARIACamel = new RegExp("^(aria)[A-Z][" + ATTRIBUTE_NAME_CHAR + "]*$"); + function validateProperty(tagName, name) { + { + if (hasOwnProperty.call(warnedProperties, name) && warnedProperties[name]) { + return true; + } + if (rARIACamel.test(name)) { + var ariaName = "aria-" + name.slice(4).toLowerCase(); + var correctName = ariaProperties.hasOwnProperty(ariaName) ? ariaName : null; + if (correctName == null) { + error("Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.", name); + warnedProperties[name] = true; + return true; + } + if (name !== correctName) { + error("Invalid ARIA attribute `%s`. Did you mean `%s`?", name, correctName); + warnedProperties[name] = true; + return true; + } + } + if (rARIA.test(name)) { + var lowerCasedName = name.toLowerCase(); + var standardName = ariaProperties.hasOwnProperty(lowerCasedName) ? lowerCasedName : null; + if (standardName == null) { + warnedProperties[name] = true; + return false; + } + if (name !== standardName) { + error("Unknown ARIA attribute `%s`. Did you mean `%s`?", name, standardName); + warnedProperties[name] = true; + return true; + } + } + } + return true; + } + function warnInvalidARIAProps(type, props) { + { + var invalidProps = []; + for (var key in props) { + var isValid = validateProperty(type, key); + if (!isValid) { + invalidProps.push(key); + } + } + var unknownPropString = invalidProps.map(function(prop) { + return "`" + prop + "`"; + }).join(", "); + if (invalidProps.length === 1) { + error("Invalid aria prop %s on <%s> tag. For details, see https://reactjs.org/link/invalid-aria-props", unknownPropString, type); + } else if (invalidProps.length > 1) { + error("Invalid aria props %s on <%s> tag. For details, see https://reactjs.org/link/invalid-aria-props", unknownPropString, type); + } + } + } + function validateProperties(type, props) { + if (isCustomComponent(type, props)) { + return; + } + warnInvalidARIAProps(type, props); + } + var didWarnValueNull = false; + function validateProperties$1(type, props) { + { + if (type !== "input" && type !== "textarea" && type !== "select") { + return; + } + if (props != null && props.value === null && !didWarnValueNull) { + didWarnValueNull = true; + if (type === "select" && props.multiple) { + error("`value` prop on `%s` should not be null. Consider using an empty array when `multiple` is set to `true` to clear the component or `undefined` for uncontrolled components.", type); + } else { + error("`value` prop on `%s` should not be null. Consider using an empty string to clear the component or `undefined` for uncontrolled components.", type); + } + } + } + } + var validateProperty$1 = function() { + }; + { + var warnedProperties$1 = {}; + var EVENT_NAME_REGEX = /^on./; + var INVALID_EVENT_NAME_REGEX = /^on[^A-Z]/; + var rARIA$1 = new RegExp("^(aria)-[" + ATTRIBUTE_NAME_CHAR + "]*$"); + var rARIACamel$1 = new RegExp("^(aria)[A-Z][" + ATTRIBUTE_NAME_CHAR + "]*$"); + validateProperty$1 = function(tagName, name, value, eventRegistry) { + if (hasOwnProperty.call(warnedProperties$1, name) && warnedProperties$1[name]) { + return true; + } + var lowerCasedName = name.toLowerCase(); + if (lowerCasedName === "onfocusin" || lowerCasedName === "onfocusout") { + error("React uses onFocus and onBlur instead of onFocusIn and onFocusOut. All React events are normalized to bubble, so onFocusIn and onFocusOut are not needed/supported by React."); + warnedProperties$1[name] = true; + return true; + } + if (eventRegistry != null) { + var { registrationNameDependencies: registrationNameDependencies2, possibleRegistrationNames: possibleRegistrationNames2 } = eventRegistry; + if (registrationNameDependencies2.hasOwnProperty(name)) { + return true; + } + var registrationName = possibleRegistrationNames2.hasOwnProperty(lowerCasedName) ? possibleRegistrationNames2[lowerCasedName] : null; + if (registrationName != null) { + error("Invalid event handler property `%s`. Did you mean `%s`?", name, registrationName); + warnedProperties$1[name] = true; + return true; + } + if (EVENT_NAME_REGEX.test(name)) { + error("Unknown event handler property `%s`. It will be ignored.", name); + warnedProperties$1[name] = true; + return true; + } + } else if (EVENT_NAME_REGEX.test(name)) { + if (INVALID_EVENT_NAME_REGEX.test(name)) { + error("Invalid event handler property `%s`. React events use the camelCase naming convention, for example `onClick`.", name); + } + warnedProperties$1[name] = true; + return true; + } + if (rARIA$1.test(name) || rARIACamel$1.test(name)) { + return true; + } + if (lowerCasedName === "innerhtml") { + error("Directly setting property `innerHTML` is not permitted. For more information, lookup documentation on `dangerouslySetInnerHTML`."); + warnedProperties$1[name] = true; + return true; + } + if (lowerCasedName === "aria") { + error("The `aria` attribute is reserved for future use in React. Pass individual `aria-` attributes instead."); + warnedProperties$1[name] = true; + return true; + } + if (lowerCasedName === "is" && value !== null && value !== undefined && typeof value !== "string") { + error("Received a `%s` for a string attribute `is`. If this is expected, cast the value to a string.", typeof value); + warnedProperties$1[name] = true; + return true; + } + if (typeof value === "number" && isNaN(value)) { + error("Received NaN for the `%s` attribute. If this is expected, cast the value to a string.", name); + warnedProperties$1[name] = true; + return true; + } + var propertyInfo = getPropertyInfo(name); + var isReserved = propertyInfo !== null && propertyInfo.type === RESERVED; + if (possibleStandardNames.hasOwnProperty(lowerCasedName)) { + var standardName = possibleStandardNames[lowerCasedName]; + if (standardName !== name) { + error("Invalid DOM property `%s`. Did you mean `%s`?", name, standardName); + warnedProperties$1[name] = true; + return true; + } + } else if (!isReserved && name !== lowerCasedName) { + error("React does not recognize the `%s` prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase `%s` instead. If you accidentally passed it from a parent component, remove it from the DOM element.", name, lowerCasedName); + warnedProperties$1[name] = true; + return true; + } + if (typeof value === "boolean" && shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) { + if (value) { + error('Received `%s` for a non-boolean attribute `%s`.\n\nIf you want to write it to the DOM, pass a string instead: %s="%s" or %s={value.toString()}.', value, name, name, value, name); + } else { + error('Received `%s` for a non-boolean attribute `%s`.\n\nIf you want to write it to the DOM, pass a string instead: %s="%s" or %s={value.toString()}.\n\nIf you used to conditionally omit it with %s={condition && value}, pass %s={condition ? value : undefined} instead.', value, name, name, value, name, name, name); + } + warnedProperties$1[name] = true; + return true; + } + if (isReserved) { + return true; + } + if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) { + warnedProperties$1[name] = true; + return false; + } + if ((value === "false" || value === "true") && propertyInfo !== null && propertyInfo.type === BOOLEAN) { + error("Received the string `%s` for the boolean attribute `%s`. %s Did you mean %s={%s}?", value, name, value === "false" ? "The browser will interpret it as a truthy value." : 'Although this works, it will not work as expected if you pass the string "false".', name, value); + warnedProperties$1[name] = true; + return true; + } + return true; + }; + } + var warnUnknownProperties = function(type, props, eventRegistry) { + { + var unknownProps = []; + for (var key in props) { + var isValid = validateProperty$1(type, key, props[key], eventRegistry); + if (!isValid) { + unknownProps.push(key); + } + } + var unknownPropString = unknownProps.map(function(prop) { + return "`" + prop + "`"; + }).join(", "); + if (unknownProps.length === 1) { + error("Invalid value for prop %s on <%s> tag. Either remove it from the element, or pass a string or number value to keep it in the DOM. For details, see https://reactjs.org/link/attribute-behavior ", unknownPropString, type); + } else if (unknownProps.length > 1) { + error("Invalid values for props %s on <%s> tag. Either remove them from the element, or pass a string or number value to keep them in the DOM. For details, see https://reactjs.org/link/attribute-behavior ", unknownPropString, type); + } + } + }; + function validateProperties$2(type, props, eventRegistry) { + if (isCustomComponent(type, props)) { + return; + } + warnUnknownProperties(type, props, eventRegistry); + } + var IS_EVENT_HANDLE_NON_MANAGED_NODE = 1; + var IS_NON_DELEGATED = 1 << 1; + var IS_CAPTURE_PHASE = 1 << 2; + var SHOULD_NOT_PROCESS_POLYFILL_EVENT_PLUGINS = IS_EVENT_HANDLE_NON_MANAGED_NODE | IS_NON_DELEGATED | IS_CAPTURE_PHASE; + var currentReplayingEvent = null; + function setReplayingEvent(event) { + { + if (currentReplayingEvent !== null) { + error("Expected currently replaying event to be null. This error is likely caused by a bug in React. Please file an issue."); + } + } + currentReplayingEvent = event; + } + function resetReplayingEvent() { + { + if (currentReplayingEvent === null) { + error("Expected currently replaying event to not be null. This error is likely caused by a bug in React. Please file an issue."); + } + } + currentReplayingEvent = null; + } + function isReplayingEvent(event) { + return event === currentReplayingEvent; + } + function getEventTarget(nativeEvent) { + var target = nativeEvent.target || nativeEvent.srcElement || window; + if (target.correspondingUseElement) { + target = target.correspondingUseElement; + } + return target.nodeType === TEXT_NODE ? target.parentNode : target; + } + var restoreImpl = null; + var restoreTarget = null; + var restoreQueue = null; + function restoreStateOfTarget(target) { + var internalInstance = getInstanceFromNode(target); + if (!internalInstance) { + return; + } + if (typeof restoreImpl !== "function") { + throw new Error("setRestoreImplementation() needs to be called to handle a target for controlled events. This error is likely caused by a bug in React. Please file an issue."); + } + var stateNode = internalInstance.stateNode; + if (stateNode) { + var _props = getFiberCurrentPropsFromNode(stateNode); + restoreImpl(internalInstance.stateNode, internalInstance.type, _props); + } + } + function setRestoreImplementation(impl) { + restoreImpl = impl; + } + function enqueueStateRestore(target) { + if (restoreTarget) { + if (restoreQueue) { + restoreQueue.push(target); + } else { + restoreQueue = [target]; + } + } else { + restoreTarget = target; + } + } + function needsStateRestore() { + return restoreTarget !== null || restoreQueue !== null; + } + function restoreStateIfNeeded() { + if (!restoreTarget) { + return; + } + var target = restoreTarget; + var queuedTargets = restoreQueue; + restoreTarget = null; + restoreQueue = null; + restoreStateOfTarget(target); + if (queuedTargets) { + for (var i = 0;i < queuedTargets.length; i++) { + restoreStateOfTarget(queuedTargets[i]); + } + } + } + var batchedUpdatesImpl = function(fn, bookkeeping) { + return fn(bookkeeping); + }; + var flushSyncImpl = function() { + }; + var isInsideEventHandler = false; + function finishEventHandler() { + var controlledComponentsHavePendingUpdates = needsStateRestore(); + if (controlledComponentsHavePendingUpdates) { + flushSyncImpl(); + restoreStateIfNeeded(); + } + } + function batchedUpdates(fn, a, b) { + if (isInsideEventHandler) { + return fn(a, b); + } + isInsideEventHandler = true; + try { + return batchedUpdatesImpl(fn, a, b); + } finally { + isInsideEventHandler = false; + finishEventHandler(); + } + } + function setBatchingImplementation(_batchedUpdatesImpl, _discreteUpdatesImpl, _flushSyncImpl) { + batchedUpdatesImpl = _batchedUpdatesImpl; + flushSyncImpl = _flushSyncImpl; + } + function isInteractive(tag) { + return tag === "button" || tag === "input" || tag === "select" || tag === "textarea"; + } + function shouldPreventMouseEvent(name, type, props) { + switch (name) { + case "onClick": + case "onClickCapture": + case "onDoubleClick": + case "onDoubleClickCapture": + case "onMouseDown": + case "onMouseDownCapture": + case "onMouseMove": + case "onMouseMoveCapture": + case "onMouseUp": + case "onMouseUpCapture": + case "onMouseEnter": + return !!(props.disabled && isInteractive(type)); + default: + return false; + } + } + function getListener(inst, registrationName) { + var stateNode = inst.stateNode; + if (stateNode === null) { + return null; + } + var props = getFiberCurrentPropsFromNode(stateNode); + if (props === null) { + return null; + } + var listener = props[registrationName]; + if (shouldPreventMouseEvent(registrationName, inst.type, props)) { + return null; + } + if (listener && typeof listener !== "function") { + throw new Error("Expected `" + registrationName + "` listener to be a function, instead got a value of `" + typeof listener + "` type."); + } + return listener; + } + var passiveBrowserEventsSupported = false; + if (canUseDOM) { + try { + var options = {}; + Object.defineProperty(options, "passive", { + get: function() { + passiveBrowserEventsSupported = true; + } + }); + window.addEventListener("test", options, options); + window.removeEventListener("test", options, options); + } catch (e) { + passiveBrowserEventsSupported = false; + } + } + 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 (error2) { + this.onError(error2); + } + } + var invokeGuardedCallbackImpl = invokeGuardedCallbackProd; + { + 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 (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; + var didError = true; + var windowEvent = window.event; + var windowEventDescriptor = Object.getOwnPropertyDescriptor(window, "event"); + function restoreAfterDispatch() { + fakeNode.removeEventListener(evtType, callCallback2, false); + if (typeof window.event !== "undefined" && window.hasOwnProperty("event")) { + window.event = windowEvent; + } + } + var funcArgs = Array.prototype.slice.call(arguments, 3); + function callCallback2() { + didCall = true; + restoreAfterDispatch(); + func.apply(context, funcArgs); + didError = false; + } + var error2; + var didSetError = false; + var isCrossOriginError = false; + function handleWindowError(event) { + error2 = event.error; + didSetError = true; + if (error2 === null && event.colno === 0 && event.lineno === 0) { + isCrossOriginError = true; + } + if (event.defaultPrevented) { + if (error2 != null && typeof error2 === "object") { + try { + error2._suppressLogging = true; + } catch (inner) { + } + } + } + } + var evtType = "react-" + (name ? name : "invokeguardedcallback"); + window.addEventListener("error", handleWindowError); + fakeNode.addEventListener(evtType, callCallback2, false); + evt.initEvent(evtType, false, false); + fakeNode.dispatchEvent(evt); + if (windowEventDescriptor) { + Object.defineProperty(window, "event", windowEventDescriptor); + } + if (didCall && didError) { + if (!didSetError) { + error2 = 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) { + error2 = 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(error2); + } + window.removeEventListener("error", handleWindowError); + if (!didCall) { + restoreAfterDispatch(); + return invokeGuardedCallbackProd.apply(this, arguments); + } + }; + } + } + var invokeGuardedCallbackImpl$1 = invokeGuardedCallbackImpl; + var hasError = false; + var caughtError = null; + var hasRethrowError = false; + var rethrowError = null; + var reporter = { + onError: function(error2) { + hasError = true; + caughtError = error2; + } + }; + function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) { + hasError = false; + caughtError = null; + invokeGuardedCallbackImpl$1.apply(reporter, arguments); + } + function invokeGuardedCallbackAndCatchFirstError(name, func, context, a, b, c, d, e, f) { + invokeGuardedCallback.apply(this, arguments); + if (hasError) { + var error2 = clearCaughtError(); + if (!hasRethrowError) { + hasRethrowError = true; + rethrowError = error2; + } + } + } + function rethrowCaughtError() { + if (hasRethrowError) { + var error2 = rethrowError; + hasRethrowError = false; + rethrowError = null; + throw error2; + } + } + function hasCaughtError() { + return hasError; + } + function clearCaughtError() { + if (hasError) { + var error2 = caughtError; + hasError = false; + caughtError = null; + return error2; + } 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."); + } + } + function get(key) { + return key._reactInternals; + } + function has(key) { + return key._reactInternals !== undefined; + } + function set(key, value) { + key._reactInternals = value; + } + var NoFlags = 0; + var PerformedWork = 1; + var Placement = 2; + var Update = 4; + 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 Visibility = 8192; + var StoreConsistency = 16384; + var LifecycleEffectMask = Passive | Update | Callback | Ref | Snapshot | StoreConsistency; + var HostEffectMask = 32767; + var Incomplete = 32768; + var ShouldCapture = 65536; + var ForceUpdateForLegacySuspense = 131072; + var Forked = 1048576; + var RefStatic = 2097152; + var LayoutStatic = 4194304; + var PassiveStatic = 8388608; + var MountLayoutDev = 16777216; + var MountPassiveDev = 33554432; + var BeforeMutationMask = Update | Snapshot | 0; + var MutationMask = Placement | Update | ChildDeletion | ContentReset | Ref | Hydrating | Visibility; + var LayoutMask = Update | Callback | Ref | Visibility; + var PassiveMask = Passive | ChildDeletion; + var StaticMask = LayoutStatic | PassiveStatic | RefStatic; + var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner; + function getNearestMountedFiber(fiber) { + var node = fiber; + var nearestMounted = fiber; + if (!fiber.alternate) { + var nextNode = node; + do { + node = nextNode; + if ((node.flags & (Placement | Hydrating)) !== NoFlags) { + nearestMounted = node.return; + } + nextNode = node.return; + } while (nextNode); + } else { + while (node.return) { + node = node.return; + } + } + if (node.tag === HostRoot) { + return nearestMounted; + } + return null; + } + function getSuspenseInstanceFromFiber(fiber) { + if (fiber.tag === SuspenseComponent) { + var suspenseState = fiber.memoizedState; + if (suspenseState === null) { + var current2 = fiber.alternate; + if (current2 !== null) { + suspenseState = current2.memoizedState; + } + } + if (suspenseState !== null) { + return suspenseState.dehydrated; + } + } + return null; + } + function getContainerFromFiber(fiber) { + return fiber.tag === HostRoot ? fiber.stateNode.containerInfo : 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) { + 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; + } + var a = fiber; + var b = alternate; + while (true) { + var parentA = a.return; + if (parentA === null) { + break; + } + var parentB = parentA.alternate; + if (parentB === null) { + var nextParent = parentA.return; + if (nextParent !== null) { + a = b = nextParent; + continue; + } + break; + } + if (parentA.child === parentB.child) { + var child = parentA.child; + while (child) { + if (child === a) { + assertIsMounted(parentA); + return fiber; + } + if (child === b) { + assertIsMounted(parentA); + return alternate; + } + child = child.sibling; + } + throw new Error("Unable to find node on an unmounted component."); + } + if (a.return !== b.return) { + a = parentA; + b = parentB; + } else { + 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) { + _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 (a.tag !== HostRoot) { + throw new Error("Unable to find node on an unmounted component."); + } + if (a.stateNode.current === a) { + return fiber; + } + return alternate; + } + function findCurrentHostFiber(parent) { + var currentParent = findCurrentFiberUsingSlowPath(parent); + return currentParent !== null ? findCurrentHostFiberImpl(currentParent) : null; + } + function findCurrentHostFiberImpl(node) { + 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) { + 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 scheduleCallback = Scheduler.unstable_scheduleCallback; + var cancelCallback = Scheduler.unstable_cancelCallback; + var shouldYield = Scheduler.unstable_shouldYield; + var requestPaint = Scheduler.unstable_requestPaint; + var now = Scheduler.unstable_now; + var getCurrentPriorityLevel = Scheduler.unstable_getCurrentPriorityLevel; + var ImmediatePriority = Scheduler.unstable_ImmediatePriority; + var UserBlockingPriority = Scheduler.unstable_UserBlockingPriority; + var NormalPriority = Scheduler.unstable_NormalPriority; + var LowPriority = Scheduler.unstable_LowPriority; + var IdlePriority = Scheduler.unstable_IdlePriority; + var unstable_yieldValue2 = Scheduler.unstable_yieldValue; + var unstable_setDisableYieldValue2 = 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") { + return false; + } + var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__; + if (hook.isDisabled) { + 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"); + } + return true; + } + try { + if (enableSchedulingProfiler) { + internals = assign({}, internals, { + getLaneLabelMap, + injectProfilingHooks + }); + } + rendererID = hook.inject(internals); + injectedHook = hook; + } catch (err) { + { + error("React instrumentation encountered an error: %s.", err); + } + } + if (hook.checkDCE) { + return true; + } else { + return false; + } + } + function onScheduleRoot(root2, children) { + { + if (injectedHook && typeof injectedHook.onScheduleFiberRoot === "function") { + try { + injectedHook.onScheduleFiberRoot(rendererID, root2, children); + } catch (err) { + if (!hasLoggedError) { + hasLoggedError = true; + error("React instrumentation encountered an error: %s", err); + } + } + } + } + } + function onCommitRoot(root2, eventPriority) { + if (injectedHook && typeof injectedHook.onCommitFiberRoot === "function") { + try { + var didError = (root2.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, root2, schedulerPriority, didError); + } else { + injectedHook.onCommitFiberRoot(rendererID, root2, undefined, didError); + } + } catch (err) { + { + if (!hasLoggedError) { + hasLoggedError = true; + error("React instrumentation encountered an error: %s", err); + } + } + } + } + } + function onPostCommitRoot(root2) { + if (injectedHook && typeof injectedHook.onPostCommitFiberRoot === "function") { + try { + injectedHook.onPostCommitFiberRoot(rendererID, root2); + } 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_yieldValue2 === "function") { + unstable_setDisableYieldValue2(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); + } + } + } + } + } + } + function injectProfilingHooks(profilingHooks) { + injectedProfilingHooks = profilingHooks; + } + function getLaneLabelMap() { + { + var map = new Map; + var lane = 1; + for (var index2 = 0;index2 < TotalLanes; index2++) { + 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); + } + } + } + var NoMode = 0; + var ConcurrentMode = 1; + var ProfileMode = 2; + var StrictLegacyMode = 8; + var StrictEffectsMode = 16; + var clz32 = Math.clz32 ? Math.clz32 : clz32Fallback; + 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; + } + 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; + 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."); + } + return lanes; + } + } + function getNextLanes(root2, wipLanes) { + var pendingLanes = root2.pendingLanes; + if (pendingLanes === NoLanes) { + return NoLanes; + } + var nextLanes = NoLanes; + var suspendedLanes = root2.suspendedLanes; + var pingedLanes = root2.pingedLanes; + 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 { + var unblockedLanes = pendingLanes & ~suspendedLanes; + if (unblockedLanes !== NoLanes) { + nextLanes = getHighestPriorityLanes(unblockedLanes); + } else { + if (pingedLanes !== NoLanes) { + nextLanes = getHighestPriorityLanes(pingedLanes); + } + } + } + if (nextLanes === NoLanes) { + return NoLanes; + } + if (wipLanes !== NoLanes && wipLanes !== nextLanes && (wipLanes & suspendedLanes) === NoLanes) { + var nextLane = getHighestPriorityLane(nextLanes); + var wipLane = getHighestPriorityLane(wipLanes); + if (nextLane >= wipLane || nextLane === DefaultLane && (wipLane & TransitionLanes) !== NoLanes) { + return wipLanes; + } + } + if ((nextLanes & InputContinuousLane) !== NoLanes) { + nextLanes |= pendingLanes & DefaultLane; + } + var entangledLanes = root2.entangledLanes; + if (entangledLanes !== NoLanes) { + var entanglements = root2.entanglements; + var lanes = nextLanes & entangledLanes; + while (lanes > 0) { + var index2 = pickArbitraryLaneIndex(lanes); + var lane = 1 << index2; + nextLanes |= entanglements[index2]; + lanes &= ~lane; + } + } + return nextLanes; + } + function getMostRecentEventTime(root2, lanes) { + var eventTimes = root2.eventTimes; + var mostRecentEventTime = NoTimestamp; + while (lanes > 0) { + var index2 = pickArbitraryLaneIndex(lanes); + var lane = 1 << index2; + var eventTime = eventTimes[index2]; + if (eventTime > mostRecentEventTime) { + mostRecentEventTime = eventTime; + } + lanes &= ~lane; + } + return mostRecentEventTime; + } + function computeExpirationTime(lane, currentTime) { + switch (lane) { + case SyncLane: + case InputContinuousHydrationLane: + case InputContinuousLane: + 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: + return NoTimestamp; + case SelectiveHydrationLane: + case IdleHydrationLane: + case IdleLane: + case OffscreenLane: + return NoTimestamp; + default: + { + error("Should have found matching lanes. This is a bug in React."); + } + return NoTimestamp; + } + } + function markStarvedLanesAsExpired(root2, currentTime) { + var pendingLanes = root2.pendingLanes; + var suspendedLanes = root2.suspendedLanes; + var pingedLanes = root2.pingedLanes; + var expirationTimes = root2.expirationTimes; + var lanes = pendingLanes; + while (lanes > 0) { + var index2 = pickArbitraryLaneIndex(lanes); + var lane = 1 << index2; + var expirationTime = expirationTimes[index2]; + if (expirationTime === NoTimestamp) { + if ((lane & suspendedLanes) === NoLanes || (lane & pingedLanes) !== NoLanes) { + expirationTimes[index2] = computeExpirationTime(lane, currentTime); + } + } else if (expirationTime <= currentTime) { + root2.expiredLanes |= lane; + } + lanes &= ~lane; + } + } + function getHighestPriorityPendingLanes(root2) { + return getHighestPriorityLanes(root2.pendingLanes); + } + function getLanesToRetrySynchronouslyOnError(root2) { + var everythingButOffscreen = root2.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 includesOnlyNonUrgentLanes(lanes) { + var UrgentLanes = SyncLane | InputContinuousLane | DefaultLane; + return (lanes & UrgentLanes) === NoLanes; + } + function includesOnlyTransitions(lanes) { + return (lanes & TransitionLanes) === lanes; + } + function includesBlockingLane(root2, lanes) { + var SyncDefaultLanes = InputContinuousHydrationLane | InputContinuousLane | DefaultHydrationLane | DefaultLane; + return (lanes & SyncDefaultLanes) !== NoLanes; + } + function includesExpiredLane(root2, lanes) { + return (lanes & root2.expiredLanes) !== NoLanes; + } + function isTransitionLane(lane) { + return (lane & TransitionLanes) !== NoLanes; + } + function claimNextTransitionLane() { + var lane = nextTransitionLane; + nextTransitionLane <<= 1; + if ((nextTransitionLane & TransitionLanes) === NoLanes) { + nextTransitionLane = TransitionLane1; + } + return lane; + } + function claimNextRetryLane() { + var lane = nextRetryLane; + nextRetryLane <<= 1; + if ((nextRetryLane & RetryLanes) === NoLanes) { + nextRetryLane = RetryLane1; + } + return lane; + } + function getHighestPriorityLane(lanes) { + return lanes & -lanes; + } + function pickArbitraryLane(lanes) { + 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(set2, subset) { + return (set2 & subset) === subset; + } + function mergeLanes(a, b) { + return a | b; + } + function removeLanes(set2, subset) { + return set2 & ~subset; + } + function intersectLanes(a, b) { + return a & b; + } + function laneToLanes(lane) { + return lane; + } + function higherPriorityLane(a, b) { + return a !== NoLane && a < b ? a : b; + } + function createLaneMap(initial) { + var laneMap = []; + for (var i = 0;i < TotalLanes; i++) { + laneMap.push(initial); + } + return laneMap; + } + function markRootUpdated(root2, updateLane, eventTime) { + root2.pendingLanes |= updateLane; + if (updateLane !== IdleLane) { + root2.suspendedLanes = NoLanes; + root2.pingedLanes = NoLanes; + } + var eventTimes = root2.eventTimes; + var index2 = laneToIndex(updateLane); + eventTimes[index2] = eventTime; + } + function markRootSuspended(root2, suspendedLanes) { + root2.suspendedLanes |= suspendedLanes; + root2.pingedLanes &= ~suspendedLanes; + var expirationTimes = root2.expirationTimes; + var lanes = suspendedLanes; + while (lanes > 0) { + var index2 = pickArbitraryLaneIndex(lanes); + var lane = 1 << index2; + expirationTimes[index2] = NoTimestamp; + lanes &= ~lane; + } + } + function markRootPinged(root2, pingedLanes, eventTime) { + root2.pingedLanes |= root2.suspendedLanes & pingedLanes; + } + function markRootFinished(root2, remainingLanes) { + var noLongerPendingLanes = root2.pendingLanes & ~remainingLanes; + root2.pendingLanes = remainingLanes; + root2.suspendedLanes = NoLanes; + root2.pingedLanes = NoLanes; + root2.expiredLanes &= remainingLanes; + root2.mutableReadLanes &= remainingLanes; + root2.entangledLanes &= remainingLanes; + var entanglements = root2.entanglements; + var eventTimes = root2.eventTimes; + var expirationTimes = root2.expirationTimes; + var lanes = noLongerPendingLanes; + while (lanes > 0) { + var index2 = pickArbitraryLaneIndex(lanes); + var lane = 1 << index2; + entanglements[index2] = NoLanes; + eventTimes[index2] = NoTimestamp; + expirationTimes[index2] = NoTimestamp; + lanes &= ~lane; + } + } + function markRootEntangled(root2, entangledLanes) { + var rootEntangledLanes = root2.entangledLanes |= entangledLanes; + var entanglements = root2.entanglements; + var lanes = rootEntangledLanes; + while (lanes) { + var index2 = pickArbitraryLaneIndex(lanes); + var lane = 1 << index2; + if (lane & entangledLanes | entanglements[index2] & entangledLanes) { + entanglements[index2] |= entangledLanes; + } + lanes &= ~lane; + } + } + function getBumpedLaneForHydration(root2, renderLanes2) { + var renderLane = getHighestPriorityLane(renderLanes2); + 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: + lane = NoLane; + break; + } + if ((lane & (root2.suspendedLanes | renderLanes2)) !== NoLane) { + return NoLane; + } + return lane; + } + function addFiberToLanesMap(root2, fiber, lanes) { + if (!isDevToolsPresent) { + return; + } + var pendingUpdatersLaneMap = root2.pendingUpdatersLaneMap; + while (lanes > 0) { + var index2 = laneToIndex(lanes); + var lane = 1 << index2; + var updaters = pendingUpdatersLaneMap[index2]; + updaters.add(fiber); + lanes &= ~lane; + } + } + function movePendingFibersToMemoized(root2, lanes) { + if (!isDevToolsPresent) { + return; + } + var pendingUpdatersLaneMap = root2.pendingUpdatersLaneMap; + var memoizedUpdaters = root2.memoizedUpdaters; + while (lanes > 0) { + var index2 = laneToIndex(lanes); + var lane = 1 << index2; + var updaters = pendingUpdatersLaneMap[index2]; + 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; + } + } + function getTransitionsForLanes(root2, lanes) { + { + return null; + } + } + 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; + } + function isRootDehydrated(root2) { + var currentState = root2.current.memoizedState; + return currentState.isDehydrated; + } + var _attemptSynchronousHydration; + function setAttemptSynchronousHydration(fn) { + _attemptSynchronousHydration = fn; + } + function attemptSynchronousHydration(fiber) { + _attemptSynchronousHydration(fiber); + } + var attemptContinuousHydration; + function setAttemptContinuousHydration(fn) { + attemptContinuousHydration = fn; + } + var attemptHydrationAtCurrentPriority; + function setAttemptHydrationAtCurrentPriority(fn) { + attemptHydrationAtCurrentPriority = fn; + } + var getCurrentUpdatePriority$1; + function setGetCurrentUpdatePriority(fn) { + getCurrentUpdatePriority$1 = fn; + } + var attemptHydrationAtPriority; + function setAttemptHydrationAtPriority(fn) { + attemptHydrationAtPriority = fn; + } + var hasScheduledReplayAttempt = false; + var queuedDiscreteEvents = []; + var queuedFocus = null; + var queuedDrag = null; + var queuedMouse = null; + var queuedPointers = new Map; + var queuedPointerCaptures = new Map; + var queuedExplicitHydrationTargets = []; + var discreteReplayableEvents = [ + "mousedown", + "mouseup", + "touchcancel", + "touchend", + "touchstart", + "auxclick", + "dblclick", + "pointercancel", + "pointerdown", + "pointerup", + "dragend", + "dragstart", + "drop", + "compositionend", + "compositionstart", + "keydown", + "keypress", + "keyup", + "input", + "textInput", + "copy", + "cut", + "paste", + "click", + "change", + "contextmenu", + "reset", + "submit" + ]; + function isDiscreteEventThatRequiresHydration(eventType) { + return discreteReplayableEvents.indexOf(eventType) > -1; + } + function createQueuedReplayableEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent) { + return { + blockedOn, + domEventName, + eventSystemFlags, + nativeEvent, + targetContainers: [targetContainer] + }; + } + function clearIfContinuousEvent(domEventName, nativeEvent) { + switch (domEventName) { + case "focusin": + case "focusout": + queuedFocus = null; + break; + case "dragenter": + case "dragleave": + queuedDrag = null; + break; + case "mouseover": + case "mouseout": + queuedMouse = null; + break; + case "pointerover": + case "pointerout": { + var pointerId = nativeEvent.pointerId; + queuedPointers.delete(pointerId); + break; + } + case "gotpointercapture": + case "lostpointercapture": { + var _pointerId = nativeEvent.pointerId; + queuedPointerCaptures.delete(_pointerId); + break; + } + } + } + function accumulateOrCreateContinuousQueuedReplayableEvent(existingQueuedEvent, blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent) { + if (existingQueuedEvent === null || existingQueuedEvent.nativeEvent !== nativeEvent) { + var queuedEvent = createQueuedReplayableEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent); + if (blockedOn !== null) { + var _fiber2 = getInstanceFromNode(blockedOn); + if (_fiber2 !== null) { + attemptContinuousHydration(_fiber2); + } + } + return queuedEvent; + } + existingQueuedEvent.eventSystemFlags |= eventSystemFlags; + var targetContainers = existingQueuedEvent.targetContainers; + if (targetContainer !== null && targetContainers.indexOf(targetContainer) === -1) { + targetContainers.push(targetContainer); + } + return existingQueuedEvent; + } + function queueIfContinuousEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent) { + switch (domEventName) { + case "focusin": { + var focusEvent = nativeEvent; + queuedFocus = accumulateOrCreateContinuousQueuedReplayableEvent(queuedFocus, blockedOn, domEventName, eventSystemFlags, targetContainer, focusEvent); + return true; + } + case "dragenter": { + var dragEvent = nativeEvent; + queuedDrag = accumulateOrCreateContinuousQueuedReplayableEvent(queuedDrag, blockedOn, domEventName, eventSystemFlags, targetContainer, dragEvent); + return true; + } + case "mouseover": { + var mouseEvent = nativeEvent; + queuedMouse = accumulateOrCreateContinuousQueuedReplayableEvent(queuedMouse, blockedOn, domEventName, eventSystemFlags, targetContainer, mouseEvent); + return true; + } + case "pointerover": { + var pointerEvent = nativeEvent; + var pointerId = pointerEvent.pointerId; + queuedPointers.set(pointerId, accumulateOrCreateContinuousQueuedReplayableEvent(queuedPointers.get(pointerId) || null, blockedOn, domEventName, eventSystemFlags, targetContainer, pointerEvent)); + return true; + } + case "gotpointercapture": { + var _pointerEvent = nativeEvent; + var _pointerId2 = _pointerEvent.pointerId; + queuedPointerCaptures.set(_pointerId2, accumulateOrCreateContinuousQueuedReplayableEvent(queuedPointerCaptures.get(_pointerId2) || null, blockedOn, domEventName, eventSystemFlags, targetContainer, _pointerEvent)); + return true; + } + } + return false; + } + function attemptExplicitHydrationTarget(queuedTarget) { + var targetInst = getClosestInstanceFromNode(queuedTarget.target); + if (targetInst !== null) { + var nearestMounted = getNearestMountedFiber(targetInst); + if (nearestMounted !== null) { + var tag = nearestMounted.tag; + if (tag === SuspenseComponent) { + var instance = getSuspenseInstanceFromFiber(nearestMounted); + if (instance !== null) { + queuedTarget.blockedOn = instance; + attemptHydrationAtPriority(queuedTarget.priority, function() { + attemptHydrationAtCurrentPriority(nearestMounted); + }); + return; + } + } else if (tag === HostRoot) { + var root2 = nearestMounted.stateNode; + if (isRootDehydrated(root2)) { + queuedTarget.blockedOn = getContainerFromFiber(nearestMounted); + return; + } + } + } + } + queuedTarget.blockedOn = null; + } + function queueExplicitHydrationTarget(target) { + var updatePriority = getCurrentUpdatePriority$1(); + var queuedTarget = { + blockedOn: null, + target, + priority: updatePriority + }; + var i = 0; + for (;i < queuedExplicitHydrationTargets.length; i++) { + if (!isHigherEventPriority(updatePriority, queuedExplicitHydrationTargets[i].priority)) { + break; + } + } + queuedExplicitHydrationTargets.splice(i, 0, queuedTarget); + if (i === 0) { + attemptExplicitHydrationTarget(queuedTarget); + } + } + function attemptReplayContinuousQueuedEvent(queuedEvent) { + if (queuedEvent.blockedOn !== null) { + return false; + } + var targetContainers = queuedEvent.targetContainers; + while (targetContainers.length > 0) { + var targetContainer = targetContainers[0]; + var nextBlockedOn = findInstanceBlockingEvent(queuedEvent.domEventName, queuedEvent.eventSystemFlags, targetContainer, queuedEvent.nativeEvent); + if (nextBlockedOn === null) { + { + var nativeEvent = queuedEvent.nativeEvent; + var nativeEventClone = new nativeEvent.constructor(nativeEvent.type, nativeEvent); + setReplayingEvent(nativeEventClone); + nativeEvent.target.dispatchEvent(nativeEventClone); + resetReplayingEvent(); + } + } else { + var _fiber3 = getInstanceFromNode(nextBlockedOn); + if (_fiber3 !== null) { + attemptContinuousHydration(_fiber3); + } + queuedEvent.blockedOn = nextBlockedOn; + return false; + } + targetContainers.shift(); + } + return true; + } + function attemptReplayContinuousQueuedEventInMap(queuedEvent, key, map) { + if (attemptReplayContinuousQueuedEvent(queuedEvent)) { + map.delete(key); + } + } + function replayUnblockedEvents() { + hasScheduledReplayAttempt = false; + if (queuedFocus !== null && attemptReplayContinuousQueuedEvent(queuedFocus)) { + queuedFocus = null; + } + if (queuedDrag !== null && attemptReplayContinuousQueuedEvent(queuedDrag)) { + queuedDrag = null; + } + if (queuedMouse !== null && attemptReplayContinuousQueuedEvent(queuedMouse)) { + queuedMouse = null; + } + queuedPointers.forEach(attemptReplayContinuousQueuedEventInMap); + queuedPointerCaptures.forEach(attemptReplayContinuousQueuedEventInMap); + } + function scheduleCallbackIfUnblocked(queuedEvent, unblocked) { + if (queuedEvent.blockedOn === unblocked) { + queuedEvent.blockedOn = null; + if (!hasScheduledReplayAttempt) { + hasScheduledReplayAttempt = true; + Scheduler.unstable_scheduleCallback(Scheduler.unstable_NormalPriority, replayUnblockedEvents); + } + } + } + function retryIfBlockedOn(unblocked) { + if (queuedDiscreteEvents.length > 0) { + scheduleCallbackIfUnblocked(queuedDiscreteEvents[0], unblocked); + for (var i = 1;i < queuedDiscreteEvents.length; i++) { + var queuedEvent = queuedDiscreteEvents[i]; + if (queuedEvent.blockedOn === unblocked) { + queuedEvent.blockedOn = null; + } + } + } + if (queuedFocus !== null) { + scheduleCallbackIfUnblocked(queuedFocus, unblocked); + } + if (queuedDrag !== null) { + scheduleCallbackIfUnblocked(queuedDrag, unblocked); + } + if (queuedMouse !== null) { + scheduleCallbackIfUnblocked(queuedMouse, unblocked); + } + var unblock = function(queuedEvent2) { + return scheduleCallbackIfUnblocked(queuedEvent2, unblocked); + }; + queuedPointers.forEach(unblock); + queuedPointerCaptures.forEach(unblock); + for (var _i = 0;_i < queuedExplicitHydrationTargets.length; _i++) { + var queuedTarget = queuedExplicitHydrationTargets[_i]; + if (queuedTarget.blockedOn === unblocked) { + queuedTarget.blockedOn = null; + } + } + while (queuedExplicitHydrationTargets.length > 0) { + var nextExplicitTarget = queuedExplicitHydrationTargets[0]; + if (nextExplicitTarget.blockedOn !== null) { + break; + } else { + attemptExplicitHydrationTarget(nextExplicitTarget); + if (nextExplicitTarget.blockedOn === null) { + queuedExplicitHydrationTargets.shift(); + } + } + } + } + var ReactCurrentBatchConfig = ReactSharedInternals.ReactCurrentBatchConfig; + var _enabled = true; + function setEnabled(enabled) { + _enabled = !!enabled; + } + function isEnabled() { + return _enabled; + } + function createEventListenerWrapperWithPriority(targetContainer, domEventName, eventSystemFlags) { + var eventPriority = getEventPriority(domEventName); + var listenerWrapper; + switch (eventPriority) { + case DiscreteEventPriority: + listenerWrapper = dispatchDiscreteEvent; + break; + case ContinuousEventPriority: + listenerWrapper = dispatchContinuousEvent; + break; + case DefaultEventPriority: + default: + listenerWrapper = dispatchEvent; + break; + } + return listenerWrapper.bind(null, domEventName, eventSystemFlags, targetContainer); + } + function dispatchDiscreteEvent(domEventName, eventSystemFlags, container, nativeEvent) { + var previousPriority = getCurrentUpdatePriority(); + var prevTransition = ReactCurrentBatchConfig.transition; + ReactCurrentBatchConfig.transition = null; + try { + setCurrentUpdatePriority(DiscreteEventPriority); + dispatchEvent(domEventName, eventSystemFlags, container, nativeEvent); + } finally { + setCurrentUpdatePriority(previousPriority); + ReactCurrentBatchConfig.transition = prevTransition; + } + } + function dispatchContinuousEvent(domEventName, eventSystemFlags, container, nativeEvent) { + var previousPriority = getCurrentUpdatePriority(); + var prevTransition = ReactCurrentBatchConfig.transition; + ReactCurrentBatchConfig.transition = null; + try { + setCurrentUpdatePriority(ContinuousEventPriority); + dispatchEvent(domEventName, eventSystemFlags, container, nativeEvent); + } finally { + setCurrentUpdatePriority(previousPriority); + ReactCurrentBatchConfig.transition = prevTransition; + } + } + function dispatchEvent(domEventName, eventSystemFlags, targetContainer, nativeEvent) { + if (!_enabled) { + return; + } + { + dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay(domEventName, eventSystemFlags, targetContainer, nativeEvent); + } + } + function dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay(domEventName, eventSystemFlags, targetContainer, nativeEvent) { + var blockedOn = findInstanceBlockingEvent(domEventName, eventSystemFlags, targetContainer, nativeEvent); + if (blockedOn === null) { + dispatchEventForPluginEventSystem(domEventName, eventSystemFlags, nativeEvent, return_targetInst, targetContainer); + clearIfContinuousEvent(domEventName, nativeEvent); + return; + } + if (queueIfContinuousEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent)) { + nativeEvent.stopPropagation(); + return; + } + clearIfContinuousEvent(domEventName, nativeEvent); + if (eventSystemFlags & IS_CAPTURE_PHASE && isDiscreteEventThatRequiresHydration(domEventName)) { + while (blockedOn !== null) { + var fiber = getInstanceFromNode(blockedOn); + if (fiber !== null) { + attemptSynchronousHydration(fiber); + } + var nextBlockedOn = findInstanceBlockingEvent(domEventName, eventSystemFlags, targetContainer, nativeEvent); + if (nextBlockedOn === null) { + dispatchEventForPluginEventSystem(domEventName, eventSystemFlags, nativeEvent, return_targetInst, targetContainer); + } + if (nextBlockedOn === blockedOn) { + break; + } + blockedOn = nextBlockedOn; + } + if (blockedOn !== null) { + nativeEvent.stopPropagation(); + } + return; + } + dispatchEventForPluginEventSystem(domEventName, eventSystemFlags, nativeEvent, null, targetContainer); + } + var return_targetInst = null; + function findInstanceBlockingEvent(domEventName, eventSystemFlags, targetContainer, nativeEvent) { + return_targetInst = null; + var nativeEventTarget = getEventTarget(nativeEvent); + var targetInst = getClosestInstanceFromNode(nativeEventTarget); + if (targetInst !== null) { + var nearestMounted = getNearestMountedFiber(targetInst); + if (nearestMounted === null) { + targetInst = null; + } else { + var tag = nearestMounted.tag; + if (tag === SuspenseComponent) { + var instance = getSuspenseInstanceFromFiber(nearestMounted); + if (instance !== null) { + return instance; + } + targetInst = null; + } else if (tag === HostRoot) { + var root2 = nearestMounted.stateNode; + if (isRootDehydrated(root2)) { + return getContainerFromFiber(nearestMounted); + } + targetInst = null; + } else if (nearestMounted !== targetInst) { + targetInst = null; + } + } + } + return_targetInst = targetInst; + return null; + } + function getEventPriority(domEventName) { + switch (domEventName) { + case "cancel": + case "click": + case "close": + case "contextmenu": + case "copy": + case "cut": + case "auxclick": + case "dblclick": + case "dragend": + case "dragstart": + case "drop": + case "focusin": + case "focusout": + case "input": + case "invalid": + case "keydown": + case "keypress": + case "keyup": + case "mousedown": + case "mouseup": + case "paste": + case "pause": + case "play": + case "pointercancel": + case "pointerdown": + case "pointerup": + case "ratechange": + case "reset": + case "resize": + case "seeked": + case "submit": + case "touchcancel": + case "touchend": + case "touchstart": + case "volumechange": + case "change": + case "selectionchange": + case "textInput": + case "compositionstart": + case "compositionend": + case "compositionupdate": + case "beforeblur": + case "afterblur": + case "beforeinput": + case "blur": + case "fullscreenchange": + case "focus": + case "hashchange": + case "popstate": + case "select": + case "selectstart": + return DiscreteEventPriority; + case "drag": + case "dragenter": + case "dragexit": + case "dragleave": + case "dragover": + case "mousemove": + case "mouseout": + case "mouseover": + case "pointermove": + case "pointerout": + case "pointerover": + case "scroll": + case "toggle": + case "touchmove": + case "wheel": + case "mouseenter": + case "mouseleave": + case "pointerenter": + case "pointerleave": + return ContinuousEventPriority; + case "message": { + var schedulerPriority = getCurrentPriorityLevel(); + switch (schedulerPriority) { + case ImmediatePriority: + return DiscreteEventPriority; + case UserBlockingPriority: + return ContinuousEventPriority; + case NormalPriority: + case LowPriority: + return DefaultEventPriority; + case IdlePriority: + return IdleEventPriority; + default: + return DefaultEventPriority; + } + } + default: + return DefaultEventPriority; + } + } + function addEventBubbleListener(target, eventType, listener) { + target.addEventListener(eventType, listener, false); + return listener; + } + function addEventCaptureListener(target, eventType, listener) { + target.addEventListener(eventType, listener, true); + return listener; + } + function addEventCaptureListenerWithPassiveFlag(target, eventType, listener, passive) { + target.addEventListener(eventType, listener, { + capture: true, + passive + }); + return listener; + } + function addEventBubbleListenerWithPassiveFlag(target, eventType, listener, passive) { + target.addEventListener(eventType, listener, { + passive + }); + return listener; + } + var root = null; + var startText = null; + var fallbackText = null; + function initialize(nativeEventTarget) { + root = nativeEventTarget; + startText = getText(); + return true; + } + function reset() { + root = null; + startText = null; + fallbackText = null; + } + function getData() { + if (fallbackText) { + return fallbackText; + } + var start; + var startValue = startText; + var startLength = startValue.length; + var end; + var endValue = getText(); + var endLength = endValue.length; + for (start = 0;start < startLength; start++) { + if (startValue[start] !== endValue[start]) { + break; + } + } + var minEnd = startLength - start; + for (end = 1;end <= minEnd; end++) { + if (startValue[startLength - end] !== endValue[endLength - end]) { + break; + } + } + var sliceTail = end > 1 ? 1 - end : undefined; + fallbackText = endValue.slice(start, sliceTail); + return fallbackText; + } + function getText() { + if ("value" in root) { + return root.value; + } + return root.textContent; + } + function getEventCharCode(nativeEvent) { + var charCode; + var keyCode = nativeEvent.keyCode; + if ("charCode" in nativeEvent) { + charCode = nativeEvent.charCode; + if (charCode === 0 && keyCode === 13) { + charCode = 13; + } + } else { + charCode = keyCode; + } + if (charCode === 10) { + charCode = 13; + } + if (charCode >= 32 || charCode === 13) { + return charCode; + } + return 0; + } + function functionThatReturnsTrue() { + return true; + } + function functionThatReturnsFalse() { + return false; + } + function createSyntheticEvent(Interface) { + function SyntheticBaseEvent(reactName, reactEventType, targetInst, nativeEvent, nativeEventTarget) { + this._reactName = reactName; + this._targetInst = targetInst; + this.type = reactEventType; + this.nativeEvent = nativeEvent; + this.target = nativeEventTarget; + this.currentTarget = null; + for (var _propName in Interface) { + if (!Interface.hasOwnProperty(_propName)) { + continue; + } + var normalize = Interface[_propName]; + if (normalize) { + this[_propName] = normalize(nativeEvent); + } else { + this[_propName] = nativeEvent[_propName]; + } + } + var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false; + if (defaultPrevented) { + this.isDefaultPrevented = functionThatReturnsTrue; + } else { + this.isDefaultPrevented = functionThatReturnsFalse; + } + this.isPropagationStopped = functionThatReturnsFalse; + return this; + } + assign(SyntheticBaseEvent.prototype, { + preventDefault: function() { + this.defaultPrevented = true; + var event = this.nativeEvent; + if (!event) { + return; + } + if (event.preventDefault) { + event.preventDefault(); + } else if (typeof event.returnValue !== "unknown") { + event.returnValue = false; + } + this.isDefaultPrevented = functionThatReturnsTrue; + }, + stopPropagation: function() { + var event = this.nativeEvent; + if (!event) { + return; + } + if (event.stopPropagation) { + event.stopPropagation(); + } else if (typeof event.cancelBubble !== "unknown") { + event.cancelBubble = true; + } + this.isPropagationStopped = functionThatReturnsTrue; + }, + persist: function() { + }, + isPersistent: functionThatReturnsTrue + }); + return SyntheticBaseEvent; + } + var EventInterface = { + eventPhase: 0, + bubbles: 0, + cancelable: 0, + timeStamp: function(event) { + return event.timeStamp || Date.now(); + }, + defaultPrevented: 0, + isTrusted: 0 + }; + var SyntheticEvent = createSyntheticEvent(EventInterface); + var UIEventInterface = assign({}, EventInterface, { + view: 0, + detail: 0 + }); + var SyntheticUIEvent = createSyntheticEvent(UIEventInterface); + var lastMovementX; + var lastMovementY; + var lastMouseEvent; + function updateMouseMovementPolyfillState(event) { + if (event !== lastMouseEvent) { + if (lastMouseEvent && event.type === "mousemove") { + lastMovementX = event.screenX - lastMouseEvent.screenX; + lastMovementY = event.screenY - lastMouseEvent.screenY; + } else { + lastMovementX = 0; + lastMovementY = 0; + } + lastMouseEvent = event; + } + } + var MouseEventInterface = assign({}, UIEventInterface, { + screenX: 0, + screenY: 0, + clientX: 0, + clientY: 0, + pageX: 0, + pageY: 0, + ctrlKey: 0, + shiftKey: 0, + altKey: 0, + metaKey: 0, + getModifierState: getEventModifierState, + button: 0, + buttons: 0, + relatedTarget: function(event) { + if (event.relatedTarget === undefined) + return event.fromElement === event.srcElement ? event.toElement : event.fromElement; + return event.relatedTarget; + }, + movementX: function(event) { + if ("movementX" in event) { + return event.movementX; + } + updateMouseMovementPolyfillState(event); + return lastMovementX; + }, + movementY: function(event) { + if ("movementY" in event) { + return event.movementY; + } + return lastMovementY; + } + }); + var SyntheticMouseEvent = createSyntheticEvent(MouseEventInterface); + var DragEventInterface = assign({}, MouseEventInterface, { + dataTransfer: 0 + }); + var SyntheticDragEvent = createSyntheticEvent(DragEventInterface); + var FocusEventInterface = assign({}, UIEventInterface, { + relatedTarget: 0 + }); + var SyntheticFocusEvent = createSyntheticEvent(FocusEventInterface); + var AnimationEventInterface = assign({}, EventInterface, { + animationName: 0, + elapsedTime: 0, + pseudoElement: 0 + }); + var SyntheticAnimationEvent = createSyntheticEvent(AnimationEventInterface); + var ClipboardEventInterface = assign({}, EventInterface, { + clipboardData: function(event) { + return "clipboardData" in event ? event.clipboardData : window.clipboardData; + } + }); + var SyntheticClipboardEvent = createSyntheticEvent(ClipboardEventInterface); + var CompositionEventInterface = assign({}, EventInterface, { + data: 0 + }); + var SyntheticCompositionEvent = createSyntheticEvent(CompositionEventInterface); + var SyntheticInputEvent = SyntheticCompositionEvent; + var normalizeKey = { + Esc: "Escape", + Spacebar: " ", + Left: "ArrowLeft", + Up: "ArrowUp", + Right: "ArrowRight", + Down: "ArrowDown", + Del: "Delete", + Win: "OS", + Menu: "ContextMenu", + Apps: "ContextMenu", + Scroll: "ScrollLock", + MozPrintableKey: "Unidentified" + }; + var translateToKey = { + "8": "Backspace", + "9": "Tab", + "12": "Clear", + "13": "Enter", + "16": "Shift", + "17": "Control", + "18": "Alt", + "19": "Pause", + "20": "CapsLock", + "27": "Escape", + "32": " ", + "33": "PageUp", + "34": "PageDown", + "35": "End", + "36": "Home", + "37": "ArrowLeft", + "38": "ArrowUp", + "39": "ArrowRight", + "40": "ArrowDown", + "45": "Insert", + "46": "Delete", + "112": "F1", + "113": "F2", + "114": "F3", + "115": "F4", + "116": "F5", + "117": "F6", + "118": "F7", + "119": "F8", + "120": "F9", + "121": "F10", + "122": "F11", + "123": "F12", + "144": "NumLock", + "145": "ScrollLock", + "224": "Meta" + }; + function getEventKey(nativeEvent) { + if (nativeEvent.key) { + var key = normalizeKey[nativeEvent.key] || nativeEvent.key; + if (key !== "Unidentified") { + return key; + } + } + if (nativeEvent.type === "keypress") { + var charCode = getEventCharCode(nativeEvent); + return charCode === 13 ? "Enter" : String.fromCharCode(charCode); + } + if (nativeEvent.type === "keydown" || nativeEvent.type === "keyup") { + return translateToKey[nativeEvent.keyCode] || "Unidentified"; + } + return ""; + } + var modifierKeyToProp = { + Alt: "altKey", + Control: "ctrlKey", + Meta: "metaKey", + Shift: "shiftKey" + }; + function modifierStateGetter(keyArg) { + var syntheticEvent = this; + var nativeEvent = syntheticEvent.nativeEvent; + if (nativeEvent.getModifierState) { + return nativeEvent.getModifierState(keyArg); + } + var keyProp = modifierKeyToProp[keyArg]; + return keyProp ? !!nativeEvent[keyProp] : false; + } + function getEventModifierState(nativeEvent) { + return modifierStateGetter; + } + var KeyboardEventInterface = assign({}, UIEventInterface, { + key: getEventKey, + code: 0, + location: 0, + ctrlKey: 0, + shiftKey: 0, + altKey: 0, + metaKey: 0, + repeat: 0, + locale: 0, + getModifierState: getEventModifierState, + charCode: function(event) { + if (event.type === "keypress") { + return getEventCharCode(event); + } + return 0; + }, + keyCode: function(event) { + if (event.type === "keydown" || event.type === "keyup") { + return event.keyCode; + } + return 0; + }, + which: function(event) { + if (event.type === "keypress") { + return getEventCharCode(event); + } + if (event.type === "keydown" || event.type === "keyup") { + return event.keyCode; + } + return 0; + } + }); + var SyntheticKeyboardEvent = createSyntheticEvent(KeyboardEventInterface); + var PointerEventInterface = assign({}, MouseEventInterface, { + pointerId: 0, + width: 0, + height: 0, + pressure: 0, + tangentialPressure: 0, + tiltX: 0, + tiltY: 0, + twist: 0, + pointerType: 0, + isPrimary: 0 + }); + var SyntheticPointerEvent = createSyntheticEvent(PointerEventInterface); + var TouchEventInterface = assign({}, UIEventInterface, { + touches: 0, + targetTouches: 0, + changedTouches: 0, + altKey: 0, + metaKey: 0, + ctrlKey: 0, + shiftKey: 0, + getModifierState: getEventModifierState + }); + var SyntheticTouchEvent = createSyntheticEvent(TouchEventInterface); + var TransitionEventInterface = assign({}, EventInterface, { + propertyName: 0, + elapsedTime: 0, + pseudoElement: 0 + }); + var SyntheticTransitionEvent = createSyntheticEvent(TransitionEventInterface); + var WheelEventInterface = assign({}, MouseEventInterface, { + deltaX: function(event) { + return "deltaX" in event ? event.deltaX : ("wheelDeltaX" in event) ? -event.wheelDeltaX : 0; + }, + deltaY: function(event) { + return "deltaY" in event ? event.deltaY : ("wheelDeltaY" in event) ? -event.wheelDeltaY : ("wheelDelta" in event) ? -event.wheelDelta : 0; + }, + deltaZ: 0, + deltaMode: 0 + }); + var SyntheticWheelEvent = createSyntheticEvent(WheelEventInterface); + var END_KEYCODES = [9, 13, 27, 32]; + var START_KEYCODE = 229; + var canUseCompositionEvent = canUseDOM && "CompositionEvent" in window; + var documentMode = null; + if (canUseDOM && "documentMode" in document) { + documentMode = document.documentMode; + } + var canUseTextInputEvent = canUseDOM && "TextEvent" in window && !documentMode; + var useFallbackCompositionData = canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11); + var SPACEBAR_CODE = 32; + var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE); + function registerEvents() { + registerTwoPhaseEvent("onBeforeInput", ["compositionend", "keypress", "textInput", "paste"]); + registerTwoPhaseEvent("onCompositionEnd", ["compositionend", "focusout", "keydown", "keypress", "keyup", "mousedown"]); + registerTwoPhaseEvent("onCompositionStart", ["compositionstart", "focusout", "keydown", "keypress", "keyup", "mousedown"]); + registerTwoPhaseEvent("onCompositionUpdate", ["compositionupdate", "focusout", "keydown", "keypress", "keyup", "mousedown"]); + } + var hasSpaceKeypress = false; + function isKeypressCommand(nativeEvent) { + return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) && !(nativeEvent.ctrlKey && nativeEvent.altKey); + } + function getCompositionEventType(domEventName) { + switch (domEventName) { + case "compositionstart": + return "onCompositionStart"; + case "compositionend": + return "onCompositionEnd"; + case "compositionupdate": + return "onCompositionUpdate"; + } + } + function isFallbackCompositionStart(domEventName, nativeEvent) { + return domEventName === "keydown" && nativeEvent.keyCode === START_KEYCODE; + } + function isFallbackCompositionEnd(domEventName, nativeEvent) { + switch (domEventName) { + case "keyup": + return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1; + case "keydown": + return nativeEvent.keyCode !== START_KEYCODE; + case "keypress": + case "mousedown": + case "focusout": + return true; + default: + return false; + } + } + function getDataFromCustomEvent(nativeEvent) { + var detail = nativeEvent.detail; + if (typeof detail === "object" && "data" in detail) { + return detail.data; + } + return null; + } + function isUsingKoreanIME(nativeEvent) { + return nativeEvent.locale === "ko"; + } + var isComposing = false; + function extractCompositionEvent(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget) { + var eventType; + var fallbackData; + if (canUseCompositionEvent) { + eventType = getCompositionEventType(domEventName); + } else if (!isComposing) { + if (isFallbackCompositionStart(domEventName, nativeEvent)) { + eventType = "onCompositionStart"; + } + } else if (isFallbackCompositionEnd(domEventName, nativeEvent)) { + eventType = "onCompositionEnd"; + } + if (!eventType) { + return null; + } + if (useFallbackCompositionData && !isUsingKoreanIME(nativeEvent)) { + if (!isComposing && eventType === "onCompositionStart") { + isComposing = initialize(nativeEventTarget); + } else if (eventType === "onCompositionEnd") { + if (isComposing) { + fallbackData = getData(); + } + } + } + var listeners = accumulateTwoPhaseListeners(targetInst, eventType); + if (listeners.length > 0) { + var event = new SyntheticCompositionEvent(eventType, domEventName, null, nativeEvent, nativeEventTarget); + dispatchQueue.push({ + event, + listeners + }); + if (fallbackData) { + event.data = fallbackData; + } else { + var customData = getDataFromCustomEvent(nativeEvent); + if (customData !== null) { + event.data = customData; + } + } + } + } + function getNativeBeforeInputChars(domEventName, nativeEvent) { + switch (domEventName) { + case "compositionend": + return getDataFromCustomEvent(nativeEvent); + case "keypress": + var which = nativeEvent.which; + if (which !== SPACEBAR_CODE) { + return null; + } + hasSpaceKeypress = true; + return SPACEBAR_CHAR; + case "textInput": + var chars = nativeEvent.data; + if (chars === SPACEBAR_CHAR && hasSpaceKeypress) { + return null; + } + return chars; + default: + return null; + } + } + function getFallbackBeforeInputChars(domEventName, nativeEvent) { + if (isComposing) { + if (domEventName === "compositionend" || !canUseCompositionEvent && isFallbackCompositionEnd(domEventName, nativeEvent)) { + var chars = getData(); + reset(); + isComposing = false; + return chars; + } + return null; + } + switch (domEventName) { + case "paste": + return null; + case "keypress": + if (!isKeypressCommand(nativeEvent)) { + if (nativeEvent.char && nativeEvent.char.length > 1) { + return nativeEvent.char; + } else if (nativeEvent.which) { + return String.fromCharCode(nativeEvent.which); + } + } + return null; + case "compositionend": + return useFallbackCompositionData && !isUsingKoreanIME(nativeEvent) ? null : nativeEvent.data; + default: + return null; + } + } + function extractBeforeInputEvent(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget) { + var chars; + if (canUseTextInputEvent) { + chars = getNativeBeforeInputChars(domEventName, nativeEvent); + } else { + chars = getFallbackBeforeInputChars(domEventName, nativeEvent); + } + if (!chars) { + return null; + } + var listeners = accumulateTwoPhaseListeners(targetInst, "onBeforeInput"); + if (listeners.length > 0) { + var event = new SyntheticInputEvent("onBeforeInput", "beforeinput", null, nativeEvent, nativeEventTarget); + dispatchQueue.push({ + event, + listeners + }); + event.data = chars; + } + } + function extractEvents(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) { + extractCompositionEvent(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget); + extractBeforeInputEvent(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget); + } + var supportedInputTypes = { + color: true, + date: true, + datetime: true, + "datetime-local": true, + email: true, + month: true, + number: true, + password: true, + range: true, + search: true, + tel: true, + text: true, + time: true, + url: true, + week: true + }; + function isTextInputElement(elem) { + var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase(); + if (nodeName === "input") { + return !!supportedInputTypes[elem.type]; + } + if (nodeName === "textarea") { + return true; + } + return false; + } + function isEventSupported(eventNameSuffix) { + if (!canUseDOM) { + return false; + } + var eventName = "on" + eventNameSuffix; + var isSupported = eventName in document; + if (!isSupported) { + var element = document.createElement("div"); + element.setAttribute(eventName, "return;"); + isSupported = typeof element[eventName] === "function"; + } + return isSupported; + } + function registerEvents$1() { + registerTwoPhaseEvent("onChange", ["change", "click", "focusin", "focusout", "input", "keydown", "keyup", "selectionchange"]); + } + function createAndAccumulateChangeEvent(dispatchQueue, inst, nativeEvent, target) { + enqueueStateRestore(target); + var listeners = accumulateTwoPhaseListeners(inst, "onChange"); + if (listeners.length > 0) { + var event = new SyntheticEvent("onChange", "change", null, nativeEvent, target); + dispatchQueue.push({ + event, + listeners + }); + } + } + var activeElement = null; + var activeElementInst = null; + function shouldUseChangeEvent(elem) { + var nodeName = elem.nodeName && elem.nodeName.toLowerCase(); + return nodeName === "select" || nodeName === "input" && elem.type === "file"; + } + function manualDispatchChangeEvent(nativeEvent) { + var dispatchQueue = []; + createAndAccumulateChangeEvent(dispatchQueue, activeElementInst, nativeEvent, getEventTarget(nativeEvent)); + batchedUpdates(runEventInBatch, dispatchQueue); + } + function runEventInBatch(dispatchQueue) { + processDispatchQueue(dispatchQueue, 0); + } + function getInstIfValueChanged(targetInst) { + var targetNode = getNodeFromInstance(targetInst); + if (updateValueIfChanged(targetNode)) { + return targetInst; + } + } + function getTargetInstForChangeEvent(domEventName, targetInst) { + if (domEventName === "change") { + return targetInst; + } + } + var isInputEventSupported = false; + if (canUseDOM) { + isInputEventSupported = isEventSupported("input") && (!document.documentMode || document.documentMode > 9); + } + function startWatchingForValueChange(target, targetInst) { + activeElement = target; + activeElementInst = targetInst; + activeElement.attachEvent("onpropertychange", handlePropertyChange); + } + function stopWatchingForValueChange() { + if (!activeElement) { + return; + } + activeElement.detachEvent("onpropertychange", handlePropertyChange); + activeElement = null; + activeElementInst = null; + } + function handlePropertyChange(nativeEvent) { + if (nativeEvent.propertyName !== "value") { + return; + } + if (getInstIfValueChanged(activeElementInst)) { + manualDispatchChangeEvent(nativeEvent); + } + } + function handleEventsForInputEventPolyfill(domEventName, target, targetInst) { + if (domEventName === "focusin") { + stopWatchingForValueChange(); + startWatchingForValueChange(target, targetInst); + } else if (domEventName === "focusout") { + stopWatchingForValueChange(); + } + } + function getTargetInstForInputEventPolyfill(domEventName, targetInst) { + if (domEventName === "selectionchange" || domEventName === "keyup" || domEventName === "keydown") { + return getInstIfValueChanged(activeElementInst); + } + } + function shouldUseClickEvent(elem) { + var nodeName = elem.nodeName; + return nodeName && nodeName.toLowerCase() === "input" && (elem.type === "checkbox" || elem.type === "radio"); + } + function getTargetInstForClickEvent(domEventName, targetInst) { + if (domEventName === "click") { + return getInstIfValueChanged(targetInst); + } + } + function getTargetInstForInputOrChangeEvent(domEventName, targetInst) { + if (domEventName === "input" || domEventName === "change") { + return getInstIfValueChanged(targetInst); + } + } + function handleControlledInputBlur(node) { + var state = node._wrapperState; + if (!state || !state.controlled || node.type !== "number") { + return; + } + { + setDefaultValue(node, "number", node.value); + } + } + function extractEvents$1(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) { + var targetNode = targetInst ? getNodeFromInstance(targetInst) : window; + var getTargetInstFunc, handleEventFunc; + if (shouldUseChangeEvent(targetNode)) { + getTargetInstFunc = getTargetInstForChangeEvent; + } else if (isTextInputElement(targetNode)) { + if (isInputEventSupported) { + getTargetInstFunc = getTargetInstForInputOrChangeEvent; + } else { + getTargetInstFunc = getTargetInstForInputEventPolyfill; + handleEventFunc = handleEventsForInputEventPolyfill; + } + } else if (shouldUseClickEvent(targetNode)) { + getTargetInstFunc = getTargetInstForClickEvent; + } + if (getTargetInstFunc) { + var inst = getTargetInstFunc(domEventName, targetInst); + if (inst) { + createAndAccumulateChangeEvent(dispatchQueue, inst, nativeEvent, nativeEventTarget); + return; + } + } + if (handleEventFunc) { + handleEventFunc(domEventName, targetNode, targetInst); + } + if (domEventName === "focusout") { + handleControlledInputBlur(targetNode); + } + } + function registerEvents$2() { + registerDirectEvent("onMouseEnter", ["mouseout", "mouseover"]); + registerDirectEvent("onMouseLeave", ["mouseout", "mouseover"]); + registerDirectEvent("onPointerEnter", ["pointerout", "pointerover"]); + registerDirectEvent("onPointerLeave", ["pointerout", "pointerover"]); + } + function extractEvents$2(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) { + var isOverEvent = domEventName === "mouseover" || domEventName === "pointerover"; + var isOutEvent = domEventName === "mouseout" || domEventName === "pointerout"; + if (isOverEvent && !isReplayingEvent(nativeEvent)) { + var related = nativeEvent.relatedTarget || nativeEvent.fromElement; + if (related) { + if (getClosestInstanceFromNode(related) || isContainerMarkedAsRoot(related)) { + return; + } + } + } + if (!isOutEvent && !isOverEvent) { + return; + } + var win; + if (nativeEventTarget.window === nativeEventTarget) { + win = nativeEventTarget; + } else { + var doc = nativeEventTarget.ownerDocument; + if (doc) { + win = doc.defaultView || doc.parentWindow; + } else { + win = window; + } + } + var from; + var to; + if (isOutEvent) { + var _related = nativeEvent.relatedTarget || nativeEvent.toElement; + from = targetInst; + to = _related ? getClosestInstanceFromNode(_related) : null; + if (to !== null) { + var nearestMounted = getNearestMountedFiber(to); + if (to !== nearestMounted || to.tag !== HostComponent && to.tag !== HostText) { + to = null; + } + } + } else { + from = null; + to = targetInst; + } + if (from === to) { + return; + } + var SyntheticEventCtor = SyntheticMouseEvent; + var leaveEventType = "onMouseLeave"; + var enterEventType = "onMouseEnter"; + var eventTypePrefix = "mouse"; + if (domEventName === "pointerout" || domEventName === "pointerover") { + SyntheticEventCtor = SyntheticPointerEvent; + leaveEventType = "onPointerLeave"; + enterEventType = "onPointerEnter"; + eventTypePrefix = "pointer"; + } + var fromNode = from == null ? win : getNodeFromInstance(from); + var toNode = to == null ? win : getNodeFromInstance(to); + var leave = new SyntheticEventCtor(leaveEventType, eventTypePrefix + "leave", from, nativeEvent, nativeEventTarget); + leave.target = fromNode; + leave.relatedTarget = toNode; + var enter = null; + var nativeTargetInst = getClosestInstanceFromNode(nativeEventTarget); + if (nativeTargetInst === targetInst) { + var enterEvent = new SyntheticEventCtor(enterEventType, eventTypePrefix + "enter", to, nativeEvent, nativeEventTarget); + enterEvent.target = toNode; + enterEvent.relatedTarget = fromNode; + enter = enterEvent; + } + accumulateEnterLeaveTwoPhaseListeners(dispatchQueue, leave, enter, from, to); + } + function is(x, y) { + return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y; + } + var objectIs = typeof Object.is === "function" ? Object.is : is; + 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; + } + 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 getLeafNode(node) { + while (node && node.firstChild) { + node = node.firstChild; + } + return node; + } + function getSiblingNode(node) { + while (node) { + if (node.nextSibling) { + return node.nextSibling; + } + node = node.parentNode; + } + } + function getNodeForCharacterOffset(root2, offset) { + var node = getLeafNode(root2); + var nodeStart = 0; + var nodeEnd = 0; + while (node) { + if (node.nodeType === TEXT_NODE) { + nodeEnd = nodeStart + node.textContent.length; + if (nodeStart <= offset && nodeEnd >= offset) { + return { + node, + offset: offset - nodeStart + }; + } + nodeStart = nodeEnd; + } + node = getLeafNode(getSiblingNode(node)); + } + } + function getOffsets(outerNode) { + var ownerDocument = outerNode.ownerDocument; + var win = ownerDocument && ownerDocument.defaultView || window; + var selection = win.getSelection && win.getSelection(); + if (!selection || selection.rangeCount === 0) { + return null; + } + var { anchorNode, anchorOffset, focusNode, focusOffset } = selection; + try { + anchorNode.nodeType; + focusNode.nodeType; + } catch (e) { + return null; + } + return getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset); + } + function getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset) { + var length = 0; + var start = -1; + var end = -1; + var indexWithinAnchor = 0; + var indexWithinFocus = 0; + var node = outerNode; + var parentNode = null; + outer: + while (true) { + var next = null; + while (true) { + if (node === anchorNode && (anchorOffset === 0 || node.nodeType === TEXT_NODE)) { + start = length + anchorOffset; + } + if (node === focusNode && (focusOffset === 0 || node.nodeType === TEXT_NODE)) { + end = length + focusOffset; + } + if (node.nodeType === TEXT_NODE) { + length += node.nodeValue.length; + } + if ((next = node.firstChild) === null) { + break; + } + parentNode = node; + node = next; + } + while (true) { + if (node === outerNode) { + break outer; + } + if (parentNode === anchorNode && ++indexWithinAnchor === anchorOffset) { + start = length; + } + if (parentNode === focusNode && ++indexWithinFocus === focusOffset) { + end = length; + } + if ((next = node.nextSibling) !== null) { + break; + } + node = parentNode; + parentNode = node.parentNode; + } + node = next; + } + if (start === -1 || end === -1) { + return null; + } + return { + start, + end + }; + } + function setOffsets(node, offsets) { + var doc = node.ownerDocument || document; + var win = doc && doc.defaultView || window; + if (!win.getSelection) { + return; + } + var selection = win.getSelection(); + var length = node.textContent.length; + var start = Math.min(offsets.start, length); + var end = offsets.end === undefined ? start : Math.min(offsets.end, length); + if (!selection.extend && start > end) { + var temp = end; + end = start; + start = temp; + } + var startMarker = getNodeForCharacterOffset(node, start); + var endMarker = getNodeForCharacterOffset(node, end); + if (startMarker && endMarker) { + if (selection.rangeCount === 1 && selection.anchorNode === startMarker.node && selection.anchorOffset === startMarker.offset && selection.focusNode === endMarker.node && selection.focusOffset === endMarker.offset) { + return; + } + var range = doc.createRange(); + range.setStart(startMarker.node, startMarker.offset); + selection.removeAllRanges(); + if (start > end) { + selection.addRange(range); + selection.extend(endMarker.node, endMarker.offset); + } else { + range.setEnd(endMarker.node, endMarker.offset); + selection.addRange(range); + } + } + } + function isTextNode(node) { + return node && node.nodeType === TEXT_NODE; + } + function containsNode(outerNode, innerNode) { + if (!outerNode || !innerNode) { + return false; + } else if (outerNode === innerNode) { + return true; + } else if (isTextNode(outerNode)) { + return false; + } else if (isTextNode(innerNode)) { + return containsNode(outerNode, innerNode.parentNode); + } else if ("contains" in outerNode) { + return outerNode.contains(innerNode); + } else if (outerNode.compareDocumentPosition) { + return !!(outerNode.compareDocumentPosition(innerNode) & 16); + } else { + return false; + } + } + function isInDocument(node) { + return node && node.ownerDocument && containsNode(node.ownerDocument.documentElement, node); + } + function isSameOriginFrame(iframe) { + try { + return typeof iframe.contentWindow.location.href === "string"; + } catch (err) { + return false; + } + } + function getActiveElementDeep() { + var win = window; + var element = getActiveElement(); + while (element instanceof win.HTMLIFrameElement) { + if (isSameOriginFrame(element)) { + win = element.contentWindow; + } else { + return element; + } + element = getActiveElement(win.document); + } + return element; + } + function hasSelectionCapabilities(elem) { + var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase(); + return nodeName && (nodeName === "input" && (elem.type === "text" || elem.type === "search" || elem.type === "tel" || elem.type === "url" || elem.type === "password") || nodeName === "textarea" || elem.contentEditable === "true"); + } + function getSelectionInformation() { + var focusedElem = getActiveElementDeep(); + return { + focusedElem, + selectionRange: hasSelectionCapabilities(focusedElem) ? getSelection(focusedElem) : null + }; + } + function restoreSelection(priorSelectionInformation) { + var curFocusedElem = getActiveElementDeep(); + var priorFocusedElem = priorSelectionInformation.focusedElem; + var priorSelectionRange = priorSelectionInformation.selectionRange; + if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) { + if (priorSelectionRange !== null && hasSelectionCapabilities(priorFocusedElem)) { + setSelection(priorFocusedElem, priorSelectionRange); + } + var ancestors = []; + var ancestor = priorFocusedElem; + while (ancestor = ancestor.parentNode) { + if (ancestor.nodeType === ELEMENT_NODE) { + ancestors.push({ + element: ancestor, + left: ancestor.scrollLeft, + top: ancestor.scrollTop + }); + } + } + if (typeof priorFocusedElem.focus === "function") { + priorFocusedElem.focus(); + } + for (var i = 0;i < ancestors.length; i++) { + var info = ancestors[i]; + info.element.scrollLeft = info.left; + info.element.scrollTop = info.top; + } + } + } + function getSelection(input) { + var selection; + if ("selectionStart" in input) { + selection = { + start: input.selectionStart, + end: input.selectionEnd + }; + } else { + selection = getOffsets(input); + } + return selection || { + start: 0, + end: 0 + }; + } + function setSelection(input, offsets) { + var start = offsets.start; + var end = offsets.end; + if (end === undefined) { + end = start; + } + if ("selectionStart" in input) { + input.selectionStart = start; + input.selectionEnd = Math.min(end, input.value.length); + } else { + setOffsets(input, offsets); + } + } + var skipSelectionChangeEvent = canUseDOM && "documentMode" in document && document.documentMode <= 11; + function registerEvents$3() { + registerTwoPhaseEvent("onSelect", ["focusout", "contextmenu", "dragend", "focusin", "keydown", "keyup", "mousedown", "mouseup", "selectionchange"]); + } + var activeElement$1 = null; + var activeElementInst$1 = null; + var lastSelection = null; + var mouseDown = false; + function getSelection$1(node) { + if ("selectionStart" in node && hasSelectionCapabilities(node)) { + return { + start: node.selectionStart, + end: node.selectionEnd + }; + } else { + var win = node.ownerDocument && node.ownerDocument.defaultView || window; + var selection = win.getSelection(); + return { + anchorNode: selection.anchorNode, + anchorOffset: selection.anchorOffset, + focusNode: selection.focusNode, + focusOffset: selection.focusOffset + }; + } + } + function getEventTargetDocument(eventTarget) { + return eventTarget.window === eventTarget ? eventTarget.document : eventTarget.nodeType === DOCUMENT_NODE ? eventTarget : eventTarget.ownerDocument; + } + function constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget) { + var doc = getEventTargetDocument(nativeEventTarget); + if (mouseDown || activeElement$1 == null || activeElement$1 !== getActiveElement(doc)) { + return; + } + var currentSelection = getSelection$1(activeElement$1); + if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) { + lastSelection = currentSelection; + var listeners = accumulateTwoPhaseListeners(activeElementInst$1, "onSelect"); + if (listeners.length > 0) { + var event = new SyntheticEvent("onSelect", "select", null, nativeEvent, nativeEventTarget); + dispatchQueue.push({ + event, + listeners + }); + event.target = activeElement$1; + } + } + } + function extractEvents$3(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) { + var targetNode = targetInst ? getNodeFromInstance(targetInst) : window; + switch (domEventName) { + case "focusin": + if (isTextInputElement(targetNode) || targetNode.contentEditable === "true") { + activeElement$1 = targetNode; + activeElementInst$1 = targetInst; + lastSelection = null; + } + break; + case "focusout": + activeElement$1 = null; + activeElementInst$1 = null; + lastSelection = null; + break; + case "mousedown": + mouseDown = true; + break; + case "contextmenu": + case "mouseup": + case "dragend": + mouseDown = false; + constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget); + break; + case "selectionchange": + if (skipSelectionChangeEvent) { + break; + } + case "keydown": + case "keyup": + constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget); + } + } + function makePrefixMap(styleProp, eventName) { + var prefixes2 = {}; + prefixes2[styleProp.toLowerCase()] = eventName.toLowerCase(); + prefixes2["Webkit" + styleProp] = "webkit" + eventName; + prefixes2["Moz" + styleProp] = "moz" + eventName; + return prefixes2; + } + var vendorPrefixes = { + animationend: makePrefixMap("Animation", "AnimationEnd"), + animationiteration: makePrefixMap("Animation", "AnimationIteration"), + animationstart: makePrefixMap("Animation", "AnimationStart"), + transitionend: makePrefixMap("Transition", "TransitionEnd") + }; + var prefixedEventNames = {}; + var style = {}; + if (canUseDOM) { + style = document.createElement("div").style; + if (!("AnimationEvent" in window)) { + delete vendorPrefixes.animationend.animation; + delete vendorPrefixes.animationiteration.animation; + delete vendorPrefixes.animationstart.animation; + } + if (!("TransitionEvent" in window)) { + delete vendorPrefixes.transitionend.transition; + } + } + function getVendorPrefixedEventName(eventName) { + if (prefixedEventNames[eventName]) { + return prefixedEventNames[eventName]; + } else if (!vendorPrefixes[eventName]) { + return eventName; + } + var prefixMap = vendorPrefixes[eventName]; + for (var styleProp in prefixMap) { + if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) { + return prefixedEventNames[eventName] = prefixMap[styleProp]; + } + } + return eventName; + } + var ANIMATION_END = getVendorPrefixedEventName("animationend"); + var ANIMATION_ITERATION = getVendorPrefixedEventName("animationiteration"); + var ANIMATION_START = getVendorPrefixedEventName("animationstart"); + var TRANSITION_END = getVendorPrefixedEventName("transitionend"); + var topLevelEventsToReactNames = new Map; + var simpleEventPluginEvents = ["abort", "auxClick", "cancel", "canPlay", "canPlayThrough", "click", "close", "contextMenu", "copy", "cut", "drag", "dragEnd", "dragEnter", "dragExit", "dragLeave", "dragOver", "dragStart", "drop", "durationChange", "emptied", "encrypted", "ended", "error", "gotPointerCapture", "input", "invalid", "keyDown", "keyPress", "keyUp", "load", "loadedData", "loadedMetadata", "loadStart", "lostPointerCapture", "mouseDown", "mouseMove", "mouseOut", "mouseOver", "mouseUp", "paste", "pause", "play", "playing", "pointerCancel", "pointerDown", "pointerMove", "pointerOut", "pointerOver", "pointerUp", "progress", "rateChange", "reset", "resize", "seeked", "seeking", "stalled", "submit", "suspend", "timeUpdate", "touchCancel", "touchEnd", "touchStart", "volumeChange", "scroll", "toggle", "touchMove", "waiting", "wheel"]; + function registerSimpleEvent(domEventName, reactName) { + topLevelEventsToReactNames.set(domEventName, reactName); + registerTwoPhaseEvent(reactName, [domEventName]); + } + function registerSimpleEvents() { + for (var i = 0;i < simpleEventPluginEvents.length; i++) { + var eventName = simpleEventPluginEvents[i]; + var domEventName = eventName.toLowerCase(); + var capitalizedEvent = eventName[0].toUpperCase() + eventName.slice(1); + registerSimpleEvent(domEventName, "on" + capitalizedEvent); + } + registerSimpleEvent(ANIMATION_END, "onAnimationEnd"); + registerSimpleEvent(ANIMATION_ITERATION, "onAnimationIteration"); + registerSimpleEvent(ANIMATION_START, "onAnimationStart"); + registerSimpleEvent("dblclick", "onDoubleClick"); + registerSimpleEvent("focusin", "onFocus"); + registerSimpleEvent("focusout", "onBlur"); + registerSimpleEvent(TRANSITION_END, "onTransitionEnd"); + } + function extractEvents$4(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) { + var reactName = topLevelEventsToReactNames.get(domEventName); + if (reactName === undefined) { + return; + } + var SyntheticEventCtor = SyntheticEvent; + var reactEventType = domEventName; + switch (domEventName) { + case "keypress": + if (getEventCharCode(nativeEvent) === 0) { + return; + } + case "keydown": + case "keyup": + SyntheticEventCtor = SyntheticKeyboardEvent; + break; + case "focusin": + reactEventType = "focus"; + SyntheticEventCtor = SyntheticFocusEvent; + break; + case "focusout": + reactEventType = "blur"; + SyntheticEventCtor = SyntheticFocusEvent; + break; + case "beforeblur": + case "afterblur": + SyntheticEventCtor = SyntheticFocusEvent; + break; + case "click": + if (nativeEvent.button === 2) { + return; + } + case "auxclick": + case "dblclick": + case "mousedown": + case "mousemove": + case "mouseup": + case "mouseout": + case "mouseover": + case "contextmenu": + SyntheticEventCtor = SyntheticMouseEvent; + break; + case "drag": + case "dragend": + case "dragenter": + case "dragexit": + case "dragleave": + case "dragover": + case "dragstart": + case "drop": + SyntheticEventCtor = SyntheticDragEvent; + break; + case "touchcancel": + case "touchend": + case "touchmove": + case "touchstart": + SyntheticEventCtor = SyntheticTouchEvent; + break; + case ANIMATION_END: + case ANIMATION_ITERATION: + case ANIMATION_START: + SyntheticEventCtor = SyntheticAnimationEvent; + break; + case TRANSITION_END: + SyntheticEventCtor = SyntheticTransitionEvent; + break; + case "scroll": + SyntheticEventCtor = SyntheticUIEvent; + break; + case "wheel": + SyntheticEventCtor = SyntheticWheelEvent; + break; + case "copy": + case "cut": + case "paste": + SyntheticEventCtor = SyntheticClipboardEvent; + break; + case "gotpointercapture": + case "lostpointercapture": + case "pointercancel": + case "pointerdown": + case "pointermove": + case "pointerout": + case "pointerover": + case "pointerup": + SyntheticEventCtor = SyntheticPointerEvent; + break; + } + var inCapturePhase = (eventSystemFlags & IS_CAPTURE_PHASE) !== 0; + { + var accumulateTargetOnly = !inCapturePhase && domEventName === "scroll"; + var _listeners = accumulateSinglePhaseListeners(targetInst, reactName, nativeEvent.type, inCapturePhase, accumulateTargetOnly); + if (_listeners.length > 0) { + var _event = new SyntheticEventCtor(reactName, reactEventType, null, nativeEvent, nativeEventTarget); + dispatchQueue.push({ + event: _event, + listeners: _listeners + }); + } + } + } + registerSimpleEvents(); + registerEvents$2(); + registerEvents$1(); + registerEvents$3(); + registerEvents(); + function extractEvents$5(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) { + extractEvents$4(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags); + var shouldProcessPolyfillPlugins = (eventSystemFlags & SHOULD_NOT_PROCESS_POLYFILL_EVENT_PLUGINS) === 0; + if (shouldProcessPolyfillPlugins) { + extractEvents$2(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget); + extractEvents$1(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget); + extractEvents$3(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget); + extractEvents(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget); + } + } + var mediaEventTypes = ["abort", "canplay", "canplaythrough", "durationchange", "emptied", "encrypted", "ended", "error", "loadeddata", "loadedmetadata", "loadstart", "pause", "play", "playing", "progress", "ratechange", "resize", "seeked", "seeking", "stalled", "suspend", "timeupdate", "volumechange", "waiting"]; + var nonDelegatedEvents = new Set(["cancel", "close", "invalid", "load", "scroll", "toggle"].concat(mediaEventTypes)); + function executeDispatch(event, listener, currentTarget) { + var type = event.type || "unknown-event"; + event.currentTarget = currentTarget; + invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event); + event.currentTarget = null; + } + function processDispatchQueueItemsInOrder(event, dispatchListeners, inCapturePhase) { + var previousInstance; + if (inCapturePhase) { + for (var i = dispatchListeners.length - 1;i >= 0; i--) { + var _dispatchListeners$i = dispatchListeners[i], instance = _dispatchListeners$i.instance, currentTarget = _dispatchListeners$i.currentTarget, listener = _dispatchListeners$i.listener; + if (instance !== previousInstance && event.isPropagationStopped()) { + return; + } + executeDispatch(event, listener, currentTarget); + previousInstance = instance; + } + } else { + for (var _i = 0;_i < dispatchListeners.length; _i++) { + var _dispatchListeners$_i = dispatchListeners[_i], _instance = _dispatchListeners$_i.instance, _currentTarget = _dispatchListeners$_i.currentTarget, _listener = _dispatchListeners$_i.listener; + if (_instance !== previousInstance && event.isPropagationStopped()) { + return; + } + executeDispatch(event, _listener, _currentTarget); + previousInstance = _instance; + } + } + } + function processDispatchQueue(dispatchQueue, eventSystemFlags) { + var inCapturePhase = (eventSystemFlags & IS_CAPTURE_PHASE) !== 0; + for (var i = 0;i < dispatchQueue.length; i++) { + var _dispatchQueue$i = dispatchQueue[i], event = _dispatchQueue$i.event, listeners = _dispatchQueue$i.listeners; + processDispatchQueueItemsInOrder(event, listeners, inCapturePhase); + } + rethrowCaughtError(); + } + function dispatchEventsForPlugins(domEventName, eventSystemFlags, nativeEvent, targetInst, targetContainer) { + var nativeEventTarget = getEventTarget(nativeEvent); + var dispatchQueue = []; + extractEvents$5(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags); + processDispatchQueue(dispatchQueue, eventSystemFlags); + } + function listenToNonDelegatedEvent(domEventName, targetElement) { + { + if (!nonDelegatedEvents.has(domEventName)) { + error('Did not expect a listenToNonDelegatedEvent() call for "%s". This is a bug in React. Please file an issue.', domEventName); + } + } + var isCapturePhaseListener = false; + var listenerSet = getEventListenerSet(targetElement); + var listenerSetKey = getListenerSetKey(domEventName, isCapturePhaseListener); + if (!listenerSet.has(listenerSetKey)) { + addTrappedEventListener(targetElement, domEventName, IS_NON_DELEGATED, isCapturePhaseListener); + listenerSet.add(listenerSetKey); + } + } + function listenToNativeEvent(domEventName, isCapturePhaseListener, target) { + { + if (nonDelegatedEvents.has(domEventName) && !isCapturePhaseListener) { + error('Did not expect a listenToNativeEvent() call for "%s" in the bubble phase. This is a bug in React. Please file an issue.', domEventName); + } + } + var eventSystemFlags = 0; + if (isCapturePhaseListener) { + eventSystemFlags |= IS_CAPTURE_PHASE; + } + addTrappedEventListener(target, domEventName, eventSystemFlags, isCapturePhaseListener); + } + var listeningMarker = "_reactListening" + Math.random().toString(36).slice(2); + function listenToAllSupportedEvents(rootContainerElement) { + if (!rootContainerElement[listeningMarker]) { + rootContainerElement[listeningMarker] = true; + allNativeEvents.forEach(function(domEventName) { + if (domEventName !== "selectionchange") { + if (!nonDelegatedEvents.has(domEventName)) { + listenToNativeEvent(domEventName, false, rootContainerElement); + } + listenToNativeEvent(domEventName, true, rootContainerElement); + } + }); + var ownerDocument = rootContainerElement.nodeType === DOCUMENT_NODE ? rootContainerElement : rootContainerElement.ownerDocument; + if (ownerDocument !== null) { + if (!ownerDocument[listeningMarker]) { + ownerDocument[listeningMarker] = true; + listenToNativeEvent("selectionchange", false, ownerDocument); + } + } + } + } + function addTrappedEventListener(targetContainer, domEventName, eventSystemFlags, isCapturePhaseListener, isDeferredListenerForLegacyFBSupport) { + var listener = createEventListenerWrapperWithPriority(targetContainer, domEventName, eventSystemFlags); + var isPassiveListener = undefined; + if (passiveBrowserEventsSupported) { + if (domEventName === "touchstart" || domEventName === "touchmove" || domEventName === "wheel") { + isPassiveListener = true; + } + } + targetContainer = targetContainer; + var unsubscribeListener; + if (isCapturePhaseListener) { + if (isPassiveListener !== undefined) { + unsubscribeListener = addEventCaptureListenerWithPassiveFlag(targetContainer, domEventName, listener, isPassiveListener); + } else { + unsubscribeListener = addEventCaptureListener(targetContainer, domEventName, listener); + } + } else { + if (isPassiveListener !== undefined) { + unsubscribeListener = addEventBubbleListenerWithPassiveFlag(targetContainer, domEventName, listener, isPassiveListener); + } else { + unsubscribeListener = addEventBubbleListener(targetContainer, domEventName, listener); + } + } + } + function isMatchingRootContainer(grandContainer, targetContainer) { + return grandContainer === targetContainer || grandContainer.nodeType === COMMENT_NODE && grandContainer.parentNode === targetContainer; + } + function dispatchEventForPluginEventSystem(domEventName, eventSystemFlags, nativeEvent, targetInst, targetContainer) { + var ancestorInst = targetInst; + if ((eventSystemFlags & IS_EVENT_HANDLE_NON_MANAGED_NODE) === 0 && (eventSystemFlags & IS_NON_DELEGATED) === 0) { + var targetContainerNode = targetContainer; + if (targetInst !== null) { + var node = targetInst; + mainLoop: + while (true) { + if (node === null) { + return; + } + var nodeTag = node.tag; + if (nodeTag === HostRoot || nodeTag === HostPortal) { + var container = node.stateNode.containerInfo; + if (isMatchingRootContainer(container, targetContainerNode)) { + break; + } + if (nodeTag === HostPortal) { + var grandNode = node.return; + while (grandNode !== null) { + var grandTag = grandNode.tag; + if (grandTag === HostRoot || grandTag === HostPortal) { + var grandContainer = grandNode.stateNode.containerInfo; + if (isMatchingRootContainer(grandContainer, targetContainerNode)) { + return; + } + } + grandNode = grandNode.return; + } + } + while (container !== null) { + var parentNode = getClosestInstanceFromNode(container); + if (parentNode === null) { + return; + } + var parentTag = parentNode.tag; + if (parentTag === HostComponent || parentTag === HostText) { + node = ancestorInst = parentNode; + continue mainLoop; + } + container = container.parentNode; + } + } + node = node.return; + } + } + } + batchedUpdates(function() { + return dispatchEventsForPlugins(domEventName, eventSystemFlags, nativeEvent, ancestorInst); + }); + } + function createDispatchListener(instance, listener, currentTarget) { + return { + instance, + listener, + currentTarget + }; + } + function accumulateSinglePhaseListeners(targetFiber, reactName, nativeEventType, inCapturePhase, accumulateTargetOnly, nativeEvent) { + var captureName = reactName !== null ? reactName + "Capture" : null; + var reactEventName = inCapturePhase ? captureName : reactName; + var listeners = []; + var instance = targetFiber; + var lastHostComponent = null; + while (instance !== null) { + var _instance2 = instance, stateNode = _instance2.stateNode, tag = _instance2.tag; + if (tag === HostComponent && stateNode !== null) { + lastHostComponent = stateNode; + if (reactEventName !== null) { + var listener = getListener(instance, reactEventName); + if (listener != null) { + listeners.push(createDispatchListener(instance, listener, lastHostComponent)); + } + } + } + if (accumulateTargetOnly) { + break; + } + instance = instance.return; + } + return listeners; + } + function accumulateTwoPhaseListeners(targetFiber, reactName) { + var captureName = reactName + "Capture"; + var listeners = []; + var instance = targetFiber; + while (instance !== null) { + var _instance3 = instance, stateNode = _instance3.stateNode, tag = _instance3.tag; + if (tag === HostComponent && stateNode !== null) { + var currentTarget = stateNode; + var captureListener = getListener(instance, captureName); + if (captureListener != null) { + listeners.unshift(createDispatchListener(instance, captureListener, currentTarget)); + } + var bubbleListener = getListener(instance, reactName); + if (bubbleListener != null) { + listeners.push(createDispatchListener(instance, bubbleListener, currentTarget)); + } + } + instance = instance.return; + } + return listeners; + } + function getParent(inst) { + if (inst === null) { + return null; + } + do { + inst = inst.return; + } while (inst && inst.tag !== HostComponent); + if (inst) { + return inst; + } + return null; + } + function getLowestCommonAncestor(instA, instB) { + var nodeA = instA; + var nodeB = instB; + var depthA = 0; + for (var tempA = nodeA;tempA; tempA = getParent(tempA)) { + depthA++; + } + var depthB = 0; + for (var tempB = nodeB;tempB; tempB = getParent(tempB)) { + depthB++; + } + while (depthA - depthB > 0) { + nodeA = getParent(nodeA); + depthA--; + } + while (depthB - depthA > 0) { + nodeB = getParent(nodeB); + depthB--; + } + var depth = depthA; + while (depth--) { + if (nodeA === nodeB || nodeB !== null && nodeA === nodeB.alternate) { + return nodeA; + } + nodeA = getParent(nodeA); + nodeB = getParent(nodeB); + } + return null; + } + function accumulateEnterLeaveListenersForEvent(dispatchQueue, event, target, common, inCapturePhase) { + var registrationName = event._reactName; + var listeners = []; + var instance = target; + while (instance !== null) { + if (instance === common) { + break; + } + var _instance4 = instance, alternate = _instance4.alternate, stateNode = _instance4.stateNode, tag = _instance4.tag; + if (alternate !== null && alternate === common) { + break; + } + if (tag === HostComponent && stateNode !== null) { + var currentTarget = stateNode; + if (inCapturePhase) { + var captureListener = getListener(instance, registrationName); + if (captureListener != null) { + listeners.unshift(createDispatchListener(instance, captureListener, currentTarget)); + } + } else if (!inCapturePhase) { + var bubbleListener = getListener(instance, registrationName); + if (bubbleListener != null) { + listeners.push(createDispatchListener(instance, bubbleListener, currentTarget)); + } + } + } + instance = instance.return; + } + if (listeners.length !== 0) { + dispatchQueue.push({ + event, + listeners + }); + } + } + function accumulateEnterLeaveTwoPhaseListeners(dispatchQueue, leaveEvent, enterEvent, from, to) { + var common = from && to ? getLowestCommonAncestor(from, to) : null; + if (from !== null) { + accumulateEnterLeaveListenersForEvent(dispatchQueue, leaveEvent, from, common, false); + } + if (to !== null && enterEvent !== null) { + accumulateEnterLeaveListenersForEvent(dispatchQueue, enterEvent, to, common, true); + } + } + function getListenerSetKey(domEventName, capture) { + return domEventName + "__" + (capture ? "capture" : "bubble"); + } + var didWarnInvalidHydration = false; + var DANGEROUSLY_SET_INNER_HTML = "dangerouslySetInnerHTML"; + var SUPPRESS_CONTENT_EDITABLE_WARNING = "suppressContentEditableWarning"; + var SUPPRESS_HYDRATION_WARNING = "suppressHydrationWarning"; + var AUTOFOCUS = "autoFocus"; + var CHILDREN = "children"; + var STYLE = "style"; + var HTML$1 = "__html"; + var warnedUnknownTags; + var validatePropertiesInDevelopment; + var warnForPropDifference; + var warnForExtraAttributes; + var warnForInvalidEventListener; + var canDiffStyleForHydrationWarning; + var normalizeHTML; + { + warnedUnknownTags = { + dialog: true, + webview: true + }; + validatePropertiesInDevelopment = function(type, props) { + validateProperties(type, props); + validateProperties$1(type, props); + validateProperties$2(type, props, { + registrationNameDependencies, + possibleRegistrationNames + }); + }; + canDiffStyleForHydrationWarning = canUseDOM && !document.documentMode; + warnForPropDifference = function(propName, serverValue, clientValue) { + if (didWarnInvalidHydration) { + return; + } + var normalizedClientValue = normalizeMarkupForTextOrAttribute(clientValue); + var normalizedServerValue = normalizeMarkupForTextOrAttribute(serverValue); + if (normalizedServerValue === normalizedClientValue) { + return; + } + didWarnInvalidHydration = true; + error("Prop `%s` did not match. Server: %s Client: %s", propName, JSON.stringify(normalizedServerValue), JSON.stringify(normalizedClientValue)); + }; + warnForExtraAttributes = function(attributeNames) { + if (didWarnInvalidHydration) { + return; + } + didWarnInvalidHydration = true; + var names = []; + attributeNames.forEach(function(name) { + names.push(name); + }); + error("Extra attributes from the server: %s", names); + }; + warnForInvalidEventListener = function(registrationName, listener) { + if (listener === false) { + error("Expected `%s` listener to be a function, instead got `false`.\n\nIf you used to conditionally omit it with %s={condition && value}, pass %s={condition ? value : undefined} instead.", registrationName, registrationName, registrationName); + } else { + error("Expected `%s` listener to be a function, instead got a value of `%s` type.", registrationName, typeof listener); + } + }; + normalizeHTML = function(parent, html) { + var testElement = parent.namespaceURI === HTML_NAMESPACE ? parent.ownerDocument.createElement(parent.tagName) : parent.ownerDocument.createElementNS(parent.namespaceURI, parent.tagName); + testElement.innerHTML = html; + return testElement.innerHTML; + }; + } + var NORMALIZE_NEWLINES_REGEX = /\r\n?/g; + var NORMALIZE_NULL_AND_REPLACEMENT_REGEX = /\u0000|\uFFFD/g; + function normalizeMarkupForTextOrAttribute(markup) { + { + checkHtmlStringCoercion(markup); + } + var markupString = typeof markup === "string" ? markup : "" + markup; + return markupString.replace(NORMALIZE_NEWLINES_REGEX, "\n").replace(NORMALIZE_NULL_AND_REPLACEMENT_REGEX, ""); + } + function checkForUnmatchedText(serverText, clientText, isConcurrentMode, shouldWarnDev) { + var normalizedClientText = normalizeMarkupForTextOrAttribute(clientText); + var normalizedServerText = normalizeMarkupForTextOrAttribute(serverText); + if (normalizedServerText === normalizedClientText) { + return; + } + if (shouldWarnDev) { + { + if (!didWarnInvalidHydration) { + didWarnInvalidHydration = true; + error('Text content did not match. Server: "%s" Client: "%s"', normalizedServerText, normalizedClientText); + } + } + } + if (isConcurrentMode && enableClientRenderFallbackOnTextMismatch) { + throw new Error("Text content does not match server-rendered HTML."); + } + } + function getOwnerDocumentFromRootContainer(rootContainerElement) { + return rootContainerElement.nodeType === DOCUMENT_NODE ? rootContainerElement : rootContainerElement.ownerDocument; + } + function noop() { + } + function trapClickOnNonInteractiveElement(node) { + node.onclick = noop; + } + function setInitialDOMProperties(tag, domElement, rootContainerElement, nextProps, isCustomComponentTag) { + for (var propKey in nextProps) { + if (!nextProps.hasOwnProperty(propKey)) { + continue; + } + var nextProp = nextProps[propKey]; + if (propKey === STYLE) { + { + if (nextProp) { + Object.freeze(nextProp); + } + } + setValueForStyles(domElement, nextProp); + } else if (propKey === DANGEROUSLY_SET_INNER_HTML) { + var nextHtml = nextProp ? nextProp[HTML$1] : undefined; + if (nextHtml != null) { + setInnerHTML(domElement, nextHtml); + } + } else if (propKey === CHILDREN) { + if (typeof nextProp === "string") { + var canSetTextContent = tag !== "textarea" || nextProp !== ""; + if (canSetTextContent) { + setTextContent(domElement, nextProp); + } + } else if (typeof nextProp === "number") { + setTextContent(domElement, "" + nextProp); + } + } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING) + ; + else if (propKey === AUTOFOCUS) + ; + else if (registrationNameDependencies.hasOwnProperty(propKey)) { + if (nextProp != null) { + if (typeof nextProp !== "function") { + warnForInvalidEventListener(propKey, nextProp); + } + if (propKey === "onScroll") { + listenToNonDelegatedEvent("scroll", domElement); + } + } + } else if (nextProp != null) { + setValueForProperty(domElement, propKey, nextProp, isCustomComponentTag); + } + } + } + function updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag) { + for (var i = 0;i < updatePayload.length; i += 2) { + var propKey = updatePayload[i]; + var propValue = updatePayload[i + 1]; + if (propKey === STYLE) { + setValueForStyles(domElement, propValue); + } else if (propKey === DANGEROUSLY_SET_INNER_HTML) { + setInnerHTML(domElement, propValue); + } else if (propKey === CHILDREN) { + setTextContent(domElement, propValue); + } else { + setValueForProperty(domElement, propKey, propValue, isCustomComponentTag); + } + } + } + function createElement(type, props, rootContainerElement, parentNamespace) { + var isCustomComponentTag; + var ownerDocument = getOwnerDocumentFromRootContainer(rootContainerElement); + var domElement; + var namespaceURI = parentNamespace; + if (namespaceURI === HTML_NAMESPACE) { + namespaceURI = getIntrinsicNamespace(type); + } + if (namespaceURI === HTML_NAMESPACE) { + { + isCustomComponentTag = isCustomComponent(type, props); + if (!isCustomComponentTag && type !== type.toLowerCase()) { + error("<%s /> is using incorrect casing. Use PascalCase for React components, or lowercase for HTML elements.", type); + } + } + if (type === "script") { + var div = ownerDocument.createElement("div"); + div.innerHTML = "<script></script>"; + var firstChild = div.firstChild; + domElement = div.removeChild(firstChild); + } else if (typeof props.is === "string") { + domElement = ownerDocument.createElement(type, { + is: props.is + }); + } else { + domElement = ownerDocument.createElement(type); + if (type === "select") { + var node = domElement; + if (props.multiple) { + node.multiple = true; + } else if (props.size) { + node.size = props.size; + } + } + } + } else { + domElement = ownerDocument.createElementNS(namespaceURI, type); + } + { + if (namespaceURI === HTML_NAMESPACE) { + if (!isCustomComponentTag && Object.prototype.toString.call(domElement) === "[object HTMLUnknownElement]" && !hasOwnProperty.call(warnedUnknownTags, type)) { + warnedUnknownTags[type] = true; + error("The tag <%s> is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter.", type); + } + } + } + return domElement; + } + function createTextNode(text, rootContainerElement) { + return getOwnerDocumentFromRootContainer(rootContainerElement).createTextNode(text); + } + function setInitialProperties(domElement, tag, rawProps, rootContainerElement) { + var isCustomComponentTag = isCustomComponent(tag, rawProps); + { + validatePropertiesInDevelopment(tag, rawProps); + } + var props; + switch (tag) { + case "dialog": + listenToNonDelegatedEvent("cancel", domElement); + listenToNonDelegatedEvent("close", domElement); + props = rawProps; + break; + case "iframe": + case "object": + case "embed": + listenToNonDelegatedEvent("load", domElement); + props = rawProps; + break; + case "video": + case "audio": + for (var i = 0;i < mediaEventTypes.length; i++) { + listenToNonDelegatedEvent(mediaEventTypes[i], domElement); + } + props = rawProps; + break; + case "source": + listenToNonDelegatedEvent("error", domElement); + props = rawProps; + break; + case "img": + case "image": + case "link": + listenToNonDelegatedEvent("error", domElement); + listenToNonDelegatedEvent("load", domElement); + props = rawProps; + break; + case "details": + listenToNonDelegatedEvent("toggle", domElement); + props = rawProps; + break; + case "input": + initWrapperState(domElement, rawProps); + props = getHostProps(domElement, rawProps); + listenToNonDelegatedEvent("invalid", domElement); + break; + case "option": + validateProps(domElement, rawProps); + props = rawProps; + break; + case "select": + initWrapperState$1(domElement, rawProps); + props = getHostProps$1(domElement, rawProps); + listenToNonDelegatedEvent("invalid", domElement); + break; + case "textarea": + initWrapperState$2(domElement, rawProps); + props = getHostProps$2(domElement, rawProps); + listenToNonDelegatedEvent("invalid", domElement); + break; + default: + props = rawProps; + } + assertValidProps(tag, props); + setInitialDOMProperties(tag, domElement, rootContainerElement, props, isCustomComponentTag); + switch (tag) { + case "input": + track(domElement); + postMountWrapper(domElement, rawProps, false); + break; + case "textarea": + track(domElement); + postMountWrapper$3(domElement); + break; + case "option": + postMountWrapper$1(domElement, rawProps); + break; + case "select": + postMountWrapper$2(domElement, rawProps); + break; + default: + if (typeof props.onClick === "function") { + trapClickOnNonInteractiveElement(domElement); + } + break; + } + } + function diffProperties(domElement, tag, lastRawProps, nextRawProps, rootContainerElement) { + { + validatePropertiesInDevelopment(tag, nextRawProps); + } + var updatePayload = null; + var lastProps; + var nextProps; + switch (tag) { + case "input": + lastProps = getHostProps(domElement, lastRawProps); + nextProps = getHostProps(domElement, nextRawProps); + updatePayload = []; + break; + case "select": + lastProps = getHostProps$1(domElement, lastRawProps); + nextProps = getHostProps$1(domElement, nextRawProps); + updatePayload = []; + break; + case "textarea": + lastProps = getHostProps$2(domElement, lastRawProps); + nextProps = getHostProps$2(domElement, nextRawProps); + updatePayload = []; + break; + default: + lastProps = lastRawProps; + nextProps = nextRawProps; + if (typeof lastProps.onClick !== "function" && typeof nextProps.onClick === "function") { + trapClickOnNonInteractiveElement(domElement); + } + break; + } + assertValidProps(tag, nextProps); + var propKey; + var styleName; + var styleUpdates = null; + for (propKey in lastProps) { + if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey) || lastProps[propKey] == null) { + continue; + } + if (propKey === STYLE) { + var lastStyle = lastProps[propKey]; + for (styleName in lastStyle) { + if (lastStyle.hasOwnProperty(styleName)) { + if (!styleUpdates) { + styleUpdates = {}; + } + styleUpdates[styleName] = ""; + } + } + } else if (propKey === DANGEROUSLY_SET_INNER_HTML || propKey === CHILDREN) + ; + else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING) + ; + else if (propKey === AUTOFOCUS) + ; + else if (registrationNameDependencies.hasOwnProperty(propKey)) { + if (!updatePayload) { + updatePayload = []; + } + } else { + (updatePayload = updatePayload || []).push(propKey, null); + } + } + for (propKey in nextProps) { + var nextProp = nextProps[propKey]; + var lastProp = lastProps != null ? lastProps[propKey] : undefined; + if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp || nextProp == null && lastProp == null) { + continue; + } + if (propKey === STYLE) { + { + if (nextProp) { + Object.freeze(nextProp); + } + } + if (lastProp) { + for (styleName in lastProp) { + if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) { + if (!styleUpdates) { + styleUpdates = {}; + } + styleUpdates[styleName] = ""; + } + } + for (styleName in nextProp) { + if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) { + if (!styleUpdates) { + styleUpdates = {}; + } + styleUpdates[styleName] = nextProp[styleName]; + } + } + } else { + if (!styleUpdates) { + if (!updatePayload) { + updatePayload = []; + } + updatePayload.push(propKey, styleUpdates); + } + styleUpdates = nextProp; + } + } else if (propKey === DANGEROUSLY_SET_INNER_HTML) { + var nextHtml = nextProp ? nextProp[HTML$1] : undefined; + var lastHtml = lastProp ? lastProp[HTML$1] : undefined; + if (nextHtml != null) { + if (lastHtml !== nextHtml) { + (updatePayload = updatePayload || []).push(propKey, nextHtml); + } + } + } else if (propKey === CHILDREN) { + if (typeof nextProp === "string" || typeof nextProp === "number") { + (updatePayload = updatePayload || []).push(propKey, "" + nextProp); + } + } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING) + ; + else if (registrationNameDependencies.hasOwnProperty(propKey)) { + if (nextProp != null) { + if (typeof nextProp !== "function") { + warnForInvalidEventListener(propKey, nextProp); + } + if (propKey === "onScroll") { + listenToNonDelegatedEvent("scroll", domElement); + } + } + if (!updatePayload && lastProp !== nextProp) { + updatePayload = []; + } + } else { + (updatePayload = updatePayload || []).push(propKey, nextProp); + } + } + if (styleUpdates) { + { + validateShorthandPropertyCollisionInDev(styleUpdates, nextProps[STYLE]); + } + (updatePayload = updatePayload || []).push(STYLE, styleUpdates); + } + return updatePayload; + } + function updateProperties(domElement, updatePayload, tag, lastRawProps, nextRawProps) { + if (tag === "input" && nextRawProps.type === "radio" && nextRawProps.name != null) { + updateChecked(domElement, nextRawProps); + } + var wasCustomComponentTag = isCustomComponent(tag, lastRawProps); + var isCustomComponentTag = isCustomComponent(tag, nextRawProps); + updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag); + switch (tag) { + case "input": + updateWrapper(domElement, nextRawProps); + break; + case "textarea": + updateWrapper$1(domElement, nextRawProps); + break; + case "select": + postUpdateWrapper(domElement, nextRawProps); + break; + } + } + function getPossibleStandardName(propName) { + { + var lowerCasedName = propName.toLowerCase(); + if (!possibleStandardNames.hasOwnProperty(lowerCasedName)) { + return null; + } + return possibleStandardNames[lowerCasedName] || null; + } + } + function diffHydratedProperties(domElement, tag, rawProps, parentNamespace, rootContainerElement, isConcurrentMode, shouldWarnDev) { + var isCustomComponentTag; + var extraAttributeNames; + { + isCustomComponentTag = isCustomComponent(tag, rawProps); + validatePropertiesInDevelopment(tag, rawProps); + } + switch (tag) { + case "dialog": + listenToNonDelegatedEvent("cancel", domElement); + listenToNonDelegatedEvent("close", domElement); + break; + case "iframe": + case "object": + case "embed": + listenToNonDelegatedEvent("load", domElement); + break; + case "video": + case "audio": + for (var i = 0;i < mediaEventTypes.length; i++) { + listenToNonDelegatedEvent(mediaEventTypes[i], domElement); + } + break; + case "source": + listenToNonDelegatedEvent("error", domElement); + break; + case "img": + case "image": + case "link": + listenToNonDelegatedEvent("error", domElement); + listenToNonDelegatedEvent("load", domElement); + break; + case "details": + listenToNonDelegatedEvent("toggle", domElement); + break; + case "input": + initWrapperState(domElement, rawProps); + listenToNonDelegatedEvent("invalid", domElement); + break; + case "option": + validateProps(domElement, rawProps); + break; + case "select": + initWrapperState$1(domElement, rawProps); + listenToNonDelegatedEvent("invalid", domElement); + break; + case "textarea": + initWrapperState$2(domElement, rawProps); + listenToNonDelegatedEvent("invalid", domElement); + break; + } + assertValidProps(tag, rawProps); + { + extraAttributeNames = new Set; + var attributes = domElement.attributes; + for (var _i = 0;_i < attributes.length; _i++) { + var name = attributes[_i].name.toLowerCase(); + switch (name) { + case "value": + break; + case "checked": + break; + case "selected": + break; + default: + extraAttributeNames.add(attributes[_i].name); + } + } + } + var updatePayload = null; + for (var propKey in rawProps) { + if (!rawProps.hasOwnProperty(propKey)) { + continue; + } + var nextProp = rawProps[propKey]; + if (propKey === CHILDREN) { + if (typeof nextProp === "string") { + if (domElement.textContent !== nextProp) { + if (rawProps[SUPPRESS_HYDRATION_WARNING] !== true) { + checkForUnmatchedText(domElement.textContent, nextProp, isConcurrentMode, shouldWarnDev); + } + updatePayload = [CHILDREN, nextProp]; + } + } else if (typeof nextProp === "number") { + if (domElement.textContent !== "" + nextProp) { + if (rawProps[SUPPRESS_HYDRATION_WARNING] !== true) { + checkForUnmatchedText(domElement.textContent, nextProp, isConcurrentMode, shouldWarnDev); + } + updatePayload = [CHILDREN, "" + nextProp]; + } + } + } else if (registrationNameDependencies.hasOwnProperty(propKey)) { + if (nextProp != null) { + if (typeof nextProp !== "function") { + warnForInvalidEventListener(propKey, nextProp); + } + if (propKey === "onScroll") { + listenToNonDelegatedEvent("scroll", domElement); + } + } + } else if (shouldWarnDev && true && typeof isCustomComponentTag === "boolean") { + var serverValue = undefined; + var propertyInfo = isCustomComponentTag && enableCustomElementPropertySupport ? null : getPropertyInfo(propKey); + if (rawProps[SUPPRESS_HYDRATION_WARNING] === true) + ; + else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING || propKey === "value" || propKey === "checked" || propKey === "selected") + ; + else if (propKey === DANGEROUSLY_SET_INNER_HTML) { + var serverHTML = domElement.innerHTML; + var nextHtml = nextProp ? nextProp[HTML$1] : undefined; + if (nextHtml != null) { + var expectedHTML = normalizeHTML(domElement, nextHtml); + if (expectedHTML !== serverHTML) { + warnForPropDifference(propKey, serverHTML, expectedHTML); + } + } + } else if (propKey === STYLE) { + extraAttributeNames.delete(propKey); + if (canDiffStyleForHydrationWarning) { + var expectedStyle = createDangerousStringForStyles(nextProp); + serverValue = domElement.getAttribute("style"); + if (expectedStyle !== serverValue) { + warnForPropDifference(propKey, serverValue, expectedStyle); + } + } + } else if (isCustomComponentTag && !enableCustomElementPropertySupport) { + extraAttributeNames.delete(propKey.toLowerCase()); + serverValue = getValueForAttribute(domElement, propKey, nextProp); + if (nextProp !== serverValue) { + warnForPropDifference(propKey, serverValue, nextProp); + } + } else if (!shouldIgnoreAttribute(propKey, propertyInfo, isCustomComponentTag) && !shouldRemoveAttribute(propKey, nextProp, propertyInfo, isCustomComponentTag)) { + var isMismatchDueToBadCasing = false; + if (propertyInfo !== null) { + extraAttributeNames.delete(propertyInfo.attributeName); + serverValue = getValueForProperty(domElement, propKey, nextProp, propertyInfo); + } else { + var ownNamespace = parentNamespace; + if (ownNamespace === HTML_NAMESPACE) { + ownNamespace = getIntrinsicNamespace(tag); + } + if (ownNamespace === HTML_NAMESPACE) { + extraAttributeNames.delete(propKey.toLowerCase()); + } else { + var standardName = getPossibleStandardName(propKey); + if (standardName !== null && standardName !== propKey) { + isMismatchDueToBadCasing = true; + extraAttributeNames.delete(standardName); + } + extraAttributeNames.delete(propKey); + } + serverValue = getValueForAttribute(domElement, propKey, nextProp); + } + var dontWarnCustomElement = enableCustomElementPropertySupport; + if (!dontWarnCustomElement && nextProp !== serverValue && !isMismatchDueToBadCasing) { + warnForPropDifference(propKey, serverValue, nextProp); + } + } + } + } + { + if (shouldWarnDev) { + if (extraAttributeNames.size > 0 && rawProps[SUPPRESS_HYDRATION_WARNING] !== true) { + warnForExtraAttributes(extraAttributeNames); + } + } + } + switch (tag) { + case "input": + track(domElement); + postMountWrapper(domElement, rawProps, true); + break; + case "textarea": + track(domElement); + postMountWrapper$3(domElement); + break; + case "select": + case "option": + break; + default: + if (typeof rawProps.onClick === "function") { + trapClickOnNonInteractiveElement(domElement); + } + break; + } + return updatePayload; + } + function diffHydratedText(textNode, text, isConcurrentMode) { + var isDifferent = textNode.nodeValue !== text; + return isDifferent; + } + function warnForDeletedHydratableElement(parentNode, child) { + { + if (didWarnInvalidHydration) { + return; + } + didWarnInvalidHydration = true; + error("Did not expect server HTML to contain a <%s> in <%s>.", child.nodeName.toLowerCase(), parentNode.nodeName.toLowerCase()); + } + } + function warnForDeletedHydratableText(parentNode, child) { + { + if (didWarnInvalidHydration) { + return; + } + didWarnInvalidHydration = true; + error('Did not expect server HTML to contain the text node "%s" in <%s>.', child.nodeValue, parentNode.nodeName.toLowerCase()); + } + } + function warnForInsertedHydratedElement(parentNode, tag, props) { + { + if (didWarnInvalidHydration) { + return; + } + didWarnInvalidHydration = true; + error("Expected server HTML to contain a matching <%s> in <%s>.", tag, parentNode.nodeName.toLowerCase()); + } + } + function warnForInsertedHydratedText(parentNode, text) { + { + if (text === "") { + return; + } + if (didWarnInvalidHydration) { + return; + } + didWarnInvalidHydration = true; + error('Expected server HTML to contain a matching text node for "%s" in <%s>.', text, parentNode.nodeName.toLowerCase()); + } + } + function restoreControlledState$3(domElement, tag, props) { + switch (tag) { + case "input": + restoreControlledState(domElement, props); + return; + case "textarea": + restoreControlledState$2(domElement, props); + return; + case "select": + restoreControlledState$1(domElement, props); + return; + } + } + var validateDOMNesting = function() { + }; + var updatedAncestorInfo = function() { + }; + { + var specialTags = ["address", "applet", "area", "article", "aside", "base", "basefont", "bgsound", "blockquote", "body", "br", "button", "caption", "center", "col", "colgroup", "dd", "details", "dir", "div", "dl", "dt", "embed", "fieldset", "figcaption", "figure", "footer", "form", "frame", "frameset", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup", "hr", "html", "iframe", "img", "input", "isindex", "li", "link", "listing", "main", "marquee", "menu", "menuitem", "meta", "nav", "noembed", "noframes", "noscript", "object", "ol", "p", "param", "plaintext", "pre", "script", "section", "select", "source", "style", "summary", "table", "tbody", "td", "template", "textarea", "tfoot", "th", "thead", "title", "tr", "track", "ul", "wbr", "xmp"]; + var inScopeTags = [ + "applet", + "caption", + "html", + "table", + "td", + "th", + "marquee", + "object", + "template", + "foreignObject", + "desc", + "title" + ]; + var buttonScopeTags = inScopeTags.concat(["button"]); + var impliedEndTags = ["dd", "dt", "li", "option", "optgroup", "p", "rp", "rt"]; + var emptyAncestorInfo = { + current: null, + formTag: null, + aTagInScope: null, + buttonTagInScope: null, + nobrTagInScope: null, + pTagInButtonScope: null, + listItemTagAutoclosing: null, + dlItemTagAutoclosing: null + }; + updatedAncestorInfo = function(oldInfo, tag) { + var ancestorInfo = assign({}, oldInfo || emptyAncestorInfo); + var info = { + tag + }; + if (inScopeTags.indexOf(tag) !== -1) { + ancestorInfo.aTagInScope = null; + ancestorInfo.buttonTagInScope = null; + ancestorInfo.nobrTagInScope = null; + } + if (buttonScopeTags.indexOf(tag) !== -1) { + ancestorInfo.pTagInButtonScope = null; + } + if (specialTags.indexOf(tag) !== -1 && tag !== "address" && tag !== "div" && tag !== "p") { + ancestorInfo.listItemTagAutoclosing = null; + ancestorInfo.dlItemTagAutoclosing = null; + } + ancestorInfo.current = info; + if (tag === "form") { + ancestorInfo.formTag = info; + } + if (tag === "a") { + ancestorInfo.aTagInScope = info; + } + if (tag === "button") { + ancestorInfo.buttonTagInScope = info; + } + if (tag === "nobr") { + ancestorInfo.nobrTagInScope = info; + } + if (tag === "p") { + ancestorInfo.pTagInButtonScope = info; + } + if (tag === "li") { + ancestorInfo.listItemTagAutoclosing = info; + } + if (tag === "dd" || tag === "dt") { + ancestorInfo.dlItemTagAutoclosing = info; + } + return ancestorInfo; + }; + var isTagValidWithParent = function(tag, parentTag) { + switch (parentTag) { + case "select": + return tag === "option" || tag === "optgroup" || tag === "#text"; + case "optgroup": + return tag === "option" || tag === "#text"; + case "option": + return tag === "#text"; + case "tr": + return tag === "th" || tag === "td" || tag === "style" || tag === "script" || tag === "template"; + case "tbody": + case "thead": + case "tfoot": + return tag === "tr" || tag === "style" || tag === "script" || tag === "template"; + case "colgroup": + return tag === "col" || tag === "template"; + case "table": + return tag === "caption" || tag === "colgroup" || tag === "tbody" || tag === "tfoot" || tag === "thead" || tag === "style" || tag === "script" || tag === "template"; + case "head": + return tag === "base" || tag === "basefont" || tag === "bgsound" || tag === "link" || tag === "meta" || tag === "title" || tag === "noscript" || tag === "noframes" || tag === "style" || tag === "script" || tag === "template"; + case "html": + return tag === "head" || tag === "body" || tag === "frameset"; + case "frameset": + return tag === "frame"; + case "#document": + return tag === "html"; + } + switch (tag) { + case "h1": + case "h2": + case "h3": + case "h4": + case "h5": + case "h6": + return parentTag !== "h1" && parentTag !== "h2" && parentTag !== "h3" && parentTag !== "h4" && parentTag !== "h5" && parentTag !== "h6"; + case "rp": + case "rt": + return impliedEndTags.indexOf(parentTag) === -1; + case "body": + case "caption": + case "col": + case "colgroup": + case "frameset": + case "frame": + case "head": + case "html": + case "tbody": + case "td": + case "tfoot": + case "th": + case "thead": + case "tr": + return parentTag == null; + } + return true; + }; + var findInvalidAncestorForTag = function(tag, ancestorInfo) { + switch (tag) { + case "address": + case "article": + case "aside": + case "blockquote": + case "center": + case "details": + case "dialog": + case "dir": + case "div": + case "dl": + case "fieldset": + case "figcaption": + case "figure": + case "footer": + case "header": + case "hgroup": + case "main": + case "menu": + case "nav": + case "ol": + case "p": + case "section": + case "summary": + case "ul": + case "pre": + case "listing": + case "table": + case "hr": + case "xmp": + case "h1": + case "h2": + case "h3": + case "h4": + case "h5": + case "h6": + return ancestorInfo.pTagInButtonScope; + case "form": + return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope; + case "li": + return ancestorInfo.listItemTagAutoclosing; + case "dd": + case "dt": + return ancestorInfo.dlItemTagAutoclosing; + case "button": + return ancestorInfo.buttonTagInScope; + case "a": + return ancestorInfo.aTagInScope; + case "nobr": + return ancestorInfo.nobrTagInScope; + } + return null; + }; + var didWarn$1 = {}; + validateDOMNesting = function(childTag, childText, ancestorInfo) { + ancestorInfo = ancestorInfo || emptyAncestorInfo; + var parentInfo = ancestorInfo.current; + var parentTag = parentInfo && parentInfo.tag; + if (childText != null) { + if (childTag != null) { + error("validateDOMNesting: when childText is passed, childTag should be null"); + } + childTag = "#text"; + } + var invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo; + var invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo); + var invalidParentOrAncestor = invalidParent || invalidAncestor; + if (!invalidParentOrAncestor) { + return; + } + var ancestorTag = invalidParentOrAncestor.tag; + var warnKey = !!invalidParent + "|" + childTag + "|" + ancestorTag; + if (didWarn$1[warnKey]) { + return; + } + didWarn$1[warnKey] = true; + var tagDisplayName = childTag; + var whitespaceInfo = ""; + if (childTag === "#text") { + if (/\S/.test(childText)) { + tagDisplayName = "Text nodes"; + } else { + tagDisplayName = "Whitespace text nodes"; + whitespaceInfo = " Make sure you don't have any extra whitespace between tags on each line of your source code."; + } + } else { + tagDisplayName = "<" + childTag + ">"; + } + if (invalidParent) { + var info = ""; + if (ancestorTag === "table" && childTag === "tr") { + info += " Add a <tbody>, <thead> or <tfoot> to your code to match the DOM tree generated by the browser."; + } + error("validateDOMNesting(...): %s cannot appear as a child of <%s>.%s%s", tagDisplayName, ancestorTag, whitespaceInfo, info); + } else { + error("validateDOMNesting(...): %s cannot appear as a descendant of <%s>.", tagDisplayName, ancestorTag); + } + }; + } + var SUPPRESS_HYDRATION_WARNING$1 = "suppressHydrationWarning"; + var SUSPENSE_START_DATA = "$"; + var SUSPENSE_END_DATA = "/$"; + var SUSPENSE_PENDING_START_DATA = "$?"; + var SUSPENSE_FALLBACK_START_DATA = "$!"; + var STYLE$1 = "style"; + var eventsEnabled = null; + var selectionInformation = null; + function getRootHostContext(rootContainerInstance) { + var type; + var namespace; + var nodeType = rootContainerInstance.nodeType; + switch (nodeType) { + case DOCUMENT_NODE: + case DOCUMENT_FRAGMENT_NODE: { + type = nodeType === DOCUMENT_NODE ? "#document" : "#fragment"; + var root2 = rootContainerInstance.documentElement; + namespace = root2 ? root2.namespaceURI : getChildNamespace(null, ""); + break; + } + default: { + var container = nodeType === COMMENT_NODE ? rootContainerInstance.parentNode : rootContainerInstance; + var ownNamespace = container.namespaceURI || null; + type = container.tagName; + namespace = getChildNamespace(ownNamespace, type); + break; + } + } + { + var validatedTag = type.toLowerCase(); + var ancestorInfo = updatedAncestorInfo(null, validatedTag); + return { + namespace, + ancestorInfo + }; + } + } + function getChildHostContext(parentHostContext, type, rootContainerInstance) { + { + var parentHostContextDev = parentHostContext; + var namespace = getChildNamespace(parentHostContextDev.namespace, type); + var ancestorInfo = updatedAncestorInfo(parentHostContextDev.ancestorInfo, type); + return { + namespace, + ancestorInfo + }; + } + } + function getPublicInstance(instance) { + return instance; + } + function prepareForCommit(containerInfo) { + eventsEnabled = isEnabled(); + selectionInformation = getSelectionInformation(); + var activeInstance = null; + setEnabled(false); + return activeInstance; + } + function resetAfterCommit(containerInfo) { + restoreSelection(selectionInformation); + setEnabled(eventsEnabled); + eventsEnabled = null; + selectionInformation = null; + } + function createInstance(type, props, rootContainerInstance, hostContext, internalInstanceHandle) { + var parentNamespace; + { + var hostContextDev = hostContext; + validateDOMNesting(type, null, hostContextDev.ancestorInfo); + if (typeof props.children === "string" || typeof props.children === "number") { + var string = "" + props.children; + var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type); + validateDOMNesting(null, string, ownAncestorInfo); + } + parentNamespace = hostContextDev.namespace; + } + var domElement = createElement(type, props, rootContainerInstance, parentNamespace); + precacheFiberNode(internalInstanceHandle, domElement); + updateFiberProps(domElement, props); + return domElement; + } + function appendInitialChild(parentInstance, child) { + parentInstance.appendChild(child); + } + function finalizeInitialChildren(domElement, type, props, rootContainerInstance, hostContext) { + setInitialProperties(domElement, type, props, rootContainerInstance); + switch (type) { + case "button": + case "input": + case "select": + case "textarea": + return !!props.autoFocus; + case "img": + return true; + default: + return false; + } + } + function prepareUpdate(domElement, type, oldProps, newProps, rootContainerInstance, hostContext) { + { + var hostContextDev = hostContext; + if (typeof newProps.children !== typeof oldProps.children && (typeof newProps.children === "string" || typeof newProps.children === "number")) { + var string = "" + newProps.children; + var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type); + validateDOMNesting(null, string, ownAncestorInfo); + } + } + return diffProperties(domElement, type, oldProps, newProps); + } + function shouldSetTextContent(type, props) { + return type === "textarea" || type === "noscript" || typeof props.children === "string" || typeof props.children === "number" || typeof props.dangerouslySetInnerHTML === "object" && props.dangerouslySetInnerHTML !== null && props.dangerouslySetInnerHTML.__html != null; + } + function createTextInstance(text, rootContainerInstance, hostContext, internalInstanceHandle) { + { + var hostContextDev = hostContext; + validateDOMNesting(null, text, hostContextDev.ancestorInfo); + } + var textNode = createTextNode(text, rootContainerInstance); + precacheFiberNode(internalInstanceHandle, textNode); + return textNode; + } + function getCurrentEventPriority() { + var currentEvent = window.event; + if (currentEvent === undefined) { + return DefaultEventPriority; + } + return getEventPriority(currentEvent.type); + } + var scheduleTimeout = typeof setTimeout === "function" ? setTimeout : undefined; + var cancelTimeout = typeof clearTimeout === "function" ? clearTimeout : undefined; + var noTimeout = -1; + var localPromise = typeof Promise === "function" ? Promise : undefined; + var scheduleMicrotask = typeof queueMicrotask === "function" ? queueMicrotask : typeof localPromise !== "undefined" ? function(callback) { + return localPromise.resolve(null).then(callback).catch(handleErrorInNextTick); + } : scheduleTimeout; + function handleErrorInNextTick(error2) { + setTimeout(function() { + throw error2; + }); + } + function commitMount(domElement, type, newProps, internalInstanceHandle) { + switch (type) { + case "button": + case "input": + case "select": + case "textarea": + if (newProps.autoFocus) { + domElement.focus(); + } + return; + case "img": { + if (newProps.src) { + domElement.src = newProps.src; + } + return; + } + } + } + function commitUpdate(domElement, updatePayload, type, oldProps, newProps, internalInstanceHandle) { + updateProperties(domElement, updatePayload, type, oldProps, newProps); + updateFiberProps(domElement, newProps); + } + function resetTextContent(domElement) { + setTextContent(domElement, ""); + } + function commitTextUpdate(textInstance, oldText, newText) { + textInstance.nodeValue = newText; + } + function appendChild(parentInstance, child) { + parentInstance.appendChild(child); + } + function appendChildToContainer(container, child) { + var parentNode; + if (container.nodeType === COMMENT_NODE) { + parentNode = container.parentNode; + parentNode.insertBefore(child, container); + } else { + parentNode = container; + parentNode.appendChild(child); + } + var reactRootContainer = container._reactRootContainer; + if ((reactRootContainer === null || reactRootContainer === undefined) && parentNode.onclick === null) { + trapClickOnNonInteractiveElement(parentNode); + } + } + function insertBefore(parentInstance, child, beforeChild) { + parentInstance.insertBefore(child, beforeChild); + } + function insertInContainerBefore(container, child, beforeChild) { + if (container.nodeType === COMMENT_NODE) { + container.parentNode.insertBefore(child, beforeChild); + } else { + container.insertBefore(child, beforeChild); + } + } + function removeChild(parentInstance, child) { + parentInstance.removeChild(child); + } + function removeChildFromContainer(container, child) { + if (container.nodeType === COMMENT_NODE) { + container.parentNode.removeChild(child); + } else { + container.removeChild(child); + } + } + function clearSuspenseBoundary(parentInstance, suspenseInstance) { + var node = suspenseInstance; + var depth = 0; + do { + var nextNode = node.nextSibling; + parentInstance.removeChild(node); + if (nextNode && nextNode.nodeType === COMMENT_NODE) { + var data = nextNode.data; + if (data === SUSPENSE_END_DATA) { + if (depth === 0) { + parentInstance.removeChild(nextNode); + retryIfBlockedOn(suspenseInstance); + return; + } else { + depth--; + } + } else if (data === SUSPENSE_START_DATA || data === SUSPENSE_PENDING_START_DATA || data === SUSPENSE_FALLBACK_START_DATA) { + depth++; + } + } + node = nextNode; + } while (node); + retryIfBlockedOn(suspenseInstance); + } + function clearSuspenseBoundaryFromContainer(container, suspenseInstance) { + if (container.nodeType === COMMENT_NODE) { + clearSuspenseBoundary(container.parentNode, suspenseInstance); + } else if (container.nodeType === ELEMENT_NODE) { + clearSuspenseBoundary(container, suspenseInstance); + } + retryIfBlockedOn(container); + } + function hideInstance(instance) { + instance = instance; + var style2 = instance.style; + if (typeof style2.setProperty === "function") { + style2.setProperty("display", "none", "important"); + } else { + style2.display = "none"; + } + } + function hideTextInstance(textInstance) { + textInstance.nodeValue = ""; + } + function unhideInstance(instance, props) { + instance = instance; + var styleProp = props[STYLE$1]; + var display = styleProp !== undefined && styleProp !== null && styleProp.hasOwnProperty("display") ? styleProp.display : null; + instance.style.display = dangerousStyleValue("display", display); + } + function unhideTextInstance(textInstance, text) { + textInstance.nodeValue = text; + } + function clearContainer(container) { + if (container.nodeType === ELEMENT_NODE) { + container.textContent = ""; + } else if (container.nodeType === DOCUMENT_NODE) { + if (container.documentElement) { + container.removeChild(container.documentElement); + } + } + } + function canHydrateInstance(instance, type, props) { + if (instance.nodeType !== ELEMENT_NODE || type.toLowerCase() !== instance.nodeName.toLowerCase()) { + return null; + } + return instance; + } + function canHydrateTextInstance(instance, text) { + if (text === "" || instance.nodeType !== TEXT_NODE) { + return null; + } + return instance; + } + function canHydrateSuspenseInstance(instance) { + if (instance.nodeType !== COMMENT_NODE) { + return null; + } + return instance; + } + function isSuspenseInstancePending(instance) { + return instance.data === SUSPENSE_PENDING_START_DATA; + } + function isSuspenseInstanceFallback(instance) { + return instance.data === SUSPENSE_FALLBACK_START_DATA; + } + function getSuspenseInstanceFallbackErrorDetails(instance) { + var dataset = instance.nextSibling && instance.nextSibling.dataset; + var digest, message, stack; + if (dataset) { + digest = dataset.dgst; + { + message = dataset.msg; + stack = dataset.stck; + } + } + { + return { + message, + digest, + stack + }; + } + } + function registerSuspenseInstanceRetry(instance, callback) { + instance._reactRetry = callback; + } + function getNextHydratable(node) { + for (;node != null; node = node.nextSibling) { + var nodeType = node.nodeType; + if (nodeType === ELEMENT_NODE || nodeType === TEXT_NODE) { + break; + } + if (nodeType === COMMENT_NODE) { + var nodeData = node.data; + if (nodeData === SUSPENSE_START_DATA || nodeData === SUSPENSE_FALLBACK_START_DATA || nodeData === SUSPENSE_PENDING_START_DATA) { + break; + } + if (nodeData === SUSPENSE_END_DATA) { + return null; + } + } + } + return node; + } + function getNextHydratableSibling(instance) { + return getNextHydratable(instance.nextSibling); + } + function getFirstHydratableChild(parentInstance) { + return getNextHydratable(parentInstance.firstChild); + } + function getFirstHydratableChildWithinContainer(parentContainer) { + return getNextHydratable(parentContainer.firstChild); + } + function getFirstHydratableChildWithinSuspenseInstance(parentInstance) { + return getNextHydratable(parentInstance.nextSibling); + } + function hydrateInstance(instance, type, props, rootContainerInstance, hostContext, internalInstanceHandle, shouldWarnDev) { + precacheFiberNode(internalInstanceHandle, instance); + updateFiberProps(instance, props); + var parentNamespace; + { + var hostContextDev = hostContext; + parentNamespace = hostContextDev.namespace; + } + var isConcurrentMode = (internalInstanceHandle.mode & ConcurrentMode) !== NoMode; + return diffHydratedProperties(instance, type, props, parentNamespace, rootContainerInstance, isConcurrentMode, shouldWarnDev); + } + function hydrateTextInstance(textInstance, text, internalInstanceHandle, shouldWarnDev) { + precacheFiberNode(internalInstanceHandle, textInstance); + var isConcurrentMode = (internalInstanceHandle.mode & ConcurrentMode) !== NoMode; + return diffHydratedText(textInstance, text); + } + function hydrateSuspenseInstance(suspenseInstance, internalInstanceHandle) { + precacheFiberNode(internalInstanceHandle, suspenseInstance); + } + function getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance) { + var node = suspenseInstance.nextSibling; + var depth = 0; + while (node) { + if (node.nodeType === COMMENT_NODE) { + var data = node.data; + if (data === SUSPENSE_END_DATA) { + if (depth === 0) { + return getNextHydratableSibling(node); + } else { + depth--; + } + } else if (data === SUSPENSE_START_DATA || data === SUSPENSE_FALLBACK_START_DATA || data === SUSPENSE_PENDING_START_DATA) { + depth++; + } + } + node = node.nextSibling; + } + return null; + } + function getParentSuspenseInstance(targetInstance) { + var node = targetInstance.previousSibling; + var depth = 0; + while (node) { + if (node.nodeType === COMMENT_NODE) { + var data = node.data; + if (data === SUSPENSE_START_DATA || data === SUSPENSE_FALLBACK_START_DATA || data === SUSPENSE_PENDING_START_DATA) { + if (depth === 0) { + return node; + } else { + depth--; + } + } else if (data === SUSPENSE_END_DATA) { + depth++; + } + } + node = node.previousSibling; + } + return null; + } + function commitHydratedContainer(container) { + retryIfBlockedOn(container); + } + function commitHydratedSuspenseInstance(suspenseInstance) { + retryIfBlockedOn(suspenseInstance); + } + function shouldDeleteUnhydratedTailInstances(parentType) { + return parentType !== "head" && parentType !== "body"; + } + function didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, text, isConcurrentMode) { + var shouldWarnDev = true; + checkForUnmatchedText(textInstance.nodeValue, text, isConcurrentMode, shouldWarnDev); + } + function didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, text, isConcurrentMode) { + if (parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) { + var shouldWarnDev = true; + checkForUnmatchedText(textInstance.nodeValue, text, isConcurrentMode, shouldWarnDev); + } + } + function didNotHydrateInstanceWithinContainer(parentContainer, instance) { + { + if (instance.nodeType === ELEMENT_NODE) { + warnForDeletedHydratableElement(parentContainer, instance); + } else if (instance.nodeType === COMMENT_NODE) + ; + else { + warnForDeletedHydratableText(parentContainer, instance); + } + } + } + function didNotHydrateInstanceWithinSuspenseInstance(parentInstance, instance) { + { + var parentNode = parentInstance.parentNode; + if (parentNode !== null) { + if (instance.nodeType === ELEMENT_NODE) { + warnForDeletedHydratableElement(parentNode, instance); + } else if (instance.nodeType === COMMENT_NODE) + ; + else { + warnForDeletedHydratableText(parentNode, instance); + } + } + } + } + function didNotHydrateInstance(parentType, parentProps, parentInstance, instance, isConcurrentMode) { + { + if (isConcurrentMode || parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) { + if (instance.nodeType === ELEMENT_NODE) { + warnForDeletedHydratableElement(parentInstance, instance); + } else if (instance.nodeType === COMMENT_NODE) + ; + else { + warnForDeletedHydratableText(parentInstance, instance); + } + } + } + } + function didNotFindHydratableInstanceWithinContainer(parentContainer, type, props) { + { + warnForInsertedHydratedElement(parentContainer, type); + } + } + function didNotFindHydratableTextInstanceWithinContainer(parentContainer, text) { + { + warnForInsertedHydratedText(parentContainer, text); + } + } + function didNotFindHydratableInstanceWithinSuspenseInstance(parentInstance, type, props) { + { + var parentNode = parentInstance.parentNode; + if (parentNode !== null) + warnForInsertedHydratedElement(parentNode, type); + } + } + function didNotFindHydratableTextInstanceWithinSuspenseInstance(parentInstance, text) { + { + var parentNode = parentInstance.parentNode; + if (parentNode !== null) + warnForInsertedHydratedText(parentNode, text); + } + } + function didNotFindHydratableInstance(parentType, parentProps, parentInstance, type, props, isConcurrentMode) { + { + if (isConcurrentMode || parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) { + warnForInsertedHydratedElement(parentInstance, type); + } + } + } + function didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, text, isConcurrentMode) { + { + if (isConcurrentMode || parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) { + warnForInsertedHydratedText(parentInstance, text); + } + } + } + function errorHydratingContainer(parentContainer) { + { + error("An error occurred during hydration. The server HTML was replaced with client content in <%s>.", parentContainer.nodeName.toLowerCase()); + } + } + function preparePortalMount(portalInstance) { + listenToAllSupportedEvents(portalInstance); + } + var randomKey = Math.random().toString(36).slice(2); + var internalInstanceKey = "__reactFiber$" + randomKey; + var internalPropsKey = "__reactProps$" + randomKey; + var internalContainerInstanceKey = "__reactContainer$" + randomKey; + var internalEventHandlersKey = "__reactEvents$" + randomKey; + var internalEventHandlerListenersKey = "__reactListeners$" + randomKey; + var internalEventHandlesSetKey = "__reactHandles$" + randomKey; + function detachDeletedInstance(node) { + delete node[internalInstanceKey]; + delete node[internalPropsKey]; + delete node[internalEventHandlersKey]; + delete node[internalEventHandlerListenersKey]; + delete node[internalEventHandlesSetKey]; + } + function precacheFiberNode(hostInst, node) { + node[internalInstanceKey] = hostInst; + } + function markContainerAsRoot(hostRoot, node) { + node[internalContainerInstanceKey] = hostRoot; + } + function unmarkContainerAsRoot(node) { + node[internalContainerInstanceKey] = null; + } + function isContainerMarkedAsRoot(node) { + return !!node[internalContainerInstanceKey]; + } + function getClosestInstanceFromNode(targetNode) { + var targetInst = targetNode[internalInstanceKey]; + if (targetInst) { + return targetInst; + } + var parentNode = targetNode.parentNode; + while (parentNode) { + targetInst = parentNode[internalContainerInstanceKey] || parentNode[internalInstanceKey]; + if (targetInst) { + var alternate = targetInst.alternate; + if (targetInst.child !== null || alternate !== null && alternate.child !== null) { + var suspenseInstance = getParentSuspenseInstance(targetNode); + while (suspenseInstance !== null) { + var targetSuspenseInst = suspenseInstance[internalInstanceKey]; + if (targetSuspenseInst) { + return targetSuspenseInst; + } + suspenseInstance = getParentSuspenseInstance(suspenseInstance); + } + } + return targetInst; + } + targetNode = parentNode; + parentNode = targetNode.parentNode; + } + return null; + } + function getInstanceFromNode(node) { + var inst = node[internalInstanceKey] || node[internalContainerInstanceKey]; + if (inst) { + if (inst.tag === HostComponent || inst.tag === HostText || inst.tag === SuspenseComponent || inst.tag === HostRoot) { + return inst; + } else { + return null; + } + } + return null; + } + function getNodeFromInstance(inst) { + if (inst.tag === HostComponent || inst.tag === HostText) { + return inst.stateNode; + } + throw new Error("getNodeFromInstance: Invalid argument."); + } + function getFiberCurrentPropsFromNode(node) { + return node[internalPropsKey] || null; + } + function updateFiberProps(node, props) { + node[internalPropsKey] = props; + } + function getEventListenerSet(node) { + var elementListenerSet = node[internalEventHandlersKey]; + if (elementListenerSet === undefined) { + elementListenerSet = node[internalEventHandlersKey] = new Set; + } + return elementListenerSet; + } + var loggedTypeFailures = {}; + var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; + function setCurrentlyValidatingElement(element) { + { + if (element) { + var owner = element._owner; + var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); + ReactDebugCurrentFrame$1.setExtraStackFrame(stack); + } else { + ReactDebugCurrentFrame$1.setExtraStackFrame(null); + } + } + } + function checkPropTypes(typeSpecs, values, location, componentName, element) { + { + var has2 = Function.call.bind(hasOwnProperty); + for (var typeSpecName in typeSpecs) { + if (has2(typeSpecs, typeSpecName)) { + var error$1 = undefined; + try { + if (typeof typeSpecs[typeSpecName] !== "function") { + 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)) { + 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); + } + var contextStackCursor = createCursor(emptyContextObject); + var didPerformWorkStackCursor = createCursor(false); + var previousContext = emptyContextObject; + function getUnmaskedContext(workInProgress2, Component, didPushOwnContextIfProvider) { + { + if (didPushOwnContextIfProvider && isContextProvider(Component)) { + return previousContext; + } + return contextStackCursor.current; + } + } + function cacheContext(workInProgress2, unmaskedContext, maskedContext) { + { + var instance = workInProgress2.stateNode; + instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext; + instance.__reactInternalMemoizedMaskedChildContext = maskedContext; + } + } + function getMaskedContext(workInProgress2, unmaskedContext) { + { + var type = workInProgress2.type; + var contextTypes = type.contextTypes; + if (!contextTypes) { + return emptyContextObject; + } + var instance = workInProgress2.stateNode; + if (instance && instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext) { + return instance.__reactInternalMemoizedMaskedChildContext; + } + var context = {}; + for (var key in contextTypes) { + context[key] = unmaskedContext[key]; + } + { + var name = getComponentNameFromFiber(workInProgress2) || "Unknown"; + checkPropTypes(contextTypes, context, "context", name); + } + if (instance) { + cacheContext(workInProgress2, 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; + 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(workInProgress2) { + { + var instance = workInProgress2.stateNode; + var memoizedMergedChildContext = instance && instance.__reactInternalMemoizedMergedChildContext || emptyContextObject; + previousContext = contextStackCursor.current; + push(contextStackCursor, memoizedMergedChildContext, workInProgress2); + push(didPerformWorkStackCursor, didPerformWorkStackCursor.current, workInProgress2); + return true; + } + } + function invalidateContextProvider(workInProgress2, type, didChange) { + { + var instance = workInProgress2.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) { + var mergedContext = processChildContext(workInProgress2, type, previousContext); + instance.__reactInternalMemoizedMergedChildContext = mergedContext; + pop(didPerformWorkStackCursor, workInProgress2); + pop(contextStackCursor, workInProgress2); + push(contextStackCursor, mergedContext, workInProgress2); + push(didPerformWorkStackCursor, didChange, workInProgress2); + } else { + pop(didPerformWorkStackCursor, workInProgress2); + push(didPerformWorkStackCursor, didChange, workInProgress2); + } + } + } + function findCurrentUnmaskedContext(fiber) { + { + 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 syncQueue = null; + var includesLegacySyncCallbacks = false; + var isFlushingSyncQueue = false; + function scheduleSyncCallback(callback) { + if (syncQueue === null) { + syncQueue = [callback]; + } else { + syncQueue.push(callback); + } + } + function scheduleLegacySyncCallback(callback) { + includesLegacySyncCallbacks = true; + scheduleSyncCallback(callback); + } + function flushSyncCallbacksOnlyInLegacyMode() { + if (includesLegacySyncCallbacks) { + flushSyncCallbacks(); + } + } + function flushSyncCallbacks() { + if (!isFlushingSyncQueue && syncQueue !== null) { + isFlushingSyncQueue = true; + var i = 0; + var previousUpdatePriority = getCurrentUpdatePriority(); + try { + var isSync = true; + var queue = syncQueue; + setCurrentUpdatePriority(DiscreteEventPriority); + for (;i < queue.length; i++) { + var callback = queue[i]; + do { + callback = callback(isSync); + } while (callback !== null); + } + syncQueue = null; + includesLegacySyncCallbacks = false; + } catch (error2) { + if (syncQueue !== null) { + syncQueue = syncQueue.slice(i + 1); + } + scheduleCallback(ImmediatePriority, flushSyncCallbacks); + throw error2; + } finally { + setCurrentUpdatePriority(previousUpdatePriority); + isFlushingSyncQueue = false; + } + } + return null; + } + 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(workInProgress2) { + warnIfNotHydrating(); + return (workInProgress2.flags & Forked) !== NoFlags; + } + function getForksAtLevel(workInProgress2) { + warnIfNotHydrating(); + return treeForkCount; + } + function getTreeId() { + var overflow = treeContextOverflow; + var idWithLeadingBit = treeContextId; + var id = idWithLeadingBit & ~getLeadingBit(idWithLeadingBit); + return id.toString(32) + overflow; + } + function pushTreeFork(workInProgress2, totalChildren) { + warnIfNotHydrating(); + forkStack[forkStackIndex++] = treeForkCount; + forkStack[forkStackIndex++] = treeForkProvider; + treeForkProvider = workInProgress2; + treeForkCount = totalChildren; + } + function pushTreeId(workInProgress2, totalChildren, index2) { + warnIfNotHydrating(); + idStack[idStackIndex++] = treeContextId; + idStack[idStackIndex++] = treeContextOverflow; + idStack[idStackIndex++] = treeContextProvider; + treeContextProvider = workInProgress2; + var baseIdWithLeadingBit = treeContextId; + var baseOverflow = treeContextOverflow; + var baseLength = getBitLength(baseIdWithLeadingBit) - 1; + var baseId = baseIdWithLeadingBit & ~(1 << baseLength); + var slot = index2 + 1; + var length = getBitLength(totalChildren) + baseLength; + if (length > 30) { + var numberOfOverflowBits = baseLength - baseLength % 5; + var newOverflowBits = (1 << numberOfOverflowBits) - 1; + var newOverflow = (baseId & newOverflowBits).toString(32); + var restOfBaseId = baseId >> numberOfOverflowBits; + var restOfBaseLength = baseLength - numberOfOverflowBits; + var restOfLength = getBitLength(totalChildren) + restOfBaseLength; + var restOfNewBits = slot << restOfBaseLength; + var id = restOfNewBits | restOfBaseId; + var overflow = newOverflow + baseOverflow; + treeContextId = 1 << restOfLength | id; + treeContextOverflow = overflow; + } else { + var newBits = slot << baseLength; + var _id = newBits | baseId; + var _overflow = baseOverflow; + treeContextId = 1 << length | _id; + treeContextOverflow = _overflow; + } + } + function pushMaterializedTreeId(workInProgress2) { + warnIfNotHydrating(); + var returnFiber = workInProgress2.return; + if (returnFiber !== null) { + var numberOfForks = 1; + var slotIndex = 0; + pushTreeFork(workInProgress2, numberOfForks); + pushTreeId(workInProgress2, numberOfForks, slotIndex); + } + } + function getBitLength(number) { + return 32 - clz32(number); + } + function getLeadingBit(id) { + return 1 << getBitLength(id) - 1; + } + function popTreeContext(workInProgress2) { + while (workInProgress2 === treeForkProvider) { + treeForkProvider = forkStack[--forkStackIndex]; + forkStack[forkStackIndex] = null; + treeForkCount = forkStack[--forkStackIndex]; + forkStack[forkStackIndex] = null; + } + while (workInProgress2 === 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(workInProgress2, suspendedContext) { + warnIfNotHydrating(); + idStack[idStackIndex++] = treeContextId; + idStack[idStackIndex++] = treeContextOverflow; + idStack[idStackIndex++] = treeContextProvider; + treeContextId = suspendedContext.id; + treeContextOverflow = suspendedContext.overflow; + treeContextProvider = workInProgress2; + } + function warnIfNotHydrating() { + { + if (!getIsHydrating()) { + error("Expected to be hydrating. This is a bug in React. Please file an issue."); + } + } + } + var hydrationParentFiber = null; + var nextHydratableInstance = null; + var isHydrating = false; + var didSuspendOrErrorDEV = false; + 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 markDidThrowWhileHydratingDEV() { + { + didSuspendOrErrorDEV = true; + } + } + function didSuspendOrErrorWhileHydratingDEV() { + { + return didSuspendOrErrorDEV; + } + } + function enterHydrationState(fiber) { + var parentInstance = fiber.stateNode.containerInfo; + nextHydratableInstance = getFirstHydratableChildWithinContainer(parentInstance); + hydrationParentFiber = fiber; + isHydrating = true; + hydrationErrors = null; + didSuspendOrErrorDEV = false; + return true; + } + function reenterHydrationStateFromDehydratedSuspenseInstance(fiber, suspenseInstance, treeContext) { + nextHydratableInstance = getFirstHydratableChildWithinSuspenseInstance(suspenseInstance); + hydrationParentFiber = fiber; + isHydrating = true; + hydrationErrors = null; + didSuspendOrErrorDEV = 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: { + var isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode; + didNotHydrateInstance(returnFiber.type, returnFiber.memoizedProps, returnFiber.stateNode, instance, isConcurrentMode); + 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 (didSuspendOrErrorDEV) { + 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); + break; + case HostText: + var text = fiber.pendingProps; + didNotFindHydratableTextInstanceWithinContainer(parentContainer, text); + 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; + var isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode; + didNotFindHydratableInstance(parentType, parentProps, parentInstance, _type, _props, isConcurrentMode); + break; + } + case HostText: { + var _text = fiber.pendingProps; + var _isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode; + didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, _text, _isConcurrentMode); + 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); + break; + case HostText: + var _text2 = fiber.pendingProps; + didNotFindHydratableTextInstanceWithinSuspenseInstance(_parentInstance, _text2); + 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); + 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; + 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; + var dehydratedFragment = createFiberFromDehydratedFragment(suspenseInstance); + dehydratedFragment.return = fiber; + fiber.child = dehydratedFragment; + hydrationParentFiber = fiber; + 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(); + } + insertNonHydratedInstance(hydrationParentFiber, fiber); + isHydrating = false; + hydrationParentFiber = fiber; + return; + } + var firstAttemptedInstance = nextInstance; + if (!tryHydrate(fiber, nextInstance)) { + if (shouldClientRenderOnMismatch(fiber)) { + warnNonhydratedInstance(hydrationParentFiber, fiber); + throwOnHydrationMismatch(); + } + nextInstance = getNextHydratableSibling(firstAttemptedInstance); + var prevHydrationParentFiber = hydrationParentFiber; + if (!nextInstance || !tryHydrate(fiber, nextInstance)) { + insertNonHydratedInstance(hydrationParentFiber, fiber); + isHydrating = false; + hydrationParentFiber = fiber; + return; + } + deleteHydratableInstance(prevHydrationParentFiber, firstAttemptedInstance); + } + } + function prepareToHydrateHostInstance(fiber, rootContainerInstance, hostContext) { + var instance = fiber.stateNode; + var shouldWarnIfMismatchDev = !didSuspendOrErrorDEV; + var updatePayload = hydrateInstance(instance, fiber.type, fiber.memoizedProps, rootContainerInstance, hostContext, fiber, shouldWarnIfMismatchDev); + fiber.updateQueue = updatePayload; + if (updatePayload !== null) { + return true; + } + return false; + } + function prepareToHydrateHostTextInstance(fiber) { + var textInstance = fiber.stateNode; + var textContent = fiber.memoizedProps; + var shouldUpdate = hydrateTextInstance(textInstance, textContent, fiber); + if (shouldUpdate) { + var returnFiber = hydrationParentFiber; + if (returnFiber !== null) { + switch (returnFiber.tag) { + case HostRoot: { + var parentContainer = returnFiber.stateNode.containerInfo; + var isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode; + didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, textContent, isConcurrentMode); + break; + } + case HostComponent: { + var parentType = returnFiber.type; + var parentProps = returnFiber.memoizedProps; + var parentInstance = returnFiber.stateNode; + var _isConcurrentMode2 = (returnFiber.mode & ConcurrentMode) !== NoMode; + didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, textContent, _isConcurrentMode2); + break; + } + } + } + } + return shouldUpdate; + } + function prepareToHydrateHostSuspenseInstance(fiber) { + 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) { + 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 (fiber !== hydrationParentFiber) { + return false; + } + if (!isHydrating) { + popToNextHostParent(fiber); + isHydrating = true; + return false; + } + 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() { + hydrationParentFiber = null; + nextHydratableInstance = null; + isHydrating = false; + didSuspendOrErrorDEV = false; + } + function upgradeHydrationErrorsToRecoverable() { + if (hydrationErrors !== null) { + queueRecoverableErrors(hydrationErrors); + hydrationErrors = null; + } + } + function getIsHydrating() { + return isHydrating; + } + function queueHydrationError(error2) { + if (hydrationErrors === null) { + hydrationErrors = [error2]; + } else { + hydrationErrors.push(error2); + } + } + var ReactCurrentBatchConfig$1 = ReactSharedInternals.ReactCurrentBatchConfig; + var NoTransition = null; + function requestCurrentTransition() { + return ReactCurrentBatchConfig$1.transition; + } + 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(set2) { + var array = []; + set2.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 = []; + var didWarnAboutUnsafeLifecycles = new Set; + ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = function(fiber, instance) { + if (didWarnAboutUnsafeLifecycles.has(fiber.type)) { + return; + } + if (typeof instance.componentWillMount === "function" && 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() { + 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 = []; + } + 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; + 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; + } + 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; + }; + } + var didWarnAboutMaps; + var didWarnAboutGenerators; + var didWarnAboutStringRefs; + var ownerHasKeyUseWarning; + var ownerHasFunctionTypeWarning; + var warnForMissingKey = function(child, returnFiber) { + }; + { + didWarnAboutMaps = false; + didWarnAboutGenerators = false; + didWarnAboutStringRefs = {}; + 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 isReactClass(type) { + return type.prototype && type.prototype.isReactComponent; + } + function coerceRef(returnFiber, current2, element) { + var mixedRef = element.ref; + if (mixedRef !== null && typeof mixedRef !== "function" && typeof mixedRef !== "object") { + { + if ((returnFiber.mode & StrictLegacyMode || warnAboutStringRefs) && !(element._owner && element._self && element._owner.stateNode !== element._self) && !(element._owner && element._owner.tag !== ClassComponent) && !(typeof element.type === "function" && !isReactClass(element.type)) && element._owner) { + var componentName = getComponentNameFromFiber(returnFiber) || "Component"; + if (!didWarnAboutStringRefs[componentName]) { + { + error('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. We recommend using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref', componentName, 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."); + } + var resolvedInst = inst; + { + checkPropStringCoercion(mixedRef, "ref"); + } + var stringRef = "" + mixedRef; + if (current2 !== null && current2.ref !== null && typeof current2.ref === "function" && current2.ref._stringRef === stringRef) { + return current2.ref; + } + var ref = function(value) { + var 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:\n1. You may be adding a ref to a function component\n2. You may be adding a ref to a component that was not created inside a component's render method\n3. You have multiple copies of React loaded\nSee 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 <Component /> 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); + } + function ChildReconciler(shouldTrackSideEffects) { + function deleteChild(returnFiber, childToDelete) { + if (!shouldTrackSideEffects) { + return; + } + var deletions = returnFiber.deletions; + if (deletions === null) { + returnFiber.deletions = [childToDelete]; + returnFiber.flags |= ChildDeletion; + } else { + deletions.push(childToDelete); + } + } + function deleteRemainingChildren(returnFiber, currentFirstChild) { + if (!shouldTrackSideEffects) { + return null; + } + var childToDelete = currentFirstChild; + while (childToDelete !== null) { + deleteChild(returnFiber, childToDelete); + childToDelete = childToDelete.sibling; + } + return null; + } + function mapRemainingChildren(returnFiber, currentFirstChild) { + 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) { + var clone = createWorkInProgress(fiber, pendingProps); + clone.index = 0; + clone.sibling = null; + return clone; + } + function placeChild(newFiber, lastPlacedIndex, newIndex) { + newFiber.index = newIndex; + if (!shouldTrackSideEffects) { + newFiber.flags |= Forked; + return lastPlacedIndex; + } + var current2 = newFiber.alternate; + if (current2 !== null) { + var oldIndex = current2.index; + if (oldIndex < lastPlacedIndex) { + newFiber.flags |= Placement; + return lastPlacedIndex; + } else { + return oldIndex; + } + } else { + newFiber.flags |= Placement; + return lastPlacedIndex; + } + } + function placeSingleChild(newFiber) { + if (shouldTrackSideEffects && newFiber.alternate === null) { + newFiber.flags |= Placement; + } + return newFiber; + } + function updateTextNode(returnFiber, current2, textContent, lanes) { + if (current2 === null || current2.tag !== HostText) { + var created = createFiberFromText(textContent, returnFiber.mode, lanes); + created.return = returnFiber; + return created; + } else { + var existing = useFiber(current2, textContent); + existing.return = returnFiber; + return existing; + } + } + function updateElement(returnFiber, current2, element, lanes) { + var elementType = element.type; + if (elementType === REACT_FRAGMENT_TYPE) { + return updateFragment2(returnFiber, current2, element.props.children, lanes, element.key); + } + if (current2 !== null) { + if (current2.elementType === elementType || isCompatibleFamilyForHotReloading(current2, element) || typeof elementType === "object" && elementType !== null && elementType.$$typeof === REACT_LAZY_TYPE && resolveLazy(elementType) === current2.type) { + var existing = useFiber(current2, element.props); + existing.ref = coerceRef(returnFiber, current2, element); + existing.return = returnFiber; + { + existing._debugSource = element._source; + existing._debugOwner = element._owner; + } + return existing; + } + } + var created = createFiberFromElement(element, returnFiber.mode, lanes); + created.ref = coerceRef(returnFiber, current2, element); + created.return = returnFiber; + return created; + } + function updatePortal(returnFiber, current2, portal, lanes) { + if (current2 === null || current2.tag !== HostPortal || current2.stateNode.containerInfo !== portal.containerInfo || current2.stateNode.implementation !== portal.implementation) { + var created = createFiberFromPortal(portal, returnFiber.mode, lanes); + created.return = returnFiber; + return created; + } else { + var existing = useFiber(current2, portal.children || []); + existing.return = returnFiber; + return existing; + } + } + function updateFragment2(returnFiber, current2, fragment, lanes, key) { + if (current2 === null || current2.tag !== Fragment) { + var created = createFiberFromFragment(fragment, returnFiber.mode, lanes, key); + created.return = returnFiber; + return created; + } else { + var existing = useFiber(current2, fragment); + existing.return = returnFiber; + return existing; + } + } + function createChild(returnFiber, newChild, lanes) { + if (typeof newChild === "string" && newChild !== "" || typeof newChild === "number") { + 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) { + var key = oldFiber !== null ? oldFiber.key : null; + if (typeof newChild === "string" && newChild !== "" || typeof newChild === "number") { + 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 updateFragment2(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") { + 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 updateFragment2(returnFiber, _matchedFiber3, newChild, lanes, null); + } + throwOnInvalidObjectType(returnFiber, newChild); + } + { + if (typeof newChild === "function") { + warnOnFunctionType(returnFiber); + } + } + return null; + } + 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 \u2014 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) { + { + 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) { + if (oldFiber === null) { + oldFiber = nextOldFiber; + } + break; + } + if (shouldTrackSideEffects) { + if (oldFiber && newFiber.alternate === null) { + deleteChild(returnFiber, oldFiber); + } + } + lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); + if (previousNewFiber === null) { + resultingFirstChild = newFiber; + } else { + previousNewFiber.sibling = newFiber; + } + previousNewFiber = newFiber; + oldFiber = nextOldFiber; + } + if (newIdx === newChildren.length) { + deleteRemainingChildren(returnFiber, oldFiber); + if (getIsHydrating()) { + var numberOfForks = newIdx; + pushTreeFork(returnFiber, numberOfForks); + } + return resultingFirstChild; + } + if (oldFiber === null) { + for (;newIdx < newChildren.length; newIdx++) { + var _newFiber = createChild(returnFiber, newChildren[newIdx], lanes); + if (_newFiber === null) { + continue; + } + lastPlacedIndex = placeChild(_newFiber, lastPlacedIndex, newIdx); + if (previousNewFiber === null) { + resultingFirstChild = _newFiber; + } else { + previousNewFiber.sibling = _newFiber; + } + previousNewFiber = _newFiber; + } + if (getIsHydrating()) { + var _numberOfForks = newIdx; + pushTreeFork(returnFiber, _numberOfForks); + } + return resultingFirstChild; + } + var existingChildren = mapRemainingChildren(returnFiber, oldFiber); + for (;newIdx < newChildren.length; newIdx++) { + var _newFiber2 = updateFromMap(existingChildren, returnFiber, newIdx, newChildren[newIdx], lanes); + if (_newFiber2 !== null) { + if (shouldTrackSideEffects) { + if (_newFiber2.alternate !== null) { + 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) { + existingChildren.forEach(function(child2) { + return deleteChild(returnFiber, child2); + }); + } + if (getIsHydrating()) { + var _numberOfForks2 = newIdx; + pushTreeFork(returnFiber, _numberOfForks2); + } + return resultingFirstChild; + } + function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildrenIterable, lanes) { + 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."); + } + { + if (typeof Symbol === "function" && 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; + } + if (newChildrenIterable.entries === iteratorFn) { + if (!didWarnAboutMaps) { + error("Using Maps as children is not supported. Use an array of keyed ReactElements instead."); + } + didWarnAboutMaps = true; + } + 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) { + if (oldFiber === null) { + oldFiber = nextOldFiber; + } + break; + } + if (shouldTrackSideEffects) { + if (oldFiber && newFiber.alternate === null) { + deleteChild(returnFiber, oldFiber); + } + } + lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); + if (previousNewFiber === null) { + resultingFirstChild = newFiber; + } else { + previousNewFiber.sibling = newFiber; + } + previousNewFiber = newFiber; + oldFiber = nextOldFiber; + } + if (step.done) { + deleteRemainingChildren(returnFiber, oldFiber); + if (getIsHydrating()) { + var numberOfForks = newIdx; + pushTreeFork(returnFiber, numberOfForks); + } + return resultingFirstChild; + } + if (oldFiber === null) { + 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) { + resultingFirstChild = _newFiber3; + } else { + previousNewFiber.sibling = _newFiber3; + } + previousNewFiber = _newFiber3; + } + if (getIsHydrating()) { + var _numberOfForks3 = newIdx; + pushTreeFork(returnFiber, _numberOfForks3); + } + return resultingFirstChild; + } + var existingChildren = mapRemainingChildren(returnFiber, oldFiber); + 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) { + 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) { + existingChildren.forEach(function(child2) { + return deleteChild(returnFiber, child2); + }); + } + if (getIsHydrating()) { + var _numberOfForks4 = newIdx; + pushTreeFork(returnFiber, _numberOfForks4); + } + return resultingFirstChild; + } + function reconcileSingleTextNode(returnFiber, currentFirstChild, textContent, lanes) { + if (currentFirstChild !== null && currentFirstChild.tag === HostText) { + deleteRemainingChildren(returnFiber, currentFirstChild.sibling); + var existing = useFiber(currentFirstChild, textContent); + existing.return = returnFiber; + return existing; + } + 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) { + 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 || isCompatibleFamilyForHotReloading(child, element) || 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; + } + } + 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) { + 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; + } + function reconcileChildFibers2(returnFiber, currentFirstChild, newChild, lanes) { + var isUnkeyedTopLevelFragment = typeof newChild === "object" && newChild !== null && newChild.type === REACT_FRAGMENT_TYPE && newChild.key === null; + if (isUnkeyedTopLevelFragment) { + newChild = newChild.props.children; + } + 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; + return reconcileChildFibers2(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); + } + } + return deleteRemainingChildren(returnFiber, currentFirstChild); + } + return reconcileChildFibers2; + } + var reconcileChildFibers = ChildReconciler(true); + var mountChildFibers = ChildReconciler(false); + function cloneChildFibers(current2, workInProgress2) { + if (current2 !== null && workInProgress2.child !== current2.child) { + throw new Error("Resuming work not yet implemented."); + } + if (workInProgress2.child === null) { + return; + } + var currentChild = workInProgress2.child; + var newChild = createWorkInProgress(currentChild, currentChild.pendingProps); + workInProgress2.child = newChild; + newChild.return = workInProgress2; + while (currentChild.sibling !== null) { + currentChild = currentChild.sibling; + newChild = newChild.sibling = createWorkInProgress(currentChild, currentChild.pendingProps); + newChild.return = workInProgress2; + } + newChild.sibling = null; + } + function resetChildFibers(workInProgress2, lanes) { + var child = workInProgress2.child; + while (child !== null) { + resetWorkInProgress(child, lanes); + child = child.sibling; + } + } + var valueCursor = createCursor(null); + var rendererSigil; + { + rendererSigil = {}; + } + var currentlyRenderingFiber = null; + var lastContextDependency = null; + var lastFullyObservedContext = null; + var isDisallowedContextReadInDEV = false; + function resetContextDependencies() { + currentlyRenderingFiber = null; + lastContextDependency = null; + lastFullyObservedContext = null; + { + isDisallowedContextReadInDEV = false; + } + } + function enterDisallowedContextReadInDEV() { + { + isDisallowedContextReadInDEV = true; + } + } + function exitDisallowedContextReadInDEV() { + { + isDisallowedContextReadInDEV = false; + } + } + function pushProvider(providerFiber, context, nextValue) { + { + 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; + } + } + } + function popProvider(context, providerFiber) { + var currentValue = valueCursor.current; + pop(valueCursor, providerFiber); + { + { + context._currentValue = currentValue; + } + } + } + function scheduleContextWorkOnParentPath(parent, renderLanes2, propagationRoot) { + var node = parent; + while (node !== null) { + var alternate = node.alternate; + if (!isSubsetOfLanes(node.childLanes, renderLanes2)) { + node.childLanes = mergeLanes(node.childLanes, renderLanes2); + if (alternate !== null) { + alternate.childLanes = mergeLanes(alternate.childLanes, renderLanes2); + } + } else if (alternate !== null && !isSubsetOfLanes(alternate.childLanes, renderLanes2)) { + alternate.childLanes = mergeLanes(alternate.childLanes, renderLanes2); + } + 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(workInProgress2, context, renderLanes2) { + { + propagateContextChange_eager(workInProgress2, context, renderLanes2); + } + } + function propagateContextChange_eager(workInProgress2, context, renderLanes2) { + var fiber = workInProgress2.child; + if (fiber !== null) { + fiber.return = workInProgress2; + } + while (fiber !== null) { + var nextFiber = undefined; + var list = fiber.dependencies; + if (list !== null) { + nextFiber = fiber.child; + var dependency = list.firstContext; + while (dependency !== null) { + if (dependency.context === context) { + if (fiber.tag === ClassComponent) { + var lane = pickArbitraryLane(renderLanes2); + var update = createUpdate(NoTimestamp, lane); + update.tag = ForceUpdate; + var updateQueue = fiber.updateQueue; + if (updateQueue === null) + ; + else { + var sharedQueue = updateQueue.shared; + var pending = sharedQueue.pending; + if (pending === null) { + update.next = update; + } else { + update.next = pending.next; + pending.next = update; + } + sharedQueue.pending = update; + } + } + fiber.lanes = mergeLanes(fiber.lanes, renderLanes2); + var alternate = fiber.alternate; + if (alternate !== null) { + alternate.lanes = mergeLanes(alternate.lanes, renderLanes2); + } + scheduleContextWorkOnParentPath(fiber.return, renderLanes2, workInProgress2); + list.lanes = mergeLanes(list.lanes, renderLanes2); + break; + } + dependency = dependency.next; + } + } else if (fiber.tag === ContextProvider) { + nextFiber = fiber.type === workInProgress2.type ? null : fiber.child; + } else if (fiber.tag === DehydratedFragment) { + 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, renderLanes2); + var _alternate = parentSuspense.alternate; + if (_alternate !== null) { + _alternate.lanes = mergeLanes(_alternate.lanes, renderLanes2); + } + scheduleContextWorkOnParentPath(parentSuspense, renderLanes2, workInProgress2); + nextFiber = fiber.sibling; + } else { + nextFiber = fiber.child; + } + if (nextFiber !== null) { + nextFiber.return = fiber; + } else { + nextFiber = fiber; + while (nextFiber !== null) { + if (nextFiber === workInProgress2) { + nextFiber = null; + break; + } + var sibling = nextFiber.sibling; + if (sibling !== null) { + sibling.return = nextFiber.return; + nextFiber = sibling; + break; + } + nextFiber = nextFiber.return; + } + } + fiber = nextFiber; + } + } + function prepareToReadContext(workInProgress2, renderLanes2) { + currentlyRenderingFiber = workInProgress2; + lastContextDependency = null; + lastFullyObservedContext = null; + var dependencies = workInProgress2.dependencies; + if (dependencies !== null) { + { + var firstContext = dependencies.firstContext; + if (firstContext !== null) { + if (includesSomeLane(dependencies.lanes, renderLanes2)) { + markWorkInProgressReceivedUpdate(); + } + dependencies.firstContext = null; + } + } + } + } + function readContext(context) { + { + 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 = context._currentValue; + if (lastFullyObservedContext === context) + ; + else { + var contextItem = { + 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()."); + } + lastContextDependency = contextItem; + currentlyRenderingFiber.dependencies = { + lanes: NoLanes, + firstContext: contextItem + }; + } else { + lastContextDependency = lastContextDependency.next = contextItem; + } + } + return value; + } + var concurrentQueues = null; + function pushConcurrentUpdateQueue(queue) { + if (concurrentQueues === null) { + concurrentQueues = [queue]; + } else { + concurrentQueues.push(queue); + } + } + function finishQueueingConcurrentUpdates() { + if (concurrentQueues !== null) { + for (var i = 0;i < concurrentQueues.length; i++) { + var queue = concurrentQueues[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; + } + } + concurrentQueues = null; + } + } + function enqueueConcurrentHookUpdate(fiber, queue, update, lane) { + var interleaved = queue.interleaved; + if (interleaved === null) { + update.next = update; + pushConcurrentUpdateQueue(queue); + } else { + update.next = interleaved.next; + interleaved.next = update; + } + queue.interleaved = update; + return markUpdateLaneFromFiberToRoot(fiber, lane); + } + function enqueueConcurrentHookUpdateAndEagerlyBailout(fiber, queue, update, lane) { + var interleaved = queue.interleaved; + if (interleaved === null) { + update.next = update; + pushConcurrentUpdateQueue(queue); + } else { + update.next = interleaved.next; + interleaved.next = update; + } + queue.interleaved = update; + } + function enqueueConcurrentClassUpdate(fiber, queue, update, lane) { + var interleaved = queue.interleaved; + if (interleaved === null) { + update.next = update; + pushConcurrentUpdateQueue(queue); + } else { + update.next = interleaved.next; + interleaved.next = update; + } + queue.interleaved = update; + return markUpdateLaneFromFiberToRoot(fiber, lane); + } + function enqueueConcurrentRenderForLane(fiber, lane) { + return markUpdateLaneFromFiberToRoot(fiber, lane); + } + var unsafe_markUpdateLaneFromFiberToRoot = markUpdateLaneFromFiberToRoot; + function markUpdateLaneFromFiberToRoot(sourceFiber, lane) { + 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); + } + } + 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 root2 = node.stateNode; + return root2; + } else { + return null; + } + } + var UpdateState = 0; + var ReplaceState = 1; + var ForceUpdate = 2; + var CaptureUpdate = 3; + 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(current2, workInProgress2) { + var queue = workInProgress2.updateQueue; + var currentQueue = current2.updateQueue; + if (queue === currentQueue) { + var clone = { + baseState: currentQueue.baseState, + firstBaseUpdate: currentQueue.firstBaseUpdate, + lastBaseUpdate: currentQueue.lastBaseUpdate, + shared: currentQueue.shared, + effects: currentQueue.effects + }; + workInProgress2.updateQueue = clone; + } + } + function createUpdate(eventTime, lane) { + var update = { + eventTime, + lane, + tag: UpdateState, + payload: null, + callback: null, + next: null + }; + return update; + } + function enqueueUpdate(fiber, update, lane) { + var updateQueue = fiber.updateQueue; + if (updateQueue === null) { + return null; + } + var sharedQueue = updateQueue.shared; + { + 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; + } + } + if (isUnsafeClassRenderPhaseUpdate()) { + var pending = sharedQueue.pending; + if (pending === null) { + update.next = update; + } else { + update.next = pending.next; + pending.next = update; + } + sharedQueue.pending = update; + return unsafe_markUpdateLaneFromFiberToRoot(fiber, lane); + } else { + return enqueueConcurrentClassUpdate(fiber, sharedQueue, update, lane); + } + } + function entangleTransitions(root2, fiber, lane) { + var updateQueue = fiber.updateQueue; + if (updateQueue === null) { + return; + } + var sharedQueue = updateQueue.shared; + if (isTransitionLane(lane)) { + var queueLanes = sharedQueue.lanes; + queueLanes = intersectLanes(queueLanes, root2.pendingLanes); + var newQueueLanes = mergeLanes(queueLanes, lane); + sharedQueue.lanes = newQueueLanes; + markRootEntangled(root2, newQueueLanes); + } + } + function enqueueCapturedUpdate(workInProgress2, capturedUpdate) { + var queue = workInProgress2.updateQueue; + var current2 = workInProgress2.alternate; + if (current2 !== null) { + var currentQueue = current2.updateQueue; + if (queue === currentQueue) { + var newFirst = null; + var newLast = null; + var firstBaseUpdate = queue.firstBaseUpdate; + if (firstBaseUpdate !== null) { + 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); + if (newLast === null) { + newFirst = newLast = capturedUpdate; + } else { + newLast.next = capturedUpdate; + newLast = capturedUpdate; + } + } else { + newFirst = newLast = capturedUpdate; + } + queue = { + baseState: currentQueue.baseState, + firstBaseUpdate: newFirst, + lastBaseUpdate: newLast, + shared: currentQueue.shared, + effects: currentQueue.effects + }; + workInProgress2.updateQueue = queue; + return; + } + } + var lastBaseUpdate = queue.lastBaseUpdate; + if (lastBaseUpdate === null) { + queue.firstBaseUpdate = capturedUpdate; + } else { + lastBaseUpdate.next = capturedUpdate; + } + queue.lastBaseUpdate = capturedUpdate; + } + function getStateFromUpdate(workInProgress2, queue, update, prevState, nextProps, instance) { + switch (update.tag) { + case ReplaceState: { + var payload = update.payload; + if (typeof payload === "function") { + { + enterDisallowedContextReadInDEV(); + } + var nextState = payload.call(instance, prevState, nextProps); + { + if (workInProgress2.mode & StrictLegacyMode) { + setIsStrictModeForDevtools(true); + try { + payload.call(instance, prevState, nextProps); + } finally { + setIsStrictModeForDevtools(false); + } + } + exitDisallowedContextReadInDEV(); + } + return nextState; + } + return payload; + } + case CaptureUpdate: { + workInProgress2.flags = workInProgress2.flags & ~ShouldCapture | DidCapture; + } + case UpdateState: { + var _payload = update.payload; + var partialState; + if (typeof _payload === "function") { + { + enterDisallowedContextReadInDEV(); + } + partialState = _payload.call(instance, prevState, nextProps); + { + if (workInProgress2.mode & StrictLegacyMode) { + setIsStrictModeForDevtools(true); + try { + _payload.call(instance, prevState, nextProps); + } finally { + setIsStrictModeForDevtools(false); + } + } + exitDisallowedContextReadInDEV(); + } + } else { + partialState = _payload; + } + if (partialState === null || partialState === undefined) { + return prevState; + } + return assign({}, prevState, partialState); + } + case ForceUpdate: { + hasForceUpdate = true; + return prevState; + } + } + return prevState; + } + function processUpdateQueue(workInProgress2, props, instance, renderLanes2) { + var queue = workInProgress2.updateQueue; + hasForceUpdate = false; + { + currentlyProcessingQueue = queue.shared; + } + var firstBaseUpdate = queue.firstBaseUpdate; + var lastBaseUpdate = queue.lastBaseUpdate; + var pendingQueue = queue.shared.pending; + if (pendingQueue !== null) { + queue.shared.pending = null; + var lastPendingUpdate = pendingQueue; + var firstPendingUpdate = lastPendingUpdate.next; + lastPendingUpdate.next = null; + if (lastBaseUpdate === null) { + firstBaseUpdate = firstPendingUpdate; + } else { + lastBaseUpdate.next = firstPendingUpdate; + } + lastBaseUpdate = lastPendingUpdate; + var current2 = workInProgress2.alternate; + if (current2 !== null) { + var currentQueue = current2.updateQueue; + var currentLastBaseUpdate = currentQueue.lastBaseUpdate; + if (currentLastBaseUpdate !== lastBaseUpdate) { + if (currentLastBaseUpdate === null) { + currentQueue.firstBaseUpdate = firstPendingUpdate; + } else { + currentLastBaseUpdate.next = firstPendingUpdate; + } + currentQueue.lastBaseUpdate = lastPendingUpdate; + } + } + } + if (firstBaseUpdate !== null) { + var newState = queue.baseState; + 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(renderLanes2, updateLane)) { + 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; + } + newLanes = mergeLanes(newLanes, updateLane); + } else { + if (newLastBaseUpdate !== null) { + var _clone = { + eventTime: updateEventTime, + lane: NoLane, + tag: update.tag, + payload: update.payload, + callback: update.callback, + next: null + }; + newLastBaseUpdate = newLastBaseUpdate.next = _clone; + } + newState = getStateFromUpdate(workInProgress2, queue, update, newState, props, instance); + var callback = update.callback; + if (callback !== null && update.lane !== NoLane) { + workInProgress2.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 { + var _lastPendingUpdate = pendingQueue; + 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; + 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.shared.lanes = NoLanes; + } + markSkippedUpdateLanes(newLanes); + workInProgress2.lanes = newLanes; + workInProgress2.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) { + 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 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(rootInstanceStackCursor, nextRootInstance, fiber); + push(contextFiberStackCursor, fiber, fiber); + push(contextStackCursor$1, NO_CONTEXT, fiber); + var nextRootContext = getRootHostContext(nextRootInstance); + 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); + if (context === nextContext) { + return; + } + push(contextFiberStackCursor, fiber, fiber); + push(contextStackCursor$1, nextContext, fiber); + } + function popHostContext(fiber) { + if (contextFiberStackCursor.current !== fiber) { + return; + } + pop(contextStackCursor$1, fiber); + pop(contextFiberStackCursor, fiber); + } + var DefaultSuspenseContext = 0; + var SubtreeSuspenseContextMask = 1; + var InvisibleParentSuspenseContext = 1; + 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(workInProgress2, hasInvisibleParent) { + var nextState = workInProgress2.memoizedState; + if (nextState !== null) { + if (nextState.dehydrated !== null) { + return true; + } + return false; + } + var props = workInProgress2.memoizedProps; + { + return true; + } + } + 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 && 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; + var HasEffect = 1; + var Insertion = 2; + var Layout = 4; + var Passive$1 = 8; + var workInProgressSources = []; + function resetWorkInProgressVersions() { + for (var i = 0;i < workInProgressSources.length; i++) { + var mutableSource = workInProgressSources[i]; + { + mutableSource._workInProgressVersionPrimary = null; + } + } + workInProgressSources.length = 0; + } + function registerMutableSourceForHydration(root2, mutableSource) { + var getVersion = mutableSource._getVersion; + var version = getVersion(mutableSource._source); + if (root2.mutableSourceEagerHydrationData == null) { + root2.mutableSourceEagerHydrationData = [mutableSource, version]; + } else { + root2.mutableSourceEagerHydrationData.push(mutableSource, version); + } + } + var { ReactCurrentDispatcher: ReactCurrentDispatcher$1, ReactCurrentBatchConfig: ReactCurrentBatchConfig$2 } = ReactSharedInternals; + var didWarnAboutMismatchedHooksForComponent; + var didWarnUncachedGetSnapshot; + { + didWarnAboutMismatchedHooksForComponent = new Set; + } + var renderLanes = NoLanes; + var currentlyRenderingFiber$1 = null; + var currentHook = null; + var workInProgressHook = null; + var didScheduleRenderPhaseUpdate = false; + var didScheduleRenderPhaseUpdateDuringThisPass = false; + var localIdCounter = 0; + var globalClientIdCounter = 0; + var RE_RENDER_LIMIT = 25; + var currentHookNameInDev = null; + var hookTypesDev = null; + var hookTypesUpdateIndexDev = -1; + 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)) { + 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; + 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:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem."); + } + function areHookInputsEqual(nextDeps, prevDeps) { + { + if (ignorePreviousDependencies) { + 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; + } + { + 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\nPrevious: %s\nIncoming: %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(current2, workInProgress2, Component, props, secondArg, nextRenderLanes) { + renderLanes = nextRenderLanes; + currentlyRenderingFiber$1 = workInProgress2; + { + hookTypesDev = current2 !== null ? current2._debugHookTypes : null; + hookTypesUpdateIndexDev = -1; + ignorePreviousDependencies = current2 !== null && current2.type !== workInProgress2.type; + } + workInProgress2.memoizedState = null; + workInProgress2.updateQueue = null; + workInProgress2.lanes = NoLanes; + { + if (current2 !== null && current2.memoizedState !== null) { + ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV; + } else if (hookTypesDev !== null) { + ReactCurrentDispatcher$1.current = HooksDispatcherOnMountWithHookTypesInDEV; + } else { + ReactCurrentDispatcher$1.current = HooksDispatcherOnMountInDEV; + } + } + var children = Component(props, secondArg); + if (didScheduleRenderPhaseUpdateDuringThisPass) { + 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; + { + ignorePreviousDependencies = false; + } + currentHook = null; + workInProgressHook = null; + workInProgress2.updateQueue = null; + { + hookTypesUpdateIndexDev = -1; + } + ReactCurrentDispatcher$1.current = HooksDispatcherOnRerenderInDEV; + children = Component(props, secondArg); + } while (didScheduleRenderPhaseUpdateDuringThisPass); + } + ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; + { + workInProgress2._debugHookTypes = hookTypesDev; + } + var didRenderTooFewHooks = currentHook !== null && currentHook.next !== null; + renderLanes = NoLanes; + currentlyRenderingFiber$1 = null; + currentHook = null; + workInProgressHook = null; + { + currentHookNameInDev = null; + hookTypesDev = null; + hookTypesUpdateIndexDev = -1; + if (current2 !== null && (current2.flags & StaticMask) !== (workInProgress2.flags & StaticMask) && (current2.mode & ConcurrentMode) !== NoMode) { + error("Internal React error: Expected static flag was missing. Please notify the React team."); + } + } + didScheduleRenderPhaseUpdate = false; + if (didRenderTooFewHooks) { + throw new Error("Rendered fewer hooks than expected. This may be caused by an accidental early return statement."); + } + return children; + } + function checkDidRenderIdHook() { + var didRenderIdHook = localIdCounter !== 0; + localIdCounter = 0; + return didRenderIdHook; + } + function bailoutHooks(current2, workInProgress2, lanes) { + workInProgress2.updateQueue = current2.updateQueue; + if ((workInProgress2.mode & StrictEffectsMode) !== NoMode) { + workInProgress2.flags &= ~(MountPassiveDev | MountLayoutDev | Passive | Update); + } else { + workInProgress2.flags &= ~(Passive | Update); + } + current2.lanes = removeLanes(current2.lanes, lanes); + } + function resetHooksAfterThrow() { + ReactCurrentDispatcher$1.current = ContextOnlyDispatcher; + if (didScheduleRenderPhaseUpdate) { + 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) { + currentlyRenderingFiber$1.memoizedState = workInProgressHook = hook; + } else { + workInProgressHook = workInProgressHook.next = hook; + } + return workInProgressHook; + } + function updateWorkInProgressHook() { + var nextCurrentHook; + if (currentHook === null) { + var current2 = currentlyRenderingFiber$1.alternate; + if (current2 !== null) { + nextCurrentHook = current2.memoizedState; + } else { + nextCurrentHook = null; + } + } else { + nextCurrentHook = currentHook.next; + } + var nextWorkInProgressHook; + if (workInProgressHook === null) { + nextWorkInProgressHook = currentlyRenderingFiber$1.memoizedState; + } else { + nextWorkInProgressHook = workInProgressHook.next; + } + if (nextWorkInProgressHook !== null) { + workInProgressHook = nextWorkInProgressHook; + nextWorkInProgressHook = workInProgressHook.next; + currentHook = nextCurrentHook; + } else { + 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) { + currentlyRenderingFiber$1.memoizedState = workInProgressHook = newHook; + } else { + workInProgressHook = workInProgressHook.next = newHook; + } + } + return workInProgressHook; + } + function createFunctionComponentUpdateQueue() { + return { + lastEffect: null, + stores: null + }; + } + function basicStateReducer(state, action) { + 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 current2 = currentHook; + var baseQueue = current2.baseQueue; + var pendingQueue = queue.pending; + if (pendingQueue !== null) { + if (baseQueue !== null) { + var baseFirst = baseQueue.next; + var pendingFirst = pendingQueue.next; + baseQueue.next = pendingFirst; + pendingQueue.next = baseFirst; + } + { + if (current2.baseQueue !== baseQueue) { + error("Internal error: Expected work-in-progress queue to be a clone. This is a bug in React."); + } + } + current2.baseQueue = baseQueue = pendingQueue; + queue.pending = null; + } + if (baseQueue !== null) { + var first = baseQueue.next; + var newState = current2.baseState; + var newBaseState = null; + var newBaseQueueFirst = null; + var newBaseQueueLast = null; + var update = first; + do { + var updateLane = update.lane; + if (!isSubsetOfLanes(renderLanes, updateLane)) { + 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; + } + currentlyRenderingFiber$1.lanes = mergeLanes(currentlyRenderingFiber$1.lanes, updateLane); + markSkippedUpdateLanes(updateLane); + } else { + if (newBaseQueueLast !== null) { + var _clone = { + lane: NoLane, + action: update.action, + hasEagerState: update.hasEagerState, + eagerState: update.eagerState, + next: null + }; + newBaseQueueLast = newBaseQueueLast.next = _clone; + } + if (update.hasEagerState) { + 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; + } + if (!objectIs(newState, hook.memoizedState)) { + markWorkInProgressReceivedUpdate(); + } + hook.memoizedState = newState; + hook.baseState = newBaseState; + hook.baseQueue = newBaseQueueLast; + queue.lastRenderedState = newState; + } + 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 = 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; + var dispatch = queue.dispatch; + var lastRenderPhaseUpdate = queue.pending; + var newState = hook.memoizedState; + if (lastRenderPhaseUpdate !== null) { + queue.pending = null; + var firstRenderPhaseUpdate = lastRenderPhaseUpdate.next; + var update = firstRenderPhaseUpdate; + do { + var action = update.action; + newState = reducer(newState, action); + update = update.next; + } while (update !== firstRenderPhaseUpdate); + if (!objectIs(newState, hook.memoizedState)) { + markWorkInProgressReceivedUpdate(); + } + hook.memoizedState = newState; + if (hook.baseQueue === null) { + hook.baseState = newState; + } + queue.lastRenderedState = newState; + } + return [newState, dispatch]; + } + function mountMutableSource(source, getSnapshot, subscribe) { + { + return; + } + } + function updateMutableSource(source, getSnapshot, subscribe) { + { + return; + } + } + function mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { + var fiber = currentlyRenderingFiber$1; + var hook = mountWorkInProgressHook(); + var nextSnapshot; + var isHydrating2 = getIsHydrating(); + if (isHydrating2) { + 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; + } + } + } + var root2 = getWorkInProgressRoot(); + if (root2 === null) { + throw new Error("Expected a work-in-progress root. This is a bug in React. Please file an issue."); + } + if (!includesBlockingLane(root2, renderLanes)) { + pushStoreConsistencyCheck(fiber, getSnapshot, nextSnapshot); + } + } + hook.memoizedState = nextSnapshot; + var inst = { + value: nextSnapshot, + getSnapshot + }; + hook.queue = inst; + mountEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [subscribe]); + 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(); + 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]); + if (inst.getSnapshot !== getSnapshot || snapshotChanged || workInProgressHook !== null && workInProgressHook.memoizedState.tag & HasEffect) { + fiber.flags |= Passive; + pushEffect(HasEffect | Passive$1, updateStoreInstance.bind(null, fiber, inst, nextSnapshot, getSnapshot), undefined, null); + var root2 = getWorkInProgressRoot(); + if (root2 === null) { + throw new Error("Expected a work-in-progress root. This is a bug in React. Please file an issue."); + } + if (!includesBlockingLane(root2, renderLanes)) { + pushStoreConsistencyCheck(fiber, getSnapshot, nextSnapshot); + } + } + return nextSnapshot; + } + function pushStoreConsistencyCheck(fiber, getSnapshot, renderedSnapshot) { + fiber.flags |= StoreConsistency; + var check = { + 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) { + inst.value = nextSnapshot; + inst.getSnapshot = getSnapshot; + if (checkIfSnapshotChanged(inst)) { + forceStoreRerender(fiber); + } + } + function subscribeToStore(fiber, inst, subscribe) { + var handleStoreChange = function() { + if (checkIfSnapshotChanged(inst)) { + forceStoreRerender(fiber); + } + }; + return subscribe(handleStoreChange); + } + function checkIfSnapshotChanged(inst) { + var latestGetSnapshot = inst.getSnapshot; + var prevValue = inst.value; + try { + var nextValue = latestGetSnapshot(); + return !objectIs(prevValue, nextValue); + } catch (error2) { + return true; + } + } + function forceStoreRerender(fiber) { + var root2 = enqueueConcurrentRenderForLane(fiber, SyncLane); + if (root2 !== null) { + scheduleUpdateOnFiber(root2, fiber, SyncLane, NoTimestamp); + } + } + function mountState(initialState) { + var hook = mountWorkInProgressHook(); + if (typeof initialState === "function") { + 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, + create, + destroy, + deps, + 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"); + } + } + 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"); + } + } + var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null; + return updateEffectImpl(Update, Layout, imperativeHandleEffect.bind(null, create, ref), effectDeps); + } + function mountDebugValue(value, formatterFn) { + } + 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) { + 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 hook = mountWorkInProgressHook(); + hook.memoizedState = value; + return value; + } + function updateDeferredValue(value) { + var hook = updateWorkInProgressHook(); + var resolvedCurrentHook = currentHook; + var prevValue = resolvedCurrentHook.memoizedState; + return updateDeferredValueImpl(hook, prevValue, value); + } + function rerenderDeferredValue(value) { + var hook = updateWorkInProgressHook(); + if (currentHook === null) { + hook.memoizedState = value; + return value; + } else { + var prevValue = currentHook.memoizedState; + return updateDeferredValueImpl(hook, prevValue, value); + } + } + function updateDeferredValueImpl(hook, prevValue, value) { + var shouldDeferValue = !includesOnlyNonUrgentLanes(renderLanes); + if (shouldDeferValue) { + if (!objectIs(value, prevValue)) { + var deferredLane = claimNextTransitionLane(); + currentlyRenderingFiber$1.lanes = mergeLanes(currentlyRenderingFiber$1.lanes, deferredLane); + markSkippedUpdateLanes(deferredLane); + hook.baseState = true; + } + return prevValue; + } else { + if (hook.baseState) { + hook.baseState = false; + markWorkInProgressReceivedUpdate(); + } + hook.memoizedState = value; + return value; + } + } + function startTransition(setPending, callback, options2) { + var previousPriority = getCurrentUpdatePriority(); + setCurrentUpdatePriority(higherEventPriority(previousPriority, ContinuousEventPriority)); + setPending(true); + var prevTransition = ReactCurrentBatchConfig$2.transition; + ReactCurrentBatchConfig$2.transition = {}; + var currentTransition = ReactCurrentBatchConfig$2.transition; + { + ReactCurrentBatchConfig$2.transition._updatedFibers = new Set; + } + try { + setPending(false); + callback(); + } finally { + setCurrentUpdatePriority(previousPriority); + ReactCurrentBatchConfig$2.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 _mountState = mountState(false), isPending = _mountState[0], setPending = _mountState[1]; + var start = startTransition.bind(null, setPending); + var hook = mountWorkInProgressHook(); + hook.memoizedState = start; + return [isPending, start]; + } + function updateTransition() { + var _updateState = updateState(), isPending = _updateState[0]; + var hook = updateWorkInProgressHook(); + var start = hook.memoizedState; + return [isPending, start]; + } + function rerenderTransition() { + var _rerenderState = rerenderState(), isPending = _rerenderState[0]; + var hook = updateWorkInProgressHook(); + var start = hook.memoizedState; + return [isPending, start]; + } + var isUpdatingOpaqueValueInRenderPhase = false; + function getIsUpdatingOpaqueValueInRenderPhaseInDEV() { + { + return isUpdatingOpaqueValueInRenderPhase; + } + } + function mountId() { + var hook = mountWorkInProgressHook(); + var root2 = getWorkInProgressRoot(); + var identifierPrefix = root2.identifierPrefix; + var id; + if (getIsHydrating()) { + var treeId = getTreeId(); + id = ":" + identifierPrefix + "R" + treeId; + var localId = localIdCounter++; + if (localId > 0) { + id += "H" + localId.toString(32); + } + id += ":"; + } else { + 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, + action, + hasEagerState: false, + eagerState: null, + next: null + }; + if (isRenderPhaseUpdate(fiber)) { + enqueueRenderPhaseUpdate(queue, update); + } else { + var root2 = enqueueConcurrentHookUpdate(fiber, queue, update, lane); + if (root2 !== null) { + var eventTime = requestEventTime(); + scheduleUpdateOnFiber(root2, fiber, lane, eventTime); + entangleTransitionUpdate(root2, 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, + action, + hasEagerState: false, + eagerState: null, + next: null + }; + if (isRenderPhaseUpdate(fiber)) { + enqueueRenderPhaseUpdate(queue, update); + } else { + var alternate = fiber.alternate; + if (fiber.lanes === NoLanes && (alternate === null || alternate.lanes === NoLanes)) { + 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); + update.hasEagerState = true; + update.eagerState = eagerState; + if (objectIs(eagerState, currentState)) { + enqueueConcurrentHookUpdateAndEagerlyBailout(fiber, queue, update, lane); + return; + } + } catch (error2) { + } finally { + { + ReactCurrentDispatcher$1.current = prevDispatcher; + } + } + } + } + var root2 = enqueueConcurrentHookUpdate(fiber, queue, update, lane); + if (root2 !== null) { + var eventTime = requestEventTime(); + scheduleUpdateOnFiber(root2, fiber, lane, eventTime); + entangleTransitionUpdate(root2, 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) { + didScheduleRenderPhaseUpdateDuringThisPass = didScheduleRenderPhaseUpdate = true; + var pending = queue.pending; + if (pending === null) { + update.next = update; + } else { + update.next = pending.next; + pending.next = update; + } + queue.pending = update; + } + function entangleTransitionUpdate(root2, queue, lane) { + if (isTransitionLane(lane)) { + var queueLanes = queue.lanes; + queueLanes = intersectLanes(queueLanes, root2.pendingLanes); + var newQueueLanes = mergeLanes(queueLanes, lane); + queue.lanes = newQueueLanes; + markRootEntangled(root2, newQueueLanes); + } + } + function markUpdateInDevTools(fiber, lane, action) { + { + markStateUpdateScheduled(fiber, lane); + } + } + var ContextOnlyDispatcher = { + 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$1 = Scheduler.unstable_now; + var commitTime = 0; + var layoutEffectStartTime = -1; + var profilerStartTime = -1; + var passiveEffectStartTime = -1; + 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$1(); + } + function startProfilerTimer(fiber) { + profilerStartTime = now$1(); + if (fiber.actualStartTime < 0) { + fiber.actualStartTime = now$1(); + } + } + function stopProfilerTimerIfRunning(fiber) { + profilerStartTime = -1; + } + function stopProfilerTimerIfRunningAndRecordDelta(fiber, overrideBaseTime) { + if (profilerStartTime >= 0) { + var elapsedTime = now$1() - profilerStartTime; + fiber.actualDuration += elapsedTime; + if (overrideBaseTime) { + fiber.selfBaseDuration = elapsedTime; + } + profilerStartTime = -1; + } + } + function recordLayoutEffectDuration(fiber) { + if (layoutEffectStartTime >= 0) { + var elapsedTime = now$1() - layoutEffectStartTime; + layoutEffectStartTime = -1; + var parentFiber = fiber.return; + while (parentFiber !== null) { + switch (parentFiber.tag) { + case HostRoot: + var root2 = parentFiber.stateNode; + root2.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$1() - passiveEffectStartTime; + passiveEffectStartTime = -1; + var parentFiber = fiber.return; + while (parentFiber !== null) { + switch (parentFiber.tag) { + case HostRoot: + var root2 = parentFiber.stateNode; + if (root2 !== null) { + root2.passiveEffectDuration += elapsedTime; + } + return; + case Profiler: + var parentStateNode = parentFiber.stateNode; + if (parentStateNode !== null) { + parentStateNode.passiveEffectDuration += elapsedTime; + } + return; + } + parentFiber = parentFiber.return; + } + } + } + function startLayoutEffectTimer() { + layoutEffectStartTime = now$1(); + } + function startPassiveEffectTimer() { + passiveEffectStartTime = now$1(); + } + function transferActualDuration(fiber) { + var child = fiber.child; + while (child) { + fiber.actualDuration += child.actualDuration; + child = child.sibling; + } + } + function resolveDefaultProps(Component, baseProps) { + if (Component && Component.defaultProps) { + 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 fakeInternalInstance = {}; + var didWarnAboutStateAssignmentForComponent; + var didWarnAboutUninitializedState; + var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate; + var didWarnAboutLegacyLifecyclesAndDerivedState; + var didWarnAboutUndefinedDerivedState; + var warnOnUndefinedDerivedState; + var warnOnInvalidCallback; + var didWarnAboutDirectlyAssigningPropsToState; + var didWarnAboutContextTypeAndContextTypes; + var didWarnAboutInvalidateContextType; + var didWarnAboutLegacyContext$1; + { + didWarnAboutStateAssignmentForComponent = new Set; + didWarnAboutUninitializedState = new Set; + didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set; + didWarnAboutLegacyLifecyclesAndDerivedState = new Set; + didWarnAboutDirectlyAssigningPropsToState = new Set; + didWarnAboutUndefinedDerivedState = new Set; + didWarnAboutContextTypeAndContextTypes = new Set; + didWarnAboutInvalidateContextType = new Set; + didWarnAboutLegacyContext$1 = 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); + } + } + }; + 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(workInProgress2, ctor, getDerivedStateFromProps, nextProps) { + var prevState = workInProgress2.memoizedState; + var partialState = getDerivedStateFromProps(nextProps, prevState); + { + if (workInProgress2.mode & StrictLegacyMode) { + setIsStrictModeForDevtools(true); + try { + partialState = getDerivedStateFromProps(nextProps, prevState); + } finally { + setIsStrictModeForDevtools(false); + } + } + warnOnUndefinedDerivedState(ctor, partialState); + } + var memoizedState = partialState === null || partialState === undefined ? prevState : assign({}, prevState, partialState); + workInProgress2.memoizedState = memoizedState; + if (workInProgress2.lanes === NoLanes) { + var updateQueue = workInProgress2.updateQueue; + updateQueue.baseState = memoizedState; + } + } + var classComponentUpdater = { + 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; + } + var root2 = enqueueUpdate(fiber, update, lane); + if (root2 !== null) { + scheduleUpdateOnFiber(root2, fiber, lane, eventTime); + entangleTransitions(root2, 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; + } + var root2 = enqueueUpdate(fiber, update, lane); + if (root2 !== null) { + scheduleUpdateOnFiber(root2, fiber, lane, eventTime); + entangleTransitions(root2, 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; + } + var root2 = enqueueUpdate(fiber, update, lane); + if (root2 !== null) { + scheduleUpdateOnFiber(root2, fiber, lane, eventTime); + entangleTransitions(root2, fiber, lane); + } + { + markForceUpdateScheduled(fiber, lane); + } + } + }; + function checkShouldComponentUpdate(workInProgress2, ctor, oldProps, newProps, oldState, newState, nextContext) { + var instance = workInProgress2.stateNode; + if (typeof instance.shouldComponentUpdate === "function") { + var shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext); + { + if (workInProgress2.mode & StrictLegacyMode) { + setIsStrictModeForDevtools(true); + try { + 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(workInProgress2, ctor, newProps) { + var instance = workInProgress2.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 (ctor.childContextTypes && !didWarnAboutLegacyContext$1.has(ctor) && (workInProgress2.mode & StrictLegacyMode) === NoMode) { + didWarnAboutLegacyContext$1.add(ctor); + error("%s uses the legacy childContextTypes API which is no longer supported and will be removed in the next major release. Use React.createContext() instead\n\n.Learn more about this warning here: https://reactjs.org/link/legacy-context", name); + } + if (ctor.contextTypes && !didWarnAboutLegacyContext$1.has(ctor) && (workInProgress2.mode & StrictLegacyMode) === NoMode) { + didWarnAboutLegacyContext$1.add(ctor); + error("%s uses the legacy contextTypes API which is no longer supported and will be removed in the next major release. Use React.createContext() with static contextType instead.\n\nLearn more about this warning here: https://reactjs.org/link/legacy-context", 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(workInProgress2, instance) { + instance.updater = classComponentUpdater; + workInProgress2.stateNode = instance; + set(instance, workInProgress2); + { + instance._reactInternalInstance = fakeInternalInstance; + } + } + function constructClassInstance(workInProgress2, ctor, props) { + var isLegacyContextConsumer = false; + var unmaskedContext = emptyContextObject; + var context = emptyContextObject; + var contextType = ctor.contextType; + { + if ("contextType" in ctor) { + var isValid = contextType === null || contextType !== undefined && contextType.$$typeof === REACT_CONTEXT_TYPE && contextType._context === undefined; + 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(workInProgress2, ctor, true); + var contextTypes = ctor.contextTypes; + isLegacyContextConsumer = contextTypes !== null && contextTypes !== undefined; + context = isLegacyContextConsumer ? getMaskedContext(workInProgress2, unmaskedContext) : emptyContextObject; + } + var instance = new ctor(props, context); + { + if (workInProgress2.mode & StrictLegacyMode) { + setIsStrictModeForDevtools(true); + try { + instance = new ctor(props, context); + } finally { + setIsStrictModeForDevtools(false); + } + } + } + var state = workInProgress2.memoizedState = instance.state !== null && instance.state !== undefined ? instance.state : null; + adoptClassInstance(workInProgress2, 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 (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\nThe above lifecycles should be removed. Learn more about this warning here:\nhttps://reactjs.org/link/unsafe-component-lifecycles", _componentName, newApiName, foundWillMountName !== null ? "\n " + foundWillMountName : "", foundWillReceivePropsName !== null ? "\n " + foundWillReceivePropsName : "", foundWillUpdateName !== null ? "\n " + foundWillUpdateName : ""); + } + } + } + } + if (isLegacyContextConsumer) { + cacheContext(workInProgress2, unmaskedContext, context); + } + return instance; + } + function callComponentWillMount(workInProgress2, 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(workInProgress2) || "Component"); + } + classComponentUpdater.enqueueReplaceState(instance, instance.state, null); + } + } + function callComponentWillReceiveProps(workInProgress2, 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(workInProgress2) || "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); + } + } + function mountClassInstance(workInProgress2, ctor, newProps, renderLanes2) { + { + checkClassInstance(workInProgress2, ctor, newProps); + } + var instance = workInProgress2.stateNode; + instance.props = newProps; + instance.state = workInProgress2.memoizedState; + instance.refs = {}; + initializeUpdateQueue(workInProgress2); + var contextType = ctor.contextType; + if (typeof contextType === "object" && contextType !== null) { + instance.context = readContext(contextType); + } else { + var unmaskedContext = getUnmaskedContext(workInProgress2, ctor, true); + instance.context = getMaskedContext(workInProgress2, 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 (workInProgress2.mode & StrictLegacyMode) { + ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress2, instance); + } + { + ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(workInProgress2, instance); + } + } + instance.state = workInProgress2.memoizedState; + var getDerivedStateFromProps = ctor.getDerivedStateFromProps; + if (typeof getDerivedStateFromProps === "function") { + applyDerivedStateFromProps(workInProgress2, ctor, getDerivedStateFromProps, newProps); + instance.state = workInProgress2.memoizedState; + } + if (typeof ctor.getDerivedStateFromProps !== "function" && typeof instance.getSnapshotBeforeUpdate !== "function" && (typeof instance.UNSAFE_componentWillMount === "function" || typeof instance.componentWillMount === "function")) { + callComponentWillMount(workInProgress2, instance); + processUpdateQueue(workInProgress2, newProps, instance, renderLanes2); + instance.state = workInProgress2.memoizedState; + } + if (typeof instance.componentDidMount === "function") { + var fiberFlags = Update; + { + fiberFlags |= LayoutStatic; + } + if ((workInProgress2.mode & StrictEffectsMode) !== NoMode) { + fiberFlags |= MountLayoutDev; + } + workInProgress2.flags |= fiberFlags; + } + } + function resumeMountClassInstance(workInProgress2, ctor, newProps, renderLanes2) { + var instance = workInProgress2.stateNode; + var oldProps = workInProgress2.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(workInProgress2, ctor, true); + nextContext = getMaskedContext(workInProgress2, nextLegacyUnmaskedContext); + } + var getDerivedStateFromProps = ctor.getDerivedStateFromProps; + var hasNewLifecycles = typeof getDerivedStateFromProps === "function" || typeof instance.getSnapshotBeforeUpdate === "function"; + if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === "function" || typeof instance.componentWillReceiveProps === "function")) { + if (oldProps !== newProps || oldContext !== nextContext) { + callComponentWillReceiveProps(workInProgress2, instance, newProps, nextContext); + } + } + resetHasForceUpdateBeforeProcessing(); + var oldState = workInProgress2.memoizedState; + var newState = instance.state = oldState; + processUpdateQueue(workInProgress2, newProps, instance, renderLanes2); + newState = workInProgress2.memoizedState; + if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) { + if (typeof instance.componentDidMount === "function") { + var fiberFlags = Update; + { + fiberFlags |= LayoutStatic; + } + if ((workInProgress2.mode & StrictEffectsMode) !== NoMode) { + fiberFlags |= MountLayoutDev; + } + workInProgress2.flags |= fiberFlags; + } + return false; + } + if (typeof getDerivedStateFromProps === "function") { + applyDerivedStateFromProps(workInProgress2, ctor, getDerivedStateFromProps, newProps); + newState = workInProgress2.memoizedState; + } + var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress2, ctor, oldProps, newProps, oldState, newState, nextContext); + if (shouldUpdate) { + 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 ((workInProgress2.mode & StrictEffectsMode) !== NoMode) { + _fiberFlags |= MountLayoutDev; + } + workInProgress2.flags |= _fiberFlags; + } + } else { + if (typeof instance.componentDidMount === "function") { + var _fiberFlags2 = Update; + { + _fiberFlags2 |= LayoutStatic; + } + if ((workInProgress2.mode & StrictEffectsMode) !== NoMode) { + _fiberFlags2 |= MountLayoutDev; + } + workInProgress2.flags |= _fiberFlags2; + } + workInProgress2.memoizedProps = newProps; + workInProgress2.memoizedState = newState; + } + instance.props = newProps; + instance.state = newState; + instance.context = nextContext; + return shouldUpdate; + } + function updateClassInstance(current2, workInProgress2, ctor, newProps, renderLanes2) { + var instance = workInProgress2.stateNode; + cloneUpdateQueue(current2, workInProgress2); + var unresolvedOldProps = workInProgress2.memoizedProps; + var oldProps = workInProgress2.type === workInProgress2.elementType ? unresolvedOldProps : resolveDefaultProps(workInProgress2.type, unresolvedOldProps); + instance.props = oldProps; + var unresolvedNewProps = workInProgress2.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(workInProgress2, ctor, true); + nextContext = getMaskedContext(workInProgress2, nextUnmaskedContext); + } + var getDerivedStateFromProps = ctor.getDerivedStateFromProps; + var hasNewLifecycles = typeof getDerivedStateFromProps === "function" || typeof instance.getSnapshotBeforeUpdate === "function"; + if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === "function" || typeof instance.componentWillReceiveProps === "function")) { + if (unresolvedOldProps !== unresolvedNewProps || oldContext !== nextContext) { + callComponentWillReceiveProps(workInProgress2, instance, newProps, nextContext); + } + } + resetHasForceUpdateBeforeProcessing(); + var oldState = workInProgress2.memoizedState; + var newState = instance.state = oldState; + processUpdateQueue(workInProgress2, newProps, instance, renderLanes2); + newState = workInProgress2.memoizedState; + if (unresolvedOldProps === unresolvedNewProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing() && !enableLazyContextPropagation) { + if (typeof instance.componentDidUpdate === "function") { + if (unresolvedOldProps !== current2.memoizedProps || oldState !== current2.memoizedState) { + workInProgress2.flags |= Update; + } + } + if (typeof instance.getSnapshotBeforeUpdate === "function") { + if (unresolvedOldProps !== current2.memoizedProps || oldState !== current2.memoizedState) { + workInProgress2.flags |= Snapshot; + } + } + return false; + } + if (typeof getDerivedStateFromProps === "function") { + applyDerivedStateFromProps(workInProgress2, ctor, getDerivedStateFromProps, newProps); + newState = workInProgress2.memoizedState; + } + var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress2, ctor, oldProps, newProps, oldState, newState, nextContext) || enableLazyContextPropagation; + if (shouldUpdate) { + 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") { + workInProgress2.flags |= Update; + } + if (typeof instance.getSnapshotBeforeUpdate === "function") { + workInProgress2.flags |= Snapshot; + } + } else { + if (typeof instance.componentDidUpdate === "function") { + if (unresolvedOldProps !== current2.memoizedProps || oldState !== current2.memoizedState) { + workInProgress2.flags |= Update; + } + } + if (typeof instance.getSnapshotBeforeUpdate === "function") { + if (unresolvedOldProps !== current2.memoizedProps || oldState !== current2.memoizedState) { + workInProgress2.flags |= Snapshot; + } + } + workInProgress2.memoizedProps = newProps; + workInProgress2.memoizedState = newState; + } + instance.props = newProps; + instance.state = newState; + instance.context = nextContext; + return shouldUpdate; + } + function createCapturedValueAtFiber(value, source) { + return { + value, + source, + stack: getStackByFiberInDevAndProd(source), + digest: null + }; + } + function createCapturedValue(value, digest, stack) { + return { + value, + source: null, + stack: stack != null ? stack : null, + digest: digest != null ? digest : null + }; + } + function showErrorDialog(boundary, errorInfo) { + return true; + } + function logCapturedError(boundary, errorInfo) { + try { + var logError = showErrorDialog(boundary, errorInfo); + if (logError === false) { + return; + } + var error2 = errorInfo.value; + if (true) { + var source = errorInfo.source; + var stack = errorInfo.stack; + var componentStack = stack !== null ? stack : ""; + if (error2 != null && error2._suppressLogging) { + if (boundary.tag === ClassComponent) { + return; + } + console["error"](error2); + } + 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.\nVisit 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); + console["error"](combinedMessage); + } else { + } + } catch (e) { + setTimeout(function() { + throw e; + }); + } + } + var PossiblyWeakMap$1 = typeof WeakMap === "function" ? WeakMap : Map; + function createRootErrorUpdate(fiber, errorInfo, lane) { + var update = createUpdate(NoTimestamp, lane); + update.tag = CaptureUpdate; + update.payload = { + element: null + }; + var error2 = errorInfo.value; + update.callback = function() { + onUncaughtError(error2); + 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") { + markLegacyErrorBoundaryAsFailed(this); + } + var error$12 = errorInfo.value; + var stack = errorInfo.stack; + this.componentDidCatch(error$12, { + componentStack: stack !== null ? stack : "" + }); + { + if (typeof getDerivedStateFromError !== "function") { + 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(root2, wakeable, lanes) { + var pingCache = root2.pingCache; + var threadIDs; + if (pingCache === null) { + pingCache = root2.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)) { + threadIDs.add(lanes); + var ping = pingSuspendedRoot.bind(null, root2, wakeable, lanes); + { + if (isDevToolsPresent) { + restorePendingUpdaters(root2, lanes); + } + } + wakeable.then(ping, ping); + } + } + function attachRetryListener(suspenseBoundary, root2, wakeable, lanes) { + 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) { + 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; + } + node = node.return; + } while (node !== null); + return null; + } + function markSuspenseBoundaryShouldCapture(suspenseBoundary, returnFiber, sourceFiber, root2, rootRenderLanes) { + if ((suspenseBoundary.mode & ConcurrentMode) === NoMode) { + if (suspenseBoundary === returnFiber) { + suspenseBoundary.flags |= ShouldCapture; + } else { + suspenseBoundary.flags |= DidCapture; + sourceFiber.flags |= ForceUpdateForLegacySuspense; + sourceFiber.flags &= ~(LifecycleEffectMask | Incomplete); + if (sourceFiber.tag === ClassComponent) { + var currentSourceFiber = sourceFiber.alternate; + if (currentSourceFiber === null) { + sourceFiber.tag = IncompleteClassComponent; + } else { + var update = createUpdate(NoTimestamp, SyncLane); + update.tag = ForceUpdate; + enqueueUpdate(sourceFiber, update, SyncLane); + } + } + sourceFiber.lanes = mergeLanes(sourceFiber.lanes, SyncLane); + } + return suspenseBoundary; + } + suspenseBoundary.flags |= ShouldCapture; + suspenseBoundary.lanes = rootRenderLanes; + return suspenseBoundary; + } + function throwException(root2, returnFiber, sourceFiber, value, rootRenderLanes) { + sourceFiber.flags |= Incomplete; + { + if (isDevToolsPresent) { + restorePendingUpdaters(root2, rootRenderLanes); + } + } + if (value !== null && typeof value === "object" && typeof value.then === "function") { + var wakeable = value; + resetSuspendedComponent(sourceFiber); + { + if (getIsHydrating() && sourceFiber.mode & ConcurrentMode) { + markDidThrowWhileHydratingDEV(); + } + } + var suspenseBoundary = getNearestSuspenseBoundaryToCapture(returnFiber); + if (suspenseBoundary !== null) { + suspenseBoundary.flags &= ~ForceClientRender; + markSuspenseBoundaryShouldCapture(suspenseBoundary, returnFiber, sourceFiber, root2, rootRenderLanes); + if (suspenseBoundary.mode & ConcurrentMode) { + attachPingListener(root2, wakeable, rootRenderLanes); + } + attachRetryListener(suspenseBoundary, root2, wakeable); + return; + } else { + if (!includesSyncLane(rootRenderLanes)) { + attachPingListener(root2, wakeable, rootRenderLanes); + renderDidSuspendDelayIfPossible(); + return; + } + 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."); + value = uncaughtSuspenseError; + } + } else { + if (getIsHydrating() && sourceFiber.mode & ConcurrentMode) { + markDidThrowWhileHydratingDEV(); + var _suspenseBoundary = getNearestSuspenseBoundaryToCapture(returnFiber); + if (_suspenseBoundary !== null) { + if ((_suspenseBoundary.flags & ShouldCapture) === NoFlags) { + _suspenseBoundary.flags |= ForceClientRender; + } + markSuspenseBoundaryShouldCapture(_suspenseBoundary, returnFiber, sourceFiber, root2, rootRenderLanes); + queueHydrationError(createCapturedValueAtFiber(value, sourceFiber)); + return; + } + } + } + value = createCapturedValueAtFiber(value, sourceFiber); + renderDidError(value); + var workInProgress2 = returnFiber; + do { + switch (workInProgress2.tag) { + case HostRoot: { + var _errorInfo = value; + workInProgress2.flags |= ShouldCapture; + var lane = pickArbitraryLane(rootRenderLanes); + workInProgress2.lanes = mergeLanes(workInProgress2.lanes, lane); + var update = createRootErrorUpdate(workInProgress2, _errorInfo, lane); + enqueueCapturedUpdate(workInProgress2, update); + return; + } + case ClassComponent: + var errorInfo = value; + var ctor = workInProgress2.type; + var instance = workInProgress2.stateNode; + if ((workInProgress2.flags & DidCapture) === NoFlags && (typeof ctor.getDerivedStateFromError === "function" || instance !== null && typeof instance.componentDidCatch === "function" && !isAlreadyFailedLegacyErrorBoundary(instance))) { + workInProgress2.flags |= ShouldCapture; + var _lane = pickArbitraryLane(rootRenderLanes); + workInProgress2.lanes = mergeLanes(workInProgress2.lanes, _lane); + var _update = createClassErrorUpdate(workInProgress2, errorInfo, _lane); + enqueueCapturedUpdate(workInProgress2, _update); + return; + } + break; + } + workInProgress2 = workInProgress2.return; + } while (workInProgress2 !== null); + } + function getSuspendedCache() { + { + return null; + } + } + 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 didWarnAboutDefaultPropsOnFunctionComponent; + { + didWarnAboutBadClass = {}; + didWarnAboutModulePatternComponent = {}; + didWarnAboutContextTypeOnFunctionComponent = {}; + didWarnAboutGetDerivedStateOnFunctionComponent = {}; + didWarnAboutFunctionRefs = {}; + didWarnAboutReassigningProps = false; + didWarnAboutRevealOrder = {}; + didWarnAboutTailOptions = {}; + didWarnAboutDefaultPropsOnFunctionComponent = {}; + } + function reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2) { + if (current2 === null) { + workInProgress2.child = mountChildFibers(workInProgress2, null, nextChildren, renderLanes2); + } else { + workInProgress2.child = reconcileChildFibers(workInProgress2, current2.child, nextChildren, renderLanes2); + } + } + function forceUnmountCurrentAndReconcile(current2, workInProgress2, nextChildren, renderLanes2) { + workInProgress2.child = reconcileChildFibers(workInProgress2, current2.child, null, renderLanes2); + workInProgress2.child = reconcileChildFibers(workInProgress2, null, nextChildren, renderLanes2); + } + function updateForwardRef(current2, workInProgress2, Component, nextProps, renderLanes2) { + { + if (workInProgress2.type !== workInProgress2.elementType) { + var innerPropTypes = Component.propTypes; + if (innerPropTypes) { + checkPropTypes(innerPropTypes, nextProps, "prop", getComponentNameFromType(Component)); + } + } + } + var render2 = Component.render; + var ref = workInProgress2.ref; + var nextChildren; + var hasId; + prepareToReadContext(workInProgress2, renderLanes2); + { + markComponentRenderStarted(workInProgress2); + } + { + ReactCurrentOwner$1.current = workInProgress2; + setIsRendering(true); + nextChildren = renderWithHooks(current2, workInProgress2, render2, nextProps, ref, renderLanes2); + hasId = checkDidRenderIdHook(); + if (workInProgress2.mode & StrictLegacyMode) { + setIsStrictModeForDevtools(true); + try { + nextChildren = renderWithHooks(current2, workInProgress2, render2, nextProps, ref, renderLanes2); + hasId = checkDidRenderIdHook(); + } finally { + setIsStrictModeForDevtools(false); + } + } + setIsRendering(false); + } + { + markComponentRenderStopped(); + } + if (current2 !== null && !didReceiveUpdate) { + bailoutHooks(current2, workInProgress2, renderLanes2); + return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2); + } + if (getIsHydrating() && hasId) { + pushMaterializedTreeId(workInProgress2); + } + workInProgress2.flags |= PerformedWork; + reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2); + return workInProgress2.child; + } + function updateMemoComponent(current2, workInProgress2, Component, nextProps, renderLanes2) { + if (current2 === null) { + var type = Component.type; + if (isSimpleFunctionComponent(type) && Component.compare === null && Component.defaultProps === undefined) { + var resolvedType = type; + { + resolvedType = resolveFunctionForHotReloading(type); + } + workInProgress2.tag = SimpleMemoComponent; + workInProgress2.type = resolvedType; + { + validateFunctionComponentInDev(workInProgress2, type); + } + return updateSimpleMemoComponent(current2, workInProgress2, resolvedType, nextProps, renderLanes2); + } + { + var innerPropTypes = type.propTypes; + if (innerPropTypes) { + checkPropTypes(innerPropTypes, nextProps, "prop", getComponentNameFromType(type)); + } + if (Component.defaultProps !== undefined) { + var componentName = getComponentNameFromType(type) || "Unknown"; + if (!didWarnAboutDefaultPropsOnFunctionComponent[componentName]) { + error("%s: Support for defaultProps will be removed from memo components in a future major release. Use JavaScript default parameters instead.", componentName); + didWarnAboutDefaultPropsOnFunctionComponent[componentName] = true; + } + } + } + var child = createFiberFromTypeAndProps(Component.type, null, nextProps, workInProgress2, workInProgress2.mode, renderLanes2); + child.ref = workInProgress2.ref; + child.return = workInProgress2; + workInProgress2.child = child; + return child; + } + { + var _type = Component.type; + var _innerPropTypes = _type.propTypes; + if (_innerPropTypes) { + checkPropTypes(_innerPropTypes, nextProps, "prop", getComponentNameFromType(_type)); + } + } + var currentChild = current2.child; + var hasScheduledUpdateOrContext = checkScheduledUpdateOrContext(current2, renderLanes2); + if (!hasScheduledUpdateOrContext) { + var prevProps = currentChild.memoizedProps; + var compare = Component.compare; + compare = compare !== null ? compare : shallowEqual; + if (compare(prevProps, nextProps) && current2.ref === workInProgress2.ref) { + return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2); + } + } + workInProgress2.flags |= PerformedWork; + var newChild = createWorkInProgress(currentChild, nextProps); + newChild.ref = workInProgress2.ref; + newChild.return = workInProgress2; + workInProgress2.child = newChild; + return newChild; + } + function updateSimpleMemoComponent(current2, workInProgress2, Component, nextProps, renderLanes2) { + { + if (workInProgress2.type !== workInProgress2.elementType) { + var outerMemoType = workInProgress2.elementType; + if (outerMemoType.$$typeof === REACT_LAZY_TYPE) { + var lazyComponent = outerMemoType; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + try { + outerMemoType = init(payload); + } catch (x) { + outerMemoType = null; + } + var outerPropTypes = outerMemoType && outerMemoType.propTypes; + if (outerPropTypes) { + checkPropTypes(outerPropTypes, nextProps, "prop", getComponentNameFromType(outerMemoType)); + } + } + } + } + if (current2 !== null) { + var prevProps = current2.memoizedProps; + if (shallowEqual(prevProps, nextProps) && current2.ref === workInProgress2.ref && workInProgress2.type === current2.type) { + didReceiveUpdate = false; + workInProgress2.pendingProps = nextProps = prevProps; + if (!checkScheduledUpdateOrContext(current2, renderLanes2)) { + workInProgress2.lanes = current2.lanes; + return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2); + } else if ((current2.flags & ForceUpdateForLegacySuspense) !== NoFlags) { + didReceiveUpdate = true; + } + } + } + return updateFunctionComponent(current2, workInProgress2, Component, nextProps, renderLanes2); + } + function updateOffscreenComponent(current2, workInProgress2, renderLanes2) { + var nextProps = workInProgress2.pendingProps; + var nextChildren = nextProps.children; + var prevState = current2 !== null ? current2.memoizedState : null; + if (nextProps.mode === "hidden" || enableLegacyHidden) { + if ((workInProgress2.mode & ConcurrentMode) === NoMode) { + var nextState = { + baseLanes: NoLanes, + cachePool: null, + transitions: null + }; + workInProgress2.memoizedState = nextState; + pushRenderLanes(workInProgress2, renderLanes2); + } else if (!includesSomeLane(renderLanes2, OffscreenLane)) { + var spawnedCachePool = null; + var nextBaseLanes; + if (prevState !== null) { + var prevBaseLanes = prevState.baseLanes; + nextBaseLanes = mergeLanes(prevBaseLanes, renderLanes2); + } else { + nextBaseLanes = renderLanes2; + } + workInProgress2.lanes = workInProgress2.childLanes = laneToLanes(OffscreenLane); + var _nextState = { + baseLanes: nextBaseLanes, + cachePool: spawnedCachePool, + transitions: null + }; + workInProgress2.memoizedState = _nextState; + workInProgress2.updateQueue = null; + pushRenderLanes(workInProgress2, nextBaseLanes); + return null; + } else { + var _nextState2 = { + baseLanes: NoLanes, + cachePool: null, + transitions: null + }; + workInProgress2.memoizedState = _nextState2; + var subtreeRenderLanes2 = prevState !== null ? prevState.baseLanes : renderLanes2; + pushRenderLanes(workInProgress2, subtreeRenderLanes2); + } + } else { + var _subtreeRenderLanes; + if (prevState !== null) { + _subtreeRenderLanes = mergeLanes(prevState.baseLanes, renderLanes2); + workInProgress2.memoizedState = null; + } else { + _subtreeRenderLanes = renderLanes2; + } + pushRenderLanes(workInProgress2, _subtreeRenderLanes); + } + reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2); + return workInProgress2.child; + } + function updateFragment(current2, workInProgress2, renderLanes2) { + var nextChildren = workInProgress2.pendingProps; + reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2); + return workInProgress2.child; + } + function updateMode(current2, workInProgress2, renderLanes2) { + var nextChildren = workInProgress2.pendingProps.children; + reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2); + return workInProgress2.child; + } + function updateProfiler(current2, workInProgress2, renderLanes2) { + { + workInProgress2.flags |= Update; + { + var stateNode = workInProgress2.stateNode; + stateNode.effectDuration = 0; + stateNode.passiveEffectDuration = 0; + } + } + var nextProps = workInProgress2.pendingProps; + var nextChildren = nextProps.children; + reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2); + return workInProgress2.child; + } + function markRef(current2, workInProgress2) { + var ref = workInProgress2.ref; + if (current2 === null && ref !== null || current2 !== null && current2.ref !== ref) { + workInProgress2.flags |= Ref; + { + workInProgress2.flags |= RefStatic; + } + } + } + function updateFunctionComponent(current2, workInProgress2, Component, nextProps, renderLanes2) { + { + if (workInProgress2.type !== workInProgress2.elementType) { + var innerPropTypes = Component.propTypes; + if (innerPropTypes) { + checkPropTypes(innerPropTypes, nextProps, "prop", getComponentNameFromType(Component)); + } + } + } + var context; + { + var unmaskedContext = getUnmaskedContext(workInProgress2, Component, true); + context = getMaskedContext(workInProgress2, unmaskedContext); + } + var nextChildren; + var hasId; + prepareToReadContext(workInProgress2, renderLanes2); + { + markComponentRenderStarted(workInProgress2); + } + { + ReactCurrentOwner$1.current = workInProgress2; + setIsRendering(true); + nextChildren = renderWithHooks(current2, workInProgress2, Component, nextProps, context, renderLanes2); + hasId = checkDidRenderIdHook(); + if (workInProgress2.mode & StrictLegacyMode) { + setIsStrictModeForDevtools(true); + try { + nextChildren = renderWithHooks(current2, workInProgress2, Component, nextProps, context, renderLanes2); + hasId = checkDidRenderIdHook(); + } finally { + setIsStrictModeForDevtools(false); + } + } + setIsRendering(false); + } + { + markComponentRenderStopped(); + } + if (current2 !== null && !didReceiveUpdate) { + bailoutHooks(current2, workInProgress2, renderLanes2); + return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2); + } + if (getIsHydrating() && hasId) { + pushMaterializedTreeId(workInProgress2); + } + workInProgress2.flags |= PerformedWork; + reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2); + return workInProgress2.child; + } + function updateClassComponent(current2, workInProgress2, Component, nextProps, renderLanes2) { + { + switch (shouldError(workInProgress2)) { + case false: { + var _instance = workInProgress2.stateNode; + var ctor = workInProgress2.type; + var tempInstance = new ctor(workInProgress2.memoizedProps, _instance.context); + var state = tempInstance.state; + _instance.updater.enqueueSetState(_instance, state, null); + break; + } + case true: { + workInProgress2.flags |= DidCapture; + workInProgress2.flags |= ShouldCapture; + var error$1 = new Error("Simulated error coming from DevTools"); + var lane = pickArbitraryLane(renderLanes2); + workInProgress2.lanes = mergeLanes(workInProgress2.lanes, lane); + var update = createClassErrorUpdate(workInProgress2, createCapturedValueAtFiber(error$1, workInProgress2), lane); + enqueueCapturedUpdate(workInProgress2, update); + break; + } + } + if (workInProgress2.type !== workInProgress2.elementType) { + var innerPropTypes = Component.propTypes; + if (innerPropTypes) { + checkPropTypes(innerPropTypes, nextProps, "prop", getComponentNameFromType(Component)); + } + } + } + var hasContext; + if (isContextProvider(Component)) { + hasContext = true; + pushContextProvider(workInProgress2); + } else { + hasContext = false; + } + prepareToReadContext(workInProgress2, renderLanes2); + var instance = workInProgress2.stateNode; + var shouldUpdate; + if (instance === null) { + resetSuspendedCurrentOnMountInLegacyMode(current2, workInProgress2); + constructClassInstance(workInProgress2, Component, nextProps); + mountClassInstance(workInProgress2, Component, nextProps, renderLanes2); + shouldUpdate = true; + } else if (current2 === null) { + shouldUpdate = resumeMountClassInstance(workInProgress2, Component, nextProps, renderLanes2); + } else { + shouldUpdate = updateClassInstance(current2, workInProgress2, Component, nextProps, renderLanes2); + } + var nextUnitOfWork = finishClassComponent(current2, workInProgress2, Component, shouldUpdate, hasContext, renderLanes2); + { + var inst = workInProgress2.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(workInProgress2) || "a component"); + } + didWarnAboutReassigningProps = true; + } + } + return nextUnitOfWork; + } + function finishClassComponent(current2, workInProgress2, Component, shouldUpdate, hasContext, renderLanes2) { + markRef(current2, workInProgress2); + var didCaptureError = (workInProgress2.flags & DidCapture) !== NoFlags; + if (!shouldUpdate && !didCaptureError) { + if (hasContext) { + invalidateContextProvider(workInProgress2, Component, false); + } + return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2); + } + var instance = workInProgress2.stateNode; + ReactCurrentOwner$1.current = workInProgress2; + var nextChildren; + if (didCaptureError && typeof Component.getDerivedStateFromError !== "function") { + nextChildren = null; + { + stopProfilerTimerIfRunning(); + } + } else { + { + markComponentRenderStarted(workInProgress2); + } + { + setIsRendering(true); + nextChildren = instance.render(); + if (workInProgress2.mode & StrictLegacyMode) { + setIsStrictModeForDevtools(true); + try { + instance.render(); + } finally { + setIsStrictModeForDevtools(false); + } + } + setIsRendering(false); + } + { + markComponentRenderStopped(); + } + } + workInProgress2.flags |= PerformedWork; + if (current2 !== null && didCaptureError) { + forceUnmountCurrentAndReconcile(current2, workInProgress2, nextChildren, renderLanes2); + } else { + reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2); + } + workInProgress2.memoizedState = instance.state; + if (hasContext) { + invalidateContextProvider(workInProgress2, Component, true); + } + return workInProgress2.child; + } + function pushHostRootContext(workInProgress2) { + var root2 = workInProgress2.stateNode; + if (root2.pendingContext) { + pushTopLevelContextObject(workInProgress2, root2.pendingContext, root2.pendingContext !== root2.context); + } else if (root2.context) { + pushTopLevelContextObject(workInProgress2, root2.context, false); + } + pushHostContainer(workInProgress2, root2.containerInfo); + } + function updateHostRoot(current2, workInProgress2, renderLanes2) { + pushHostRootContext(workInProgress2); + if (current2 === null) { + throw new Error("Should have a current fiber. This is a bug in React."); + } + var nextProps = workInProgress2.pendingProps; + var prevState = workInProgress2.memoizedState; + var prevChildren = prevState.element; + cloneUpdateQueue(current2, workInProgress2); + processUpdateQueue(workInProgress2, nextProps, null, renderLanes2); + var nextState = workInProgress2.memoizedState; + var root2 = workInProgress2.stateNode; + var nextChildren = nextState.element; + if (prevState.isDehydrated) { + var overrideState = { + element: nextChildren, + isDehydrated: false, + cache: nextState.cache, + pendingSuspenseBoundaries: nextState.pendingSuspenseBoundaries, + transitions: nextState.transitions + }; + var updateQueue = workInProgress2.updateQueue; + updateQueue.baseState = overrideState; + workInProgress2.memoizedState = overrideState; + if (workInProgress2.flags & ForceClientRender) { + var recoverableError = createCapturedValueAtFiber(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."), workInProgress2); + return mountHostRootWithoutHydrating(current2, workInProgress2, nextChildren, renderLanes2, recoverableError); + } else if (nextChildren !== prevChildren) { + var _recoverableError = createCapturedValueAtFiber(new Error("This root received an early update, before anything was able hydrate. Switched the entire root to client rendering."), workInProgress2); + return mountHostRootWithoutHydrating(current2, workInProgress2, nextChildren, renderLanes2, _recoverableError); + } else { + enterHydrationState(workInProgress2); + var child = mountChildFibers(workInProgress2, null, nextChildren, renderLanes2); + workInProgress2.child = child; + var node = child; + while (node) { + node.flags = node.flags & ~Placement | Hydrating; + node = node.sibling; + } + } + } else { + resetHydrationState(); + if (nextChildren === prevChildren) { + return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2); + } + reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2); + } + return workInProgress2.child; + } + function mountHostRootWithoutHydrating(current2, workInProgress2, nextChildren, renderLanes2, recoverableError) { + resetHydrationState(); + queueHydrationError(recoverableError); + workInProgress2.flags |= ForceClientRender; + reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2); + return workInProgress2.child; + } + function updateHostComponent(current2, workInProgress2, renderLanes2) { + pushHostContext(workInProgress2); + if (current2 === null) { + tryToClaimNextHydratableInstance(workInProgress2); + } + var type = workInProgress2.type; + var nextProps = workInProgress2.pendingProps; + var prevProps = current2 !== null ? current2.memoizedProps : null; + var nextChildren = nextProps.children; + var isDirectTextChild = shouldSetTextContent(type, nextProps); + if (isDirectTextChild) { + nextChildren = null; + } else if (prevProps !== null && shouldSetTextContent(type, prevProps)) { + workInProgress2.flags |= ContentReset; + } + markRef(current2, workInProgress2); + reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2); + return workInProgress2.child; + } + function updateHostText(current2, workInProgress2) { + if (current2 === null) { + tryToClaimNextHydratableInstance(workInProgress2); + } + return null; + } + function mountLazyComponent(_current, workInProgress2, elementType, renderLanes2) { + resetSuspendedCurrentOnMountInLegacyMode(_current, workInProgress2); + var props = workInProgress2.pendingProps; + var lazyComponent = elementType; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + var Component = init(payload); + workInProgress2.type = Component; + var resolvedTag = workInProgress2.tag = resolveLazyComponentTag(Component); + var resolvedProps = resolveDefaultProps(Component, props); + var child; + switch (resolvedTag) { + case FunctionComponent: { + { + validateFunctionComponentInDev(workInProgress2, Component); + workInProgress2.type = Component = resolveFunctionForHotReloading(Component); + } + child = updateFunctionComponent(null, workInProgress2, Component, resolvedProps, renderLanes2); + return child; + } + case ClassComponent: { + { + workInProgress2.type = Component = resolveClassForHotReloading(Component); + } + child = updateClassComponent(null, workInProgress2, Component, resolvedProps, renderLanes2); + return child; + } + case ForwardRef: { + { + workInProgress2.type = Component = resolveForwardRefForHotReloading(Component); + } + child = updateForwardRef(null, workInProgress2, Component, resolvedProps, renderLanes2); + return child; + } + case MemoComponent: { + { + if (workInProgress2.type !== workInProgress2.elementType) { + var outerPropTypes = Component.propTypes; + if (outerPropTypes) { + checkPropTypes(outerPropTypes, resolvedProps, "prop", getComponentNameFromType(Component)); + } + } + } + child = updateMemoComponent(null, workInProgress2, Component, resolveDefaultProps(Component.type, resolvedProps), renderLanes2); + 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?"; + } + } + 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, workInProgress2, Component, nextProps, renderLanes2) { + resetSuspendedCurrentOnMountInLegacyMode(_current, workInProgress2); + workInProgress2.tag = ClassComponent; + var hasContext; + if (isContextProvider(Component)) { + hasContext = true; + pushContextProvider(workInProgress2); + } else { + hasContext = false; + } + prepareToReadContext(workInProgress2, renderLanes2); + constructClassInstance(workInProgress2, Component, nextProps); + mountClassInstance(workInProgress2, Component, nextProps, renderLanes2); + return finishClassComponent(null, workInProgress2, Component, true, hasContext, renderLanes2); + } + function mountIndeterminateComponent(_current, workInProgress2, Component, renderLanes2) { + resetSuspendedCurrentOnMountInLegacyMode(_current, workInProgress2); + var props = workInProgress2.pendingProps; + var context; + { + var unmaskedContext = getUnmaskedContext(workInProgress2, Component, false); + context = getMaskedContext(workInProgress2, unmaskedContext); + } + prepareToReadContext(workInProgress2, renderLanes2); + var value; + var hasId; + { + markComponentRenderStarted(workInProgress2); + } + { + 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 (workInProgress2.mode & StrictLegacyMode) { + ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress2, null); + } + setIsRendering(true); + ReactCurrentOwner$1.current = workInProgress2; + value = renderWithHooks(null, workInProgress2, Component, props, context, renderLanes2); + hasId = checkDidRenderIdHook(); + setIsRendering(false); + } + { + markComponentRenderStopped(); + } + workInProgress2.flags |= PerformedWork; + { + 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 (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; + } + } + workInProgress2.tag = ClassComponent; + workInProgress2.memoizedState = null; + workInProgress2.updateQueue = null; + var hasContext = false; + if (isContextProvider(Component)) { + hasContext = true; + pushContextProvider(workInProgress2); + } else { + hasContext = false; + } + workInProgress2.memoizedState = value.state !== null && value.state !== undefined ? value.state : null; + initializeUpdateQueue(workInProgress2); + adoptClassInstance(workInProgress2, value); + mountClassInstance(workInProgress2, Component, props, renderLanes2); + return finishClassComponent(null, workInProgress2, Component, true, hasContext, renderLanes2); + } else { + workInProgress2.tag = FunctionComponent; + { + if (workInProgress2.mode & StrictLegacyMode) { + setIsStrictModeForDevtools(true); + try { + value = renderWithHooks(null, workInProgress2, Component, props, context, renderLanes2); + hasId = checkDidRenderIdHook(); + } finally { + setIsStrictModeForDevtools(false); + } + } + } + if (getIsHydrating() && hasId) { + pushMaterializedTreeId(workInProgress2); + } + reconcileChildren(null, workInProgress2, value, renderLanes2); + { + validateFunctionComponentInDev(workInProgress2, Component); + } + return workInProgress2.child; + } + } + function validateFunctionComponentInDev(workInProgress2, Component) { + { + if (Component) { + if (Component.childContextTypes) { + error("%s(...): childContextTypes cannot be defined on a function component.", Component.displayName || Component.name || "Component"); + } + } + if (workInProgress2.ref !== null) { + var info = ""; + var ownerName = getCurrentFiberOwnerNameInDevOrNull(); + if (ownerName) { + info += "\n\nCheck the render method of `" + ownerName + "`."; + } + var warningKey = ownerName || ""; + var debugSource = workInProgress2._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 (Component.defaultProps !== undefined) { + var componentName = getComponentNameFromType(Component) || "Unknown"; + if (!didWarnAboutDefaultPropsOnFunctionComponent[componentName]) { + error("%s: Support for defaultProps will be removed from function components in a future major release. Use JavaScript default parameters instead.", componentName); + didWarnAboutDefaultPropsOnFunctionComponent[componentName] = true; + } + } + 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(renderLanes2) { + return { + baseLanes: renderLanes2, + cachePool: getSuspendedCache(), + transitions: null + }; + } + function updateSuspenseOffscreenState(prevOffscreenState, renderLanes2) { + var cachePool = null; + return { + baseLanes: mergeLanes(prevOffscreenState.baseLanes, renderLanes2), + cachePool, + transitions: prevOffscreenState.transitions + }; + } + function shouldRemainOnFallback(suspenseContext, current2, workInProgress2, renderLanes2) { + if (current2 !== null) { + var suspenseState = current2.memoizedState; + if (suspenseState === null) { + return false; + } + } + return hasSuspenseContext(suspenseContext, ForceSuspenseFallback); + } + function getRemainingWorkInPrimaryTree(current2, renderLanes2) { + return removeLanes(current2.childLanes, renderLanes2); + } + function updateSuspenseComponent(current2, workInProgress2, renderLanes2) { + var nextProps = workInProgress2.pendingProps; + { + if (shouldSuspend(workInProgress2)) { + workInProgress2.flags |= DidCapture; + } + } + var suspenseContext = suspenseStackCursor.current; + var showFallback = false; + var didSuspend = (workInProgress2.flags & DidCapture) !== NoFlags; + if (didSuspend || shouldRemainOnFallback(suspenseContext, current2)) { + showFallback = true; + workInProgress2.flags &= ~DidCapture; + } else { + if (current2 === null || current2.memoizedState !== null) { + { + suspenseContext = addSubtreeSuspenseContext(suspenseContext, InvisibleParentSuspenseContext); + } + } + } + suspenseContext = setDefaultShallowSuspenseContext(suspenseContext); + pushSuspenseContext(workInProgress2, suspenseContext); + if (current2 === null) { + tryToClaimNextHydratableInstance(workInProgress2); + var suspenseState = workInProgress2.memoizedState; + if (suspenseState !== null) { + var dehydrated = suspenseState.dehydrated; + if (dehydrated !== null) { + return mountDehydratedSuspenseComponent(workInProgress2, dehydrated); + } + } + var nextPrimaryChildren = nextProps.children; + var nextFallbackChildren = nextProps.fallback; + if (showFallback) { + var fallbackFragment = mountSuspenseFallbackChildren(workInProgress2, nextPrimaryChildren, nextFallbackChildren, renderLanes2); + var primaryChildFragment = workInProgress2.child; + primaryChildFragment.memoizedState = mountSuspenseOffscreenState(renderLanes2); + workInProgress2.memoizedState = SUSPENDED_MARKER; + return fallbackFragment; + } else { + return mountSuspensePrimaryChildren(workInProgress2, nextPrimaryChildren); + } + } else { + var prevState = current2.memoizedState; + if (prevState !== null) { + var _dehydrated = prevState.dehydrated; + if (_dehydrated !== null) { + return updateDehydratedSuspenseComponent(current2, workInProgress2, didSuspend, nextProps, _dehydrated, prevState, renderLanes2); + } + } + if (showFallback) { + var _nextFallbackChildren = nextProps.fallback; + var _nextPrimaryChildren = nextProps.children; + var fallbackChildFragment = updateSuspenseFallbackChildren(current2, workInProgress2, _nextPrimaryChildren, _nextFallbackChildren, renderLanes2); + var _primaryChildFragment2 = workInProgress2.child; + var prevOffscreenState = current2.child.memoizedState; + _primaryChildFragment2.memoizedState = prevOffscreenState === null ? mountSuspenseOffscreenState(renderLanes2) : updateSuspenseOffscreenState(prevOffscreenState, renderLanes2); + _primaryChildFragment2.childLanes = getRemainingWorkInPrimaryTree(current2, renderLanes2); + workInProgress2.memoizedState = SUSPENDED_MARKER; + return fallbackChildFragment; + } else { + var _nextPrimaryChildren2 = nextProps.children; + var _primaryChildFragment3 = updateSuspensePrimaryChildren(current2, workInProgress2, _nextPrimaryChildren2, renderLanes2); + workInProgress2.memoizedState = null; + return _primaryChildFragment3; + } + } + } + function mountSuspensePrimaryChildren(workInProgress2, primaryChildren, renderLanes2) { + var mode = workInProgress2.mode; + var primaryChildProps = { + mode: "visible", + children: primaryChildren + }; + var primaryChildFragment = mountWorkInProgressOffscreenFiber(primaryChildProps, mode); + primaryChildFragment.return = workInProgress2; + workInProgress2.child = primaryChildFragment; + return primaryChildFragment; + } + function mountSuspenseFallbackChildren(workInProgress2, primaryChildren, fallbackChildren, renderLanes2) { + var mode = workInProgress2.mode; + var progressedPrimaryFragment = workInProgress2.child; + var primaryChildProps = { + mode: "hidden", + children: primaryChildren + }; + var primaryChildFragment; + var fallbackChildFragment; + if ((mode & ConcurrentMode) === NoMode && progressedPrimaryFragment !== null) { + primaryChildFragment = progressedPrimaryFragment; + primaryChildFragment.childLanes = NoLanes; + primaryChildFragment.pendingProps = primaryChildProps; + if (workInProgress2.mode & ProfileMode) { + primaryChildFragment.actualDuration = 0; + primaryChildFragment.actualStartTime = -1; + primaryChildFragment.selfBaseDuration = 0; + primaryChildFragment.treeBaseDuration = 0; + } + fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes2, null); + } else { + primaryChildFragment = mountWorkInProgressOffscreenFiber(primaryChildProps, mode); + fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes2, null); + } + primaryChildFragment.return = workInProgress2; + fallbackChildFragment.return = workInProgress2; + primaryChildFragment.sibling = fallbackChildFragment; + workInProgress2.child = primaryChildFragment; + return fallbackChildFragment; + } + function mountWorkInProgressOffscreenFiber(offscreenProps, mode, renderLanes2) { + return createFiberFromOffscreen(offscreenProps, mode, NoLanes, null); + } + function updateWorkInProgressOffscreenFiber(current2, offscreenProps) { + return createWorkInProgress(current2, offscreenProps); + } + function updateSuspensePrimaryChildren(current2, workInProgress2, primaryChildren, renderLanes2) { + var currentPrimaryChildFragment = current2.child; + var currentFallbackChildFragment = currentPrimaryChildFragment.sibling; + var primaryChildFragment = updateWorkInProgressOffscreenFiber(currentPrimaryChildFragment, { + mode: "visible", + children: primaryChildren + }); + if ((workInProgress2.mode & ConcurrentMode) === NoMode) { + primaryChildFragment.lanes = renderLanes2; + } + primaryChildFragment.return = workInProgress2; + primaryChildFragment.sibling = null; + if (currentFallbackChildFragment !== null) { + var deletions = workInProgress2.deletions; + if (deletions === null) { + workInProgress2.deletions = [currentFallbackChildFragment]; + workInProgress2.flags |= ChildDeletion; + } else { + deletions.push(currentFallbackChildFragment); + } + } + workInProgress2.child = primaryChildFragment; + return primaryChildFragment; + } + function updateSuspenseFallbackChildren(current2, workInProgress2, primaryChildren, fallbackChildren, renderLanes2) { + var mode = workInProgress2.mode; + var currentPrimaryChildFragment = current2.child; + var currentFallbackChildFragment = currentPrimaryChildFragment.sibling; + var primaryChildProps = { + mode: "hidden", + children: primaryChildren + }; + var primaryChildFragment; + if ((mode & ConcurrentMode) === NoMode && workInProgress2.child !== currentPrimaryChildFragment) { + var progressedPrimaryFragment = workInProgress2.child; + primaryChildFragment = progressedPrimaryFragment; + primaryChildFragment.childLanes = NoLanes; + primaryChildFragment.pendingProps = primaryChildProps; + if (workInProgress2.mode & ProfileMode) { + primaryChildFragment.actualDuration = 0; + primaryChildFragment.actualStartTime = -1; + primaryChildFragment.selfBaseDuration = currentPrimaryChildFragment.selfBaseDuration; + primaryChildFragment.treeBaseDuration = currentPrimaryChildFragment.treeBaseDuration; + } + workInProgress2.deletions = null; + } else { + primaryChildFragment = updateWorkInProgressOffscreenFiber(currentPrimaryChildFragment, primaryChildProps); + primaryChildFragment.subtreeFlags = currentPrimaryChildFragment.subtreeFlags & StaticMask; + } + var fallbackChildFragment; + if (currentFallbackChildFragment !== null) { + fallbackChildFragment = createWorkInProgress(currentFallbackChildFragment, fallbackChildren); + } else { + fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes2, null); + fallbackChildFragment.flags |= Placement; + } + fallbackChildFragment.return = workInProgress2; + primaryChildFragment.return = workInProgress2; + primaryChildFragment.sibling = fallbackChildFragment; + workInProgress2.child = primaryChildFragment; + return fallbackChildFragment; + } + function retrySuspenseComponentWithoutHydrating(current2, workInProgress2, renderLanes2, recoverableError) { + if (recoverableError !== null) { + queueHydrationError(recoverableError); + } + reconcileChildFibers(workInProgress2, current2.child, null, renderLanes2); + var nextProps = workInProgress2.pendingProps; + var primaryChildren = nextProps.children; + var primaryChildFragment = mountSuspensePrimaryChildren(workInProgress2, primaryChildren); + primaryChildFragment.flags |= Placement; + workInProgress2.memoizedState = null; + return primaryChildFragment; + } + function mountSuspenseFallbackAfterRetryWithoutHydrating(current2, workInProgress2, primaryChildren, fallbackChildren, renderLanes2) { + var fiberMode = workInProgress2.mode; + var primaryChildProps = { + mode: "visible", + children: primaryChildren + }; + var primaryChildFragment = mountWorkInProgressOffscreenFiber(primaryChildProps, fiberMode); + var fallbackChildFragment = createFiberFromFragment(fallbackChildren, fiberMode, renderLanes2, null); + fallbackChildFragment.flags |= Placement; + primaryChildFragment.return = workInProgress2; + fallbackChildFragment.return = workInProgress2; + primaryChildFragment.sibling = fallbackChildFragment; + workInProgress2.child = primaryChildFragment; + if ((workInProgress2.mode & ConcurrentMode) !== NoMode) { + reconcileChildFibers(workInProgress2, current2.child, null, renderLanes2); + } + return fallbackChildFragment; + } + function mountDehydratedSuspenseComponent(workInProgress2, suspenseInstance, renderLanes2) { + if ((workInProgress2.mode & ConcurrentMode) === NoMode) { + { + error("Cannot hydrate Suspense in legacy mode. Switch from ReactDOM.hydrate(element, container) to ReactDOMClient.hydrateRoot(container, <App />).render(element) or remove the Suspense components from the server rendered components."); + } + workInProgress2.lanes = laneToLanes(SyncLane); + } else if (isSuspenseInstanceFallback(suspenseInstance)) { + workInProgress2.lanes = laneToLanes(DefaultHydrationLane); + } else { + workInProgress2.lanes = laneToLanes(OffscreenLane); + } + return null; + } + function updateDehydratedSuspenseComponent(current2, workInProgress2, didSuspend, nextProps, suspenseInstance, suspenseState, renderLanes2) { + if (!didSuspend) { + warnIfHydrating(); + if ((workInProgress2.mode & ConcurrentMode) === NoMode) { + return retrySuspenseComponentWithoutHydrating(current2, workInProgress2, renderLanes2, null); + } + if (isSuspenseInstanceFallback(suspenseInstance)) { + var digest, message, stack; + { + var _getSuspenseInstanceF = getSuspenseInstanceFallbackErrorDetails(suspenseInstance); + digest = _getSuspenseInstanceF.digest; + message = _getSuspenseInstanceF.message; + stack = _getSuspenseInstanceF.stack; + } + var error2; + if (message) { + error2 = new Error(message); + } else { + error2 = new Error("The server could not finish this Suspense boundary, likely due to an error during server rendering. Switched to client rendering."); + } + var capturedValue = createCapturedValue(error2, digest, stack); + return retrySuspenseComponentWithoutHydrating(current2, workInProgress2, renderLanes2, capturedValue); + } + var hasContextChanged2 = includesSomeLane(renderLanes2, current2.childLanes); + if (didReceiveUpdate || hasContextChanged2) { + var root2 = getWorkInProgressRoot(); + if (root2 !== null) { + var attemptHydrationAtLane = getBumpedLaneForHydration(root2, renderLanes2); + if (attemptHydrationAtLane !== NoLane && attemptHydrationAtLane !== suspenseState.retryLane) { + suspenseState.retryLane = attemptHydrationAtLane; + var eventTime = NoTimestamp; + enqueueConcurrentRenderForLane(current2, attemptHydrationAtLane); + scheduleUpdateOnFiber(root2, current2, attemptHydrationAtLane, eventTime); + } + } + renderDidSuspendDelayIfPossible(); + var _capturedValue = createCapturedValue(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.")); + return retrySuspenseComponentWithoutHydrating(current2, workInProgress2, renderLanes2, _capturedValue); + } else if (isSuspenseInstancePending(suspenseInstance)) { + workInProgress2.flags |= DidCapture; + workInProgress2.child = current2.child; + var retry = retryDehydratedSuspenseBoundary.bind(null, current2); + registerSuspenseInstanceRetry(suspenseInstance, retry); + return null; + } else { + reenterHydrationStateFromDehydratedSuspenseInstance(workInProgress2, suspenseInstance, suspenseState.treeContext); + var primaryChildren = nextProps.children; + var primaryChildFragment = mountSuspensePrimaryChildren(workInProgress2, primaryChildren); + primaryChildFragment.flags |= Hydrating; + return primaryChildFragment; + } + } else { + if (workInProgress2.flags & ForceClientRender) { + workInProgress2.flags &= ~ForceClientRender; + var _capturedValue2 = createCapturedValue(new Error("There was an error while hydrating this Suspense boundary. Switched to client rendering.")); + return retrySuspenseComponentWithoutHydrating(current2, workInProgress2, renderLanes2, _capturedValue2); + } else if (workInProgress2.memoizedState !== null) { + workInProgress2.child = current2.child; + workInProgress2.flags |= DidCapture; + return null; + } else { + var nextPrimaryChildren = nextProps.children; + var nextFallbackChildren = nextProps.fallback; + var fallbackChildFragment = mountSuspenseFallbackAfterRetryWithoutHydrating(current2, workInProgress2, nextPrimaryChildren, nextFallbackChildren, renderLanes2); + var _primaryChildFragment4 = workInProgress2.child; + _primaryChildFragment4.memoizedState = mountSuspenseOffscreenState(renderLanes2); + workInProgress2.memoizedState = SUSPENDED_MARKER; + return fallbackChildFragment; + } + } + } + function scheduleSuspenseWorkOnFiber(fiber, renderLanes2, propagationRoot) { + fiber.lanes = mergeLanes(fiber.lanes, renderLanes2); + var alternate = fiber.alternate; + if (alternate !== null) { + alternate.lanes = mergeLanes(alternate.lanes, renderLanes2); + } + scheduleContextWorkOnParentPath(fiber.return, renderLanes2, propagationRoot); + } + function propagateSuspenseContextChange(workInProgress2, firstChild, renderLanes2) { + var node = firstChild; + while (node !== null) { + if (node.tag === SuspenseComponent) { + var state = node.memoizedState; + if (state !== null) { + scheduleSuspenseWorkOnFiber(node, renderLanes2, workInProgress2); + } + } else if (node.tag === SuspenseListComponent) { + scheduleSuspenseWorkOnFiber(node, renderLanes2, workInProgress2); + } else if (node.child !== null) { + node.child.return = node; + node = node.child; + continue; + } + if (node === workInProgress2) { + return; + } + while (node.sibling === null) { + if (node.return === null || node.return === workInProgress2) { + return; + } + node = node.return; + } + node.sibling.return = node.return; + node = node.sibling; + } + } + function findLastContentRow(firstChild) { + var row = firstChild; + var lastContentRow = null; + while (row !== null) { + var currentRow = row.alternate; + 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 <SuspenseList />. Use lowercase "%s" instead.', revealOrder, revealOrder.toLowerCase()); + break; + } + case "forward": + case "backward": { + error('"%s" is not a valid value for revealOrder on <SuspenseList />. React uses the -s suffix in the spelling. Use "%ss" instead.', revealOrder, revealOrder.toLowerCase()); + break; + } + default: + error('"%s" is not a supported revealOrder on <SuspenseList />. Did you mean "together", "forwards" or "backwards"?', revealOrder); + break; + } + } else { + error('%s is not a supported value for revealOrder on <SuspenseList />. 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 <SuspenseList />. Did you mean "collapsed" or "hidden"?', tailMode); + } else if (revealOrder !== "forwards" && revealOrder !== "backwards") { + didWarnAboutTailOptions[tailMode] = true; + error('<SuspenseList tail="%s" /> is only valid if revealOrder is "forwards" or "backwards". Did you mean to specify revealOrder="forwards"?', tailMode); + } + } + } + } + function validateSuspenseListNestedChild(childSlot, index2) { + { + 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 <SuspenseList />. Wrap it in an additional SuspenseList to configure its revealOrder: <SuspenseList revealOrder=...> ... <SuspenseList revealOrder=...>{%s}</SuspenseList> ... </SuspenseList>", type, index2, 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 <SuspenseList revealOrder="%s" />. This is not useful since it needs multiple rows. Did you mean to pass multiple children or an array?', revealOrder); + } + } + } + } + } + function initSuspenseListRenderState(workInProgress2, isBackwards, tail, lastContentRow, tailMode) { + var renderState = workInProgress2.memoizedState; + if (renderState === null) { + workInProgress2.memoizedState = { + isBackwards, + rendering: null, + renderingStartTime: 0, + last: lastContentRow, + tail, + tailMode + }; + } else { + renderState.isBackwards = isBackwards; + renderState.rendering = null; + renderState.renderingStartTime = 0; + renderState.last = lastContentRow; + renderState.tail = tail; + renderState.tailMode = tailMode; + } + } + function updateSuspenseListComponent(current2, workInProgress2, renderLanes2) { + var nextProps = workInProgress2.pendingProps; + var revealOrder = nextProps.revealOrder; + var tailMode = nextProps.tail; + var newChildren = nextProps.children; + validateRevealOrder(revealOrder); + validateTailOptions(tailMode, revealOrder); + validateSuspenseListChildren(newChildren, revealOrder); + reconcileChildren(current2, workInProgress2, newChildren, renderLanes2); + var suspenseContext = suspenseStackCursor.current; + var shouldForceFallback = hasSuspenseContext(suspenseContext, ForceSuspenseFallback); + if (shouldForceFallback) { + suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback); + workInProgress2.flags |= DidCapture; + } else { + var didSuspendBefore = current2 !== null && (current2.flags & DidCapture) !== NoFlags; + if (didSuspendBefore) { + propagateSuspenseContextChange(workInProgress2, workInProgress2.child, renderLanes2); + } + suspenseContext = setDefaultShallowSuspenseContext(suspenseContext); + } + pushSuspenseContext(workInProgress2, suspenseContext); + if ((workInProgress2.mode & ConcurrentMode) === NoMode) { + workInProgress2.memoizedState = null; + } else { + switch (revealOrder) { + case "forwards": { + var lastContentRow = findLastContentRow(workInProgress2.child); + var tail; + if (lastContentRow === null) { + tail = workInProgress2.child; + workInProgress2.child = null; + } else { + tail = lastContentRow.sibling; + lastContentRow.sibling = null; + } + initSuspenseListRenderState(workInProgress2, false, tail, lastContentRow, tailMode); + break; + } + case "backwards": { + var _tail = null; + var row = workInProgress2.child; + workInProgress2.child = null; + while (row !== null) { + var currentRow = row.alternate; + if (currentRow !== null && findFirstSuspended(currentRow) === null) { + workInProgress2.child = row; + break; + } + var nextRow = row.sibling; + row.sibling = _tail; + _tail = row; + row = nextRow; + } + initSuspenseListRenderState(workInProgress2, true, _tail, null, tailMode); + break; + } + case "together": { + initSuspenseListRenderState(workInProgress2, false, null, null, undefined); + break; + } + default: { + workInProgress2.memoizedState = null; + } + } + } + return workInProgress2.child; + } + function updatePortalComponent(current2, workInProgress2, renderLanes2) { + pushHostContainer(workInProgress2, workInProgress2.stateNode.containerInfo); + var nextChildren = workInProgress2.pendingProps; + if (current2 === null) { + workInProgress2.child = reconcileChildFibers(workInProgress2, null, nextChildren, renderLanes2); + } else { + reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2); + } + return workInProgress2.child; + } + var hasWarnedAboutUsingNoValuePropOnContextProvider = false; + function updateContextProvider(current2, workInProgress2, renderLanes2) { + var providerType = workInProgress2.type; + var context = providerType._context; + var newProps = workInProgress2.pendingProps; + var oldProps = workInProgress2.memoizedProps; + var newValue = newProps.value; + { + if (!("value" in newProps)) { + if (!hasWarnedAboutUsingNoValuePropOnContextProvider) { + hasWarnedAboutUsingNoValuePropOnContextProvider = true; + error("The `value` prop is required for the `<Context.Provider>`. Did you misspell it or forget to pass it?"); + } + } + var providerPropTypes = workInProgress2.type.propTypes; + if (providerPropTypes) { + checkPropTypes(providerPropTypes, newProps, "prop", "Context.Provider"); + } + } + pushProvider(workInProgress2, context, newValue); + { + if (oldProps !== null) { + var oldValue = oldProps.value; + if (objectIs(oldValue, newValue)) { + if (oldProps.children === newProps.children && !hasContextChanged()) { + return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2); + } + } else { + propagateContextChange(workInProgress2, context, renderLanes2); + } + } + } + var newChildren = newProps.children; + reconcileChildren(current2, workInProgress2, newChildren, renderLanes2); + return workInProgress2.child; + } + var hasWarnedAboutUsingContextAsConsumer = false; + function updateContextConsumer(current2, workInProgress2, renderLanes2) { + var context = workInProgress2.type; + { + if (context._context === undefined) { + if (context !== context.Consumer) { + if (!hasWarnedAboutUsingContextAsConsumer) { + hasWarnedAboutUsingContextAsConsumer = true; + error("Rendering <Context> directly is not supported and will be removed in a future major release. Did you mean to render <Context.Consumer> instead?"); + } + } + } else { + context = context._context; + } + } + var newProps = workInProgress2.pendingProps; + var render2 = newProps.children; + { + if (typeof render2 !== "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(workInProgress2, renderLanes2); + var newValue = readContext(context); + { + markComponentRenderStarted(workInProgress2); + } + var newChildren; + { + ReactCurrentOwner$1.current = workInProgress2; + setIsRendering(true); + newChildren = render2(newValue); + setIsRendering(false); + } + { + markComponentRenderStopped(); + } + workInProgress2.flags |= PerformedWork; + reconcileChildren(current2, workInProgress2, newChildren, renderLanes2); + return workInProgress2.child; + } + function markWorkInProgressReceivedUpdate() { + didReceiveUpdate = true; + } + function resetSuspendedCurrentOnMountInLegacyMode(current2, workInProgress2) { + if ((workInProgress2.mode & ConcurrentMode) === NoMode) { + if (current2 !== null) { + current2.alternate = null; + workInProgress2.alternate = null; + workInProgress2.flags |= Placement; + } + } + } + function bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2) { + if (current2 !== null) { + workInProgress2.dependencies = current2.dependencies; + } + { + stopProfilerTimerIfRunning(); + } + markSkippedUpdateLanes(workInProgress2.lanes); + if (!includesSomeLane(renderLanes2, workInProgress2.childLanes)) { + { + return null; + } + } + cloneChildFibers(current2, workInProgress2); + return workInProgress2.child; + } + function remountFiber(current2, oldWorkInProgress, newWorkInProgress) { + { + var returnFiber = oldWorkInProgress.return; + if (returnFiber === null) { + throw new Error("Cannot swap the root fiber."); + } + current2.alternate = null; + oldWorkInProgress.alternate = null; + newWorkInProgress.index = oldWorkInProgress.index; + newWorkInProgress.sibling = oldWorkInProgress.sibling; + newWorkInProgress.return = oldWorkInProgress.return; + newWorkInProgress.ref = oldWorkInProgress.ref; + if (oldWorkInProgress === returnFiber.child) { + returnFiber.child = newWorkInProgress; + } else { + var prevSibling = returnFiber.child; + if (prevSibling === null) { + throw new Error("Expected parent to have a child."); + } + while (prevSibling.sibling !== oldWorkInProgress) { + prevSibling = prevSibling.sibling; + if (prevSibling === null) { + throw new Error("Expected to find the previous sibling."); + } + } + prevSibling.sibling = newWorkInProgress; + } + var deletions = returnFiber.deletions; + if (deletions === null) { + returnFiber.deletions = [current2]; + returnFiber.flags |= ChildDeletion; + } else { + deletions.push(current2); + } + newWorkInProgress.flags |= Placement; + return newWorkInProgress; + } + } + function checkScheduledUpdateOrContext(current2, renderLanes2) { + var updateLanes = current2.lanes; + if (includesSomeLane(updateLanes, renderLanes2)) { + return true; + } + return false; + } + function attemptEarlyBailoutIfNoScheduledUpdate(current2, workInProgress2, renderLanes2) { + switch (workInProgress2.tag) { + case HostRoot: + pushHostRootContext(workInProgress2); + var root2 = workInProgress2.stateNode; + resetHydrationState(); + break; + case HostComponent: + pushHostContext(workInProgress2); + break; + case ClassComponent: { + var Component = workInProgress2.type; + if (isContextProvider(Component)) { + pushContextProvider(workInProgress2); + } + break; + } + case HostPortal: + pushHostContainer(workInProgress2, workInProgress2.stateNode.containerInfo); + break; + case ContextProvider: { + var newValue = workInProgress2.memoizedProps.value; + var context = workInProgress2.type._context; + pushProvider(workInProgress2, context, newValue); + break; + } + case Profiler: + { + var hasChildWork = includesSomeLane(renderLanes2, workInProgress2.childLanes); + if (hasChildWork) { + workInProgress2.flags |= Update; + } + { + var stateNode = workInProgress2.stateNode; + stateNode.effectDuration = 0; + stateNode.passiveEffectDuration = 0; + } + } + break; + case SuspenseComponent: { + var state = workInProgress2.memoizedState; + if (state !== null) { + if (state.dehydrated !== null) { + pushSuspenseContext(workInProgress2, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); + workInProgress2.flags |= DidCapture; + return null; + } + var primaryChildFragment = workInProgress2.child; + var primaryChildLanes = primaryChildFragment.childLanes; + if (includesSomeLane(renderLanes2, primaryChildLanes)) { + return updateSuspenseComponent(current2, workInProgress2, renderLanes2); + } else { + pushSuspenseContext(workInProgress2, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); + var child = bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2); + if (child !== null) { + return child.sibling; + } else { + return null; + } + } + } else { + pushSuspenseContext(workInProgress2, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); + } + break; + } + case SuspenseListComponent: { + var didSuspendBefore = (current2.flags & DidCapture) !== NoFlags; + var _hasChildWork = includesSomeLane(renderLanes2, workInProgress2.childLanes); + if (didSuspendBefore) { + if (_hasChildWork) { + return updateSuspenseListComponent(current2, workInProgress2, renderLanes2); + } + workInProgress2.flags |= DidCapture; + } + var renderState = workInProgress2.memoizedState; + if (renderState !== null) { + renderState.rendering = null; + renderState.tail = null; + renderState.lastEffect = null; + } + pushSuspenseContext(workInProgress2, suspenseStackCursor.current); + if (_hasChildWork) { + break; + } else { + return null; + } + } + case OffscreenComponent: + case LegacyHiddenComponent: { + workInProgress2.lanes = NoLanes; + return updateOffscreenComponent(current2, workInProgress2, renderLanes2); + } + } + return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2); + } + function beginWork(current2, workInProgress2, renderLanes2) { + { + if (workInProgress2._debugNeedsRemount && current2 !== null) { + return remountFiber(current2, workInProgress2, createFiberFromTypeAndProps(workInProgress2.type, workInProgress2.key, workInProgress2.pendingProps, workInProgress2._debugOwner || null, workInProgress2.mode, workInProgress2.lanes)); + } + } + if (current2 !== null) { + var oldProps = current2.memoizedProps; + var newProps = workInProgress2.pendingProps; + if (oldProps !== newProps || hasContextChanged() || workInProgress2.type !== current2.type) { + didReceiveUpdate = true; + } else { + var hasScheduledUpdateOrContext = checkScheduledUpdateOrContext(current2, renderLanes2); + if (!hasScheduledUpdateOrContext && (workInProgress2.flags & DidCapture) === NoFlags) { + didReceiveUpdate = false; + return attemptEarlyBailoutIfNoScheduledUpdate(current2, workInProgress2, renderLanes2); + } + if ((current2.flags & ForceUpdateForLegacySuspense) !== NoFlags) { + didReceiveUpdate = true; + } else { + didReceiveUpdate = false; + } + } + } else { + didReceiveUpdate = false; + if (getIsHydrating() && isForkedChild(workInProgress2)) { + var slotIndex = workInProgress2.index; + var numberOfForks = getForksAtLevel(); + pushTreeId(workInProgress2, numberOfForks, slotIndex); + } + } + workInProgress2.lanes = NoLanes; + switch (workInProgress2.tag) { + case IndeterminateComponent: { + return mountIndeterminateComponent(current2, workInProgress2, workInProgress2.type, renderLanes2); + } + case LazyComponent: { + var elementType = workInProgress2.elementType; + return mountLazyComponent(current2, workInProgress2, elementType, renderLanes2); + } + case FunctionComponent: { + var Component = workInProgress2.type; + var unresolvedProps = workInProgress2.pendingProps; + var resolvedProps = workInProgress2.elementType === Component ? unresolvedProps : resolveDefaultProps(Component, unresolvedProps); + return updateFunctionComponent(current2, workInProgress2, Component, resolvedProps, renderLanes2); + } + case ClassComponent: { + var _Component = workInProgress2.type; + var _unresolvedProps = workInProgress2.pendingProps; + var _resolvedProps = workInProgress2.elementType === _Component ? _unresolvedProps : resolveDefaultProps(_Component, _unresolvedProps); + return updateClassComponent(current2, workInProgress2, _Component, _resolvedProps, renderLanes2); + } + case HostRoot: + return updateHostRoot(current2, workInProgress2, renderLanes2); + case HostComponent: + return updateHostComponent(current2, workInProgress2, renderLanes2); + case HostText: + return updateHostText(current2, workInProgress2); + case SuspenseComponent: + return updateSuspenseComponent(current2, workInProgress2, renderLanes2); + case HostPortal: + return updatePortalComponent(current2, workInProgress2, renderLanes2); + case ForwardRef: { + var type = workInProgress2.type; + var _unresolvedProps2 = workInProgress2.pendingProps; + var _resolvedProps2 = workInProgress2.elementType === type ? _unresolvedProps2 : resolveDefaultProps(type, _unresolvedProps2); + return updateForwardRef(current2, workInProgress2, type, _resolvedProps2, renderLanes2); + } + case Fragment: + return updateFragment(current2, workInProgress2, renderLanes2); + case Mode: + return updateMode(current2, workInProgress2, renderLanes2); + case Profiler: + return updateProfiler(current2, workInProgress2, renderLanes2); + case ContextProvider: + return updateContextProvider(current2, workInProgress2, renderLanes2); + case ContextConsumer: + return updateContextConsumer(current2, workInProgress2, renderLanes2); + case MemoComponent: { + var _type2 = workInProgress2.type; + var _unresolvedProps3 = workInProgress2.pendingProps; + var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3); + { + if (workInProgress2.type !== workInProgress2.elementType) { + var outerPropTypes = _type2.propTypes; + if (outerPropTypes) { + checkPropTypes(outerPropTypes, _resolvedProps3, "prop", getComponentNameFromType(_type2)); + } + } + } + _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3); + return updateMemoComponent(current2, workInProgress2, _type2, _resolvedProps3, renderLanes2); + } + case SimpleMemoComponent: { + return updateSimpleMemoComponent(current2, workInProgress2, workInProgress2.type, workInProgress2.pendingProps, renderLanes2); + } + case IncompleteClassComponent: { + var _Component2 = workInProgress2.type; + var _unresolvedProps4 = workInProgress2.pendingProps; + var _resolvedProps4 = workInProgress2.elementType === _Component2 ? _unresolvedProps4 : resolveDefaultProps(_Component2, _unresolvedProps4); + return mountIncompleteClassComponent(current2, workInProgress2, _Component2, _resolvedProps4, renderLanes2); + } + case SuspenseListComponent: { + return updateSuspenseListComponent(current2, workInProgress2, renderLanes2); + } + case ScopeComponent: { + break; + } + case OffscreenComponent: { + return updateOffscreenComponent(current2, workInProgress2, renderLanes2); + } + } + throw new Error("Unknown unit of work tag (" + workInProgress2.tag + "). This error is likely caused by a bug in React. Please file an issue."); + } + function markUpdate(workInProgress2) { + workInProgress2.flags |= Update; + } + function markRef$1(workInProgress2) { + workInProgress2.flags |= Ref; + { + workInProgress2.flags |= RefStatic; + } + } + var appendAllChildren; + var updateHostContainer; + var updateHostComponent$1; + var updateHostText$1; + { + appendAllChildren = function(parent, workInProgress2, needsVisibilityToggle, isHidden) { + var node = workInProgress2.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 === workInProgress2) { + return; + } + while (node.sibling === null) { + if (node.return === null || node.return === workInProgress2) { + return; + } + node = node.return; + } + node.sibling.return = node.return; + node = node.sibling; + } + }; + updateHostContainer = function(current2, workInProgress2) { + }; + updateHostComponent$1 = function(current2, workInProgress2, type, newProps, rootContainerInstance) { + var oldProps = current2.memoizedProps; + if (oldProps === newProps) { + return; + } + var instance = workInProgress2.stateNode; + var currentHostContext = getHostContext(); + var updatePayload = prepareUpdate(instance, type, oldProps, newProps, rootContainerInstance, currentHostContext); + workInProgress2.updateQueue = updatePayload; + if (updatePayload) { + markUpdate(workInProgress2); + } + }; + updateHostText$1 = function(current2, workInProgress2, oldText, newText) { + if (oldText !== newText) { + markUpdate(workInProgress2); + } + }; + } + function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) { + if (getIsHydrating()) { + return; + } + switch (renderState.tailMode) { + case "hidden": { + var tailNode = renderState.tail; + var lastTailNode = null; + while (tailNode !== null) { + if (tailNode.alternate !== null) { + lastTailNode = tailNode; + } + tailNode = tailNode.sibling; + } + if (lastTailNode === null) { + renderState.tail = null; + } else { + lastTailNode.sibling = null; + } + break; + } + case "collapsed": { + var _tailNode = renderState.tail; + var _lastTailNode = null; + while (_tailNode !== null) { + if (_tailNode.alternate !== null) { + _lastTailNode = _tailNode; + } + _tailNode = _tailNode.sibling; + } + if (_lastTailNode === null) { + if (!hasRenderedATailFallback && renderState.tail !== null) { + renderState.tail.sibling = null; + } else { + renderState.tail = null; + } + } else { + _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) { + if ((completedWork.mode & ProfileMode) !== NoMode) { + 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; + 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; + _child.return = completedWork; + _child = _child.sibling; + } + } + completedWork.subtreeFlags |= subtreeFlags; + } else { + if ((completedWork.mode & ProfileMode) !== NoMode) { + var _treeBaseDuration = completedWork.selfBaseDuration; + var _child2 = completedWork.child; + while (_child2 !== null) { + newChildLanes = mergeLanes(newChildLanes, mergeLanes(_child2.lanes, _child2.childLanes)); + 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)); + subtreeFlags |= _child3.subtreeFlags & StaticMask; + subtreeFlags |= _child3.flags & StaticMask; + _child3.return = completedWork; + _child3 = _child3.sibling; + } + } + completedWork.subtreeFlags |= subtreeFlags; + } + completedWork.childLanes = newChildLanes; + return didBailout; + } + function completeDehydratedSuspenseBoundary(current2, workInProgress2, nextState) { + if (hasUnhydratedTailNodes() && (workInProgress2.mode & ConcurrentMode) !== NoMode && (workInProgress2.flags & DidCapture) === NoFlags) { + warnIfUnhydratedTailNodes(workInProgress2); + resetHydrationState(); + workInProgress2.flags |= ForceClientRender | Incomplete | ShouldCapture; + return false; + } + var wasHydrated = popHydrationState(workInProgress2); + if (nextState !== null && nextState.dehydrated !== null) { + if (current2 === null) { + if (!wasHydrated) { + throw new Error("A dehydrated suspense component was completed without a hydrated node. This is probably a bug in React."); + } + prepareToHydrateHostSuspenseInstance(workInProgress2); + bubbleProperties(workInProgress2); + { + if ((workInProgress2.mode & ProfileMode) !== NoMode) { + var isTimedOutSuspense = nextState !== null; + if (isTimedOutSuspense) { + var primaryChildFragment = workInProgress2.child; + if (primaryChildFragment !== null) { + workInProgress2.treeBaseDuration -= primaryChildFragment.treeBaseDuration; + } + } + } + } + return false; + } else { + resetHydrationState(); + if ((workInProgress2.flags & DidCapture) === NoFlags) { + workInProgress2.memoizedState = null; + } + workInProgress2.flags |= Update; + bubbleProperties(workInProgress2); + { + if ((workInProgress2.mode & ProfileMode) !== NoMode) { + var _isTimedOutSuspense = nextState !== null; + if (_isTimedOutSuspense) { + var _primaryChildFragment = workInProgress2.child; + if (_primaryChildFragment !== null) { + workInProgress2.treeBaseDuration -= _primaryChildFragment.treeBaseDuration; + } + } + } + } + return false; + } + } else { + upgradeHydrationErrorsToRecoverable(); + return true; + } + } + function completeWork(current2, workInProgress2, renderLanes2) { + var newProps = workInProgress2.pendingProps; + popTreeContext(workInProgress2); + switch (workInProgress2.tag) { + case IndeterminateComponent: + case LazyComponent: + case SimpleMemoComponent: + case FunctionComponent: + case ForwardRef: + case Fragment: + case Mode: + case Profiler: + case ContextConsumer: + case MemoComponent: + bubbleProperties(workInProgress2); + return null; + case ClassComponent: { + var Component = workInProgress2.type; + if (isContextProvider(Component)) { + popContext(workInProgress2); + } + bubbleProperties(workInProgress2); + return null; + } + case HostRoot: { + var fiberRoot = workInProgress2.stateNode; + popHostContainer(workInProgress2); + popTopLevelContextObject(workInProgress2); + resetWorkInProgressVersions(); + if (fiberRoot.pendingContext) { + fiberRoot.context = fiberRoot.pendingContext; + fiberRoot.pendingContext = null; + } + if (current2 === null || current2.child === null) { + var wasHydrated = popHydrationState(workInProgress2); + if (wasHydrated) { + markUpdate(workInProgress2); + } else { + if (current2 !== null) { + var prevState = current2.memoizedState; + if (!prevState.isDehydrated || (workInProgress2.flags & ForceClientRender) !== NoFlags) { + workInProgress2.flags |= Snapshot; + upgradeHydrationErrorsToRecoverable(); + } + } + } + } + updateHostContainer(current2, workInProgress2); + bubbleProperties(workInProgress2); + return null; + } + case HostComponent: { + popHostContext(workInProgress2); + var rootContainerInstance = getRootHostContainer(); + var type = workInProgress2.type; + if (current2 !== null && workInProgress2.stateNode != null) { + updateHostComponent$1(current2, workInProgress2, type, newProps, rootContainerInstance); + if (current2.ref !== workInProgress2.ref) { + markRef$1(workInProgress2); + } + } else { + if (!newProps) { + if (workInProgress2.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."); + } + bubbleProperties(workInProgress2); + return null; + } + var currentHostContext = getHostContext(); + var _wasHydrated = popHydrationState(workInProgress2); + if (_wasHydrated) { + if (prepareToHydrateHostInstance(workInProgress2, rootContainerInstance, currentHostContext)) { + markUpdate(workInProgress2); + } + } else { + var instance = createInstance(type, newProps, rootContainerInstance, currentHostContext, workInProgress2); + appendAllChildren(instance, workInProgress2, false, false); + workInProgress2.stateNode = instance; + if (finalizeInitialChildren(instance, type, newProps, rootContainerInstance)) { + markUpdate(workInProgress2); + } + } + if (workInProgress2.ref !== null) { + markRef$1(workInProgress2); + } + } + bubbleProperties(workInProgress2); + return null; + } + case HostText: { + var newText = newProps; + if (current2 && workInProgress2.stateNode != null) { + var oldText = current2.memoizedProps; + updateHostText$1(current2, workInProgress2, oldText, newText); + } else { + if (typeof newText !== "string") { + if (workInProgress2.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."); + } + } + var _rootContainerInstance = getRootHostContainer(); + var _currentHostContext = getHostContext(); + var _wasHydrated2 = popHydrationState(workInProgress2); + if (_wasHydrated2) { + if (prepareToHydrateHostTextInstance(workInProgress2)) { + markUpdate(workInProgress2); + } + } else { + workInProgress2.stateNode = createTextInstance(newText, _rootContainerInstance, _currentHostContext, workInProgress2); + } + } + bubbleProperties(workInProgress2); + return null; + } + case SuspenseComponent: { + popSuspenseContext(workInProgress2); + var nextState = workInProgress2.memoizedState; + if (current2 === null || current2.memoizedState !== null && current2.memoizedState.dehydrated !== null) { + var fallthroughToNormalSuspensePath = completeDehydratedSuspenseBoundary(current2, workInProgress2, nextState); + if (!fallthroughToNormalSuspensePath) { + if (workInProgress2.flags & ShouldCapture) { + return workInProgress2; + } else { + return null; + } + } + } + if ((workInProgress2.flags & DidCapture) !== NoFlags) { + workInProgress2.lanes = renderLanes2; + if ((workInProgress2.mode & ProfileMode) !== NoMode) { + transferActualDuration(workInProgress2); + } + return workInProgress2; + } + var nextDidTimeout = nextState !== null; + var prevDidTimeout = current2 !== null && current2.memoizedState !== null; + if (nextDidTimeout !== prevDidTimeout) { + if (nextDidTimeout) { + var _offscreenFiber2 = workInProgress2.child; + _offscreenFiber2.flags |= Visibility; + if ((workInProgress2.mode & ConcurrentMode) !== NoMode) { + var hasInvisibleChildContext = current2 === null && (workInProgress2.memoizedProps.unstable_avoidThisFallback !== true || !enableSuspenseAvoidThisFallback); + if (hasInvisibleChildContext || hasSuspenseContext(suspenseStackCursor.current, InvisibleParentSuspenseContext)) { + renderDidSuspend(); + } else { + renderDidSuspendDelayIfPossible(); + } + } + } + } + var wakeables = workInProgress2.updateQueue; + if (wakeables !== null) { + workInProgress2.flags |= Update; + } + bubbleProperties(workInProgress2); + { + if ((workInProgress2.mode & ProfileMode) !== NoMode) { + if (nextDidTimeout) { + var primaryChildFragment = workInProgress2.child; + if (primaryChildFragment !== null) { + workInProgress2.treeBaseDuration -= primaryChildFragment.treeBaseDuration; + } + } + } + } + return null; + } + case HostPortal: + popHostContainer(workInProgress2); + updateHostContainer(current2, workInProgress2); + if (current2 === null) { + preparePortalMount(workInProgress2.stateNode.containerInfo); + } + bubbleProperties(workInProgress2); + return null; + case ContextProvider: + var context = workInProgress2.type._context; + popProvider(context, workInProgress2); + bubbleProperties(workInProgress2); + return null; + case IncompleteClassComponent: { + var _Component = workInProgress2.type; + if (isContextProvider(_Component)) { + popContext(workInProgress2); + } + bubbleProperties(workInProgress2); + return null; + } + case SuspenseListComponent: { + popSuspenseContext(workInProgress2); + var renderState = workInProgress2.memoizedState; + if (renderState === null) { + bubbleProperties(workInProgress2); + return null; + } + var didSuspendAlready = (workInProgress2.flags & DidCapture) !== NoFlags; + var renderedTail = renderState.rendering; + if (renderedTail === null) { + if (!didSuspendAlready) { + var cannotBeSuspended = renderHasNotSuspendedYet() && (current2 === null || (current2.flags & DidCapture) === NoFlags); + if (!cannotBeSuspended) { + var row = workInProgress2.child; + while (row !== null) { + var suspended = findFirstSuspended(row); + if (suspended !== null) { + didSuspendAlready = true; + workInProgress2.flags |= DidCapture; + cutOffTailIfNeeded(renderState, false); + var newThenables = suspended.updateQueue; + if (newThenables !== null) { + workInProgress2.updateQueue = newThenables; + workInProgress2.flags |= Update; + } + workInProgress2.subtreeFlags = NoFlags; + resetChildFibers(workInProgress2, renderLanes2); + pushSuspenseContext(workInProgress2, setShallowSuspenseContext(suspenseStackCursor.current, ForceSuspenseFallback)); + return workInProgress2.child; + } + row = row.sibling; + } + } + if (renderState.tail !== null && now() > getRenderTargetTime()) { + workInProgress2.flags |= DidCapture; + didSuspendAlready = true; + cutOffTailIfNeeded(renderState, false); + workInProgress2.lanes = SomeRetryLane; + } + } else { + cutOffTailIfNeeded(renderState, false); + } + } else { + if (!didSuspendAlready) { + var _suspended = findFirstSuspended(renderedTail); + if (_suspended !== null) { + workInProgress2.flags |= DidCapture; + didSuspendAlready = true; + var _newThenables = _suspended.updateQueue; + if (_newThenables !== null) { + workInProgress2.updateQueue = _newThenables; + workInProgress2.flags |= Update; + } + cutOffTailIfNeeded(renderState, true); + if (renderState.tail === null && renderState.tailMode === "hidden" && !renderedTail.alternate && !getIsHydrating()) { + bubbleProperties(workInProgress2); + return null; + } + } else if (now() * 2 - renderState.renderingStartTime > getRenderTargetTime() && renderLanes2 !== OffscreenLane) { + workInProgress2.flags |= DidCapture; + didSuspendAlready = true; + cutOffTailIfNeeded(renderState, false); + workInProgress2.lanes = SomeRetryLane; + } + } + if (renderState.isBackwards) { + renderedTail.sibling = workInProgress2.child; + workInProgress2.child = renderedTail; + } else { + var previousSibling = renderState.last; + if (previousSibling !== null) { + previousSibling.sibling = renderedTail; + } else { + workInProgress2.child = renderedTail; + } + renderState.last = renderedTail; + } + } + if (renderState.tail !== null) { + var next = renderState.tail; + renderState.rendering = next; + renderState.tail = next.sibling; + renderState.renderingStartTime = now(); + next.sibling = null; + var suspenseContext = suspenseStackCursor.current; + if (didSuspendAlready) { + suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback); + } else { + suspenseContext = setDefaultShallowSuspenseContext(suspenseContext); + } + pushSuspenseContext(workInProgress2, suspenseContext); + return next; + } + bubbleProperties(workInProgress2); + return null; + } + case ScopeComponent: { + break; + } + case OffscreenComponent: + case LegacyHiddenComponent: { + popRenderLanes(workInProgress2); + var _nextState = workInProgress2.memoizedState; + var nextIsHidden = _nextState !== null; + if (current2 !== null) { + var _prevState = current2.memoizedState; + var prevIsHidden = _prevState !== null; + if (prevIsHidden !== nextIsHidden && !enableLegacyHidden) { + workInProgress2.flags |= Visibility; + } + } + if (!nextIsHidden || (workInProgress2.mode & ConcurrentMode) === NoMode) { + bubbleProperties(workInProgress2); + } else { + if (includesSomeLane(subtreeRenderLanes, OffscreenLane)) { + bubbleProperties(workInProgress2); + { + if (workInProgress2.subtreeFlags & (Placement | Update)) { + workInProgress2.flags |= Visibility; + } + } + } + } + return null; + } + case CacheComponent: { + return null; + } + case TracingMarkerComponent: { + return null; + } + } + throw new Error("Unknown unit of work tag (" + workInProgress2.tag + "). This error is likely caused by a bug in React. Please file an issue."); + } + function unwindWork(current2, workInProgress2, renderLanes2) { + popTreeContext(workInProgress2); + switch (workInProgress2.tag) { + case ClassComponent: { + var Component = workInProgress2.type; + if (isContextProvider(Component)) { + popContext(workInProgress2); + } + var flags = workInProgress2.flags; + if (flags & ShouldCapture) { + workInProgress2.flags = flags & ~ShouldCapture | DidCapture; + if ((workInProgress2.mode & ProfileMode) !== NoMode) { + transferActualDuration(workInProgress2); + } + return workInProgress2; + } + return null; + } + case HostRoot: { + var root2 = workInProgress2.stateNode; + popHostContainer(workInProgress2); + popTopLevelContextObject(workInProgress2); + resetWorkInProgressVersions(); + var _flags = workInProgress2.flags; + if ((_flags & ShouldCapture) !== NoFlags && (_flags & DidCapture) === NoFlags) { + workInProgress2.flags = _flags & ~ShouldCapture | DidCapture; + return workInProgress2; + } + return null; + } + case HostComponent: { + popHostContext(workInProgress2); + return null; + } + case SuspenseComponent: { + popSuspenseContext(workInProgress2); + var suspenseState = workInProgress2.memoizedState; + if (suspenseState !== null && suspenseState.dehydrated !== null) { + if (workInProgress2.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 = workInProgress2.flags; + if (_flags2 & ShouldCapture) { + workInProgress2.flags = _flags2 & ~ShouldCapture | DidCapture; + if ((workInProgress2.mode & ProfileMode) !== NoMode) { + transferActualDuration(workInProgress2); + } + return workInProgress2; + } + return null; + } + case SuspenseListComponent: { + popSuspenseContext(workInProgress2); + return null; + } + case HostPortal: + popHostContainer(workInProgress2); + return null; + case ContextProvider: + var context = workInProgress2.type._context; + popProvider(context, workInProgress2); + return null; + case OffscreenComponent: + case LegacyHiddenComponent: + popRenderLanes(workInProgress2); + return null; + case CacheComponent: + return null; + default: + return null; + } + } + function unwindInterruptedWork(current2, interruptedWork, renderLanes2) { + popTreeContext(interruptedWork); + switch (interruptedWork.tag) { + case ClassComponent: { + var childContextTypes = interruptedWork.type.childContextTypes; + if (childContextTypes !== null && childContextTypes !== undefined) { + popContext(interruptedWork); + } + break; + } + case HostRoot: { + var root2 = interruptedWork.stateNode; + 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; + } + } + var didWarnAboutUndefinedSnapshotBeforeUpdate = null; + { + didWarnAboutUndefinedSnapshotBeforeUpdate = new Set; + } + var offscreenSubtreeIsHidden = false; + var offscreenSubtreeWasHidden = false; + var PossiblyWeakSet = typeof WeakSet === "function" ? WeakSet : Set; + var nextEffect = null; + var inProgressLanes = null; + var inProgressRoot = null; + function reportUncaughtErrorInDEV(error2) { + { + invokeGuardedCallback(null, function() { + throw error2; + }); + clearCaughtError(); + } + } + var callComponentWillUnmountWithTimer = function(current2, instance) { + instance.props = current2.memoizedProps; + instance.state = current2.memoizedState; + if (current2.mode & ProfileMode) { + try { + startLayoutEffectTimer(); + instance.componentWillUnmount(); + } finally { + recordLayoutEffectDuration(current2); + } + } else { + instance.componentWillUnmount(); + } + }; + function safelyCallCommitHookLayoutEffectListMount(current2, nearestMountedAncestor) { + try { + commitHookEffectListMount(Layout, current2); + } catch (error2) { + captureCommitPhaseError(current2, nearestMountedAncestor, error2); + } + } + function safelyCallComponentWillUnmount(current2, nearestMountedAncestor, instance) { + try { + callComponentWillUnmountWithTimer(current2, instance); + } catch (error2) { + captureCommitPhaseError(current2, nearestMountedAncestor, error2); + } + } + function safelyCallComponentDidMount(current2, nearestMountedAncestor, instance) { + try { + instance.componentDidMount(); + } catch (error2) { + captureCommitPhaseError(current2, nearestMountedAncestor, error2); + } + } + function safelyAttachRef(current2, nearestMountedAncestor) { + try { + commitAttachRef(current2); + } catch (error2) { + captureCommitPhaseError(current2, nearestMountedAncestor, error2); + } + } + function safelyDetachRef(current2, nearestMountedAncestor) { + var ref = current2.ref; + if (ref !== null) { + if (typeof ref === "function") { + var retVal; + try { + if (enableProfilerTimer && enableProfilerCommitHooks && current2.mode & ProfileMode) { + try { + startLayoutEffectTimer(); + retVal = ref(null); + } finally { + recordLayoutEffectDuration(current2); + } + } else { + retVal = ref(null); + } + } catch (error2) { + captureCommitPhaseError(current2, nearestMountedAncestor, error2); + } + { + if (typeof retVal === "function") { + error("Unexpected return value from a callback ref in %s. A callback ref should not return a function.", getComponentNameFromFiber(current2)); + } + } + } else { + ref.current = null; + } + } + } + function safelyCallDestroy(current2, nearestMountedAncestor, destroy) { + try { + destroy(); + } catch (error2) { + captureCommitPhaseError(current2, nearestMountedAncestor, error2); + } + } + var focusedInstanceHandle = null; + var shouldFireAfterActiveInstanceBlur = false; + function commitBeforeMutationEffects(root2, firstChild) { + focusedInstanceHandle = prepareForCommit(root2.containerInfo); + nextEffect = firstChild; + commitBeforeMutationEffects_begin(); + var shouldFire = shouldFireAfterActiveInstanceBlur; + shouldFireAfterActiveInstanceBlur = false; + focusedInstanceHandle = null; + return shouldFire; + } + function commitBeforeMutationEffects_begin() { + while (nextEffect !== null) { + var fiber = nextEffect; + var child = fiber.child; + if ((fiber.subtreeFlags & BeforeMutationMask) !== NoFlags && child !== null) { + child.return = fiber; + nextEffect = child; + } else { + commitBeforeMutationEffects_complete(); + } + } + } + function commitBeforeMutationEffects_complete() { + while (nextEffect !== null) { + var fiber = nextEffect; + setCurrentFiber(fiber); + try { + commitBeforeMutationEffectsOnFiber(fiber); + } catch (error2) { + captureCommitPhaseError(fiber, fiber.return, error2); + } + resetCurrentFiber(); + var sibling = fiber.sibling; + if (sibling !== null) { + sibling.return = fiber.return; + nextEffect = sibling; + return; + } + nextEffect = fiber.return; + } + } + function commitBeforeMutationEffectsOnFiber(finishedWork) { + var current2 = 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 (current2 !== null) { + var prevProps = current2.memoizedProps; + var prevState = current2.memoizedState; + var instance = finishedWork.stateNode; + { + 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: { + { + var root2 = finishedWork.stateNode; + clearContainer(root2.containerInfo); + } + break; + } + case HostComponent: + case HostText: + case HostPortal: + case IncompleteClassComponent: + 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) { + 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); + } + } + { + if ((flags & Insertion) !== NoFlags$1) { + setIsRunningInsertionEffect(true); + } + } + safelyCallDestroy(finishedWork, nearestMountedAncestor, destroy); + { + if ((flags & Insertion) !== NoFlags$1) { + setIsRunningInsertionEffect(false); + } + } + { + 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); + } + } + var create = effect.create; + { + if ((flags & Insertion) !== NoFlags$1) { + setIsRunningInsertionEffect(true); + } + } + effect.destroy = create(); + { + if ((flags & Insertion) !== NoFlags$1) { + setIsRunningInsertionEffect(false); + } + } + { + 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 = undefined; + if ((effect.tag & Layout) !== NoFlags) { + hookName = "useLayoutEffect"; + } else if ((effect.tag & Insertion) !== NoFlags) { + hookName = "useInsertionEffect"; + } else { + hookName = "useEffect"; + } + var addendum = undefined; + 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\nLearn 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) { + { + 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; + var commitTime2 = getCommitTime(); + var phase = finishedWork.alternate === null ? "mount" : "update"; + { + if (isCurrentUpdateNested()) { + phase = "nested-update"; + } + } + if (typeof onPostCommit === "function") { + onPostCommit(id, phase, passiveEffectDuration, commitTime2); + } + var parentFiber = finishedWork.return; + outer: + while (parentFiber !== null) { + switch (parentFiber.tag) { + case HostRoot: + var root2 = parentFiber.stateNode; + root2.passiveEffectDuration += passiveEffectDuration; + break outer; + case Profiler: + var parentStateNode = parentFiber.stateNode; + parentStateNode.passiveEffectDuration += passiveEffectDuration; + break outer; + } + parentFiber = parentFiber.return; + } + break; + } + } + } + } + } + function commitLayoutEffectOnFiber(finishedRoot, current2, finishedWork, committedLanes) { + if ((finishedWork.flags & LayoutMask) !== NoFlags) { + switch (finishedWork.tag) { + case FunctionComponent: + case ForwardRef: + case SimpleMemoComponent: { + if (!offscreenSubtreeWasHidden) { + 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 (current2 === null) { + { + 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 ? current2.memoizedProps : resolveDefaultProps(finishedWork.type, current2.memoizedProps); + var prevState = current2.memoizedState; + { + 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); + } + } + } + } + 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"); + } + } + } + commitUpdateQueue(finishedWork, updateQueue, instance); + } + break; + } + case HostRoot: { + 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; + if (current2 === null && finishedWork.flags & Update) { + var type = finishedWork.type; + var props = finishedWork.memoizedProps; + commitMount(_instance2, type, props); + } + break; + } + case HostText: { + break; + } + case HostPortal: { + break; + } + case Profiler: { + { + var _finishedWork$memoize2 = finishedWork.memoizedProps, onCommit = _finishedWork$memoize2.onCommit, onRender = _finishedWork$memoize2.onRender; + var effectDuration = finishedWork.stateNode.effectDuration; + var commitTime2 = getCommitTime(); + var phase = current2 === null ? "mount" : "update"; + { + if (isCurrentUpdateNested()) { + phase = "nested-update"; + } + } + if (typeof onRender === "function") { + onRender(finishedWork.memoizedProps.id, phase, finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, commitTime2); + } + { + if (typeof onCommit === "function") { + onCommit(finishedWork.memoizedProps.id, phase, effectDuration, commitTime2); + } + enqueuePendingPassiveProfilerEffect(finishedWork); + var parentFiber = finishedWork.return; + outer: + while (parentFiber !== null) { + switch (parentFiber.tag) { + case HostRoot: + var root2 = parentFiber.stateNode; + root2.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: + case TracingMarkerComponent: { + 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) { + 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) { + var hostSubtreeRoot = null; + { + var node = finishedWork; + while (true) { + if (node.tag === HostComponent) { + if (hostSubtreeRoot === null) { + hostSubtreeRoot = node; + try { + var instance = node.stateNode; + if (isHidden) { + hideInstance(instance); + } else { + unhideInstance(node.stateNode, node.memoizedProps); + } + } catch (error2) { + captureCommitPhaseError(finishedWork, finishedWork.return, error2); + } + } + } else if (node.tag === HostText) { + if (hostSubtreeRoot === null) { + try { + var _instance3 = node.stateNode; + if (isHidden) { + hideTextInstance(_instance3); + } else { + unhideTextInstance(_instance3, node.memoizedProps); + } + } catch (error2) { + captureCommitPhaseError(finishedWork, finishedWork.return, error2); + } + } + } 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; + } + 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 detachFiberMutation(fiber) { + 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); + } + { + fiber.child = null; + fiber.deletions = null; + fiber.sibling = null; + if (fiber.tag === HostComponent) { + var hostInstance = fiber.stateNode; + if (hostInstance !== null) { + detachDeletedInstance(hostInstance); + } + } + fiber.stateNode = null; + { + fiber._debugOwner = null; + } + { + fiber.return = null; + fiber.dependencies = null; + fiber.memoizedProps = null; + fiber.memoizedState = null; + fiber.pendingProps = null; + fiber.stateNode = null; + fiber.updateQueue = null; + } + } + } + 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) { + var node = fiber; + siblings: + while (true) { + while (node.sibling === null) { + if (node.return === null || isHostParent(node.return)) { + return null; + } + node = node.return; + } + node.sibling.return = node.return; + node = node.sibling; + while (node.tag !== HostComponent && node.tag !== HostText && node.tag !== DehydratedFragment) { + if (node.flags & Placement) { + continue siblings; + } + if (node.child === null || node.tag === HostPortal) { + continue siblings; + } else { + node.child.return = node; + node = node.child; + } + } + if (!(node.flags & Placement)) { + return node.stateNode; + } + } + } + function commitPlacement(finishedWork) { + var parentFiber = getHostParentFiber(finishedWork); + switch (parentFiber.tag) { + case HostComponent: { + var parent = parentFiber.stateNode; + if (parentFiber.flags & ContentReset) { + resetTextContent(parent); + parentFiber.flags &= ~ContentReset; + } + var before = getHostSibling(finishedWork); + insertOrAppendPlacementNode(finishedWork, before, parent); + break; + } + case HostRoot: + case HostPortal: { + var _parent = parentFiber.stateNode.containerInfo; + var _before = getHostSibling(finishedWork); + insertOrAppendPlacementNodeIntoContainer(finishedWork, _before, _parent); + break; + } + 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; + } + } + } + } + var hostParent = null; + var hostParentIsContainer = false; + function commitDeletionEffects(root2, returnFiber, deletedFiber) { + { + var parent = returnFiber; + findParent: + while (parent !== null) { + switch (parent.tag) { + case HostComponent: { + hostParent = parent.stateNode; + hostParentIsContainer = false; + break findParent; + } + case HostRoot: { + hostParent = parent.stateNode.containerInfo; + hostParentIsContainer = true; + break findParent; + } + case HostPortal: { + hostParent = parent.stateNode.containerInfo; + hostParentIsContainer = true; + break findParent; + } + } + parent = parent.return; + } + if (hostParent === null) { + throw new Error("Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue."); + } + commitDeletionEffectsOnFiber(root2, returnFiber, deletedFiber); + hostParent = null; + hostParentIsContainer = false; + } + detachFiberMutation(deletedFiber); + } + function recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, parent) { + var child = parent.child; + while (child !== null) { + commitDeletionEffectsOnFiber(finishedRoot, nearestMountedAncestor, child); + child = child.sibling; + } + } + function commitDeletionEffectsOnFiber(finishedRoot, nearestMountedAncestor, deletedFiber) { + onCommitUnmount(deletedFiber); + switch (deletedFiber.tag) { + case HostComponent: { + if (!offscreenSubtreeWasHidden) { + safelyDetachRef(deletedFiber, nearestMountedAncestor); + } + } + case HostText: { + { + var prevHostParent = hostParent; + var prevHostParentIsContainer = hostParentIsContainer; + hostParent = null; + recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber); + hostParent = prevHostParent; + hostParentIsContainer = prevHostParentIsContainer; + if (hostParent !== null) { + if (hostParentIsContainer) { + removeChildFromContainer(hostParent, deletedFiber.stateNode); + } else { + removeChild(hostParent, deletedFiber.stateNode); + } + } + } + return; + } + case DehydratedFragment: { + { + if (hostParent !== null) { + if (hostParentIsContainer) { + clearSuspenseBoundaryFromContainer(hostParent, deletedFiber.stateNode); + } else { + clearSuspenseBoundary(hostParent, deletedFiber.stateNode); + } + } + } + return; + } + case HostPortal: { + { + var _prevHostParent = hostParent; + var _prevHostParentIsContainer = hostParentIsContainer; + hostParent = deletedFiber.stateNode.containerInfo; + hostParentIsContainer = true; + recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber); + hostParent = _prevHostParent; + hostParentIsContainer = _prevHostParentIsContainer; + } + return; + } + case FunctionComponent: + case ForwardRef: + case MemoComponent: + case SimpleMemoComponent: { + if (!offscreenSubtreeWasHidden) { + var updateQueue = deletedFiber.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(deletedFiber, nearestMountedAncestor, destroy); + } else if ((tag & Layout) !== NoFlags$1) { + { + markComponentLayoutEffectUnmountStarted(deletedFiber); + } + if (deletedFiber.mode & ProfileMode) { + startLayoutEffectTimer(); + safelyCallDestroy(deletedFiber, nearestMountedAncestor, destroy); + recordLayoutEffectDuration(deletedFiber); + } else { + safelyCallDestroy(deletedFiber, nearestMountedAncestor, destroy); + } + { + markComponentLayoutEffectUnmountStopped(); + } + } + } + effect = effect.next; + } while (effect !== firstEffect); + } + } + } + recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber); + return; + } + case ClassComponent: { + if (!offscreenSubtreeWasHidden) { + safelyDetachRef(deletedFiber, nearestMountedAncestor); + var instance = deletedFiber.stateNode; + if (typeof instance.componentWillUnmount === "function") { + safelyCallComponentWillUnmount(deletedFiber, nearestMountedAncestor, instance); + } + } + recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber); + return; + } + case ScopeComponent: { + recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber); + return; + } + case OffscreenComponent: { + if (deletedFiber.mode & ConcurrentMode) { + var prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden; + offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden || deletedFiber.memoizedState !== null; + recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber); + offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden; + } else { + recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber); + } + break; + } + default: { + recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber); + return; + } + } + } + function commitSuspenseCallback(finishedWork) { + var newState = finishedWork.memoizedState; + } + function commitSuspenseHydrationCallbacks(finishedRoot, finishedWork) { + var newState = finishedWork.memoizedState; + if (newState === null) { + var current2 = finishedWork.alternate; + if (current2 !== null) { + var prevState = current2.memoizedState; + if (prevState !== null) { + var suspenseInstance = prevState.dehydrated; + if (suspenseInstance !== null) { + commitHydratedSuspenseInstance(suspenseInstance); + } + } + } + } + } + function attachSuspenseRetryListeners(finishedWork) { + 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) { + var retry = resolveRetryWakeable.bind(null, finishedWork, wakeable); + if (!retryCache.has(wakeable)) { + retryCache.add(wakeable); + { + if (isDevToolsPresent) { + if (inProgressLanes !== null && inProgressRoot !== null) { + restorePendingUpdaters(inProgressRoot, inProgressLanes); + } else { + throw Error("Expected finished root and lanes to be set. This is a bug in React."); + } + } + } + wakeable.then(retry, retry); + } + }); + } + } + function commitMutationEffects(root2, finishedWork, committedLanes) { + inProgressLanes = committedLanes; + inProgressRoot = root2; + setCurrentFiber(finishedWork); + commitMutationEffectsOnFiber(finishedWork, root2); + setCurrentFiber(finishedWork); + inProgressLanes = null; + inProgressRoot = null; + } + function recursivelyTraverseMutationEffects(root2, parentFiber, lanes) { + var deletions = parentFiber.deletions; + if (deletions !== null) { + for (var i = 0;i < deletions.length; i++) { + var childToDelete = deletions[i]; + try { + commitDeletionEffects(root2, parentFiber, childToDelete); + } catch (error2) { + captureCommitPhaseError(childToDelete, parentFiber, error2); + } + } + } + var prevDebugFiber = getCurrentFiber(); + if (parentFiber.subtreeFlags & MutationMask) { + var child = parentFiber.child; + while (child !== null) { + setCurrentFiber(child); + commitMutationEffectsOnFiber(child, root2); + child = child.sibling; + } + } + setCurrentFiber(prevDebugFiber); + } + function commitMutationEffectsOnFiber(finishedWork, root2, lanes) { + var current2 = finishedWork.alternate; + var flags = finishedWork.flags; + switch (finishedWork.tag) { + case FunctionComponent: + case ForwardRef: + case MemoComponent: + case SimpleMemoComponent: { + recursivelyTraverseMutationEffects(root2, finishedWork); + commitReconciliationEffects(finishedWork); + if (flags & Update) { + try { + commitHookEffectListUnmount(Insertion | HasEffect, finishedWork, finishedWork.return); + commitHookEffectListMount(Insertion | HasEffect, finishedWork); + } catch (error2) { + captureCommitPhaseError(finishedWork, finishedWork.return, error2); + } + if (finishedWork.mode & ProfileMode) { + try { + startLayoutEffectTimer(); + commitHookEffectListUnmount(Layout | HasEffect, finishedWork, finishedWork.return); + } catch (error2) { + captureCommitPhaseError(finishedWork, finishedWork.return, error2); + } + recordLayoutEffectDuration(finishedWork); + } else { + try { + commitHookEffectListUnmount(Layout | HasEffect, finishedWork, finishedWork.return); + } catch (error2) { + captureCommitPhaseError(finishedWork, finishedWork.return, error2); + } + } + } + return; + } + case ClassComponent: { + recursivelyTraverseMutationEffects(root2, finishedWork); + commitReconciliationEffects(finishedWork); + if (flags & Ref) { + if (current2 !== null) { + safelyDetachRef(current2, current2.return); + } + } + return; + } + case HostComponent: { + recursivelyTraverseMutationEffects(root2, finishedWork); + commitReconciliationEffects(finishedWork); + if (flags & Ref) { + if (current2 !== null) { + safelyDetachRef(current2, current2.return); + } + } + { + if (finishedWork.flags & ContentReset) { + var instance = finishedWork.stateNode; + try { + resetTextContent(instance); + } catch (error2) { + captureCommitPhaseError(finishedWork, finishedWork.return, error2); + } + } + if (flags & Update) { + var _instance4 = finishedWork.stateNode; + if (_instance4 != null) { + var newProps = finishedWork.memoizedProps; + var oldProps = current2 !== null ? current2.memoizedProps : newProps; + var type = finishedWork.type; + var updatePayload = finishedWork.updateQueue; + finishedWork.updateQueue = null; + if (updatePayload !== null) { + try { + commitUpdate(_instance4, updatePayload, type, oldProps, newProps, finishedWork); + } catch (error2) { + captureCommitPhaseError(finishedWork, finishedWork.return, error2); + } + } + } + } + } + return; + } + case HostText: { + recursivelyTraverseMutationEffects(root2, finishedWork); + commitReconciliationEffects(finishedWork); + if (flags & Update) { + { + 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; + var oldText = current2 !== null ? current2.memoizedProps : newText; + try { + commitTextUpdate(textInstance, oldText, newText); + } catch (error2) { + captureCommitPhaseError(finishedWork, finishedWork.return, error2); + } + } + } + return; + } + case HostRoot: { + recursivelyTraverseMutationEffects(root2, finishedWork); + commitReconciliationEffects(finishedWork); + if (flags & Update) { + { + if (current2 !== null) { + var prevRootState = current2.memoizedState; + if (prevRootState.isDehydrated) { + try { + commitHydratedContainer(root2.containerInfo); + } catch (error2) { + captureCommitPhaseError(finishedWork, finishedWork.return, error2); + } + } + } + } + } + return; + } + case HostPortal: { + recursivelyTraverseMutationEffects(root2, finishedWork); + commitReconciliationEffects(finishedWork); + return; + } + case SuspenseComponent: { + recursivelyTraverseMutationEffects(root2, finishedWork); + commitReconciliationEffects(finishedWork); + var offscreenFiber = finishedWork.child; + if (offscreenFiber.flags & Visibility) { + var offscreenInstance = offscreenFiber.stateNode; + var newState = offscreenFiber.memoizedState; + var isHidden = newState !== null; + offscreenInstance.isHidden = isHidden; + if (isHidden) { + var wasHidden = offscreenFiber.alternate !== null && offscreenFiber.alternate.memoizedState !== null; + if (!wasHidden) { + markCommitTimeOfFallback(); + } + } + } + if (flags & Update) { + try { + commitSuspenseCallback(finishedWork); + } catch (error2) { + captureCommitPhaseError(finishedWork, finishedWork.return, error2); + } + attachSuspenseRetryListeners(finishedWork); + } + return; + } + case OffscreenComponent: { + var _wasHidden = current2 !== null && current2.memoizedState !== null; + if (finishedWork.mode & ConcurrentMode) { + var prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden; + offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden || _wasHidden; + recursivelyTraverseMutationEffects(root2, finishedWork); + offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden; + } else { + recursivelyTraverseMutationEffects(root2, finishedWork); + } + commitReconciliationEffects(finishedWork); + if (flags & Visibility) { + var _offscreenInstance = finishedWork.stateNode; + var _newState = finishedWork.memoizedState; + var _isHidden = _newState !== null; + var offscreenBoundary = finishedWork; + _offscreenInstance.isHidden = _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; + } + } + } + } + } + { + hideOrUnhideAllChildren(offscreenBoundary, _isHidden); + } + } + return; + } + case SuspenseListComponent: { + recursivelyTraverseMutationEffects(root2, finishedWork); + commitReconciliationEffects(finishedWork); + if (flags & Update) { + attachSuspenseRetryListeners(finishedWork); + } + return; + } + case ScopeComponent: { + return; + } + default: { + recursivelyTraverseMutationEffects(root2, finishedWork); + commitReconciliationEffects(finishedWork); + return; + } + } + } + function commitReconciliationEffects(finishedWork) { + var flags = finishedWork.flags; + if (flags & Placement) { + try { + commitPlacement(finishedWork); + } catch (error2) { + captureCommitPhaseError(finishedWork, finishedWork.return, error2); + } + finishedWork.flags &= ~Placement; + } + if (flags & Hydrating) { + finishedWork.flags &= ~Hydrating; + } + } + function commitLayoutEffects(finishedWork, root2, committedLanes) { + inProgressLanes = committedLanes; + inProgressRoot = root2; + nextEffect = finishedWork; + commitLayoutEffects_begin(finishedWork, root2, committedLanes); + inProgressLanes = null; + inProgressRoot = null; + } + function commitLayoutEffects_begin(subtreeRoot, root2, committedLanes) { + var isModernRoot = (subtreeRoot.mode & ConcurrentMode) !== NoMode; + while (nextEffect !== null) { + var fiber = nextEffect; + var firstChild = fiber.child; + if (fiber.tag === OffscreenComponent && isModernRoot) { + var isHidden = fiber.memoizedState !== null; + var newOffscreenSubtreeIsHidden = isHidden || offscreenSubtreeIsHidden; + if (newOffscreenSubtreeIsHidden) { + commitLayoutMountEffects_complete(subtreeRoot, root2, committedLanes); + continue; + } else { + var current2 = fiber.alternate; + var wasHidden = current2 !== null && current2.memoizedState !== null; + var newOffscreenSubtreeWasHidden = wasHidden || offscreenSubtreeWasHidden; + var prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden; + var prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden; + offscreenSubtreeIsHidden = newOffscreenSubtreeIsHidden; + offscreenSubtreeWasHidden = newOffscreenSubtreeWasHidden; + if (offscreenSubtreeWasHidden && !prevOffscreenSubtreeWasHidden) { + nextEffect = fiber; + reappearLayoutEffects_begin(fiber); + } + var child = firstChild; + while (child !== null) { + nextEffect = child; + commitLayoutEffects_begin(child, root2, committedLanes); + child = child.sibling; + } + nextEffect = fiber; + offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden; + offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden; + commitLayoutMountEffects_complete(subtreeRoot, root2, committedLanes); + continue; + } + } + if ((fiber.subtreeFlags & LayoutMask) !== NoFlags && firstChild !== null) { + firstChild.return = fiber; + nextEffect = firstChild; + } else { + commitLayoutMountEffects_complete(subtreeRoot, root2, committedLanes); + } + } + } + function commitLayoutMountEffects_complete(subtreeRoot, root2, committedLanes) { + while (nextEffect !== null) { + var fiber = nextEffect; + if ((fiber.flags & LayoutMask) !== NoFlags) { + var current2 = fiber.alternate; + setCurrentFiber(fiber); + try { + commitLayoutEffectOnFiber(root2, current2, fiber, committedLanes); + } catch (error2) { + captureCommitPhaseError(fiber, fiber.return, error2); + } + resetCurrentFiber(); + } + if (fiber === subtreeRoot) { + nextEffect = null; + return; + } + var sibling = fiber.sibling; + if (sibling !== null) { + sibling.return = fiber.return; + nextEffect = sibling; + return; + } + nextEffect = fiber.return; + } + } + function disappearLayoutEffects_begin(subtreeRoot) { + while (nextEffect !== null) { + var fiber = nextEffect; + var firstChild = fiber.child; + 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: { + 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: { + var isHidden = fiber.memoizedState !== null; + if (isHidden) { + disappearLayoutEffects_complete(subtreeRoot); + continue; + } + break; + } + } + 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) { + reappearLayoutEffects_complete(subtreeRoot); + continue; + } + } + if (firstChild !== null) { + firstChild.return = fiber; + nextEffect = firstChild; + } else { + reappearLayoutEffects_complete(subtreeRoot); + } + } + } + function reappearLayoutEffects_complete(subtreeRoot) { + while (nextEffect !== null) { + var fiber = nextEffect; + setCurrentFiber(fiber); + try { + reappearLayoutEffectsOnFiber(fiber); + } catch (error2) { + captureCommitPhaseError(fiber, fiber.return, error2); + } + resetCurrentFiber(); + if (fiber === subtreeRoot) { + nextEffect = null; + return; + } + var sibling = fiber.sibling; + if (sibling !== null) { + sibling.return = fiber.return; + nextEffect = sibling; + return; + } + nextEffect = fiber.return; + } + } + function commitPassiveMountEffects(root2, finishedWork, committedLanes, committedTransitions) { + nextEffect = finishedWork; + commitPassiveMountEffects_begin(finishedWork, root2, committedLanes, committedTransitions); + } + function commitPassiveMountEffects_begin(subtreeRoot, root2, committedLanes, committedTransitions) { + while (nextEffect !== null) { + var fiber = nextEffect; + var firstChild = fiber.child; + if ((fiber.subtreeFlags & PassiveMask) !== NoFlags && firstChild !== null) { + firstChild.return = fiber; + nextEffect = firstChild; + } else { + commitPassiveMountEffects_complete(subtreeRoot, root2, committedLanes, committedTransitions); + } + } + } + function commitPassiveMountEffects_complete(subtreeRoot, root2, committedLanes, committedTransitions) { + while (nextEffect !== null) { + var fiber = nextEffect; + if ((fiber.flags & Passive) !== NoFlags) { + setCurrentFiber(fiber); + try { + commitPassiveMountOnFiber(root2, fiber, committedLanes, committedTransitions); + } catch (error2) { + captureCommitPhaseError(fiber, fiber.return, error2); + } + resetCurrentFiber(); + } + if (fiber === subtreeRoot) { + nextEffect = null; + return; + } + var sibling = fiber.sibling; + if (sibling !== null) { + sibling.return = fiber.return; + nextEffect = sibling; + return; + } + nextEffect = fiber.return; + } + } + function commitPassiveMountOnFiber(finishedRoot, finishedWork, committedLanes, committedTransitions) { + 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); + } + { + 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) { + child.return = 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) { + sibling.return = 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; + setCurrentFiber(fiber); + commitPassiveUnmountInsideDeletedTreeOnFiber(fiber, nearestMountedAncestor); + resetCurrentFiber(); + var child = fiber.child; + if (child !== null) { + child.return = 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; + { + detachFiberAfterEffects(fiber); + if (fiber === deletedSubtreeRoot) { + nextEffect = null; + return; + } + } + if (sibling !== null) { + sibling.return = returnFiber; + nextEffect = sibling; + return; + } + nextEffect = returnFiber; + } + } + function commitPassiveUnmountInsideDeletedTreeOnFiber(current2, nearestMountedAncestor) { + switch (current2.tag) { + case FunctionComponent: + case ForwardRef: + case SimpleMemoComponent: { + if (current2.mode & ProfileMode) { + startPassiveEffectTimer(); + commitHookEffectListUnmount(Passive$1, current2, nearestMountedAncestor); + recordPassiveEffectDuration(current2); + } else { + commitHookEffectListUnmount(Passive$1, current2, nearestMountedAncestor); + } + break; + } + } + } + function invokeLayoutEffectMountInDEV(fiber) { + { + switch (fiber.tag) { + case FunctionComponent: + case ForwardRef: + case SimpleMemoComponent: { + try { + commitHookEffectListMount(Layout | HasEffect, fiber); + } catch (error2) { + captureCommitPhaseError(fiber, fiber.return, error2); + } + break; + } + case ClassComponent: { + var instance = fiber.stateNode; + try { + instance.componentDidMount(); + } catch (error2) { + captureCommitPhaseError(fiber, fiber.return, error2); + } + break; + } + } + } + } + function invokePassiveEffectMountInDEV(fiber) { + { + switch (fiber.tag) { + case FunctionComponent: + case ForwardRef: + case SimpleMemoComponent: { + try { + commitHookEffectListMount(Passive$1 | HasEffect, fiber); + } catch (error2) { + captureCommitPhaseError(fiber, fiber.return, error2); + } + break; + } + } + } + } + function invokeLayoutEffectUnmountInDEV(fiber) { + { + switch (fiber.tag) { + case FunctionComponent: + case ForwardRef: + case SimpleMemoComponent: { + try { + commitHookEffectListUnmount(Layout | HasEffect, fiber, fiber.return); + } catch (error2) { + captureCommitPhaseError(fiber, fiber.return, error2); + } + break; + } + case ClassComponent: { + var instance = fiber.stateNode; + if (typeof instance.componentWillUnmount === "function") { + safelyCallComponentWillUnmount(fiber, fiber.return, instance); + } + break; + } + } + } + } + function invokePassiveEffectUnmountInDEV(fiber) { + { + switch (fiber.tag) { + case FunctionComponent: + case ForwardRef: + case SimpleMemoComponent: { + try { + commitHookEffectListUnmount(Passive$1 | HasEffect, fiber, fiber.return); + } catch (error2) { + captureCommitPhaseError(fiber, fiber.return, error2); + } + } + } + } + } + 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"); + } + var commitHooks = []; + function onCommitRoot$1() { + { + commitHooks.forEach(function(commitHook) { + return commitHook(); + }); + } + } + var ReactCurrentActQueue = ReactSharedInternals.ReactCurrentActQueue; + function isLegacyActEnvironment(fiber) { + { + var isReactActEnvironmentGlobal = typeof IS_REACT_ACT_ENVIRONMENT !== "undefined" ? IS_REACT_ACT_ENVIRONMENT : undefined; + var jestIsDefined = typeof jest !== "undefined"; + return jestIsDefined && isReactActEnvironmentGlobal !== false; + } + } + function isConcurrentActEnvironment() { + { + var isReactActEnvironmentGlobal = typeof IS_REACT_ACT_ENVIRONMENT !== "undefined" ? IS_REACT_ACT_ENVIRONMENT : undefined; + if (!isReactActEnvironmentGlobal && ReactCurrentActQueue.current !== null) { + error("The current testing environment is not configured to support act(...)"); + } + return isReactActEnvironmentGlobal; + } + } + var ceil = Math.ceil; + var { ReactCurrentDispatcher: ReactCurrentDispatcher$2, ReactCurrentOwner: ReactCurrentOwner$2, ReactCurrentBatchConfig: ReactCurrentBatchConfig$3, ReactCurrentActQueue: ReactCurrentActQueue$1 } = ReactSharedInternals; + 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; + var executionContext = NoContext; + var workInProgressRoot = null; + var workInProgress = null; + var workInProgressRootRenderLanes = NoLanes; + var subtreeRenderLanes = NoLanes; + var subtreeRenderLanesCursor = createCursor(NoLanes); + var workInProgressRootExitStatus = RootInProgress; + var workInProgressRootFatalError = null; + var workInProgressRootIncludedLanes = NoLanes; + var workInProgressRootSkippedLanes = NoLanes; + var workInProgressRootInterleavedUpdatedLanes = NoLanes; + var workInProgressRootPingedLanes = NoLanes; + var workInProgressRootConcurrentErrors = null; + var workInProgressRootRecoverableErrors = null; + var globalMostRecentFallbackTime = 0; + var FALLBACK_THROTTLE_MS = 500; + var workInProgressRootRenderTargetTime = Infinity; + var RENDER_TIMEOUT_MS = 500; + var workInProgressTransitions = null; + function resetRenderTimer() { + workInProgressRootRenderTargetTime = now() + RENDER_TIMEOUT_MS; + } + function getRenderTargetTime() { + return workInProgressRootRenderTargetTime; + } + var hasUncaughtError = false; + var firstUncaughtError = null; + var legacyErrorBoundariesThatAlreadyFailed = null; + var rootDoesHavePassiveEffects = false; + var rootWithPendingPassiveEffects = null; + var pendingPassiveEffectsLanes = NoLanes; + var pendingPassiveProfilerEffects = []; + var pendingPassiveTransitions = null; + var NESTED_UPDATE_LIMIT = 50; + var nestedUpdateCount = 0; + var rootWithNestedUpdates = null; + var isFlushingPassiveEffects = false; + var didScheduleUpdateDuringPassiveEffects = false; + var NESTED_PASSIVE_UPDATE_LIMIT = 50; + var nestedPassiveUpdateCount = 0; + var rootWithPassiveNestedUpdates = null; + var currentEventTime = NoTimestamp; + var currentEventTransitionLane = NoLanes; + var isRunningInsertionEffect = false; + function getWorkInProgressRoot() { + return workInProgressRoot; + } + function requestEventTime() { + if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { + return now(); + } + if (currentEventTime !== NoTimestamp) { + return currentEventTime; + } + currentEventTime = now(); + return currentEventTime; + } + function requestUpdateLane(fiber) { + var mode = fiber.mode; + if ((mode & ConcurrentMode) === NoMode) { + return SyncLane; + } else if ((executionContext & RenderContext) !== NoContext && workInProgressRootRenderLanes !== NoLanes) { + return pickArbitraryLane(workInProgressRootRenderLanes); + } + var isTransition = requestCurrentTransition() !== NoTransition; + if (isTransition) { + if (ReactCurrentBatchConfig$3.transition !== null) { + var transition = ReactCurrentBatchConfig$3.transition; + if (!transition._updatedFibers) { + transition._updatedFibers = new Set; + } + transition._updatedFibers.add(fiber); + } + if (currentEventTransitionLane === NoLane) { + currentEventTransitionLane = claimNextTransitionLane(); + } + return currentEventTransitionLane; + } + var updateLane = getCurrentUpdatePriority(); + if (updateLane !== NoLane) { + return updateLane; + } + var eventLane = getCurrentEventPriority(); + return eventLane; + } + function requestRetryLane(fiber) { + var mode = fiber.mode; + if ((mode & ConcurrentMode) === NoMode) { + return SyncLane; + } + return claimNextRetryLane(); + } + function scheduleUpdateOnFiber(root2, fiber, lane, eventTime) { + checkForNestedUpdates(); + { + if (isRunningInsertionEffect) { + error("useInsertionEffect must not schedule updates."); + } + } + { + if (isFlushingPassiveEffects) { + didScheduleUpdateDuringPassiveEffects = true; + } + } + markRootUpdated(root2, lane, eventTime); + if ((executionContext & RenderContext) !== NoLanes && root2 === workInProgressRoot) { + warnAboutRenderPhaseUpdatesInDEV(fiber); + } else { + { + if (isDevToolsPresent) { + addFiberToLanesMap(root2, fiber, lane); + } + } + warnIfUpdatesNotWrappedWithActDEV(fiber); + if (root2 === workInProgressRoot) { + if ((executionContext & RenderContext) === NoContext) { + workInProgressRootInterleavedUpdatedLanes = mergeLanes(workInProgressRootInterleavedUpdatedLanes, lane); + } + if (workInProgressRootExitStatus === RootSuspendedWithDelay) { + markRootSuspended$1(root2, workInProgressRootRenderLanes); + } + } + ensureRootIsScheduled(root2, eventTime); + if (lane === SyncLane && executionContext === NoContext && (fiber.mode & ConcurrentMode) === NoMode && !ReactCurrentActQueue$1.isBatchingLegacy) { + resetRenderTimer(); + flushSyncCallbacksOnlyInLegacyMode(); + } + } + } + function scheduleInitialHydrationOnRoot(root2, lane, eventTime) { + var current2 = root2.current; + current2.lanes = lane; + markRootUpdated(root2, lane, eventTime); + ensureRootIsScheduled(root2, eventTime); + } + function isUnsafeClassRenderPhaseUpdate(fiber) { + return (executionContext & RenderContext) !== NoContext; + } + function ensureRootIsScheduled(root2, currentTime) { + var existingCallbackNode = root2.callbackNode; + markStarvedLanesAsExpired(root2, currentTime); + var nextLanes = getNextLanes(root2, root2 === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes); + if (nextLanes === NoLanes) { + if (existingCallbackNode !== null) { + cancelCallback$1(existingCallbackNode); + } + root2.callbackNode = null; + root2.callbackPriority = NoLane; + return; + } + var newCallbackPriority = getHighestPriorityLane(nextLanes); + var existingCallbackPriority = root2.callbackPriority; + if (existingCallbackPriority === newCallbackPriority && !(ReactCurrentActQueue$1.current !== null && existingCallbackNode !== fakeActCallbackNode)) { + { + 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."); + } + } + return; + } + if (existingCallbackNode != null) { + cancelCallback$1(existingCallbackNode); + } + var newCallbackNode; + if (newCallbackPriority === SyncLane) { + if (root2.tag === LegacyRoot) { + if (ReactCurrentActQueue$1.isBatchingLegacy !== null) { + ReactCurrentActQueue$1.didScheduleLegacyUpdate = true; + } + scheduleLegacySyncCallback(performSyncWorkOnRoot.bind(null, root2)); + } else { + scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root2)); + } + { + if (ReactCurrentActQueue$1.current !== null) { + ReactCurrentActQueue$1.current.push(flushSyncCallbacks); + } else { + scheduleMicrotask(function() { + if ((executionContext & (RenderContext | CommitContext)) === NoContext) { + 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, root2)); + } + root2.callbackPriority = newCallbackPriority; + root2.callbackNode = newCallbackNode; + } + function performConcurrentWorkOnRoot(root2, didTimeout) { + { + resetNestedUpdateFlag(); + } + currentEventTime = NoTimestamp; + currentEventTransitionLane = NoLanes; + if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { + throw new Error("Should not already be working."); + } + var originalCallbackNode = root2.callbackNode; + var didFlushPassiveEffects = flushPassiveEffects(); + if (didFlushPassiveEffects) { + if (root2.callbackNode !== originalCallbackNode) { + return null; + } + } + var lanes = getNextLanes(root2, root2 === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes); + if (lanes === NoLanes) { + return null; + } + var shouldTimeSlice = !includesBlockingLane(root2, lanes) && !includesExpiredLane(root2, lanes) && !didTimeout; + var exitStatus = shouldTimeSlice ? renderRootConcurrent(root2, lanes) : renderRootSync(root2, lanes); + if (exitStatus !== RootInProgress) { + if (exitStatus === RootErrored) { + var errorRetryLanes = getLanesToRetrySynchronouslyOnError(root2); + if (errorRetryLanes !== NoLanes) { + lanes = errorRetryLanes; + exitStatus = recoverFromConcurrentError(root2, errorRetryLanes); + } + } + if (exitStatus === RootFatalErrored) { + var fatalError = workInProgressRootFatalError; + prepareFreshStack(root2, NoLanes); + markRootSuspended$1(root2, lanes); + ensureRootIsScheduled(root2, now()); + throw fatalError; + } + if (exitStatus === RootDidNotComplete) { + markRootSuspended$1(root2, lanes); + } else { + var renderWasConcurrent = !includesBlockingLane(root2, lanes); + var finishedWork = root2.current.alternate; + if (renderWasConcurrent && !isRenderConsistentWithExternalStores(finishedWork)) { + exitStatus = renderRootSync(root2, lanes); + if (exitStatus === RootErrored) { + var _errorRetryLanes = getLanesToRetrySynchronouslyOnError(root2); + if (_errorRetryLanes !== NoLanes) { + lanes = _errorRetryLanes; + exitStatus = recoverFromConcurrentError(root2, _errorRetryLanes); + } + } + if (exitStatus === RootFatalErrored) { + var _fatalError = workInProgressRootFatalError; + prepareFreshStack(root2, NoLanes); + markRootSuspended$1(root2, lanes); + ensureRootIsScheduled(root2, now()); + throw _fatalError; + } + } + root2.finishedWork = finishedWork; + root2.finishedLanes = lanes; + finishConcurrentRender(root2, exitStatus, lanes); + } + } + ensureRootIsScheduled(root2, now()); + if (root2.callbackNode === originalCallbackNode) { + return performConcurrentWorkOnRoot.bind(null, root2); + } + return null; + } + function recoverFromConcurrentError(root2, errorRetryLanes) { + var errorsFromFirstAttempt = workInProgressRootConcurrentErrors; + if (isRootDehydrated(root2)) { + var rootWorkInProgress = prepareFreshStack(root2, errorRetryLanes); + rootWorkInProgress.flags |= ForceClientRender; + { + errorHydratingContainer(root2.containerInfo); + } + } + var exitStatus = renderRootSync(root2, errorRetryLanes); + if (exitStatus !== RootErrored) { + var errorsFromSecondAttempt = workInProgressRootRecoverableErrors; + workInProgressRootRecoverableErrors = errorsFromFirstAttempt; + if (errorsFromSecondAttempt !== null) { + queueRecoverableErrors(errorsFromSecondAttempt); + } + } + return exitStatus; + } + function queueRecoverableErrors(errors) { + if (workInProgressRootRecoverableErrors === null) { + workInProgressRootRecoverableErrors = errors; + } else { + workInProgressRootRecoverableErrors.push.apply(workInProgressRootRecoverableErrors, errors); + } + } + function finishConcurrentRender(root2, exitStatus, lanes) { + switch (exitStatus) { + case RootInProgress: + case RootFatalErrored: { + throw new Error("Root did not complete. This is a bug in React."); + } + case RootErrored: { + commitRoot(root2, workInProgressRootRecoverableErrors, workInProgressTransitions); + break; + } + case RootSuspended: { + markRootSuspended$1(root2, lanes); + if (includesOnlyRetries(lanes) && !shouldForceFlushFallbacksInDEV()) { + var msUntilTimeout = globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now(); + if (msUntilTimeout > 10) { + var nextLanes = getNextLanes(root2, NoLanes); + if (nextLanes !== NoLanes) { + break; + } + var suspendedLanes = root2.suspendedLanes; + if (!isSubsetOfLanes(suspendedLanes, lanes)) { + var eventTime = requestEventTime(); + markRootPinged(root2, suspendedLanes); + break; + } + root2.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root2, workInProgressRootRecoverableErrors, workInProgressTransitions), msUntilTimeout); + break; + } + } + commitRoot(root2, workInProgressRootRecoverableErrors, workInProgressTransitions); + break; + } + case RootSuspendedWithDelay: { + markRootSuspended$1(root2, lanes); + if (includesOnlyTransitions(lanes)) { + break; + } + if (!shouldForceFlushFallbacksInDEV()) { + var mostRecentEventTime = getMostRecentEventTime(root2, lanes); + var eventTimeMs = mostRecentEventTime; + var timeElapsedMs = now() - eventTimeMs; + var _msUntilTimeout = jnd(timeElapsedMs) - timeElapsedMs; + if (_msUntilTimeout > 10) { + root2.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root2, workInProgressRootRecoverableErrors, workInProgressTransitions), _msUntilTimeout); + break; + } + } + commitRoot(root2, workInProgressRootRecoverableErrors, workInProgressTransitions); + break; + } + case RootCompleted: { + commitRoot(root2, workInProgressRootRecoverableErrors, workInProgressTransitions); + break; + } + default: { + throw new Error("Unknown root exit status."); + } + } + } + function isRenderConsistentWithExternalStores(finishedWork) { + 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)) { + return false; + } + } catch (error2) { + 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; + } + return true; + } + function markRootSuspended$1(root2, suspendedLanes) { + suspendedLanes = removeLanes(suspendedLanes, workInProgressRootPingedLanes); + suspendedLanes = removeLanes(suspendedLanes, workInProgressRootInterleavedUpdatedLanes); + markRootSuspended(root2, suspendedLanes); + } + function performSyncWorkOnRoot(root2) { + { + syncNestedUpdateFlag(); + } + if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { + throw new Error("Should not already be working."); + } + flushPassiveEffects(); + var lanes = getNextLanes(root2, NoLanes); + if (!includesSomeLane(lanes, SyncLane)) { + ensureRootIsScheduled(root2, now()); + return null; + } + var exitStatus = renderRootSync(root2, lanes); + if (root2.tag !== LegacyRoot && exitStatus === RootErrored) { + var errorRetryLanes = getLanesToRetrySynchronouslyOnError(root2); + if (errorRetryLanes !== NoLanes) { + lanes = errorRetryLanes; + exitStatus = recoverFromConcurrentError(root2, errorRetryLanes); + } + } + if (exitStatus === RootFatalErrored) { + var fatalError = workInProgressRootFatalError; + prepareFreshStack(root2, NoLanes); + markRootSuspended$1(root2, lanes); + ensureRootIsScheduled(root2, now()); + throw fatalError; + } + if (exitStatus === RootDidNotComplete) { + throw new Error("Root did not complete. This is a bug in React."); + } + var finishedWork = root2.current.alternate; + root2.finishedWork = finishedWork; + root2.finishedLanes = lanes; + commitRoot(root2, workInProgressRootRecoverableErrors, workInProgressTransitions); + ensureRootIsScheduled(root2, now()); + return null; + } + function flushRoot(root2, lanes) { + if (lanes !== NoLanes) { + markRootEntangled(root2, mergeLanes(lanes, SyncLane)); + ensureRootIsScheduled(root2, now()); + if ((executionContext & (RenderContext | CommitContext)) === NoContext) { + resetRenderTimer(); + flushSyncCallbacks(); + } + } + } + function batchedUpdates$1(fn, a) { + var prevExecutionContext = executionContext; + executionContext |= BatchedContext; + try { + return fn(a); + } finally { + executionContext = prevExecutionContext; + if (executionContext === NoContext && !ReactCurrentActQueue$1.isBatchingLegacy) { + resetRenderTimer(); + flushSyncCallbacksOnlyInLegacyMode(); + } + } + } + function discreteUpdates(fn, a, b, c, d) { + var previousPriority = getCurrentUpdatePriority(); + var prevTransition = ReactCurrentBatchConfig$3.transition; + try { + ReactCurrentBatchConfig$3.transition = null; + setCurrentUpdatePriority(DiscreteEventPriority); + return fn(a, b, c, d); + } finally { + setCurrentUpdatePriority(previousPriority); + ReactCurrentBatchConfig$3.transition = prevTransition; + if (executionContext === NoContext) { + resetRenderTimer(); + } + } + } + function flushSync(fn) { + if (rootWithPendingPassiveEffects !== null && rootWithPendingPassiveEffects.tag === LegacyRoot && (executionContext & (RenderContext | CommitContext)) === NoContext) { + flushPassiveEffects(); + } + var prevExecutionContext = executionContext; + executionContext |= BatchedContext; + var prevTransition = ReactCurrentBatchConfig$3.transition; + var previousPriority = getCurrentUpdatePriority(); + try { + ReactCurrentBatchConfig$3.transition = null; + setCurrentUpdatePriority(DiscreteEventPriority); + if (fn) { + return fn(); + } else { + return; + } + } finally { + setCurrentUpdatePriority(previousPriority); + ReactCurrentBatchConfig$3.transition = prevTransition; + executionContext = prevExecutionContext; + if ((executionContext & (RenderContext | CommitContext)) === NoContext) { + flushSyncCallbacks(); + } + } + } + function isAlreadyRendering() { + return (executionContext & (RenderContext | CommitContext)) !== NoContext; + } + function pushRenderLanes(fiber, lanes) { + push(subtreeRenderLanesCursor, subtreeRenderLanes, fiber); + subtreeRenderLanes = mergeLanes(subtreeRenderLanes, lanes); + workInProgressRootIncludedLanes = mergeLanes(workInProgressRootIncludedLanes, lanes); + } + function popRenderLanes(fiber) { + subtreeRenderLanes = subtreeRenderLanesCursor.current; + pop(subtreeRenderLanesCursor, fiber); + } + function prepareFreshStack(root2, lanes) { + root2.finishedWork = null; + root2.finishedLanes = NoLanes; + var timeoutHandle = root2.timeoutHandle; + if (timeoutHandle !== noTimeout) { + root2.timeoutHandle = noTimeout; + cancelTimeout(timeoutHandle); + } + if (workInProgress !== null) { + var interruptedWork = workInProgress.return; + while (interruptedWork !== null) { + var current2 = interruptedWork.alternate; + unwindInterruptedWork(current2, interruptedWork); + interruptedWork = interruptedWork.return; + } + } + workInProgressRoot = root2; + var rootWorkInProgress = createWorkInProgress(root2.current, null); + workInProgress = rootWorkInProgress; + workInProgressRootRenderLanes = subtreeRenderLanes = workInProgressRootIncludedLanes = lanes; + workInProgressRootExitStatus = RootInProgress; + workInProgressRootFatalError = null; + workInProgressRootSkippedLanes = NoLanes; + workInProgressRootInterleavedUpdatedLanes = NoLanes; + workInProgressRootPingedLanes = NoLanes; + workInProgressRootConcurrentErrors = null; + workInProgressRootRecoverableErrors = null; + finishQueueingConcurrentUpdates(); + { + ReactStrictModeWarnings.discardPendingWarnings(); + } + return rootWorkInProgress; + } + function handleError(root2, thrownValue) { + do { + var erroredWork = workInProgress; + try { + resetContextDependencies(); + resetHooksAfterThrow(); + resetCurrentFiber(); + ReactCurrentOwner$2.current = null; + if (erroredWork === null || erroredWork.return === null) { + workInProgressRootExitStatus = RootFatalErrored; + workInProgressRootFatalError = thrownValue; + workInProgress = null; + return; + } + if (enableProfilerTimer && erroredWork.mode & ProfileMode) { + 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(root2, erroredWork.return, erroredWork, thrownValue, workInProgressRootRenderLanes); + completeUnitOfWork(erroredWork); + } catch (yetAnotherThrownValue) { + thrownValue = yetAnotherThrownValue; + if (workInProgress === erroredWork && erroredWork !== null) { + erroredWork = erroredWork.return; + workInProgress = erroredWork; + } else { + erroredWork = workInProgress; + } + continue; + } + return; + } while (true); + } + function pushDispatcher() { + var prevDispatcher = ReactCurrentDispatcher$2.current; + ReactCurrentDispatcher$2.current = ContextOnlyDispatcher; + if (prevDispatcher === null) { + return ContextOnlyDispatcher; + } else { + return prevDispatcher; + } + } + function popDispatcher(prevDispatcher) { + ReactCurrentDispatcher$2.current = prevDispatcher; + } + function markCommitTimeOfFallback() { + globalMostRecentFallbackTime = now(); + } + 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; + } + if (workInProgressRoot !== null && (includesNonIdleWork(workInProgressRootSkippedLanes) || includesNonIdleWork(workInProgressRootInterleavedUpdatedLanes))) { + markRootSuspended$1(workInProgressRoot, workInProgressRootRenderLanes); + } + } + function renderDidError(error2) { + if (workInProgressRootExitStatus !== RootSuspendedWithDelay) { + workInProgressRootExitStatus = RootErrored; + } + if (workInProgressRootConcurrentErrors === null) { + workInProgressRootConcurrentErrors = [error2]; + } else { + workInProgressRootConcurrentErrors.push(error2); + } + } + function renderHasNotSuspendedYet() { + return workInProgressRootExitStatus === RootInProgress; + } + function renderRootSync(root2, lanes) { + var prevExecutionContext = executionContext; + executionContext |= RenderContext; + var prevDispatcher = pushDispatcher(); + if (workInProgressRoot !== root2 || workInProgressRootRenderLanes !== lanes) { + { + if (isDevToolsPresent) { + var memoizedUpdaters = root2.memoizedUpdaters; + if (memoizedUpdaters.size > 0) { + restorePendingUpdaters(root2, workInProgressRootRenderLanes); + memoizedUpdaters.clear(); + } + movePendingFibersToMemoized(root2, lanes); + } + } + workInProgressTransitions = getTransitionsForLanes(); + prepareFreshStack(root2, lanes); + } + { + markRenderStarted(lanes); + } + do { + try { + workLoopSync(); + break; + } catch (thrownValue) { + handleError(root2, thrownValue); + } + } while (true); + resetContextDependencies(); + executionContext = prevExecutionContext; + popDispatcher(prevDispatcher); + if (workInProgress !== null) { + throw new Error("Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue."); + } + { + markRenderStopped(); + } + workInProgressRoot = null; + workInProgressRootRenderLanes = NoLanes; + return workInProgressRootExitStatus; + } + function workLoopSync() { + while (workInProgress !== null) { + performUnitOfWork(workInProgress); + } + } + function renderRootConcurrent(root2, lanes) { + var prevExecutionContext = executionContext; + executionContext |= RenderContext; + var prevDispatcher = pushDispatcher(); + if (workInProgressRoot !== root2 || workInProgressRootRenderLanes !== lanes) { + { + if (isDevToolsPresent) { + var memoizedUpdaters = root2.memoizedUpdaters; + if (memoizedUpdaters.size > 0) { + restorePendingUpdaters(root2, workInProgressRootRenderLanes); + memoizedUpdaters.clear(); + } + movePendingFibersToMemoized(root2, lanes); + } + } + workInProgressTransitions = getTransitionsForLanes(); + resetRenderTimer(); + prepareFreshStack(root2, lanes); + } + { + markRenderStarted(lanes); + } + do { + try { + workLoopConcurrent(); + break; + } catch (thrownValue) { + handleError(root2, thrownValue); + } + } while (true); + resetContextDependencies(); + popDispatcher(prevDispatcher); + executionContext = prevExecutionContext; + if (workInProgress !== null) { + { + markRenderYielded(); + } + return RootInProgress; + } else { + { + markRenderStopped(); + } + workInProgressRoot = null; + workInProgressRootRenderLanes = NoLanes; + return workInProgressRootExitStatus; + } + } + function workLoopConcurrent() { + while (workInProgress !== null && !shouldYield()) { + performUnitOfWork(workInProgress); + } + } + function performUnitOfWork(unitOfWork) { + var current2 = unitOfWork.alternate; + setCurrentFiber(unitOfWork); + var next; + if ((unitOfWork.mode & ProfileMode) !== NoMode) { + startProfilerTimer(unitOfWork); + next = beginWork$1(current2, unitOfWork, subtreeRenderLanes); + stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true); + } else { + next = beginWork$1(current2, unitOfWork, subtreeRenderLanes); + } + resetCurrentFiber(); + unitOfWork.memoizedProps = unitOfWork.pendingProps; + if (next === null) { + completeUnitOfWork(unitOfWork); + } else { + workInProgress = next; + } + ReactCurrentOwner$2.current = null; + } + function completeUnitOfWork(unitOfWork) { + var completedWork = unitOfWork; + do { + var current2 = completedWork.alternate; + var returnFiber = completedWork.return; + if ((completedWork.flags & Incomplete) === NoFlags) { + setCurrentFiber(completedWork); + var next = undefined; + if ((completedWork.mode & ProfileMode) === NoMode) { + next = completeWork(current2, completedWork, subtreeRenderLanes); + } else { + startProfilerTimer(completedWork); + next = completeWork(current2, completedWork, subtreeRenderLanes); + stopProfilerTimerIfRunningAndRecordDelta(completedWork, false); + } + resetCurrentFiber(); + if (next !== null) { + workInProgress = next; + return; + } + } else { + var _next = unwindWork(current2, completedWork); + if (_next !== null) { + _next.flags &= HostEffectMask; + workInProgress = _next; + return; + } + if ((completedWork.mode & ProfileMode) !== NoMode) { + stopProfilerTimerIfRunningAndRecordDelta(completedWork, false); + var actualDuration = completedWork.actualDuration; + var child = completedWork.child; + while (child !== null) { + actualDuration += child.actualDuration; + child = child.sibling; + } + completedWork.actualDuration = actualDuration; + } + if (returnFiber !== null) { + returnFiber.flags |= Incomplete; + returnFiber.subtreeFlags = NoFlags; + returnFiber.deletions = null; + } else { + workInProgressRootExitStatus = RootDidNotComplete; + workInProgress = null; + return; + } + } + var siblingFiber = completedWork.sibling; + if (siblingFiber !== null) { + workInProgress = siblingFiber; + return; + } + completedWork = returnFiber; + workInProgress = completedWork; + } while (completedWork !== null); + if (workInProgressRootExitStatus === RootInProgress) { + workInProgressRootExitStatus = RootCompleted; + } + } + function commitRoot(root2, recoverableErrors, transitions) { + var previousUpdateLanePriority = getCurrentUpdatePriority(); + var prevTransition = ReactCurrentBatchConfig$3.transition; + try { + ReactCurrentBatchConfig$3.transition = null; + setCurrentUpdatePriority(DiscreteEventPriority); + commitRootImpl(root2, recoverableErrors, transitions, previousUpdateLanePriority); + } finally { + ReactCurrentBatchConfig$3.transition = prevTransition; + setCurrentUpdatePriority(previousUpdateLanePriority); + } + return null; + } + function commitRootImpl(root2, recoverableErrors, transitions, renderPriorityLevel) { + do { + flushPassiveEffects(); + } while (rootWithPendingPassiveEffects !== null); + flushRenderPhaseStrictModeWarningsInDEV(); + if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { + throw new Error("Should not already be working."); + } + var finishedWork = root2.finishedWork; + var lanes = root2.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."); + } + } + } + root2.finishedWork = null; + root2.finishedLanes = NoLanes; + if (finishedWork === root2.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."); + } + root2.callbackNode = null; + root2.callbackPriority = NoLane; + var remainingLanes = mergeLanes(finishedWork.lanes, finishedWork.childLanes); + markRootFinished(root2, remainingLanes); + if (root2 === workInProgressRoot) { + workInProgressRoot = null; + workInProgress = null; + workInProgressRootRenderLanes = NoLanes; + } + if ((finishedWork.subtreeFlags & PassiveMask) !== NoFlags || (finishedWork.flags & PassiveMask) !== NoFlags) { + if (!rootDoesHavePassiveEffects) { + rootDoesHavePassiveEffects = true; + pendingPassiveTransitions = transitions; + scheduleCallback$1(NormalPriority, function() { + flushPassiveEffects(); + return null; + }); + } + } + var subtreeHasEffects = (finishedWork.subtreeFlags & (BeforeMutationMask | MutationMask | LayoutMask | PassiveMask)) !== NoFlags; + var rootHasEffect = (finishedWork.flags & (BeforeMutationMask | MutationMask | LayoutMask | PassiveMask)) !== NoFlags; + if (subtreeHasEffects || rootHasEffect) { + var prevTransition = ReactCurrentBatchConfig$3.transition; + ReactCurrentBatchConfig$3.transition = null; + var previousPriority = getCurrentUpdatePriority(); + setCurrentUpdatePriority(DiscreteEventPriority); + var prevExecutionContext = executionContext; + executionContext |= CommitContext; + ReactCurrentOwner$2.current = null; + var shouldFireAfterActiveInstanceBlur2 = commitBeforeMutationEffects(root2, finishedWork); + { + recordCommitTime(); + } + commitMutationEffects(root2, finishedWork, lanes); + resetAfterCommit(root2.containerInfo); + root2.current = finishedWork; + { + markLayoutEffectsStarted(lanes); + } + commitLayoutEffects(finishedWork, root2, lanes); + { + markLayoutEffectsStopped(); + } + requestPaint(); + executionContext = prevExecutionContext; + setCurrentUpdatePriority(previousPriority); + ReactCurrentBatchConfig$3.transition = prevTransition; + } else { + root2.current = finishedWork; + { + recordCommitTime(); + } + } + var rootDidHavePassiveEffects = rootDoesHavePassiveEffects; + if (rootDoesHavePassiveEffects) { + rootDoesHavePassiveEffects = false; + rootWithPendingPassiveEffects = root2; + pendingPassiveEffectsLanes = lanes; + } else { + { + nestedPassiveUpdateCount = 0; + rootWithPassiveNestedUpdates = null; + } + } + remainingLanes = root2.pendingLanes; + if (remainingLanes === NoLanes) { + legacyErrorBoundariesThatAlreadyFailed = null; + } + { + if (!rootDidHavePassiveEffects) { + commitDoubleInvokeEffectsInDEV(root2.current, false); + } + } + onCommitRoot(finishedWork.stateNode, renderPriorityLevel); + { + if (isDevToolsPresent) { + root2.memoizedUpdaters.clear(); + } + } + { + onCommitRoot$1(); + } + ensureRootIsScheduled(root2, now()); + if (recoverableErrors !== null) { + var onRecoverableError = root2.onRecoverableError; + for (var i = 0;i < recoverableErrors.length; i++) { + var recoverableError = recoverableErrors[i]; + var componentStack = recoverableError.stack; + var digest = recoverableError.digest; + onRecoverableError(recoverableError.value, { + componentStack, + digest + }); + } + } + if (hasUncaughtError) { + hasUncaughtError = false; + var error$1 = firstUncaughtError; + firstUncaughtError = null; + throw error$1; + } + if (includesSomeLane(pendingPassiveEffectsLanes, SyncLane) && root2.tag !== LegacyRoot) { + flushPassiveEffects(); + } + remainingLanes = root2.pendingLanes; + if (includesSomeLane(remainingLanes, SyncLane)) { + { + markNestedUpdateScheduled(); + } + if (root2 === rootWithNestedUpdates) { + nestedUpdateCount++; + } else { + nestedUpdateCount = 0; + rootWithNestedUpdates = root2; + } + } else { + nestedUpdateCount = 0; + } + flushSyncCallbacks(); + { + markCommitStopped(); + } + return null; + } + function flushPassiveEffects() { + if (rootWithPendingPassiveEffects !== null) { + var renderPriority = lanesToEventPriority(pendingPassiveEffectsLanes); + var priority = lowerEventPriority(DefaultEventPriority, renderPriority); + var prevTransition = ReactCurrentBatchConfig$3.transition; + var previousPriority = getCurrentUpdatePriority(); + try { + ReactCurrentBatchConfig$3.transition = null; + setCurrentUpdatePriority(priority); + return flushPassiveEffectsImpl(); + } finally { + setCurrentUpdatePriority(previousPriority); + ReactCurrentBatchConfig$3.transition = prevTransition; + } + } + 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 transitions = pendingPassiveTransitions; + pendingPassiveTransitions = null; + var root2 = rootWithPendingPassiveEffects; + var lanes = pendingPassiveEffectsLanes; + rootWithPendingPassiveEffects = null; + pendingPassiveEffectsLanes = NoLanes; + if ((executionContext & (RenderContext | CommitContext)) !== NoContext) { + throw new Error("Cannot flush passive effects while already rendering."); + } + { + isFlushingPassiveEffects = true; + didScheduleUpdateDuringPassiveEffects = false; + } + { + markPassiveEffectsStarted(lanes); + } + var prevExecutionContext = executionContext; + executionContext |= CommitContext; + commitPassiveUnmountEffects(root2.current); + commitPassiveMountEffects(root2, root2.current, lanes, transitions); + { + var profilerEffects = pendingPassiveProfilerEffects; + pendingPassiveProfilerEffects = []; + for (var i = 0;i < profilerEffects.length; i++) { + var _fiber = profilerEffects[i]; + commitPassiveEffectDurations(root2, _fiber); + } + } + { + markPassiveEffectsStopped(); + } + { + commitDoubleInvokeEffectsInDEV(root2.current, true); + } + executionContext = prevExecutionContext; + flushSyncCallbacks(); + { + if (didScheduleUpdateDuringPassiveEffects) { + if (root2 === rootWithPassiveNestedUpdates) { + nestedPassiveUpdateCount++; + } else { + nestedPassiveUpdateCount = 0; + rootWithPassiveNestedUpdates = root2; + } + } else { + nestedPassiveUpdateCount = 0; + } + isFlushingPassiveEffects = false; + didScheduleUpdateDuringPassiveEffects = false; + } + onPostCommitRoot(root2); + { + var stateNode = root2.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(error2) { + if (!hasUncaughtError) { + hasUncaughtError = true; + firstUncaughtError = error2; + } + } + var onUncaughtError = prepareToThrowUncaughtError; + function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error2) { + var errorInfo = createCapturedValueAtFiber(error2, sourceFiber); + var update = createRootErrorUpdate(rootFiber, errorInfo, SyncLane); + var root2 = enqueueUpdate(rootFiber, update, SyncLane); + var eventTime = requestEventTime(); + if (root2 !== null) { + markRootUpdated(root2, SyncLane, eventTime); + ensureRootIsScheduled(root2, eventTime); + } + } + function captureCommitPhaseError(sourceFiber, nearestMountedAncestor, error$1) { + { + reportUncaughtErrorInDEV(error$1); + setIsRunningInsertionEffect(false); + } + if (sourceFiber.tag === HostRoot) { + 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 = createCapturedValueAtFiber(error$1, sourceFiber); + var update = createClassErrorUpdate(fiber, errorInfo, SyncLane); + var root2 = enqueueUpdate(fiber, update, SyncLane); + var eventTime = requestEventTime(); + if (root2 !== null) { + markRootUpdated(root2, SyncLane, eventTime); + ensureRootIsScheduled(root2, eventTime); + } + return; + } + } + fiber = fiber.return; + } + { + 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\nError message:\n\n%s", error$1); + } + } + function pingSuspendedRoot(root2, wakeable, pingedLanes) { + var pingCache = root2.pingCache; + if (pingCache !== null) { + pingCache.delete(wakeable); + } + var eventTime = requestEventTime(); + markRootPinged(root2, pingedLanes); + warnIfSuspenseResolutionNotWrappedWithActDEV(root2); + if (workInProgressRoot === root2 && isSubsetOfLanes(workInProgressRootRenderLanes, pingedLanes)) { + if (workInProgressRootExitStatus === RootSuspendedWithDelay || workInProgressRootExitStatus === RootSuspended && includesOnlyRetries(workInProgressRootRenderLanes) && now() - globalMostRecentFallbackTime < FALLBACK_THROTTLE_MS) { + prepareFreshStack(root2, NoLanes); + } else { + workInProgressRootPingedLanes = mergeLanes(workInProgressRootPingedLanes, pingedLanes); + } + } + ensureRootIsScheduled(root2, eventTime); + } + function retryTimedOutBoundary(boundaryFiber, retryLane) { + if (retryLane === NoLane) { + retryLane = requestRetryLane(boundaryFiber); + } + var eventTime = requestEventTime(); + var root2 = enqueueConcurrentRenderForLane(boundaryFiber, retryLane); + if (root2 !== null) { + markRootUpdated(root2, retryLane, eventTime); + ensureRootIsScheduled(root2, 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; + 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) { + retryCache.delete(wakeable); + } + retryTimedOutBoundary(boundaryFiber, retryLane); + } + 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; + rootWithPassiveNestedUpdates = null; + 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) { + { + 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) { + { + var current2 = firstChild; + var subtreeRoot = null; + while (current2 !== null) { + var primarySubtreeFlag = current2.subtreeFlags & fiberFlags; + if (current2 !== subtreeRoot && current2.child !== null && primarySubtreeFlag !== NoFlags) { + current2 = current2.child; + } else { + if ((current2.flags & fiberFlags) !== NoFlags) { + invokeEffectFn(current2); + } + if (current2.sibling !== null) { + current2 = current2.sibling; + } else { + current2 = subtreeRoot = current2.return; + } + } + } + } + } + var didWarnStateUpdateForNotYetMountedComponent = null; + function warnAboutUpdateOnNotYetMountedFiberInDEV(fiber) { + { + if ((executionContext & RenderContext) !== NoContext) { + 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) { + return; + } + 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(current2, unitOfWork, lanes) { + var originalWorkInProgressCopy = assignFiberPropertiesInDEV(dummyFiber, unitOfWork); + try { + return beginWork(current2, unitOfWork, lanes); + } catch (originalError) { + if (didSuspendOrErrorWhileHydratingDEV() || originalError !== null && typeof originalError === "object" && typeof originalError.then === "function") { + throw originalError; + } + resetContextDependencies(); + resetHooksAfterThrow(); + unwindInterruptedWork(current2, unitOfWork); + assignFiberPropertiesInDEV(unitOfWork, originalWorkInProgressCopy); + if (unitOfWork.mode & ProfileMode) { + startProfilerTimer(unitOfWork); + } + invokeGuardedCallback(null, beginWork, null, current2, unitOfWork, lanes); + if (hasCaughtError()) { + var replayError = clearCaughtError(); + if (typeof replayError === "object" && replayError !== null && replayError._suppressLogging && typeof originalError === "object" && originalError !== null && !originalError._suppressLogging) { + originalError._suppressLogging = true; + } + } + 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"; + 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(root2, lanes) { + { + if (isDevToolsPresent) { + var memoizedUpdaters = root2.memoizedUpdaters; + memoizedUpdaters.forEach(function(schedulingFiber) { + addFiberToLanesMap(root2, schedulingFiber, lanes); + }); + } + } + } + var fakeActCallbackNode = {}; + function scheduleCallback$1(priorityLevel, callback) { + { + 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; + } + return cancelCallback(callbackNode); + } + function shouldForceFlushFallbacksInDEV() { + return ReactCurrentActQueue$1.current !== null; + } + function warnIfUpdatesNotWrappedWithActDEV(fiber) { + { + if (fiber.mode & ConcurrentMode) { + if (!isConcurrentActEnvironment()) { + return; + } + } else { + if (!isLegacyActEnvironment()) { + return; + } + if (executionContext !== NoContext) { + return; + } + if (fiber.tag !== FunctionComponent && fiber.tag !== ForwardRef && fiber.tag !== SimpleMemoComponent) { + 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\nWhen testing, code that causes React state updates should be wrapped into act(...):\n\nact(() => {\n /* fire events that update state */\n});\n/* assert on the output */\n\nThis 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(root2) { + { + if (root2.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\nWhen testing, code that resolves suspended data should be wrapped into act(...):\n\nact(() => {\n /* finish loading suspended data */\n});\n/* assert on the output */\n\nThis 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"); + } + } + } + function setIsRunningInsertionEffect(isRunning) { + { + isRunningInsertionEffect = isRunning; + } + } + var resolveFamily = null; + var failedBoundaries = null; + var setRefreshHandler = function(handler) { + { + resolveFamily = handler; + } + }; + function resolveFunctionForHotReloading(type) { + { + if (resolveFamily === null) { + return type; + } + var family = resolveFamily(type); + if (family === undefined) { + return type; + } + return family.current; + } + } + function resolveClassForHotReloading(type) { + return resolveFunctionForHotReloading(type); + } + function resolveForwardRefForHotReloading(type) { + { + if (resolveFamily === null) { + return type; + } + var family = resolveFamily(type); + if (family === undefined) { + if (type !== null && type !== undefined && typeof type.render === "function") { + 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; + } + return family.current; + } + } + function isCompatibleFamilyForHotReloading(fiber, element) { + { + if (resolveFamily === null) { + return false; + } + var prevType = fiber.elementType; + var nextType = element.type; + 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) { + 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) { + needsCompareFamilies = true; + } else if ($$typeofNextType === REACT_LAZY_TYPE) { + needsCompareFamilies = true; + } + break; + } + default: + return false; + } + if (needsCompareFamilies) { + var prevFamily = resolveFamily(prevType); + if (prevFamily !== undefined && prevFamily === resolveFamily(nextType)) { + return true; + } + } + return false; + } + } + function markFailedErrorBoundaryForHotReloading(fiber) { + { + if (resolveFamily === null) { + return; + } + if (typeof WeakSet !== "function") { + return; + } + if (failedBoundaries === null) { + failedBoundaries = new WeakSet; + } + failedBoundaries.add(fiber); + } + } + var scheduleRefresh = function(root2, update) { + { + if (resolveFamily === null) { + return; + } + var { staleFamilies, updatedFamilies } = update; + flushPassiveEffects(); + flushSync(function() { + scheduleFibersWithFamiliesRecursively(root2.current, updatedFamilies, staleFamilies); + }); + } + }; + var scheduleRoot = function(root2, element) { + { + if (root2.context !== emptyContextObject) { + return; + } + flushPassiveEffects(); + flushSync(function() { + updateContainer(element, root2, null, null); + }); + } + }; + function scheduleFibersWithFamiliesRecursively(fiber, updatedFamilies, staleFamilies) { + { + var { alternate, child, sibling, tag, type } = fiber; + 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) { + var _root = enqueueConcurrentRenderForLane(fiber, SyncLane); + if (_root !== null) { + scheduleUpdateOnFiber(_root, fiber, SyncLane, NoTimestamp); + } + } + if (child !== null && !needsRemount) { + scheduleFibersWithFamiliesRecursively(child, updatedFamilies, staleFamilies); + } + if (sibling !== null) { + scheduleFibersWithFamiliesRecursively(sibling, updatedFamilies, staleFamilies); + } + } + } + var findHostInstancesForRefresh = function(root2, families) { + { + var hostInstances = new Set; + var types = new Set(families.map(function(family) { + return family.current; + })); + findHostInstancesForMatchingFibersRecursively(root2.current, types, hostInstances); + return hostInstances; + } + }; + function findHostInstancesForMatchingFibersRecursively(fiber, types, hostInstances) { + { + var { child, sibling, tag, type } = fiber; + 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) { + findHostInstancesForFiberShallowly(fiber, hostInstances); + } else { + 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; + } + 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) { + foundHostInstances = true; + hostInstances.add(node.stateNode); + } 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({}); + new Map([[nonExtensibleObject, null]]); + new Set([nonExtensibleObject]); + } catch (e) { + hasBadMapPolyfill = true; + } + } + function FiberNode(tag, pendingProps, key, mode) { + this.tag = tag; + this.key = key; + this.elementType = null; + this.type = null; + this.stateNode = null; + 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; + this.flags = NoFlags; + this.subtreeFlags = NoFlags; + this.deletions = null; + this.lanes = NoLanes; + this.childLanes = NoLanes; + this.alternate = null; + { + this.actualDuration = Number.NaN; + this.actualStartTime = Number.NaN; + this.selfBaseDuration = Number.NaN; + this.treeBaseDuration = Number.NaN; + this.actualDuration = 0; + this.actualStartTime = -1; + this.selfBaseDuration = 0; + this.treeBaseDuration = 0; + } + { + this._debugSource = null; + this._debugOwner = null; + this._debugNeedsRemount = false; + this._debugHookTypes = null; + if (!hasBadMapPolyfill && typeof Object.preventExtensions === "function") { + Object.preventExtensions(this); + } + } + } + var createFiber = function(tag, pendingProps, key, mode) { + 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; + } + function createWorkInProgress(current2, pendingProps) { + var workInProgress2 = current2.alternate; + if (workInProgress2 === null) { + workInProgress2 = createFiber(current2.tag, pendingProps, current2.key, current2.mode); + workInProgress2.elementType = current2.elementType; + workInProgress2.type = current2.type; + workInProgress2.stateNode = current2.stateNode; + { + workInProgress2._debugSource = current2._debugSource; + workInProgress2._debugOwner = current2._debugOwner; + workInProgress2._debugHookTypes = current2._debugHookTypes; + } + workInProgress2.alternate = current2; + current2.alternate = workInProgress2; + } else { + workInProgress2.pendingProps = pendingProps; + workInProgress2.type = current2.type; + workInProgress2.flags = NoFlags; + workInProgress2.subtreeFlags = NoFlags; + workInProgress2.deletions = null; + { + workInProgress2.actualDuration = 0; + workInProgress2.actualStartTime = -1; + } + } + workInProgress2.flags = current2.flags & StaticMask; + workInProgress2.childLanes = current2.childLanes; + workInProgress2.lanes = current2.lanes; + workInProgress2.child = current2.child; + workInProgress2.memoizedProps = current2.memoizedProps; + workInProgress2.memoizedState = current2.memoizedState; + workInProgress2.updateQueue = current2.updateQueue; + var currentDependencies = current2.dependencies; + workInProgress2.dependencies = currentDependencies === null ? null : { + lanes: currentDependencies.lanes, + firstContext: currentDependencies.firstContext + }; + workInProgress2.sibling = current2.sibling; + workInProgress2.index = current2.index; + workInProgress2.ref = current2.ref; + { + workInProgress2.selfBaseDuration = current2.selfBaseDuration; + workInProgress2.treeBaseDuration = current2.treeBaseDuration; + } + { + workInProgress2._debugNeedsRemount = current2._debugNeedsRemount; + switch (workInProgress2.tag) { + case IndeterminateComponent: + case FunctionComponent: + case SimpleMemoComponent: + workInProgress2.type = resolveFunctionForHotReloading(current2.type); + break; + case ClassComponent: + workInProgress2.type = resolveClassForHotReloading(current2.type); + break; + case ForwardRef: + workInProgress2.type = resolveForwardRefForHotReloading(current2.type); + break; + } + } + return workInProgress2; + } + function resetWorkInProgress(workInProgress2, renderLanes2) { + workInProgress2.flags &= StaticMask | Placement; + var current2 = workInProgress2.alternate; + if (current2 === null) { + workInProgress2.childLanes = NoLanes; + workInProgress2.lanes = renderLanes2; + workInProgress2.child = null; + workInProgress2.subtreeFlags = NoFlags; + workInProgress2.memoizedProps = null; + workInProgress2.memoizedState = null; + workInProgress2.updateQueue = null; + workInProgress2.dependencies = null; + workInProgress2.stateNode = null; + { + workInProgress2.selfBaseDuration = 0; + workInProgress2.treeBaseDuration = 0; + } + } else { + workInProgress2.childLanes = current2.childLanes; + workInProgress2.lanes = current2.lanes; + workInProgress2.child = current2.child; + workInProgress2.subtreeFlags = NoFlags; + workInProgress2.deletions = null; + workInProgress2.memoizedProps = current2.memoizedProps; + workInProgress2.memoizedState = current2.memoizedState; + workInProgress2.updateQueue = current2.updateQueue; + workInProgress2.type = current2.type; + var currentDependencies = current2.dependencies; + workInProgress2.dependencies = currentDependencies === null ? null : { + lanes: currentDependencies.lanes, + firstContext: currentDependencies.firstContext + }; + { + workInProgress2.selfBaseDuration = current2.selfBaseDuration; + workInProgress2.treeBaseDuration = current2.treeBaseDuration; + } + } + return workInProgress2; + } + function createHostRootFiber(tag, isStrictMode, concurrentUpdatesByDefaultOverride) { + var mode; + if (tag === ConcurrentRoot) { + mode = ConcurrentMode; + if (isStrictMode === true) { + mode |= StrictLegacyMode; + { + mode |= StrictEffectsMode; + } + } + } else { + mode = NoMode; + } + if (isDevToolsPresent) { + mode |= ProfileMode; + } + return createFiber(HostRoot, null, null, mode); + } + function createFiberFromTypeAndProps(type, key, pendingProps, owner, mode, lanes) { + var fiberTag = IndeterminateComponent; + 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) { + 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: + case REACT_SCOPE_TYPE: + case REACT_CACHE_TYPE: + case REACT_TRACING_MARKER_TYPE: + case REACT_DEBUG_TRACING_MODE_TYPE: + default: { + if (typeof type === "object" && type !== null) { + switch (type.$$typeof) { + case REACT_PROVIDER_TYPE: + fiberTag = ContextProvider; + break getTag; + case REACT_CONTEXT_TYPE: + 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 = { + isHidden: false + }; + 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, + implementation: portal.implementation + }; + return fiber; + } + function assignFiberPropertiesInDEV(target, source) { + if (target === null) { + target = createFiber(IndeterminateComponent, null, null, NoMode); + } + 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, hydrate2, 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; + { + 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 = hydrate2 ? "hydrateRoot()" : "createRoot()"; + break; + case LegacyRoot: + this._debugRootType = hydrate2 ? "hydrate()" : "render()"; + break; + } + } + } + function createFiberRoot(containerInfo, tag, hydrate2, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError, transitionCallbacks) { + var root2 = new FiberRootNode(containerInfo, tag, hydrate2, identifierPrefix, onRecoverableError); + var uninitializedFiber = createHostRootFiber(tag, isStrictMode); + root2.current = uninitializedFiber; + uninitializedFiber.stateNode = root2; + { + var _initialState = { + element: initialChildren, + isDehydrated: hydrate2, + cache: null, + transitions: null, + pendingSuspenseBoundaries: null + }; + uninitializedFiber.memoizedState = _initialState; + } + initializeUpdateQueue(uninitializedFiber); + return root2; + } + var ReactVersion = "18.3.1"; + function createPortal(children, containerInfo, implementation) { + var key = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; + { + checkKeyStringCoercion(key); + } + return { + $$typeof: REACT_PORTAL_TYPE, + key: key == null ? null : "" + key, + children, + containerInfo, + 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 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 { + if (previousFiber) { + setCurrentFiber(previousFiber); + } else { + resetCurrentFiber(); + } + } + } + } + return hostFiber.stateNode; + } + } + function createContainer(containerInfo, tag, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError, transitionCallbacks) { + var hydrate2 = false; + var initialChildren = null; + return createFiberRoot(containerInfo, tag, hydrate2, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError); + } + function createHydrationContainer(initialChildren, callback, containerInfo, tag, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError, transitionCallbacks) { + var hydrate2 = true; + var root2 = createFiberRoot(containerInfo, tag, hydrate2, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError); + root2.context = getContextForSubtree(null); + var current2 = root2.current; + var eventTime = requestEventTime(); + var lane = requestUpdateLane(current2); + var update = createUpdate(eventTime, lane); + update.callback = callback !== undefined && callback !== null ? callback : null; + enqueueUpdate(current2, update, lane); + scheduleInitialHydrationOnRoot(root2, lane, eventTime); + return root2; + } + 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\nCheck the render method of %s.", getComponentNameFromFiber(current) || "Unknown"); + } + } + var update = createUpdate(eventTime, lane); + update.payload = { + 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; + } + var root2 = enqueueUpdate(current$1, update, lane); + if (root2 !== null) { + scheduleUpdateOnFiber(root2, current$1, lane, eventTime); + entangleTransitions(root2, 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$1(fiber) { + switch (fiber.tag) { + case HostRoot: { + var root2 = fiber.stateNode; + if (isRootDehydrated(root2)) { + var lanes = getHighestPriorityPendingLanes(root2); + flushRoot(root2, lanes); + } + break; + } + case SuspenseComponent: { + flushSync(function() { + var root3 = enqueueConcurrentRenderForLane(fiber, SyncLane); + if (root3 !== null) { + var eventTime = requestEventTime(); + scheduleUpdateOnFiber(root3, fiber, SyncLane, eventTime); + } + }); + 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); + } + } + function markRetryLaneIfNotHydrated(fiber, retryLane) { + markRetryLaneImpl(fiber, retryLane); + var alternate = fiber.alternate; + if (alternate) { + markRetryLaneImpl(alternate, retryLane); + } + } + function attemptContinuousHydration$1(fiber) { + if (fiber.tag !== SuspenseComponent) { + return; + } + var lane = SelectiveHydrationLane; + var root2 = enqueueConcurrentRenderForLane(fiber, lane); + if (root2 !== null) { + var eventTime = requestEventTime(); + scheduleUpdateOnFiber(root2, fiber, lane, eventTime); + } + markRetryLaneIfNotHydrated(fiber, lane); + } + function attemptHydrationAtCurrentPriority$1(fiber) { + if (fiber.tag !== SuspenseComponent) { + return; + } + var lane = requestUpdateLane(fiber); + var root2 = enqueueConcurrentRenderForLane(fiber, lane); + if (root2 !== null) { + var eventTime = requestEventTime(); + scheduleUpdateOnFiber(root2, 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, index2) { + var key = path[index2]; + var updated = isArray(obj) ? obj.slice() : assign({}, obj); + if (index2 + 1 === path.length) { + if (isArray(updated)) { + updated.splice(key, 1); + } else { + delete updated[key]; + } + return updated; + } + updated[key] = copyWithDeleteImpl(obj[key], path, index2 + 1); + return updated; + }; + var copyWithDelete = function(obj, path) { + return copyWithDeleteImpl(obj, path, 0); + }; + var copyWithRenameImpl = function(obj, oldPath, newPath, index2) { + var oldKey = oldPath[index2]; + var updated = isArray(obj) ? obj.slice() : assign({}, obj); + if (index2 + 1 === oldPath.length) { + var newKey = newPath[index2]; + updated[newKey] = updated[oldKey]; + if (isArray(updated)) { + updated.splice(oldKey, 1); + } else { + delete updated[oldKey]; + } + } else { + updated[oldKey] = copyWithRenameImpl(obj[oldKey], oldPath, newPath, index2 + 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, index2, value) { + if (index2 >= path.length) { + return value; + } + var key = path[index2]; + var updated = isArray(obj) ? obj.slice() : assign({}, obj); + updated[key] = copyWithSetImpl(obj[key], path, index2 + 1, value); + return updated; + }; + var copyWithSet = function(obj, path, value) { + return copyWithSetImpl(obj, path, 0, value); + }; + var findHook = function(fiber, id) { + var currentHook2 = fiber.memoizedState; + while (currentHook2 !== null && id > 0) { + currentHook2 = currentHook2.next; + id--; + } + return currentHook2; + }; + 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; + fiber.memoizedProps = assign({}, fiber.memoizedProps); + var root2 = enqueueConcurrentRenderForLane(fiber, SyncLane); + if (root2 !== null) { + scheduleUpdateOnFiber(root2, 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; + fiber.memoizedProps = assign({}, fiber.memoizedProps); + var root2 = enqueueConcurrentRenderForLane(fiber, SyncLane); + if (root2 !== null) { + scheduleUpdateOnFiber(root2, 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; + fiber.memoizedProps = assign({}, fiber.memoizedProps); + var root2 = enqueueConcurrentRenderForLane(fiber, SyncLane); + if (root2 !== null) { + scheduleUpdateOnFiber(root2, fiber, SyncLane, NoTimestamp); + } + } + }; + overrideProps = function(fiber, path, value) { + fiber.pendingProps = copyWithSet(fiber.memoizedProps, path, value); + if (fiber.alternate) { + fiber.alternate.pendingProps = fiber.pendingProps; + } + var root2 = enqueueConcurrentRenderForLane(fiber, SyncLane); + if (root2 !== null) { + scheduleUpdateOnFiber(root2, fiber, SyncLane, NoTimestamp); + } + }; + overridePropsDeletePath = function(fiber, path) { + fiber.pendingProps = copyWithDelete(fiber.memoizedProps, path); + if (fiber.alternate) { + fiber.alternate.pendingProps = fiber.pendingProps; + } + var root2 = enqueueConcurrentRenderForLane(fiber, SyncLane); + if (root2 !== null) { + scheduleUpdateOnFiber(root2, fiber, SyncLane, NoTimestamp); + } + }; + overridePropsRenamePath = function(fiber, oldPath, newPath) { + fiber.pendingProps = copyWithRename(fiber.memoizedProps, oldPath, newPath); + if (fiber.alternate) { + fiber.alternate.pendingProps = fiber.pendingProps; + } + var root2 = enqueueConcurrentRenderForLane(fiber, SyncLane); + if (root2 !== null) { + scheduleUpdateOnFiber(root2, fiber, SyncLane, NoTimestamp); + } + }; + scheduleUpdate = function(fiber) { + var root2 = enqueueConcurrentRenderForLane(fiber, SyncLane); + if (root2 !== null) { + scheduleUpdateOnFiber(root2, 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 ReactCurrentDispatcher2 = ReactSharedInternals.ReactCurrentDispatcher; + return injectInternals({ + bundleType: devToolsConfig.bundleType, + version: devToolsConfig.version, + rendererPackageName: devToolsConfig.rendererPackageName, + rendererConfig: devToolsConfig.rendererConfig, + overrideHookState, + overrideHookStateDeletePath, + overrideHookStateRenamePath, + overrideProps, + overridePropsDeletePath, + overridePropsRenamePath, + setErrorHandler, + setSuspenseHandler, + scheduleUpdate, + currentDispatcherRef: ReactCurrentDispatcher2, + findHostInstanceByFiber, + findFiberByHostInstance: findFiberByHostInstance || emptyFindFiberByHostInstance, + findHostInstancesForRefresh, + scheduleRefresh, + scheduleRoot, + setRefreshHandler, + getCurrentFiber: getCurrentFiberForDevTools, + reconcilerVersion: ReactVersion + }); + } + var defaultOnRecoverableError = typeof reportError === "function" ? reportError : function(error2) { + console["error"](error2); + }; + function ReactDOMRoot(internalRoot) { + this._internalRoot = internalRoot; + } + ReactDOMHydrationRoot.prototype.render = ReactDOMRoot.prototype.render = function(children) { + var root2 = this._internalRoot; + if (root2 === null) { + throw new Error("Cannot update an unmounted root."); + } + { + if (typeof arguments[1] === "function") { + error("render(...): does not support the second callback argument. To execute a side effect after rendering, declare it in a component body with useEffect()."); + } else if (isValidContainer(arguments[1])) { + error("You passed a container to the second argument of root.render(...). You don't need to pass it again since you already passed it to create the root."); + } else if (typeof arguments[1] !== "undefined") { + error("You passed a second argument to root.render(...) but it only accepts one argument."); + } + var container = root2.containerInfo; + if (container.nodeType !== COMMENT_NODE) { + var hostInstance = findHostInstanceWithNoPortals(root2.current); + if (hostInstance) { + if (hostInstance.parentNode !== container) { + error("render(...): It looks like the React-rendered content of the root container was removed without using React. This is not supported and will cause errors. Instead, call root.unmount() to empty a root's container."); + } + } + } + } + updateContainer(children, root2, null, null); + }; + ReactDOMHydrationRoot.prototype.unmount = ReactDOMRoot.prototype.unmount = function() { + { + if (typeof arguments[0] === "function") { + error("unmount(...): does not support a callback argument. To execute a side effect after rendering, declare it in a component body with useEffect()."); + } + } + var root2 = this._internalRoot; + if (root2 !== null) { + this._internalRoot = null; + var container = root2.containerInfo; + { + if (isAlreadyRendering()) { + error("Attempted to synchronously unmount a root while React was already rendering. React cannot finish unmounting the root until the current render has completed, which may lead to a race condition."); + } + } + flushSync(function() { + updateContainer(null, root2, null, null); + }); + unmarkContainerAsRoot(container); + } + }; + function createRoot(container, options2) { + if (!isValidContainer(container)) { + throw new Error("createRoot(...): Target container is not a DOM element."); + } + warnIfReactDOMContainerInDEV(container); + var isStrictMode = false; + var concurrentUpdatesByDefaultOverride = false; + var identifierPrefix = ""; + var onRecoverableError = defaultOnRecoverableError; + var transitionCallbacks = null; + if (options2 !== null && options2 !== undefined) { + { + if (options2.hydrate) { + warn("hydrate through createRoot is deprecated. Use ReactDOMClient.hydrateRoot(container, <App />) instead."); + } else { + if (typeof options2 === "object" && options2 !== null && options2.$$typeof === REACT_ELEMENT_TYPE) { + error("You passed a JSX element to createRoot. You probably meant to call root.render instead. Example usage:\n\n let root = createRoot(domContainer);\n root.render(<App />);"); + } + } + } + if (options2.unstable_strictMode === true) { + isStrictMode = true; + } + if (options2.identifierPrefix !== undefined) { + identifierPrefix = options2.identifierPrefix; + } + if (options2.onRecoverableError !== undefined) { + onRecoverableError = options2.onRecoverableError; + } + if (options2.transitionCallbacks !== undefined) { + transitionCallbacks = options2.transitionCallbacks; + } + } + var root2 = createContainer(container, ConcurrentRoot, null, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError); + markContainerAsRoot(root2.current, container); + var rootContainerElement = container.nodeType === COMMENT_NODE ? container.parentNode : container; + listenToAllSupportedEvents(rootContainerElement); + return new ReactDOMRoot(root2); + } + function ReactDOMHydrationRoot(internalRoot) { + this._internalRoot = internalRoot; + } + function scheduleHydration(target) { + if (target) { + queueExplicitHydrationTarget(target); + } + } + ReactDOMHydrationRoot.prototype.unstable_scheduleHydration = scheduleHydration; + function hydrateRoot(container, initialChildren, options2) { + if (!isValidContainer(container)) { + throw new Error("hydrateRoot(...): Target container is not a DOM element."); + } + warnIfReactDOMContainerInDEV(container); + { + if (initialChildren === undefined) { + error("Must provide initial children as second argument to hydrateRoot. Example usage: hydrateRoot(domContainer, <App />)"); + } + } + var hydrationCallbacks = options2 != null ? options2 : null; + var mutableSources = options2 != null && options2.hydratedSources || null; + var isStrictMode = false; + var concurrentUpdatesByDefaultOverride = false; + var identifierPrefix = ""; + var onRecoverableError = defaultOnRecoverableError; + if (options2 !== null && options2 !== undefined) { + if (options2.unstable_strictMode === true) { + isStrictMode = true; + } + if (options2.identifierPrefix !== undefined) { + identifierPrefix = options2.identifierPrefix; + } + if (options2.onRecoverableError !== undefined) { + onRecoverableError = options2.onRecoverableError; + } + } + var root2 = createHydrationContainer(initialChildren, null, container, ConcurrentRoot, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError); + markContainerAsRoot(root2.current, container); + listenToAllSupportedEvents(container); + if (mutableSources) { + for (var i = 0;i < mutableSources.length; i++) { + var mutableSource = mutableSources[i]; + registerMutableSourceForHydration(root2, mutableSource); + } + } + return new ReactDOMHydrationRoot(root2); + } + function isValidContainer(node) { + return !!(node && (node.nodeType === ELEMENT_NODE || node.nodeType === DOCUMENT_NODE || node.nodeType === DOCUMENT_FRAGMENT_NODE || !disableCommentsAsDOMContainers)); + } + function isValidContainerLegacy(node) { + return !!(node && (node.nodeType === ELEMENT_NODE || node.nodeType === DOCUMENT_NODE || node.nodeType === DOCUMENT_FRAGMENT_NODE || node.nodeType === COMMENT_NODE && node.nodeValue === " react-mount-point-unstable ")); + } + function warnIfReactDOMContainerInDEV(container) { + { + if (container.nodeType === ELEMENT_NODE && container.tagName && container.tagName.toUpperCase() === "BODY") { + error("createRoot(): Creating roots directly with document.body is discouraged, since its children are often manipulated by third-party scripts and browser extensions. This may lead to subtle reconciliation issues. Try using a container element created for your app."); + } + if (isContainerMarkedAsRoot(container)) { + if (container._reactRootContainer) { + error("You are calling ReactDOMClient.createRoot() on a container that was previously passed to ReactDOM.render(). This is not supported."); + } else { + error("You are calling ReactDOMClient.createRoot() on a container that has already been passed to createRoot() before. Instead, call root.render() on the existing root instead if you want to update it."); + } + } + } + } + var ReactCurrentOwner$3 = ReactSharedInternals.ReactCurrentOwner; + var topLevelUpdateWarnings; + { + topLevelUpdateWarnings = function(container) { + if (container._reactRootContainer && container.nodeType !== COMMENT_NODE) { + var hostInstance = findHostInstanceWithNoPortals(container._reactRootContainer.current); + if (hostInstance) { + if (hostInstance.parentNode !== container) { + error("render(...): It looks like the React-rendered content of this container was removed without using React. This is not supported and will cause errors. Instead, call ReactDOM.unmountComponentAtNode to empty a container."); + } + } + } + var isRootRenderedBySomeReact = !!container._reactRootContainer; + var rootEl = getReactRootElementInContainer(container); + var hasNonRootReactChild = !!(rootEl && getInstanceFromNode(rootEl)); + if (hasNonRootReactChild && !isRootRenderedBySomeReact) { + error("render(...): Replacing React-rendered children with a new root component. If you intended to update the children of this node, you should instead have the existing children update their state and render the new components instead of calling ReactDOM.render."); + } + if (container.nodeType === ELEMENT_NODE && container.tagName && container.tagName.toUpperCase() === "BODY") { + error("render(): Rendering components directly into document.body is discouraged, since its children are often manipulated by third-party scripts and browser extensions. This may lead to subtle reconciliation issues. Try rendering into a container element created for your app."); + } + }; + } + function getReactRootElementInContainer(container) { + if (!container) { + return null; + } + if (container.nodeType === DOCUMENT_NODE) { + return container.documentElement; + } else { + return container.firstChild; + } + } + function noopOnRecoverableError() { + } + function legacyCreateRootFromDOMContainer(container, initialChildren, parentComponent, callback, isHydrationContainer) { + if (isHydrationContainer) { + if (typeof callback === "function") { + var originalCallback = callback; + callback = function() { + var instance = getPublicRootInstance(root2); + originalCallback.call(instance); + }; + } + var root2 = createHydrationContainer(initialChildren, callback, container, LegacyRoot, null, false, false, "", noopOnRecoverableError); + container._reactRootContainer = root2; + markContainerAsRoot(root2.current, container); + var rootContainerElement = container.nodeType === COMMENT_NODE ? container.parentNode : container; + listenToAllSupportedEvents(rootContainerElement); + flushSync(); + return root2; + } else { + var rootSibling; + while (rootSibling = container.lastChild) { + container.removeChild(rootSibling); + } + if (typeof callback === "function") { + var _originalCallback = callback; + callback = function() { + var instance = getPublicRootInstance(_root); + _originalCallback.call(instance); + }; + } + var _root = createContainer(container, LegacyRoot, null, false, false, "", noopOnRecoverableError); + container._reactRootContainer = _root; + markContainerAsRoot(_root.current, container); + var _rootContainerElement = container.nodeType === COMMENT_NODE ? container.parentNode : container; + listenToAllSupportedEvents(_rootContainerElement); + flushSync(function() { + updateContainer(initialChildren, _root, parentComponent, callback); + }); + return _root; + } + } + function warnOnInvalidCallback$1(callback, callerName) { + { + if (callback !== null && typeof callback !== "function") { + error("%s(...): Expected the last optional `callback` argument to be a function. Instead received: %s.", callerName, callback); + } + } + } + function legacyRenderSubtreeIntoContainer(parentComponent, children, container, forceHydrate, callback) { + { + topLevelUpdateWarnings(container); + warnOnInvalidCallback$1(callback === undefined ? null : callback, "render"); + } + var maybeRoot = container._reactRootContainer; + var root2; + if (!maybeRoot) { + root2 = legacyCreateRootFromDOMContainer(container, children, parentComponent, callback, forceHydrate); + } else { + root2 = maybeRoot; + if (typeof callback === "function") { + var originalCallback = callback; + callback = function() { + var instance = getPublicRootInstance(root2); + originalCallback.call(instance); + }; + } + updateContainer(children, root2, parentComponent, callback); + } + return getPublicRootInstance(root2); + } + var didWarnAboutFindDOMNode = false; + function findDOMNode(componentOrElement) { + { + if (!didWarnAboutFindDOMNode) { + didWarnAboutFindDOMNode = true; + error("findDOMNode is deprecated and will be removed in the next major release. 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"); + } + var owner = ReactCurrentOwner$3.current; + if (owner !== null && owner.stateNode !== null) { + var warnedAboutRefsInRender = owner.stateNode._warnedAboutRefsInRender; + if (!warnedAboutRefsInRender) { + error("%s is accessing findDOMNode inside its render(). 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.", getComponentNameFromType(owner.type) || "A component"); + } + owner.stateNode._warnedAboutRefsInRender = true; + } + } + if (componentOrElement == null) { + return null; + } + if (componentOrElement.nodeType === ELEMENT_NODE) { + return componentOrElement; + } + { + return findHostInstanceWithWarning(componentOrElement, "findDOMNode"); + } + } + function hydrate(element, container, callback) { + { + error("ReactDOM.hydrate is no longer supported in React 18. Use hydrateRoot instead. Until you switch to the new API, your app will behave as if it's running React 17. Learn more: https://reactjs.org/link/switch-to-createroot"); + } + if (!isValidContainerLegacy(container)) { + throw new Error("Target container is not a DOM element."); + } + { + var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === undefined; + if (isModernRoot) { + error("You are calling ReactDOM.hydrate() on a container that was previously passed to ReactDOMClient.createRoot(). This is not supported. Did you mean to call hydrateRoot(container, element)?"); + } + } + return legacyRenderSubtreeIntoContainer(null, element, container, true, callback); + } + function render(element, container, callback) { + { + error("ReactDOM.render is no longer supported in React 18. Use createRoot instead. Until you switch to the new API, your app will behave as if it's running React 17. Learn more: https://reactjs.org/link/switch-to-createroot"); + } + if (!isValidContainerLegacy(container)) { + throw new Error("Target container is not a DOM element."); + } + { + var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === undefined; + if (isModernRoot) { + error("You are calling ReactDOM.render() on a container that was previously passed to ReactDOMClient.createRoot(). This is not supported. Did you mean to call root.render(element)?"); + } + } + return legacyRenderSubtreeIntoContainer(null, element, container, false, callback); + } + function unstable_renderSubtreeIntoContainer(parentComponent, element, containerNode, callback) { + { + error("ReactDOM.unstable_renderSubtreeIntoContainer() is no longer supported in React 18. Consider using a portal instead. Until you switch to the createRoot API, your app will behave as if it's running React 17. Learn more: https://reactjs.org/link/switch-to-createroot"); + } + if (!isValidContainerLegacy(containerNode)) { + throw new Error("Target container is not a DOM element."); + } + if (parentComponent == null || !has(parentComponent)) { + throw new Error("parentComponent must be a valid React Component"); + } + return legacyRenderSubtreeIntoContainer(parentComponent, element, containerNode, false, callback); + } + var didWarnAboutUnmountComponentAtNode = false; + function unmountComponentAtNode(container) { + { + if (!didWarnAboutUnmountComponentAtNode) { + didWarnAboutUnmountComponentAtNode = true; + error("unmountComponentAtNode is deprecated and will be removed in the next major release. Switch to the createRoot API. Learn more: https://reactjs.org/link/switch-to-createroot"); + } + } + if (!isValidContainerLegacy(container)) { + throw new Error("unmountComponentAtNode(...): Target container is not a DOM element."); + } + { + var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === undefined; + if (isModernRoot) { + error("You are calling ReactDOM.unmountComponentAtNode() on a container that was previously passed to ReactDOMClient.createRoot(). This is not supported. Did you mean to call root.unmount()?"); + } + } + if (container._reactRootContainer) { + { + var rootEl = getReactRootElementInContainer(container); + var renderedByDifferentReact = rootEl && !getInstanceFromNode(rootEl); + if (renderedByDifferentReact) { + error("unmountComponentAtNode(): The node you're attempting to unmount was rendered by another copy of React."); + } + } + flushSync(function() { + legacyRenderSubtreeIntoContainer(null, null, container, false, function() { + container._reactRootContainer = null; + unmarkContainerAsRoot(container); + }); + }); + return true; + } else { + { + var _rootEl = getReactRootElementInContainer(container); + var hasNonRootReactChild = !!(_rootEl && getInstanceFromNode(_rootEl)); + var isContainerReactRoot = container.nodeType === ELEMENT_NODE && isValidContainerLegacy(container.parentNode) && !!container.parentNode._reactRootContainer; + if (hasNonRootReactChild) { + error("unmountComponentAtNode(): The node you're attempting to unmount was rendered by React and is not a top-level container. %s", isContainerReactRoot ? "You may have accidentally passed in a React root node instead of its container." : "Instead, have the parent component update its state and rerender in order to remove this component."); + } + } + return false; + } + } + setAttemptSynchronousHydration(attemptSynchronousHydration$1); + setAttemptContinuousHydration(attemptContinuousHydration$1); + setAttemptHydrationAtCurrentPriority(attemptHydrationAtCurrentPriority$1); + setGetCurrentUpdatePriority(getCurrentUpdatePriority); + setAttemptHydrationAtPriority(runWithPriority); + { + if (typeof Map !== "function" || Map.prototype == null || typeof Map.prototype.forEach !== "function" || typeof Set !== "function" || Set.prototype == null || typeof Set.prototype.clear !== "function" || typeof Set.prototype.forEach !== "function") { + error("React depends on Map and Set built-in types. Make sure that you load a polyfill in older browsers. https://reactjs.org/link/react-polyfills"); + } + } + setRestoreImplementation(restoreControlledState$3); + setBatchingImplementation(batchedUpdates$1, discreteUpdates, flushSync); + function createPortal$1(children, container) { + var key = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; + if (!isValidContainer(container)) { + throw new Error("Target container is not a DOM element."); + } + return createPortal(children, container, null, key); + } + function renderSubtreeIntoContainer(parentComponent, element, containerNode, callback) { + return unstable_renderSubtreeIntoContainer(parentComponent, element, containerNode, callback); + } + var Internals = { + usingClientEntryPoint: false, + Events: [getInstanceFromNode, getNodeFromInstance, getFiberCurrentPropsFromNode, enqueueStateRestore, restoreStateIfNeeded, batchedUpdates$1] + }; + function createRoot$1(container, options2) { + { + if (!Internals.usingClientEntryPoint && true) { + error('You are importing createRoot from "react-dom" which is not supported. You should instead import it from "react-dom/client".'); + } + } + return createRoot(container, options2); + } + function hydrateRoot$1(container, initialChildren, options2) { + { + if (!Internals.usingClientEntryPoint && true) { + error('You are importing hydrateRoot from "react-dom" which is not supported. You should instead import it from "react-dom/client".'); + } + } + return hydrateRoot(container, initialChildren, options2); + } + function flushSync$1(fn) { + { + if (isAlreadyRendering()) { + error("flushSync was called from inside a lifecycle method. React cannot flush when React is already rendering. Consider moving this call to a scheduler task or micro task."); + } + } + return flushSync(fn); + } + var foundDevTools = injectIntoDevTools({ + findFiberByHostInstance: getClosestInstanceFromNode, + bundleType: 1, + version: ReactVersion, + rendererPackageName: "react-dom" + }); + { + if (!foundDevTools && canUseDOM && window.top === window.self) { + if (navigator.userAgent.indexOf("Chrome") > -1 && navigator.userAgent.indexOf("Edge") === -1 || navigator.userAgent.indexOf("Firefox") > -1) { + var protocol = window.location.protocol; + if (/^(https?|file):$/.test(protocol)) { + console.info("%cDownload the React DevTools for a better development experience: https://reactjs.org/link/react-devtools" + (protocol === "file:" ? "\nYou might need to use a local HTTP server (instead of file://): https://reactjs.org/link/react-devtools-faq" : ""), "font-weight:bold"); + } + } + } + } + exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = Internals; + exports.createPortal = createPortal$1; + exports.createRoot = createRoot$1; + exports.findDOMNode = findDOMNode; + exports.flushSync = flushSync$1; + exports.hydrate = hydrate; + exports.hydrateRoot = hydrateRoot$1; + exports.render = render; + exports.unmountComponentAtNode = unmountComponentAtNode; + exports.unstable_batchedUpdates = batchedUpdates$1; + exports.unstable_renderSubtreeIntoContainer = renderSubtreeIntoContainer; + exports.version = ReactVersion; + if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === "function") { + __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error); + } + })(); + } +}); + +// node_modules/react-dom/index.js +var require_react_dom = __commonJS((exports, module) => { + var react_dom_development = __toESM(require_react_dom_development(), 1); + if (false) { + } else { + module.exports = react_dom_development; + } +}); + +// node_modules/react-dom/client.js +var require_client = __commonJS((exports) => { + var m = __toESM(require_react_dom(), 1); + if (false) { + } else { + i = m.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; + exports.createRoot = function(c, o) { + i.usingClientEntryPoint = true; + try { + return m.createRoot(c, o); + } finally { + i.usingClientEntryPoint = false; + } + }; + exports.hydrateRoot = function(c, h, o) { + i.usingClientEntryPoint = true; + try { + return m.hydrateRoot(c, h, o); + } finally { + i.usingClientEntryPoint = false; + } + }; + } + var i; +}); + +// node_modules/react/cjs/react-jsx-dev-runtime.development.js +var require_react_jsx_dev_runtime_development = __commonJS((exports) => { + var React = __toESM(require_react(), 1); + if (true) { + (function() { + 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_OFFSCREEN_TYPE = Symbol.for("react.offscreen"); + 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; + } + var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; + function error(format) { + { + { + 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) { + { + var ReactDebugCurrentFrame2 = ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame2.getStackAddendum(); + if (stack !== "") { + format += "%s"; + args = args.concat([stack]); + } + var argsWithFormat = args.map(function(item) { + return String(item); + }); + argsWithFormat.unshift("Warning: " + format); + Function.prototype.apply.call(console[level], console, argsWithFormat); + } + } + var enableScopeAPI = false; + var enableCacheElement = false; + var enableTransitionTracing = false; + var enableLegacyHidden = false; + var enableDebugTracing = false; + var REACT_MODULE_REFERENCE; + { + REACT_MODULE_REFERENCE = Symbol.for("react.module.reference"); + } + function isValidElementType(type) { + if (typeof type === "string" || typeof type === "function") { + return true; + } + if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing) { + return true; + } + if (typeof type === "object" && type !== null) { + if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) { + return true; + } + } + return false; + } + function getWrappedName(outerType, innerType, wrapperName) { + var displayName = outerType.displayName; + if (displayName) { + return displayName; + } + var functionName = innerType.displayName || innerType.name || ""; + return functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName; + } + function getContextName(type) { + return type.displayName || "Context"; + } + function getComponentNameFromType(type) { + if (type == null) { + 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; + } + } + } + } + return null; + } + var assign = Object.assign; + 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) { + prevLog = console.log; + prevInfo = console.info; + prevWarn = console.warn; + prevError = console.error; + prevGroup = console.group; + prevGroupCollapsed = console.groupCollapsed; + prevGroupEnd = console.groupEnd; + var props = { + configurable: true, + enumerable: true, + value: disabledLog, + writable: true + }; + Object.defineProperties(console, { + info: props, + log: props, + warn: props, + error: props, + group: props, + groupCollapsed: props, + groupEnd: props + }); + } + disabledDepth++; + } + } + function reenableLogs() { + { + disabledDepth--; + if (disabledDepth === 0) { + var props = { + configurable: true, + enumerable: true, + writable: true + }; + 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 + }) + }); + } + 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) { + try { + throw Error(); + } catch (x) { + var match = x.stack.trim().match(/\n( *(at )?)/); + prefix = match && match[1] || ""; + } + } + return "\n" + prefix + name; + } + } + var reentry = false; + var componentFrameCache; + { + var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map; + componentFrameCache = new PossiblyWeakMap; + } + function describeNativeComponentFrame(fn, construct) { + if (!fn || reentry) { + return ""; + } + { + var frame = componentFrameCache.get(fn); + if (frame !== undefined) { + return frame; + } + } + var control; + reentry = true; + var previousPrepareStackTrace = Error.prepareStackTrace; + Error.prepareStackTrace = undefined; + var previousDispatcher; + { + previousDispatcher = ReactCurrentDispatcher.current; + ReactCurrentDispatcher.current = null; + disableLogs(); + } + try { + if (construct) { + var Fake = function() { + throw Error(); + }; + Object.defineProperty(Fake.prototype, "props", { + set: function() { + throw Error(); + } + }); + if (typeof Reflect === "object" && Reflect.construct) { + 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) { + if (sample && control && typeof sample.stack === "string") { + 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]) { + c--; + } + for (;s >= 1 && c >= 0; s--, c--) { + if (sampleLines[s] !== controlLines[c]) { + if (s !== 1 || c !== 1) { + do { + s--; + c--; + if (c < 0 || sampleLines[s] !== controlLines[c]) { + var _frame = "\n" + sampleLines[s].replace(" at new ", " at "); + if (fn.displayName && _frame.includes("<anonymous>")) { + _frame = _frame.replace("<anonymous>", fn.displayName); + } + { + if (typeof fn === "function") { + componentFrameCache.set(fn, _frame); + } + } + return _frame; + } + } while (s >= 1 && c >= 0); + } + break; + } + } + } + } finally { + reentry = false; + { + ReactCurrentDispatcher.current = previousDispatcher; + reenableLogs(); + } + Error.prepareStackTrace = previousPrepareStackTrace; + } + var name = fn ? fn.displayName || fn.name : ""; + var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ""; + { + if (typeof fn === "function") { + componentFrameCache.set(fn, syntheticFrame); + } + } + return syntheticFrame; + } + 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: + return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); + case REACT_LAZY_TYPE: { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + try { + 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) { + { + var has = Function.call.bind(hasOwnProperty); + for (var typeSpecName in typeSpecs) { + if (has(typeSpecs, typeSpecName)) { + var error$1 = undefined; + try { + if (typeof typeSpecs[typeSpecName] !== "function") { + 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)) { + loggedTypeFailures[error$1.message] = true; + setCurrentlyValidatingElement(element); + error("Failed %s type: %s", location, error$1.message); + setCurrentlyValidatingElement(null); + } + } + } + } + } + var isArrayImpl = Array.isArray; + function isArray(a) { + return isArrayImpl(a); + } + function typeName(value) { + { + var hasToStringTag = typeof Symbol === "function" && Symbol.toStringTag; + var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object"; + return type; + } + } + function willCoercionThrow(value) { + { + try { + testStringCoercion(value); + return false; + } catch (e) { + return true; + } + } + } + function testStringCoercion(value) { + 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); + } + } + } + var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner; + var RESERVED_PROPS = { + key: true, + ref: true, + __self: true, + __source: true + }; + var specialPropKeyWarningShown; + var specialPropRefWarningShown; + var didWarnAboutStringRefs; + { + didWarnAboutStringRefs = {}; + } + function hasValidRef(config) { + { + if (hasOwnProperty.call(config, "ref")) { + var getter = Object.getOwnPropertyDescriptor(config, "ref").get; + if (getter && getter.isReactWarning) { + return false; + } + } + } + return config.ref !== undefined; + } + function hasValidKey(config) { + { + if (hasOwnProperty.call(config, "key")) { + var getter = Object.getOwnPropertyDescriptor(config, "key").get; + if (getter && getter.isReactWarning) { + return false; + } + } + } + return config.key !== undefined; + } + function warnIfStringRefCannotBeAutoConverted(config, self2) { + { + if (typeof config.ref === "string" && ReactCurrentOwner.current && self2 && ReactCurrentOwner.current.stateNode !== self2) { + var componentName = getComponentNameFromType(ReactCurrentOwner.current.type); + if (!didWarnAboutStringRefs[componentName]) { + error('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. This case cannot be automatically converted to an arrow function. We ask you to manually fix this case by using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref', getComponentNameFromType(ReactCurrentOwner.current.type), config.ref); + didWarnAboutStringRefs[componentName] = true; + } + } + } + } + function defineKeyPropWarningGetter(props, displayName) { + { + var warnAboutAccessingKey = function() { + if (!specialPropKeyWarningShown) { + specialPropKeyWarningShown = true; + error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName); + } + }; + warnAboutAccessingKey.isReactWarning = true; + Object.defineProperty(props, "key", { + get: warnAboutAccessingKey, + configurable: true + }); + } + } + function defineRefPropWarningGetter(props, displayName) { + { + var warnAboutAccessingRef = function() { + if (!specialPropRefWarningShown) { + specialPropRefWarningShown = true; + error("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName); + } + }; + warnAboutAccessingRef.isReactWarning = true; + Object.defineProperty(props, "ref", { + get: warnAboutAccessingRef, + configurable: true + }); + } + } + var ReactElement = function(type, key, ref, self2, source, owner, props) { + var element = { + $$typeof: REACT_ELEMENT_TYPE, + type, + key, + ref, + props, + _owner: owner + }; + { + element._store = {}; + Object.defineProperty(element._store, "validated", { + configurable: false, + enumerable: false, + writable: true, + value: false + }); + Object.defineProperty(element, "_self", { + configurable: false, + enumerable: false, + writable: false, + value: self2 + }); + Object.defineProperty(element, "_source", { + configurable: false, + enumerable: false, + writable: false, + value: source + }); + if (Object.freeze) { + Object.freeze(element.props); + Object.freeze(element); + } + } + return element; + }; + function jsxDEV(type, config, maybeKey, source, self2) { + { + var propName; + var props = {}; + var key = null; + var ref = null; + if (maybeKey !== undefined) { + { + checkKeyStringCoercion(maybeKey); + } + key = "" + maybeKey; + } + if (hasValidKey(config)) { + { + checkKeyStringCoercion(config.key); + } + key = "" + config.key; + } + if (hasValidRef(config)) { + ref = config.ref; + warnIfStringRefCannotBeAutoConverted(config, self2); + } + for (propName in config) { + if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { + props[propName] = config[propName]; + } + } + if (type && type.defaultProps) { + var defaultProps = type.defaultProps; + for (propName in defaultProps) { + if (props[propName] === undefined) { + props[propName] = defaultProps[propName]; + } + } + } + if (key || ref) { + var displayName = typeof type === "function" ? type.displayName || type.name || "Unknown" : type; + if (key) { + defineKeyPropWarningGetter(props, displayName); + } + if (ref) { + defineRefPropWarningGetter(props, displayName); + } + } + return ReactElement(type, key, ref, self2, source, ReactCurrentOwner.current, props); + } + } + var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner; + var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; + function setCurrentlyValidatingElement$1(element) { + { + if (element) { + var owner = element._owner; + var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); + ReactDebugCurrentFrame$1.setExtraStackFrame(stack); + } else { + ReactDebugCurrentFrame$1.setExtraStackFrame(null); + } + } + } + var propTypesMisspellWarningShown; + { + propTypesMisspellWarningShown = false; + } + function isValidElement(object) { + { + return typeof object === "object" && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; + } + } + function getDeclarationErrorAddendum() { + { + if (ReactCurrentOwner$1.current) { + var name = getComponentNameFromType(ReactCurrentOwner$1.current.type); + if (name) { + return "\n\nCheck the render method of `" + name + "`."; + } + } + return ""; + } + } + function getSourceInfoErrorAddendum(source) { + { + if (source !== undefined) { + var fileName = source.fileName.replace(/^.*[\\\/]/, ""); + var lineNumber = source.lineNumber; + return "\n\nCheck your code at " + fileName + ":" + lineNumber + "."; + } + return ""; + } + } + var ownerHasKeyUseWarning = {}; + function getCurrentComponentErrorInfo(parentType) { + { + var info = getDeclarationErrorAddendum(); + if (!info) { + var parentName = typeof parentType === "string" ? parentType : parentType.displayName || parentType.name; + if (parentName) { + info = "\n\nCheck the top-level render call using <" + parentName + ">."; + } + } + return info; + } + } + function validateExplicitKey(element, parentType) { + { + if (!element._store || element._store.validated || element.key != null) { + return; + } + element._store.validated = true; + var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); + if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { + return; + } + ownerHasKeyUseWarning[currentComponentErrorInfo] = true; + var childOwner = ""; + if (element && element._owner && element._owner !== ReactCurrentOwner$1.current) { + childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + "."; + } + setCurrentlyValidatingElement$1(element); + error('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner); + setCurrentlyValidatingElement$1(null); + } + } + function validateChildKeys(node, parentType) { + { + if (typeof node !== "object") { + return; + } + if (isArray(node)) { + for (var i = 0;i < node.length; i++) { + var child = node[i]; + if (isValidElement(child)) { + validateExplicitKey(child, parentType); + } + } + } else if (isValidElement(node)) { + if (node._store) { + node._store.validated = true; + } + } else if (node) { + var iteratorFn = getIteratorFn(node); + if (typeof iteratorFn === "function") { + if (iteratorFn !== node.entries) { + var iterator = iteratorFn.call(node); + var step; + while (!(step = iterator.next()).done) { + if (isValidElement(step.value)) { + validateExplicitKey(step.value, parentType); + } + } + } + } + } + } + } + function validatePropTypes(element) { + { + var type = element.type; + if (type === null || type === undefined || typeof type === "string") { + return; + } + var propTypes; + if (typeof type === "function") { + propTypes = type.propTypes; + } else if (typeof type === "object" && (type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_MEMO_TYPE)) { + propTypes = type.propTypes; + } else { + return; + } + if (propTypes) { + var name = getComponentNameFromType(type); + checkPropTypes(propTypes, element.props, "prop", name, element); + } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) { + propTypesMisspellWarningShown = true; + var _name = getComponentNameFromType(type); + error("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?", _name || "Unknown"); + } + if (typeof type.getDefaultProps === "function" && !type.getDefaultProps.isReactClassApproved) { + error("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead."); + } + } + } + function validateFragmentProps(fragment) { + { + var keys = Object.keys(fragment.props); + for (var i = 0;i < keys.length; i++) { + var key = keys[i]; + if (key !== "children" && key !== "key") { + setCurrentlyValidatingElement$1(fragment); + error("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.", key); + setCurrentlyValidatingElement$1(null); + break; + } + } + if (fragment.ref !== null) { + setCurrentlyValidatingElement$1(fragment); + error("Invalid attribute `ref` supplied to `React.Fragment`."); + setCurrentlyValidatingElement$1(null); + } + } + } + var didWarnAboutKeySpread = {}; + function jsxWithValidation(type, props, key, isStaticChildren, source, self2) { + { + var validType = isValidElementType(type); + if (!validType) { + 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 sourceInfo = getSourceInfoErrorAddendum(source); + if (sourceInfo) { + info += sourceInfo; + } else { + info += getDeclarationErrorAddendum(); + } + var typeString; + if (type === null) { + typeString = "null"; + } else if (isArray(type)) { + typeString = "array"; + } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) { + typeString = "<" + (getComponentNameFromType(type.type) || "Unknown") + " />"; + info = " Did you accidentally export a JSX literal instead of a component?"; + } else { + typeString = typeof type; + } + error("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s", typeString, info); + } + var element = jsxDEV(type, props, key, source, self2); + if (element == null) { + return element; + } + if (validType) { + var children = props.children; + if (children !== undefined) { + if (isStaticChildren) { + if (isArray(children)) { + for (var i = 0;i < children.length; i++) { + validateChildKeys(children[i], type); + } + if (Object.freeze) { + Object.freeze(children); + } + } else { + error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead."); + } + } else { + validateChildKeys(children, type); + } + } + } + { + if (hasOwnProperty.call(props, "key")) { + var componentName = getComponentNameFromType(type); + var keys = Object.keys(props).filter(function(k) { + return k !== "key"; + }); + var beforeExample = keys.length > 0 ? "{key: someKey, " + keys.join(": ..., ") + ": ...}" : "{key: someKey}"; + if (!didWarnAboutKeySpread[componentName + beforeExample]) { + var afterExample = keys.length > 0 ? "{" + keys.join(": ..., ") + ": ...}" : "{}"; + error('A props object containing a "key" prop is being spread into JSX:\n let props = %s;\n <%s {...props} />\nReact keys must be passed directly to JSX without using spread:\n let props = %s;\n <%s key={someKey} {...props} />', beforeExample, componentName, afterExample, componentName); + didWarnAboutKeySpread[componentName + beforeExample] = true; + } + } + } + if (type === REACT_FRAGMENT_TYPE) { + validateFragmentProps(element); + } else { + validatePropTypes(element); + } + return element; + } + } + var jsxDEV$1 = jsxWithValidation; + exports.Fragment = REACT_FRAGMENT_TYPE; + exports.jsxDEV = jsxDEV$1; + })(); + } +}); + +// node_modules/react/jsx-dev-runtime.js +var require_jsx_dev_runtime = __commonJS((exports, module) => { + var react_jsx_dev_runtime_development = __toESM(require_react_jsx_dev_runtime_development(), 1); + if (false) { + } else { + module.exports = react_jsx_dev_runtime_development; + } +}); + +// node_modules/lodash.throttle/index.js +var require_lodash = __commonJS((exports, module) => { + var debounce = function(func, wait, options) { + var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true; + if (typeof func != "function") { + throw new TypeError(FUNC_ERROR_TEXT); + } + wait = toNumber(wait) || 0; + if (isObject(options)) { + leading = !!options.leading; + maxing = "maxWait" in options; + maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; + trailing = "trailing" in options ? !!options.trailing : trailing; + } + function invokeFunc(time) { + var args = lastArgs, thisArg = lastThis; + lastArgs = lastThis = undefined; + lastInvokeTime = time; + result = func.apply(thisArg, args); + return result; + } + function leadingEdge(time) { + lastInvokeTime = time; + timerId = setTimeout(timerExpired, wait); + return leading ? invokeFunc(time) : result; + } + function remainingWait(time) { + var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, result2 = wait - timeSinceLastCall; + return maxing ? nativeMin(result2, maxWait - timeSinceLastInvoke) : result2; + } + function shouldInvoke(time) { + var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime; + return lastCallTime === undefined || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait; + } + function timerExpired() { + var time = now(); + if (shouldInvoke(time)) { + return trailingEdge(time); + } + timerId = setTimeout(timerExpired, remainingWait(time)); + } + function trailingEdge(time) { + timerId = undefined; + if (trailing && lastArgs) { + return invokeFunc(time); + } + lastArgs = lastThis = undefined; + return result; + } + function cancel() { + if (timerId !== undefined) { + clearTimeout(timerId); + } + lastInvokeTime = 0; + lastArgs = lastCallTime = lastThis = timerId = undefined; + } + function flush() { + return timerId === undefined ? result : trailingEdge(now()); + } + function debounced() { + var time = now(), isInvoking = shouldInvoke(time); + lastArgs = arguments; + lastThis = this; + lastCallTime = time; + if (isInvoking) { + if (timerId === undefined) { + return leadingEdge(lastCallTime); + } + if (maxing) { + timerId = setTimeout(timerExpired, wait); + return invokeFunc(lastCallTime); + } + } + if (timerId === undefined) { + timerId = setTimeout(timerExpired, wait); + } + return result; + } + debounced.cancel = cancel; + debounced.flush = flush; + return debounced; + }; + var throttle = function(func, wait, options) { + var leading = true, trailing = true; + if (typeof func != "function") { + throw new TypeError(FUNC_ERROR_TEXT); + } + if (isObject(options)) { + leading = "leading" in options ? !!options.leading : leading; + trailing = "trailing" in options ? !!options.trailing : trailing; + } + return debounce(func, wait, { + leading, + maxWait: wait, + trailing + }); + }; + var isObject = function(value) { + var type = typeof value; + return !!value && (type == "object" || type == "function"); + }; + var isObjectLike = function(value) { + return !!value && typeof value == "object"; + }; + var isSymbol = function(value) { + return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag; + }; + var toNumber = function(value) { + if (typeof value == "number") { + return value; + } + if (isSymbol(value)) { + return NAN; + } + if (isObject(value)) { + var other = typeof value.valueOf == "function" ? value.valueOf() : value; + value = isObject(other) ? other + "" : other; + } + if (typeof value != "string") { + return value === 0 ? value : +value; + } + value = value.replace(reTrim, ""); + var isBinary = reIsBinary.test(value); + return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value; + }; + var FUNC_ERROR_TEXT = "Expected a function"; + var NAN = 0 / 0; + var symbolTag = "[object Symbol]"; + var reTrim = /^\s+|\s+$/g; + var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + var reIsBinary = /^0b[01]+$/i; + var reIsOctal = /^0o[0-7]+$/i; + var freeParseInt = parseInt; + var freeGlobal = typeof global == "object" && global && global.Object === Object && global; + var freeSelf = typeof self == "object" && self && self.Object === Object && self; + var root = freeGlobal || freeSelf || Function("return this")(); + var objectProto = Object.prototype; + var objectToString = objectProto.toString; + var nativeMax = Math.max; + var nativeMin = Math.min; + var now = function() { + return root.Date.now(); + }; + module.exports = throttle; +}); + +// src/index.tsx +var client = __toESM(require_client(), 1); + +// src/app.tsx +var import_react7 = __toESM(require_react(), 1); + +// src/components/ui/alert.tsx +var React = __toESM(require_react(), 1); + +// node_modules/class-variance-authority/node_modules/clsx/dist/clsx.mjs +var r = function(e) { + var t, f, n = ""; + if (typeof e == "string" || typeof e == "number") + n += e; + else if (typeof e == "object") + if (Array.isArray(e)) + for (t = 0;t < e.length; t++) + e[t] && (f = r(e[t])) && (n && (n += " "), n += f); + else + for (t in e) + e[t] && (n && (n += " "), n += t); + return n; +}; +function clsx() { + for (var e, t, f = 0, n = "";f < arguments.length; ) + (e = arguments[f++]) && (t = r(e)) && (n && (n += " "), n += t); + return n; +} + +// node_modules/class-variance-authority/dist/index.mjs +var falsyToString = (value) => typeof value === "boolean" ? "".concat(value) : value === 0 ? "0" : value; +var cx = clsx; +var cva = (base, config) => { + return (props) => { + var ref; + if ((config === null || config === undefined ? undefined : config.variants) == null) + return cx(base, props === null || props === undefined ? undefined : props.class, props === null || props === undefined ? undefined : props.className); + const { variants, defaultVariants } = config; + const getVariantClassNames = Object.keys(variants).map((variant) => { + const variantProp = props === null || props === undefined ? undefined : props[variant]; + const defaultVariantProp = defaultVariants === null || defaultVariants === undefined ? undefined : defaultVariants[variant]; + if (variantProp === null) + return null; + const variantKey = falsyToString(variantProp) || falsyToString(defaultVariantProp); + return variants[variant][variantKey]; + }); + const propsWithoutUndefined = props && Object.entries(props).reduce((acc, param) => { + let [key, value] = param; + if (value === undefined) { + return acc; + } + acc[key] = value; + return acc; + }, {}); + const getCompoundVariantClassNames = config === null || config === undefined ? undefined : (ref = config.compoundVariants) === null || ref === undefined ? undefined : ref.reduce((acc, param1) => { + let { class: cvClass, className: cvClassName, ...compoundVariantOptions } = param1; + return Object.entries(compoundVariantOptions).every((param) => { + let [key, value] = param; + return Array.isArray(value) ? value.includes({ + ...defaultVariants, + ...propsWithoutUndefined + }[key]) : { + ...defaultVariants, + ...propsWithoutUndefined + }[key] === value; + }) ? [ + ...acc, + cvClass, + cvClassName + ] : acc; + }, []); + return cx(base, getVariantClassNames, getCompoundVariantClassNames, props === null || props === undefined ? undefined : props.class, props === null || props === undefined ? undefined : props.className); + }; +}; + +// node_modules/clsx/dist/clsx.mjs +var r2 = function(e) { + var t, f, n = ""; + if (typeof e == "string" || typeof e == "number") + n += e; + else if (typeof e == "object") + if (Array.isArray(e)) { + var o = e.length; + for (t = 0;t < o; t++) + e[t] && (f = r2(e[t])) && (n && (n += " "), n += f); + } else + for (f in e) + e[f] && (n && (n += " "), n += f); + return n; +}; +function clsx2() { + for (var e, t, f = 0, n = "", o = arguments.length;f < o; f++) + (e = arguments[f]) && (t = r2(e)) && (n && (n += " "), n += t); + return n; +} + +// node_modules/tailwind-merge/dist/bundle-mjs.mjs +var twJoin = function() { + let index = 0; + let argument; + let resolvedValue; + let string = ""; + while (index < arguments.length) { + if (argument = arguments[index++]) { + if (resolvedValue = toValue(argument)) { + string && (string += " "); + string += resolvedValue; + } + } + } + return string; +}; +var createTailwindMerge = function(createConfigFirst, ...createConfigRest) { + let configUtils; + let cacheGet; + let cacheSet; + let functionToCall = initTailwindMerge; + function initTailwindMerge(classList) { + const config = createConfigRest.reduce((previousConfig, createConfigCurrent) => createConfigCurrent(previousConfig), createConfigFirst()); + configUtils = createConfigUtils(config); + cacheGet = configUtils.cache.get; + cacheSet = configUtils.cache.set; + functionToCall = tailwindMerge; + return tailwindMerge(classList); + } + function tailwindMerge(classList) { + const cachedResult = cacheGet(classList); + if (cachedResult) { + return cachedResult; + } + const result = mergeClassList(classList, configUtils); + cacheSet(classList, result); + return result; + } + return function callTailwindMerge() { + return functionToCall(twJoin.apply(null, arguments)); + }; +}; +var CLASS_PART_SEPARATOR = "-"; +var createClassGroupUtils = (config) => { + const classMap = createClassMap(config); + const { + conflictingClassGroups, + conflictingClassGroupModifiers + } = config; + const getClassGroupId = (className) => { + const classParts = className.split(CLASS_PART_SEPARATOR); + if (classParts[0] === "" && classParts.length !== 1) { + classParts.shift(); + } + return getGroupRecursive(classParts, classMap) || getGroupIdForArbitraryProperty(className); + }; + const getConflictingClassGroupIds = (classGroupId, hasPostfixModifier) => { + const conflicts = conflictingClassGroups[classGroupId] || []; + if (hasPostfixModifier && conflictingClassGroupModifiers[classGroupId]) { + return [...conflicts, ...conflictingClassGroupModifiers[classGroupId]]; + } + return conflicts; + }; + return { + getClassGroupId, + getConflictingClassGroupIds + }; +}; +var getGroupRecursive = (classParts, classPartObject) => { + if (classParts.length === 0) { + return classPartObject.classGroupId; + } + const currentClassPart = classParts[0]; + const nextClassPartObject = classPartObject.nextPart.get(currentClassPart); + const classGroupFromNextClassPart = nextClassPartObject ? getGroupRecursive(classParts.slice(1), nextClassPartObject) : undefined; + if (classGroupFromNextClassPart) { + return classGroupFromNextClassPart; + } + if (classPartObject.validators.length === 0) { + return; + } + const classRest = classParts.join(CLASS_PART_SEPARATOR); + return classPartObject.validators.find(({ + validator + }) => validator(classRest))?.classGroupId; +}; +var arbitraryPropertyRegex = /^\[(.+)\]$/; +var getGroupIdForArbitraryProperty = (className) => { + if (arbitraryPropertyRegex.test(className)) { + const arbitraryPropertyClassName = arbitraryPropertyRegex.exec(className)[1]; + const property = arbitraryPropertyClassName?.substring(0, arbitraryPropertyClassName.indexOf(":")); + if (property) { + return "arbitrary.." + property; + } + } +}; +var createClassMap = (config) => { + const { + theme, + prefix + } = config; + const classMap = { + nextPart: new Map, + validators: [] + }; + const prefixedClassGroupEntries = getPrefixedClassGroupEntries(Object.entries(config.classGroups), prefix); + prefixedClassGroupEntries.forEach(([classGroupId, classGroup]) => { + processClassesRecursively(classGroup, classMap, classGroupId, theme); + }); + return classMap; +}; +var processClassesRecursively = (classGroup, classPartObject, classGroupId, theme) => { + classGroup.forEach((classDefinition) => { + if (typeof classDefinition === "string") { + const classPartObjectToEdit = classDefinition === "" ? classPartObject : getPart(classPartObject, classDefinition); + classPartObjectToEdit.classGroupId = classGroupId; + return; + } + if (typeof classDefinition === "function") { + if (isThemeGetter(classDefinition)) { + processClassesRecursively(classDefinition(theme), classPartObject, classGroupId, theme); + return; + } + classPartObject.validators.push({ + validator: classDefinition, + classGroupId + }); + return; + } + Object.entries(classDefinition).forEach(([key, classGroup2]) => { + processClassesRecursively(classGroup2, getPart(classPartObject, key), classGroupId, theme); + }); + }); +}; +var getPart = (classPartObject, path) => { + let currentClassPartObject = classPartObject; + path.split(CLASS_PART_SEPARATOR).forEach((pathPart) => { + if (!currentClassPartObject.nextPart.has(pathPart)) { + currentClassPartObject.nextPart.set(pathPart, { + nextPart: new Map, + validators: [] + }); + } + currentClassPartObject = currentClassPartObject.nextPart.get(pathPart); + }); + return currentClassPartObject; +}; +var isThemeGetter = (func) => func.isThemeGetter; +var getPrefixedClassGroupEntries = (classGroupEntries, prefix) => { + if (!prefix) { + return classGroupEntries; + } + return classGroupEntries.map(([classGroupId, classGroup]) => { + const prefixedClassGroup = classGroup.map((classDefinition) => { + if (typeof classDefinition === "string") { + return prefix + classDefinition; + } + if (typeof classDefinition === "object") { + return Object.fromEntries(Object.entries(classDefinition).map(([key, value]) => [prefix + key, value])); + } + return classDefinition; + }); + return [classGroupId, prefixedClassGroup]; + }); +}; +var createLruCache = (maxCacheSize) => { + if (maxCacheSize < 1) { + return { + get: () => { + return; + }, + set: () => { + } + }; + } + let cacheSize = 0; + let cache = new Map; + let previousCache = new Map; + const update = (key, value) => { + cache.set(key, value); + cacheSize++; + if (cacheSize > maxCacheSize) { + cacheSize = 0; + previousCache = cache; + cache = new Map; + } + }; + return { + get(key) { + let value = cache.get(key); + if (value !== undefined) { + return value; + } + if ((value = previousCache.get(key)) !== undefined) { + update(key, value); + return value; + } + }, + set(key, value) { + if (cache.has(key)) { + cache.set(key, value); + } else { + update(key, value); + } + } + }; +}; +var IMPORTANT_MODIFIER = "!"; +var createParseClassName = (config) => { + const { + separator, + experimentalParseClassName + } = config; + const isSeparatorSingleCharacter = separator.length === 1; + const firstSeparatorCharacter = separator[0]; + const separatorLength = separator.length; + const parseClassName = (className) => { + const modifiers = []; + let bracketDepth = 0; + let modifierStart = 0; + let postfixModifierPosition; + for (let index = 0;index < className.length; index++) { + let currentCharacter = className[index]; + if (bracketDepth === 0) { + if (currentCharacter === firstSeparatorCharacter && (isSeparatorSingleCharacter || className.slice(index, index + separatorLength) === separator)) { + modifiers.push(className.slice(modifierStart, index)); + modifierStart = index + separatorLength; + continue; + } + if (currentCharacter === "/") { + postfixModifierPosition = index; + continue; + } + } + if (currentCharacter === "[") { + bracketDepth++; + } else if (currentCharacter === "]") { + bracketDepth--; + } + } + const baseClassNameWithImportantModifier = modifiers.length === 0 ? className : className.substring(modifierStart); + const hasImportantModifier = baseClassNameWithImportantModifier.startsWith(IMPORTANT_MODIFIER); + const baseClassName = hasImportantModifier ? baseClassNameWithImportantModifier.substring(1) : baseClassNameWithImportantModifier; + const maybePostfixModifierPosition = postfixModifierPosition && postfixModifierPosition > modifierStart ? postfixModifierPosition - modifierStart : undefined; + return { + modifiers, + hasImportantModifier, + baseClassName, + maybePostfixModifierPosition + }; + }; + if (experimentalParseClassName) { + return (className) => experimentalParseClassName({ + className, + parseClassName + }); + } + return parseClassName; +}; +var sortModifiers = (modifiers) => { + if (modifiers.length <= 1) { + return modifiers; + } + const sortedModifiers = []; + let unsortedModifiers = []; + modifiers.forEach((modifier) => { + const isArbitraryVariant = modifier[0] === "["; + if (isArbitraryVariant) { + sortedModifiers.push(...unsortedModifiers.sort(), modifier); + unsortedModifiers = []; + } else { + unsortedModifiers.push(modifier); + } + }); + sortedModifiers.push(...unsortedModifiers.sort()); + return sortedModifiers; +}; +var createConfigUtils = (config) => ({ + cache: createLruCache(config.cacheSize), + parseClassName: createParseClassName(config), + ...createClassGroupUtils(config) +}); +var SPLIT_CLASSES_REGEX = /\s+/; +var mergeClassList = (classList, configUtils) => { + const { + parseClassName, + getClassGroupId, + getConflictingClassGroupIds + } = configUtils; + const classGroupsInConflict = []; + const classNames = classList.trim().split(SPLIT_CLASSES_REGEX); + let result = ""; + for (let index = classNames.length - 1;index >= 0; index -= 1) { + const originalClassName = classNames[index]; + const { + modifiers, + hasImportantModifier, + baseClassName, + maybePostfixModifierPosition + } = parseClassName(originalClassName); + let hasPostfixModifier = Boolean(maybePostfixModifierPosition); + let classGroupId = getClassGroupId(hasPostfixModifier ? baseClassName.substring(0, maybePostfixModifierPosition) : baseClassName); + if (!classGroupId) { + if (!hasPostfixModifier) { + result = originalClassName + (result.length > 0 ? " " + result : result); + continue; + } + classGroupId = getClassGroupId(baseClassName); + if (!classGroupId) { + result = originalClassName + (result.length > 0 ? " " + result : result); + continue; + } + hasPostfixModifier = false; + } + const variantModifier = sortModifiers(modifiers).join(":"); + const modifierId = hasImportantModifier ? variantModifier + IMPORTANT_MODIFIER : variantModifier; + const classId = modifierId + classGroupId; + if (classGroupsInConflict.includes(classId)) { + continue; + } + classGroupsInConflict.push(classId); + const conflictGroups = getConflictingClassGroupIds(classGroupId, hasPostfixModifier); + for (let i = 0;i < conflictGroups.length; ++i) { + const group = conflictGroups[i]; + classGroupsInConflict.push(modifierId + group); + } + result = originalClassName + (result.length > 0 ? " " + result : result); + } + return result; +}; +var toValue = (mix) => { + if (typeof mix === "string") { + return mix; + } + let resolvedValue; + let string = ""; + for (let k = 0;k < mix.length; k++) { + if (mix[k]) { + if (resolvedValue = toValue(mix[k])) { + string && (string += " "); + string += resolvedValue; + } + } + } + return string; +}; +var fromTheme = (key) => { + const themeGetter = (theme) => theme[key] || []; + themeGetter.isThemeGetter = true; + return themeGetter; +}; +var arbitraryValueRegex = /^\[(?:([a-z-]+):)?(.+)\]$/i; +var fractionRegex = /^\d+\/\d+$/; +var stringLengths = new Set(["px", "full", "screen"]); +var tshirtUnitRegex = /^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/; +var lengthUnitRegex = /\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/; +var colorFunctionRegex = /^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/; +var shadowRegex = /^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/; +var imageRegex = /^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/; +var isLength = (value) => isNumber(value) || stringLengths.has(value) || fractionRegex.test(value); +var isArbitraryLength = (value) => getIsArbitraryValue(value, "length", isLengthOnly); +var isNumber = (value) => Boolean(value) && !Number.isNaN(Number(value)); +var isArbitraryNumber = (value) => getIsArbitraryValue(value, "number", isNumber); +var isInteger = (value) => Boolean(value) && Number.isInteger(Number(value)); +var isPercent = (value) => value.endsWith("%") && isNumber(value.slice(0, -1)); +var isArbitraryValue = (value) => arbitraryValueRegex.test(value); +var isTshirtSize = (value) => tshirtUnitRegex.test(value); +var sizeLabels = new Set(["length", "size", "percentage"]); +var isArbitrarySize = (value) => getIsArbitraryValue(value, sizeLabels, isNever); +var isArbitraryPosition = (value) => getIsArbitraryValue(value, "position", isNever); +var imageLabels = new Set(["image", "url"]); +var isArbitraryImage = (value) => getIsArbitraryValue(value, imageLabels, isImage); +var isArbitraryShadow = (value) => getIsArbitraryValue(value, "", isShadow); +var isAny = () => true; +var getIsArbitraryValue = (value, label, testValue) => { + const result = arbitraryValueRegex.exec(value); + if (result) { + if (result[1]) { + return typeof label === "string" ? result[1] === label : label.has(result[1]); + } + return testValue(result[2]); + } + return false; +}; +var isLengthOnly = (value) => lengthUnitRegex.test(value) && !colorFunctionRegex.test(value); +var isNever = () => false; +var isShadow = (value) => shadowRegex.test(value); +var isImage = (value) => imageRegex.test(value); +var getDefaultConfig = () => { + const colors = fromTheme("colors"); + const spacing = fromTheme("spacing"); + const blur = fromTheme("blur"); + const brightness = fromTheme("brightness"); + const borderColor = fromTheme("borderColor"); + const borderRadius = fromTheme("borderRadius"); + const borderSpacing = fromTheme("borderSpacing"); + const borderWidth = fromTheme("borderWidth"); + const contrast = fromTheme("contrast"); + const grayscale = fromTheme("grayscale"); + const hueRotate = fromTheme("hueRotate"); + const invert = fromTheme("invert"); + const gap = fromTheme("gap"); + const gradientColorStops = fromTheme("gradientColorStops"); + const gradientColorStopPositions = fromTheme("gradientColorStopPositions"); + const inset = fromTheme("inset"); + const margin = fromTheme("margin"); + const opacity = fromTheme("opacity"); + const padding = fromTheme("padding"); + const saturate = fromTheme("saturate"); + const scale = fromTheme("scale"); + const sepia = fromTheme("sepia"); + const skew = fromTheme("skew"); + const space = fromTheme("space"); + const translate = fromTheme("translate"); + const getOverscroll = () => ["auto", "contain", "none"]; + const getOverflow = () => ["auto", "hidden", "clip", "visible", "scroll"]; + const getSpacingWithAutoAndArbitrary = () => ["auto", isArbitraryValue, spacing]; + const getSpacingWithArbitrary = () => [isArbitraryValue, spacing]; + const getLengthWithEmptyAndArbitrary = () => ["", isLength, isArbitraryLength]; + const getNumberWithAutoAndArbitrary = () => ["auto", isNumber, isArbitraryValue]; + const getPositions = () => ["bottom", "center", "left", "left-bottom", "left-top", "right", "right-bottom", "right-top", "top"]; + const getLineStyles = () => ["solid", "dashed", "dotted", "double", "none"]; + const getBlendModes = () => ["normal", "multiply", "screen", "overlay", "darken", "lighten", "color-dodge", "color-burn", "hard-light", "soft-light", "difference", "exclusion", "hue", "saturation", "color", "luminosity"]; + const getAlign = () => ["start", "end", "center", "between", "around", "evenly", "stretch"]; + const getZeroAndEmpty = () => ["", "0", isArbitraryValue]; + const getBreaks = () => ["auto", "avoid", "all", "avoid-page", "page", "left", "right", "column"]; + const getNumberAndArbitrary = () => [isNumber, isArbitraryValue]; + return { + cacheSize: 500, + separator: ":", + theme: { + colors: [isAny], + spacing: [isLength, isArbitraryLength], + blur: ["none", "", isTshirtSize, isArbitraryValue], + brightness: getNumberAndArbitrary(), + borderColor: [colors], + borderRadius: ["none", "", "full", isTshirtSize, isArbitraryValue], + borderSpacing: getSpacingWithArbitrary(), + borderWidth: getLengthWithEmptyAndArbitrary(), + contrast: getNumberAndArbitrary(), + grayscale: getZeroAndEmpty(), + hueRotate: getNumberAndArbitrary(), + invert: getZeroAndEmpty(), + gap: getSpacingWithArbitrary(), + gradientColorStops: [colors], + gradientColorStopPositions: [isPercent, isArbitraryLength], + inset: getSpacingWithAutoAndArbitrary(), + margin: getSpacingWithAutoAndArbitrary(), + opacity: getNumberAndArbitrary(), + padding: getSpacingWithArbitrary(), + saturate: getNumberAndArbitrary(), + scale: getNumberAndArbitrary(), + sepia: getZeroAndEmpty(), + skew: getNumberAndArbitrary(), + space: getSpacingWithArbitrary(), + translate: getSpacingWithArbitrary() + }, + classGroups: { + aspect: [{ + aspect: ["auto", "square", "video", isArbitraryValue] + }], + container: ["container"], + columns: [{ + columns: [isTshirtSize] + }], + "break-after": [{ + "break-after": getBreaks() + }], + "break-before": [{ + "break-before": getBreaks() + }], + "break-inside": [{ + "break-inside": ["auto", "avoid", "avoid-page", "avoid-column"] + }], + "box-decoration": [{ + "box-decoration": ["slice", "clone"] + }], + box: [{ + box: ["border", "content"] + }], + display: ["block", "inline-block", "inline", "flex", "inline-flex", "table", "inline-table", "table-caption", "table-cell", "table-column", "table-column-group", "table-footer-group", "table-header-group", "table-row-group", "table-row", "flow-root", "grid", "inline-grid", "contents", "list-item", "hidden"], + float: [{ + float: ["right", "left", "none", "start", "end"] + }], + clear: [{ + clear: ["left", "right", "both", "none", "start", "end"] + }], + isolation: ["isolate", "isolation-auto"], + "object-fit": [{ + object: ["contain", "cover", "fill", "none", "scale-down"] + }], + "object-position": [{ + object: [...getPositions(), isArbitraryValue] + }], + overflow: [{ + overflow: getOverflow() + }], + "overflow-x": [{ + "overflow-x": getOverflow() + }], + "overflow-y": [{ + "overflow-y": getOverflow() + }], + overscroll: [{ + overscroll: getOverscroll() + }], + "overscroll-x": [{ + "overscroll-x": getOverscroll() + }], + "overscroll-y": [{ + "overscroll-y": getOverscroll() + }], + position: ["static", "fixed", "absolute", "relative", "sticky"], + inset: [{ + inset: [inset] + }], + "inset-x": [{ + "inset-x": [inset] + }], + "inset-y": [{ + "inset-y": [inset] + }], + start: [{ + start: [inset] + }], + end: [{ + end: [inset] + }], + top: [{ + top: [inset] + }], + right: [{ + right: [inset] + }], + bottom: [{ + bottom: [inset] + }], + left: [{ + left: [inset] + }], + visibility: ["visible", "invisible", "collapse"], + z: [{ + z: ["auto", isInteger, isArbitraryValue] + }], + basis: [{ + basis: getSpacingWithAutoAndArbitrary() + }], + "flex-direction": [{ + flex: ["row", "row-reverse", "col", "col-reverse"] + }], + "flex-wrap": [{ + flex: ["wrap", "wrap-reverse", "nowrap"] + }], + flex: [{ + flex: ["1", "auto", "initial", "none", isArbitraryValue] + }], + grow: [{ + grow: getZeroAndEmpty() + }], + shrink: [{ + shrink: getZeroAndEmpty() + }], + order: [{ + order: ["first", "last", "none", isInteger, isArbitraryValue] + }], + "grid-cols": [{ + "grid-cols": [isAny] + }], + "col-start-end": [{ + col: ["auto", { + span: ["full", isInteger, isArbitraryValue] + }, isArbitraryValue] + }], + "col-start": [{ + "col-start": getNumberWithAutoAndArbitrary() + }], + "col-end": [{ + "col-end": getNumberWithAutoAndArbitrary() + }], + "grid-rows": [{ + "grid-rows": [isAny] + }], + "row-start-end": [{ + row: ["auto", { + span: [isInteger, isArbitraryValue] + }, isArbitraryValue] + }], + "row-start": [{ + "row-start": getNumberWithAutoAndArbitrary() + }], + "row-end": [{ + "row-end": getNumberWithAutoAndArbitrary() + }], + "grid-flow": [{ + "grid-flow": ["row", "col", "dense", "row-dense", "col-dense"] + }], + "auto-cols": [{ + "auto-cols": ["auto", "min", "max", "fr", isArbitraryValue] + }], + "auto-rows": [{ + "auto-rows": ["auto", "min", "max", "fr", isArbitraryValue] + }], + gap: [{ + gap: [gap] + }], + "gap-x": [{ + "gap-x": [gap] + }], + "gap-y": [{ + "gap-y": [gap] + }], + "justify-content": [{ + justify: ["normal", ...getAlign()] + }], + "justify-items": [{ + "justify-items": ["start", "end", "center", "stretch"] + }], + "justify-self": [{ + "justify-self": ["auto", "start", "end", "center", "stretch"] + }], + "align-content": [{ + content: ["normal", ...getAlign(), "baseline"] + }], + "align-items": [{ + items: ["start", "end", "center", "baseline", "stretch"] + }], + "align-self": [{ + self: ["auto", "start", "end", "center", "stretch", "baseline"] + }], + "place-content": [{ + "place-content": [...getAlign(), "baseline"] + }], + "place-items": [{ + "place-items": ["start", "end", "center", "baseline", "stretch"] + }], + "place-self": [{ + "place-self": ["auto", "start", "end", "center", "stretch"] + }], + p: [{ + p: [padding] + }], + px: [{ + px: [padding] + }], + py: [{ + py: [padding] + }], + ps: [{ + ps: [padding] + }], + pe: [{ + pe: [padding] + }], + pt: [{ + pt: [padding] + }], + pr: [{ + pr: [padding] + }], + pb: [{ + pb: [padding] + }], + pl: [{ + pl: [padding] + }], + m: [{ + m: [margin] + }], + mx: [{ + mx: [margin] + }], + my: [{ + my: [margin] + }], + ms: [{ + ms: [margin] + }], + me: [{ + me: [margin] + }], + mt: [{ + mt: [margin] + }], + mr: [{ + mr: [margin] + }], + mb: [{ + mb: [margin] + }], + ml: [{ + ml: [margin] + }], + "space-x": [{ + "space-x": [space] + }], + "space-x-reverse": ["space-x-reverse"], + "space-y": [{ + "space-y": [space] + }], + "space-y-reverse": ["space-y-reverse"], + w: [{ + w: ["auto", "min", "max", "fit", "svw", "lvw", "dvw", isArbitraryValue, spacing] + }], + "min-w": [{ + "min-w": [isArbitraryValue, spacing, "min", "max", "fit"] + }], + "max-w": [{ + "max-w": [isArbitraryValue, spacing, "none", "full", "min", "max", "fit", "prose", { + screen: [isTshirtSize] + }, isTshirtSize] + }], + h: [{ + h: [isArbitraryValue, spacing, "auto", "min", "max", "fit", "svh", "lvh", "dvh"] + }], + "min-h": [{ + "min-h": [isArbitraryValue, spacing, "min", "max", "fit", "svh", "lvh", "dvh"] + }], + "max-h": [{ + "max-h": [isArbitraryValue, spacing, "min", "max", "fit", "svh", "lvh", "dvh"] + }], + size: [{ + size: [isArbitraryValue, spacing, "auto", "min", "max", "fit"] + }], + "font-size": [{ + text: ["base", isTshirtSize, isArbitraryLength] + }], + "font-smoothing": ["antialiased", "subpixel-antialiased"], + "font-style": ["italic", "not-italic"], + "font-weight": [{ + font: ["thin", "extralight", "light", "normal", "medium", "semibold", "bold", "extrabold", "black", isArbitraryNumber] + }], + "font-family": [{ + font: [isAny] + }], + "fvn-normal": ["normal-nums"], + "fvn-ordinal": ["ordinal"], + "fvn-slashed-zero": ["slashed-zero"], + "fvn-figure": ["lining-nums", "oldstyle-nums"], + "fvn-spacing": ["proportional-nums", "tabular-nums"], + "fvn-fraction": ["diagonal-fractions", "stacked-fractons"], + tracking: [{ + tracking: ["tighter", "tight", "normal", "wide", "wider", "widest", isArbitraryValue] + }], + "line-clamp": [{ + "line-clamp": ["none", isNumber, isArbitraryNumber] + }], + leading: [{ + leading: ["none", "tight", "snug", "normal", "relaxed", "loose", isLength, isArbitraryValue] + }], + "list-image": [{ + "list-image": ["none", isArbitraryValue] + }], + "list-style-type": [{ + list: ["none", "disc", "decimal", isArbitraryValue] + }], + "list-style-position": [{ + list: ["inside", "outside"] + }], + "placeholder-color": [{ + placeholder: [colors] + }], + "placeholder-opacity": [{ + "placeholder-opacity": [opacity] + }], + "text-alignment": [{ + text: ["left", "center", "right", "justify", "start", "end"] + }], + "text-color": [{ + text: [colors] + }], + "text-opacity": [{ + "text-opacity": [opacity] + }], + "text-decoration": ["underline", "overline", "line-through", "no-underline"], + "text-decoration-style": [{ + decoration: [...getLineStyles(), "wavy"] + }], + "text-decoration-thickness": [{ + decoration: ["auto", "from-font", isLength, isArbitraryLength] + }], + "underline-offset": [{ + "underline-offset": ["auto", isLength, isArbitraryValue] + }], + "text-decoration-color": [{ + decoration: [colors] + }], + "text-transform": ["uppercase", "lowercase", "capitalize", "normal-case"], + "text-overflow": ["truncate", "text-ellipsis", "text-clip"], + "text-wrap": [{ + text: ["wrap", "nowrap", "balance", "pretty"] + }], + indent: [{ + indent: getSpacingWithArbitrary() + }], + "vertical-align": [{ + align: ["baseline", "top", "middle", "bottom", "text-top", "text-bottom", "sub", "super", isArbitraryValue] + }], + whitespace: [{ + whitespace: ["normal", "nowrap", "pre", "pre-line", "pre-wrap", "break-spaces"] + }], + break: [{ + break: ["normal", "words", "all", "keep"] + }], + hyphens: [{ + hyphens: ["none", "manual", "auto"] + }], + content: [{ + content: ["none", isArbitraryValue] + }], + "bg-attachment": [{ + bg: ["fixed", "local", "scroll"] + }], + "bg-clip": [{ + "bg-clip": ["border", "padding", "content", "text"] + }], + "bg-opacity": [{ + "bg-opacity": [opacity] + }], + "bg-origin": [{ + "bg-origin": ["border", "padding", "content"] + }], + "bg-position": [{ + bg: [...getPositions(), isArbitraryPosition] + }], + "bg-repeat": [{ + bg: ["no-repeat", { + repeat: ["", "x", "y", "round", "space"] + }] + }], + "bg-size": [{ + bg: ["auto", "cover", "contain", isArbitrarySize] + }], + "bg-image": [{ + bg: ["none", { + "gradient-to": ["t", "tr", "r", "br", "b", "bl", "l", "tl"] + }, isArbitraryImage] + }], + "bg-color": [{ + bg: [colors] + }], + "gradient-from-pos": [{ + from: [gradientColorStopPositions] + }], + "gradient-via-pos": [{ + via: [gradientColorStopPositions] + }], + "gradient-to-pos": [{ + to: [gradientColorStopPositions] + }], + "gradient-from": [{ + from: [gradientColorStops] + }], + "gradient-via": [{ + via: [gradientColorStops] + }], + "gradient-to": [{ + to: [gradientColorStops] + }], + rounded: [{ + rounded: [borderRadius] + }], + "rounded-s": [{ + "rounded-s": [borderRadius] + }], + "rounded-e": [{ + "rounded-e": [borderRadius] + }], + "rounded-t": [{ + "rounded-t": [borderRadius] + }], + "rounded-r": [{ + "rounded-r": [borderRadius] + }], + "rounded-b": [{ + "rounded-b": [borderRadius] + }], + "rounded-l": [{ + "rounded-l": [borderRadius] + }], + "rounded-ss": [{ + "rounded-ss": [borderRadius] + }], + "rounded-se": [{ + "rounded-se": [borderRadius] + }], + "rounded-ee": [{ + "rounded-ee": [borderRadius] + }], + "rounded-es": [{ + "rounded-es": [borderRadius] + }], + "rounded-tl": [{ + "rounded-tl": [borderRadius] + }], + "rounded-tr": [{ + "rounded-tr": [borderRadius] + }], + "rounded-br": [{ + "rounded-br": [borderRadius] + }], + "rounded-bl": [{ + "rounded-bl": [borderRadius] + }], + "border-w": [{ + border: [borderWidth] + }], + "border-w-x": [{ + "border-x": [borderWidth] + }], + "border-w-y": [{ + "border-y": [borderWidth] + }], + "border-w-s": [{ + "border-s": [borderWidth] + }], + "border-w-e": [{ + "border-e": [borderWidth] + }], + "border-w-t": [{ + "border-t": [borderWidth] + }], + "border-w-r": [{ + "border-r": [borderWidth] + }], + "border-w-b": [{ + "border-b": [borderWidth] + }], + "border-w-l": [{ + "border-l": [borderWidth] + }], + "border-opacity": [{ + "border-opacity": [opacity] + }], + "border-style": [{ + border: [...getLineStyles(), "hidden"] + }], + "divide-x": [{ + "divide-x": [borderWidth] + }], + "divide-x-reverse": ["divide-x-reverse"], + "divide-y": [{ + "divide-y": [borderWidth] + }], + "divide-y-reverse": ["divide-y-reverse"], + "divide-opacity": [{ + "divide-opacity": [opacity] + }], + "divide-style": [{ + divide: getLineStyles() + }], + "border-color": [{ + border: [borderColor] + }], + "border-color-x": [{ + "border-x": [borderColor] + }], + "border-color-y": [{ + "border-y": [borderColor] + }], + "border-color-t": [{ + "border-t": [borderColor] + }], + "border-color-r": [{ + "border-r": [borderColor] + }], + "border-color-b": [{ + "border-b": [borderColor] + }], + "border-color-l": [{ + "border-l": [borderColor] + }], + "divide-color": [{ + divide: [borderColor] + }], + "outline-style": [{ + outline: ["", ...getLineStyles()] + }], + "outline-offset": [{ + "outline-offset": [isLength, isArbitraryValue] + }], + "outline-w": [{ + outline: [isLength, isArbitraryLength] + }], + "outline-color": [{ + outline: [colors] + }], + "ring-w": [{ + ring: getLengthWithEmptyAndArbitrary() + }], + "ring-w-inset": ["ring-inset"], + "ring-color": [{ + ring: [colors] + }], + "ring-opacity": [{ + "ring-opacity": [opacity] + }], + "ring-offset-w": [{ + "ring-offset": [isLength, isArbitraryLength] + }], + "ring-offset-color": [{ + "ring-offset": [colors] + }], + shadow: [{ + shadow: ["", "inner", "none", isTshirtSize, isArbitraryShadow] + }], + "shadow-color": [{ + shadow: [isAny] + }], + opacity: [{ + opacity: [opacity] + }], + "mix-blend": [{ + "mix-blend": [...getBlendModes(), "plus-lighter", "plus-darker"] + }], + "bg-blend": [{ + "bg-blend": getBlendModes() + }], + filter: [{ + filter: ["", "none"] + }], + blur: [{ + blur: [blur] + }], + brightness: [{ + brightness: [brightness] + }], + contrast: [{ + contrast: [contrast] + }], + "drop-shadow": [{ + "drop-shadow": ["", "none", isTshirtSize, isArbitraryValue] + }], + grayscale: [{ + grayscale: [grayscale] + }], + "hue-rotate": [{ + "hue-rotate": [hueRotate] + }], + invert: [{ + invert: [invert] + }], + saturate: [{ + saturate: [saturate] + }], + sepia: [{ + sepia: [sepia] + }], + "backdrop-filter": [{ + "backdrop-filter": ["", "none"] + }], + "backdrop-blur": [{ + "backdrop-blur": [blur] + }], + "backdrop-brightness": [{ + "backdrop-brightness": [brightness] + }], + "backdrop-contrast": [{ + "backdrop-contrast": [contrast] + }], + "backdrop-grayscale": [{ + "backdrop-grayscale": [grayscale] + }], + "backdrop-hue-rotate": [{ + "backdrop-hue-rotate": [hueRotate] + }], + "backdrop-invert": [{ + "backdrop-invert": [invert] + }], + "backdrop-opacity": [{ + "backdrop-opacity": [opacity] + }], + "backdrop-saturate": [{ + "backdrop-saturate": [saturate] + }], + "backdrop-sepia": [{ + "backdrop-sepia": [sepia] + }], + "border-collapse": [{ + border: ["collapse", "separate"] + }], + "border-spacing": [{ + "border-spacing": [borderSpacing] + }], + "border-spacing-x": [{ + "border-spacing-x": [borderSpacing] + }], + "border-spacing-y": [{ + "border-spacing-y": [borderSpacing] + }], + "table-layout": [{ + table: ["auto", "fixed"] + }], + caption: [{ + caption: ["top", "bottom"] + }], + transition: [{ + transition: ["none", "all", "", "colors", "opacity", "shadow", "transform", isArbitraryValue] + }], + duration: [{ + duration: getNumberAndArbitrary() + }], + ease: [{ + ease: ["linear", "in", "out", "in-out", isArbitraryValue] + }], + delay: [{ + delay: getNumberAndArbitrary() + }], + animate: [{ + animate: ["none", "spin", "ping", "pulse", "bounce", isArbitraryValue] + }], + transform: [{ + transform: ["", "gpu", "none"] + }], + scale: [{ + scale: [scale] + }], + "scale-x": [{ + "scale-x": [scale] + }], + "scale-y": [{ + "scale-y": [scale] + }], + rotate: [{ + rotate: [isInteger, isArbitraryValue] + }], + "translate-x": [{ + "translate-x": [translate] + }], + "translate-y": [{ + "translate-y": [translate] + }], + "skew-x": [{ + "skew-x": [skew] + }], + "skew-y": [{ + "skew-y": [skew] + }], + "transform-origin": [{ + origin: ["center", "top", "top-right", "right", "bottom-right", "bottom", "bottom-left", "left", "top-left", isArbitraryValue] + }], + accent: [{ + accent: ["auto", colors] + }], + appearance: [{ + appearance: ["none", "auto"] + }], + cursor: [{ + cursor: ["auto", "default", "pointer", "wait", "text", "move", "help", "not-allowed", "none", "context-menu", "progress", "cell", "crosshair", "vertical-text", "alias", "copy", "no-drop", "grab", "grabbing", "all-scroll", "col-resize", "row-resize", "n-resize", "e-resize", "s-resize", "w-resize", "ne-resize", "nw-resize", "se-resize", "sw-resize", "ew-resize", "ns-resize", "nesw-resize", "nwse-resize", "zoom-in", "zoom-out", isArbitraryValue] + }], + "caret-color": [{ + caret: [colors] + }], + "pointer-events": [{ + "pointer-events": ["none", "auto"] + }], + resize: [{ + resize: ["none", "y", "x", ""] + }], + "scroll-behavior": [{ + scroll: ["auto", "smooth"] + }], + "scroll-m": [{ + "scroll-m": getSpacingWithArbitrary() + }], + "scroll-mx": [{ + "scroll-mx": getSpacingWithArbitrary() + }], + "scroll-my": [{ + "scroll-my": getSpacingWithArbitrary() + }], + "scroll-ms": [{ + "scroll-ms": getSpacingWithArbitrary() + }], + "scroll-me": [{ + "scroll-me": getSpacingWithArbitrary() + }], + "scroll-mt": [{ + "scroll-mt": getSpacingWithArbitrary() + }], + "scroll-mr": [{ + "scroll-mr": getSpacingWithArbitrary() + }], + "scroll-mb": [{ + "scroll-mb": getSpacingWithArbitrary() + }], + "scroll-ml": [{ + "scroll-ml": getSpacingWithArbitrary() + }], + "scroll-p": [{ + "scroll-p": getSpacingWithArbitrary() + }], + "scroll-px": [{ + "scroll-px": getSpacingWithArbitrary() + }], + "scroll-py": [{ + "scroll-py": getSpacingWithArbitrary() + }], + "scroll-ps": [{ + "scroll-ps": getSpacingWithArbitrary() + }], + "scroll-pe": [{ + "scroll-pe": getSpacingWithArbitrary() + }], + "scroll-pt": [{ + "scroll-pt": getSpacingWithArbitrary() + }], + "scroll-pr": [{ + "scroll-pr": getSpacingWithArbitrary() + }], + "scroll-pb": [{ + "scroll-pb": getSpacingWithArbitrary() + }], + "scroll-pl": [{ + "scroll-pl": getSpacingWithArbitrary() + }], + "snap-align": [{ + snap: ["start", "end", "center", "align-none"] + }], + "snap-stop": [{ + snap: ["normal", "always"] + }], + "snap-type": [{ + snap: ["none", "x", "y", "both"] + }], + "snap-strictness": [{ + snap: ["mandatory", "proximity"] + }], + touch: [{ + touch: ["auto", "none", "manipulation"] + }], + "touch-x": [{ + "touch-pan": ["x", "left", "right"] + }], + "touch-y": [{ + "touch-pan": ["y", "up", "down"] + }], + "touch-pz": ["touch-pinch-zoom"], + select: [{ + select: ["none", "text", "all", "auto"] + }], + "will-change": [{ + "will-change": ["auto", "scroll", "contents", "transform", isArbitraryValue] + }], + fill: [{ + fill: [colors, "none"] + }], + "stroke-w": [{ + stroke: [isLength, isArbitraryLength, isArbitraryNumber] + }], + stroke: [{ + stroke: [colors, "none"] + }], + sr: ["sr-only", "not-sr-only"], + "forced-color-adjust": [{ + "forced-color-adjust": ["auto", "none"] + }] + }, + conflictingClassGroups: { + overflow: ["overflow-x", "overflow-y"], + overscroll: ["overscroll-x", "overscroll-y"], + inset: ["inset-x", "inset-y", "start", "end", "top", "right", "bottom", "left"], + "inset-x": ["right", "left"], + "inset-y": ["top", "bottom"], + flex: ["basis", "grow", "shrink"], + gap: ["gap-x", "gap-y"], + p: ["px", "py", "ps", "pe", "pt", "pr", "pb", "pl"], + px: ["pr", "pl"], + py: ["pt", "pb"], + m: ["mx", "my", "ms", "me", "mt", "mr", "mb", "ml"], + mx: ["mr", "ml"], + my: ["mt", "mb"], + size: ["w", "h"], + "font-size": ["leading"], + "fvn-normal": ["fvn-ordinal", "fvn-slashed-zero", "fvn-figure", "fvn-spacing", "fvn-fraction"], + "fvn-ordinal": ["fvn-normal"], + "fvn-slashed-zero": ["fvn-normal"], + "fvn-figure": ["fvn-normal"], + "fvn-spacing": ["fvn-normal"], + "fvn-fraction": ["fvn-normal"], + "line-clamp": ["display", "overflow"], + rounded: ["rounded-s", "rounded-e", "rounded-t", "rounded-r", "rounded-b", "rounded-l", "rounded-ss", "rounded-se", "rounded-ee", "rounded-es", "rounded-tl", "rounded-tr", "rounded-br", "rounded-bl"], + "rounded-s": ["rounded-ss", "rounded-es"], + "rounded-e": ["rounded-se", "rounded-ee"], + "rounded-t": ["rounded-tl", "rounded-tr"], + "rounded-r": ["rounded-tr", "rounded-br"], + "rounded-b": ["rounded-br", "rounded-bl"], + "rounded-l": ["rounded-tl", "rounded-bl"], + "border-spacing": ["border-spacing-x", "border-spacing-y"], + "border-w": ["border-w-s", "border-w-e", "border-w-t", "border-w-r", "border-w-b", "border-w-l"], + "border-w-x": ["border-w-r", "border-w-l"], + "border-w-y": ["border-w-t", "border-w-b"], + "border-color": ["border-color-t", "border-color-r", "border-color-b", "border-color-l"], + "border-color-x": ["border-color-r", "border-color-l"], + "border-color-y": ["border-color-t", "border-color-b"], + "scroll-m": ["scroll-mx", "scroll-my", "scroll-ms", "scroll-me", "scroll-mt", "scroll-mr", "scroll-mb", "scroll-ml"], + "scroll-mx": ["scroll-mr", "scroll-ml"], + "scroll-my": ["scroll-mt", "scroll-mb"], + "scroll-p": ["scroll-px", "scroll-py", "scroll-ps", "scroll-pe", "scroll-pt", "scroll-pr", "scroll-pb", "scroll-pl"], + "scroll-px": ["scroll-pr", "scroll-pl"], + "scroll-py": ["scroll-pt", "scroll-pb"], + touch: ["touch-x", "touch-y", "touch-pz"], + "touch-x": ["touch"], + "touch-y": ["touch"], + "touch-pz": ["touch"] + }, + conflictingClassGroupModifiers: { + "font-size": ["leading"] + } + }; +}; +var twMerge = createTailwindMerge(getDefaultConfig); + +// src/lib/utils.ts +function cn(...inputs) { + return twMerge(clsx2(inputs)); +} +function truncateFileName(fileName, maxLength = 16) { + if (fileName.length <= maxLength) + return fileName; + const start = fileName.slice(0, maxLength / 2 - 1); + const end = fileName.slice(-maxLength / 2 + 2); + return `${start}...${end}`; +} + +// src/components/ui/alert.tsx +var jsx_dev_runtime = __toESM(require_jsx_dev_runtime(), 1); +var alertVariants = cva("relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground", { + variants: { + variant: { + default: "bg-background text-foreground", + destructive: "border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive" + } + }, + defaultVariants: { + variant: "default" + } +}); +var Alert = React.forwardRef(({ className, variant, ...props }, ref) => jsx_dev_runtime.jsxDEV("div", { + ref, + role: "alert", + className: cn(alertVariants({ variant }), className), + ...props +}, undefined, false, undefined, this)); +Alert.displayName = "Alert"; +var AlertTitle = React.forwardRef(({ className, ...props }, ref) => jsx_dev_runtime.jsxDEV("h5", { + ref, + className: cn("mb-1 font-medium leading-none tracking-tight", className), + ...props +}, undefined, false, undefined, this)); +AlertTitle.displayName = "AlertTitle"; +var AlertDescription = React.forwardRef(({ className, ...props }, ref) => jsx_dev_runtime.jsxDEV("div", { + ref, + className: cn("text-sm [&_p]:leading-relaxed", className), + ...props +}, undefined, false, undefined, this)); +AlertDescription.displayName = "AlertDescription"; + +// src/hooks/useFaceLandmarkDetection.tsx +var import_react5 = __toESM(require_react(), 1); + +// node_modules/@mediapipe/tasks-vision/vision_bundle.mjs +var exports_vision_bundle = {}; +__export(exports_vision_bundle, { + VisionTaskRunner: () => { + { + return Za; + } + }, + PoseLandmarker: () => { + { + return Yh; + } + }, + ObjectDetector: () => { + { + return Hh; + } + }, + MPMask: () => { + { + return wa; + } + }, + MPImage: () => { + { + return ja; + } + }, + InteractiveSegmenterResult: () => { + { + return Mh; + } + }, + InteractiveSegmenter: () => { + { + return Xh; + } + }, + ImageSegmenterResult: () => { + { + return xh; + } + }, + ImageSegmenter: () => { + { + return Fh; + } + }, + ImageEmbedder: () => { + { + return Sh; + } + }, + ImageClassifier: () => { + { + return kh; + } + }, + HolisticLandmarker: () => { + { + return bh; + } + }, + HandLandmarker: () => { + { + return vh; + } + }, + GestureRecognizer: () => { + { + return yh; + } + }, + FilesetResolver: () => { + { + return Uo; + } + }, + FaceStylizer: () => { + { + return fh; + } + }, + FaceLandmarker: () => { + { + return lh; + } + }, + FaceDetector: () => { + { + return Qa; + } + }, + DrawingUtils: () => { + { + return Ia; + } + } +}); +var e = function(e2, n) { + t: { + for (var r3 = ["CLOSURE_FLAGS"], i = t, s = 0;s < r3.length; s++) + if ((i = i[r3[s]]) == null) { + r3 = null; + break t; + } + r3 = i; + } + return (e2 = r3 && r3[e2]) != null ? e2 : n; +}; +var n = function() { + throw Error("Invalid UTF8"); +}; +var r3 = function(t, e2) { + return e2 = String.fromCharCode.apply(null, e2), t == null ? e2 : t + e2; +}; +var c = function(t) { + if (h) + t = (a ||= new TextEncoder).encode(t); + else { + let n2 = 0; + const r4 = new Uint8Array(3 * t.length); + for (let i = 0;i < t.length; i++) { + var e2 = t.charCodeAt(i); + if (e2 < 128) + r4[n2++] = e2; + else { + if (e2 < 2048) + r4[n2++] = e2 >> 6 | 192; + else { + if (e2 >= 55296 && e2 <= 57343) { + if (e2 <= 56319 && i < t.length) { + const s = t.charCodeAt(++i); + if (s >= 56320 && s <= 57343) { + e2 = 1024 * (e2 - 55296) + s - 56320 + 65536, r4[n2++] = e2 >> 18 | 240, r4[n2++] = e2 >> 12 & 63 | 128, r4[n2++] = e2 >> 6 & 63 | 128, r4[n2++] = 63 & e2 | 128; + continue; + } + i--; + } + e2 = 65533; + } + r4[n2++] = e2 >> 12 | 224, r4[n2++] = e2 >> 6 & 63 | 128; + } + r4[n2++] = 63 & e2 | 128; + } + } + t = n2 === r4.length ? r4 : r4.subarray(0, n2); + } + return t; +}; +var g = function(t) { + return !!l && (!!u && u.brands.some(({ brand: e2 }) => e2 && e2.indexOf(t) != -1)); +}; +var m = function(e2) { + var n2; + return (n2 = t.navigator) && (n2 = n2.userAgent) || (n2 = ""), n2.indexOf(e2) != -1; +}; +var y = function() { + return !!l && (!!u && u.brands.length > 0); +}; +var _ = function() { + return y() ? g("Chromium") : (m("Chrome") || m("CriOS")) && !(!y() && m("Edge")) || m("Silk"); +}; +var v = function(t) { + return v[" "](t), t; +}; +var A = function(t) { + var e2 = t.length, n2 = 3 * e2 / 4; + n2 % 3 ? n2 = Math.floor(n2) : "=.".indexOf(t[e2 - 1]) != -1 && (n2 = "=.".indexOf(t[e2 - 2]) != -1 ? n2 - 2 : n2 - 1); + var r4 = new Uint8Array(n2), i = 0; + return function(t2, e3) { + function n3(e4) { + for (;r5 < t2.length; ) { + var n4 = t2.charAt(r5++), i3 = T[n4]; + if (i3 != null) + return i3; + if (!/^[\s\xa0]*$/.test(n4)) + throw Error("Unknown base64 encoding at char: " + n4); + } + return e4; + } + b(); + for (var r5 = 0;; ) { + var i2 = n3(-1), s = n3(0), o = n3(64), a = n3(64); + if (a === 64 && i2 === -1) + break; + e3(i2 << 2 | s >> 4), o != 64 && (e3(s << 4 & 240 | o >> 2), a != 64 && e3(o << 6 & 192 | a)); + } + }(t, function(t2) { + r4[i++] = t2; + }), i !== n2 ? r4.subarray(0, i) : r4; +}; +var b = function() { + if (!T) { + T = {}; + for (var t = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""), e2 = ["+/=", "+/", "-_=", "-_.", "-_"], n2 = 0;n2 < 5; n2++) { + var r4 = t.concat(e2[n2].split("")); + w[n2] = r4; + for (var i = 0;i < r4.length; i++) { + var s = r4[i]; + T[s] === undefined && (T[s] = i); + } + } + } +}; +var x = function(t) { + if (!S) { + var e2; + e2 === undefined && (e2 = 0), b(), e2 = w[e2]; + var n2 = Array(Math.floor(t.length / 3)), r4 = e2[64] || ""; + let h = 0, c2 = 0; + for (;h < t.length - 2; h += 3) { + var i = t[h], s = t[h + 1], o = t[h + 2], a = e2[i >> 2]; + i = e2[(3 & i) << 4 | s >> 4], s = e2[(15 & s) << 2 | o >> 6], o = e2[63 & o], n2[c2++] = a + i + s + o; + } + switch (a = 0, o = r4, t.length - h) { + case 2: + o = e2[(15 & (a = t[h + 1])) << 2] || r4; + case 1: + t = t[h], n2[c2] = e2[t >> 2] + e2[(3 & t) << 4 | a >> 4] + o + r4; + } + return n2.join(""); + } + for (e2 = "", n2 = 0, r4 = t.length - 10240;n2 < r4; ) + e2 += String.fromCharCode.apply(null, t.subarray(n2, n2 += 10240)); + return e2 += String.fromCharCode.apply(null, n2 ? t.subarray(n2) : t), btoa(e2); +}; +var F = function(t) { + return R[t] || ""; +}; +var M = function(t) { + if (!S) + return A(t); + L.test(t) && (t = t.replace(L, F)), t = atob(t); + const e2 = new Uint8Array(t.length); + for (let n2 = 0;n2 < t.length; n2++) + e2[n2] = t.charCodeAt(n2); + return e2; +}; +var I = function(t) { + return k && t != null && t instanceof Uint8Array; +}; +var C = function(t) { + if (t !== P) + throw Error("illegal external caller"); +}; +var N = function() { + return O ||= new D(null, P); +}; +var U = function(t) { + C(P); + var e2 = t.ba; + return (e2 = e2 == null || I(e2) ? e2 : typeof e2 == "string" ? M(e2) : null) == null ? e2 : t.ba = e2; +}; +var B = function(t, e2) { + t.__closure__error__context__984382 || (t.__closure__error__context__984382 = {}), t.__closure__error__context__984382.severity = e2; +}; +var j = function() { + const e2 = Error(); + B(e2, "incident"), function(e3) { + t.setTimeout(() => { + throw e3; + }, 0); + }(e2); +}; +var V = function(t) { + return B(t = Error(t), "warning"), t; +}; +var X = function() { + return typeof BigInt == "function"; +}; +var H = function(t) { + return Array.prototype.slice.call(t); +}; +var z = function(t) { + return typeof Symbol == "function" && typeof Symbol() == "symbol" ? Symbol() : t; +}; +var rt = function(t) { + return Z(t, 34), t; +}; +var it = function(t, e2) { + nt(e2, -14591 & (0 | t)); +}; +var st = function(t, e2) { + nt(e2, -14557 & (34 | t)); +}; +var ct = function(t) { + return !(!t || typeof t != "object" || t.La !== ht); +}; +var ut = function(t) { + return t !== null && typeof t == "object" && !Array.isArray(t) && t.constructor === Object; +}; +var lt = function(t, e2, n2) { + if (t != null) { + if (typeof t == "string") + t = t ? new D(t, P) : N(); + else if (t.constructor !== D) + if (I(t)) + t = t.length ? new D(n2 ? t : new Uint8Array(t), P) : N(); + else { + if (!e2) + throw Error(); + t = undefined; + } + } + return t; +}; +var ft = function(t) { + return !(!Array.isArray(t) || t.length) && !!(1 & tt(t)); +}; +var pt = function(t) { + if (2 & t) + throw Error(); +}; +var yt = function(t, e2) { + (e2 = mt ? e2[mt] : undefined) && (t[mt] = H(e2)); +}; +var Et = function(t) { + return t.Sa = true, t; +}; +var Ft = function(t, e2) { + if (t.length > e2.length) + return false; + if (t.length < e2.length || t === e2) + return true; + for (let n2 = 0;n2 < t.length; n2++) { + const r4 = t[n2], i = e2[n2]; + if (r4 > i) + return false; + if (r4 < i) + return true; + } +}; +var Ct = function(t) { + const e2 = t >>> 0; + Pt = e2, Ot = (t - e2) / 4294967296 >>> 0; +}; +var Nt = function(t) { + if (t < 0) { + Ct(-t); + const [e2, n2] = Xt(Pt, Ot); + Pt = e2 >>> 0, Ot = n2 >>> 0; + } else + Ct(t); +}; +var Ut = function(t) { + const e2 = It ||= new DataView(new ArrayBuffer(8)); + e2.setFloat32(0, +t, true), Ot = 0, Pt = e2.getUint32(0, true); +}; +var Dt = function(t, e2) { + return 4294967296 * e2 + (t >>> 0); +}; +var Bt = function(t, e2) { + const n2 = 2147483648 & e2; + return n2 && (e2 = ~e2 >>> 0, (t = 1 + ~t >>> 0) == 0 && (e2 = e2 + 1 >>> 0)), t = Dt(t, e2), n2 ? -t : t; +}; +var Gt = function(t, e2) { + if (t >>>= 0, (e2 >>>= 0) <= 2097151) + var n2 = "" + (4294967296 * e2 + t); + else + X() ? n2 = "" + (BigInt(e2) << BigInt(32) | BigInt(t)) : (t = (16777215 & t) + 6777216 * (n2 = 16777215 & (t >>> 24 | e2 << 8)) + 6710656 * (e2 = e2 >> 16 & 65535), n2 += 8147497 * e2, e2 *= 2, t >= 1e7 && (n2 += t / 1e7 >>> 0, t %= 1e7), n2 >= 1e7 && (e2 += n2 / 1e7 >>> 0, n2 %= 1e7), n2 = e2 + jt(n2) + jt(t)); + return n2; +}; +var jt = function(t) { + return t = String(t), "0000000".slice(t.length) + t; +}; +var Vt = function(t) { + if (t.length < 16) + Nt(Number(t)); + else if (X()) + t = BigInt(t), Pt = Number(t & BigInt(4294967295)) >>> 0, Ot = Number(t >> BigInt(32) & BigInt(4294967295)); + else { + const e2 = +(t[0] === "-"); + Ot = Pt = 0; + const n2 = t.length; + for (let r4 = e2, i = (n2 - e2) % 6 + e2;i <= n2; r4 = i, i += 6) { + const e3 = Number(t.slice(r4, i)); + Ot *= 1e6, Pt = 1e6 * Pt + e3, Pt >= 4294967296 && (Ot += Math.trunc(Pt / 4294967296), Ot >>>= 0, Pt >>>= 0); + } + if (e2) { + const [t2, e3] = Xt(Pt, Ot); + Pt = t2, Ot = e3; + } + } +}; +var Xt = function(t, e2) { + return e2 = ~e2, t ? t = 1 + ~t : e2 += 1, [t, e2]; +}; +var Ht = function(t) { + return t == null || typeof t == "number" ? t : t === "NaN" || t === "Infinity" || t === "-Infinity" ? Number(t) : undefined; +}; +var Wt = function(t) { + return t == null || typeof t == "boolean" ? t : typeof t == "number" ? !!t : undefined; +}; +var Kt = function(t) { + const e2 = typeof t; + switch (e2) { + case "bigint": + return true; + case "number": + return Number.isFinite(t); + } + return e2 === "string" && zt.test(t); +}; +var Yt = function(t) { + if (t == null) + return t; + if (typeof t == "string") { + if (!t) + return; + t = +t; + } + return typeof t == "number" && Number.isFinite(t) ? 0 | t : undefined; +}; +var $t = function(t) { + if (t == null) + return t; + if (typeof t == "string") { + if (!t) + return; + t = +t; + } + return typeof t == "number" && Number.isFinite(t) ? t >>> 0 : undefined; +}; +var qt = function(t) { + return t[0] !== "-" && (t.length < 20 || t.length === 20 && Number(t.substring(0, 6)) < 184467); +}; +var Jt = function(t) { + return t = Math.trunc(t), Number.isSafeInteger(t) || (Nt(t), t = Bt(Pt, Ot)), t; +}; +var Zt = function(t) { + var e2 = Math.trunc(Number(t)); + if (Number.isSafeInteger(e2)) + return String(e2); + if ((e2 = t.indexOf(".")) !== -1 && (t = t.substring(0, e2)), !(t[0] === "-" ? t.length < 20 || t.length === 20 && Number(t.substring(0, 7)) > -922337 : t.length < 19 || t.length === 19 && Number(t.substring(0, 6)) < 922337)) + if (Vt(t), t = Pt, 2147483648 & (e2 = Ot)) + if (X()) + t = "" + (BigInt(0 | e2) << BigInt(32) | BigInt(t >>> 0)); + else { + const [n2, r4] = Xt(t, e2); + t = "-" + Gt(n2, r4); + } + else + t = Gt(t, e2); + return t; +}; +var Qt = function(t) { + return t == null ? t : typeof t == "bigint" ? (kt(t) ? t = Number(t) : (t = BigInt.asIntN(64, t), t = kt(t) ? Number(t) : String(t)), t) : Kt(t) ? typeof t == "number" ? Jt(t) : Zt(t) : undefined; +}; +var te = function(t) { + if (t == null) + return t; + var e2 = typeof t; + if (e2 === "bigint") + return String(BigInt.asUintN(64, t)); + if (Kt(t)) { + if (e2 === "string") + return e2 = Math.trunc(Number(t)), Number.isSafeInteger(e2) && e2 >= 0 ? t = String(e2) : ((e2 = t.indexOf(".")) !== -1 && (t = t.substring(0, e2)), qt(t) || (Vt(t), t = Gt(Pt, Ot))), t; + if (e2 === "number") + return (t = Math.trunc(t)) >= 0 && Number.isSafeInteger(t) ? t : function(t2) { + if (t2 < 0) { + Nt(t2); + const e3 = Gt(Pt, Ot); + return t2 = Number(e3), Number.isSafeInteger(t2) ? t2 : e3; + } + return qt(String(t2)) ? t2 : (Nt(t2), Dt(Pt, Ot)); + }(t); + } +}; +var ee = function(t) { + if (typeof t != "string") + throw Error(); + return t; +}; +var ne = function(t) { + if (t != null && typeof t != "string") + throw Error(); + return t; +}; +var re = function(t) { + return t == null || typeof t == "string" ? t : undefined; +}; +var ie = function(t, e2, n2, r4) { + if (t != null && typeof t == "object" && t.Y === at) + return t; + if (!Array.isArray(t)) + return n2 ? 2 & r4 ? (t = e2[Y]) ? e2 = t : (rt((t = new e2).u), e2 = e2[Y] = t) : e2 = new e2 : e2 = undefined, e2; + let i = n2 = tt(t); + return i === 0 && (i |= 32 & r4), i |= 2 & r4, i !== n2 && nt(t, i), new e2(t); +}; +var se = function(t, e2, n2) { + if (e2) + t: { + if (!Kt(e2 = t)) + throw V("int64"); + switch (typeof e2) { + case "string": + e2 = Zt(e2); + break t; + case "bigint": + if (t = e2 = BigInt.asIntN(64, e2), Tt(t)) { + if (!/^\s*(?:-?[1-9]\d*|0)?\s*$/.test(t)) + throw Error(String(t)); + } else if (wt(t) && !Number.isSafeInteger(t)) + throw Error(String(t)); + e2 = bt ? BigInt(e2) : At(e2) ? e2 ? "1" : "0" : Tt(e2) ? e2.trim() || "0" : String(e2); + break t; + default: + e2 = Jt(e2); + } + } + else + e2 = Qt(t); + return typeof (n2 = (t = e2) == null ? n2 ? 0 : undefined : t) == "string" && (e2 = +n2, Number.isSafeInteger(e2)) ? e2 : n2; +}; +var oe = function(t) { + if (ce === undefined && (ce = typeof Proxy == "function" ? ye(Proxy) : null), !ce || !me()) + return t; + let e2 = ae?.get(t); + return e2 || (Math.random() > 0.01 ? t : (function(t2) { + if (le === undefined) { + const t3 = new ce([], {}); + le = Array.prototype.concat.call([], t3).length === 1; + } + le && typeof Symbol == "function" && Symbol.isConcatSpreadable && (t2[Symbol.isConcatSpreadable] = true); + }(t), e2 = new ce(t, { set: (t2, e3, n2) => (j(), t2[e3] = n2, true) }), function(t2, e3) { + (ae ||= new ue).set(t2, e3), (he ||= new ue).set(e3, t2); + }(t, e2), e2)); +}; +var me = function() { + return ue === undefined && (ue = typeof WeakMap == "function" ? ye(WeakMap) : null), ue; +}; +var ye = function(t) { + try { + return t.toString().indexOf("[native code]") !== -1 ? t : null; + } catch { + return null; + } +}; +var _e = function(t, e2, n2) { + if (f && me()) { + if (fe?.get(e2)?.get(t)) { + if (n2) + return; + } else if (Math.random() > 0.01) + return; + var r4 = t.length; + n2 = { length: r4 }; + for (var i = 0;i < Math.min(r4, 10); i++) { + if (r4 <= 10) + var s = i; + else { + s = r4 / 10; + const t2 = Math.floor(i * s); + s = t2 + Math.floor(Math.random() * (Math.floor((i + 1) * s) - t2)); + } + n2[s] = t[s]; + } + Ee(t, n2) ? ((i = (r4 = fe ||= new ue).get(e2)) || (i = new ue, r4.set(e2, i)), i.set(t, n2)) : (j(), Te(t, e2)); + } +}; +var ve = function(t, e2) { + const n2 = fe?.get(e2)?.get(t); + n2 && !Ee(t, n2) && (j(), Te(t, e2)); +}; +var Ee = function(t, e2) { + if (t.length !== e2.length) + return false; + for (const i in e2) { + var n2, r4 = Number(i); + if ((n2 = Number.isInteger(r4)) && (n2 = t[r4], r4 = e2[r4], n2 = !(Number.isNaN(n2) ? Number.isNaN(r4) : n2 === r4)), n2) + return false; + } + return true; +}; +var we = function(t) { + if (t && fe?.has(t)) { + var e2 = t.u; + if (e2) + for (let n2 = 0;n2 < e2.length; n2++) { + const r4 = e2[n2]; + if (n2 === e2.length - 1 && ut(r4)) + for (const e3 in r4) { + const n3 = r4[e3]; + Array.isArray(n3) && ve(n3, t); + } + else + Array.isArray(r4) && ve(r4, t); + } + } +}; +var Te = function(t, e2) { + fe?.get(e2)?.delete(t); +}; +var Ae = function(t, e2) { + return t = be(t, e2[0], e2[1]), Z(t, 16384), t; +}; +var be = function(t, e2, n2) { + if (t == null && (t = de), de = undefined, t == null) { + var r4 = 96; + n2 ? (t = [n2], r4 |= 512) : t = [], e2 && (r4 = -33521665 & r4 | (1023 & e2) << 15); + } else { + if (!Array.isArray(t)) + throw Error("narr"); + if (2048 & (r4 = tt(t))) + throw Error("farr"); + if (64 & r4) + return t; + if (r4 |= 64, n2 && (r4 |= 512, n2 !== t[0])) + throw Error("mid"); + t: { + const i = (n2 = t).length; + if (i) { + const t2 = i - 1; + if (ut(n2[t2])) { + if ((e2 = t2 - (+!!(512 & (r4 |= 256)) - 1)) >= 1024) + throw Error("pvtlmt"); + r4 = -33521665 & r4 | (1023 & e2) << 15; + break t; + } + } + if (e2) { + if ((e2 = Math.max(e2, i - (+!!(512 & r4) - 1))) > 1024) + throw Error("spvt"); + r4 = -33521665 & r4 | (1023 & e2) << 15; + } + } + } + return nt(t, r4), t; +}; +var Re = function(t) { + return t; +}; +var Fe = function(t) { + if (2 & t.M) + throw Error("Cannot mutate an immutable Map"); +}; +var Ie = function(t, e2, n2, r4, i, s) { + return t = ie(t, r4, n2, s), i && (t = He(t)), t; +}; +var Pe = function(t) { + return t; +}; +var Oe = function(t) { + return [t, this.get(t)]; +}; +var Ne = function() { + return Ce ||= new Me(rt([]), undefined, undefined, undefined, ke); +}; +var Ue = function(t, e2, n2, r4, i) { + if (t != null) { + if (Array.isArray(t)) + t = ft(t) ? undefined : i && 2 & tt(t) ? t : De(t, e2, n2, r4 !== undefined, i); + else if (ut(t)) { + const s = {}; + for (let o in t) + s[o] = Ue(t[o], e2, n2, r4, i); + t = s; + } else + t = e2(t, r4); + return t; + } +}; +var De = function(t, e2, n2, r4, i) { + const s = r4 || n2 ? tt(t) : 0; + r4 = r4 ? !!(32 & s) : undefined; + const o = H(t); + for (let t2 = 0;t2 < o.length; t2++) + o[t2] = Ue(o[t2], e2, n2, r4, i); + return n2 && (yt(o, t), n2(s, o)), o; +}; +var Be = function(t) { + return Ue(t, Ge, undefined, undefined, false); +}; +var Ge = function(t) { + return t.Y === at ? t.toJSON() : t instanceof Me ? t.pa(Be) : function(t2) { + switch (typeof t2) { + case "number": + return isFinite(t2) ? t2 : String(t2); + case "bigint": + return kt(t2) ? Number(t2) : String(t2); + case "boolean": + return t2 ? 1 : 0; + case "object": + if (t2) + if (Array.isArray(t2)) { + if (ft(t2)) + return; + } else { + if (I(t2)) + return x(t2); + if (t2 instanceof D) { + const e2 = t2.ba; + return e2 == null ? "" : typeof e2 == "string" ? e2 : t2.ba = x(e2); + } + if (t2 instanceof Me) + return t2.pa(); + } + } + return t2; + }(t); +}; +var je = function(t, e2, n2 = st) { + if (t != null) { + if (k && t instanceof Uint8Array) + return e2 ? t : new Uint8Array(t); + if (Array.isArray(t)) { + var r4 = tt(t); + return 2 & r4 ? t : (e2 &&= r4 === 0 || !!(32 & r4) && !(64 & r4 || !(16 & r4)), e2 ? (nt(t, -12293 & (34 | r4)), t) : De(t, je, 4 & r4 ? st : n2, true, true)); + } + return t.Y === at ? (n2 = t.u, t = 2 & (r4 = et(n2)) ? t : Ve(t, n2, r4, true)) : t instanceof Me && !(2 & t.M) && (n2 = rt(t.Z(je)), t = new Me(n2, t.U, t.T, t.aa)), t; + } +}; +var Ve = function(t, e2, n2, r4) { + return we(t), t = t.constructor, de = e2 = Xe(e2, n2, r4), e2 = new t(e2), de = undefined, e2; +}; +var Xe = function(t, e2, n2) { + const r4 = n2 || 2 & e2 ? st : it, i = !!(32 & e2); + return t = function(t2, e3, n3) { + const r5 = H(t2); + var i2 = r5.length; + const s = 256 & e3 ? r5[i2 - 1] : undefined; + for (i2 += s ? -1 : 0, e3 = 512 & e3 ? 1 : 0;e3 < i2; e3++) + r5[e3] = n3(r5[e3]); + if (s) { + e3 = r5[e3] = {}; + for (const t3 in s) + e3[t3] = n3(s[t3]); + } + return yt(r5, t2), r5; + }(t, e2, (t2) => je(t2, i, r4)), Z(t, 32 | (n2 ? 2 : 0)), t; +}; +var He = function(t) { + const e2 = t.u, n2 = et(e2); + return 2 & n2 ? Ve(t, e2, n2, false) : t; +}; +var We = function(t, e2, n2, r4) { + return !(4 & e2) || n2 != null && (!r4 && n2 === 0 && (4096 & e2 || 8192 & e2) && (t.constructor[J] = 1 + (0 | t.constructor[J])) < 5 && j(), n2 !== 0 && !(n2 & e2)); +}; +var ze = function(t, e2) { + return Ye(t = t.u, et(t), e2); +}; +var Ke = function(t, e2, n2, r4) { + if (!((e2 = r4 + (+!!(512 & e2) - 1)) < 0 || e2 >= t.length || e2 >= n2)) + return t[e2]; +}; +var Ye = function(t, e2, n2, r4) { + if (n2 === -1) + return null; + const i = e2 >> 15 & 1023 || 536870912; + if (!(n2 >= i)) { + var s = t.length; + return r4 && 256 & e2 && (r4 = t[s - 1][n2]) != null ? (Ke(t, e2, i, n2) && $ != null && ((e2 = (t = G ??= {})[$] || 0) >= 4 || (t[$] = e2 + 1, j())), r4) : Ke(t, e2, i, n2); + } + return 256 & e2 ? t[t.length - 1][n2] : undefined; +}; +var $e = function(t, e2, n2) { + const r4 = t.u; + let i = et(r4); + return pt(i), qe(r4, i, e2, n2), t; +}; +var qe = function(t, e2, n2, r4) { + const i = e2 >> 15 & 1023 || 536870912; + if (n2 >= i) { + let s, o = e2; + if (256 & e2) + s = t[t.length - 1]; + else { + if (r4 == null) + return o; + s = t[i + (+!!(512 & e2) - 1)] = {}, o |= 256; + } + return s[n2] = r4, n2 < i && (t[n2 + (+!!(512 & e2) - 1)] = undefined), o !== e2 && nt(t, o), o; + } + return t[n2 + (+!!(512 & e2) - 1)] = r4, 256 & e2 && ((n2 in (t = t[t.length - 1])) && delete t[n2]), e2; +}; +var Je = function(t, e2, n2, r4, i) { + var s = 2 & e2; + i = Ye(t, e2, n2, i), Array.isArray(i) || (i = ot); + const o = !(2 & r4); + r4 = !(1 & r4); + const a = !!(32 & e2); + let h = tt(i); + return h !== 0 || !a || s || o ? 1 & h || (h |= 1, nt(i, h)) : (h |= 33, nt(i, h)), s ? (t = false, 2 & h || (rt(i), t = !!(4 & h)), (r4 || t) && Object.freeze(i)) : (s = !!(2 & h) || !!(2048 & h), r4 && s ? (i = H(i), s = 1, a && !o && (s |= 32), nt(i, s), qe(t, e2, n2, i)) : o && 32 & h && !s && Q(i, 32)), i; +}; +var Ze = function(t, e2) { + t = t.u; + let n2 = et(t); + const r4 = Ye(t, n2, e2), i = Ht(r4); + return i != null && i !== r4 && qe(t, n2, e2, i), i; +}; +var Qe = function(t) { + t = t.u; + let e2 = et(t); + const n2 = Ye(t, e2, 1), r4 = lt(n2, true, !!(34 & e2)); + return r4 != null && r4 !== n2 && qe(t, e2, 1, r4), r4; +}; +var tn = function() { + return _t === undefined ? 2 : 5; +}; +var en = function(t, e2, n2, r4, i, s) { + const o = t.u; + let a = et(o); + r4 = 2 & a ? 1 : r4, s = !!s, i = nn(o, a, e2, i); + var h = tt(i), c2 = i; + if (ve(c2, t), r4 !== 2 && r4 !== 1 || Te(c2, t), We(t, h, undefined, s)) { + 4 & h && (i = H(i), h = vn(h, a), a = qe(o, a, e2, i)); + let t2 = c2 = 0; + for (;c2 < i.length; c2++) { + const e3 = n2(i[c2]); + e3 != null && (i[t2++] = e3); + } + t2 < c2 && (i.length = t2), h = -4097 & (20 | (h = rn(h, a))), nt(i, h &= -8193), 2 & h && Object.freeze(i); + } + let u; + return r4 === 1 || r4 === 4 && 32 & h ? sn(h) || (t = h, (h |= 2) !== t && nt(i, h), Object.freeze(i)) : (n2 = r4 === 5 && (!!(32 & h) || sn(h) || !!ae?.get(i)), (r4 === 2 || n2) && sn(h) && (i = H(i), h = En(h = vn(h, a), a, s), nt(i, h), a = qe(o, a, e2, i)), sn(h) || (e2 = h, (h = En(h, a, s)) !== e2 && nt(i, h)), n2 ? (u = oe(i), _e(i, t, true)) : r4 !== 2 || s || ae?.delete(i)), u || i; +}; +var nn = function(t, e2, n2, r4) { + return t = Ye(t, e2, n2, r4), Array.isArray(t) ? t : ot; +}; +var rn = function(t, e2) { + return t === 0 && (t = vn(t, e2)), 1 | t; +}; +var sn = function(t) { + return !!(2 & t) && !!(4 & t) || !!(2048 & t); +}; +var on = function(t) { + t = H(t); + for (let e2 = 0;e2 < t.length; e2++) { + const n2 = t[e2] = H(t[e2]); + Array.isArray(n2[1]) && (n2[1] = rt(n2[1])); + } + return t; +}; +var an = function(t, e2, n2, r4) { + t = t.u; + let i = et(t); + pt(i), qe(t, i, e2, (r4 === "0" ? Number(n2) === 0 : n2 === r4) ? undefined : n2); +}; +var hn = function(t, e2) { + var n2 = _s; + return ln(cn2(t = t.u), t, et(t), n2) === e2 ? e2 : -1; +}; +var cn2 = function(t) { + if (W) + return t[q] ?? (t[q] = new Map); + if (q in t) + return t[q]; + const e2 = new Map; + return Object.defineProperty(t, q, { value: e2 }), e2; +}; +var un = function(t, e2, n2, r4) { + const i = cn2(t), s = ln(i, t, e2, n2); + return s !== r4 && (s && (e2 = qe(t, e2, s)), i.set(n2, r4)), e2; +}; +var ln = function(t, e2, n2, r4) { + let i = t.get(r4); + if (i != null) + return i; + i = 0; + for (let t2 = 0;t2 < r4.length; t2++) { + const s = r4[t2]; + Ye(e2, n2, s) != null && (i !== 0 && (n2 = qe(e2, n2, i)), i = s); + } + return t.set(r4, i), i; +}; +var fn = function(t, e2, n2, r4) { + let i, s = et(t); + if ((r4 = Ye(t, s, n2, r4)) != null && r4.Y === at) + return (e2 = He(r4)) !== r4 && qe(t, s, n2, e2), e2.u; + if (Array.isArray(r4)) { + const t2 = tt(r4); + i = 2 & t2 ? Xe(r4, t2, false) : r4, i = Ae(i, e2); + } else + i = Ae(undefined, e2); + return i !== r4 && qe(t, s, n2, i), i; +}; +var dn = function(t, e2, n2, r4) { + t = t.u; + let i = et(t); + return (e2 = ie(r4 = Ye(t, i, n2, r4), e2, false, i)) !== r4 && e2 != null && qe(t, i, n2, e2), e2; +}; +var pn = function(t, e2, n2, r4 = false) { + if ((e2 = dn(t, e2, n2, r4)) == null) + return e2; + if (t = t.u, !(2 & (r4 = et(t)))) { + const i = He(e2); + i !== e2 && qe(t, r4, n2, e2 = i); + } + return e2; +}; +var gn = function(t, e2, n2, r4, i, s, o) { + const a = t.u; + var h = !!(2 & e2); + i = h ? 1 : i, s = !!s, o &&= !h, h = nn(a, e2, r4); + var c2 = tt(h), u = h; + if (ve(u, t), i !== 2 && i !== 1 || Te(u, t), !(u = !!(4 & c2))) { + var l = h, f = e2; + const t2 = !!(2 & (c2 = rn(c2, e2))); + t2 && (f |= 2); + let r5 = !t2, i2 = true, s2 = 0, o2 = 0; + for (;s2 < l.length; s2++) { + const e3 = ie(l[s2], n2, false, f); + if (e3 instanceof n2) { + if (!t2) { + const t3 = !!(2 & tt(e3.u)); + r5 &&= !t3, i2 &&= t3; + } + l[o2++] = e3; + } + } + o2 < s2 && (l.length = o2), c2 |= 4, c2 = i2 ? 16 | c2 : -17 & c2, nt(l, c2 = r5 ? 8 | c2 : -9 & c2), t2 && Object.freeze(l); + } + if (o && !(8 & c2 || !h.length && (i === 1 || i === 4 && 32 & c2))) { + for (sn(c2) ? (h = H(h), c2 = vn(c2, e2), e2 = qe(a, e2, r4, h)) : Te(h, t), n2 = h, o = c2, l = 0;l < n2.length; l++) + (c2 = n2[l]) !== (f = He(c2)) && (n2[l] = f); + o |= 8, o = n2.length ? -17 & o : 16 | o, nt(n2, o), c2 = o; + } + let d; + return i === 1 || i === 4 && 32 & c2 ? sn(c2) || (t = c2, (c2 |= !h.length || 16 & c2 && (!u || 32 & c2) ? 2 : 2048) !== t && nt(h, c2), Object.freeze(h)) : (u = i === 5 && (!!(32 & c2) || sn(c2) || !!ae?.get(h)), (i === 2 || u) && sn(c2) && (h = H(h), c2 = En(c2 = vn(c2, e2), e2, s), nt(h, c2), e2 = qe(a, e2, r4, h)), sn(c2) || (r4 = c2, (c2 = En(c2, e2, s)) !== r4 && nt(h, c2)), u ? (d = oe(h), _e(h, t, true)) : i !== 2 || s || ae?.delete(h)), d || h; +}; +var mn = function(t, e2, n2) { + const r4 = et(t.u); + return gn(t, r4, e2, n2, tn(), false, !(2 & r4)); +}; +var yn = function(t, e2, n2, r4) { + return r4 == null && (r4 = undefined), $e(t, n2, r4); +}; +var _n = function(t, e2, n2, r4) { + r4 == null && (r4 = undefined); + t: { + t = t.u; + let i = et(t); + if (pt(i), r4 == null) { + const r5 = cn2(t); + if (ln(r5, t, i, n2) !== e2) + break t; + r5.set(n2, 0); + } else + i = un(t, i, n2, e2); + qe(t, i, e2, r4); + } +}; +var vn = function(t, e2) { + return -2049 & (t = 32 | (2 & e2 ? 2 | t : -3 & t)); +}; +var En = function(t, e2, n2) { + return 32 & e2 && n2 || (t &= -33), t; +}; +var wn = function(t, e2, n2, r4) { + const i = et(t.u); + pt(i), t = gn(t, i, n2, e2, 2, true), n2 = r4 != null ? r4 : new n2, t.push(n2), 2 & tt(n2.u) ? Q(t, 8) : Q(t, 16); +}; +var Tn = function(t, e2) { + return t ?? e2; +}; +var An = function(t, e2) { + return Yt(ze(t, e2)); +}; +var bn = function(t, e2) { + return Tn(Ze(t, e2), 0); +}; +var kn = function(t, e2) { + return Tn(re(ze(t, e2)), ""); +}; +var Sn = function(t, e2, n2) { + if (n2 != null && typeof n2 != "boolean") + throw t = typeof n2, Error(`Expected boolean but got ${t != "object" ? t : n2 ? Array.isArray(n2) ? "array" : t : "null"}: ${n2}`); + $e(t, e2, n2); +}; +var xn = function(t, e2, n2) { + if (n2 != null) { + if (typeof n2 != "number") + throw V("int32"); + if (!Number.isFinite(n2)) + throw V("int32"); + n2 |= 0; + } + $e(t, e2, n2); +}; +var Ln = function(t, e2, n2) { + if (n2 != null && typeof n2 != "number") + throw Error(`Value of float/double field must be a number, found ${typeof n2}: ${n2}`); + $e(t, e2, n2); +}; +var Rn = function(t, e2, n2) { + { + const a = t.u; + let h = et(a); + if (pt(h), n2 == null) + qe(a, h, e2); + else { + n2 = he?.get(n2) || n2; + var r4, i = tt(n2), s = i, o = !!(2 & i) || Object.isFrozen(n2); + if ((r4 = !o) && (r4 = vt === undefined || false), We(t, i)) { + i = 21, o && (n2 = H(n2), s = 0, i = En(i = vn(i, h), h, true)); + for (let t2 = 0;t2 < n2.length; t2++) + n2[t2] = ee(n2[t2]); + } + r4 ? (n2 = H(n2), s = 0, i = En(i = vn(i, h), h, true)) : o || _e(n2, t), i !== s && nt(n2, i), qe(a, h, e2, n2); + } + } +}; +var Fn = function(t, e2, n2) { + pt(et(t.u)), en(t, e2, re, 2, undefined, true).push(ee(n2)); +}; +var Mn = function(t, e2) { + return Error(`Invalid wire type: ${t} (at position ${e2})`); +}; +var In = function() { + return Error("Failed to read varint, encoding is invalid."); +}; +var Pn = function(t, e2) { + return Error(`Tried to read past the end of the data ${e2} > ${t}`); +}; +var On = function(t) { + if (typeof t == "string") + return { buffer: M(t), O: false }; + if (Array.isArray(t)) + return { buffer: new Uint8Array(t), O: false }; + if (t.constructor === Uint8Array) + return { buffer: t, O: false }; + if (t.constructor === ArrayBuffer) + return { buffer: new Uint8Array(t), O: false }; + if (t.constructor === D) + return { buffer: U(t) || new Uint8Array(0), O: true }; + if (t instanceof Uint8Array) + return { buffer: new Uint8Array(t.buffer, t.byteOffset, t.byteLength), O: false }; + throw Error("Type not convertible to a Uint8Array, expected a Uint8Array, an ArrayBuffer, a base64 encoded string, a ByteString or an Array of numbers"); +}; +var Cn = function(t, e2) { + let n2, r4 = 0, i = 0, s = 0; + const o = t.h; + let a = t.g; + do { + n2 = o[a++], r4 |= (127 & n2) << s, s += 7; + } while (s < 32 && 128 & n2); + for (s > 32 && (i |= (127 & n2) >> 4), s = 3;s < 32 && 128 & n2; s += 7) + n2 = o[a++], i |= (127 & n2) << s; + if (Xn(t, a), n2 < 128) + return e2(r4 >>> 0, i >>> 0); + throw In(); +}; +var Nn = function(t) { + let e2 = 0, n2 = t.g; + const r4 = n2 + 10, i = t.h; + for (;n2 < r4; ) { + const r5 = i[n2++]; + if (e2 |= r5, (128 & r5) == 0) + return Xn(t, n2), !!(127 & e2); + } + throw In(); +}; +var Un = function(t) { + const e2 = t.h; + let n2 = t.g, r4 = e2[n2++], i = 127 & r4; + if (128 & r4 && (r4 = e2[n2++], i |= (127 & r4) << 7, 128 & r4 && (r4 = e2[n2++], i |= (127 & r4) << 14, 128 & r4 && (r4 = e2[n2++], i |= (127 & r4) << 21, 128 & r4 && (r4 = e2[n2++], i |= r4 << 28, 128 & r4 && 128 & e2[n2++] && 128 & e2[n2++] && 128 & e2[n2++] && 128 & e2[n2++] && 128 & e2[n2++]))))) + throw In(); + return Xn(t, n2), i; +}; +var Dn = function(t) { + return Un(t) >>> 0; +}; +var Bn = function(t) { + var e2 = t.h; + const n2 = t.g, r4 = e2[n2], i = e2[n2 + 1], s = e2[n2 + 2]; + return e2 = e2[n2 + 3], Xn(t, t.g + 4), (r4 << 0 | i << 8 | s << 16 | e2 << 24) >>> 0; +}; +var Gn = function(t) { + var e2 = Bn(t); + t = 2 * (e2 >> 31) + 1; + const n2 = e2 >>> 23 & 255; + return e2 &= 8388607, n2 == 255 ? e2 ? NaN : t * (1 / 0) : n2 == 0 ? 0.000000000000000000000000000000000000000000001401298464324817 * t * e2 : t * Math.pow(2, n2 - 150) * (e2 + 8388608); +}; +var jn = function(t) { + return Un(t); +}; +var Vn = function(t, e2, { ea: n2 = false } = {}) { + t.ea = n2, e2 && (e2 = On(e2), t.h = e2.buffer, t.m = e2.O, t.j = 0, t.l = t.h.length, t.g = t.j); +}; +var Xn = function(t, e2) { + if (t.g = e2, e2 > t.l) + throw Pn(t.l, e2); +}; +var Hn = function(t, e2) { + if (e2 < 0) + throw Error(`Tried to read a negative byte length: ${e2}`); + const n2 = t.g, r4 = n2 + e2; + if (r4 > t.l) + throw Pn(e2, t.l - n2); + return t.g = r4, n2; +}; +var Wn = function(t, e2) { + if (e2 == 0) + return N(); + var n2 = Hn(t, e2); + return t.ea && t.m ? n2 = t.h.subarray(n2, n2 + e2) : (t = t.h, n2 = n2 === (e2 = n2 + e2) ? new Uint8Array(0) : Mt ? t.slice(n2, e2) : new Uint8Array(t.subarray(n2, e2))), n2.length == 0 ? N() : new D(n2, P); +}; +var Kn = function(t) { + var e2 = t.g; + if (e2.g == e2.l) + return false; + t.l = t.g.g; + var n2 = Dn(t.g); + if (e2 = n2 >>> 3, !((n2 &= 7) >= 0 && n2 <= 5)) + throw Mn(n2, t.l); + if (e2 < 1) + throw Error(`Invalid field number: ${e2} (at position ${t.l})`); + return t.m = e2, t.h = n2, true; +}; +var Yn = function(t) { + switch (t.h) { + case 0: + t.h != 0 ? Yn(t) : Nn(t.g); + break; + case 1: + Xn(t = t.g, t.g + 8); + break; + case 2: + if (t.h != 2) + Yn(t); + else { + var e2 = Dn(t.g); + Xn(t = t.g, t.g + e2); + } + break; + case 5: + Xn(t = t.g, t.g + 4); + break; + case 3: + for (e2 = t.m;; ) { + if (!Kn(t)) + throw Error("Unmatched start-group tag: stream EOF"); + if (t.h == 4) { + if (t.m != e2) + throw Error("Unmatched end-group tag"); + break; + } + Yn(t); + } + break; + default: + throw Mn(t.h, t.l); + } +}; +var $n = function(t, e2, n2) { + const r4 = t.g.l, i = Dn(t.g), s = t.g.g + i; + let o = s - r4; + if (o <= 0 && (t.g.l = s, n2(e2, t, undefined, undefined, undefined), o = s - t.g.g), o) + throw Error(`Message parsing ended unexpectedly. Expected to read ${i} bytes, instead read ${i - o} bytes, either the data ended unexpectedly or the message misreported its own length`); + return t.g.g = s, t.g.l = r4, e2; +}; +var qn = function(t) { + var e2 = Dn(t.g), a = Hn(t = t.g, e2); + if (t = t.h, o) { + var h, c2 = t; + (h = s) || (h = s = new TextDecoder("utf-8", { fatal: true })), e2 = a + e2, c2 = a === 0 && e2 === c2.length ? c2 : c2.subarray(a, e2); + try { + var u = h.decode(c2); + } catch (t2) { + if (i === undefined) { + try { + h.decode(new Uint8Array([128])); + } catch (t3) { + } + try { + h.decode(new Uint8Array([97])), i = true; + } catch (t3) { + i = false; + } + } + throw !i && (s = undefined), t2; + } + } else { + e2 = (u = a) + e2, a = []; + let i, s = null; + for (;u < e2; ) { + var l = t[u++]; + l < 128 ? a.push(l) : l < 224 ? u >= e2 ? n() : (i = t[u++], l < 194 || (192 & i) != 128 ? (u--, n()) : a.push((31 & l) << 6 | 63 & i)) : l < 240 ? u >= e2 - 1 ? n() : (i = t[u++], (192 & i) != 128 || l === 224 && i < 160 || l === 237 && i >= 160 || (192 & (h = t[u++])) != 128 ? (u--, n()) : a.push((15 & l) << 12 | (63 & i) << 6 | 63 & h)) : l <= 244 ? u >= e2 - 2 ? n() : (i = t[u++], (192 & i) != 128 || i - 144 + (l << 28) >> 30 != 0 || (192 & (h = t[u++])) != 128 || (192 & (c2 = t[u++])) != 128 ? (u--, n()) : (l = (7 & l) << 18 | (63 & i) << 12 | (63 & h) << 6 | 63 & c2, l -= 65536, a.push(55296 + (l >> 10 & 1023), 56320 + (1023 & l)))) : n(), a.length >= 8192 && (s = r3(s, a), a.length = 0); + } + u = r3(s, a); + } + return u; +}; +var Jn = function(t) { + const e2 = Dn(t.g); + return Wn(t.g, e2); +}; +var Zn = function(t, e2, n2) { + var r4 = Dn(t.g); + for (r4 = t.g.g + r4;t.g.g < r4; ) + n2.push(e2(t.g)); +}; +var er = function(t, e2, n2) { + e2.g ? e2.m(t, e2.g, e2.h, n2, true) : e2.m(t, e2.h, n2, true); +}; +var rr = function(t) { + we(t), t = tr ? t.u : De(t.u, Ge, undefined, undefined, false); + { + var e2 = !tr; + let c2 = t.length; + if (c2) { + var n2 = t[c2 - 1], r4 = ut(n2); + r4 ? c2-- : n2 = undefined; + var i = t; + if (r4) { + t: { + var s, o = n2, a = false; + if (o) + for (let t2 in o) + isNaN(+t2) ? (s ??= {})[t2] = o[t2] : (r4 = o[t2], Array.isArray(r4) && (ft(r4) || ct(r4) && r4.size === 0) && (r4 = null), r4 == null && (a = true), r4 != null && ((s ??= {})[t2] = r4)); + if (a || (s = o), s) + for (let t2 in s) { + a = s; + break t; + } + a = null; + } + o = a == null ? n2 != null : a !== n2; + } + for (;c2 > 0 && ((s = i[c2 - 1]) == null || ft(s) || ct(s) && s.size === 0); c2--) + var h = true; + (i !== t || o || h) && (e2 ? (h || o || a) && (i.length = c2) : i = Array.prototype.slice.call(i, 0, c2), a && i.push(a)), h = i; + } else + h = t; + } + return h; +}; +var ir = function(t) { + return t ? /^\d+$/.test(t) ? (Vt(t), new sr(Pt, Ot)) : null : or ||= new sr(0, 0); +}; +var ar = function(t) { + return t ? /^-?\d+$/.test(t) ? (Vt(t), new hr(Pt, Ot)) : null : cr ||= new hr(0, 0); +}; +var ur = function(t, e2, n2) { + for (;n2 > 0 || e2 > 127; ) + t.g.push(127 & e2 | 128), e2 = (e2 >>> 7 | n2 << 25) >>> 0, n2 >>>= 7; + t.g.push(e2); +}; +var lr = function(t, e2) { + for (;e2 > 127; ) + t.g.push(127 & e2 | 128), e2 >>>= 7; + t.g.push(e2); +}; +var fr = function(t, e2) { + if (e2 >= 0) + lr(t, e2); + else { + for (let n2 = 0;n2 < 9; n2++) + t.g.push(127 & e2 | 128), e2 >>= 7; + t.g.push(1); + } +}; +var dr = function(t, e2) { + t.g.push(e2 >>> 0 & 255), t.g.push(e2 >>> 8 & 255), t.g.push(e2 >>> 16 & 255), t.g.push(e2 >>> 24 & 255); +}; +var pr = function(t, e2) { + e2.length !== 0 && (t.l.push(e2), t.h += e2.length); +}; +var gr = function(t, e2, n2) { + lr(t.g, 8 * e2 + n2); +}; +var mr = function(t, e2) { + return gr(t, e2, 2), e2 = t.g.end(), pr(t, e2), e2.push(t.h), e2; +}; +var yr = function(t, e2) { + var n2 = e2.pop(); + for (n2 = t.h + t.g.length() - n2;n2 > 127; ) + e2.push(127 & n2 | 128), n2 >>>= 7, t.h++; + e2.push(n2), t.h++; +}; +var _r = function(t, e2, n2) { + gr(t, e2, 2), lr(t.g, n2.length), pr(t, t.g.end()), pr(t, n2); +}; +var vr = function(t, e2, n2, r4) { + n2 != null && (e2 = mr(t, e2), r4(n2, t), yr(t, e2)); +}; +var wr = function(t) { + return Array.isArray(t) ? t[0] instanceof Er ? t : [gi, t] : [t, undefined]; +}; +var Tr = function(t, e2) { + if (Array.isArray(e2)) { + var n2 = tt(e2); + if (4 & n2) + return e2; + for (var r4 = 0, i = 0;r4 < e2.length; r4++) { + const n3 = t(e2[r4]); + n3 != null && (e2[i++] = n3); + } + return i < r4 && (e2.length = i), nt(e2, -12289 & (5 | n2)), 2 & n2 && Object.freeze(e2), e2; + } +}; +var br = function(t) { + let e2 = t[Ar]; + if (!e2) { + const n2 = Ur(t), r4 = n2.h; + e2 = r4 ? (t2, e3) => r4(t2, e3, n2) : (t2, e3) => { + for (;Kn(e3) && e3.h != 4; ) { + var r5 = e3.m; + let o = n2[r5]; + const a = !o; + let h = false; + if (!o) { + var i = n2.X; + if (i) { + var s = i[r5]; + s && (h = i.P?.[r5], (!d || h) && (i = kr(s)) && (o = n2[r5] = i)); + } + } + o && o(e3, t2, r5) || (r5 = (i = e3).l, Yn(i), i.ja ? i = undefined : (s = i.g.g - r5, i.g.g = r5, i = Wn(i.g, s)), r5 = t2, i && (mt ||= Symbol(), (s = r5[mt]) ? s.push(i) : r5[mt] = [i])), a && o && !h && Wr++ < 5 && j(); + } + }, t[Ar] = e2; + } + return e2; +}; +var kr = function(t) { + const e2 = (t = wr(t))[0].g; + if (t = t[1]) { + const n2 = br(t), r4 = Ur(t).g; + return (t2, i, s) => e2(t2, i, s, r4, n2); + } + return e2; +}; +var Sr = function(t, e2, n2) { + t[e2] = n2; +}; +var xr = function(t, e2, n2, r4) { + var i = Sr; + e2.g = function(t2) { + switch (typeof t2) { + case "boolean": + return pe ||= [0, undefined, true]; + case "number": + return t2 > 0 ? undefined : t2 === 0 ? ge ||= [0, undefined] : [-t2, undefined]; + case "string": + return [0, t2]; + case "object": + return t2; + } + }(t[0]); + let s = 0; + var o = t[++s]; + o && o.constructor === Object && (e2.X = o, typeof (o = t[++s]) == "function" && (e2.h = o, e2.l = t[++s], o = t[++s])); + const a = {}; + for (;Array.isArray(o) && typeof o[0] == "number" && o[0] > 0; ) { + for (var h = 0;h < o.length; h++) + a[o[h]] = o; + o = t[++s]; + } + for (h = 1;o !== undefined; ) { + let l; + typeof o == "number" && (h += o, o = t[++s]); + var c2 = undefined; + if (o instanceof Er ? l = o : (l = mi, s--), l.qa) { + o = t[++s], c2 = t; + var u = s; + typeof o == "function" && (o = o(), c2[u] = o), c2 = o; + } + for (u = h + 1, typeof (o = t[++s]) == "number" && o < 0 && (u -= o, o = t[++s]);h < u; h++) { + const t2 = a[h]; + i(e2, h, c2 ? r4(l, c2, t2) : n2(l, t2)); + } + } + return e2; +}; +var Rr = function(t) { + let e2 = t[Lr]; + if (!e2) { + const n2 = Pr(t); + e2 = (t2, e3) => Br(t2, e3, n2), t[Lr] = e2; + } + return e2; +}; +var Mr = function(t) { + return t.h; +}; +var Ir = function(t, e2) { + let n2, r4; + const i = t.h; + return (t2, s, o) => i(t2, s, o, r4 ||= Pr(e2).g, n2 ||= Rr(e2)); +}; +var Pr = function(t) { + let e2 = t[Fr]; + return e2 || (e2 = xr(t, t[Fr] = {}, Mr, Ir)); +}; +var Cr = function(t, e2) { + const n2 = t.g; + return e2 ? (t2, r4, i) => n2(t2, r4, i, e2) : n2; +}; +var Nr = function(t, e2, n2) { + const r4 = t.g; + let i, s; + return (t2, o, a) => r4(t2, o, a, s ||= Ur(e2).g, i ||= br(e2), n2); +}; +var Ur = function(t) { + let e2 = t[Or]; + return e2 || (e2 = xr(t, t[Or] = {}, Cr, Nr)); +}; +var Dr = function(t, e2) { + var n2 = t[e2]; + if (n2) + return n2; + if (n2 = t.X) { + var r4 = n2[e2]; + if (r4) { + var i = (r4 = wr(r4))[0].h; + if (r4 = r4[1], n2 = n2.P?.[e2], !d || n2) { + if (r4) { + const e3 = Rr(r4), s = Pr(r4).g; + n2 = (n2 = t.l) ? n2(s, e3) : (t2, n3, r5) => i(t2, n3, r5, s, e3); + } else + n2 = i; + return t[e2] = n2; + } + } + } +}; +var Br = function(t, e2, n2) { + for (var r4 = et(t), i = +!!(512 & r4) - 1, s = t.length, o = 512 & r4 ? 1 : 0, a = s + (256 & r4 ? -1 : 0);o < a; o++) { + const r5 = t[o]; + if (r5 == null) + continue; + const s2 = o - i, a2 = Dr(n2, s2); + if (!a2) + continue; + const h = n2.X; + h?.[s2] && !h?.P?.[s2] && Wr++ < 5 && j(), a2(e2, r5, s2); + } + if (256 & r4) { + r4 = t[s - 1]; + for (let t2 in r4) + i = +t2, !Number.isNaN(i) && ((s = r4[t2]) != null && (a = Dr(n2, i))) && ((o = n2.X)?.[i] && !o?.P?.[i] && Wr++ < 5 && j(), a(e2, s, i)); + } + if (t = mt ? t[mt] : undefined) + for (pr(e2, e2.g.end()), n2 = 0;n2 < t.length; n2++) + pr(e2, U(t[n2]) || new Uint8Array(0)); +}; +var Gr = function(t, e2) { + return new Er(t, e2, false); +}; +var jr = function(t, e2) { + return new Er(t, e2, false); +}; +var Vr = function(t, e2) { + return new Er(t, e2, true); +}; +var Xr = function(t, e2, n2) { + qe(t, et(t), e2, n2); +}; +var zr = function(t, e2, n2) { + if (e2 = function(t2) { + if (t2 == null) + return t2; + const e3 = typeof t2; + if (e3 === "bigint") + return String(BigInt.asIntN(64, t2)); + if (Kt(t2)) { + if (e3 === "string") + return Zt(t2); + if (e3 === "number") + return Jt(t2); + } + }(e2), e2 != null) { + if (typeof e2 == "string") + ar(e2); + if (e2 != null) + switch (gr(t, n2, 0), typeof e2) { + case "number": + t = t.g, Nt(e2), ur(t, Pt, Ot); + break; + case "bigint": + n2 = BigInt.asUintN(64, e2), n2 = new hr(Number(n2 & BigInt(4294967295)), Number(n2 >> BigInt(32))), ur(t.g, n2.h, n2.g); + break; + default: + n2 = ar(e2), ur(t.g, n2.h, n2.g); + } + } +}; +var Kr = function(t, e2, n2) { + (e2 = Yt(e2)) != null && e2 != null && (gr(t, n2, 0), fr(t.g, e2)); +}; +var Yr = function(t, e2, n2) { + (e2 = Wt(e2)) != null && (gr(t, n2, 0), t.g.g.push(e2 ? 1 : 0)); +}; +var $r = function(t, e2, n2) { + (e2 = re(e2)) != null && _r(t, n2, c(e2)); +}; +var qr = function(t, e2, n2, r4, i) { + e2 instanceof nr ? (we(e2), e2 = e2.u) : e2 = Array.isArray(e2) ? Ae(e2, r4) : undefined, vr(t, n2, e2, i); +}; +var Jr = function(t, e2, n2) { + (e2 = e2 == null || typeof e2 == "string" || I(e2) || e2 instanceof D ? e2 : undefined) != null && _r(t, n2, On(e2).buffer); +}; +var Zr = function(t, e2, n2) { + return (t.h === 5 || t.h === 2) && (e2 = Je(e2, et(e2), n2, 2, false), t.h == 2 ? Zn(t, Gn, e2) : e2.push(Gn(t.g)), true); +}; +var Ti = function(t, e2) { + return new wi(t, e2); +}; +var Ai = function(t, e2) { + return (n2, r4) => { + if (Qn.length) { + const t2 = Qn.pop(); + t2.o(r4), Vn(t2.g, n2, r4), n2 = t2; + } else + n2 = new class { + constructor(t2, e3) { + if (zn.length) { + const n3 = zn.pop(); + Vn(n3, t2, e3), t2 = n3; + } else + t2 = new class { + constructor(t3, e4) { + this.h = null, this.m = false, this.g = this.l = this.j = 0, Vn(this, t3, e4); + } + clear() { + this.h = null, this.m = false, this.g = this.l = this.j = 0, this.ea = false; + } + }(t2, e3); + this.g = t2, this.l = this.g.g, this.h = this.m = -1, this.o(e3); + } + o({ ja: t2 = false } = {}) { + this.ja = t2; + } + }(n2, r4); + try { + const r5 = new t, s = r5.u; + br(e2)(s, n2); + var i = r5; + } finally { + n2.g.clear(), n2.m = -1, n2.h = -1, Qn.length < 100 && Qn.push(n2); + } + return i; + }; +}; +var bi = function(t) { + return function() { + we(this); + const e2 = new class { + constructor() { + this.l = [], this.h = 0, this.g = new class { + constructor() { + this.g = []; + } + length() { + return this.g.length; + } + end() { + const t2 = this.g; + return this.g = [], t2; + } + }; + } + }; + Br(this.u, e2, Pr(t)), pr(e2, e2.g.end()); + const n2 = new Uint8Array(e2.h), r4 = e2.l, i = r4.length; + let s = 0; + for (let t2 = 0;t2 < i; t2++) { + const e3 = r4[t2]; + n2.set(e3, s), s += e3.length; + } + return e2.l = [n2], n2; + }; +}; +var Bi = function(t, e2) { + an(t, 2, ne(e2), ""); +}; +var Gi = function(t, e2) { + Fn(t, 3, e2); +}; +var ji = function(t, e2) { + Fn(t, 4, e2); +}; +var zi = function(t, e2) { + wn(t, 1, Vi, e2); +}; +var Ki = function(t, e2) { + Fn(t, 10, e2); +}; +var Yi = function(t, e2) { + Fn(t, 15, e2); +}; +var So = function(t, e2) { + return e2 = e2 ? e2.clone() : new Es, t.displayNamesLocale !== undefined ? $e(e2, 1, ne(t.displayNamesLocale)) : t.displayNamesLocale === undefined && $e(e2, 1), t.maxResults !== undefined ? xn(e2, 2, t.maxResults) : ("maxResults" in t) && $e(e2, 2), t.scoreThreshold !== undefined ? Ln(e2, 3, t.scoreThreshold) : ("scoreThreshold" in t) && $e(e2, 3), t.categoryAllowlist !== undefined ? Rn(e2, 4, t.categoryAllowlist) : ("categoryAllowlist" in t) && $e(e2, 4), t.categoryDenylist !== undefined ? Rn(e2, 5, t.categoryDenylist) : ("categoryDenylist" in t) && $e(e2, 5), e2; +}; +var xo = function(t, e2 = -1, n2 = "") { + return { categories: t.map((t2) => ({ index: Tn(An(t2, 1), 0) ?? -1, score: bn(t2, 2) ?? 0, categoryName: kn(t2, 3) ?? "", displayName: kn(t2, 4) ?? "" })), headIndex: e2, headName: n2 }; +}; +var Lo = function(t) { + var e2 = en(t, 3, Ht, tn()), n2 = en(t, 2, Yt, tn()), r4 = en(t, 1, re, tn()), i = en(t, 9, re, tn()); + const s = { categories: [], keypoints: [] }; + for (let t2 = 0;t2 < e2.length; t2++) + s.categories.push({ score: e2[t2], index: n2[t2] ?? -1, categoryName: r4[t2] ?? "", displayName: i[t2] ?? "" }); + if ((e2 = pn(t, is, 4)?.h()) && (s.boundingBox = { originX: An(e2, 1) ?? 0, originY: An(e2, 2) ?? 0, width: An(e2, 3) ?? 0, height: An(e2, 4) ?? 0, angle: 0 }), pn(t, is, 4)?.g().length) + for (const e3 of pn(t, is, 4).g()) + s.keypoints.push({ x: Ze(e3, 1) ?? 0, y: Ze(e3, 2) ?? 0, score: Ze(e3, 4) ?? 0, label: re(ze(e3, 3)) ?? "" }); + return s; +}; +var Ro = function(t) { + const e2 = []; + for (const n2 of mn(t, hs, 1)) + e2.push({ x: bn(n2, 1) ?? 0, y: bn(n2, 2) ?? 0, z: bn(n2, 3) ?? 0, visibility: bn(n2, 4) ?? 0 }); + return e2; +}; +var Fo = function(t) { + const e2 = []; + for (const n2 of mn(t, os, 1)) + e2.push({ x: bn(n2, 1) ?? 0, y: bn(n2, 2) ?? 0, z: bn(n2, 3) ?? 0, visibility: bn(n2, 4) ?? 0 }); + return e2; +}; +var Mo = function(t) { + return Array.from(t, (t2) => t2 > 127 ? t2 - 256 : t2); +}; +var Io = function(t, e2) { + if (t.length !== e2.length) + throw Error(`Cannot compute cosine similarity between embeddings of different sizes (${t.length} vs. ${e2.length}).`); + let n2 = 0, r4 = 0, i = 0; + for (let s = 0;s < t.length; s++) + n2 += t[s] * e2[s], r4 += t[s] * t[s], i += e2[s] * e2[s]; + if (r4 <= 0 || i <= 0) + throw Error("Cannot compute cosine similarity on embedding with 0 norm."); + return n2 / Math.sqrt(r4 * i); +}; +async function Co() { + if (Po === undefined) + try { + await WebAssembly.instantiate(Oo), Po = true; + } catch { + Po = false; + } + return Po; +} +async function No(t, e2 = "") { + const n2 = await Co() ? "wasm_internal" : "wasm_nosimd_internal"; + return { wasmLoaderPath: `${e2}/${t}_${n2}.js`, wasmBinaryPath: `${e2}/${t}_${n2}.wasm` }; +} +var Do = function() { + var t = navigator; + return typeof OffscreenCanvas != "undefined" && (!function(t2 = navigator) { + return (t2 = t2.userAgent).includes("Safari") && !t2.includes("Chrome"); + }(t) || !!((t = t.userAgent.match(/Version\/([\d]+).*Safari/)) && t.length >= 1 && Number(t[1]) >= 17)); +}; +async function Bo(t) { + if (typeof importScripts != "function") { + const e2 = document.createElement("script"); + return e2.src = t.toString(), e2.crossOrigin = "anonymous", new Promise((t2, n2) => { + e2.addEventListener("load", () => { + t2(); + }, false), e2.addEventListener("error", (t3) => { + n2(t3); + }, false), document.body.appendChild(e2); + }); + } + importScripts(t.toString()); +} +var Go = function(t) { + return t.videoWidth !== undefined ? [t.videoWidth, t.videoHeight] : t.naturalWidth !== undefined ? [t.naturalWidth, t.naturalHeight] : t.displayWidth !== undefined ? [t.displayWidth, t.displayHeight] : [t.width, t.height]; +}; +var jo = function(t, e2, n2) { + t.m || console.error("No wasm multistream support detected: ensure dependency inclusion of :gl_graph_runner_internal_multi_input target"), n2(e2 = t.i.stringToNewUTF8(e2)), t.i._free(e2); +}; +var Vo = function(t, e2, n2) { + if (!t.i.canvas) + throw Error("No OpenGL canvas configured."); + if (n2 ? t.i._bindTextureToStream(n2) : t.i._bindTextureToCanvas(), !(n2 = t.i.canvas.getContext("webgl2") || t.i.canvas.getContext("webgl"))) + throw Error("Failed to obtain WebGL context from the provided canvas. `getContext()` should only be invoked with `webgl` or `webgl2`."); + t.i.gpuOriginForWebTexturesIsBottomLeft && n2.pixelStorei(n2.UNPACK_FLIP_Y_WEBGL, true), n2.texImage2D(n2.TEXTURE_2D, 0, n2.RGBA, n2.RGBA, n2.UNSIGNED_BYTE, e2), t.i.gpuOriginForWebTexturesIsBottomLeft && n2.pixelStorei(n2.UNPACK_FLIP_Y_WEBGL, false); + const [r4, i] = Go(e2); + return !t.l || r4 === t.i.canvas.width && i === t.i.canvas.height || (t.i.canvas.width = r4, t.i.canvas.height = i), [r4, i]; +}; +var Xo = function(t, e2, n2) { + t.m || console.error("No wasm multistream support detected: ensure dependency inclusion of :gl_graph_runner_internal_multi_input target"); + const r4 = new Uint32Array(e2.length); + for (let n3 = 0;n3 < e2.length; n3++) + r4[n3] = t.i.stringToNewUTF8(e2[n3]); + e2 = t.i._malloc(4 * r4.length), t.i.HEAPU32.set(r4, e2 >> 2), n2(e2); + for (const e3 of r4) + t.i._free(e3); + t.i._free(e2); +}; +var Ho = function(t, e2, n2) { + t.i.simpleListeners = t.i.simpleListeners || {}, t.i.simpleListeners[e2] = n2; +}; +var Wo = function(t, e2, n2) { + let r4 = []; + t.i.simpleListeners = t.i.simpleListeners || {}, t.i.simpleListeners[e2] = (t2, e3, i) => { + e3 ? (n2(r4, i), r4 = []) : r4.push(t2); + }; +}; +async function zo(t, e2, n2, r4) { + return t = await (async (t2, e3, n3, r5, i) => { + if (e3 && await Bo(e3), !self.ModuleFactory) + throw Error("ModuleFactory not set."); + if (n3 && (await Bo(n3), !self.ModuleFactory)) + throw Error("ModuleFactory not set."); + return self.Module && i && ((e3 = self.Module).locateFile = i.locateFile, i.mainScriptUrlOrBlob && (e3.mainScriptUrlOrBlob = i.mainScriptUrlOrBlob)), i = await self.ModuleFactory(self.Module || i), self.ModuleFactory = self.Module = undefined, new t2(i, r5); + })(t, n2.wasmLoaderPath, n2.assetLoaderPath, e2, { locateFile: (t2) => t2.endsWith(".wasm") ? n2.wasmBinaryPath.toString() : n2.assetBinaryPath && t2.endsWith(".data") ? n2.assetBinaryPath.toString() : t2 }), await t.o(r4), t; +} +var Ko = function(t, e2) { + const n2 = pn(t.baseOptions, Ss, 1) || new Ss; + typeof e2 == "string" ? ($e(n2, 2, ne(e2)), $e(n2, 1)) : e2 instanceof Uint8Array && ($e(n2, 1, lt(e2, false, false)), $e(n2, 2)), yn(t.baseOptions, 0, 1, n2); +}; +var Yo = function(t) { + try { + const e2 = t.H.length; + if (e2 === 1) + throw Error(t.H[0].message); + if (e2 > 1) + throw Error("Encountered multiple errors: " + t.H.map((t2) => t2.message).join(", ")); + } finally { + t.H = []; + } +}; +var $o = function(t, e2) { + t.B = Math.max(t.B, e2); +}; +var qo = function(t, e2) { + t.A = new Vi, Bi(t.A, "PassThroughCalculator"), Gi(t.A, "free_memory"), ji(t.A, "free_memory_unused_out"), Ki(e2, "free_memory"), zi(e2, t.A); +}; +var Jo = function(t, e2) { + Gi(t.A, e2), ji(t.A, e2 + "_unused_out"); +}; +var Zo = function(t) { + t.g.addBoolToStream(true, "free_memory", t.B); +}; +var ta = function(t, e2) { + if (!t) + throw Error(`Unable to obtain required WebGL resource: ${e2}`); + return t; +}; +var na = function(t, e2, n2) { + const r4 = t.g; + if (n2 = ta(r4.createShader(n2), "Failed to create WebGL shader"), r4.shaderSource(n2, e2), r4.compileShader(n2), !r4.getShaderParameter(n2, r4.COMPILE_STATUS)) + throw Error(`Could not compile WebGL shader: ${r4.getShaderInfoLog(n2)}`); + return r4.attachShader(t.h, n2), n2; +}; +var ra = function(t, e2) { + const n2 = t.g, r4 = ta(n2.createVertexArray(), "Failed to create vertex array"); + n2.bindVertexArray(r4); + const i = ta(n2.createBuffer(), "Failed to create buffer"); + n2.bindBuffer(n2.ARRAY_BUFFER, i), n2.enableVertexAttribArray(t.R), n2.vertexAttribPointer(t.R, 2, n2.FLOAT, false, 0, 0), n2.bufferData(n2.ARRAY_BUFFER, new Float32Array([-1, -1, -1, 1, 1, 1, 1, -1]), n2.STATIC_DRAW); + const s = ta(n2.createBuffer(), "Failed to create buffer"); + return n2.bindBuffer(n2.ARRAY_BUFFER, s), n2.enableVertexAttribArray(t.J), n2.vertexAttribPointer(t.J, 2, n2.FLOAT, false, 0, 0), n2.bufferData(n2.ARRAY_BUFFER, new Float32Array(e2 ? [0, 1, 0, 0, 1, 0, 1, 1] : [0, 0, 0, 1, 1, 1, 1, 0]), n2.STATIC_DRAW), n2.bindBuffer(n2.ARRAY_BUFFER, null), n2.bindVertexArray(null), new ea(n2, r4, i, s); +}; +var ia = function(t, e2) { + if (t.g) { + if (e2 !== t.g) + throw Error("Cannot change GL context once initialized"); + } else + t.g = e2; +}; +var sa = function(t, e2, n2, r4) { + return ia(t, e2), t.h || (t.m(), t.C()), n2 ? (t.s || (t.s = ra(t, true)), n2 = t.s) : (t.v || (t.v = ra(t, false)), n2 = t.v), e2.useProgram(t.h), n2.bind(), t.l(), t = r4(), n2.g.bindVertexArray(null), t; +}; +var oa = function(t, e2, n2) { + return ia(t, e2), t = ta(e2.createTexture(), "Failed to create texture"), e2.bindTexture(e2.TEXTURE_2D, t), e2.texParameteri(e2.TEXTURE_2D, e2.TEXTURE_WRAP_S, e2.CLAMP_TO_EDGE), e2.texParameteri(e2.TEXTURE_2D, e2.TEXTURE_WRAP_T, e2.CLAMP_TO_EDGE), e2.texParameteri(e2.TEXTURE_2D, e2.TEXTURE_MIN_FILTER, n2 ?? e2.LINEAR), e2.texParameteri(e2.TEXTURE_2D, e2.TEXTURE_MAG_FILTER, n2 ?? e2.LINEAR), e2.bindTexture(e2.TEXTURE_2D, null), t; +}; +var aa = function(t, e2, n2) { + ia(t, e2), t.A || (t.A = ta(e2.createFramebuffer(), "Failed to create framebuffe.")), e2.bindFramebuffer(e2.FRAMEBUFFER, t.A), e2.framebufferTexture2D(e2.FRAMEBUFFER, e2.COLOR_ATTACHMENT0, e2.TEXTURE_2D, n2, 0); +}; +var ha = function(t) { + t.g?.bindFramebuffer(t.g.FRAMEBUFFER, null); +}; +var fa = function(t, e2) { + switch (e2) { + case 0: + return t.g.find((t2) => t2 instanceof Uint8Array); + case 1: + return t.g.find((t2) => t2 instanceof Float32Array); + case 2: + return t.g.find((t2) => typeof WebGLTexture != "undefined" && t2 instanceof WebGLTexture); + default: + throw Error(`Type is not supported: ${e2}`); + } +}; +var da = function(t) { + var e2 = fa(t, 1); + if (!e2) { + if (e2 = fa(t, 0)) + e2 = new Float32Array(e2).map((t2) => t2 / 255); + else { + e2 = new Float32Array(t.width * t.height); + const r4 = ga(t); + var n2 = ya(t); + if (aa(n2, r4, pa(t)), "iPad Simulator;iPhone Simulator;iPod Simulator;iPad;iPhone;iPod".split(";").includes(navigator.platform) || navigator.userAgent.includes("Mac") && "ontouchend" in self.document) { + n2 = new Float32Array(t.width * t.height * 4), r4.readPixels(0, 0, t.width, t.height, r4.RGBA, r4.FLOAT, n2); + for (let t2 = 0, r5 = 0;t2 < e2.length; ++t2, r5 += 4) + e2[t2] = n2[r5]; + } else + r4.readPixels(0, 0, t.width, t.height, r4.RED, r4.FLOAT, e2); + } + t.g.push(e2); + } + return e2; +}; +var pa = function(t) { + let e2 = fa(t, 2); + if (!e2) { + const n2 = ga(t); + e2 = _a(t); + const r4 = da(t), i = ma(t); + n2.texImage2D(n2.TEXTURE_2D, 0, i, t.width, t.height, 0, n2.RED, n2.FLOAT, r4), va(t); + } + return e2; +}; +var ga = function(t) { + if (!t.canvas) + throw Error("Conversion to different image formats require that a canvas is passed when initializing the image."); + return t.h || (t.h = ta(t.canvas.getContext("webgl2"), "You cannot use a canvas that is already bound to a different type of rendering context.")), t.h; +}; +var ma = function(t) { + if (t = ga(t), !Ea) + if (t.getExtension("EXT_color_buffer_float") && t.getExtension("OES_texture_float_linear") && t.getExtension("EXT_float_blend")) + Ea = t.R32F; + else { + if (!t.getExtension("EXT_color_buffer_half_float")) + throw Error("GPU does not fully support 4-channel float32 or float16 formats"); + Ea = t.R16F; + } + return Ea; +}; +var ya = function(t) { + return t.l || (t.l = new ca), t.l; +}; +var _a = function(t) { + const e2 = ga(t); + e2.viewport(0, 0, t.width, t.height), e2.activeTexture(e2.TEXTURE0); + let n2 = fa(t, 2); + return n2 || (n2 = oa(ya(t), e2, t.m ? e2.LINEAR : e2.NEAREST), t.g.push(n2), t.j = true), e2.bindTexture(e2.TEXTURE_2D, n2), n2; +}; +var va = function(t) { + t.h.bindTexture(t.h.TEXTURE_2D, null); +}; +var ba = function(t) { + return { ...Aa, fillColor: (t = t || {}).color, ...t }; +}; +var ka = function(t, e2) { + return t instanceof Function ? t(e2) : t; +}; +var Sa = function(t, e2, n2) { + return Math.max(Math.min(e2, n2), Math.min(Math.max(e2, n2), t)); +}; +var xa = function(t) { + if (!t.l) + throw Error("CPU rendering requested but CanvasRenderingContext2D not provided."); + return t.l; +}; +var La = function(t) { + if (!t.j) + throw Error("GPU rendering requested but WebGL2RenderingContext not provided."); + return t.j; +}; +var Ra = function(t, e2, n2) { + if (e2.S()) + n2(e2.N()); + else { + const r4 = e2.ma() ? e2.ka() : e2.la(); + t.m = t.m ?? new ca; + const i = La(t); + n2((t = new wa([r4], e2.m, false, i.canvas, t.m, e2.width, e2.height)).N()), t.close(); + } +}; +var Fa = function(t, e2, n2, r4) { + const i = function(t2) { + return t2.g || (t2.g = new ua), t2.g; + }(t), s = La(t), o = Array.isArray(n2) ? new ImageData(new Uint8ClampedArray(n2), 1, 1) : n2; + sa(i, s, true, () => { + (function(t3, e3, n3, r5) { + const i2 = t3.g; + if (i2.activeTexture(i2.TEXTURE0), i2.bindTexture(i2.TEXTURE_2D, e3), i2.activeTexture(i2.TEXTURE1), i2.bindTexture(i2.TEXTURE_2D, t3.B), i2.texImage2D(i2.TEXTURE_2D, 0, i2.RGBA, i2.RGBA, i2.UNSIGNED_BYTE, n3), t3.I && function(t4, e4) { + if (t4 !== e4) + return false; + t4 = t4.entries(), e4 = e4.entries(); + for (const [r6, i3] of t4) { + t4 = r6; + const s2 = i3; + var n4 = e4.next(); + if (n4.done) + return false; + const [o2, a] = n4.value; + if (n4 = a, t4 !== o2 || s2[0] !== n4[0] || s2[1] !== n4[1] || s2[2] !== n4[2] || s2[3] !== n4[3]) + return false; + } + return !!e4.next().done; + }(t3.I, r5)) + i2.activeTexture(i2.TEXTURE2), i2.bindTexture(i2.TEXTURE_2D, t3.j); + else { + t3.I = r5; + const e4 = Array(1024).fill(0); + r5.forEach((t4, n4) => { + if (t4.length !== 4) + throw Error(`Color at index ${n4} is not a four-channel value.`); + e4[4 * n4] = t4[0], e4[4 * n4 + 1] = t4[1], e4[4 * n4 + 2] = t4[2], e4[4 * n4 + 3] = t4[3]; + }), i2.activeTexture(i2.TEXTURE2), i2.bindTexture(i2.TEXTURE_2D, t3.j), i2.texImage2D(i2.TEXTURE_2D, 0, i2.RGBA, 256, 1, 0, i2.RGBA, i2.UNSIGNED_BYTE, new Uint8Array(e4)); + } + })(i, e2, o, r4), s.clearColor(0, 0, 0, 0), s.clear(s.COLOR_BUFFER_BIT), s.drawArrays(s.TRIANGLE_FAN, 0, 4); + const t2 = i.g; + t2.activeTexture(t2.TEXTURE0), t2.bindTexture(t2.TEXTURE_2D, null), t2.activeTexture(t2.TEXTURE1), t2.bindTexture(t2.TEXTURE_2D, null), t2.activeTexture(t2.TEXTURE2), t2.bindTexture(t2.TEXTURE_2D, null); + }); +}; +var Ma = function(t, e2, n2, r4) { + const i = La(t), s = function(t2) { + return t2.h || (t2.h = new la), t2.h; + }(t), o = Array.isArray(n2) ? new ImageData(new Uint8ClampedArray(n2), 1, 1) : n2, a = Array.isArray(r4) ? new ImageData(new Uint8ClampedArray(r4), 1, 1) : r4; + sa(s, i, true, () => { + var t2 = s.g; + t2.activeTexture(t2.TEXTURE0), t2.bindTexture(t2.TEXTURE_2D, e2), t2.activeTexture(t2.TEXTURE1), t2.bindTexture(t2.TEXTURE_2D, s.j), t2.texImage2D(t2.TEXTURE_2D, 0, t2.RGBA, t2.RGBA, t2.UNSIGNED_BYTE, o), t2.activeTexture(t2.TEXTURE2), t2.bindTexture(t2.TEXTURE_2D, s.B), t2.texImage2D(t2.TEXTURE_2D, 0, t2.RGBA, t2.RGBA, t2.UNSIGNED_BYTE, a), i.clearColor(0, 0, 0, 0), i.clear(i.COLOR_BUFFER_BIT), i.drawArrays(i.TRIANGLE_FAN, 0, 4), i.bindTexture(i.TEXTURE_2D, null), (t2 = s.g).activeTexture(t2.TEXTURE0), t2.bindTexture(t2.TEXTURE_2D, null), t2.activeTexture(t2.TEXTURE1), t2.bindTexture(t2.TEXTURE_2D, null), t2.activeTexture(t2.TEXTURE2), t2.bindTexture(t2.TEXTURE_2D, null); + }); +}; +var Pa = function(t, e2) { + switch (e2) { + case 0: + return t.g.find((t2) => t2 instanceof ImageData); + case 1: + return t.g.find((t2) => typeof ImageBitmap != "undefined" && t2 instanceof ImageBitmap); + case 2: + return t.g.find((t2) => typeof WebGLTexture != "undefined" && t2 instanceof WebGLTexture); + default: + throw Error(`Type is not supported: ${e2}`); + } +}; +var Oa = function(t) { + var e2 = Pa(t, 0); + if (!e2) { + e2 = Na(t); + const n2 = Ua(t), r4 = new Uint8Array(t.width * t.height * 4); + aa(n2, e2, Ca(t)), e2.readPixels(0, 0, t.width, t.height, e2.RGBA, e2.UNSIGNED_BYTE, r4), ha(n2), e2 = new ImageData(new Uint8ClampedArray(r4.buffer), t.width, t.height), t.g.push(e2); + } + return e2; +}; +var Ca = function(t) { + let e2 = Pa(t, 2); + if (!e2) { + const n2 = Na(t); + e2 = Da(t); + const r4 = Pa(t, 1) || Oa(t); + n2.texImage2D(n2.TEXTURE_2D, 0, n2.RGBA, n2.RGBA, n2.UNSIGNED_BYTE, r4), Ba(t); + } + return e2; +}; +var Na = function(t) { + if (!t.canvas) + throw Error("Conversion to different image formats require that a canvas is passed when iniitializing the image."); + return t.h || (t.h = ta(t.canvas.getContext("webgl2"), "You cannot use a canvas that is already bound to a different type of rendering context.")), t.h; +}; +var Ua = function(t) { + return t.l || (t.l = new ca), t.l; +}; +var Da = function(t) { + const e2 = Na(t); + e2.viewport(0, 0, t.width, t.height), e2.activeTexture(e2.TEXTURE0); + let n2 = Pa(t, 2); + return n2 || (n2 = oa(Ua(t), e2), t.g.push(n2), t.m = true), e2.bindTexture(e2.TEXTURE_2D, n2), n2; +}; +var Ba = function(t) { + t.h.bindTexture(t.h.TEXTURE_2D, null); +}; +var Ga = function(t) { + const e2 = Na(t); + return sa(Ua(t), e2, true, () => function(t2, e3) { + const n2 = t2.canvas; + if (n2.width === t2.width && n2.height === t2.height) + return e3(); + const { width: r4, height: i } = n2; + return n2.width = t2.width, n2.height = t2.height, t2 = e3(), n2.width = r4, n2.height = i, t2; + }(t, () => { + if (e2.bindFramebuffer(e2.FRAMEBUFFER, null), e2.clearColor(0, 0, 0, 0), e2.clear(e2.COLOR_BUFFER_BIT), e2.drawArrays(e2.TRIANGLE_FAN, 0, 4), !(t.canvas instanceof OffscreenCanvas)) + throw Error("Conversion to ImageBitmap requires that the MediaPipe Tasks is initialized with an OffscreenCanvas"); + return t.canvas.transferToImageBitmap(); + })); +}; +var Xa = function(...t) { + return t.map(([t2, e2]) => ({ start: t2, end: e2 })); +}; +async function Ka(t, e2, n2) { + return async function(t2, e3, n3, r4) { + return zo(t2, e3, n3, r4); + }(t, n2.canvas ?? (Do() ? undefined : document.createElement("canvas")), e2, n2); +} +var Ya = function(t, e2, n2, r4) { + if (t.V) { + const s = new fs; + if (n2?.regionOfInterest) { + if (!t.sa) + throw Error("This task doesn't support region-of-interest."); + var i = n2.regionOfInterest; + if (i.left >= i.right || i.top >= i.bottom) + throw Error("Expected RectF with left < right and top < bottom."); + if (i.left < 0 || i.top < 0 || i.right > 1 || i.bottom > 1) + throw Error("Expected RectF values to be in [0,1]."); + Ln(s, 1, (i.left + i.right) / 2), Ln(s, 2, (i.top + i.bottom) / 2), Ln(s, 4, i.right - i.left), Ln(s, 3, i.bottom - i.top); + } else + Ln(s, 1, 0.5), Ln(s, 2, 0.5), Ln(s, 4, 1), Ln(s, 3, 1); + if (n2?.rotationDegrees) { + if (n2?.rotationDegrees % 90 != 0) + throw Error("Expected rotation to be a multiple of 90\xB0."); + if (Ln(s, 5, -Math.PI * n2.rotationDegrees / 180), n2?.rotationDegrees % 180 != 0) { + const [t2, r5] = Go(e2); + n2 = bn(s, 3) * r5 / t2, i = bn(s, 4) * t2 / r5, Ln(s, 4, n2), Ln(s, 3, i); + } + } + t.g.addProtoToStream(s.g(), "mediapipe.NormalizedRect", t.V, r4); + } + t.g.ta(e2, t.da, r4 ?? performance.now()), t.finishProcessing(); +}; +var $a = function(t, e2, n2) { + if (t.baseOptions?.g()) + throw Error("Task is not initialized with image mode. 'runningMode' must be set to 'IMAGE'."); + Ya(t, e2, n2, t.B + 1); +}; +var qa = function(t, e2, n2, r4) { + if (!t.baseOptions?.g()) + throw Error("Task is not initialized with video mode. 'runningMode' must be set to 'VIDEO'."); + Ya(t, e2, n2, r4); +}; +var Ja = function(t, e2, n2, r4) { + var i = e2.data; + const s = e2.width, o = s * (e2 = e2.height); + if ((i instanceof Uint8Array || i instanceof Float32Array) && i.length !== o) + throw Error("Unsupported channel count: " + i.length / o); + return t = new wa([i], n2, false, t.g.i.canvas, t.R, s, e2), r4 ? t.clone() : t; +}; +var uh = function(t) { + t.j = { faceLandmarks: [], faceBlendshapes: [], facialTransformationMatrixes: [] }; +}; +var ph = function(t) { + t.gestures = [], t.landmarks = [], t.worldLandmarks = [], t.handedness = []; +}; +var gh = function(t) { + return t.gestures.length === 0 ? { gestures: [], landmarks: [], worldLandmarks: [], handedness: [], handednesses: [] } : { gestures: t.gestures, landmarks: t.landmarks, worldLandmarks: t.worldLandmarks, handedness: t.handedness, handednesses: t.handedness }; +}; +var mh = function(t, e2 = true) { + const n2 = []; + for (const i of t) { + var r4 = es(i); + t = []; + for (const n3 of r4.g()) + r4 = e2 && An(n3, 1) != null ? Tn(An(n3, 1), 0) : -1, t.push({ score: bn(n3, 2) ?? 0, index: r4, categoryName: kn(n3, 3) ?? "", displayName: kn(n3, 4) ?? "" }); + n2.push(t); + } + return n2; +}; +var _h = function(t) { + return { landmarks: t.landmarks, worldLandmarks: t.worldLandmarks, handednesses: t.handedness, handedness: t.handedness }; +}; +var wh = function(t) { + t.h = { faceLandmarks: [], faceBlendshapes: [], poseLandmarks: [], poseWorldLandmarks: [], poseSegmentationMasks: [], leftHandLandmarks: [], leftHandWorldLandmarks: [], rightHandLandmarks: [], rightHandWorldLandmarks: [] }; +}; +var Th = function(t) { + try { + if (!t.C) + return t.h; + t.C(t.h); + } finally { + Zo(t); + } +}; +var Ah = function(t, e2) { + t = cs(t), e2.push(Ro(t)); +}; +var Lh = function(t) { + t.categoryMask = undefined, t.confidenceMasks = undefined, t.qualityScores = undefined; +}; +var Rh = function(t) { + try { + const e2 = new xh(t.confidenceMasks, t.categoryMask, t.qualityScores); + if (!t.j) + return e2; + t.j(e2); + } finally { + Zo(t); + } +}; +var zh = function(t) { + t.landmarks = [], t.worldLandmarks = [], t.segmentationMasks = undefined; +}; +var Kh = function(t) { + try { + const e2 = new Wh(t.landmarks, t.worldLandmarks, t.segmentationMasks); + if (!t.s) + return e2; + t.s(e2); + } finally { + Zo(t); + } +}; +var t = typeof self != "undefined" ? self : {}; +var i; +var s; +var o = typeof TextDecoder != "undefined"; +var a; +var h = typeof TextEncoder != "undefined"; +var u; +var l = e(610401301, false); +var f = e(653718497, e(1, true)); +var d = e(660014094, false); +var p = t.navigator; +u = p && p.userAgentData || null, v[" "] = function() { +}; +var E = !y() && (m("Trident") || m("MSIE")); +!m("Android") || _(), _(), m("Safari") && (_() || !y() && m("Coast") || !y() && m("Opera") || !y() && m("Edge") || (y() ? g("Microsoft Edge") : m("Edg/")) || y() && g("Opera")); +var w = {}; +var T = null; +var k = typeof Uint8Array != "undefined"; +var S = !E && typeof btoa == "function"; +var L = /[-_.]/g; +var R = { "-": "+", _: "/", ".": "=" }; +var P = {}; +var O; +var D = class { + constructor(t2, e2) { + if (C(e2), this.ba = t2, t2 != null && t2.length === 0) + throw Error("ByteString should be constructed with non-empty values"); + } + ua() { + return new Uint8Array(U(this) || 0); + } +}; +var G; +var W = typeof Symbol == "function" && typeof Symbol() == "symbol"; +var K = z(); +var Y = z("0di"); +var $ = z("2ex"); +var q = z("1oa"); +var J = z("0dg"); +var Z = W ? (t2, e2) => { + t2[K] |= e2; +} : (t2, e2) => { + t2.G !== undefined ? t2.G |= e2 : Object.defineProperties(t2, { G: { value: e2, configurable: true, writable: true, enumerable: false } }); +}; +var Q = W ? (t2, e2) => { + t2[K] &= ~e2; +} : (t2, e2) => { + t2.G !== undefined && (t2.G &= ~e2); +}; +var tt = W ? (t2) => 0 | t2[K] : (t2) => 0 | t2.G; +var et = W ? (t2) => t2[K] : (t2) => t2.G; +var nt = W ? (t2, e2) => { + t2[K] = e2; +} : (t2, e2) => { + t2.G !== undefined ? t2.G = e2 : Object.defineProperties(t2, { G: { value: e2, configurable: true, writable: true, enumerable: false } }); +}; +var ot; +var at = {}; +var ht = {}; +var dt = []; +nt(dt, 55), ot = Object.freeze(dt); + +class gt { + constructor(t2, e2, n2) { + this.l = 0, this.g = t2, this.h = e2, this.m = n2; + } + next() { + if (this.l < this.g.length) { + const t2 = this.g[this.l++]; + return { done: false, value: this.h ? this.h.call(this.m, t2) : t2 }; + } + return { done: true, value: undefined }; + } + [Symbol.iterator]() { + return new gt(this.g, this.h, this.m); + } +} +var mt; +var _t = Object.freeze({}); +Object.freeze({}); +var vt = Object.freeze({}); +var wt = Et((t2) => typeof t2 == "number"); +var Tt = Et((t2) => typeof t2 == "string"); +var At = Et((t2) => typeof t2 == "boolean"); +var bt = typeof t.BigInt == "function" && typeof t.BigInt(0) == "bigint"; +var kt = Et((t2) => bt ? t2 >= xt && t2 <= Rt : t2[0] === "-" ? Ft(t2, St) : Ft(t2, Lt)); +var St = Number.MIN_SAFE_INTEGER.toString(); +var xt = bt ? BigInt(Number.MIN_SAFE_INTEGER) : undefined; +var Lt = Number.MAX_SAFE_INTEGER.toString(); +var Rt = bt ? BigInt(Number.MAX_SAFE_INTEGER) : undefined; +var Mt = typeof Uint8Array.prototype.slice == "function"; +var It; +var Pt = 0; +var Ot = 0; +var zt = /^-?([1-9][0-9]*|0)(\.[0-9]+)?$/; +var ae; +var he; +var ce; +var ue; +var le; +var fe; +var de; +var pe; +var ge; +var ke = {}; +var Se = function() { + try { + return v(new class extends Map { + constructor() { + super(); + } + }), false; + } catch { + return true; + } +}(); + +class xe { + constructor() { + this.g = new Map; + } + get(t2) { + return this.g.get(t2); + } + set(t2, e2) { + return this.g.set(t2, e2), this.size = this.g.size, this; + } + delete(t2) { + return t2 = this.g.delete(t2), this.size = this.g.size, t2; + } + clear() { + this.g.clear(), this.size = this.g.size; + } + has(t2) { + return this.g.has(t2); + } + entries() { + return this.g.entries(); + } + keys() { + return this.g.keys(); + } + values() { + return this.g.values(); + } + forEach(t2, e2) { + return this.g.forEach(t2, e2); + } + [Symbol.iterator]() { + return this.entries(); + } +} +var Le = Se ? (Object.setPrototypeOf(xe.prototype, Map.prototype), Object.defineProperties(xe.prototype, { size: { value: 0, configurable: true, enumerable: true, writable: true } }), xe) : class extends Map { + constructor() { + super(); + } +}; +var Me = class extends Le { + constructor(t2, e2, n2 = Re, r4 = Re) { + super(); + let i2 = tt(t2); + i2 |= 64, nt(t2, i2), this.M = i2, this.U = e2, this.T = n2, this.aa = this.U ? Ie : r4; + for (let s2 = 0;s2 < t2.length; s2++) { + const o2 = t2[s2], a2 = n2(o2[0], false, true); + let h2 = o2[1]; + e2 ? h2 === undefined && (h2 = null) : h2 = r4(o2[1], false, true, undefined, undefined, i2), super.set(a2, h2); + } + } + pa(t2 = Pe) { + if (this.size !== 0) + return this.Z(t2); + } + Z(t2 = Pe) { + const e2 = [], n2 = super.entries(); + for (var r4;!(r4 = n2.next()).done; ) + (r4 = r4.value)[0] = t2(r4[0]), r4[1] = t2(r4[1]), e2.push(r4); + return e2; + } + clear() { + Fe(this), super.clear(); + } + delete(t2) { + return Fe(this), super.delete(this.T(t2, true, false)); + } + entries() { + var t2 = this.oa(); + return new gt(t2, Oe, this); + } + keys() { + return this.Ka(); + } + values() { + var t2 = this.oa(); + return new gt(t2, Me.prototype.get, this); + } + forEach(t2, e2) { + super.forEach((n2, r4) => { + t2.call(e2, this.get(r4), r4, this); + }); + } + set(t2, e2) { + return Fe(this), (t2 = this.T(t2, true, false)) == null ? this : e2 == null ? (super.delete(t2), this) : super.set(t2, this.aa(e2, true, true, this.U, false, this.M)); + } + Qa(t2) { + const e2 = this.T(t2[0], false, true); + t2 = t2[1], t2 = this.U ? t2 === undefined ? null : t2 : this.aa(t2, false, true, undefined, false, this.M), super.set(e2, t2); + } + has(t2) { + return super.has(this.T(t2, false, false)); + } + get(t2) { + t2 = this.T(t2, false, false); + const e2 = super.get(t2); + if (e2 !== undefined) { + var n2 = this.U; + return n2 ? ((n2 = this.aa(e2, false, true, n2, this.va, this.M)) !== e2 && super.set(t2, n2), n2) : e2; + } + } + oa() { + return Array.from(super.keys()); + } + Ka() { + return super.keys(); + } + [Symbol.iterator]() { + return this.entries(); + } +}; +var Ce; +Me.prototype.toJSON = undefined, Me.prototype.La = ht; +var zn = []; +var Qn = []; +var tr; +var nr = class { + constructor(t2, e2) { + this.u = be(t2, e2); + } + toJSON() { + return rr(this); + } + l() { + var t2 = vo; + return t2.g ? t2.l(this, t2.g, t2.h, true) : t2.l(this, t2.h, t2.defaultValue, true); + } + clone() { + const t2 = this.u; + return Ve(this, t2, et(t2), false); + } + O() { + return !!(2 & tt(this.u)); + } +}; +nr.prototype.Y = at, nr.prototype.toString = function() { + try { + return tr = true, rr(this).toString(); + } finally { + tr = false; + } +}; +var sr = class { + constructor(t2, e2) { + this.h = t2 >>> 0, this.g = e2 >>> 0; + } +}; +var or; +var hr = class { + constructor(t2, e2) { + this.h = t2 >>> 0, this.g = e2 >>> 0; + } +}; +var cr; + +class Er { + constructor(t2, e2, n2) { + this.g = t2, this.h = e2, this.qa = n2; + } +} +var Ar = Symbol(); +var Lr = Symbol(); +var Fr = Symbol(); +var Or = Symbol(); +var Hr = Vr(function(t2, e2, n2, r4, i2) { + return t2.h === 2 && (t2 = $n(t2, Ae([undefined, undefined], r4), i2), pt(r4 = et(e2)), (i2 = Ye(e2, r4, n2)) instanceof Me ? (2 & i2.M) != 0 ? ((i2 = i2.Z()).push(t2), qe(e2, r4, n2, i2)) : i2.Qa(t2) : Array.isArray(i2) ? (2 & tt(i2) && qe(e2, r4, n2, i2 = on(i2)), i2.push(t2)) : qe(e2, r4, n2, [t2]), true); +}, function(t2, e2, n2, r4, i2) { + if (e2 instanceof Me) + e2.forEach((e3, s2) => { + vr(t2, n2, Ae([s2, e3], r4), i2); + }); + else if (Array.isArray(e2)) + for (let s2 = 0;s2 < e2.length; s2++) { + const o2 = e2[s2]; + Array.isArray(o2) && vr(t2, n2, Ae(o2, r4), i2); + } +}); +var Wr = 0; +var Qr; +var ti = Gr(function(t2, e2, n2) { + if (t2.h !== 1) + return false; + var r4 = t2.g; + t2 = Bn(r4); + const i2 = Bn(r4); + r4 = 2 * (i2 >> 31) + 1; + const s2 = i2 >>> 20 & 2047; + return t2 = 4294967296 * (1048575 & i2) + t2, Xr(e2, n2, s2 == 2047 ? t2 ? NaN : r4 * (1 / 0) : s2 == 0 ? 0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005 * r4 * t2 : r4 * Math.pow(2, s2 - 1075) * (t2 + 4503599627370496)), true; +}, function(t2, e2, n2) { + (e2 = Ht(e2)) != null && (gr(t2, n2, 1), t2 = t2.g, (n2 = It ||= new DataView(new ArrayBuffer(8))).setFloat64(0, +e2, true), Pt = n2.getUint32(0, true), Ot = n2.getUint32(4, true), dr(t2, Pt), dr(t2, Ot)); +}); +var ei = Gr(function(t2, e2, n2) { + return t2.h === 5 && (Xr(e2, n2, Gn(t2.g)), true); +}, function(t2, e2, n2) { + (e2 = Ht(e2)) != null && (gr(t2, n2, 5), t2 = t2.g, Ut(e2), dr(t2, Pt)); +}); +var ni = jr(Zr, function(t2, e2, n2) { + if ((e2 = Tr(Ht, e2)) != null) + for (let o2 = 0;o2 < e2.length; o2++) { + var r4 = t2, i2 = n2, s2 = e2[o2]; + s2 != null && (gr(r4, i2, 5), r4 = r4.g, Ut(s2), dr(r4, Pt)); + } +}); +var ri = jr(Zr, function(t2, e2, n2) { + if ((e2 = Tr(Ht, e2)) != null && e2.length) { + gr(t2, n2, 2), lr(t2.g, 4 * e2.length); + for (let r4 = 0;r4 < e2.length; r4++) + n2 = t2.g, Ut(e2[r4]), dr(n2, Pt); + } +}); +var ii = Gr(function(t2, e2, n2) { + return t2.h === 0 && (Xr(e2, n2, Cn(t2.g, Bt)), true); +}, zr); +var si = Gr(function(t2, e2, n2) { + return t2.h === 0 && (Xr(e2, n2, (t2 = Cn(t2.g, Bt)) === 0 ? undefined : t2), true); +}, zr); +var oi = Gr(function(t2, e2, n2) { + return t2.h === 0 && (Xr(e2, n2, Cn(t2.g, Dt)), true); +}, function(t2, e2, n2) { + if ((e2 = te(e2)) != null) { + if (typeof e2 == "string") + ir(e2); + if (e2 != null) + switch (gr(t2, n2, 0), typeof e2) { + case "number": + t2 = t2.g, Nt(e2), ur(t2, Pt, Ot); + break; + case "bigint": + n2 = BigInt.asUintN(64, e2), n2 = new sr(Number(n2 & BigInt(4294967295)), Number(n2 >> BigInt(32))), ur(t2.g, n2.h, n2.g); + break; + default: + n2 = ir(e2), ur(t2.g, n2.h, n2.g); + } + } +}); +var ai = Gr(function(t2, e2, n2) { + return t2.h === 0 && (Xr(e2, n2, Un(t2.g)), true); +}, Kr); +var hi = jr(function(t2, e2, n2) { + return (t2.h === 0 || t2.h === 2) && (e2 = Je(e2, et(e2), n2, 2, false), t2.h == 2 ? Zn(t2, Un, e2) : e2.push(Un(t2.g)), true); +}, function(t2, e2, n2) { + if ((e2 = Tr(Yt, e2)) != null && e2.length) { + n2 = mr(t2, n2); + for (let n3 = 0;n3 < e2.length; n3++) + fr(t2.g, e2[n3]); + yr(t2, n2); + } +}); +var ci = Gr(function(t2, e2, n2) { + return t2.h === 0 && (Xr(e2, n2, (t2 = Un(t2.g)) === 0 ? undefined : t2), true); +}, Kr); +var ui = Gr(function(t2, e2, n2) { + return t2.h === 0 && (Xr(e2, n2, Nn(t2.g)), true); +}, Yr); +var li = Gr(function(t2, e2, n2) { + return t2.h === 0 && (Xr(e2, n2, (t2 = Nn(t2.g)) === false ? undefined : t2), true); +}, Yr); +var fi = jr(function(t2, e2, n2) { + if (t2.h !== 2) + return false; + t2 = qn(t2); + const r4 = et(e2); + return pt(r4), Je(e2, r4, n2, 2).push(t2), true; +}, function(t2, e2, n2) { + if ((e2 = Tr(re, e2)) != null) + for (let o2 = 0;o2 < e2.length; o2++) { + var r4 = t2, i2 = n2, s2 = e2[o2]; + s2 != null && _r(r4, i2, c(s2)); + } +}); +var di = Gr(function(t2, e2, n2) { + return t2.h === 2 && (Xr(e2, n2, (t2 = qn(t2)) === "" ? undefined : t2), true); +}, $r); +var pi = Gr(function(t2, e2, n2) { + return t2.h === 2 && (Xr(e2, n2, qn(t2)), true); +}, $r); +var gi = Vr(function(t2, e2, n2, r4, i2) { + return t2.h === 2 && ($n(t2, fn(e2, r4, n2, true), i2), true); +}, qr); +var mi = Vr(function(t2, e2, n2, r4, i2) { + return t2.h === 2 && ($n(t2, fn(e2, r4, n2), i2), true); +}, qr); +Qr = new Er(function(t2, e2, n2, r4, i2) { + if (t2.h !== 2) + return false; + r4 = Ae(undefined, r4); + let s2 = et(e2); + pt(s2); + let o2 = Je(e2, s2, n2, 3); + return s2 = et(e2), 4 & tt(o2) && (o2 = H(o2), nt(o2, -2079 & (1 | tt(o2))), qe(e2, s2, n2, o2)), o2.push(r4), $n(t2, r4, i2), true; +}, function(t2, e2, n2, r4, i2) { + if (Array.isArray(e2)) + for (let s2 = 0;s2 < e2.length; s2++) + qr(t2, e2[s2], n2, r4, i2); +}, true); +var yi = Vr(function(t2, e2, n2, r4, i2, s2) { + return t2.h === 2 && (un(e2, et(e2), s2, n2), $n(t2, e2 = fn(e2, r4, n2), i2), true); +}, qr); +var _i = Gr(function(t2, e2, n2) { + return t2.h === 2 && (Xr(e2, n2, Jn(t2)), true); +}, Jr); +var vi = jr(function(t2, e2, n2) { + return (t2.h === 0 || t2.h === 2) && (e2 = Je(e2, et(e2), n2, 2, false), t2.h == 2 ? Zn(t2, Dn, e2) : e2.push(Dn(t2.g)), true); +}, function(t2, e2, n2) { + if ((e2 = Tr($t, e2)) != null) + for (let o2 = 0;o2 < e2.length; o2++) { + var r4 = t2, i2 = n2, s2 = e2[o2]; + s2 != null && (gr(r4, i2, 0), lr(r4.g, s2)); + } +}); +var Ei = Gr(function(t2, e2, n2) { + return t2.h === 0 && (Xr(e2, n2, Un(t2.g)), true); +}, function(t2, e2, n2) { + (e2 = Yt(e2)) != null && (e2 = parseInt(e2, 10), gr(t2, n2, 0), fr(t2.g, e2)); +}); + +class wi { + constructor(t2, e2) { + this.h = t2, this.g = e2, this.l = pn, this.m = yn, this.defaultValue = undefined; + } +} +var ki = class extends nr { + constructor(t2) { + super(t2); + } +}; +var Si = [0, di, Gr(function(t2, e2, n2) { + return t2.h === 2 && (Xr(e2, n2, (t2 = Jn(t2)) === N() ? undefined : t2), true); +}, function(t2, e2, n2) { + if (e2 != null) { + if (e2 instanceof nr) { + const r4 = e2.Ta; + return void (r4 && (e2 = r4(e2), e2 != null && _r(t2, n2, On(e2).buffer))); + } + if (Array.isArray(e2)) + return; + } + Jr(t2, e2, n2); +})]; +var xi = [0, ai, Ei, ui, -1, hi, Ei, -1]; +var Li = class extends nr { + constructor() { + super(); + } +}; +var Ri = [0, ui, pi, ui, Ei, -1, jr(function(t2, e2, n2) { + return (t2.h === 0 || t2.h === 2) && (e2 = Je(e2, et(e2), n2, 2, false), t2.h == 2 ? Zn(t2, jn, e2) : e2.push(Un(t2.g)), true); +}, function(t2, e2, n2) { + if ((e2 = Tr(Yt, e2)) != null && e2.length) { + n2 = mr(t2, n2); + for (let n3 = 0;n3 < e2.length; n3++) + fr(t2.g, e2[n3]); + yr(t2, n2); + } +}), pi, -1, [0, ui, -1], Ei, ui, -1]; +var Fi = [0, pi, -2]; +var Mi = class extends nr { + constructor() { + super(); + } +}; +var Ii = [0]; +var Pi = [0, ai, ui, 1, ui, -3]; +var Oi = [0, pi, ui, -1, ai, [0, [1, 2, 3, 4, 5, 6, 7], yi, Ii, yi, Ri, yi, Fi, yi, Pi, yi, xi, yi, [0, pi, -2], yi, [0, pi, Ei]], [0, pi], ui, [0, [1, 3], [2, 4], yi, [0, hi], -1, yi, [0, fi], -1, Qr, [0, pi, -1]], pi]; +var Ci = class extends nr { + constructor(t2) { + super(t2, 2); + } +}; +var Ni = {}; +var Ui = Ni.P = {}; +Ni[336783863] = Oi, Ui[336783863] = 1; +var Di = [0, si, -1, li, -3, si, hi, di, ci, si, -1, li, ci, li, -2, di]; +var Vi = class extends nr { + constructor(t2) { + super(t2, 500); + } + o(t2) { + return yn(this, 0, 7, t2); + } +}; +var Xi = [-1, { P: {} }]; +var Hi = [0, pi, 1, Xi]; +var Wi = [0, pi, fi, Xi]; +var $i = class extends nr { + constructor(t2) { + super(t2, 500); + } + o(t2) { + return yn(this, 0, 1001, t2); + } +}; +var qi = [-500, Qr, [-500, di, -1, fi, -3, [-2, Ni, ui], Qr, Si, ci, -1, Hi, Wi, Qr, [0, di, li], di, Di, ci, fi, 987, fi], 4, Qr, [-500, pi, -1, [-1, { P: {} }], 998, pi], Qr, [-500, pi, fi, -1, [-2, { P: {} }, ui], 997, fi, -1], ci, Qr, [-500, pi, fi, Xi, 998, fi], fi, ci, Hi, Wi, Qr, [0, di, -1, Xi], fi, -2, Di, di, -1, li, 979, Xi, Qr, Si]; +$i.prototype.g = bi(qi); +var Ji = Ai($i, qi); +var Zi = class extends nr { + constructor(t2) { + super(t2); + } +}; +var Qi = class extends nr { + constructor(t2) { + super(t2); + } + g() { + return mn(this, Zi, 1); + } +}; +var ts = [0, Qr, [0, ai, ei, pi, -1]]; +var es = Ai(Qi, ts); +var ns = class extends nr { + constructor(t2) { + super(t2); + } +}; +var rs = class extends nr { + constructor(t2) { + super(t2); + } +}; +var is = class extends nr { + constructor(t2) { + super(t2); + } + h() { + return pn(this, ns, 2); + } + g() { + return mn(this, rs, 5); + } +}; +var ss = Ai(class extends nr { + constructor(t2) { + super(t2); + } +}, [0, fi, hi, ri, [0, Ei, [0, ai, -3], [0, ei, -3], [0, ai, -1, [0, Qr, [0, ai, -2]]], Qr, [0, ei, -1, pi, ei]], pi, -1, ii, Qr, [0, ai, ei], fi, ii]); +var os = class extends nr { + constructor(t2) { + super(t2); + } +}; +var as = Ai(class extends nr { + constructor(t2) { + super(t2); + } +}, [0, Qr, [0, ei, -4]]); +var hs = class extends nr { + constructor(t2) { + super(t2); + } +}; +var cs = Ai(class extends nr { + constructor(t2) { + super(t2); + } +}, [0, Qr, [0, ei, -4]]); +var us = class extends nr { + constructor(t2) { + super(t2); + } +}; +var ls = [0, ai, -1, ri, Ei]; +var fs = class extends nr { + constructor() { + super(); + } +}; +fs.prototype.g = bi([0, ei, -4, ii]); +var ds = class extends nr { + constructor(t2) { + super(t2); + } +}; +var ps = Ai(class extends nr { + constructor(t2) { + super(t2); + } +}, [0, Qr, [0, 1, ai, pi, ts], ii]); +var gs = class extends nr { + constructor(t2) { + super(t2); + } +}; +var ms = class extends nr { + constructor(t2) { + super(t2); + } + ra() { + const t2 = Qe(this); + return t2 == null ? N() : t2; + } +}; +var ys = class extends nr { + constructor(t2) { + super(t2); + } +}; +var _s = [1, 2]; +var vs = Ai(class extends nr { + constructor(t2) { + super(t2); + } +}, [0, Qr, [0, _s, yi, [0, ri], yi, [0, _i], ai, pi], ii]); +var Es = class extends nr { + constructor(t2) { + super(t2); + } +}; +var ws = [0, pi, ai, ei, fi, -1]; +var Ts = class extends nr { + constructor(t2) { + super(t2); + } +}; +var As = [0, ui, -1]; +var bs = class extends nr { + constructor(t2) { + super(t2); + } +}; +var ks = [1, 2, 3, 4, 5]; +var Ss = class extends nr { + constructor(t2) { + super(t2); + } + g() { + return Qe(this) != null; + } + h() { + return re(ze(this, 2)) != null; + } +}; +var xs = class extends nr { + constructor(t2) { + super(t2); + } + g() { + return Wt(ze(this, 2)) ?? false; + } +}; +var Ls = [0, _i, pi, [0, ai, ii, -1], [0, oi, ii]]; +var Rs = [0, Ls, ui, [0, ks, yi, Pi, yi, Ri, yi, xi, yi, Ii, yi, Fi], Ei]; +var Fs = class extends nr { + constructor(t2) { + super(t2); + } +}; +var Ms = [0, Rs, ei, -1, ai]; +var Is = Ti(502141897, Fs); +Ni[502141897] = Ms, Ui[502141897] = 1; +var Ps = [0, Ls]; +Ni[512499200] = Ps; +var Os = [0, Ps]; +Ni[515723506] = Os; +var Cs = Ai(class extends nr { + constructor(t2) { + super(t2); + } +}, [0, [0, Ei, -1, ni, vi], ls]); +var Ns = [0, Rs]; +Ni[508981768] = Ns; +var Us = class extends nr { + constructor(t2) { + super(t2); + } +}; +var Ds = class extends nr { + constructor(t2) { + super(t2); + } +}; +var Bs = [0, Rs, ei, Ns, ui]; +var Gs = [0, Rs, Ms, Bs, ei, Os]; +Ni[508968149] = Bs; +var js = Ti(508968150, Ds); +Ni[508968150] = Gs, Ui[508968150] = 1, Ui[508968149] = 1; +var Vs = class extends nr { + constructor(t2) { + super(t2); + } +}; +var Xs = Ti(513916220, Vs); +Ni[513916220] = [0, Rs, Gs, ai], Ui[513916220] = 1; +var Hs = class extends nr { + constructor(t2) { + super(t2); + } + h() { + return pn(this, Es, 2); + } + g() { + $e(this, 2); + } +}; +var Ws = [0, Rs, ws]; +Ni[478825465] = Ws, Ui[478825465] = 1; +var zs = [0, Rs]; +Ni[478825422] = zs; +var Ks = class extends nr { + constructor(t2) { + super(t2); + } +}; +var Ys = class extends nr { + constructor(t2) { + super(t2); + } +}; +var $s = class extends nr { + constructor(t2) { + super(t2); + } +}; +var qs = class extends nr { + constructor(t2) { + super(t2); + } +}; +var Js = class extends nr { + constructor(t2) { + super(t2); + } +}; +var Zs = [0, Rs, zs, Ws, -1]; +var Qs = [0, Rs, ei, ai]; +var to = [0, Rs, ei]; +var eo = [0, Rs, Qs, to, ei]; +var no = [0, Rs, eo, Zs]; +Ni[463370452] = Zs, Ni[464864288] = Qs, Ni[474472470] = to; +var ro = Ti(462713202, qs); +Ni[462713202] = eo; +var io = Ti(479097054, Js); +Ni[479097054] = no, Ui[479097054] = 1, Ui[463370452] = 1, Ui[464864288] = 1, Ui[462713202] = 1, Ui[474472470] = 1; +var so = class extends nr { + constructor(t2) { + super(t2); + } +}; +var oo = class extends nr { + constructor(t2) { + super(t2); + } +}; +var ao = class extends nr { + constructor(t2) { + super(t2); + } +}; +var ho = class extends nr { + constructor() { + super(); + } +}; +var co = [0, Rs, ei, -1, ai]; +var uo = [0, Rs, ei, ui]; +ho.prototype.g = bi([0, Rs, to, [0, Rs], Ms, Bs, co, uo]), Ni[514774813] = co, Ni[518928384] = uo; +var lo = class extends nr { + constructor(t2) { + super(t2); + } +}; +var fo = Ti(456383383, lo); +Ni[456383383] = [0, Rs, ws], Ui[456383383] = 1; +var po = class extends nr { + constructor(t2) { + super(t2); + } +}; +var go = Ti(476348187, po); +Ni[476348187] = [0, Rs, As], Ui[476348187] = 1; +var mo = class extends nr { + constructor(t2) { + super(t2); + } +}; +var yo = class extends nr { + constructor(t2) { + super(t2); + } +}; +var _o = [0, Ei, -1]; +var vo = Ti(458105876, class extends nr { + constructor(t2) { + super(t2); + } + g() { + var t2 = this.u; + const e2 = et(t2); + const n2 = 2 & e2; + return t2 = function(t3, e3, n3) { + var r4 = yo; + const i2 = 2 & e3; + let s2 = false; + if (n3 == null) { + if (i2) + return Ne(); + n3 = []; + } else if (n3.constructor === Me) { + if ((2 & n3.M) == 0 || i2) + return n3; + n3 = n3.Z(); + } else + Array.isArray(n3) ? s2 = !!(2 & tt(n3)) : n3 = []; + if (i2) { + if (!n3.length) + return Ne(); + s2 || (s2 = true, rt(n3)); + } else + s2 && (s2 = false, n3 = on(n3)); + return s2 || (64 & tt(n3) ? Q(n3, 32) : 32 & e3 && Z(n3, 32)), qe(t3, e3, 2, r4 = new Me(n3, r4, se, undefined)), r4; + }(t2, e2, Ye(t2, e2, 2)), !n2 && yo && (t2.va = true), t2; + } +}); +Ni[458105876] = [0, _o, Hr, [true, ii, [0, pi, -1, fi]]], Ui[458105876] = 1; +var Eo = class extends nr { + constructor(t2) { + super(t2); + } +}; +var wo = Ti(458105758, Eo); +Ni[458105758] = [0, Rs, pi, _o], Ui[458105758] = 1; +var To = class extends nr { + constructor(t2) { + super(t2); + } +}; +var Ao = Ti(443442058, To); +Ni[443442058] = [0, Rs, pi, ai, ei, fi, -1], Ui[443442058] = 1, Ui[514774813] = 1; +var bo = class extends nr { + constructor(t2) { + super(t2); + } +}; +var ko = Ti(516587230, bo); +var Po; +Ni[516587230] = [0, Rs, co, uo, ei], Ui[516587230] = 1, Ui[518928384] = 1; +var Oo = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 5, 1, 96, 0, 1, 123, 3, 2, 1, 0, 10, 10, 1, 8, 0, 65, 0, 253, 15, 253, 98, 11]); +var Uo = class { +}; +Uo.forVisionTasks = function(t2) { + return No("vision", t2); +}, Uo.forTextTasks = function(t2) { + return No("text", t2); +}, Uo.forGenAiExperimentalTasks = function(t2) { + return No("genai_experimental", t2); +}, Uo.forGenAiTasks = function(t2) { + return No("genai", t2); +}, Uo.forAudioTasks = function(t2) { + return No("audio", t2); +}, Uo.isSimdSupported = function() { + return Co(); +}; +var Qo = class { + constructor(t2) { + this.g = t2, this.H = [], this.B = 0, this.g.setAutoRenderToScreen(false); + } + l(t2, e2 = true) { + if (e2) { + const e3 = t2.baseOptions || {}; + if (t2.baseOptions?.modelAssetBuffer && t2.baseOptions?.modelAssetPath) + throw Error("Cannot set both baseOptions.modelAssetPath and baseOptions.modelAssetBuffer"); + if (!(pn(this.baseOptions, Ss, 1)?.g() || pn(this.baseOptions, Ss, 1)?.h() || t2.baseOptions?.modelAssetBuffer || t2.baseOptions?.modelAssetPath)) + throw Error("Either baseOptions.modelAssetPath or baseOptions.modelAssetBuffer must be set"); + if (function(t3, e4) { + let n2 = pn(t3.baseOptions, bs, 3); + if (!n2) { + var r4 = n2 = new bs, i2 = new Mi; + _n(r4, 4, ks, i2); + } + "delegate" in e4 && (e4.delegate === "GPU" ? (e4 = n2, r4 = new Li, _n(e4, 2, ks, r4)) : (e4 = n2, r4 = new Mi, _n(e4, 4, ks, r4))), yn(t3.baseOptions, 0, 3, n2); + }(this, e3), e3.modelAssetPath) + return fetch(e3.modelAssetPath.toString()).then((t3) => { + if (t3.ok) + return t3.arrayBuffer(); + throw Error(`Failed to fetch model: ${e3.modelAssetPath} (${t3.status})`); + }).then((t3) => { + try { + this.g.i.FS_unlink("/model.dat"); + } catch { + } + this.g.i.FS_createDataFile("/", "model.dat", new Uint8Array(t3), true, false, false), Ko(this, "/model.dat"), this.m(), this.J(); + }); + if (e3.modelAssetBuffer instanceof Uint8Array) + Ko(this, e3.modelAssetBuffer); + else if (e3.modelAssetBuffer) + return async function(t3) { + const e4 = []; + for (var n2 = 0;; ) { + const { done: r4, value: i2 } = await t3.read(); + if (r4) + break; + e4.push(i2), n2 += i2.length; + } + if (e4.length === 0) + return new Uint8Array(0); + if (e4.length === 1) + return e4[0]; + t3 = new Uint8Array(n2), n2 = 0; + for (const r4 of e4) + t3.set(r4, n2), n2 += r4.length; + return t3; + }(e3.modelAssetBuffer).then((t3) => { + Ko(this, t3), this.m(), this.J(); + }); + } + return this.m(), this.J(), Promise.resolve(); + } + J() { + } + ga() { + let t2; + if (this.g.ga((e2) => { + t2 = Ji(e2); + }), !t2) + throw Error("Failed to retrieve CalculatorGraphConfig"); + return t2; + } + setGraph(t2, e2) { + this.g.attachErrorListener((t3, e3) => { + this.H.push(Error(e3)); + }), this.g.Oa(), this.g.setGraph(t2, e2), this.A = undefined, Yo(this); + } + finishProcessing() { + this.g.finishProcessing(), Yo(this); + } + close() { + this.A = undefined, this.g.closeGraph(); + } +}; +Qo.prototype.close = Qo.prototype.close, function(e2, n2) { + e2 = e2.split("."); + var r4, i2 = t; + e2[0] in i2 || i2.execScript === undefined || i2.execScript("var " + e2[0]); + for (;e2.length && (r4 = e2.shift()); ) + e2.length || n2 === undefined ? i2 = i2[r4] && i2[r4] !== Object.prototype[r4] ? i2[r4] : i2[r4] = {} : i2[r4] = n2; +}("TaskRunner", Qo); + +class ea { + constructor(t2, e2, n2, r4) { + this.g = t2, this.h = e2, this.m = n2, this.l = r4; + } + bind() { + this.g.bindVertexArray(this.h); + } + close() { + this.g.deleteVertexArray(this.h), this.g.deleteBuffer(this.m), this.g.deleteBuffer(this.l); + } +} +var ca = class { + H() { + return "\n precision mediump float;\n varying vec2 vTex;\n uniform sampler2D inputTexture;\n void main() {\n gl_FragColor = texture2D(inputTexture, vTex);\n }\n "; + } + m() { + const t2 = this.g; + if (this.h = ta(t2.createProgram(), "Failed to create WebGL program"), this.da = na(this, "\n attribute vec2 aVertex;\n attribute vec2 aTex;\n varying vec2 vTex;\n void main(void) {\n gl_Position = vec4(aVertex, 0.0, 1.0);\n vTex = aTex;\n }", t2.VERTEX_SHADER), this.ca = na(this, this.H(), t2.FRAGMENT_SHADER), t2.linkProgram(this.h), !t2.getProgramParameter(this.h, t2.LINK_STATUS)) + throw Error(`Error during program linking: ${t2.getProgramInfoLog(this.h)}`); + this.R = t2.getAttribLocation(this.h, "aVertex"), this.J = t2.getAttribLocation(this.h, "aTex"); + } + C() { + } + l() { + } + close() { + if (this.h) { + const t2 = this.g; + t2.deleteProgram(this.h), t2.deleteShader(this.da), t2.deleteShader(this.ca); + } + this.A && this.g.deleteFramebuffer(this.A), this.v && this.v.close(), this.s && this.s.close(); + } +}; +var ua = class extends ca { + H() { + return "\n precision mediump float;\n uniform sampler2D backgroundTexture;\n uniform sampler2D maskTexture;\n uniform sampler2D colorMappingTexture;\n varying vec2 vTex;\n void main() {\n vec4 backgroundColor = texture2D(backgroundTexture, vTex);\n float category = texture2D(maskTexture, vTex).r;\n vec4 categoryColor = texture2D(colorMappingTexture, vec2(category, 0.0));\n gl_FragColor = mix(backgroundColor, categoryColor, categoryColor.a);\n }\n "; + } + C() { + const t2 = this.g; + t2.activeTexture(t2.TEXTURE1), this.B = oa(this, t2, t2.LINEAR), t2.activeTexture(t2.TEXTURE2), this.j = oa(this, t2, t2.NEAREST); + } + m() { + super.m(); + const t2 = this.g; + this.L = ta(t2.getUniformLocation(this.h, "backgroundTexture"), "Uniform location"), this.V = ta(t2.getUniformLocation(this.h, "colorMappingTexture"), "Uniform location"), this.K = ta(t2.getUniformLocation(this.h, "maskTexture"), "Uniform location"); + } + l() { + super.l(); + const t2 = this.g; + t2.uniform1i(this.K, 0), t2.uniform1i(this.L, 1), t2.uniform1i(this.V, 2); + } + close() { + this.B && this.g.deleteTexture(this.B), this.j && this.g.deleteTexture(this.j), super.close(); + } +}; +var la = class extends ca { + H() { + return "\n precision mediump float;\n uniform sampler2D maskTexture;\n uniform sampler2D defaultTexture;\n uniform sampler2D overlayTexture;\n varying vec2 vTex;\n void main() {\n float confidence = texture2D(maskTexture, vTex).r;\n vec4 defaultColor = texture2D(defaultTexture, vTex);\n vec4 overlayColor = texture2D(overlayTexture, vTex);\n // Apply the alpha from the overlay and merge in the default color\n overlayColor = mix(defaultColor, overlayColor, overlayColor.a);\n gl_FragColor = mix(defaultColor, overlayColor, confidence);\n }\n "; + } + C() { + const t2 = this.g; + t2.activeTexture(t2.TEXTURE1), this.j = oa(this, t2), t2.activeTexture(t2.TEXTURE2), this.B = oa(this, t2); + } + m() { + super.m(); + const t2 = this.g; + this.K = ta(t2.getUniformLocation(this.h, "defaultTexture"), "Uniform location"), this.L = ta(t2.getUniformLocation(this.h, "overlayTexture"), "Uniform location"), this.I = ta(t2.getUniformLocation(this.h, "maskTexture"), "Uniform location"); + } + l() { + super.l(); + const t2 = this.g; + t2.uniform1i(this.I, 0), t2.uniform1i(this.K, 1), t2.uniform1i(this.L, 2); + } + close() { + this.j && this.g.deleteTexture(this.j), this.B && this.g.deleteTexture(this.B), super.close(); + } +}; +var Ea; +var wa = class { + constructor(t2, e2, n2, r4, i2, s2, o2) { + this.g = t2, this.m = e2, this.j = n2, this.canvas = r4, this.l = i2, this.width = s2, this.height = o2, this.j && (--Ta === 0 && console.error("You seem to be creating MPMask instances without invoking .close(). This leaks resources.")); + } + Ja() { + return !!fa(this, 0); + } + ma() { + return !!fa(this, 1); + } + S() { + return !!fa(this, 2); + } + la() { + return (e2 = fa(t2 = this, 0)) || (e2 = da(t2), e2 = new Uint8Array(e2.map((t3) => 255 * t3)), t2.g.push(e2)), e2; + var t2, e2; + } + ka() { + return da(this); + } + N() { + return pa(this); + } + clone() { + const t2 = []; + for (const e2 of this.g) { + let n2; + if (e2 instanceof Uint8Array) + n2 = new Uint8Array(e2); + else if (e2 instanceof Float32Array) + n2 = new Float32Array(e2); + else { + if (!(e2 instanceof WebGLTexture)) + throw Error(`Type is not supported: ${e2}`); + { + const t3 = ga(this), e3 = ya(this); + t3.activeTexture(t3.TEXTURE1), n2 = oa(e3, t3, this.m ? t3.LINEAR : t3.NEAREST), t3.bindTexture(t3.TEXTURE_2D, n2); + const r4 = ma(this); + t3.texImage2D(t3.TEXTURE_2D, 0, r4, this.width, this.height, 0, t3.RED, t3.FLOAT, null), t3.bindTexture(t3.TEXTURE_2D, null), aa(e3, t3, n2), sa(e3, t3, false, () => { + _a(this), t3.clearColor(0, 0, 0, 0), t3.clear(t3.COLOR_BUFFER_BIT), t3.drawArrays(t3.TRIANGLE_FAN, 0, 4), va(this); + }), ha(e3), va(this); + } + } + t2.push(n2); + } + return new wa(t2, this.m, this.S(), this.canvas, this.l, this.width, this.height); + } + close() { + this.j && ga(this).deleteTexture(fa(this, 2)), Ta = -1; + } +}; +wa.prototype.close = wa.prototype.close, wa.prototype.clone = wa.prototype.clone, wa.prototype.getAsWebGLTexture = wa.prototype.N, wa.prototype.getAsFloat32Array = wa.prototype.ka, wa.prototype.getAsUint8Array = wa.prototype.la, wa.prototype.hasWebGLTexture = wa.prototype.S, wa.prototype.hasFloat32Array = wa.prototype.ma, wa.prototype.hasUint8Array = wa.prototype.Ja; +var Ta = 250; +var Aa = { color: "white", lineWidth: 4, radius: 6 }; +var Ia = class { + constructor(t2, e2) { + t2 instanceof CanvasRenderingContext2D || t2 instanceof OffscreenCanvasRenderingContext2D ? (this.l = t2, this.j = e2) : this.j = t2; + } + Ca(t2, e2) { + if (t2) { + var n2 = xa(this); + e2 = ba(e2), n2.save(); + var r4 = n2.canvas, i2 = 0; + for (const s2 of t2) + n2.fillStyle = ka(e2.fillColor, { index: i2, from: s2 }), n2.strokeStyle = ka(e2.color, { index: i2, from: s2 }), n2.lineWidth = ka(e2.lineWidth, { index: i2, from: s2 }), (t2 = new Path2D).arc(s2.x * r4.width, s2.y * r4.height, ka(e2.radius, { index: i2, from: s2 }), 0, 2 * Math.PI), n2.fill(t2), n2.stroke(t2), ++i2; + n2.restore(); + } + } + Ba(t2, e2, n2) { + if (t2 && e2) { + var r4 = xa(this); + n2 = ba(n2), r4.save(); + var i2 = r4.canvas, s2 = 0; + for (const o2 of e2) { + r4.beginPath(), e2 = t2[o2.start]; + const a2 = t2[o2.end]; + e2 && a2 && (r4.strokeStyle = ka(n2.color, { index: s2, from: e2, to: a2 }), r4.lineWidth = ka(n2.lineWidth, { index: s2, from: e2, to: a2 }), r4.moveTo(e2.x * i2.width, e2.y * i2.height), r4.lineTo(a2.x * i2.width, a2.y * i2.height)), ++s2, r4.stroke(); + } + r4.restore(); + } + } + ya(t2, e2) { + const n2 = xa(this); + e2 = ba(e2), n2.save(), n2.beginPath(), n2.lineWidth = ka(e2.lineWidth, {}), n2.strokeStyle = ka(e2.color, {}), n2.fillStyle = ka(e2.fillColor, {}), n2.moveTo(t2.originX, t2.originY), n2.lineTo(t2.originX + t2.width, t2.originY), n2.lineTo(t2.originX + t2.width, t2.originY + t2.height), n2.lineTo(t2.originX, t2.originY + t2.height), n2.lineTo(t2.originX, t2.originY), n2.stroke(), n2.fill(), n2.restore(); + } + za(t2, e2, n2 = [0, 0, 0, 255]) { + this.l ? function(t3, e3, n3, r4) { + const i2 = La(t3); + Ra(t3, e3, (e4) => { + Fa(t3, e4, n3, r4), (e4 = xa(t3)).drawImage(i2.canvas, 0, 0, e4.canvas.width, e4.canvas.height); + }); + }(this, t2, n2, e2) : Fa(this, t2.N(), n2, e2); + } + Aa(t2, e2, n2) { + this.l ? function(t3, e3, n3, r4) { + const i2 = La(t3); + Ra(t3, e3, (e4) => { + Ma(t3, e4, n3, r4), (e4 = xa(t3)).drawImage(i2.canvas, 0, 0, e4.canvas.width, e4.canvas.height); + }); + }(this, t2, e2, n2) : Ma(this, t2.N(), e2, n2); + } + close() { + this.g?.close(), this.g = undefined, this.h?.close(), this.h = undefined, this.m?.close(), this.m = undefined; + } +}; +Ia.prototype.close = Ia.prototype.close, Ia.prototype.drawConfidenceMask = Ia.prototype.Aa, Ia.prototype.drawCategoryMask = Ia.prototype.za, Ia.prototype.drawBoundingBox = Ia.prototype.ya, Ia.prototype.drawConnectors = Ia.prototype.Ba, Ia.prototype.drawLandmarks = Ia.prototype.Ca, Ia.lerp = function(t2, e2, n2, r4, i2) { + return Sa(r4 * (1 - (t2 - e2) / (n2 - e2)) + i2 * (1 - (n2 - t2) / (n2 - e2)), r4, i2); +}, Ia.clamp = Sa; +var ja = class { + constructor(t2, e2, n2, r4, i2, s2, o2) { + this.g = t2, this.j = e2, this.m = n2, this.canvas = r4, this.l = i2, this.width = s2, this.height = o2, (this.j || this.m) && (--Va === 0 && console.error("You seem to be creating MPImage instances without invoking .close(). This leaks resources.")); + } + Ia() { + return !!Pa(this, 0); + } + na() { + return !!Pa(this, 1); + } + S() { + return !!Pa(this, 2); + } + Ga() { + return Oa(this); + } + Fa() { + var t2 = Pa(this, 1); + return t2 || (Ca(this), Da(this), t2 = Ga(this), Ba(this), this.g.push(t2), this.j = true), t2; + } + N() { + return Ca(this); + } + clone() { + const t2 = []; + for (const e2 of this.g) { + let n2; + if (e2 instanceof ImageData) + n2 = new ImageData(e2.data, this.width, this.height); + else if (e2 instanceof WebGLTexture) { + const t3 = Na(this), e3 = Ua(this); + t3.activeTexture(t3.TEXTURE1), n2 = oa(e3, t3), t3.bindTexture(t3.TEXTURE_2D, n2), t3.texImage2D(t3.TEXTURE_2D, 0, t3.RGBA, this.width, this.height, 0, t3.RGBA, t3.UNSIGNED_BYTE, null), t3.bindTexture(t3.TEXTURE_2D, null), aa(e3, t3, n2), sa(e3, t3, false, () => { + Da(this), t3.clearColor(0, 0, 0, 0), t3.clear(t3.COLOR_BUFFER_BIT), t3.drawArrays(t3.TRIANGLE_FAN, 0, 4), Ba(this); + }), ha(e3), Ba(this); + } else { + if (!(e2 instanceof ImageBitmap)) + throw Error(`Type is not supported: ${e2}`); + Ca(this), Da(this), n2 = Ga(this), Ba(this); + } + t2.push(n2); + } + return new ja(t2, this.na(), this.S(), this.canvas, this.l, this.width, this.height); + } + close() { + this.j && Pa(this, 1).close(), this.m && Na(this).deleteTexture(Pa(this, 2)), Va = -1; + } +}; +ja.prototype.close = ja.prototype.close, ja.prototype.clone = ja.prototype.clone, ja.prototype.getAsWebGLTexture = ja.prototype.N, ja.prototype.getAsImageBitmap = ja.prototype.Fa, ja.prototype.getAsImageData = ja.prototype.Ga, ja.prototype.hasWebGLTexture = ja.prototype.S, ja.prototype.hasImageBitmap = ja.prototype.na, ja.prototype.hasImageData = ja.prototype.Ia; +var Va = 250; +var Ha = function(t2) { + return class extends t2 { + Oa() { + this.i._registerModelResourcesGraphService(); + } + }; +}((Wa = class { + constructor(t2, e2) { + this.l = true, this.i = t2, this.g = null, this.h = 0, this.m = typeof this.i._addIntToInputStream == "function", e2 !== undefined ? this.i.canvas = e2 : Do() ? this.i.canvas = new OffscreenCanvas(1, 1) : (console.warn("OffscreenCanvas not supported and GraphRunner constructor glCanvas parameter is undefined. Creating backup canvas."), this.i.canvas = document.createElement("canvas")); + } + async initializeGraph(t2) { + const e2 = await (await fetch(t2)).arrayBuffer(); + t2 = !(t2.endsWith(".pbtxt") || t2.endsWith(".textproto")), this.setGraph(new Uint8Array(e2), t2); + } + setGraphFromString(t2) { + this.setGraph(new TextEncoder().encode(t2), false); + } + setGraph(t2, e2) { + const n2 = t2.length, r4 = this.i._malloc(n2); + this.i.HEAPU8.set(t2, r4), e2 ? this.i._changeBinaryGraph(n2, r4) : this.i._changeTextGraph(n2, r4), this.i._free(r4); + } + configureAudio(t2, e2, n2, r4, i2) { + this.i._configureAudio || console.warn('Attempting to use configureAudio without support for input audio. Is build dep ":gl_graph_runner_audio" missing?'), jo(this, r4 || "input_audio", (r5) => { + jo(this, i2 = i2 || "audio_header", (i3) => { + this.i._configureAudio(r5, i3, t2, e2, n2); + }); + }); + } + setAutoResizeCanvas(t2) { + this.l = t2; + } + setAutoRenderToScreen(t2) { + this.i._setAutoRenderToScreen(t2); + } + setGpuBufferVerticalFlip(t2) { + this.i.gpuOriginForWebTexturesIsBottomLeft = t2; + } + ga(t2) { + Ho(this, "__graph_config__", (e2) => { + t2(e2); + }), jo(this, "__graph_config__", (t3) => { + this.i._getGraphConfig(t3, undefined); + }), delete this.i.simpleListeners.__graph_config__; + } + attachErrorListener(t2) { + this.i.errorListener = t2; + } + attachEmptyPacketListener(t2, e2) { + this.i.emptyPacketListeners = this.i.emptyPacketListeners || {}, this.i.emptyPacketListeners[t2] = e2; + } + addAudioToStream(t2, e2, n2) { + this.addAudioToStreamWithShape(t2, 0, 0, e2, n2); + } + addAudioToStreamWithShape(t2, e2, n2, r4, i2) { + const s2 = 4 * t2.length; + this.h !== s2 && (this.g && this.i._free(this.g), this.g = this.i._malloc(s2), this.h = s2), this.i.HEAPF32.set(t2, this.g / 4), jo(this, r4, (t3) => { + this.i._addAudioToInputStream(this.g, e2, n2, t3, i2); + }); + } + addGpuBufferToStream(t2, e2, n2) { + jo(this, e2, (e3) => { + const [r4, i2] = Vo(this, t2, e3); + this.i._addBoundTextureToStream(e3, r4, i2, n2); + }); + } + addBoolToStream(t2, e2, n2) { + jo(this, e2, (e3) => { + this.i._addBoolToInputStream(t2, e3, n2); + }); + } + addDoubleToStream(t2, e2, n2) { + jo(this, e2, (e3) => { + this.i._addDoubleToInputStream(t2, e3, n2); + }); + } + addFloatToStream(t2, e2, n2) { + jo(this, e2, (e3) => { + this.i._addFloatToInputStream(t2, e3, n2); + }); + } + addIntToStream(t2, e2, n2) { + jo(this, e2, (e3) => { + this.i._addIntToInputStream(t2, e3, n2); + }); + } + addUintToStream(t2, e2, n2) { + jo(this, e2, (e3) => { + this.i._addUintToInputStream(t2, e3, n2); + }); + } + addStringToStream(t2, e2, n2) { + jo(this, e2, (e3) => { + jo(this, t2, (t3) => { + this.i._addStringToInputStream(t3, e3, n2); + }); + }); + } + addStringRecordToStream(t2, e2, n2) { + jo(this, e2, (e3) => { + Xo(this, Object.keys(t2), (r4) => { + Xo(this, Object.values(t2), (i2) => { + this.i._addFlatHashMapToInputStream(r4, i2, Object.keys(t2).length, e3, n2); + }); + }); + }); + } + addProtoToStream(t2, e2, n2, r4) { + jo(this, n2, (n3) => { + jo(this, e2, (e3) => { + const i2 = this.i._malloc(t2.length); + this.i.HEAPU8.set(t2, i2), this.i._addProtoToInputStream(i2, t2.length, e3, n3, r4), this.i._free(i2); + }); + }); + } + addEmptyPacketToStream(t2, e2) { + jo(this, t2, (t3) => { + this.i._addEmptyPacketToInputStream(t3, e2); + }); + } + addBoolVectorToStream(t2, e2, n2) { + jo(this, e2, (e3) => { + const r4 = this.i._allocateBoolVector(t2.length); + if (!r4) + throw Error("Unable to allocate new bool vector on heap."); + for (const e4 of t2) + this.i._addBoolVectorEntry(r4, e4); + this.i._addBoolVectorToInputStream(r4, e3, n2); + }); + } + addDoubleVectorToStream(t2, e2, n2) { + jo(this, e2, (e3) => { + const r4 = this.i._allocateDoubleVector(t2.length); + if (!r4) + throw Error("Unable to allocate new double vector on heap."); + for (const e4 of t2) + this.i._addDoubleVectorEntry(r4, e4); + this.i._addDoubleVectorToInputStream(r4, e3, n2); + }); + } + addFloatVectorToStream(t2, e2, n2) { + jo(this, e2, (e3) => { + const r4 = this.i._allocateFloatVector(t2.length); + if (!r4) + throw Error("Unable to allocate new float vector on heap."); + for (const e4 of t2) + this.i._addFloatVectorEntry(r4, e4); + this.i._addFloatVectorToInputStream(r4, e3, n2); + }); + } + addIntVectorToStream(t2, e2, n2) { + jo(this, e2, (e3) => { + const r4 = this.i._allocateIntVector(t2.length); + if (!r4) + throw Error("Unable to allocate new int vector on heap."); + for (const e4 of t2) + this.i._addIntVectorEntry(r4, e4); + this.i._addIntVectorToInputStream(r4, e3, n2); + }); + } + addUintVectorToStream(t2, e2, n2) { + jo(this, e2, (e3) => { + const r4 = this.i._allocateUintVector(t2.length); + if (!r4) + throw Error("Unable to allocate new unsigned int vector on heap."); + for (const e4 of t2) + this.i._addUintVectorEntry(r4, e4); + this.i._addUintVectorToInputStream(r4, e3, n2); + }); + } + addStringVectorToStream(t2, e2, n2) { + jo(this, e2, (e3) => { + const r4 = this.i._allocateStringVector(t2.length); + if (!r4) + throw Error("Unable to allocate new string vector on heap."); + for (const e4 of t2) + jo(this, e4, (t3) => { + this.i._addStringVectorEntry(r4, t3); + }); + this.i._addStringVectorToInputStream(r4, e3, n2); + }); + } + addBoolToInputSidePacket(t2, e2) { + jo(this, e2, (e3) => { + this.i._addBoolToInputSidePacket(t2, e3); + }); + } + addDoubleToInputSidePacket(t2, e2) { + jo(this, e2, (e3) => { + this.i._addDoubleToInputSidePacket(t2, e3); + }); + } + addFloatToInputSidePacket(t2, e2) { + jo(this, e2, (e3) => { + this.i._addFloatToInputSidePacket(t2, e3); + }); + } + addIntToInputSidePacket(t2, e2) { + jo(this, e2, (e3) => { + this.i._addIntToInputSidePacket(t2, e3); + }); + } + addUintToInputSidePacket(t2, e2) { + jo(this, e2, (e3) => { + this.i._addUintToInputSidePacket(t2, e3); + }); + } + addStringToInputSidePacket(t2, e2) { + jo(this, e2, (e3) => { + jo(this, t2, (t3) => { + this.i._addStringToInputSidePacket(t3, e3); + }); + }); + } + addProtoToInputSidePacket(t2, e2, n2) { + jo(this, n2, (n3) => { + jo(this, e2, (e3) => { + const r4 = this.i._malloc(t2.length); + this.i.HEAPU8.set(t2, r4), this.i._addProtoToInputSidePacket(r4, t2.length, e3, n3), this.i._free(r4); + }); + }); + } + addBoolVectorToInputSidePacket(t2, e2) { + jo(this, e2, (e3) => { + const n2 = this.i._allocateBoolVector(t2.length); + if (!n2) + throw Error("Unable to allocate new bool vector on heap."); + for (const e4 of t2) + this.i._addBoolVectorEntry(n2, e4); + this.i._addBoolVectorToInputSidePacket(n2, e3); + }); + } + addDoubleVectorToInputSidePacket(t2, e2) { + jo(this, e2, (e3) => { + const n2 = this.i._allocateDoubleVector(t2.length); + if (!n2) + throw Error("Unable to allocate new double vector on heap."); + for (const e4 of t2) + this.i._addDoubleVectorEntry(n2, e4); + this.i._addDoubleVectorToInputSidePacket(n2, e3); + }); + } + addFloatVectorToInputSidePacket(t2, e2) { + jo(this, e2, (e3) => { + const n2 = this.i._allocateFloatVector(t2.length); + if (!n2) + throw Error("Unable to allocate new float vector on heap."); + for (const e4 of t2) + this.i._addFloatVectorEntry(n2, e4); + this.i._addFloatVectorToInputSidePacket(n2, e3); + }); + } + addIntVectorToInputSidePacket(t2, e2) { + jo(this, e2, (e3) => { + const n2 = this.i._allocateIntVector(t2.length); + if (!n2) + throw Error("Unable to allocate new int vector on heap."); + for (const e4 of t2) + this.i._addIntVectorEntry(n2, e4); + this.i._addIntVectorToInputSidePacket(n2, e3); + }); + } + addUintVectorToInputSidePacket(t2, e2) { + jo(this, e2, (e3) => { + const n2 = this.i._allocateUintVector(t2.length); + if (!n2) + throw Error("Unable to allocate new unsigned int vector on heap."); + for (const e4 of t2) + this.i._addUintVectorEntry(n2, e4); + this.i._addUintVectorToInputSidePacket(n2, e3); + }); + } + addStringVectorToInputSidePacket(t2, e2) { + jo(this, e2, (e3) => { + const n2 = this.i._allocateStringVector(t2.length); + if (!n2) + throw Error("Unable to allocate new string vector on heap."); + for (const e4 of t2) + jo(this, e4, (t3) => { + this.i._addStringVectorEntry(n2, t3); + }); + this.i._addStringVectorToInputSidePacket(n2, e3); + }); + } + attachBoolListener(t2, e2) { + Ho(this, t2, e2), jo(this, t2, (t3) => { + this.i._attachBoolListener(t3); + }); + } + attachBoolVectorListener(t2, e2) { + Wo(this, t2, e2), jo(this, t2, (t3) => { + this.i._attachBoolVectorListener(t3); + }); + } + attachIntListener(t2, e2) { + Ho(this, t2, e2), jo(this, t2, (t3) => { + this.i._attachIntListener(t3); + }); + } + attachIntVectorListener(t2, e2) { + Wo(this, t2, e2), jo(this, t2, (t3) => { + this.i._attachIntVectorListener(t3); + }); + } + attachUintListener(t2, e2) { + Ho(this, t2, e2), jo(this, t2, (t3) => { + this.i._attachUintListener(t3); + }); + } + attachUintVectorListener(t2, e2) { + Wo(this, t2, e2), jo(this, t2, (t3) => { + this.i._attachUintVectorListener(t3); + }); + } + attachDoubleListener(t2, e2) { + Ho(this, t2, e2), jo(this, t2, (t3) => { + this.i._attachDoubleListener(t3); + }); + } + attachDoubleVectorListener(t2, e2) { + Wo(this, t2, e2), jo(this, t2, (t3) => { + this.i._attachDoubleVectorListener(t3); + }); + } + attachFloatListener(t2, e2) { + Ho(this, t2, e2), jo(this, t2, (t3) => { + this.i._attachFloatListener(t3); + }); + } + attachFloatVectorListener(t2, e2) { + Wo(this, t2, e2), jo(this, t2, (t3) => { + this.i._attachFloatVectorListener(t3); + }); + } + attachStringListener(t2, e2) { + Ho(this, t2, e2), jo(this, t2, (t3) => { + this.i._attachStringListener(t3); + }); + } + attachStringVectorListener(t2, e2) { + Wo(this, t2, e2), jo(this, t2, (t3) => { + this.i._attachStringVectorListener(t3); + }); + } + attachProtoListener(t2, e2, n2) { + Ho(this, t2, e2), jo(this, t2, (t3) => { + this.i._attachProtoListener(t3, n2 || false); + }); + } + attachProtoVectorListener(t2, e2, n2) { + Wo(this, t2, e2), jo(this, t2, (t3) => { + this.i._attachProtoVectorListener(t3, n2 || false); + }); + } + attachAudioListener(t2, e2, n2) { + this.i._attachAudioListener || console.warn('Attempting to use attachAudioListener without support for output audio. Is build dep ":gl_graph_runner_audio_out" missing?'), Ho(this, t2, (t3, n3) => { + t3 = new Float32Array(t3.buffer, t3.byteOffset, t3.length / 4), e2(t3, n3); + }), jo(this, t2, (t3) => { + this.i._attachAudioListener(t3, n2 || false); + }); + } + finishProcessing() { + this.i._waitUntilIdle(); + } + closeGraph() { + this.i._closeGraph(), this.i.simpleListeners = undefined, this.i.emptyPacketListeners = undefined; + } +}, class extends Wa { + get ia() { + return this.i; + } + ta(t2, e2, n2) { + jo(this, e2, (e3) => { + const [r4, i2] = Vo(this, t2, e3); + this.ia._addBoundTextureAsImageToStream(e3, r4, i2, n2); + }); + } + W(t2, e2) { + Ho(this, t2, e2), jo(this, t2, (t3) => { + this.ia._attachImageListener(t3); + }); + } + fa(t2, e2) { + Wo(this, t2, e2), jo(this, t2, (t3) => { + this.ia._attachImageVectorListener(t3); + }); + } +})); +var Wa; +var za = class extends Ha { +}; +var Za = class extends Qo { + constructor(t2, e2, n2, r4) { + super(t2), this.g = t2, this.da = e2, this.V = n2, this.sa = r4, this.R = new ca; + } + l(t2, e2 = true) { + if ("runningMode" in t2 && Sn(this.baseOptions, 2, !!t2.runningMode && t2.runningMode !== "IMAGE"), t2.canvas !== undefined && this.g.i.canvas !== t2.canvas) + throw Error("You must create a new task to reset the canvas."); + return super.l(t2, e2); + } + close() { + this.R.close(), super.close(); + } +}; +Za.prototype.close = Za.prototype.close; +var Qa = class extends Za { + constructor(t2, e2) { + super(new za(t2, e2), "image_in", "norm_rect_in", false), this.j = { detections: [] }, yn(t2 = this.h = new Fs, 0, 1, e2 = new xs), Ln(this.h, 2, 0.5), Ln(this.h, 3, 0.3); + } + get baseOptions() { + return pn(this.h, xs, 1); + } + set baseOptions(t2) { + yn(this.h, 0, 1, t2); + } + o(t2) { + return "minDetectionConfidence" in t2 && Ln(this.h, 2, t2.minDetectionConfidence ?? 0.5), "minSuppressionThreshold" in t2 && Ln(this.h, 3, t2.minSuppressionThreshold ?? 0.3), this.l(t2); + } + D(t2, e2) { + return this.j = { detections: [] }, $a(this, t2, e2), this.j; + } + F(t2, e2, n2) { + return this.j = { detections: [] }, qa(this, t2, n2, e2), this.j; + } + m() { + var t2 = new $i; + Ki(t2, "image_in"), Ki(t2, "norm_rect_in"), Yi(t2, "detections"); + const e2 = new Ci; + er(e2, Is, this.h); + const n2 = new Vi; + Bi(n2, "mediapipe.tasks.vision.face_detector.FaceDetectorGraph"), Gi(n2, "IMAGE:image_in"), Gi(n2, "NORM_RECT:norm_rect_in"), ji(n2, "DETECTIONS:detections"), n2.o(e2), zi(t2, n2), this.g.attachProtoVectorListener("detections", (t3, e3) => { + for (const e4 of t3) + t3 = ss(e4), this.j.detections.push(Lo(t3)); + $o(this, e3); + }), this.g.attachEmptyPacketListener("detections", (t3) => { + $o(this, t3); + }), t2 = t2.g(), this.setGraph(new Uint8Array(t2), true); + } +}; +Qa.prototype.detectForVideo = Qa.prototype.F, Qa.prototype.detect = Qa.prototype.D, Qa.prototype.setOptions = Qa.prototype.o, Qa.createFromModelPath = async function(t2, e2) { + return Ka(Qa, t2, { baseOptions: { modelAssetPath: e2 } }); +}, Qa.createFromModelBuffer = function(t2, e2) { + return Ka(Qa, t2, { baseOptions: { modelAssetBuffer: e2 } }); +}, Qa.createFromOptions = function(t2, e2) { + return Ka(Qa, t2, e2); +}; +var th = Xa([61, 146], [146, 91], [91, 181], [181, 84], [84, 17], [17, 314], [314, 405], [405, 321], [321, 375], [375, 291], [61, 185], [185, 40], [40, 39], [39, 37], [37, 0], [0, 267], [267, 269], [269, 270], [270, 409], [409, 291], [78, 95], [95, 88], [88, 178], [178, 87], [87, 14], [14, 317], [317, 402], [402, 318], [318, 324], [324, 308], [78, 191], [191, 80], [80, 81], [81, 82], [82, 13], [13, 312], [312, 311], [311, 310], [310, 415], [415, 308]); +var eh = Xa([263, 249], [249, 390], [390, 373], [373, 374], [374, 380], [380, 381], [381, 382], [382, 362], [263, 466], [466, 388], [388, 387], [387, 386], [386, 385], [385, 384], [384, 398], [398, 362]); +var nh = Xa([276, 283], [283, 282], [282, 295], [295, 285], [300, 293], [293, 334], [334, 296], [296, 336]); +var rh = Xa([474, 475], [475, 476], [476, 477], [477, 474]); +var ih = Xa([33, 7], [7, 163], [163, 144], [144, 145], [145, 153], [153, 154], [154, 155], [155, 133], [33, 246], [246, 161], [161, 160], [160, 159], [159, 158], [158, 157], [157, 173], [173, 133]); +var sh = Xa([46, 53], [53, 52], [52, 65], [65, 55], [70, 63], [63, 105], [105, 66], [66, 107]); +var oh = Xa([469, 470], [470, 471], [471, 472], [472, 469]); +var ah = Xa([10, 338], [338, 297], [297, 332], [332, 284], [284, 251], [251, 389], [389, 356], [356, 454], [454, 323], [323, 361], [361, 288], [288, 397], [397, 365], [365, 379], [379, 378], [378, 400], [400, 377], [377, 152], [152, 148], [148, 176], [176, 149], [149, 150], [150, 136], [136, 172], [172, 58], [58, 132], [132, 93], [93, 234], [234, 127], [127, 162], [162, 21], [21, 54], [54, 103], [103, 67], [67, 109], [109, 10]); +var hh = [...th, ...eh, ...nh, ...ih, ...sh, ...ah]; +var ch = Xa([127, 34], [34, 139], [139, 127], [11, 0], [0, 37], [37, 11], [232, 231], [231, 120], [120, 232], [72, 37], [37, 39], [39, 72], [128, 121], [121, 47], [47, 128], [232, 121], [121, 128], [128, 232], [104, 69], [69, 67], [67, 104], [175, 171], [171, 148], [148, 175], [118, 50], [50, 101], [101, 118], [73, 39], [39, 40], [40, 73], [9, 151], [151, 108], [108, 9], [48, 115], [115, 131], [131, 48], [194, 204], [204, 211], [211, 194], [74, 40], [40, 185], [185, 74], [80, 42], [42, 183], [183, 80], [40, 92], [92, 186], [186, 40], [230, 229], [229, 118], [118, 230], [202, 212], [212, 214], [214, 202], [83, 18], [18, 17], [17, 83], [76, 61], [61, 146], [146, 76], [160, 29], [29, 30], [30, 160], [56, 157], [157, 173], [173, 56], [106, 204], [204, 194], [194, 106], [135, 214], [214, 192], [192, 135], [203, 165], [165, 98], [98, 203], [21, 71], [71, 68], [68, 21], [51, 45], [45, 4], [4, 51], [144, 24], [24, 23], [23, 144], [77, 146], [146, 91], [91, 77], [205, 50], [50, 187], [187, 205], [201, 200], [200, 18], [18, 201], [91, 106], [106, 182], [182, 91], [90, 91], [91, 181], [181, 90], [85, 84], [84, 17], [17, 85], [206, 203], [203, 36], [36, 206], [148, 171], [171, 140], [140, 148], [92, 40], [40, 39], [39, 92], [193, 189], [189, 244], [244, 193], [159, 158], [158, 28], [28, 159], [247, 246], [246, 161], [161, 247], [236, 3], [3, 196], [196, 236], [54, 68], [68, 104], [104, 54], [193, 168], [168, 8], [8, 193], [117, 228], [228, 31], [31, 117], [189, 193], [193, 55], [55, 189], [98, 97], [97, 99], [99, 98], [126, 47], [47, 100], [100, 126], [166, 79], [79, 218], [218, 166], [155, 154], [154, 26], [26, 155], [209, 49], [49, 131], [131, 209], [135, 136], [136, 150], [150, 135], [47, 126], [126, 217], [217, 47], [223, 52], [52, 53], [53, 223], [45, 51], [51, 134], [134, 45], [211, 170], [170, 140], [140, 211], [67, 69], [69, 108], [108, 67], [43, 106], [106, 91], [91, 43], [230, 119], [119, 120], [120, 230], [226, 130], [130, 247], [247, 226], [63, 53], [53, 52], [52, 63], [238, 20], [20, 242], [242, 238], [46, 70], [70, 156], [156, 46], [78, 62], [62, 96], [96, 78], [46, 53], [53, 63], [63, 46], [143, 34], [34, 227], [227, 143], [123, 117], [117, 111], [111, 123], [44, 125], [125, 19], [19, 44], [236, 134], [134, 51], [51, 236], [216, 206], [206, 205], [205, 216], [154, 153], [153, 22], [22, 154], [39, 37], [37, 167], [167, 39], [200, 201], [201, 208], [208, 200], [36, 142], [142, 100], [100, 36], [57, 212], [212, 202], [202, 57], [20, 60], [60, 99], [99, 20], [28, 158], [158, 157], [157, 28], [35, 226], [226, 113], [113, 35], [160, 159], [159, 27], [27, 160], [204, 202], [202, 210], [210, 204], [113, 225], [225, 46], [46, 113], [43, 202], [202, 204], [204, 43], [62, 76], [76, 77], [77, 62], [137, 123], [123, 116], [116, 137], [41, 38], [38, 72], [72, 41], [203, 129], [129, 142], [142, 203], [64, 98], [98, 240], [240, 64], [49, 102], [102, 64], [64, 49], [41, 73], [73, 74], [74, 41], [212, 216], [216, 207], [207, 212], [42, 74], [74, 184], [184, 42], [169, 170], [170, 211], [211, 169], [170, 149], [149, 176], [176, 170], [105, 66], [66, 69], [69, 105], [122, 6], [6, 168], [168, 122], [123, 147], [147, 187], [187, 123], [96, 77], [77, 90], [90, 96], [65, 55], [55, 107], [107, 65], [89, 90], [90, 180], [180, 89], [101, 100], [100, 120], [120, 101], [63, 105], [105, 104], [104, 63], [93, 137], [137, 227], [227, 93], [15, 86], [86, 85], [85, 15], [129, 102], [102, 49], [49, 129], [14, 87], [87, 86], [86, 14], [55, 8], [8, 9], [9, 55], [100, 47], [47, 121], [121, 100], [145, 23], [23, 22], [22, 145], [88, 89], [89, 179], [179, 88], [6, 122], [122, 196], [196, 6], [88, 95], [95, 96], [96, 88], [138, 172], [172, 136], [136, 138], [215, 58], [58, 172], [172, 215], [115, 48], [48, 219], [219, 115], [42, 80], [80, 81], [81, 42], [195, 3], [3, 51], [51, 195], [43, 146], [146, 61], [61, 43], [171, 175], [175, 199], [199, 171], [81, 82], [82, 38], [38, 81], [53, 46], [46, 225], [225, 53], [144, 163], [163, 110], [110, 144], [52, 65], [65, 66], [66, 52], [229, 228], [228, 117], [117, 229], [34, 127], [127, 234], [234, 34], [107, 108], [108, 69], [69, 107], [109, 108], [108, 151], [151, 109], [48, 64], [64, 235], [235, 48], [62, 78], [78, 191], [191, 62], [129, 209], [209, 126], [126, 129], [111, 35], [35, 143], [143, 111], [117, 123], [123, 50], [50, 117], [222, 65], [65, 52], [52, 222], [19, 125], [125, 141], [141, 19], [221, 55], [55, 65], [65, 221], [3, 195], [195, 197], [197, 3], [25, 7], [7, 33], [33, 25], [220, 237], [237, 44], [44, 220], [70, 71], [71, 139], [139, 70], [122, 193], [193, 245], [245, 122], [247, 130], [130, 33], [33, 247], [71, 21], [21, 162], [162, 71], [170, 169], [169, 150], [150, 170], [188, 174], [174, 196], [196, 188], [216, 186], [186, 92], [92, 216], [2, 97], [97, 167], [167, 2], [141, 125], [125, 241], [241, 141], [164, 167], [167, 37], [37, 164], [72, 38], [38, 12], [12, 72], [38, 82], [82, 13], [13, 38], [63, 68], [68, 71], [71, 63], [226, 35], [35, 111], [111, 226], [101, 50], [50, 205], [205, 101], [206, 92], [92, 165], [165, 206], [209, 198], [198, 217], [217, 209], [165, 167], [167, 97], [97, 165], [220, 115], [115, 218], [218, 220], [133, 112], [112, 243], [243, 133], [239, 238], [238, 241], [241, 239], [214, 135], [135, 169], [169, 214], [190, 173], [173, 133], [133, 190], [171, 208], [208, 32], [32, 171], [125, 44], [44, 237], [237, 125], [86, 87], [87, 178], [178, 86], [85, 86], [86, 179], [179, 85], [84, 85], [85, 180], [180, 84], [83, 84], [84, 181], [181, 83], [201, 83], [83, 182], [182, 201], [137, 93], [93, 132], [132, 137], [76, 62], [62, 183], [183, 76], [61, 76], [76, 184], [184, 61], [57, 61], [61, 185], [185, 57], [212, 57], [57, 186], [186, 212], [214, 207], [207, 187], [187, 214], [34, 143], [143, 156], [156, 34], [79, 239], [239, 237], [237, 79], [123, 137], [137, 177], [177, 123], [44, 1], [1, 4], [4, 44], [201, 194], [194, 32], [32, 201], [64, 102], [102, 129], [129, 64], [213, 215], [215, 138], [138, 213], [59, 166], [166, 219], [219, 59], [242, 99], [99, 97], [97, 242], [2, 94], [94, 141], [141, 2], [75, 59], [59, 235], [235, 75], [24, 110], [110, 228], [228, 24], [25, 130], [130, 226], [226, 25], [23, 24], [24, 229], [229, 23], [22, 23], [23, 230], [230, 22], [26, 22], [22, 231], [231, 26], [112, 26], [26, 232], [232, 112], [189, 190], [190, 243], [243, 189], [221, 56], [56, 190], [190, 221], [28, 56], [56, 221], [221, 28], [27, 28], [28, 222], [222, 27], [29, 27], [27, 223], [223, 29], [30, 29], [29, 224], [224, 30], [247, 30], [30, 225], [225, 247], [238, 79], [79, 20], [20, 238], [166, 59], [59, 75], [75, 166], [60, 75], [75, 240], [240, 60], [147, 177], [177, 215], [215, 147], [20, 79], [79, 166], [166, 20], [187, 147], [147, 213], [213, 187], [112, 233], [233, 244], [244, 112], [233, 128], [128, 245], [245, 233], [128, 114], [114, 188], [188, 128], [114, 217], [217, 174], [174, 114], [131, 115], [115, 220], [220, 131], [217, 198], [198, 236], [236, 217], [198, 131], [131, 134], [134, 198], [177, 132], [132, 58], [58, 177], [143, 35], [35, 124], [124, 143], [110, 163], [163, 7], [7, 110], [228, 110], [110, 25], [25, 228], [356, 389], [389, 368], [368, 356], [11, 302], [302, 267], [267, 11], [452, 350], [350, 349], [349, 452], [302, 303], [303, 269], [269, 302], [357, 343], [343, 277], [277, 357], [452, 453], [453, 357], [357, 452], [333, 332], [332, 297], [297, 333], [175, 152], [152, 377], [377, 175], [347, 348], [348, 330], [330, 347], [303, 304], [304, 270], [270, 303], [9, 336], [336, 337], [337, 9], [278, 279], [279, 360], [360, 278], [418, 262], [262, 431], [431, 418], [304, 408], [408, 409], [409, 304], [310, 415], [415, 407], [407, 310], [270, 409], [409, 410], [410, 270], [450, 348], [348, 347], [347, 450], [422, 430], [430, 434], [434, 422], [313, 314], [314, 17], [17, 313], [306, 307], [307, 375], [375, 306], [387, 388], [388, 260], [260, 387], [286, 414], [414, 398], [398, 286], [335, 406], [406, 418], [418, 335], [364, 367], [367, 416], [416, 364], [423, 358], [358, 327], [327, 423], [251, 284], [284, 298], [298, 251], [281, 5], [5, 4], [4, 281], [373, 374], [374, 253], [253, 373], [307, 320], [320, 321], [321, 307], [425, 427], [427, 411], [411, 425], [421, 313], [313, 18], [18, 421], [321, 405], [405, 406], [406, 321], [320, 404], [404, 405], [405, 320], [315, 16], [16, 17], [17, 315], [426, 425], [425, 266], [266, 426], [377, 400], [400, 369], [369, 377], [322, 391], [391, 269], [269, 322], [417, 465], [465, 464], [464, 417], [386, 257], [257, 258], [258, 386], [466, 260], [260, 388], [388, 466], [456, 399], [399, 419], [419, 456], [284, 332], [332, 333], [333, 284], [417, 285], [285, 8], [8, 417], [346, 340], [340, 261], [261, 346], [413, 441], [441, 285], [285, 413], [327, 460], [460, 328], [328, 327], [355, 371], [371, 329], [329, 355], [392, 439], [439, 438], [438, 392], [382, 341], [341, 256], [256, 382], [429, 420], [420, 360], [360, 429], [364, 394], [394, 379], [379, 364], [277, 343], [343, 437], [437, 277], [443, 444], [444, 283], [283, 443], [275, 440], [440, 363], [363, 275], [431, 262], [262, 369], [369, 431], [297, 338], [338, 337], [337, 297], [273, 375], [375, 321], [321, 273], [450, 451], [451, 349], [349, 450], [446, 342], [342, 467], [467, 446], [293, 334], [334, 282], [282, 293], [458, 461], [461, 462], [462, 458], [276, 353], [353, 383], [383, 276], [308, 324], [324, 325], [325, 308], [276, 300], [300, 293], [293, 276], [372, 345], [345, 447], [447, 372], [352, 345], [345, 340], [340, 352], [274, 1], [1, 19], [19, 274], [456, 248], [248, 281], [281, 456], [436, 427], [427, 425], [425, 436], [381, 256], [256, 252], [252, 381], [269, 391], [391, 393], [393, 269], [200, 199], [199, 428], [428, 200], [266, 330], [330, 329], [329, 266], [287, 273], [273, 422], [422, 287], [250, 462], [462, 328], [328, 250], [258, 286], [286, 384], [384, 258], [265, 353], [353, 342], [342, 265], [387, 259], [259, 257], [257, 387], [424, 431], [431, 430], [430, 424], [342, 353], [353, 276], [276, 342], [273, 335], [335, 424], [424, 273], [292, 325], [325, 307], [307, 292], [366, 447], [447, 345], [345, 366], [271, 303], [303, 302], [302, 271], [423, 266], [266, 371], [371, 423], [294, 455], [455, 460], [460, 294], [279, 278], [278, 294], [294, 279], [271, 272], [272, 304], [304, 271], [432, 434], [434, 427], [427, 432], [272, 407], [407, 408], [408, 272], [394, 430], [430, 431], [431, 394], [395, 369], [369, 400], [400, 395], [334, 333], [333, 299], [299, 334], [351, 417], [417, 168], [168, 351], [352, 280], [280, 411], [411, 352], [325, 319], [319, 320], [320, 325], [295, 296], [296, 336], [336, 295], [319, 403], [403, 404], [404, 319], [330, 348], [348, 349], [349, 330], [293, 298], [298, 333], [333, 293], [323, 454], [454, 447], [447, 323], [15, 16], [16, 315], [315, 15], [358, 429], [429, 279], [279, 358], [14, 15], [15, 316], [316, 14], [285, 336], [336, 9], [9, 285], [329, 349], [349, 350], [350, 329], [374, 380], [380, 252], [252, 374], [318, 402], [402, 403], [403, 318], [6, 197], [197, 419], [419, 6], [318, 319], [319, 325], [325, 318], [367, 364], [364, 365], [365, 367], [435, 367], [367, 397], [397, 435], [344, 438], [438, 439], [439, 344], [272, 271], [271, 311], [311, 272], [195, 5], [5, 281], [281, 195], [273, 287], [287, 291], [291, 273], [396, 428], [428, 199], [199, 396], [311, 271], [271, 268], [268, 311], [283, 444], [444, 445], [445, 283], [373, 254], [254, 339], [339, 373], [282, 334], [334, 296], [296, 282], [449, 347], [347, 346], [346, 449], [264, 447], [447, 454], [454, 264], [336, 296], [296, 299], [299, 336], [338, 10], [10, 151], [151, 338], [278, 439], [439, 455], [455, 278], [292, 407], [407, 415], [415, 292], [358, 371], [371, 355], [355, 358], [340, 345], [345, 372], [372, 340], [346, 347], [347, 280], [280, 346], [442, 443], [443, 282], [282, 442], [19, 94], [94, 370], [370, 19], [441, 442], [442, 295], [295, 441], [248, 419], [419, 197], [197, 248], [263, 255], [255, 359], [359, 263], [440, 275], [275, 274], [274, 440], [300, 383], [383, 368], [368, 300], [351, 412], [412, 465], [465, 351], [263, 467], [467, 466], [466, 263], [301, 368], [368, 389], [389, 301], [395, 378], [378, 379], [379, 395], [412, 351], [351, 419], [419, 412], [436, 426], [426, 322], [322, 436], [2, 164], [164, 393], [393, 2], [370, 462], [462, 461], [461, 370], [164, 0], [0, 267], [267, 164], [302, 11], [11, 12], [12, 302], [268, 12], [12, 13], [13, 268], [293, 300], [300, 301], [301, 293], [446, 261], [261, 340], [340, 446], [330, 266], [266, 425], [425, 330], [426, 423], [423, 391], [391, 426], [429, 355], [355, 437], [437, 429], [391, 327], [327, 326], [326, 391], [440, 457], [457, 438], [438, 440], [341, 382], [382, 362], [362, 341], [459, 457], [457, 461], [461, 459], [434, 430], [430, 394], [394, 434], [414, 463], [463, 362], [362, 414], [396, 369], [369, 262], [262, 396], [354, 461], [461, 457], [457, 354], [316, 403], [403, 402], [402, 316], [315, 404], [404, 403], [403, 315], [314, 405], [405, 404], [404, 314], [313, 406], [406, 405], [405, 313], [421, 418], [418, 406], [406, 421], [366, 401], [401, 361], [361, 366], [306, 408], [408, 407], [407, 306], [291, 409], [409, 408], [408, 291], [287, 410], [410, 409], [409, 287], [432, 436], [436, 410], [410, 432], [434, 416], [416, 411], [411, 434], [264, 368], [368, 383], [383, 264], [309, 438], [438, 457], [457, 309], [352, 376], [376, 401], [401, 352], [274, 275], [275, 4], [4, 274], [421, 428], [428, 262], [262, 421], [294, 327], [327, 358], [358, 294], [433, 416], [416, 367], [367, 433], [289, 455], [455, 439], [439, 289], [462, 370], [370, 326], [326, 462], [2, 326], [326, 370], [370, 2], [305, 460], [460, 455], [455, 305], [254, 449], [449, 448], [448, 254], [255, 261], [261, 446], [446, 255], [253, 450], [450, 449], [449, 253], [252, 451], [451, 450], [450, 252], [256, 452], [452, 451], [451, 256], [341, 453], [453, 452], [452, 341], [413, 464], [464, 463], [463, 413], [441, 413], [413, 414], [414, 441], [258, 442], [442, 441], [441, 258], [257, 443], [443, 442], [442, 257], [259, 444], [444, 443], [443, 259], [260, 445], [445, 444], [444, 260], [467, 342], [342, 445], [445, 467], [459, 458], [458, 250], [250, 459], [289, 392], [392, 290], [290, 289], [290, 328], [328, 460], [460, 290], [376, 433], [433, 435], [435, 376], [250, 290], [290, 392], [392, 250], [411, 416], [416, 433], [433, 411], [341, 463], [463, 464], [464, 341], [453, 464], [464, 465], [465, 453], [357, 465], [465, 412], [412, 357], [343, 412], [412, 399], [399, 343], [360, 363], [363, 440], [440, 360], [437, 399], [399, 456], [456, 437], [420, 456], [456, 363], [363, 420], [401, 435], [435, 288], [288, 401], [372, 383], [383, 353], [353, 372], [339, 255], [255, 249], [249, 339], [448, 261], [261, 255], [255, 448], [133, 243], [243, 190], [190, 133], [133, 155], [155, 112], [112, 133], [33, 246], [246, 247], [247, 33], [33, 130], [130, 25], [25, 33], [398, 384], [384, 286], [286, 398], [362, 398], [398, 414], [414, 362], [362, 463], [463, 341], [341, 362], [263, 359], [359, 467], [467, 263], [263, 249], [249, 255], [255, 263], [466, 467], [467, 260], [260, 466], [75, 60], [60, 166], [166, 75], [238, 239], [239, 79], [79, 238], [162, 127], [127, 139], [139, 162], [72, 11], [11, 37], [37, 72], [121, 232], [232, 120], [120, 121], [73, 72], [72, 39], [39, 73], [114, 128], [128, 47], [47, 114], [233, 232], [232, 128], [128, 233], [103, 104], [104, 67], [67, 103], [152, 175], [175, 148], [148, 152], [119, 118], [118, 101], [101, 119], [74, 73], [73, 40], [40, 74], [107, 9], [9, 108], [108, 107], [49, 48], [48, 131], [131, 49], [32, 194], [194, 211], [211, 32], [184, 74], [74, 185], [185, 184], [191, 80], [80, 183], [183, 191], [185, 40], [40, 186], [186, 185], [119, 230], [230, 118], [118, 119], [210, 202], [202, 214], [214, 210], [84, 83], [83, 17], [17, 84], [77, 76], [76, 146], [146, 77], [161, 160], [160, 30], [30, 161], [190, 56], [56, 173], [173, 190], [182, 106], [106, 194], [194, 182], [138, 135], [135, 192], [192, 138], [129, 203], [203, 98], [98, 129], [54, 21], [21, 68], [68, 54], [5, 51], [51, 4], [4, 5], [145, 144], [144, 23], [23, 145], [90, 77], [77, 91], [91, 90], [207, 205], [205, 187], [187, 207], [83, 201], [201, 18], [18, 83], [181, 91], [91, 182], [182, 181], [180, 90], [90, 181], [181, 180], [16, 85], [85, 17], [17, 16], [205, 206], [206, 36], [36, 205], [176, 148], [148, 140], [140, 176], [165, 92], [92, 39], [39, 165], [245, 193], [193, 244], [244, 245], [27, 159], [159, 28], [28, 27], [30, 247], [247, 161], [161, 30], [174, 236], [236, 196], [196, 174], [103, 54], [54, 104], [104, 103], [55, 193], [193, 8], [8, 55], [111, 117], [117, 31], [31, 111], [221, 189], [189, 55], [55, 221], [240, 98], [98, 99], [99, 240], [142, 126], [126, 100], [100, 142], [219, 166], [166, 218], [218, 219], [112, 155], [155, 26], [26, 112], [198, 209], [209, 131], [131, 198], [169, 135], [135, 150], [150, 169], [114, 47], [47, 217], [217, 114], [224, 223], [223, 53], [53, 224], [220, 45], [45, 134], [134, 220], [32, 211], [211, 140], [140, 32], [109, 67], [67, 108], [108, 109], [146, 43], [43, 91], [91, 146], [231, 230], [230, 120], [120, 231], [113, 226], [226, 247], [247, 113], [105, 63], [63, 52], [52, 105], [241, 238], [238, 242], [242, 241], [124, 46], [46, 156], [156, 124], [95, 78], [78, 96], [96, 95], [70, 46], [46, 63], [63, 70], [116, 143], [143, 227], [227, 116], [116, 123], [123, 111], [111, 116], [1, 44], [44, 19], [19, 1], [3, 236], [236, 51], [51, 3], [207, 216], [216, 205], [205, 207], [26, 154], [154, 22], [22, 26], [165, 39], [39, 167], [167, 165], [199, 200], [200, 208], [208, 199], [101, 36], [36, 100], [100, 101], [43, 57], [57, 202], [202, 43], [242, 20], [20, 99], [99, 242], [56, 28], [28, 157], [157, 56], [124, 35], [35, 113], [113, 124], [29, 160], [160, 27], [27, 29], [211, 204], [204, 210], [210, 211], [124, 113], [113, 46], [46, 124], [106, 43], [43, 204], [204, 106], [96, 62], [62, 77], [77, 96], [227, 137], [137, 116], [116, 227], [73, 41], [41, 72], [72, 73], [36, 203], [203, 142], [142, 36], [235, 64], [64, 240], [240, 235], [48, 49], [49, 64], [64, 48], [42, 41], [41, 74], [74, 42], [214, 212], [212, 207], [207, 214], [183, 42], [42, 184], [184, 183], [210, 169], [169, 211], [211, 210], [140, 170], [170, 176], [176, 140], [104, 105], [105, 69], [69, 104], [193, 122], [122, 168], [168, 193], [50, 123], [123, 187], [187, 50], [89, 96], [96, 90], [90, 89], [66, 65], [65, 107], [107, 66], [179, 89], [89, 180], [180, 179], [119, 101], [101, 120], [120, 119], [68, 63], [63, 104], [104, 68], [234, 93], [93, 227], [227, 234], [16, 15], [15, 85], [85, 16], [209, 129], [129, 49], [49, 209], [15, 14], [14, 86], [86, 15], [107, 55], [55, 9], [9, 107], [120, 100], [100, 121], [121, 120], [153, 145], [145, 22], [22, 153], [178, 88], [88, 179], [179, 178], [197, 6], [6, 196], [196, 197], [89, 88], [88, 96], [96, 89], [135, 138], [138, 136], [136, 135], [138, 215], [215, 172], [172, 138], [218, 115], [115, 219], [219, 218], [41, 42], [42, 81], [81, 41], [5, 195], [195, 51], [51, 5], [57, 43], [43, 61], [61, 57], [208, 171], [171, 199], [199, 208], [41, 81], [81, 38], [38, 41], [224, 53], [53, 225], [225, 224], [24, 144], [144, 110], [110, 24], [105, 52], [52, 66], [66, 105], [118, 229], [229, 117], [117, 118], [227, 34], [34, 234], [234, 227], [66, 107], [107, 69], [69, 66], [10, 109], [109, 151], [151, 10], [219, 48], [48, 235], [235, 219], [183, 62], [62, 191], [191, 183], [142, 129], [129, 126], [126, 142], [116, 111], [111, 143], [143, 116], [118, 117], [117, 50], [50, 118], [223, 222], [222, 52], [52, 223], [94, 19], [19, 141], [141, 94], [222, 221], [221, 65], [65, 222], [196, 3], [3, 197], [197, 196], [45, 220], [220, 44], [44, 45], [156, 70], [70, 139], [139, 156], [188, 122], [122, 245], [245, 188], [139, 71], [71, 162], [162, 139], [149, 170], [170, 150], [150, 149], [122, 188], [188, 196], [196, 122], [206, 216], [216, 92], [92, 206], [164, 2], [2, 167], [167, 164], [242, 141], [141, 241], [241, 242], [0, 164], [164, 37], [37, 0], [11, 72], [72, 12], [12, 11], [12, 38], [38, 13], [13, 12], [70, 63], [63, 71], [71, 70], [31, 226], [226, 111], [111, 31], [36, 101], [101, 205], [205, 36], [203, 206], [206, 165], [165, 203], [126, 209], [209, 217], [217, 126], [98, 165], [165, 97], [97, 98], [237, 220], [220, 218], [218, 237], [237, 239], [239, 241], [241, 237], [210, 214], [214, 169], [169, 210], [140, 171], [171, 32], [32, 140], [241, 125], [125, 237], [237, 241], [179, 86], [86, 178], [178, 179], [180, 85], [85, 179], [179, 180], [181, 84], [84, 180], [180, 181], [182, 83], [83, 181], [181, 182], [194, 201], [201, 182], [182, 194], [177, 137], [137, 132], [132, 177], [184, 76], [76, 183], [183, 184], [185, 61], [61, 184], [184, 185], [186, 57], [57, 185], [185, 186], [216, 212], [212, 186], [186, 216], [192, 214], [214, 187], [187, 192], [139, 34], [34, 156], [156, 139], [218, 79], [79, 237], [237, 218], [147, 123], [123, 177], [177, 147], [45, 44], [44, 4], [4, 45], [208, 201], [201, 32], [32, 208], [98, 64], [64, 129], [129, 98], [192, 213], [213, 138], [138, 192], [235, 59], [59, 219], [219, 235], [141, 242], [242, 97], [97, 141], [97, 2], [2, 141], [141, 97], [240, 75], [75, 235], [235, 240], [229, 24], [24, 228], [228, 229], [31, 25], [25, 226], [226, 31], [230, 23], [23, 229], [229, 230], [231, 22], [22, 230], [230, 231], [232, 26], [26, 231], [231, 232], [233, 112], [112, 232], [232, 233], [244, 189], [189, 243], [243, 244], [189, 221], [221, 190], [190, 189], [222, 28], [28, 221], [221, 222], [223, 27], [27, 222], [222, 223], [224, 29], [29, 223], [223, 224], [225, 30], [30, 224], [224, 225], [113, 247], [247, 225], [225, 113], [99, 60], [60, 240], [240, 99], [213, 147], [147, 215], [215, 213], [60, 20], [20, 166], [166, 60], [192, 187], [187, 213], [213, 192], [243, 112], [112, 244], [244, 243], [244, 233], [233, 245], [245, 244], [245, 128], [128, 188], [188, 245], [188, 114], [114, 174], [174, 188], [134, 131], [131, 220], [220, 134], [174, 217], [217, 236], [236, 174], [236, 198], [198, 134], [134, 236], [215, 177], [177, 58], [58, 215], [156, 143], [143, 124], [124, 156], [25, 110], [110, 7], [7, 25], [31, 228], [228, 25], [25, 31], [264, 356], [356, 368], [368, 264], [0, 11], [11, 267], [267, 0], [451, 452], [452, 349], [349, 451], [267, 302], [302, 269], [269, 267], [350, 357], [357, 277], [277, 350], [350, 452], [452, 357], [357, 350], [299, 333], [333, 297], [297, 299], [396, 175], [175, 377], [377, 396], [280, 347], [347, 330], [330, 280], [269, 303], [303, 270], [270, 269], [151, 9], [9, 337], [337, 151], [344, 278], [278, 360], [360, 344], [424, 418], [418, 431], [431, 424], [270, 304], [304, 409], [409, 270], [272, 310], [310, 407], [407, 272], [322, 270], [270, 410], [410, 322], [449, 450], [450, 347], [347, 449], [432, 422], [422, 434], [434, 432], [18, 313], [313, 17], [17, 18], [291, 306], [306, 375], [375, 291], [259, 387], [387, 260], [260, 259], [424, 335], [335, 418], [418, 424], [434, 364], [364, 416], [416, 434], [391, 423], [423, 327], [327, 391], [301, 251], [251, 298], [298, 301], [275, 281], [281, 4], [4, 275], [254, 373], [373, 253], [253, 254], [375, 307], [307, 321], [321, 375], [280, 425], [425, 411], [411, 280], [200, 421], [421, 18], [18, 200], [335, 321], [321, 406], [406, 335], [321, 320], [320, 405], [405, 321], [314, 315], [315, 17], [17, 314], [423, 426], [426, 266], [266, 423], [396, 377], [377, 369], [369, 396], [270, 322], [322, 269], [269, 270], [413, 417], [417, 464], [464, 413], [385, 386], [386, 258], [258, 385], [248, 456], [456, 419], [419, 248], [298, 284], [284, 333], [333, 298], [168, 417], [417, 8], [8, 168], [448, 346], [346, 261], [261, 448], [417, 413], [413, 285], [285, 417], [326, 327], [327, 328], [328, 326], [277, 355], [355, 329], [329, 277], [309, 392], [392, 438], [438, 309], [381, 382], [382, 256], [256, 381], [279, 429], [429, 360], [360, 279], [365, 364], [364, 379], [379, 365], [355, 277], [277, 437], [437, 355], [282, 443], [443, 283], [283, 282], [281, 275], [275, 363], [363, 281], [395, 431], [431, 369], [369, 395], [299, 297], [297, 337], [337, 299], [335, 273], [273, 321], [321, 335], [348, 450], [450, 349], [349, 348], [359, 446], [446, 467], [467, 359], [283, 293], [293, 282], [282, 283], [250, 458], [458, 462], [462, 250], [300, 276], [276, 383], [383, 300], [292, 308], [308, 325], [325, 292], [283, 276], [276, 293], [293, 283], [264, 372], [372, 447], [447, 264], [346, 352], [352, 340], [340, 346], [354, 274], [274, 19], [19, 354], [363, 456], [456, 281], [281, 363], [426, 436], [436, 425], [425, 426], [380, 381], [381, 252], [252, 380], [267, 269], [269, 393], [393, 267], [421, 200], [200, 428], [428, 421], [371, 266], [266, 329], [329, 371], [432, 287], [287, 422], [422, 432], [290, 250], [250, 328], [328, 290], [385, 258], [258, 384], [384, 385], [446, 265], [265, 342], [342, 446], [386, 387], [387, 257], [257, 386], [422, 424], [424, 430], [430, 422], [445, 342], [342, 276], [276, 445], [422, 273], [273, 424], [424, 422], [306, 292], [292, 307], [307, 306], [352, 366], [366, 345], [345, 352], [268, 271], [271, 302], [302, 268], [358, 423], [423, 371], [371, 358], [327, 294], [294, 460], [460, 327], [331, 279], [279, 294], [294, 331], [303, 271], [271, 304], [304, 303], [436, 432], [432, 427], [427, 436], [304, 272], [272, 408], [408, 304], [395, 394], [394, 431], [431, 395], [378, 395], [395, 400], [400, 378], [296, 334], [334, 299], [299, 296], [6, 351], [351, 168], [168, 6], [376, 352], [352, 411], [411, 376], [307, 325], [325, 320], [320, 307], [285, 295], [295, 336], [336, 285], [320, 319], [319, 404], [404, 320], [329, 330], [330, 349], [349, 329], [334, 293], [293, 333], [333, 334], [366, 323], [323, 447], [447, 366], [316, 15], [15, 315], [315, 316], [331, 358], [358, 279], [279, 331], [317, 14], [14, 316], [316, 317], [8, 285], [285, 9], [9, 8], [277, 329], [329, 350], [350, 277], [253, 374], [374, 252], [252, 253], [319, 318], [318, 403], [403, 319], [351, 6], [6, 419], [419, 351], [324, 318], [318, 325], [325, 324], [397, 367], [367, 365], [365, 397], [288, 435], [435, 397], [397, 288], [278, 344], [344, 439], [439, 278], [310, 272], [272, 311], [311, 310], [248, 195], [195, 281], [281, 248], [375, 273], [273, 291], [291, 375], [175, 396], [396, 199], [199, 175], [312, 311], [311, 268], [268, 312], [276, 283], [283, 445], [445, 276], [390, 373], [373, 339], [339, 390], [295, 282], [282, 296], [296, 295], [448, 449], [449, 346], [346, 448], [356, 264], [264, 454], [454, 356], [337, 336], [336, 299], [299, 337], [337, 338], [338, 151], [151, 337], [294, 278], [278, 455], [455, 294], [308, 292], [292, 415], [415, 308], [429, 358], [358, 355], [355, 429], [265, 340], [340, 372], [372, 265], [352, 346], [346, 280], [280, 352], [295, 442], [442, 282], [282, 295], [354, 19], [19, 370], [370, 354], [285, 441], [441, 295], [295, 285], [195, 248], [248, 197], [197, 195], [457, 440], [440, 274], [274, 457], [301, 300], [300, 368], [368, 301], [417, 351], [351, 465], [465, 417], [251, 301], [301, 389], [389, 251], [394, 395], [395, 379], [379, 394], [399, 412], [412, 419], [419, 399], [410, 436], [436, 322], [322, 410], [326, 2], [2, 393], [393, 326], [354, 370], [370, 461], [461, 354], [393, 164], [164, 267], [267, 393], [268, 302], [302, 12], [12, 268], [312, 268], [268, 13], [13, 312], [298, 293], [293, 301], [301, 298], [265, 446], [446, 340], [340, 265], [280, 330], [330, 425], [425, 280], [322, 426], [426, 391], [391, 322], [420, 429], [429, 437], [437, 420], [393, 391], [391, 326], [326, 393], [344, 440], [440, 438], [438, 344], [458, 459], [459, 461], [461, 458], [364, 434], [434, 394], [394, 364], [428, 396], [396, 262], [262, 428], [274, 354], [354, 457], [457, 274], [317, 316], [316, 402], [402, 317], [316, 315], [315, 403], [403, 316], [315, 314], [314, 404], [404, 315], [314, 313], [313, 405], [405, 314], [313, 421], [421, 406], [406, 313], [323, 366], [366, 361], [361, 323], [292, 306], [306, 407], [407, 292], [306, 291], [291, 408], [408, 306], [291, 287], [287, 409], [409, 291], [287, 432], [432, 410], [410, 287], [427, 434], [434, 411], [411, 427], [372, 264], [264, 383], [383, 372], [459, 309], [309, 457], [457, 459], [366, 352], [352, 401], [401, 366], [1, 274], [274, 4], [4, 1], [418, 421], [421, 262], [262, 418], [331, 294], [294, 358], [358, 331], [435, 433], [433, 367], [367, 435], [392, 289], [289, 439], [439, 392], [328, 462], [462, 326], [326, 328], [94, 2], [2, 370], [370, 94], [289, 305], [305, 455], [455, 289], [339, 254], [254, 448], [448, 339], [359, 255], [255, 446], [446, 359], [254, 253], [253, 449], [449, 254], [253, 252], [252, 450], [450, 253], [252, 256], [256, 451], [451, 252], [256, 341], [341, 452], [452, 256], [414, 413], [413, 463], [463, 414], [286, 441], [441, 414], [414, 286], [286, 258], [258, 441], [441, 286], [258, 257], [257, 442], [442, 258], [257, 259], [259, 443], [443, 257], [259, 260], [260, 444], [444, 259], [260, 467], [467, 445], [445, 260], [309, 459], [459, 250], [250, 309], [305, 289], [289, 290], [290, 305], [305, 290], [290, 460], [460, 305], [401, 376], [376, 435], [435, 401], [309, 250], [250, 392], [392, 309], [376, 411], [411, 433], [433, 376], [453, 341], [341, 464], [464, 453], [357, 453], [453, 465], [465, 357], [343, 357], [357, 412], [412, 343], [437, 343], [343, 399], [399, 437], [344, 360], [360, 440], [440, 344], [420, 437], [437, 456], [456, 420], [360, 420], [420, 363], [363, 360], [361, 401], [401, 288], [288, 361], [265, 372], [372, 353], [353, 265], [390, 339], [339, 249], [249, 390], [339, 448], [448, 255], [255, 339]); +var lh = class extends Za { + constructor(t2, e2) { + super(new za(t2, e2), "image_in", "norm_rect", false), this.j = { faceLandmarks: [], faceBlendshapes: [], facialTransformationMatrixes: [] }, this.outputFacialTransformationMatrixes = this.outputFaceBlendshapes = false, yn(t2 = this.h = new Ds, 0, 1, e2 = new xs), this.v = new Us, yn(this.h, 0, 3, this.v), this.s = new Fs, yn(this.h, 0, 2, this.s), xn(this.s, 4, 1), Ln(this.s, 2, 0.5), Ln(this.v, 2, 0.5), Ln(this.h, 4, 0.5); + } + get baseOptions() { + return pn(this.h, xs, 1); + } + set baseOptions(t2) { + yn(this.h, 0, 1, t2); + } + o(t2) { + return "numFaces" in t2 && xn(this.s, 4, t2.numFaces ?? 1), "minFaceDetectionConfidence" in t2 && Ln(this.s, 2, t2.minFaceDetectionConfidence ?? 0.5), "minTrackingConfidence" in t2 && Ln(this.h, 4, t2.minTrackingConfidence ?? 0.5), "minFacePresenceConfidence" in t2 && Ln(this.v, 2, t2.minFacePresenceConfidence ?? 0.5), "outputFaceBlendshapes" in t2 && (this.outputFaceBlendshapes = !!t2.outputFaceBlendshapes), "outputFacialTransformationMatrixes" in t2 && (this.outputFacialTransformationMatrixes = !!t2.outputFacialTransformationMatrixes), this.l(t2); + } + D(t2, e2) { + return uh(this), $a(this, t2, e2), this.j; + } + F(t2, e2, n2) { + return uh(this), qa(this, t2, n2, e2), this.j; + } + m() { + var t2 = new $i; + Ki(t2, "image_in"), Ki(t2, "norm_rect"), Yi(t2, "face_landmarks"); + const e2 = new Ci; + er(e2, js, this.h); + const n2 = new Vi; + Bi(n2, "mediapipe.tasks.vision.face_landmarker.FaceLandmarkerGraph"), Gi(n2, "IMAGE:image_in"), Gi(n2, "NORM_RECT:norm_rect"), ji(n2, "NORM_LANDMARKS:face_landmarks"), n2.o(e2), zi(t2, n2), this.g.attachProtoVectorListener("face_landmarks", (t3, e3) => { + for (const e4 of t3) + t3 = cs(e4), this.j.faceLandmarks.push(Ro(t3)); + $o(this, e3); + }), this.g.attachEmptyPacketListener("face_landmarks", (t3) => { + $o(this, t3); + }), this.outputFaceBlendshapes && (Yi(t2, "blendshapes"), ji(n2, "BLENDSHAPES:blendshapes"), this.g.attachProtoVectorListener("blendshapes", (t3, e3) => { + if (this.outputFaceBlendshapes) + for (const e4 of t3) + t3 = es(e4), this.j.faceBlendshapes.push(xo(t3.g() ?? [])); + $o(this, e3); + }), this.g.attachEmptyPacketListener("blendshapes", (t3) => { + $o(this, t3); + })), this.outputFacialTransformationMatrixes && (Yi(t2, "face_geometry"), ji(n2, "FACE_GEOMETRY:face_geometry"), this.g.attachProtoVectorListener("face_geometry", (t3, e3) => { + if (this.outputFacialTransformationMatrixes) + for (const e4 of t3) + (t3 = pn(Cs(e4), us, 2)) && this.j.facialTransformationMatrixes.push({ rows: Tn(An(t3, 1), 0) ?? 0, columns: Tn(An(t3, 2), 0) ?? 0, data: en(t3, 3, Ht, tn()).slice() ?? [] }); + $o(this, e3); + }), this.g.attachEmptyPacketListener("face_geometry", (t3) => { + $o(this, t3); + })), t2 = t2.g(), this.setGraph(new Uint8Array(t2), true); + } +}; +lh.prototype.detectForVideo = lh.prototype.F, lh.prototype.detect = lh.prototype.D, lh.prototype.setOptions = lh.prototype.o, lh.createFromModelPath = function(t2, e2) { + return Ka(lh, t2, { baseOptions: { modelAssetPath: e2 } }); +}, lh.createFromModelBuffer = function(t2, e2) { + return Ka(lh, t2, { baseOptions: { modelAssetBuffer: e2 } }); +}, lh.createFromOptions = function(t2, e2) { + return Ka(lh, t2, e2); +}, lh.FACE_LANDMARKS_LIPS = th, lh.FACE_LANDMARKS_LEFT_EYE = eh, lh.FACE_LANDMARKS_LEFT_EYEBROW = nh, lh.FACE_LANDMARKS_LEFT_IRIS = rh, lh.FACE_LANDMARKS_RIGHT_EYE = ih, lh.FACE_LANDMARKS_RIGHT_EYEBROW = sh, lh.FACE_LANDMARKS_RIGHT_IRIS = oh, lh.FACE_LANDMARKS_FACE_OVAL = ah, lh.FACE_LANDMARKS_CONTOURS = hh, lh.FACE_LANDMARKS_TESSELATION = ch; +var fh = class extends Za { + constructor(t2, e2) { + super(new za(t2, e2), "image_in", "norm_rect", true), yn(t2 = this.j = new Vs, 0, 1, e2 = new xs); + } + get baseOptions() { + return pn(this.j, xs, 1); + } + set baseOptions(t2) { + yn(this.j, 0, 1, t2); + } + o(t2) { + return super.l(t2); + } + Ra(t2, e2, n2) { + const r4 = typeof e2 != "function" ? e2 : {}; + if (this.h = typeof e2 == "function" ? e2 : n2, $a(this, t2, r4 ?? {}), !this.h) + return this.s; + } + m() { + var t2 = new $i; + Ki(t2, "image_in"), Ki(t2, "norm_rect"), Yi(t2, "stylized_image"); + const e2 = new Ci; + er(e2, Xs, this.j); + const n2 = new Vi; + Bi(n2, "mediapipe.tasks.vision.face_stylizer.FaceStylizerGraph"), Gi(n2, "IMAGE:image_in"), Gi(n2, "NORM_RECT:norm_rect"), ji(n2, "STYLIZED_IMAGE:stylized_image"), n2.o(e2), zi(t2, n2), this.g.W("stylized_image", (t3, e3) => { + var n3 = !this.h, r4 = t3.data, i2 = t3.width; + const s2 = i2 * (t3 = t3.height); + if (r4 instanceof Uint8Array) + if (r4.length === 3 * s2) { + const e4 = new Uint8ClampedArray(4 * s2); + for (let t4 = 0;t4 < s2; ++t4) + e4[4 * t4] = r4[3 * t4], e4[4 * t4 + 1] = r4[3 * t4 + 1], e4[4 * t4 + 2] = r4[3 * t4 + 2], e4[4 * t4 + 3] = 255; + r4 = new ImageData(e4, i2, t3); + } else { + if (r4.length !== 4 * s2) + throw Error("Unsupported channel count: " + r4.length / s2); + r4 = new ImageData(new Uint8ClampedArray(r4.buffer, r4.byteOffset, r4.length), i2, t3); + } + else if (!(r4 instanceof WebGLTexture)) + throw Error(`Unsupported format: ${r4.constructor.name}`); + i2 = new ja([r4], false, false, this.g.i.canvas, this.R, i2, t3), this.s = n3 = n3 ? i2.clone() : i2, this.h && this.h(n3), $o(this, e3); + }), this.g.attachEmptyPacketListener("stylized_image", (t3) => { + this.s = null, this.h && this.h(null), $o(this, t3); + }), t2 = t2.g(), this.setGraph(new Uint8Array(t2), true); + } +}; +fh.prototype.stylize = fh.prototype.Ra, fh.prototype.setOptions = fh.prototype.o, fh.createFromModelPath = function(t2, e2) { + return Ka(fh, t2, { baseOptions: { modelAssetPath: e2 } }); +}, fh.createFromModelBuffer = function(t2, e2) { + return Ka(fh, t2, { baseOptions: { modelAssetBuffer: e2 } }); +}, fh.createFromOptions = function(t2, e2) { + return Ka(fh, t2, e2); +}; +var dh = Xa([0, 1], [1, 2], [2, 3], [3, 4], [0, 5], [5, 6], [6, 7], [7, 8], [5, 9], [9, 10], [10, 11], [11, 12], [9, 13], [13, 14], [14, 15], [15, 16], [13, 17], [0, 17], [17, 18], [18, 19], [19, 20]); +var yh = class extends Za { + constructor(t2, e2) { + super(new za(t2, e2), "image_in", "norm_rect", false), this.gestures = [], this.landmarks = [], this.worldLandmarks = [], this.handedness = [], yn(t2 = this.j = new Js, 0, 1, e2 = new xs), this.s = new qs, yn(this.j, 0, 2, this.s), this.C = new $s, yn(this.s, 0, 3, this.C), this.v = new Ys, yn(this.s, 0, 2, this.v), this.h = new Ks, yn(this.j, 0, 3, this.h), Ln(this.v, 2, 0.5), Ln(this.s, 4, 0.5), Ln(this.C, 2, 0.5); + } + get baseOptions() { + return pn(this.j, xs, 1); + } + set baseOptions(t2) { + yn(this.j, 0, 1, t2); + } + o(t2) { + if (xn(this.v, 3, t2.numHands ?? 1), "minHandDetectionConfidence" in t2 && Ln(this.v, 2, t2.minHandDetectionConfidence ?? 0.5), "minTrackingConfidence" in t2 && Ln(this.s, 4, t2.minTrackingConfidence ?? 0.5), "minHandPresenceConfidence" in t2 && Ln(this.C, 2, t2.minHandPresenceConfidence ?? 0.5), t2.cannedGesturesClassifierOptions) { + var e2 = new Hs, n2 = e2, r4 = So(t2.cannedGesturesClassifierOptions, pn(this.h, Hs, 3)?.h()); + yn(n2, 0, 2, r4), yn(this.h, 0, 3, e2); + } else + t2.cannedGesturesClassifierOptions === undefined && pn(this.h, Hs, 3)?.g(); + return t2.customGesturesClassifierOptions ? (yn(n2 = e2 = new Hs, 0, 2, r4 = So(t2.customGesturesClassifierOptions, pn(this.h, Hs, 4)?.h())), yn(this.h, 0, 4, e2)) : t2.customGesturesClassifierOptions === undefined && pn(this.h, Hs, 4)?.g(), this.l(t2); + } + Ma(t2, e2) { + return ph(this), $a(this, t2, e2), gh(this); + } + Na(t2, e2, n2) { + return ph(this), qa(this, t2, n2, e2), gh(this); + } + m() { + var t2 = new $i; + Ki(t2, "image_in"), Ki(t2, "norm_rect"), Yi(t2, "hand_gestures"), Yi(t2, "hand_landmarks"), Yi(t2, "world_hand_landmarks"), Yi(t2, "handedness"); + const e2 = new Ci; + er(e2, io, this.j); + const n2 = new Vi; + Bi(n2, "mediapipe.tasks.vision.gesture_recognizer.GestureRecognizerGraph"), Gi(n2, "IMAGE:image_in"), Gi(n2, "NORM_RECT:norm_rect"), ji(n2, "HAND_GESTURES:hand_gestures"), ji(n2, "LANDMARKS:hand_landmarks"), ji(n2, "WORLD_LANDMARKS:world_hand_landmarks"), ji(n2, "HANDEDNESS:handedness"), n2.o(e2), zi(t2, n2), this.g.attachProtoVectorListener("hand_landmarks", (t3, e3) => { + for (const e4 of t3) { + t3 = cs(e4); + const n3 = []; + for (const e5 of mn(t3, hs, 1)) + n3.push({ x: bn(e5, 1) ?? 0, y: bn(e5, 2) ?? 0, z: bn(e5, 3) ?? 0, visibility: bn(e5, 4) ?? 0 }); + this.landmarks.push(n3); + } + $o(this, e3); + }), this.g.attachEmptyPacketListener("hand_landmarks", (t3) => { + $o(this, t3); + }), this.g.attachProtoVectorListener("world_hand_landmarks", (t3, e3) => { + for (const e4 of t3) { + t3 = as(e4); + const n3 = []; + for (const e5 of mn(t3, os, 1)) + n3.push({ x: bn(e5, 1) ?? 0, y: bn(e5, 2) ?? 0, z: bn(e5, 3) ?? 0, visibility: bn(e5, 4) ?? 0 }); + this.worldLandmarks.push(n3); + } + $o(this, e3); + }), this.g.attachEmptyPacketListener("world_hand_landmarks", (t3) => { + $o(this, t3); + }), this.g.attachProtoVectorListener("hand_gestures", (t3, e3) => { + this.gestures.push(...mh(t3, false)), $o(this, e3); + }), this.g.attachEmptyPacketListener("hand_gestures", (t3) => { + $o(this, t3); + }), this.g.attachProtoVectorListener("handedness", (t3, e3) => { + this.handedness.push(...mh(t3)), $o(this, e3); + }), this.g.attachEmptyPacketListener("handedness", (t3) => { + $o(this, t3); + }), t2 = t2.g(), this.setGraph(new Uint8Array(t2), true); + } +}; +yh.prototype.recognizeForVideo = yh.prototype.Na, yh.prototype.recognize = yh.prototype.Ma, yh.prototype.setOptions = yh.prototype.o, yh.createFromModelPath = function(t2, e2) { + return Ka(yh, t2, { baseOptions: { modelAssetPath: e2 } }); +}, yh.createFromModelBuffer = function(t2, e2) { + return Ka(yh, t2, { baseOptions: { modelAssetBuffer: e2 } }); +}, yh.createFromOptions = function(t2, e2) { + return Ka(yh, t2, e2); +}, yh.HAND_CONNECTIONS = dh; +var vh = class extends Za { + constructor(t2, e2) { + super(new za(t2, e2), "image_in", "norm_rect", false), this.landmarks = [], this.worldLandmarks = [], this.handedness = [], yn(t2 = this.h = new qs, 0, 1, e2 = new xs), this.s = new $s, yn(this.h, 0, 3, this.s), this.j = new Ys, yn(this.h, 0, 2, this.j), xn(this.j, 3, 1), Ln(this.j, 2, 0.5), Ln(this.s, 2, 0.5), Ln(this.h, 4, 0.5); + } + get baseOptions() { + return pn(this.h, xs, 1); + } + set baseOptions(t2) { + yn(this.h, 0, 1, t2); + } + o(t2) { + return "numHands" in t2 && xn(this.j, 3, t2.numHands ?? 1), "minHandDetectionConfidence" in t2 && Ln(this.j, 2, t2.minHandDetectionConfidence ?? 0.5), "minTrackingConfidence" in t2 && Ln(this.h, 4, t2.minTrackingConfidence ?? 0.5), "minHandPresenceConfidence" in t2 && Ln(this.s, 2, t2.minHandPresenceConfidence ?? 0.5), this.l(t2); + } + D(t2, e2) { + return this.landmarks = [], this.worldLandmarks = [], this.handedness = [], $a(this, t2, e2), _h(this); + } + F(t2, e2, n2) { + return this.landmarks = [], this.worldLandmarks = [], this.handedness = [], qa(this, t2, n2, e2), _h(this); + } + m() { + var t2 = new $i; + Ki(t2, "image_in"), Ki(t2, "norm_rect"), Yi(t2, "hand_landmarks"), Yi(t2, "world_hand_landmarks"), Yi(t2, "handedness"); + const e2 = new Ci; + er(e2, ro, this.h); + const n2 = new Vi; + Bi(n2, "mediapipe.tasks.vision.hand_landmarker.HandLandmarkerGraph"), Gi(n2, "IMAGE:image_in"), Gi(n2, "NORM_RECT:norm_rect"), ji(n2, "LANDMARKS:hand_landmarks"), ji(n2, "WORLD_LANDMARKS:world_hand_landmarks"), ji(n2, "HANDEDNESS:handedness"), n2.o(e2), zi(t2, n2), this.g.attachProtoVectorListener("hand_landmarks", (t3, e3) => { + for (const e4 of t3) + t3 = cs(e4), this.landmarks.push(Ro(t3)); + $o(this, e3); + }), this.g.attachEmptyPacketListener("hand_landmarks", (t3) => { + $o(this, t3); + }), this.g.attachProtoVectorListener("world_hand_landmarks", (t3, e3) => { + for (const e4 of t3) + t3 = as(e4), this.worldLandmarks.push(Fo(t3)); + $o(this, e3); + }), this.g.attachEmptyPacketListener("world_hand_landmarks", (t3) => { + $o(this, t3); + }), this.g.attachProtoVectorListener("handedness", (t3, e3) => { + var n3 = this.handedness, r4 = n3.push; + const i2 = []; + for (const e4 of t3) { + t3 = es(e4); + const n4 = []; + for (const e5 of t3.g()) + n4.push({ score: bn(e5, 2) ?? 0, index: Tn(An(e5, 1), 0) ?? -1, categoryName: kn(e5, 3) ?? "", displayName: kn(e5, 4) ?? "" }); + i2.push(n4); + } + r4.call(n3, ...i2), $o(this, e3); + }), this.g.attachEmptyPacketListener("handedness", (t3) => { + $o(this, t3); + }), t2 = t2.g(), this.setGraph(new Uint8Array(t2), true); + } +}; +vh.prototype.detectForVideo = vh.prototype.F, vh.prototype.detect = vh.prototype.D, vh.prototype.setOptions = vh.prototype.o, vh.createFromModelPath = function(t2, e2) { + return Ka(vh, t2, { baseOptions: { modelAssetPath: e2 } }); +}, vh.createFromModelBuffer = function(t2, e2) { + return Ka(vh, t2, { baseOptions: { modelAssetBuffer: e2 } }); +}, vh.createFromOptions = function(t2, e2) { + return Ka(vh, t2, e2); +}, vh.HAND_CONNECTIONS = dh; +var Eh = Xa([0, 1], [1, 2], [2, 3], [3, 7], [0, 4], [4, 5], [5, 6], [6, 8], [9, 10], [11, 12], [11, 13], [13, 15], [15, 17], [15, 19], [15, 21], [17, 19], [12, 14], [14, 16], [16, 18], [16, 20], [16, 22], [18, 20], [11, 23], [12, 24], [23, 24], [23, 25], [24, 26], [25, 27], [26, 28], [27, 29], [28, 30], [29, 31], [30, 32], [27, 31], [28, 32]); +var bh = class extends Za { + constructor(t2, e2) { + super(new za(t2, e2), "input_frames_image", null, false), this.h = { faceLandmarks: [], faceBlendshapes: [], poseLandmarks: [], poseWorldLandmarks: [], poseSegmentationMasks: [], leftHandLandmarks: [], leftHandWorldLandmarks: [], rightHandLandmarks: [], rightHandWorldLandmarks: [] }, this.outputPoseSegmentationMasks = this.outputFaceBlendshapes = false, yn(t2 = this.j = new ho, 0, 1, e2 = new xs), this.K = new $s, yn(this.j, 0, 2, this.K), this.ca = new so, yn(this.j, 0, 3, this.ca), this.s = new Fs, yn(this.j, 0, 4, this.s), this.I = new Us, yn(this.j, 0, 5, this.I), this.v = new oo, yn(this.j, 0, 6, this.v), this.L = new ao, yn(this.j, 0, 7, this.L), Ln(this.s, 2, 0.5), Ln(this.s, 3, 0.3), Ln(this.I, 2, 0.5), Ln(this.v, 2, 0.5), Ln(this.v, 3, 0.3), Ln(this.L, 2, 0.5), Ln(this.K, 2, 0.5); + } + get baseOptions() { + return pn(this.j, xs, 1); + } + set baseOptions(t2) { + yn(this.j, 0, 1, t2); + } + o(t2) { + return "minFaceDetectionConfidence" in t2 && Ln(this.s, 2, t2.minFaceDetectionConfidence ?? 0.5), "minFaceSuppressionThreshold" in t2 && Ln(this.s, 3, t2.minFaceSuppressionThreshold ?? 0.3), "minFacePresenceConfidence" in t2 && Ln(this.I, 2, t2.minFacePresenceConfidence ?? 0.5), "outputFaceBlendshapes" in t2 && (this.outputFaceBlendshapes = !!t2.outputFaceBlendshapes), "minPoseDetectionConfidence" in t2 && Ln(this.v, 2, t2.minPoseDetectionConfidence ?? 0.5), "minPoseSuppressionThreshold" in t2 && Ln(this.v, 3, t2.minPoseSuppressionThreshold ?? 0.3), "minPosePresenceConfidence" in t2 && Ln(this.L, 2, t2.minPosePresenceConfidence ?? 0.5), "outputPoseSegmentationMasks" in t2 && (this.outputPoseSegmentationMasks = !!t2.outputPoseSegmentationMasks), "minHandLandmarksConfidence" in t2 && Ln(this.K, 2, t2.minHandLandmarksConfidence ?? 0.5), this.l(t2); + } + D(t2, e2, n2) { + const r4 = typeof e2 != "function" ? e2 : {}; + return this.C = typeof e2 == "function" ? e2 : n2, wh(this), $a(this, t2, r4), Th(this); + } + F(t2, e2, n2, r4) { + const i2 = typeof n2 != "function" ? n2 : {}; + return this.C = typeof n2 == "function" ? n2 : r4, wh(this), qa(this, t2, i2, e2), Th(this); + } + m() { + var t2 = new $i; + Ki(t2, "input_frames_image"), Yi(t2, "pose_landmarks"), Yi(t2, "pose_world_landmarks"), Yi(t2, "face_landmarks"), Yi(t2, "left_hand_landmarks"), Yi(t2, "left_hand_world_landmarks"), Yi(t2, "right_hand_landmarks"), Yi(t2, "right_hand_world_landmarks"); + const e2 = new Ci, n2 = new ki; + an(n2, 1, ne("type.googleapis.com/mediapipe.tasks.vision.holistic_landmarker.proto.HolisticLandmarkerGraphOptions"), ""), function(t3, e3) { + if (e3 != null) + if (Array.isArray(e3)) + $e(t3, 2, De(e3, Ge, undefined, undefined, false)); + else { + if (!(typeof e3 == "string" || e3 instanceof D || I(e3))) + throw Error("invalid value in Any.value field: " + e3 + " expected a ByteString, a base64 encoded string, a Uint8Array or a jspb array"); + an(t3, 2, lt(e3, false, false), N()); + } + }(n2, this.j.g()); + const r4 = new Vi; + Bi(r4, "mediapipe.tasks.vision.holistic_landmarker.HolisticLandmarkerGraph"), wn(r4, 8, ki, n2), Gi(r4, "IMAGE:input_frames_image"), ji(r4, "POSE_LANDMARKS:pose_landmarks"), ji(r4, "POSE_WORLD_LANDMARKS:pose_world_landmarks"), ji(r4, "FACE_LANDMARKS:face_landmarks"), ji(r4, "LEFT_HAND_LANDMARKS:left_hand_landmarks"), ji(r4, "LEFT_HAND_WORLD_LANDMARKS:left_hand_world_landmarks"), ji(r4, "RIGHT_HAND_LANDMARKS:right_hand_landmarks"), ji(r4, "RIGHT_HAND_WORLD_LANDMARKS:right_hand_world_landmarks"), r4.o(e2), zi(t2, r4), qo(this, t2), this.g.attachProtoListener("pose_landmarks", (t3, e3) => { + Ah(t3, this.h.poseLandmarks), $o(this, e3); + }), this.g.attachEmptyPacketListener("pose_landmarks", (t3) => { + $o(this, t3); + }), this.g.attachProtoListener("pose_world_landmarks", (t3, e3) => { + var n3 = this.h.poseWorldLandmarks; + t3 = as(t3), n3.push(Fo(t3)), $o(this, e3); + }), this.g.attachEmptyPacketListener("pose_world_landmarks", (t3) => { + $o(this, t3); + }), this.outputPoseSegmentationMasks && (ji(r4, "POSE_SEGMENTATION_MASK:pose_segmentation_mask"), Jo(this, "pose_segmentation_mask"), this.g.W("pose_segmentation_mask", (t3, e3) => { + this.h.poseSegmentationMasks = [Ja(this, t3, true, !this.C)], $o(this, e3); + }), this.g.attachEmptyPacketListener("pose_segmentation_mask", (t3) => { + this.h.poseSegmentationMasks = [], $o(this, t3); + })), this.g.attachProtoListener("face_landmarks", (t3, e3) => { + Ah(t3, this.h.faceLandmarks), $o(this, e3); + }), this.g.attachEmptyPacketListener("face_landmarks", (t3) => { + $o(this, t3); + }), this.outputFaceBlendshapes && (Yi(t2, "extra_blendshapes"), ji(r4, "FACE_BLENDSHAPES:extra_blendshapes"), this.g.attachProtoListener("extra_blendshapes", (t3, e3) => { + var n3 = this.h.faceBlendshapes; + this.outputFaceBlendshapes && (t3 = es(t3), n3.push(xo(t3.g() ?? []))), $o(this, e3); + }), this.g.attachEmptyPacketListener("extra_blendshapes", (t3) => { + $o(this, t3); + })), this.g.attachProtoListener("left_hand_landmarks", (t3, e3) => { + Ah(t3, this.h.leftHandLandmarks), $o(this, e3); + }), this.g.attachEmptyPacketListener("left_hand_landmarks", (t3) => { + $o(this, t3); + }), this.g.attachProtoListener("left_hand_world_landmarks", (t3, e3) => { + var n3 = this.h.leftHandWorldLandmarks; + t3 = as(t3), n3.push(Fo(t3)), $o(this, e3); + }), this.g.attachEmptyPacketListener("left_hand_world_landmarks", (t3) => { + $o(this, t3); + }), this.g.attachProtoListener("right_hand_landmarks", (t3, e3) => { + Ah(t3, this.h.rightHandLandmarks), $o(this, e3); + }), this.g.attachEmptyPacketListener("right_hand_landmarks", (t3) => { + $o(this, t3); + }), this.g.attachProtoListener("right_hand_world_landmarks", (t3, e3) => { + var n3 = this.h.rightHandWorldLandmarks; + t3 = as(t3), n3.push(Fo(t3)), $o(this, e3); + }), this.g.attachEmptyPacketListener("right_hand_world_landmarks", (t3) => { + $o(this, t3); + }), t2 = t2.g(), this.setGraph(new Uint8Array(t2), true); + } +}; +bh.prototype.detectForVideo = bh.prototype.F, bh.prototype.detect = bh.prototype.D, bh.prototype.setOptions = bh.prototype.o, bh.createFromModelPath = function(t2, e2) { + return Ka(bh, t2, { baseOptions: { modelAssetPath: e2 } }); +}, bh.createFromModelBuffer = function(t2, e2) { + return Ka(bh, t2, { baseOptions: { modelAssetBuffer: e2 } }); +}, bh.createFromOptions = function(t2, e2) { + return Ka(bh, t2, e2); +}, bh.HAND_CONNECTIONS = dh, bh.POSE_CONNECTIONS = Eh, bh.FACE_LANDMARKS_LIPS = th, bh.FACE_LANDMARKS_LEFT_EYE = eh, bh.FACE_LANDMARKS_LEFT_EYEBROW = nh, bh.FACE_LANDMARKS_LEFT_IRIS = rh, bh.FACE_LANDMARKS_RIGHT_EYE = ih, bh.FACE_LANDMARKS_RIGHT_EYEBROW = sh, bh.FACE_LANDMARKS_RIGHT_IRIS = oh, bh.FACE_LANDMARKS_FACE_OVAL = ah, bh.FACE_LANDMARKS_CONTOURS = hh, bh.FACE_LANDMARKS_TESSELATION = ch; +var kh = class extends Za { + constructor(t2, e2) { + super(new za(t2, e2), "input_image", "norm_rect", true), this.j = { classifications: [] }, yn(t2 = this.h = new lo, 0, 1, e2 = new xs); + } + get baseOptions() { + return pn(this.h, xs, 1); + } + set baseOptions(t2) { + yn(this.h, 0, 1, t2); + } + o(t2) { + return yn(this.h, 0, 2, So(t2, pn(this.h, Es, 2))), this.l(t2); + } + wa(t2, e2) { + return this.j = { classifications: [] }, $a(this, t2, e2), this.j; + } + xa(t2, e2, n2) { + return this.j = { classifications: [] }, qa(this, t2, n2, e2), this.j; + } + m() { + var t2 = new $i; + Ki(t2, "input_image"), Ki(t2, "norm_rect"), Yi(t2, "classifications"); + const e2 = new Ci; + er(e2, fo, this.h); + const n2 = new Vi; + Bi(n2, "mediapipe.tasks.vision.image_classifier.ImageClassifierGraph"), Gi(n2, "IMAGE:input_image"), Gi(n2, "NORM_RECT:norm_rect"), ji(n2, "CLASSIFICATIONS:classifications"), n2.o(e2), zi(t2, n2), this.g.attachProtoListener("classifications", (t3, e3) => { + this.j = function(t4) { + const e4 = { classifications: mn(t4, ds, 1).map((t5) => xo(pn(t5, Qi, 4)?.g() ?? [], Tn(An(t5, 2), 0), kn(t5, 3))) }; + return Qt(ze(t4, 2)) != null && (e4.timestampMs = Tn(Qt(ze(t4, 2)), 0)), e4; + }(ps(t3)), $o(this, e3); + }), this.g.attachEmptyPacketListener("classifications", (t3) => { + $o(this, t3); + }), t2 = t2.g(), this.setGraph(new Uint8Array(t2), true); + } +}; +kh.prototype.classifyForVideo = kh.prototype.xa, kh.prototype.classify = kh.prototype.wa, kh.prototype.setOptions = kh.prototype.o, kh.createFromModelPath = function(t2, e2) { + return Ka(kh, t2, { baseOptions: { modelAssetPath: e2 } }); +}, kh.createFromModelBuffer = function(t2, e2) { + return Ka(kh, t2, { baseOptions: { modelAssetBuffer: e2 } }); +}, kh.createFromOptions = function(t2, e2) { + return Ka(kh, t2, e2); +}; +var Sh = class extends Za { + constructor(t2, e2) { + super(new za(t2, e2), "image_in", "norm_rect", true), this.h = new po, this.embeddings = { embeddings: [] }, yn(t2 = this.h, 0, 1, e2 = new xs); + } + get baseOptions() { + return pn(this.h, xs, 1); + } + set baseOptions(t2) { + yn(this.h, 0, 1, t2); + } + o(t2) { + var e2 = this.h, n2 = pn(this.h, Ts, 2); + return n2 = n2 ? n2.clone() : new Ts, t2.l2Normalize !== undefined ? Sn(n2, 1, t2.l2Normalize) : ("l2Normalize" in t2) && $e(n2, 1), t2.quantize !== undefined ? Sn(n2, 2, t2.quantize) : ("quantize" in t2) && $e(n2, 2), yn(e2, 0, 2, n2), this.l(t2); + } + Da(t2, e2) { + return $a(this, t2, e2), this.embeddings; + } + Ea(t2, e2, n2) { + return qa(this, t2, n2, e2), this.embeddings; + } + m() { + var t2 = new $i; + Ki(t2, "image_in"), Ki(t2, "norm_rect"), Yi(t2, "embeddings_out"); + const e2 = new Ci; + er(e2, go, this.h); + const n2 = new Vi; + Bi(n2, "mediapipe.tasks.vision.image_embedder.ImageEmbedderGraph"), Gi(n2, "IMAGE:image_in"), Gi(n2, "NORM_RECT:norm_rect"), ji(n2, "EMBEDDINGS:embeddings_out"), n2.o(e2), zi(t2, n2), this.g.attachProtoListener("embeddings_out", (t3, e3) => { + t3 = vs(t3), this.embeddings = function(t4) { + return { embeddings: mn(t4, ys, 1).map((t5) => { + const e4 = { headIndex: Tn(An(t5, 3), 0) ?? -1, headName: kn(t5, 4) ?? "" }; + if (dn(t5, gs, hn(t5, 1)) !== undefined) + t5 = en(t5 = pn(t5, gs, hn(t5, 1)), 1, Ht, tn()), e4.floatEmbedding = t5.slice(); + else { + const n3 = new Uint8Array(0); + e4.quantizedEmbedding = pn(t5, ms, hn(t5, 2))?.ra()?.ua() ?? n3; + } + return e4; + }), timestampMs: Tn(Qt(ze(t4, 2)), 0) }; + }(t3), $o(this, e3); + }), this.g.attachEmptyPacketListener("embeddings_out", (t3) => { + $o(this, t3); + }), t2 = t2.g(), this.setGraph(new Uint8Array(t2), true); + } +}; +Sh.cosineSimilarity = function(t2, e2) { + if (t2.floatEmbedding && e2.floatEmbedding) + t2 = Io(t2.floatEmbedding, e2.floatEmbedding); + else { + if (!t2.quantizedEmbedding || !e2.quantizedEmbedding) + throw Error("Cannot compute cosine similarity between quantized and float embeddings."); + t2 = Io(Mo(t2.quantizedEmbedding), Mo(e2.quantizedEmbedding)); + } + return t2; +}, Sh.prototype.embedForVideo = Sh.prototype.Ea, Sh.prototype.embed = Sh.prototype.Da, Sh.prototype.setOptions = Sh.prototype.o, Sh.createFromModelPath = function(t2, e2) { + return Ka(Sh, t2, { baseOptions: { modelAssetPath: e2 } }); +}, Sh.createFromModelBuffer = function(t2, e2) { + return Ka(Sh, t2, { baseOptions: { modelAssetBuffer: e2 } }); +}, Sh.createFromOptions = function(t2, e2) { + return Ka(Sh, t2, e2); +}; +var xh = class { + constructor(t2, e2, n2) { + this.confidenceMasks = t2, this.categoryMask = e2, this.qualityScores = n2; + } + close() { + this.confidenceMasks?.forEach((t2) => { + t2.close(); + }), this.categoryMask?.close(); + } +}; +xh.prototype.close = xh.prototype.close; +var Fh = class extends Za { + constructor(t2, e2) { + super(new za(t2, e2), "image_in", "norm_rect", false), this.s = [], this.outputCategoryMask = false, this.outputConfidenceMasks = true, this.h = new Eo, this.v = new mo, yn(this.h, 0, 3, this.v), yn(t2 = this.h, 0, 1, e2 = new xs); + } + get baseOptions() { + return pn(this.h, xs, 1); + } + set baseOptions(t2) { + yn(this.h, 0, 1, t2); + } + o(t2) { + return t2.displayNamesLocale !== undefined ? $e(this.h, 2, ne(t2.displayNamesLocale)) : ("displayNamesLocale" in t2) && $e(this.h, 2), "outputCategoryMask" in t2 && (this.outputCategoryMask = t2.outputCategoryMask ?? false), "outputConfidenceMasks" in t2 && (this.outputConfidenceMasks = t2.outputConfidenceMasks ?? true), super.l(t2); + } + J() { + (function(t2) { + const e2 = mn(t2.ga(), Vi, 1).filter((t3) => kn(t3, 1).includes("mediapipe.tasks.TensorsToSegmentationCalculator")); + if (t2.s = [], e2.length > 1) + throw Error("The graph has more than one mediapipe.tasks.TensorsToSegmentationCalculator."); + e2.length === 1 && (pn(e2[0], Ci, 7)?.l()?.g() ?? new Map).forEach((e3, n2) => { + t2.s[Number(n2)] = kn(e3, 1); + }); + })(this); + } + ha(t2, e2, n2) { + const r4 = typeof e2 != "function" ? e2 : {}; + return this.j = typeof e2 == "function" ? e2 : n2, Lh(this), $a(this, t2, r4), Rh(this); + } + Pa(t2, e2, n2, r4) { + const i2 = typeof n2 != "function" ? n2 : {}; + return this.j = typeof n2 == "function" ? n2 : r4, Lh(this), qa(this, t2, i2, e2), Rh(this); + } + Ha() { + return this.s; + } + m() { + var t2 = new $i; + Ki(t2, "image_in"), Ki(t2, "norm_rect"); + const e2 = new Ci; + er(e2, wo, this.h); + const n2 = new Vi; + Bi(n2, "mediapipe.tasks.vision.image_segmenter.ImageSegmenterGraph"), Gi(n2, "IMAGE:image_in"), Gi(n2, "NORM_RECT:norm_rect"), n2.o(e2), zi(t2, n2), qo(this, t2), this.outputConfidenceMasks && (Yi(t2, "confidence_masks"), ji(n2, "CONFIDENCE_MASKS:confidence_masks"), Jo(this, "confidence_masks"), this.g.fa("confidence_masks", (t3, e3) => { + this.confidenceMasks = t3.map((t4) => Ja(this, t4, true, !this.j)), $o(this, e3); + }), this.g.attachEmptyPacketListener("confidence_masks", (t3) => { + this.confidenceMasks = [], $o(this, t3); + })), this.outputCategoryMask && (Yi(t2, "category_mask"), ji(n2, "CATEGORY_MASK:category_mask"), Jo(this, "category_mask"), this.g.W("category_mask", (t3, e3) => { + this.categoryMask = Ja(this, t3, false, !this.j), $o(this, e3); + }), this.g.attachEmptyPacketListener("category_mask", (t3) => { + this.categoryMask = undefined, $o(this, t3); + })), Yi(t2, "quality_scores"), ji(n2, "QUALITY_SCORES:quality_scores"), this.g.attachFloatVectorListener("quality_scores", (t3, e3) => { + this.qualityScores = t3, $o(this, e3); + }), this.g.attachEmptyPacketListener("quality_scores", (t3) => { + this.categoryMask = undefined, $o(this, t3); + }), t2 = t2.g(), this.setGraph(new Uint8Array(t2), true); + } +}; +Fh.prototype.getLabels = Fh.prototype.Ha, Fh.prototype.segmentForVideo = Fh.prototype.Pa, Fh.prototype.segment = Fh.prototype.ha, Fh.prototype.setOptions = Fh.prototype.o, Fh.createFromModelPath = function(t2, e2) { + return Ka(Fh, t2, { baseOptions: { modelAssetPath: e2 } }); +}, Fh.createFromModelBuffer = function(t2, e2) { + return Ka(Fh, t2, { baseOptions: { modelAssetBuffer: e2 } }); +}, Fh.createFromOptions = function(t2, e2) { + return Ka(Fh, t2, e2); +}; +var Mh = class { + constructor(t2, e2, n2) { + this.confidenceMasks = t2, this.categoryMask = e2, this.qualityScores = n2; + } + close() { + this.confidenceMasks?.forEach((t2) => { + t2.close(); + }), this.categoryMask?.close(); + } +}; +Mh.prototype.close = Mh.prototype.close; +var Ih = class extends nr { + constructor(t2) { + super(t2); + } +}; +var Ph = [0, ai, -2]; +var Oh = [0, ti, -3, ui, ti, -1]; +var Ch = [0, Oh]; +var Nh = [0, Oh, ai, -1]; +var Uh = class extends nr { + constructor(t2) { + super(t2); + } +}; +var Dh = [0, ti, -1, ui]; +var Bh = class extends nr { + constructor() { + super(); + } +}; +var Gh = class extends nr { + constructor(t2) { + super(t2); + } +}; +var jh = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 14, 15]; +var Vh = class extends nr { + constructor() { + super(); + } +}; +Vh.prototype.g = bi([0, Qr, [0, jh, yi, Oh, yi, [0, Oh, Ph], yi, Ch, yi, [0, Ch, Ph], yi, Dh, yi, [0, ti, -3, ui, Ei], yi, [0, ti, -3, ui], yi, [0, pi, ti, -2, ui, ai, ui, -1, 2, ti, Ph], yi, Nh, yi, [0, Nh, Ph], ti, Ph, pi, yi, [0, ti, -3, ui, Ph, -1], yi, [0, Qr, Dh]], pi, [0, pi, ai, -1, ui]]); +var Xh = class extends Za { + constructor(t2, e2) { + super(new za(t2, e2), "image_in", "norm_rect_in", false), this.outputCategoryMask = false, this.outputConfidenceMasks = true, this.h = new Eo, this.s = new mo, yn(this.h, 0, 3, this.s), yn(t2 = this.h, 0, 1, e2 = new xs); + } + get baseOptions() { + return pn(this.h, xs, 1); + } + set baseOptions(t2) { + yn(this.h, 0, 1, t2); + } + o(t2) { + return "outputCategoryMask" in t2 && (this.outputCategoryMask = t2.outputCategoryMask ?? false), "outputConfidenceMasks" in t2 && (this.outputConfidenceMasks = t2.outputConfidenceMasks ?? true), super.l(t2); + } + ha(t2, e2, n2, r4) { + const i2 = typeof n2 != "function" ? n2 : {}; + this.j = typeof n2 == "function" ? n2 : r4, this.qualityScores = this.categoryMask = this.confidenceMasks = undefined, n2 = this.B + 1, r4 = new Vh; + const s2 = new Gh; + var o2 = new Ih; + if (xn(o2, 1, 255), yn(s2, 0, 12, o2), e2.keypoint && e2.scribble) + throw Error("Cannot provide both keypoint and scribble."); + if (e2.keypoint) { + var a2 = new Uh; + Sn(a2, 3, true), Ln(a2, 1, e2.keypoint.x), Ln(a2, 2, e2.keypoint.y), _n(s2, 5, jh, a2); + } else { + if (!e2.scribble) + throw Error("Must provide either a keypoint or a scribble."); + for (a2 of (o2 = new Bh, e2.scribble)) + Sn(e2 = new Uh, 3, true), Ln(e2, 1, a2.x), Ln(e2, 2, a2.y), wn(o2, 1, Uh, e2); + _n(s2, 15, jh, o2); + } + wn(r4, 1, Gh, s2), this.g.addProtoToStream(r4.g(), "drishti.RenderData", "roi_in", n2), $a(this, t2, i2); + t: { + try { + const t3 = new Mh(this.confidenceMasks, this.categoryMask, this.qualityScores); + if (!this.j) { + var h2 = t3; + break t; + } + this.j(t3); + } finally { + Zo(this); + } + h2 = undefined; + } + return h2; + } + m() { + var t2 = new $i; + Ki(t2, "image_in"), Ki(t2, "roi_in"), Ki(t2, "norm_rect_in"); + const e2 = new Ci; + er(e2, wo, this.h); + const n2 = new Vi; + Bi(n2, "mediapipe.tasks.vision.interactive_segmenter.InteractiveSegmenterGraph"), Gi(n2, "IMAGE:image_in"), Gi(n2, "ROI:roi_in"), Gi(n2, "NORM_RECT:norm_rect_in"), n2.o(e2), zi(t2, n2), qo(this, t2), this.outputConfidenceMasks && (Yi(t2, "confidence_masks"), ji(n2, "CONFIDENCE_MASKS:confidence_masks"), Jo(this, "confidence_masks"), this.g.fa("confidence_masks", (t3, e3) => { + this.confidenceMasks = t3.map((t4) => Ja(this, t4, true, !this.j)), $o(this, e3); + }), this.g.attachEmptyPacketListener("confidence_masks", (t3) => { + this.confidenceMasks = [], $o(this, t3); + })), this.outputCategoryMask && (Yi(t2, "category_mask"), ji(n2, "CATEGORY_MASK:category_mask"), Jo(this, "category_mask"), this.g.W("category_mask", (t3, e3) => { + this.categoryMask = Ja(this, t3, false, !this.j), $o(this, e3); + }), this.g.attachEmptyPacketListener("category_mask", (t3) => { + this.categoryMask = undefined, $o(this, t3); + })), Yi(t2, "quality_scores"), ji(n2, "QUALITY_SCORES:quality_scores"), this.g.attachFloatVectorListener("quality_scores", (t3, e3) => { + this.qualityScores = t3, $o(this, e3); + }), this.g.attachEmptyPacketListener("quality_scores", (t3) => { + this.categoryMask = undefined, $o(this, t3); + }), t2 = t2.g(), this.setGraph(new Uint8Array(t2), true); + } +}; +Xh.prototype.segment = Xh.prototype.ha, Xh.prototype.setOptions = Xh.prototype.o, Xh.createFromModelPath = function(t2, e2) { + return Ka(Xh, t2, { baseOptions: { modelAssetPath: e2 } }); +}, Xh.createFromModelBuffer = function(t2, e2) { + return Ka(Xh, t2, { baseOptions: { modelAssetBuffer: e2 } }); +}, Xh.createFromOptions = function(t2, e2) { + return Ka(Xh, t2, e2); +}; +var Hh = class extends Za { + constructor(t2, e2) { + super(new za(t2, e2), "input_frame_gpu", "norm_rect", false), this.j = { detections: [] }, yn(t2 = this.h = new To, 0, 1, e2 = new xs); + } + get baseOptions() { + return pn(this.h, xs, 1); + } + set baseOptions(t2) { + yn(this.h, 0, 1, t2); + } + o(t2) { + return t2.displayNamesLocale !== undefined ? $e(this.h, 2, ne(t2.displayNamesLocale)) : ("displayNamesLocale" in t2) && $e(this.h, 2), t2.maxResults !== undefined ? xn(this.h, 3, t2.maxResults) : ("maxResults" in t2) && $e(this.h, 3), t2.scoreThreshold !== undefined ? Ln(this.h, 4, t2.scoreThreshold) : ("scoreThreshold" in t2) && $e(this.h, 4), t2.categoryAllowlist !== undefined ? Rn(this.h, 5, t2.categoryAllowlist) : ("categoryAllowlist" in t2) && $e(this.h, 5), t2.categoryDenylist !== undefined ? Rn(this.h, 6, t2.categoryDenylist) : ("categoryDenylist" in t2) && $e(this.h, 6), this.l(t2); + } + D(t2, e2) { + return this.j = { detections: [] }, $a(this, t2, e2), this.j; + } + F(t2, e2, n2) { + return this.j = { detections: [] }, qa(this, t2, n2, e2), this.j; + } + m() { + var t2 = new $i; + Ki(t2, "input_frame_gpu"), Ki(t2, "norm_rect"), Yi(t2, "detections"); + const e2 = new Ci; + er(e2, Ao, this.h); + const n2 = new Vi; + Bi(n2, "mediapipe.tasks.vision.ObjectDetectorGraph"), Gi(n2, "IMAGE:input_frame_gpu"), Gi(n2, "NORM_RECT:norm_rect"), ji(n2, "DETECTIONS:detections"), n2.o(e2), zi(t2, n2), this.g.attachProtoVectorListener("detections", (t3, e3) => { + for (const e4 of t3) + t3 = ss(e4), this.j.detections.push(Lo(t3)); + $o(this, e3); + }), this.g.attachEmptyPacketListener("detections", (t3) => { + $o(this, t3); + }), t2 = t2.g(), this.setGraph(new Uint8Array(t2), true); + } +}; +Hh.prototype.detectForVideo = Hh.prototype.F, Hh.prototype.detect = Hh.prototype.D, Hh.prototype.setOptions = Hh.prototype.o, Hh.createFromModelPath = async function(t2, e2) { + return Ka(Hh, t2, { baseOptions: { modelAssetPath: e2 } }); +}, Hh.createFromModelBuffer = function(t2, e2) { + return Ka(Hh, t2, { baseOptions: { modelAssetBuffer: e2 } }); +}, Hh.createFromOptions = function(t2, e2) { + return Ka(Hh, t2, e2); +}; +var Wh = class { + constructor(t2, e2, n2) { + this.landmarks = t2, this.worldLandmarks = e2, this.segmentationMasks = n2; + } + close() { + this.segmentationMasks?.forEach((t2) => { + t2.close(); + }); + } +}; +Wh.prototype.close = Wh.prototype.close; +var Yh = class extends Za { + constructor(t2, e2) { + super(new za(t2, e2), "image_in", "norm_rect", false), this.landmarks = [], this.worldLandmarks = [], this.outputSegmentationMasks = false, yn(t2 = this.h = new bo, 0, 1, e2 = new xs), this.v = new ao, yn(this.h, 0, 3, this.v), this.j = new oo, yn(this.h, 0, 2, this.j), xn(this.j, 4, 1), Ln(this.j, 2, 0.5), Ln(this.v, 2, 0.5), Ln(this.h, 4, 0.5); + } + get baseOptions() { + return pn(this.h, xs, 1); + } + set baseOptions(t2) { + yn(this.h, 0, 1, t2); + } + o(t2) { + return "numPoses" in t2 && xn(this.j, 4, t2.numPoses ?? 1), "minPoseDetectionConfidence" in t2 && Ln(this.j, 2, t2.minPoseDetectionConfidence ?? 0.5), "minTrackingConfidence" in t2 && Ln(this.h, 4, t2.minTrackingConfidence ?? 0.5), "minPosePresenceConfidence" in t2 && Ln(this.v, 2, t2.minPosePresenceConfidence ?? 0.5), "outputSegmentationMasks" in t2 && (this.outputSegmentationMasks = t2.outputSegmentationMasks ?? false), this.l(t2); + } + D(t2, e2, n2) { + const r4 = typeof e2 != "function" ? e2 : {}; + return this.s = typeof e2 == "function" ? e2 : n2, zh(this), $a(this, t2, r4), Kh(this); + } + F(t2, e2, n2, r4) { + const i2 = typeof n2 != "function" ? n2 : {}; + return this.s = typeof n2 == "function" ? n2 : r4, zh(this), qa(this, t2, i2, e2), Kh(this); + } + m() { + var t2 = new $i; + Ki(t2, "image_in"), Ki(t2, "norm_rect"), Yi(t2, "normalized_landmarks"), Yi(t2, "world_landmarks"), Yi(t2, "segmentation_masks"); + const e2 = new Ci; + er(e2, ko, this.h); + const n2 = new Vi; + Bi(n2, "mediapipe.tasks.vision.pose_landmarker.PoseLandmarkerGraph"), Gi(n2, "IMAGE:image_in"), Gi(n2, "NORM_RECT:norm_rect"), ji(n2, "NORM_LANDMARKS:normalized_landmarks"), ji(n2, "WORLD_LANDMARKS:world_landmarks"), n2.o(e2), zi(t2, n2), qo(this, t2), this.g.attachProtoVectorListener("normalized_landmarks", (t3, e3) => { + this.landmarks = []; + for (const e4 of t3) + t3 = cs(e4), this.landmarks.push(Ro(t3)); + $o(this, e3); + }), this.g.attachEmptyPacketListener("normalized_landmarks", (t3) => { + this.landmarks = [], $o(this, t3); + }), this.g.attachProtoVectorListener("world_landmarks", (t3, e3) => { + this.worldLandmarks = []; + for (const e4 of t3) + t3 = as(e4), this.worldLandmarks.push(Fo(t3)); + $o(this, e3); + }), this.g.attachEmptyPacketListener("world_landmarks", (t3) => { + this.worldLandmarks = [], $o(this, t3); + }), this.outputSegmentationMasks && (ji(n2, "SEGMENTATION_MASK:segmentation_masks"), Jo(this, "segmentation_masks"), this.g.fa("segmentation_masks", (t3, e3) => { + this.segmentationMasks = t3.map((t4) => Ja(this, t4, true, !this.s)), $o(this, e3); + }), this.g.attachEmptyPacketListener("segmentation_masks", (t3) => { + this.segmentationMasks = [], $o(this, t3); + })), t2 = t2.g(), this.setGraph(new Uint8Array(t2), true); + } +}; +Yh.prototype.detectForVideo = Yh.prototype.F, Yh.prototype.detect = Yh.prototype.D, Yh.prototype.setOptions = Yh.prototype.o, Yh.createFromModelPath = function(t2, e2) { + return Ka(Yh, t2, { baseOptions: { modelAssetPath: e2 } }); +}, Yh.createFromModelBuffer = function(t2, e2) { + return Ka(Yh, t2, { baseOptions: { modelAssetBuffer: e2 } }); +}, Yh.createFromOptions = function(t2, e2) { + return Ka(Yh, t2, e2); +}, Yh.POSE_CONNECTIONS = Eh; + +// node_modules/uuid/dist/esm-browser/stringify.js +function unsafeStringify(arr, offset = 0) { + return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); +} +var byteToHex = []; +for (i2 = 0;i2 < 256; ++i2) { + byteToHex.push((i2 + 256).toString(16).slice(1)); +} +var i2; + +// node_modules/uuid/dist/esm-browser/rng.js +var getRandomValues; +var rnds8 = new Uint8Array(16); +function rng() { + if (!getRandomValues) { + getRandomValues = typeof crypto !== "undefined" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto); + if (!getRandomValues) { + throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported"); + } + } + return getRandomValues(rnds8); +} + +// node_modules/uuid/dist/esm-browser/native.js +var randomUUID = typeof crypto !== "undefined" && crypto.randomUUID && crypto.randomUUID.bind(crypto); +var native_default = { + randomUUID +}; + +// node_modules/uuid/dist/esm-browser/v4.js +var v4 = function(options, buf, offset) { + if (native_default.randomUUID && !buf && !options) { + return native_default.randomUUID(); + } + options = options || {}; + var rnds = options.random || (options.rng || rng)(); + rnds[6] = rnds[6] & 15 | 64; + rnds[8] = rnds[8] & 63 | 128; + if (buf) { + offset = offset || 0; + for (var i2 = 0;i2 < 16; ++i2) { + buf[offset + i2] = rnds[i2]; + } + return buf; + } + return unsafeStringify(rnds); +}; +var v4_default = v4; +// src/lib/circularBuffer.ts +class CircularBuffer { + capacity; + buffer; + pointer; + constructor(capacity) { + this.capacity = capacity; + this.buffer = new Array(capacity); + this.pointer = 0; + } + push(item) { + this.buffer[this.pointer] = item; + this.pointer = (this.pointer + 1) % this.capacity; + } + getAll() { + return this.buffer.filter((item) => item !== undefined); + } +} + +// node_modules/zustand/esm/vanilla.mjs +var createStoreImpl = (createState) => { + let state; + const listeners = new Set; + const setState = (partial, replace) => { + const nextState = typeof partial === "function" ? partial(state) : partial; + if (!Object.is(nextState, state)) { + const previousState = state; + state = (replace != null ? replace : typeof nextState !== "object" || nextState === null) ? nextState : Object.assign({}, state, nextState); + listeners.forEach((listener) => listener(state, previousState)); + } + }; + const getState = () => state; + const getInitialState = () => initialState; + const subscribe = (listener) => { + listeners.add(listener); + return () => listeners.delete(listener); + }; + const api = { setState, getState, getInitialState, subscribe }; + const initialState = state = createState(setState, getState, api); + return api; +}; +var createStore = (createState) => createState ? createStoreImpl(createState) : createStoreImpl; + +// node_modules/zustand/esm/react.mjs +var import_react = __toESM(require_react(), 1); +var useStore = function(api, selector = identity) { + const slice = import_react.default.useSyncExternalStore(api.subscribe, () => selector(api.getState()), () => selector(api.getInitialState())); + import_react.default.useDebugValue(slice); + return slice; +}; +var identity = (arg) => arg; +var createImpl = (createState) => { + const api = createStore(createState); + const useBoundStore = (selector) => useStore(api, selector); + Object.assign(useBoundStore, api); + return useBoundStore; +}; +var create = (createState) => createState ? createImpl(createState) : createImpl; + +// src/hooks/useMainStore.ts +var useMainStore = create((set, get) => ({ + error: "", + imageFile: null, + originalImage: "", + originalImageHash: "", + previewImage: "", + minLatency: 20, + averageLatency: 190, + maxLatency: 4000, + activeLandmark: undefined, + params: {}, + setError: (error = "") => set({ error }), + setImageFile: (file) => set({ imageFile: file }), + setOriginalImage: (url) => set({ originalImage: url }), + setOriginalImageHash: (originalImageHash) => set({ originalImageHash }), + setPreviewImage: (url) => set({ previewImage: url }), + resetImage: () => { + const { originalImage } = get(); + if (originalImage) { + set({ previewImage: originalImage }); + } + }, + setAverageLatency: (averageLatency) => set({ averageLatency }), + setActiveLandmark: (activeLandmark) => set({ activeLandmark }), + setParams: (params) => { + const { params: previousParams } = get(); + set({ params: { + ...previousParams, + ...params + } }); + } +})); + +// src/lib/facePoke.ts +var WebSocketState; +(function(WebSocketState2) { + WebSocketState2[WebSocketState2["CONNECTING"] = 0] = "CONNECTING"; + WebSocketState2[WebSocketState2["OPEN"] = 1] = "OPEN"; + WebSocketState2[WebSocketState2["CLOSING"] = 2] = "CLOSING"; + WebSocketState2[WebSocketState2["CLOSED"] = 3] = "CLOSED"; +})(WebSocketState || (WebSocketState = {})); + +class FacePoke { + ws = null; + connectionId = v4_default(); + isUnloading = false; + onModifiedImage = () => { + }; + reconnectAttempts = 0; + maxReconnectAttempts = 5; + reconnectDelay = 5000; + eventListeners = new Map; + requestTracker = new Map; + responseTimeBuffer; + MAX_TRACKED_TIMES = 5; + constructor() { + console.log(`[FacePoke] Initializing FacePoke instance with connection ID: ${this.connectionId}`); + this.initializeWebSocket(); + this.setupUnloadHandler(); + this.responseTimeBuffer = new CircularBuffer(this.MAX_TRACKED_TIMES); + console.log(`[FacePoke] Initialized response time tracker with capacity: ${this.MAX_TRACKED_TIMES}`); + } + trackRequest() { + const uuid = v4_default(); + this.requestTracker.set(uuid, { uuid, timestamp: Date.now() }); + return uuid; + } + completeRequest(uuid) { + const request = this.requestTracker.get(uuid); + if (request) { + const responseTime = Date.now() - request.timestamp; + this.responseTimeBuffer.push(responseTime); + this.requestTracker.delete(uuid); + this.updateThrottleTime(); + console.log(`[FacePoke] Completed request ${uuid}. Response time: ${responseTime}ms`); + } else { + console.warn(`[FacePoke] Attempted to complete unknown request: ${uuid}`); + } + } + calculateAverageResponseTime() { + const times = this.responseTimeBuffer.getAll(); + const averageLatency = useMainStore.getState().averageLatency; + if (times.length === 0) + return averageLatency; + const sum = times.reduce((acc, time) => acc + time, 0); + return sum / times.length; + } + updateThrottleTime() { + const { minLatency, maxLatency, averageLatency, setAverageLatency } = useMainStore.getState(); + const avgResponseTime = this.calculateAverageResponseTime(); + const newLatency = Math.min(minLatency, Math.max(minLatency, avgResponseTime)); + if (newLatency !== averageLatency) { + setAverageLatency(newLatency); + console.log(`[FacePoke] Updated throttle time (latency is ${newLatency}ms)`); + } + } + setOnModifiedImage(handler) { + this.onModifiedImage = handler; + console.log(`[FacePoke] onModifiedImage handler set`); + } + async startWebSocket() { + console.log(`[FacePoke] Starting WebSocket connection.`); + if (!this.ws || this.ws.readyState !== WebSocketState.OPEN) { + await this.initializeWebSocket(); + } + } + async initializeWebSocket() { + console.log(`[FacePoke][${this.connectionId}] Initializing WebSocket connection`); + const connect = () => { + this.ws = new WebSocket(`wss://${window.location.host}/ws`); + this.ws.onopen = this.handleWebSocketOpen.bind(this); + this.ws.onmessage = this.handleWebSocketMessage.bind(this); + this.ws.onclose = this.handleWebSocketClose.bind(this); + this.ws.onerror = this.handleWebSocketError.bind(this); + }; + connect(); + } + handleWebSocketOpen() { + console.log(`[FacePoke][${this.connectionId}] WebSocket connection opened`); + this.reconnectAttempts = 0; + this.emitEvent("websocketOpen"); + } + handleWebSocketMessage(event) { + try { + const data = JSON.parse(event.data); + if (data.uuid) { + this.completeRequest(data.uuid); + } + if (data.type === "modified_image") { + if (data?.image) { + this.onModifiedImage(data.image, data.image_hash); + } + } + this.emitEvent("message", data); + } catch (error) { + console.error(`[FacePoke][${this.connectionId}] Error parsing WebSocket message:`, error); + } + } + handleWebSocketClose(event) { + if (event.wasClean) { + console.log(`[FacePoke][${this.connectionId}] WebSocket connection closed cleanly, code=${event.code}, reason=${event.reason}`); + } else { + console.warn(`[FacePoke][${this.connectionId}] WebSocket connection abruptly closed`); + } + this.emitEvent("websocketClose", event); + if (!this.isUnloading && this.reconnectAttempts < this.maxReconnectAttempts) { + this.reconnectAttempts++; + const delay = Math.min(1000 * 2 ** this.reconnectAttempts, 30000); + console.log(`[FacePoke][${this.connectionId}] Attempting to reconnect in ${delay}ms (Attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts})...`); + setTimeout(() => this.initializeWebSocket(), delay); + } else if (this.reconnectAttempts >= this.maxReconnectAttempts) { + console.error(`[FacePoke][${this.connectionId}] Max reconnect attempts reached. Please refresh the page.`); + this.emitEvent("maxReconnectAttemptsReached"); + } + } + handleWebSocketError(error) { + console.error(`[FacePoke][${this.connectionId}] WebSocket error:`, error); + this.emitEvent("websocketError", error); + } + handleInterruption(message) { + console.warn(`[FacePoke] Interruption: ${message}`); + this.emitEvent("interruption", message); + } + async toggleMicrophone(isOn) { + console.log(`[FacePoke] Attempting to ${isOn ? "start" : "stop"} microphone`); + try { + if (isOn) { + await this.startMicrophone(); + } else { + this.stopMicrophone(); + } + this.emitEvent("microphoneToggled", isOn); + } catch (error) { + console.error(`[FacePoke] Error toggling microphone:`, error); + this.emitEvent("microphoneError", error); + throw error; + } + } + cleanup() { + console.log("[FacePoke] Starting cleanup process"); + if (this.ws) { + this.ws.close(); + this.ws = null; + } + this.eventListeners.clear(); + console.log("[FacePoke] Cleanup completed"); + this.emitEvent("cleanup"); + } + modifyImage(image, imageHash, params) { + try { + const message = { + type: "modify_image", + params + }; + if (image) { + message.image = image; + } else if (imageHash) { + message.image_hash = imageHash; + } else { + throw new Error("Either image or imageHash must be provided"); + } + this.sendJsonMessage(message); + } catch (err) { + console.error(`[FacePoke] Failed to modify the image:`, err); + } + } + sendJsonMessage(message) { + if (!this.ws || this.ws.readyState !== WebSocketState.OPEN) { + const error = new Error("WebSocket connection is not open"); + console.error("[FacePoke] Error sending JSON message:", error); + this.emitEvent("sendJsonMessageError", error); + throw error; + } + const uuid = this.trackRequest(); + const messageWithUuid = { ...message, uuid }; + this.ws.send(JSON.stringify(messageWithUuid)); + } + setupUnloadHandler() { + window.addEventListener("beforeunload", () => { + console.log("[FacePoke] Page is unloading, cleaning up resources"); + this.isUnloading = true; + if (this.ws) { + this.ws.close(1000, "Page is unloading"); + } + this.cleanup(); + }); + } + addEventListener(eventType, listener) { + if (!this.eventListeners.has(eventType)) { + this.eventListeners.set(eventType, new Set); + } + this.eventListeners.get(eventType).add(listener); + console.log(`[FacePoke] Added event listener for '${eventType}'`); + } + removeEventListener(eventType, listener) { + const listeners = this.eventListeners.get(eventType); + if (listeners) { + listeners.delete(listener); + console.log(`[FacePoke] Removed event listener for '${eventType}'`); + } + } + emitEvent(eventType, data) { + const listeners = this.eventListeners.get(eventType); + if (listeners) { + console.log(`[FacePoke] Emitting event '${eventType}' with data:`, data); + listeners.forEach((listener) => listener(data)); + } + } +} +var facePoke = new FacePoke; + +// node_modules/beautiful-react-hooks/esm/useThrottledCallback.js +var import_react4 = __toESM(require_react(), 1); +var import_lodash = __toESM(require_lodash(), 1); + +// node_modules/beautiful-react-hooks/esm/useWillUnmount.js +var import_react3 = __toESM(require_react(), 1); + +// node_modules/beautiful-react-hooks/esm/shared/isFunction.js +var isFunction = (functionToCheck) => typeof functionToCheck === "function" && !!functionToCheck.constructor && !!functionToCheck.call && !!functionToCheck.apply; +var isFunction_default = isFunction; + +// node_modules/beautiful-react-hooks/esm/factory/createHandlerSetter.js +var import_react2 = __toESM(require_react(), 1); +var createHandlerSetter = (callback) => { + const handlerRef = import_react2.useRef(callback); + const setHandler = import_react2.useRef((nextCallback) => { + if (typeof nextCallback !== "function") { + throw new Error("the argument supplied to the \'setHandler\' function should be of type function"); + } + handlerRef.current = nextCallback; + }); + return [handlerRef, setHandler.current]; +}; +var createHandlerSetter_default = createHandlerSetter; + +// node_modules/beautiful-react-hooks/esm/useWillUnmount.js +var useWillUnmount = (callback) => { + const mountRef = import_react3.useRef(false); + const [handler, setHandler] = createHandlerSetter_default(callback); + import_react3.useLayoutEffect(() => { + mountRef.current = true; + return () => { + if (isFunction_default(handler === null || handler === undefined ? undefined : handler.current) && mountRef.current) { + handler.current(); + } + }; + }, []); + return setHandler; +}; +var useWillUnmount_default = useWillUnmount; + +// node_modules/beautiful-react-hooks/esm/useThrottledCallback.js +var defaultOptions = { + leading: false, + trailing: true +}; +var useThrottledCallback = (fn2, dependencies, wait = 600, options = defaultOptions) => { + const throttled = import_react4.useRef(import_lodash.default(fn2, wait, options)); + import_react4.useEffect(() => { + throttled.current = import_lodash.default(fn2, wait, options); + }, [fn2, wait, options]); + useWillUnmount_default(() => { + var _a2; + (_a2 = throttled.current) === null || _a2 === undefined || _a2.cancel(); + }); + return import_react4.useCallback(throttled.current, dependencies !== null && dependencies !== undefined ? dependencies : []); +}; +var useThrottledCallback_default = useThrottledCallback; + +// src/hooks/landmarks.ts +var landmarkGroups = { + lips: lh.FACE_LANDMARKS_LIPS, + leftEye: lh.FACE_LANDMARKS_LEFT_EYE, + leftEyebrow: lh.FACE_LANDMARKS_LEFT_EYEBROW, + leftIris: lh.FACE_LANDMARKS_LEFT_IRIS, + rightEye: lh.FACE_LANDMARKS_RIGHT_EYE, + rightEyebrow: lh.FACE_LANDMARKS_RIGHT_EYEBROW, + rightIris: lh.FACE_LANDMARKS_RIGHT_IRIS, + faceOval: lh.FACE_LANDMARKS_FACE_OVAL +}; +var FACEMESH_LIPS = Object.freeze(new Set([ + [61, 146], + [146, 91], + [91, 181], + [181, 84], + [84, 17], + [17, 314], + [314, 405], + [405, 321], + [321, 375], + [375, 291], + [61, 185], + [185, 40], + [40, 39], + [39, 37], + [37, 0], + [0, 267], + [267, 269], + [269, 270], + [270, 409], + [409, 291], + [78, 95], + [95, 88], + [88, 178], + [178, 87], + [87, 14], + [14, 317], + [317, 402], + [402, 318], + [318, 324], + [324, 308], + [78, 191], + [191, 80], + [80, 81], + [81, 82], + [82, 13], + [13, 312], + [312, 311], + [311, 310], + [310, 415], + [415, 308] +])); +var FACEMESH_LEFT_EYE = Object.freeze(new Set([ + [263, 249], + [249, 390], + [390, 373], + [373, 374], + [374, 380], + [380, 381], + [381, 382], + [382, 362], + [263, 466], + [466, 388], + [388, 387], + [387, 386], + [386, 385], + [385, 384], + [384, 398], + [398, 362] +])); +var FACEMESH_LEFT_IRIS = Object.freeze(new Set([ + [474, 475], + [475, 476], + [476, 477], + [477, 474] +])); +var FACEMESH_LEFT_EYEBROW = Object.freeze(new Set([ + [276, 283], + [283, 282], + [282, 295], + [295, 285], + [300, 293], + [293, 334], + [334, 296], + [296, 336] +])); +var FACEMESH_RIGHT_EYE = Object.freeze(new Set([ + [33, 7], + [7, 163], + [163, 144], + [144, 145], + [145, 153], + [153, 154], + [154, 155], + [155, 133], + [33, 246], + [246, 161], + [161, 160], + [160, 159], + [159, 158], + [158, 157], + [157, 173], + [173, 133] +])); +var FACEMESH_RIGHT_EYEBROW = Object.freeze(new Set([ + [46, 53], + [53, 52], + [52, 65], + [65, 55], + [70, 63], + [63, 105], + [105, 66], + [66, 107] +])); +var FACEMESH_RIGHT_IRIS = Object.freeze(new Set([ + [469, 470], + [470, 471], + [471, 472], + [472, 469] +])); +var FACEMESH_FACE_OVAL = Object.freeze(new Set([ + [10, 338], + [338, 297], + [297, 332], + [332, 284], + [284, 251], + [251, 389], + [389, 356], + [356, 454], + [454, 323], + [323, 361], + [361, 288], + [288, 397], + [397, 365], + [365, 379], + [379, 378], + [378, 400], + [400, 377], + [377, 152], + [152, 148], + [148, 176], + [176, 149], + [149, 150], + [150, 136], + [136, 172], + [172, 58], + [58, 132], + [132, 93], + [93, 234], + [234, 127], + [127, 162], + [162, 21], + [21, 54], + [54, 103], + [103, 67], + [67, 109], + [109, 10] +])); +var FACEMESH_NOSE = Object.freeze(new Set([ + [168, 6], + [6, 197], + [197, 195], + [195, 5], + [5, 4], + [4, 1], + [1, 19], + [19, 94], + [94, 2], + [98, 97], + [97, 2], + [2, 326], + [326, 327], + [327, 294], + [294, 278], + [278, 344], + [344, 440], + [440, 275], + [275, 4], + [4, 45], + [45, 220], + [220, 115], + [115, 48], + [48, 64], + [64, 98] +])); +var FACEMESH_CONTOURS = Object.freeze(new Set([ + ...FACEMESH_LIPS, + ...FACEMESH_LEFT_EYE, + ...FACEMESH_LEFT_EYEBROW, + ...FACEMESH_RIGHT_EYE, + ...FACEMESH_RIGHT_EYEBROW, + ...FACEMESH_FACE_OVAL +])); +var FACEMESH_IRISES = Object.freeze(new Set([ + ...FACEMESH_LEFT_IRIS, + ...FACEMESH_RIGHT_IRIS +])); +var FACEMESH_TESSELATION = Object.freeze(new Set([ + [127, 34], + [34, 139], + [139, 127], + [11, 0], + [0, 37], + [37, 11], + [232, 231], + [231, 120], + [120, 232], + [72, 37], + [37, 39], + [39, 72], + [128, 121], + [121, 47], + [47, 128], + [232, 121], + [121, 128], + [128, 232], + [104, 69], + [69, 67], + [67, 104], + [175, 171], + [171, 148], + [148, 175], + [118, 50], + [50, 101], + [101, 118], + [73, 39], + [39, 40], + [40, 73], + [9, 151], + [151, 108], + [108, 9], + [48, 115], + [115, 131], + [131, 48], + [194, 204], + [204, 211], + [211, 194], + [74, 40], + [40, 185], + [185, 74], + [80, 42], + [42, 183], + [183, 80], + [40, 92], + [92, 186], + [186, 40], + [230, 229], + [229, 118], + [118, 230], + [202, 212], + [212, 214], + [214, 202], + [83, 18], + [18, 17], + [17, 83], + [76, 61], + [61, 146], + [146, 76], + [160, 29], + [29, 30], + [30, 160], + [56, 157], + [157, 173], + [173, 56], + [106, 204], + [204, 194], + [194, 106], + [135, 214], + [214, 192], + [192, 135], + [203, 165], + [165, 98], + [98, 203], + [21, 71], + [71, 68], + [68, 21], + [51, 45], + [45, 4], + [4, 51], + [144, 24], + [24, 23], + [23, 144], + [77, 146], + [146, 91], + [91, 77], + [205, 50], + [50, 187], + [187, 205], + [201, 200], + [200, 18], + [18, 201], + [91, 106], + [106, 182], + [182, 91], + [90, 91], + [91, 181], + [181, 90], + [85, 84], + [84, 17], + [17, 85], + [206, 203], + [203, 36], + [36, 206], + [148, 171], + [171, 140], + [140, 148], + [92, 40], + [40, 39], + [39, 92], + [193, 189], + [189, 244], + [244, 193], + [159, 158], + [158, 28], + [28, 159], + [247, 246], + [246, 161], + [161, 247], + [236, 3], + [3, 196], + [196, 236], + [54, 68], + [68, 104], + [104, 54], + [193, 168], + [168, 8], + [8, 193], + [117, 228], + [228, 31], + [31, 117], + [189, 193], + [193, 55], + [55, 189], + [98, 97], + [97, 99], + [99, 98], + [126, 47], + [47, 100], + [100, 126], + [166, 79], + [79, 218], + [218, 166], + [155, 154], + [154, 26], + [26, 155], + [209, 49], + [49, 131], + [131, 209], + [135, 136], + [136, 150], + [150, 135], + [47, 126], + [126, 217], + [217, 47], + [223, 52], + [52, 53], + [53, 223], + [45, 51], + [51, 134], + [134, 45], + [211, 170], + [170, 140], + [140, 211], + [67, 69], + [69, 108], + [108, 67], + [43, 106], + [106, 91], + [91, 43], + [230, 119], + [119, 120], + [120, 230], + [226, 130], + [130, 247], + [247, 226], + [63, 53], + [53, 52], + [52, 63], + [238, 20], + [20, 242], + [242, 238], + [46, 70], + [70, 156], + [156, 46], + [78, 62], + [62, 96], + [96, 78], + [46, 53], + [53, 63], + [63, 46], + [143, 34], + [34, 227], + [227, 143], + [123, 117], + [117, 111], + [111, 123], + [44, 125], + [125, 19], + [19, 44], + [236, 134], + [134, 51], + [51, 236], + [216, 206], + [206, 205], + [205, 216], + [154, 153], + [153, 22], + [22, 154], + [39, 37], + [37, 167], + [167, 39], + [200, 201], + [201, 208], + [208, 200], + [36, 142], + [142, 100], + [100, 36], + [57, 212], + [212, 202], + [202, 57], + [20, 60], + [60, 99], + [99, 20], + [28, 158], + [158, 157], + [157, 28], + [35, 226], + [226, 113], + [113, 35], + [160, 159], + [159, 27], + [27, 160], + [204, 202], + [202, 210], + [210, 204], + [113, 225], + [225, 46], + [46, 113], + [43, 202], + [202, 204], + [204, 43], + [62, 76], + [76, 77], + [77, 62], + [137, 123], + [123, 116], + [116, 137], + [41, 38], + [38, 72], + [72, 41], + [203, 129], + [129, 142], + [142, 203], + [64, 98], + [98, 240], + [240, 64], + [49, 102], + [102, 64], + [64, 49], + [41, 73], + [73, 74], + [74, 41], + [212, 216], + [216, 207], + [207, 212], + [42, 74], + [74, 184], + [184, 42], + [169, 170], + [170, 211], + [211, 169], + [170, 149], + [149, 176], + [176, 170], + [105, 66], + [66, 69], + [69, 105], + [122, 6], + [6, 168], + [168, 122], + [123, 147], + [147, 187], + [187, 123], + [96, 77], + [77, 90], + [90, 96], + [65, 55], + [55, 107], + [107, 65], + [89, 90], + [90, 180], + [180, 89], + [101, 100], + [100, 120], + [120, 101], + [63, 105], + [105, 104], + [104, 63], + [93, 137], + [137, 227], + [227, 93], + [15, 86], + [86, 85], + [85, 15], + [129, 102], + [102, 49], + [49, 129], + [14, 87], + [87, 86], + [86, 14], + [55, 8], + [8, 9], + [9, 55], + [100, 47], + [47, 121], + [121, 100], + [145, 23], + [23, 22], + [22, 145], + [88, 89], + [89, 179], + [179, 88], + [6, 122], + [122, 196], + [196, 6], + [88, 95], + [95, 96], + [96, 88], + [138, 172], + [172, 136], + [136, 138], + [215, 58], + [58, 172], + [172, 215], + [115, 48], + [48, 219], + [219, 115], + [42, 80], + [80, 81], + [81, 42], + [195, 3], + [3, 51], + [51, 195], + [43, 146], + [146, 61], + [61, 43], + [171, 175], + [175, 199], + [199, 171], + [81, 82], + [82, 38], + [38, 81], + [53, 46], + [46, 225], + [225, 53], + [144, 163], + [163, 110], + [110, 144], + [52, 65], + [65, 66], + [66, 52], + [229, 228], + [228, 117], + [117, 229], + [34, 127], + [127, 234], + [234, 34], + [107, 108], + [108, 69], + [69, 107], + [109, 108], + [108, 151], + [151, 109], + [48, 64], + [64, 235], + [235, 48], + [62, 78], + [78, 191], + [191, 62], + [129, 209], + [209, 126], + [126, 129], + [111, 35], + [35, 143], + [143, 111], + [117, 123], + [123, 50], + [50, 117], + [222, 65], + [65, 52], + [52, 222], + [19, 125], + [125, 141], + [141, 19], + [221, 55], + [55, 65], + [65, 221], + [3, 195], + [195, 197], + [197, 3], + [25, 7], + [7, 33], + [33, 25], + [220, 237], + [237, 44], + [44, 220], + [70, 71], + [71, 139], + [139, 70], + [122, 193], + [193, 245], + [245, 122], + [247, 130], + [130, 33], + [33, 247], + [71, 21], + [21, 162], + [162, 71], + [170, 169], + [169, 150], + [150, 170], + [188, 174], + [174, 196], + [196, 188], + [216, 186], + [186, 92], + [92, 216], + [2, 97], + [97, 167], + [167, 2], + [141, 125], + [125, 241], + [241, 141], + [164, 167], + [167, 37], + [37, 164], + [72, 38], + [38, 12], + [12, 72], + [38, 82], + [82, 13], + [13, 38], + [63, 68], + [68, 71], + [71, 63], + [226, 35], + [35, 111], + [111, 226], + [101, 50], + [50, 205], + [205, 101], + [206, 92], + [92, 165], + [165, 206], + [209, 198], + [198, 217], + [217, 209], + [165, 167], + [167, 97], + [97, 165], + [220, 115], + [115, 218], + [218, 220], + [133, 112], + [112, 243], + [243, 133], + [239, 238], + [238, 241], + [241, 239], + [214, 135], + [135, 169], + [169, 214], + [190, 173], + [173, 133], + [133, 190], + [171, 208], + [208, 32], + [32, 171], + [125, 44], + [44, 237], + [237, 125], + [86, 87], + [87, 178], + [178, 86], + [85, 86], + [86, 179], + [179, 85], + [84, 85], + [85, 180], + [180, 84], + [83, 84], + [84, 181], + [181, 83], + [201, 83], + [83, 182], + [182, 201], + [137, 93], + [93, 132], + [132, 137], + [76, 62], + [62, 183], + [183, 76], + [61, 76], + [76, 184], + [184, 61], + [57, 61], + [61, 185], + [185, 57], + [212, 57], + [57, 186], + [186, 212], + [214, 207], + [207, 187], + [187, 214], + [34, 143], + [143, 156], + [156, 34], + [79, 239], + [239, 237], + [237, 79], + [123, 137], + [137, 177], + [177, 123], + [44, 1], + [1, 4], + [4, 44], + [201, 194], + [194, 32], + [32, 201], + [64, 102], + [102, 129], + [129, 64], + [213, 215], + [215, 138], + [138, 213], + [59, 166], + [166, 219], + [219, 59], + [242, 99], + [99, 97], + [97, 242], + [2, 94], + [94, 141], + [141, 2], + [75, 59], + [59, 235], + [235, 75], + [24, 110], + [110, 228], + [228, 24], + [25, 130], + [130, 226], + [226, 25], + [23, 24], + [24, 229], + [229, 23], + [22, 23], + [23, 230], + [230, 22], + [26, 22], + [22, 231], + [231, 26], + [112, 26], + [26, 232], + [232, 112], + [189, 190], + [190, 243], + [243, 189], + [221, 56], + [56, 190], + [190, 221], + [28, 56], + [56, 221], + [221, 28], + [27, 28], + [28, 222], + [222, 27], + [29, 27], + [27, 223], + [223, 29], + [30, 29], + [29, 224], + [224, 30], + [247, 30], + [30, 225], + [225, 247], + [238, 79], + [79, 20], + [20, 238], + [166, 59], + [59, 75], + [75, 166], + [60, 75], + [75, 240], + [240, 60], + [147, 177], + [177, 215], + [215, 147], + [20, 79], + [79, 166], + [166, 20], + [187, 147], + [147, 213], + [213, 187], + [112, 233], + [233, 244], + [244, 112], + [233, 128], + [128, 245], + [245, 233], + [128, 114], + [114, 188], + [188, 128], + [114, 217], + [217, 174], + [174, 114], + [131, 115], + [115, 220], + [220, 131], + [217, 198], + [198, 236], + [236, 217], + [198, 131], + [131, 134], + [134, 198], + [177, 132], + [132, 58], + [58, 177], + [143, 35], + [35, 124], + [124, 143], + [110, 163], + [163, 7], + [7, 110], + [228, 110], + [110, 25], + [25, 228], + [356, 389], + [389, 368], + [368, 356], + [11, 302], + [302, 267], + [267, 11], + [452, 350], + [350, 349], + [349, 452], + [302, 303], + [303, 269], + [269, 302], + [357, 343], + [343, 277], + [277, 357], + [452, 453], + [453, 357], + [357, 452], + [333, 332], + [332, 297], + [297, 333], + [175, 152], + [152, 377], + [377, 175], + [347, 348], + [348, 330], + [330, 347], + [303, 304], + [304, 270], + [270, 303], + [9, 336], + [336, 337], + [337, 9], + [278, 279], + [279, 360], + [360, 278], + [418, 262], + [262, 431], + [431, 418], + [304, 408], + [408, 409], + [409, 304], + [310, 415], + [415, 407], + [407, 310], + [270, 409], + [409, 410], + [410, 270], + [450, 348], + [348, 347], + [347, 450], + [422, 430], + [430, 434], + [434, 422], + [313, 314], + [314, 17], + [17, 313], + [306, 307], + [307, 375], + [375, 306], + [387, 388], + [388, 260], + [260, 387], + [286, 414], + [414, 398], + [398, 286], + [335, 406], + [406, 418], + [418, 335], + [364, 367], + [367, 416], + [416, 364], + [423, 358], + [358, 327], + [327, 423], + [251, 284], + [284, 298], + [298, 251], + [281, 5], + [5, 4], + [4, 281], + [373, 374], + [374, 253], + [253, 373], + [307, 320], + [320, 321], + [321, 307], + [425, 427], + [427, 411], + [411, 425], + [421, 313], + [313, 18], + [18, 421], + [321, 405], + [405, 406], + [406, 321], + [320, 404], + [404, 405], + [405, 320], + [315, 16], + [16, 17], + [17, 315], + [426, 425], + [425, 266], + [266, 426], + [377, 400], + [400, 369], + [369, 377], + [322, 391], + [391, 269], + [269, 322], + [417, 465], + [465, 464], + [464, 417], + [386, 257], + [257, 258], + [258, 386], + [466, 260], + [260, 388], + [388, 466], + [456, 399], + [399, 419], + [419, 456], + [284, 332], + [332, 333], + [333, 284], + [417, 285], + [285, 8], + [8, 417], + [346, 340], + [340, 261], + [261, 346], + [413, 441], + [441, 285], + [285, 413], + [327, 460], + [460, 328], + [328, 327], + [355, 371], + [371, 329], + [329, 355], + [392, 439], + [439, 438], + [438, 392], + [382, 341], + [341, 256], + [256, 382], + [429, 420], + [420, 360], + [360, 429], + [364, 394], + [394, 379], + [379, 364], + [277, 343], + [343, 437], + [437, 277], + [443, 444], + [444, 283], + [283, 443], + [275, 440], + [440, 363], + [363, 275], + [431, 262], + [262, 369], + [369, 431], + [297, 338], + [338, 337], + [337, 297], + [273, 375], + [375, 321], + [321, 273], + [450, 451], + [451, 349], + [349, 450], + [446, 342], + [342, 467], + [467, 446], + [293, 334], + [334, 282], + [282, 293], + [458, 461], + [461, 462], + [462, 458], + [276, 353], + [353, 383], + [383, 276], + [308, 324], + [324, 325], + [325, 308], + [276, 300], + [300, 293], + [293, 276], + [372, 345], + [345, 447], + [447, 372], + [352, 345], + [345, 340], + [340, 352], + [274, 1], + [1, 19], + [19, 274], + [456, 248], + [248, 281], + [281, 456], + [436, 427], + [427, 425], + [425, 436], + [381, 256], + [256, 252], + [252, 381], + [269, 391], + [391, 393], + [393, 269], + [200, 199], + [199, 428], + [428, 200], + [266, 330], + [330, 329], + [329, 266], + [287, 273], + [273, 422], + [422, 287], + [250, 462], + [462, 328], + [328, 250], + [258, 286], + [286, 384], + [384, 258], + [265, 353], + [353, 342], + [342, 265], + [387, 259], + [259, 257], + [257, 387], + [424, 431], + [431, 430], + [430, 424], + [342, 353], + [353, 276], + [276, 342], + [273, 335], + [335, 424], + [424, 273], + [292, 325], + [325, 307], + [307, 292], + [366, 447], + [447, 345], + [345, 366], + [271, 303], + [303, 302], + [302, 271], + [423, 266], + [266, 371], + [371, 423], + [294, 455], + [455, 460], + [460, 294], + [279, 278], + [278, 294], + [294, 279], + [271, 272], + [272, 304], + [304, 271], + [432, 434], + [434, 427], + [427, 432], + [272, 407], + [407, 408], + [408, 272], + [394, 430], + [430, 431], + [431, 394], + [395, 369], + [369, 400], + [400, 395], + [334, 333], + [333, 299], + [299, 334], + [351, 417], + [417, 168], + [168, 351], + [352, 280], + [280, 411], + [411, 352], + [325, 319], + [319, 320], + [320, 325], + [295, 296], + [296, 336], + [336, 295], + [319, 403], + [403, 404], + [404, 319], + [330, 348], + [348, 349], + [349, 330], + [293, 298], + [298, 333], + [333, 293], + [323, 454], + [454, 447], + [447, 323], + [15, 16], + [16, 315], + [315, 15], + [358, 429], + [429, 279], + [279, 358], + [14, 15], + [15, 316], + [316, 14], + [285, 336], + [336, 9], + [9, 285], + [329, 349], + [349, 350], + [350, 329], + [374, 380], + [380, 252], + [252, 374], + [318, 402], + [402, 403], + [403, 318], + [6, 197], + [197, 419], + [419, 6], + [318, 319], + [319, 325], + [325, 318], + [367, 364], + [364, 365], + [365, 367], + [435, 367], + [367, 397], + [397, 435], + [344, 438], + [438, 439], + [439, 344], + [272, 271], + [271, 311], + [311, 272], + [195, 5], + [5, 281], + [281, 195], + [273, 287], + [287, 291], + [291, 273], + [396, 428], + [428, 199], + [199, 396], + [311, 271], + [271, 268], + [268, 311], + [283, 444], + [444, 445], + [445, 283], + [373, 254], + [254, 339], + [339, 373], + [282, 334], + [334, 296], + [296, 282], + [449, 347], + [347, 346], + [346, 449], + [264, 447], + [447, 454], + [454, 264], + [336, 296], + [296, 299], + [299, 336], + [338, 10], + [10, 151], + [151, 338], + [278, 439], + [439, 455], + [455, 278], + [292, 407], + [407, 415], + [415, 292], + [358, 371], + [371, 355], + [355, 358], + [340, 345], + [345, 372], + [372, 340], + [346, 347], + [347, 280], + [280, 346], + [442, 443], + [443, 282], + [282, 442], + [19, 94], + [94, 370], + [370, 19], + [441, 442], + [442, 295], + [295, 441], + [248, 419], + [419, 197], + [197, 248], + [263, 255], + [255, 359], + [359, 263], + [440, 275], + [275, 274], + [274, 440], + [300, 383], + [383, 368], + [368, 300], + [351, 412], + [412, 465], + [465, 351], + [263, 467], + [467, 466], + [466, 263], + [301, 368], + [368, 389], + [389, 301], + [395, 378], + [378, 379], + [379, 395], + [412, 351], + [351, 419], + [419, 412], + [436, 426], + [426, 322], + [322, 436], + [2, 164], + [164, 393], + [393, 2], + [370, 462], + [462, 461], + [461, 370], + [164, 0], + [0, 267], + [267, 164], + [302, 11], + [11, 12], + [12, 302], + [268, 12], + [12, 13], + [13, 268], + [293, 300], + [300, 301], + [301, 293], + [446, 261], + [261, 340], + [340, 446], + [330, 266], + [266, 425], + [425, 330], + [426, 423], + [423, 391], + [391, 426], + [429, 355], + [355, 437], + [437, 429], + [391, 327], + [327, 326], + [326, 391], + [440, 457], + [457, 438], + [438, 440], + [341, 382], + [382, 362], + [362, 341], + [459, 457], + [457, 461], + [461, 459], + [434, 430], + [430, 394], + [394, 434], + [414, 463], + [463, 362], + [362, 414], + [396, 369], + [369, 262], + [262, 396], + [354, 461], + [461, 457], + [457, 354], + [316, 403], + [403, 402], + [402, 316], + [315, 404], + [404, 403], + [403, 315], + [314, 405], + [405, 404], + [404, 314], + [313, 406], + [406, 405], + [405, 313], + [421, 418], + [418, 406], + [406, 421], + [366, 401], + [401, 361], + [361, 366], + [306, 408], + [408, 407], + [407, 306], + [291, 409], + [409, 408], + [408, 291], + [287, 410], + [410, 409], + [409, 287], + [432, 436], + [436, 410], + [410, 432], + [434, 416], + [416, 411], + [411, 434], + [264, 368], + [368, 383], + [383, 264], + [309, 438], + [438, 457], + [457, 309], + [352, 376], + [376, 401], + [401, 352], + [274, 275], + [275, 4], + [4, 274], + [421, 428], + [428, 262], + [262, 421], + [294, 327], + [327, 358], + [358, 294], + [433, 416], + [416, 367], + [367, 433], + [289, 455], + [455, 439], + [439, 289], + [462, 370], + [370, 326], + [326, 462], + [2, 326], + [326, 370], + [370, 2], + [305, 460], + [460, 455], + [455, 305], + [254, 449], + [449, 448], + [448, 254], + [255, 261], + [261, 446], + [446, 255], + [253, 450], + [450, 449], + [449, 253], + [252, 451], + [451, 450], + [450, 252], + [256, 452], + [452, 451], + [451, 256], + [341, 453], + [453, 452], + [452, 341], + [413, 464], + [464, 463], + [463, 413], + [441, 413], + [413, 414], + [414, 441], + [258, 442], + [442, 441], + [441, 258], + [257, 443], + [443, 442], + [442, 257], + [259, 444], + [444, 443], + [443, 259], + [260, 445], + [445, 444], + [444, 260], + [467, 342], + [342, 445], + [445, 467], + [459, 458], + [458, 250], + [250, 459], + [289, 392], + [392, 290], + [290, 289], + [290, 328], + [328, 460], + [460, 290], + [376, 433], + [433, 435], + [435, 376], + [250, 290], + [290, 392], + [392, 250], + [411, 416], + [416, 433], + [433, 411], + [341, 463], + [463, 464], + [464, 341], + [453, 464], + [464, 465], + [465, 453], + [357, 465], + [465, 412], + [412, 357], + [343, 412], + [412, 399], + [399, 343], + [360, 363], + [363, 440], + [440, 360], + [437, 399], + [399, 456], + [456, 437], + [420, 456], + [456, 363], + [363, 420], + [401, 435], + [435, 288], + [288, 401], + [372, 383], + [383, 353], + [353, 372], + [339, 255], + [255, 249], + [249, 339], + [448, 261], + [261, 255], + [255, 448], + [133, 243], + [243, 190], + [190, 133], + [133, 155], + [155, 112], + [112, 133], + [33, 246], + [246, 247], + [247, 33], + [33, 130], + [130, 25], + [25, 33], + [398, 384], + [384, 286], + [286, 398], + [362, 398], + [398, 414], + [414, 362], + [362, 463], + [463, 341], + [341, 362], + [263, 359], + [359, 467], + [467, 263], + [263, 249], + [249, 255], + [255, 263], + [466, 467], + [467, 260], + [260, 466], + [75, 60], + [60, 166], + [166, 75], + [238, 239], + [239, 79], + [79, 238], + [162, 127], + [127, 139], + [139, 162], + [72, 11], + [11, 37], + [37, 72], + [121, 232], + [232, 120], + [120, 121], + [73, 72], + [72, 39], + [39, 73], + [114, 128], + [128, 47], + [47, 114], + [233, 232], + [232, 128], + [128, 233], + [103, 104], + [104, 67], + [67, 103], + [152, 175], + [175, 148], + [148, 152], + [119, 118], + [118, 101], + [101, 119], + [74, 73], + [73, 40], + [40, 74], + [107, 9], + [9, 108], + [108, 107], + [49, 48], + [48, 131], + [131, 49], + [32, 194], + [194, 211], + [211, 32], + [184, 74], + [74, 185], + [185, 184], + [191, 80], + [80, 183], + [183, 191], + [185, 40], + [40, 186], + [186, 185], + [119, 230], + [230, 118], + [118, 119], + [210, 202], + [202, 214], + [214, 210], + [84, 83], + [83, 17], + [17, 84], + [77, 76], + [76, 146], + [146, 77], + [161, 160], + [160, 30], + [30, 161], + [190, 56], + [56, 173], + [173, 190], + [182, 106], + [106, 194], + [194, 182], + [138, 135], + [135, 192], + [192, 138], + [129, 203], + [203, 98], + [98, 129], + [54, 21], + [21, 68], + [68, 54], + [5, 51], + [51, 4], + [4, 5], + [145, 144], + [144, 23], + [23, 145], + [90, 77], + [77, 91], + [91, 90], + [207, 205], + [205, 187], + [187, 207], + [83, 201], + [201, 18], + [18, 83], + [181, 91], + [91, 182], + [182, 181], + [180, 90], + [90, 181], + [181, 180], + [16, 85], + [85, 17], + [17, 16], + [205, 206], + [206, 36], + [36, 205], + [176, 148], + [148, 140], + [140, 176], + [165, 92], + [92, 39], + [39, 165], + [245, 193], + [193, 244], + [244, 245], + [27, 159], + [159, 28], + [28, 27], + [30, 247], + [247, 161], + [161, 30], + [174, 236], + [236, 196], + [196, 174], + [103, 54], + [54, 104], + [104, 103], + [55, 193], + [193, 8], + [8, 55], + [111, 117], + [117, 31], + [31, 111], + [221, 189], + [189, 55], + [55, 221], + [240, 98], + [98, 99], + [99, 240], + [142, 126], + [126, 100], + [100, 142], + [219, 166], + [166, 218], + [218, 219], + [112, 155], + [155, 26], + [26, 112], + [198, 209], + [209, 131], + [131, 198], + [169, 135], + [135, 150], + [150, 169], + [114, 47], + [47, 217], + [217, 114], + [224, 223], + [223, 53], + [53, 224], + [220, 45], + [45, 134], + [134, 220], + [32, 211], + [211, 140], + [140, 32], + [109, 67], + [67, 108], + [108, 109], + [146, 43], + [43, 91], + [91, 146], + [231, 230], + [230, 120], + [120, 231], + [113, 226], + [226, 247], + [247, 113], + [105, 63], + [63, 52], + [52, 105], + [241, 238], + [238, 242], + [242, 241], + [124, 46], + [46, 156], + [156, 124], + [95, 78], + [78, 96], + [96, 95], + [70, 46], + [46, 63], + [63, 70], + [116, 143], + [143, 227], + [227, 116], + [116, 123], + [123, 111], + [111, 116], + [1, 44], + [44, 19], + [19, 1], + [3, 236], + [236, 51], + [51, 3], + [207, 216], + [216, 205], + [205, 207], + [26, 154], + [154, 22], + [22, 26], + [165, 39], + [39, 167], + [167, 165], + [199, 200], + [200, 208], + [208, 199], + [101, 36], + [36, 100], + [100, 101], + [43, 57], + [57, 202], + [202, 43], + [242, 20], + [20, 99], + [99, 242], + [56, 28], + [28, 157], + [157, 56], + [124, 35], + [35, 113], + [113, 124], + [29, 160], + [160, 27], + [27, 29], + [211, 204], + [204, 210], + [210, 211], + [124, 113], + [113, 46], + [46, 124], + [106, 43], + [43, 204], + [204, 106], + [96, 62], + [62, 77], + [77, 96], + [227, 137], + [137, 116], + [116, 227], + [73, 41], + [41, 72], + [72, 73], + [36, 203], + [203, 142], + [142, 36], + [235, 64], + [64, 240], + [240, 235], + [48, 49], + [49, 64], + [64, 48], + [42, 41], + [41, 74], + [74, 42], + [214, 212], + [212, 207], + [207, 214], + [183, 42], + [42, 184], + [184, 183], + [210, 169], + [169, 211], + [211, 210], + [140, 170], + [170, 176], + [176, 140], + [104, 105], + [105, 69], + [69, 104], + [193, 122], + [122, 168], + [168, 193], + [50, 123], + [123, 187], + [187, 50], + [89, 96], + [96, 90], + [90, 89], + [66, 65], + [65, 107], + [107, 66], + [179, 89], + [89, 180], + [180, 179], + [119, 101], + [101, 120], + [120, 119], + [68, 63], + [63, 104], + [104, 68], + [234, 93], + [93, 227], + [227, 234], + [16, 15], + [15, 85], + [85, 16], + [209, 129], + [129, 49], + [49, 209], + [15, 14], + [14, 86], + [86, 15], + [107, 55], + [55, 9], + [9, 107], + [120, 100], + [100, 121], + [121, 120], + [153, 145], + [145, 22], + [22, 153], + [178, 88], + [88, 179], + [179, 178], + [197, 6], + [6, 196], + [196, 197], + [89, 88], + [88, 96], + [96, 89], + [135, 138], + [138, 136], + [136, 135], + [138, 215], + [215, 172], + [172, 138], + [218, 115], + [115, 219], + [219, 218], + [41, 42], + [42, 81], + [81, 41], + [5, 195], + [195, 51], + [51, 5], + [57, 43], + [43, 61], + [61, 57], + [208, 171], + [171, 199], + [199, 208], + [41, 81], + [81, 38], + [38, 41], + [224, 53], + [53, 225], + [225, 224], + [24, 144], + [144, 110], + [110, 24], + [105, 52], + [52, 66], + [66, 105], + [118, 229], + [229, 117], + [117, 118], + [227, 34], + [34, 234], + [234, 227], + [66, 107], + [107, 69], + [69, 66], + [10, 109], + [109, 151], + [151, 10], + [219, 48], + [48, 235], + [235, 219], + [183, 62], + [62, 191], + [191, 183], + [142, 129], + [129, 126], + [126, 142], + [116, 111], + [111, 143], + [143, 116], + [118, 117], + [117, 50], + [50, 118], + [223, 222], + [222, 52], + [52, 223], + [94, 19], + [19, 141], + [141, 94], + [222, 221], + [221, 65], + [65, 222], + [196, 3], + [3, 197], + [197, 196], + [45, 220], + [220, 44], + [44, 45], + [156, 70], + [70, 139], + [139, 156], + [188, 122], + [122, 245], + [245, 188], + [139, 71], + [71, 162], + [162, 139], + [149, 170], + [170, 150], + [150, 149], + [122, 188], + [188, 196], + [196, 122], + [206, 216], + [216, 92], + [92, 206], + [164, 2], + [2, 167], + [167, 164], + [242, 141], + [141, 241], + [241, 242], + [0, 164], + [164, 37], + [37, 0], + [11, 72], + [72, 12], + [12, 11], + [12, 38], + [38, 13], + [13, 12], + [70, 63], + [63, 71], + [71, 70], + [31, 226], + [226, 111], + [111, 31], + [36, 101], + [101, 205], + [205, 36], + [203, 206], + [206, 165], + [165, 203], + [126, 209], + [209, 217], + [217, 126], + [98, 165], + [165, 97], + [97, 98], + [237, 220], + [220, 218], + [218, 237], + [237, 239], + [239, 241], + [241, 237], + [210, 214], + [214, 169], + [169, 210], + [140, 171], + [171, 32], + [32, 140], + [241, 125], + [125, 237], + [237, 241], + [179, 86], + [86, 178], + [178, 179], + [180, 85], + [85, 179], + [179, 180], + [181, 84], + [84, 180], + [180, 181], + [182, 83], + [83, 181], + [181, 182], + [194, 201], + [201, 182], + [182, 194], + [177, 137], + [137, 132], + [132, 177], + [184, 76], + [76, 183], + [183, 184], + [185, 61], + [61, 184], + [184, 185], + [186, 57], + [57, 185], + [185, 186], + [216, 212], + [212, 186], + [186, 216], + [192, 214], + [214, 187], + [187, 192], + [139, 34], + [34, 156], + [156, 139], + [218, 79], + [79, 237], + [237, 218], + [147, 123], + [123, 177], + [177, 147], + [45, 44], + [44, 4], + [4, 45], + [208, 201], + [201, 32], + [32, 208], + [98, 64], + [64, 129], + [129, 98], + [192, 213], + [213, 138], + [138, 192], + [235, 59], + [59, 219], + [219, 235], + [141, 242], + [242, 97], + [97, 141], + [97, 2], + [2, 141], + [141, 97], + [240, 75], + [75, 235], + [235, 240], + [229, 24], + [24, 228], + [228, 229], + [31, 25], + [25, 226], + [226, 31], + [230, 23], + [23, 229], + [229, 230], + [231, 22], + [22, 230], + [230, 231], + [232, 26], + [26, 231], + [231, 232], + [233, 112], + [112, 232], + [232, 233], + [244, 189], + [189, 243], + [243, 244], + [189, 221], + [221, 190], + [190, 189], + [222, 28], + [28, 221], + [221, 222], + [223, 27], + [27, 222], + [222, 223], + [224, 29], + [29, 223], + [223, 224], + [225, 30], + [30, 224], + [224, 225], + [113, 247], + [247, 225], + [225, 113], + [99, 60], + [60, 240], + [240, 99], + [213, 147], + [147, 215], + [215, 213], + [60, 20], + [20, 166], + [166, 60], + [192, 187], + [187, 213], + [213, 192], + [243, 112], + [112, 244], + [244, 243], + [244, 233], + [233, 245], + [245, 244], + [245, 128], + [128, 188], + [188, 245], + [188, 114], + [114, 174], + [174, 188], + [134, 131], + [131, 220], + [220, 134], + [174, 217], + [217, 236], + [236, 174], + [236, 198], + [198, 134], + [134, 236], + [215, 177], + [177, 58], + [58, 215], + [156, 143], + [143, 124], + [124, 156], + [25, 110], + [110, 7], + [7, 25], + [31, 228], + [228, 25], + [25, 31], + [264, 356], + [356, 368], + [368, 264], + [0, 11], + [11, 267], + [267, 0], + [451, 452], + [452, 349], + [349, 451], + [267, 302], + [302, 269], + [269, 267], + [350, 357], + [357, 277], + [277, 350], + [350, 452], + [452, 357], + [357, 350], + [299, 333], + [333, 297], + [297, 299], + [396, 175], + [175, 377], + [377, 396], + [280, 347], + [347, 330], + [330, 280], + [269, 303], + [303, 270], + [270, 269], + [151, 9], + [9, 337], + [337, 151], + [344, 278], + [278, 360], + [360, 344], + [424, 418], + [418, 431], + [431, 424], + [270, 304], + [304, 409], + [409, 270], + [272, 310], + [310, 407], + [407, 272], + [322, 270], + [270, 410], + [410, 322], + [449, 450], + [450, 347], + [347, 449], + [432, 422], + [422, 434], + [434, 432], + [18, 313], + [313, 17], + [17, 18], + [291, 306], + [306, 375], + [375, 291], + [259, 387], + [387, 260], + [260, 259], + [424, 335], + [335, 418], + [418, 424], + [434, 364], + [364, 416], + [416, 434], + [391, 423], + [423, 327], + [327, 391], + [301, 251], + [251, 298], + [298, 301], + [275, 281], + [281, 4], + [4, 275], + [254, 373], + [373, 253], + [253, 254], + [375, 307], + [307, 321], + [321, 375], + [280, 425], + [425, 411], + [411, 280], + [200, 421], + [421, 18], + [18, 200], + [335, 321], + [321, 406], + [406, 335], + [321, 320], + [320, 405], + [405, 321], + [314, 315], + [315, 17], + [17, 314], + [423, 426], + [426, 266], + [266, 423], + [396, 377], + [377, 369], + [369, 396], + [270, 322], + [322, 269], + [269, 270], + [413, 417], + [417, 464], + [464, 413], + [385, 386], + [386, 258], + [258, 385], + [248, 456], + [456, 419], + [419, 248], + [298, 284], + [284, 333], + [333, 298], + [168, 417], + [417, 8], + [8, 168], + [448, 346], + [346, 261], + [261, 448], + [417, 413], + [413, 285], + [285, 417], + [326, 327], + [327, 328], + [328, 326], + [277, 355], + [355, 329], + [329, 277], + [309, 392], + [392, 438], + [438, 309], + [381, 382], + [382, 256], + [256, 381], + [279, 429], + [429, 360], + [360, 279], + [365, 364], + [364, 379], + [379, 365], + [355, 277], + [277, 437], + [437, 355], + [282, 443], + [443, 283], + [283, 282], + [281, 275], + [275, 363], + [363, 281], + [395, 431], + [431, 369], + [369, 395], + [299, 297], + [297, 337], + [337, 299], + [335, 273], + [273, 321], + [321, 335], + [348, 450], + [450, 349], + [349, 348], + [359, 446], + [446, 467], + [467, 359], + [283, 293], + [293, 282], + [282, 283], + [250, 458], + [458, 462], + [462, 250], + [300, 276], + [276, 383], + [383, 300], + [292, 308], + [308, 325], + [325, 292], + [283, 276], + [276, 293], + [293, 283], + [264, 372], + [372, 447], + [447, 264], + [346, 352], + [352, 340], + [340, 346], + [354, 274], + [274, 19], + [19, 354], + [363, 456], + [456, 281], + [281, 363], + [426, 436], + [436, 425], + [425, 426], + [380, 381], + [381, 252], + [252, 380], + [267, 269], + [269, 393], + [393, 267], + [421, 200], + [200, 428], + [428, 421], + [371, 266], + [266, 329], + [329, 371], + [432, 287], + [287, 422], + [422, 432], + [290, 250], + [250, 328], + [328, 290], + [385, 258], + [258, 384], + [384, 385], + [446, 265], + [265, 342], + [342, 446], + [386, 387], + [387, 257], + [257, 386], + [422, 424], + [424, 430], + [430, 422], + [445, 342], + [342, 276], + [276, 445], + [422, 273], + [273, 424], + [424, 422], + [306, 292], + [292, 307], + [307, 306], + [352, 366], + [366, 345], + [345, 352], + [268, 271], + [271, 302], + [302, 268], + [358, 423], + [423, 371], + [371, 358], + [327, 294], + [294, 460], + [460, 327], + [331, 279], + [279, 294], + [294, 331], + [303, 271], + [271, 304], + [304, 303], + [436, 432], + [432, 427], + [427, 436], + [304, 272], + [272, 408], + [408, 304], + [395, 394], + [394, 431], + [431, 395], + [378, 395], + [395, 400], + [400, 378], + [296, 334], + [334, 299], + [299, 296], + [6, 351], + [351, 168], + [168, 6], + [376, 352], + [352, 411], + [411, 376], + [307, 325], + [325, 320], + [320, 307], + [285, 295], + [295, 336], + [336, 285], + [320, 319], + [319, 404], + [404, 320], + [329, 330], + [330, 349], + [349, 329], + [334, 293], + [293, 333], + [333, 334], + [366, 323], + [323, 447], + [447, 366], + [316, 15], + [15, 315], + [315, 316], + [331, 358], + [358, 279], + [279, 331], + [317, 14], + [14, 316], + [316, 317], + [8, 285], + [285, 9], + [9, 8], + [277, 329], + [329, 350], + [350, 277], + [253, 374], + [374, 252], + [252, 253], + [319, 318], + [318, 403], + [403, 319], + [351, 6], + [6, 419], + [419, 351], + [324, 318], + [318, 325], + [325, 324], + [397, 367], + [367, 365], + [365, 397], + [288, 435], + [435, 397], + [397, 288], + [278, 344], + [344, 439], + [439, 278], + [310, 272], + [272, 311], + [311, 310], + [248, 195], + [195, 281], + [281, 248], + [375, 273], + [273, 291], + [291, 375], + [175, 396], + [396, 199], + [199, 175], + [312, 311], + [311, 268], + [268, 312], + [276, 283], + [283, 445], + [445, 276], + [390, 373], + [373, 339], + [339, 390], + [295, 282], + [282, 296], + [296, 295], + [448, 449], + [449, 346], + [346, 448], + [356, 264], + [264, 454], + [454, 356], + [337, 336], + [336, 299], + [299, 337], + [337, 338], + [338, 151], + [151, 337], + [294, 278], + [278, 455], + [455, 294], + [308, 292], + [292, 415], + [415, 308], + [429, 358], + [358, 355], + [355, 429], + [265, 340], + [340, 372], + [372, 265], + [352, 346], + [346, 280], + [280, 352], + [295, 442], + [442, 282], + [282, 295], + [354, 19], + [19, 370], + [370, 354], + [285, 441], + [441, 295], + [295, 285], + [195, 248], + [248, 197], + [197, 195], + [457, 440], + [440, 274], + [274, 457], + [301, 300], + [300, 368], + [368, 301], + [417, 351], + [351, 465], + [465, 417], + [251, 301], + [301, 389], + [389, 251], + [394, 395], + [395, 379], + [379, 394], + [399, 412], + [412, 419], + [419, 399], + [410, 436], + [436, 322], + [322, 410], + [326, 2], + [2, 393], + [393, 326], + [354, 370], + [370, 461], + [461, 354], + [393, 164], + [164, 267], + [267, 393], + [268, 302], + [302, 12], + [12, 268], + [312, 268], + [268, 13], + [13, 312], + [298, 293], + [293, 301], + [301, 298], + [265, 446], + [446, 340], + [340, 265], + [280, 330], + [330, 425], + [425, 280], + [322, 426], + [426, 391], + [391, 322], + [420, 429], + [429, 437], + [437, 420], + [393, 391], + [391, 326], + [326, 393], + [344, 440], + [440, 438], + [438, 344], + [458, 459], + [459, 461], + [461, 458], + [364, 434], + [434, 394], + [394, 364], + [428, 396], + [396, 262], + [262, 428], + [274, 354], + [354, 457], + [457, 274], + [317, 316], + [316, 402], + [402, 317], + [316, 315], + [315, 403], + [403, 316], + [315, 314], + [314, 404], + [404, 315], + [314, 313], + [313, 405], + [405, 314], + [313, 421], + [421, 406], + [406, 313], + [323, 366], + [366, 361], + [361, 323], + [292, 306], + [306, 407], + [407, 292], + [306, 291], + [291, 408], + [408, 306], + [291, 287], + [287, 409], + [409, 291], + [287, 432], + [432, 410], + [410, 287], + [427, 434], + [434, 411], + [411, 427], + [372, 264], + [264, 383], + [383, 372], + [459, 309], + [309, 457], + [457, 459], + [366, 352], + [352, 401], + [401, 366], + [1, 274], + [274, 4], + [4, 1], + [418, 421], + [421, 262], + [262, 418], + [331, 294], + [294, 358], + [358, 331], + [435, 433], + [433, 367], + [367, 435], + [392, 289], + [289, 439], + [439, 392], + [328, 462], + [462, 326], + [326, 328], + [94, 2], + [2, 370], + [370, 94], + [289, 305], + [305, 455], + [455, 289], + [339, 254], + [254, 448], + [448, 339], + [359, 255], + [255, 446], + [446, 359], + [254, 253], + [253, 449], + [449, 254], + [253, 252], + [252, 450], + [450, 253], + [252, 256], + [256, 451], + [451, 252], + [256, 341], + [341, 452], + [452, 256], + [414, 413], + [413, 463], + [463, 414], + [286, 441], + [441, 414], + [414, 286], + [286, 258], + [258, 441], + [441, 286], + [258, 257], + [257, 442], + [442, 258], + [257, 259], + [259, 443], + [443, 257], + [259, 260], + [260, 444], + [444, 259], + [260, 467], + [467, 445], + [445, 260], + [309, 459], + [459, 250], + [250, 309], + [305, 289], + [289, 290], + [290, 305], + [305, 290], + [290, 460], + [460, 305], + [401, 376], + [376, 435], + [435, 401], + [309, 250], + [250, 392], + [392, 309], + [376, 411], + [411, 433], + [433, 376], + [453, 341], + [341, 464], + [464, 453], + [357, 453], + [453, 465], + [465, 357], + [343, 357], + [357, 412], + [412, 343], + [437, 343], + [343, 399], + [399, 437], + [344, 360], + [360, 440], + [440, 344], + [420, 437], + [437, 456], + [456, 420], + [360, 420], + [420, 363], + [363, 360], + [361, 401], + [401, 288], + [288, 361], + [265, 372], + [372, 353], + [353, 265], + [390, 339], + [339, 249], + [249, 390], + [339, 448], + [448, 255], + [255, 339] +])); + +// src/hooks/useFaceLandmarkDetection.tsx +function useFaceLandmarkDetection() { + const error = useMainStore((s2) => s2.error); + const setError = useMainStore((s2) => s2.setError); + const imageFile = useMainStore((s2) => s2.imageFile); + const setImageFile = useMainStore((s2) => s2.setImageFile); + const originalImage = useMainStore((s2) => s2.originalImage); + const originalImageHash = useMainStore((s2) => s2.originalImageHash); + const setOriginalImageHash = useMainStore((s2) => s2.setOriginalImageHash); + const previewImage = useMainStore((s2) => s2.previewImage); + const setPreviewImage = useMainStore((s2) => s2.setPreviewImage); + const resetImage = useMainStore((s2) => s2.resetImage); + window.debugJuju = useMainStore; + const averageLatency = 220; + const [faceLandmarks, setFaceLandmarks] = import_react5.useState([]); + const [isMediaPipeReady, setIsMediaPipeReady] = import_react5.useState(false); + const [isDrawingUtilsReady, setIsDrawingUtilsReady] = import_react5.useState(false); + const [blendShapes, setBlendShapes] = import_react5.useState([]); + const [dragStart, setDragStart] = import_react5.useState(null); + const [dragEnd, setDragEnd] = import_react5.useState(null); + const [isDragging, setIsDragging] = import_react5.useState(false); + const [isWaitingForResponse, setIsWaitingForResponse] = import_react5.useState(false); + const dragStartRef = import_react5.useRef(null); + const currentMousePosRef = import_react5.useRef(null); + const lastModifiedImageHashRef = import_react5.useRef(null); + const [currentLandmark, setCurrentLandmark] = import_react5.useState(null); + const [previousLandmark, setPreviousLandmark] = import_react5.useState(null); + const [currentOpacity, setCurrentOpacity] = import_react5.useState(0); + const [previousOpacity, setPreviousOpacity] = import_react5.useState(0); + const [isHovering, setIsHovering] = import_react5.useState(false); + const canvasRef = import_react5.useRef(null); + const mediaPipeRef = import_react5.useRef({ + faceLandmarker: null, + drawingUtils: null + }); + const setActiveLandmark = import_react5.useCallback((newLandmark) => { + setPreviousLandmark(currentLandmark || null); + setCurrentLandmark(newLandmark || null); + setCurrentOpacity(0); + setPreviousOpacity(1); + }, [currentLandmark, setPreviousLandmark, setCurrentLandmark, setCurrentOpacity, setPreviousOpacity]); + import_react5.useEffect(() => { + console.log("Initializing MediaPipe..."); + let isMounted = true; + const initializeMediaPipe = async () => { + const { FaceLandmarker, FilesetResolver, DrawingUtils } = exports_vision_bundle; + try { + console.log("Initializing FilesetResolver..."); + const filesetResolver = await FilesetResolver.forVisionTasks("https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.3/wasm"); + console.log("Creating FaceLandmarker..."); + const faceLandmarker = await FaceLandmarker.createFromOptions(filesetResolver, { + baseOptions: { + modelAssetPath: `https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/1/face_landmarker.task`, + delegate: "GPU" + }, + outputFaceBlendshapes: true, + runningMode: "IMAGE", + numFaces: 1 + }); + if (isMounted) { + console.log("FaceLandmarker created successfully."); + mediaPipeRef.current.faceLandmarker = faceLandmarker; + setIsMediaPipeReady(true); + } else { + faceLandmarker.close(); + } + } catch (error2) { + console.error("Error during MediaPipe initialization:", error2); + setError("Failed to initialize face detection. Please try refreshing the page."); + } + }; + initializeMediaPipe(); + return () => { + isMounted = false; + if (mediaPipeRef.current.faceLandmarker) { + mediaPipeRef.current.faceLandmarker.close(); + } + }; + }, []); + const [landmarkCenters, setLandmarkCenters] = import_react5.useState({}); + const computeLandmarkCenters = import_react5.useCallback((landmarks2) => { + const centers = {}; + const computeGroupCenter = (group) => { + let sumX = 0, sumY = 0, sumZ = 0, count = 0; + group.forEach(([index]) => { + if (landmarks2[index]) { + sumX += landmarks2[index].x; + sumY += landmarks2[index].y; + sumZ += landmarks2[index].z || 0; + count++; + } + }); + return { x: sumX / count, y: sumY / count, z: sumZ / count }; + }; + centers.lips = computeGroupCenter(FACEMESH_LIPS); + centers.leftEye = computeGroupCenter(FACEMESH_LEFT_EYE); + centers.leftEyebrow = computeGroupCenter(FACEMESH_LEFT_EYEBROW); + centers.rightEye = computeGroupCenter(FACEMESH_RIGHT_EYE); + centers.rightEyebrow = computeGroupCenter(FACEMESH_RIGHT_EYEBROW); + centers.faceOval = computeGroupCenter(FACEMESH_FACE_OVAL); + centers.background = { x: 0.5, y: 0.5, z: 0 }; + setLandmarkCenters(centers); + }, []); + const findClosestLandmark = import_react5.useCallback((mouseX, mouseY, isGroup) => { + const defaultLandmark = { + group: "background", + distance: 0, + vector: { + x: mouseX, + y: mouseY, + z: 0 + } + }; + if (Object.keys(landmarkCenters).length === 0) { + console.warn("Landmark centers not computed yet"); + return defaultLandmark; + } + let closestGroup = null; + let minDistance = Infinity; + let closestVector = { x: 0, y: 0, z: 0 }; + let faceOvalDistance = Infinity; + let faceOvalVector = { x: 0, y: 0, z: 0 }; + Object.entries(landmarkCenters).forEach(([group, center]) => { + const dx = mouseX - center.x; + const dy = mouseY - center.y; + const distance = Math.sqrt(dx * dx + dy * dy); + if (group === "faceOval") { + faceOvalDistance = distance; + faceOvalVector = { x: dx, y: dy, z: 0 }; + } + if (isGroup) { + if (group !== isGroup) { + return; + } + } + if (distance < minDistance) { + minDistance = distance; + closestGroup = group; + closestVector = { x: dx, y: dy, z: 0 }; + } + }); + if (minDistance > 0.05) { + closestGroup = "background"; + minDistance = faceOvalDistance; + closestVector = faceOvalVector; + } + if (closestGroup) { + return { group: closestGroup, distance: minDistance, vector: closestVector }; + } else { + return defaultLandmark; + } + }, [landmarkCenters]); + const detectFaceLandmarks = import_react5.useCallback(async (imageDataUrl) => { + if (!isMediaPipeReady) { + console.log("MediaPipe not ready. Skipping detection."); + return; + } + const faceLandmarker = mediaPipeRef.current.faceLandmarker; + if (!faceLandmarker) { + console.error("FaceLandmarker is not initialized."); + return; + } + const drawingUtils = mediaPipeRef.current.drawingUtils; + const image = new Image; + image.src = imageDataUrl; + await new Promise((resolve) => { + image.onload = resolve; + }); + const faceLandmarkerResult = faceLandmarker.detect(image); + setFaceLandmarks(faceLandmarkerResult.faceLandmarks); + setBlendShapes(faceLandmarkerResult.faceBlendshapes || []); + if (faceLandmarkerResult.faceLandmarks && faceLandmarkerResult.faceLandmarks[0]) { + computeLandmarkCenters(faceLandmarkerResult.faceLandmarks[0]); + } + if (canvasRef.current && drawingUtils) { + drawLandmarks(faceLandmarkerResult.faceLandmarks[0], canvasRef.current, drawingUtils); + } + }, [isMediaPipeReady, isDrawingUtilsReady, computeLandmarkCenters]); + const drawLandmarks = import_react5.useCallback((landmarks2, canvas, drawingUtils) => { + const ctx = canvas.getContext("2d"); + if (!ctx) + return; + ctx.clearRect(0, 0, canvas.width, canvas.height); + if (canvasRef.current && previewImage) { + const img = new Image; + img.onload = () => { + canvas.width = img.width; + canvas.height = img.height; + const drawLandmarkGroup = (landmark, opacity) => { + if (!landmark) + return; + const connections = landmarkGroups[landmark.group]; + if (connections) { + ctx.globalAlpha = opacity; + drawingUtils.drawConnectors(landmarks2, connections, { color: "orange", lineWidth: 4 }); + } + }; + drawLandmarkGroup(previousLandmark, previousOpacity); + drawLandmarkGroup(currentLandmark, currentOpacity); + ctx.globalAlpha = 1; + }; + img.src = previewImage; + } + }, [previewImage, currentLandmark, previousLandmark, currentOpacity, previousOpacity]); + import_react5.useEffect(() => { + if (isMediaPipeReady && isDrawingUtilsReady && faceLandmarks.length > 0 && canvasRef.current && mediaPipeRef.current.drawingUtils) { + drawLandmarks(faceLandmarks[0], canvasRef.current, mediaPipeRef.current.drawingUtils); + } + }, [isMediaPipeReady, isDrawingUtilsReady, faceLandmarks, currentLandmark, previousLandmark, currentOpacity, previousOpacity, drawLandmarks]); + import_react5.useEffect(() => { + let animationFrame; + const animate = () => { + setCurrentOpacity((prev) => Math.min(prev + 0.2, 1)); + setPreviousOpacity((prev) => Math.max(prev - 0.2, 0)); + if (currentOpacity < 1 || previousOpacity > 0) { + animationFrame = requestAnimationFrame(animate); + } + }; + animationFrame = requestAnimationFrame(animate); + return () => cancelAnimationFrame(animationFrame); + }, [currentLandmark]); + const canvasRefCallback = import_react5.useCallback((node) => { + if (node !== null) { + const ctx = node.getContext("2d"); + if (ctx) { + const pixelRatio = window.devicePixelRatio || 1; + node.width = node.clientWidth * pixelRatio; + node.height = node.clientHeight * pixelRatio; + ctx.scale(pixelRatio, pixelRatio); + mediaPipeRef.current.drawingUtils = new Ia(ctx); + setIsDrawingUtilsReady(true); + } else { + console.error("Failed to get 2D context from canvas."); + } + canvasRef.current = node; + } + }, []); + import_react5.useEffect(() => { + if (!isMediaPipeReady) { + console.log("MediaPipe not ready. Skipping landmark detection."); + return; + } + if (!previewImage) { + console.log("Preview image not ready. Skipping landmark detection."); + return; + } + if (!isDrawingUtilsReady) { + console.log("DrawingUtils not ready. Skipping landmark detection."); + return; + } + detectFaceLandmarks(previewImage); + }, [isMediaPipeReady, isDrawingUtilsReady, previewImage]); + const modifyImage = import_react5.useCallback(({ landmark, vector }) => { + const { + originalImage: originalImage2, + originalImageHash: originalImageHash2, + params: previousParams, + setParams, + setError: setError2 + } = useMainStore.getState(); + if (!originalImage2) { + console.error("Image file or facePoke not available"); + return; + } + const params = { + ...previousParams + }; + const minX = -0.5; + const maxX = 0.5; + const minY = -0.5; + const maxY = 0.5; + const mapRange = (value, inMin, inMax, outMin, outMax) => { + return Math.min(outMax, Math.max(outMin, (value - inMin) * (outMax - outMin) / (inMax - inMin) + outMin)); + }; + console.log("modifyImage:", { + originalImage: originalImage2, + originalImageHash: originalImageHash2, + landmark, + vector, + minX, + maxX, + minY, + maxY + }); + switch (landmark.group) { + case "leftEye": + case "rightEye": + const eyesMin = 210; + const eyesMax = 5; + params.eyes = mapRange(vector.x, minX, maxX, eyesMin, eyesMax); + break; + case "leftEyebrow": + case "rightEyebrow": + const eyebrowMin = -10; + const eyebrowMax = 15; + params.eyebrow = mapRange(vector.y, minY, maxY, eyebrowMin, eyebrowMax); + break; + case "lips": + const eeeMin = -20; + const eeeMax = 15; + params.eee = mapRange(vector.y, minY, maxY, eeeMin, eeeMax); + const wooMin = -20; + const wooMax = 15; + params.woo = mapRange(vector.x, minX, maxX, wooMin, wooMax); + break; + case "faceOval": + const rollMin = -40; + const rollMax = 40; + params.rotate_roll = mapRange(vector.x, minX, maxX, rollMin, rollMax); + break; + case "background": + const yawMin = -40; + const yawMax = 40; + params.rotate_yaw = mapRange(-vector.x, minX, maxX, yawMin, yawMax); + const pitchMin = -40; + const pitchMax = 40; + params.rotate_pitch = mapRange(vector.y, minY, maxY, pitchMin, pitchMax); + break; + default: + return; + } + for (const [key, value] of Object.entries(params)) { + if (isNaN(value) || !isFinite(value)) { + console.log(`${key} is NaN, aborting`); + return; + } + } + console.log(`PITCH=${params.rotate_pitch || 0}, YAW=${params.rotate_yaw || 0}, ROLL=${params.rotate_roll || 0}`); + setParams(params); + try { + if (!lastModifiedImageHashRef.current || lastModifiedImageHashRef.current !== originalImageHash2) { + lastModifiedImageHashRef.current = originalImageHash2; + facePoke.modifyImage(originalImage2, null, params); + } else { + facePoke.modifyImage(null, lastModifiedImageHashRef.current, params); + } + } catch (error2) { + setError2("Failed to modify image"); + } + }, []); + const modifyImageWithRateLimit = useThrottledCallback_default((params) => { + modifyImage(params); + }, [modifyImage], averageLatency); + const handleMouseEnter = import_react5.useCallback(() => { + setIsHovering(true); + }, []); + const handleMouseLeave = import_react5.useCallback(() => { + setIsHovering(false); + }, []); + const handleMouseDown = import_react5.useCallback((event) => { + if (!canvasRef.current) + return; + const rect = canvasRef.current.getBoundingClientRect(); + const x2 = (event.clientX - rect.left) / rect.width; + const y2 = (event.clientY - rect.top) / rect.height; + const landmark = findClosestLandmark(x2, y2); + console.log(`Mouse down on ${landmark.group}`); + setActiveLandmark(landmark); + setDragStart({ x: x2, y: y2 }); + dragStartRef.current = { x: x2, y: y2 }; + }, [findClosestLandmark, setActiveLandmark, setDragStart]); + const handleMouseMove = import_react5.useCallback((event) => { + if (!canvasRef.current) + return; + const rect = canvasRef.current.getBoundingClientRect(); + const x2 = (event.clientX - rect.left) / rect.width; + const y2 = (event.clientY - rect.top) / rect.height; + if (dragStart && dragStartRef.current) { + const landmark = findClosestLandmark(x2, y2, currentLandmark?.group); + console.log(`Dragging mouse (was over ${currentLandmark?.group || "nothing"}, now over ${landmark.group})`); + modifyImageWithRateLimit({ + landmark: currentLandmark || landmark, + vector: { + x: x2 - landmarkCenters[landmark.group].x, + y: y2 - landmarkCenters[landmark.group].y, + z: 0 + } + }); + setIsDragging(true); + } else { + const landmark = findClosestLandmark(x2, y2); + if (!currentLandmark || currentLandmark?.group !== landmark?.group) { + setActiveLandmark(landmark); + } + setIsHovering(true); + } + }, [currentLandmark, dragStart, setIsHovering, setActiveLandmark, setIsDragging, modifyImageWithRateLimit, landmarkCenters]); + const handleMouseUp = import_react5.useCallback((event) => { + if (!canvasRef.current) + return; + const rect = canvasRef.current.getBoundingClientRect(); + const x2 = (event.clientX - rect.left) / rect.width; + const y2 = (event.clientY - rect.top) / rect.height; + if (dragStart && dragStartRef.current) { + const landmark = findClosestLandmark(x2, y2, currentLandmark?.group); + console.log(`Mouse up (was over ${currentLandmark?.group || "nothing"}, now over ${landmark.group})`); + modifyImageWithRateLimit({ + landmark: currentLandmark || landmark, + vector: { + x: x2 - landmarkCenters[landmark.group].x, + y: y2 - landmarkCenters[landmark.group].y, + z: 0 + } + }); + } + setIsDragging(false); + dragStartRef.current = null; + setActiveLandmark(undefined); + }, [currentLandmark, isDragging, modifyImageWithRateLimit, findClosestLandmark, setActiveLandmark, landmarkCenters, modifyImageWithRateLimit, setIsDragging]); + import_react5.useEffect(() => { + facePoke.setOnModifiedImage((image, image_hash) => { + if (image) { + setPreviewImage(image); + } + setOriginalImageHash(image_hash); + lastModifiedImageHashRef.current = image_hash; + }); + }, [setPreviewImage, setOriginalImageHash]); + return { + canvasRef, + canvasRefCallback, + mediaPipeRef, + faceLandmarks, + isMediaPipeReady, + isDrawingUtilsReady, + blendShapes, + setFaceLandmarks, + setBlendShapes, + handleMouseDown, + handleMouseUp, + handleMouseMove, + handleMouseEnter, + handleMouseLeave, + currentLandmark, + currentOpacity + }; +} + +// src/components/PoweredBy.tsx +var jsx_dev_runtime2 = __toESM(require_jsx_dev_runtime(), 1); +function PoweredBy() { + return jsx_dev_runtime2.jsxDEV("div", { + className: "flex flex-row items-center justify-center font-sans mt-4 w-full", + children: [ + jsx_dev_runtime2.jsxDEV("span", { + className: "ml-2 mr-1", + children: jsx_dev_runtime2.jsxDEV("img", { + src: "/hf-logo.svg", + alt: "Hugging Face", + className: "w-5 h-5" + }, undefined, false, undefined, this) + }, undefined, false, undefined, this), + jsx_dev_runtime2.jsxDEV("span", { + className: "text-neutral-900 text-sm font-semibold", + style: { textShadow: "rgb(255 255 255 / 80%) 0px 0px 2px" }, + children: "Hugging Face" + }, undefined, false, undefined, this) + ] + }, undefined, true, undefined, this); +} + +// src/components/Spinner.tsx +var jsx_dev_runtime3 = __toESM(require_jsx_dev_runtime(), 1); +function Spinner() { + return jsx_dev_runtime3.jsxDEV("svg", { + className: "mr-3 h-6 w-6", + fill: "none", + viewBox: "0 0 24 24", + stroke: "currentColor", + children: jsx_dev_runtime3.jsxDEV("path", { + strokeLinecap: "round", + strokeLinejoin: "round", + strokeWidth: 2, + d: "M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" + }, undefined, false, undefined, this) + }, undefined, false, undefined, this); +} + +// src/hooks/useFacePokeAPI.ts +var import_react6 = __toESM(require_react(), 1); +function useFacePokeAPI() { + const [status, setStatus] = import_react6.useState(""); + const [isDebugMode, setIsDebugMode] = import_react6.useState(false); + const [interruptMessage, setInterruptMessage] = import_react6.useState(null); + const [isLoading, setIsLoading] = import_react6.useState(false); + import_react6.useEffect(() => { + const urlParams = new URLSearchParams(window.location.search); + setIsDebugMode(urlParams.get("debug") === "true"); + }, []); + import_react6.useEffect(() => { + const handleInterruption = (event) => { + setInterruptMessage(event.detail.message); + }; + window.addEventListener("websocketInterruption", handleInterruption); + return () => { + window.removeEventListener("websocketInterruption", handleInterruption); + }; + }, []); + return { + facePoke, + status, + setStatus, + isDebugMode, + setIsDebugMode, + interruptMessage, + isLoading, + setIsLoading + }; +} + +// src/layout.tsx +var jsx_dev_runtime4 = __toESM(require_jsx_dev_runtime(), 1); +function Layout({ children }) { + return jsx_dev_runtime4.jsxDEV("div", { + className: "fixed min-h-screen w-full flex items-center justify-center bg-gradient-to-br from-gray-300 to-stone-300", + style: { boxShadow: "inset 0 0 10vh 0 rgb(0 0 0 / 30%)" }, + children: jsx_dev_runtime4.jsxDEV("div", { + className: "min-h-screen w-full py-8 flex flex-col justify-center", + children: jsx_dev_runtime4.jsxDEV("div", { + className: "relative p-4 sm:max-w-5xl sm:mx-auto", + children + }, undefined, false, undefined, this) + }, undefined, false, undefined, this) + }, undefined, false, undefined, this); +} + +// src/lib/convertImageToBase64.ts +async function convertImageToBase64(imageFile) { + return new Promise((resolve, reject) => { + const reader = new FileReader; + reader.onload = () => { + if (typeof reader.result === "string") { + resolve(reader.result); + } else { + reject(new Error("Failed to convert image to base64")); + } + }; + reader.onerror = () => { + reject(new Error("Error reading file")); + }; + reader.readAsDataURL(imageFile); + }); +} + +// src/app.tsx +var jsx_dev_runtime5 = __toESM(require_jsx_dev_runtime(), 1); +function App() { + const error = useMainStore((s2) => s2.error); + const setError = useMainStore((s2) => s2.setError); + const imageFile = useMainStore((s2) => s2.imageFile); + const setImageFile = useMainStore((s2) => s2.setImageFile); + const originalImage = useMainStore((s2) => s2.originalImage); + const setOriginalImage = useMainStore((s2) => s2.setOriginalImage); + const previewImage = useMainStore((s2) => s2.previewImage); + const setPreviewImage = useMainStore((s2) => s2.setPreviewImage); + const resetImage = useMainStore((s2) => s2.resetImage); + const { + status, + setStatus, + isDebugMode, + setIsDebugMode, + interruptMessage + } = useFacePokeAPI(); + const { + canvasRef, + canvasRefCallback, + mediaPipeRef, + faceLandmarks, + isMediaPipeReady, + blendShapes, + setFaceLandmarks, + setBlendShapes, + handleMouseDown, + handleMouseUp, + handleMouseMove, + handleMouseEnter, + handleMouseLeave, + currentOpacity + } = useFaceLandmarkDetection(); + const videoRef = import_react7.useRef(null); + const handleFileChange = import_react7.useCallback(async (event) => { + const files = event.target.files; + if (files && files[0]) { + setImageFile(files[0]); + setStatus(`File selected: ${truncateFileName(files[0].name, 16)}`); + try { + const image = await convertImageToBase64(files[0]); + setPreviewImage(image); + setOriginalImage(image); + } catch (err) { + console.log(`failed to convert the image: `, err); + setImageFile(null); + setStatus(""); + setPreviewImage(""); + setOriginalImage(""); + setFaceLandmarks([]); + setBlendShapes([]); + } + } else { + setImageFile(null); + setStatus(""); + setPreviewImage(""); + setOriginalImage(""); + setFaceLandmarks([]); + setBlendShapes([]); + } + }, [isMediaPipeReady, setImageFile, setPreviewImage, setOriginalImage, setFaceLandmarks, setBlendShapes, setStatus]); + const canDisplayBlendShapes = false; + const displayBlendShapes = import_react7.useMemo(() => jsx_dev_runtime5.jsxDEV("div", { + className: "mt-4", + children: [ + jsx_dev_runtime5.jsxDEV("h3", { + className: "text-lg font-semibold mb-2", + children: "Blend Shapes" + }, undefined, false, undefined, this), + jsx_dev_runtime5.jsxDEV("ul", { + className: "space-y-1", + children: (blendShapes?.[0]?.categories || []).map((shape, index) => jsx_dev_runtime5.jsxDEV("li", { + className: "flex items-center", + children: [ + jsx_dev_runtime5.jsxDEV("span", { + className: "w-32 text-sm", + children: shape.categoryName || shape.displayName + }, undefined, false, undefined, this), + jsx_dev_runtime5.jsxDEV("div", { + className: "w-full bg-gray-200 rounded-full h-2.5", + children: jsx_dev_runtime5.jsxDEV("div", { + className: "bg-blue-600 h-2.5 rounded-full", + style: { width: `${shape.score * 100}%` } + }, undefined, false, undefined, this) + }, undefined, false, undefined, this), + jsx_dev_runtime5.jsxDEV("span", { + className: "ml-2 text-sm", + children: shape.score.toFixed(2) + }, undefined, false, undefined, this) + ] + }, index, true, undefined, this)) + }, undefined, false, undefined, this) + ] + }, undefined, true, undefined, this), [JSON.stringify(blendShapes)]); + return jsx_dev_runtime5.jsxDEV(Layout, { + children: [ + error && jsx_dev_runtime5.jsxDEV(Alert, { + variant: "destructive", + children: [ + jsx_dev_runtime5.jsxDEV(AlertTitle, { + children: "Error" + }, undefined, false, undefined, this), + jsx_dev_runtime5.jsxDEV(AlertDescription, { + children: error + }, undefined, false, undefined, this) + ] + }, undefined, true, undefined, this), + interruptMessage && jsx_dev_runtime5.jsxDEV(Alert, { + children: [ + jsx_dev_runtime5.jsxDEV(AlertTitle, { + children: "Notice" + }, undefined, false, undefined, this), + jsx_dev_runtime5.jsxDEV(AlertDescription, { + children: interruptMessage + }, undefined, false, undefined, this) + ] + }, undefined, true, undefined, this), + jsx_dev_runtime5.jsxDEV("div", { + className: "mb-5 relative", + children: [ + jsx_dev_runtime5.jsxDEV("div", { + className: "flex flex-row items-center justify-between w-full", + children: [ + jsx_dev_runtime5.jsxDEV("div", { + className: "relative", + children: [ + jsx_dev_runtime5.jsxDEV("input", { + id: "imageInput", + type: "file", + accept: "image/*", + onChange: handleFileChange, + className: "hidden", + disabled: !isMediaPipeReady + }, undefined, false, undefined, this), + jsx_dev_runtime5.jsxDEV("label", { + htmlFor: "imageInput", + className: `cursor-pointer inline-flex items-center px-3 py-1.5 border border-transparent text-sm font-medium rounded-md text-white ${isMediaPipeReady ? "bg-gray-600 hover:bg-gray-500" : "bg-gray-500 cursor-not-allowed"} focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500 shadow-xl`, + children: [ + jsx_dev_runtime5.jsxDEV(Spinner, {}, undefined, false, undefined, this), + imageFile ? truncateFileName(imageFile.name, 32) : isMediaPipeReady ? "Choose an image" : "Initializing..." + ] + }, undefined, true, undefined, this) + ] + }, undefined, true, undefined, this), + previewImage && jsx_dev_runtime5.jsxDEV("label", { + className: "mt-4 flex items-center", + children: [ + jsx_dev_runtime5.jsxDEV("input", { + type: "checkbox", + checked: isDebugMode, + onChange: (e2) => setIsDebugMode(e2.target.checked), + className: "mr-2" + }, undefined, false, undefined, this), + "Show face landmarks on hover" + ] + }, undefined, true, undefined, this) + ] + }, undefined, true, undefined, this), + previewImage && jsx_dev_runtime5.jsxDEV("div", { + className: "mt-5 relative shadow-2xl rounded-xl overflow-hidden", + children: [ + jsx_dev_runtime5.jsxDEV("img", { + src: previewImage, + alt: "Preview", + className: "w-full" + }, undefined, false, undefined, this), + jsx_dev_runtime5.jsxDEV("canvas", { + ref: canvasRefCallback, + className: "absolute top-0 left-0 w-full h-full select-none", + onMouseEnter: handleMouseEnter, + onMouseLeave: handleMouseLeave, + onMouseDown: handleMouseDown, + onMouseUp: handleMouseUp, + onMouseMove: handleMouseMove, + style: { + position: "absolute", + top: 0, + left: 0, + width: "100%", + height: "100%", + opacity: isDebugMode ? currentOpacity : 0, + transition: "opacity 0.2s ease-in-out" + } + }, undefined, false, undefined, this) + ] + }, undefined, true, undefined, this), + canDisplayBlendShapes && displayBlendShapes + ] + }, undefined, true, undefined, this), + jsx_dev_runtime5.jsxDEV(PoweredBy, {}, undefined, false, undefined, this) + ] + }, undefined, true, undefined, this); +} + +// src/index.tsx +var jsx_dev_runtime6 = __toESM(require_jsx_dev_runtime(), 1); +var root = client.createRoot(document.getElementById("root")); +root.render(jsx_dev_runtime6.jsxDEV(App, {}, undefined, false, undefined, this)); diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..7285a5477a8ff112ab1bfcc9d7513689e2f597c3 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,87 @@ + +# -------------------------------------------------------------------- +# Cuda 12.4 +# -------------------------------------------------------------------- + +--extra-index-url https://download.pytorch.org/whl/cu124 +torch +torchvision +torchaudio + + +# -------------------------------------------------------------------- +# Common libraries for LivePortrait and all +# -------------------------------------------------------------------- + +# note: gradio is only used for the cropping utility +gradio==5.0.0b4 + +gradio-webrtc==0.0.1 + +opuslib==3.0.1 + +pyyaml==6.0.1 +numpy==1.22.0 # Updated to resolve conflicts +opencv-python==4.8.1.78 # Downgraded to be compatible with numpy +scipy==1.10.1 +imageio==2.31.1 +imageio-ffmpeg==0.5.1 +lmdb==1.4.1 +tqdm==4.66.4 +rich==13.7.1 + +# this one is from 5 years ago, we should probably +# use python-ffmpeg or typed-ffmpeg instead +# https://pypi.org/search/?q=ffmpeg-python +ffmpeg-python==0.2.0 + +# versions of onnx gpu <= 1.17 did not support Cuda 12 +onnxruntime-gpu==1.19.2 +onnx==1.16.2 +scikit-image==0.20.0 +albumentations==1.3.1 +matplotlib==3.7.2 +tyro==0.8.5 +chumpy==0.70 + +diffusers==0.30.3 +accelerate==0.34.2 +tensorflow==2.12.0 +tensorboard==2.12.0 +soundfile==0.12.1 +transformers==4.39.2 + +gdown==5.2.0 +requests==2.32.3 +omegaconf==2.3.0 +moviepy==1.0.3 + +pydantic==2.9.2 + +# -------------------------------------------------------------------- +# RESERVED FOR FUTURE USAGE +# +# (it adds bloat, so you can remove them if you want) +# -------------------------------------------------------------------- +dnspython>=2.0.0 +ifaddr>=0.2.0 +aioice==0.9.0 +aiortc==1.9.0 +aiohttp==3.10.5 +av==12.3.0 +einops==0.7.0 +safetensors==0.4.5 +sentencepiece==0.2.0 +sounddevice==0.5.0 +sphn==0.1.4 +huggingface-hub==0.25.1 +optimum-quanto==0.2.4 +httpx==0.24.1 +timm==1.0.9 +ftfy==6.2.3 +facexlib==0.3.0 + +# -------------------------------------------------------------------- +# Used for advanced LivePortrait features +# -------------------------------------------------------------------- +pillow==10.4.0