From a5e840765e45fa16d3fd8491d0b2cdf7a679cbf0 Mon Sep 17 00:00:00 2001 From: Qing Date: Mon, 22 Aug 2022 23:23:48 +0800 Subject: [PATCH 1/3] make crop mode use more context --- lama_cleaner/model/base.py | 28 ++++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/lama_cleaner/model/base.py b/lama_cleaner/model/base.py index 4e8beb2..93183cb 100644 --- a/lama_cleaner/model/base.py +++ b/lama_cleaner/model/base.py @@ -120,10 +120,30 @@ class InpaintModel: w = box_w + config.hd_strategy_crop_margin * 2 h = box_h + config.hd_strategy_crop_margin * 2 - l = max(cx - w // 2, 0) - t = max(cy - h // 2, 0) - r = min(cx + w // 2, img_w) - b = min(cy + h // 2, img_h) + _l = cx - w // 2 + _r = cx + w // 2 + _t = cy - h // 2 + _b = cy + h // 2 + + l = max(_l, 0) + r = min(_r, img_w) + t = max(_t, 0) + b = min(_b, img_h) + + # try to get more context when crop around image edge + if _l < 0: + r += abs(_l) + if _r > img_w: + l -= (_r - img_w) + if _t < 0: + b += abs(_t) + if _b > img_h: + t -= (_b - img_h) + + l = max(l, 0) + r = min(r, img_w) + t = max(t, 0) + b = min(b, img_h) crop_img = image[t:b, l:r, :] crop_mask = mask[t:b, l:r] From 6d2b24ed6b07921cc06e94ad638f5e61690a5021 Mon Sep 17 00:00:00 2001 From: Qing Date: Mon, 22 Aug 2022 23:24:02 +0800 Subject: [PATCH 2/3] add MAT model --- README.md | 4 +- .../components/Settings/ModelSettingBlock.tsx | 8 + lama_cleaner/app/src/store/Atoms.tsx | 7 + lama_cleaner/helper.py | 20 + lama_cleaner/model/mat.py | 2064 +++++++++++++++++ lama_cleaner/model_manager.py | 4 +- lama_cleaner/parse_args.py | 2 +- lama_cleaner/tests/test_model.py | 32 +- 8 files changed, 2132 insertions(+), 9 deletions(-) create mode 100644 lama_cleaner/model/mat.py diff --git a/README.md b/README.md index f6f9a1f..94e8dad 100644 --- a/README.md +++ b/README.md @@ -26,6 +26,7 @@ 1. [LaMa](https://github.com/saic-mdal/lama) 1. [LDM](https://github.com/CompVis/latent-diffusion) 1. [ZITS](https://github.com/DQiaole/ZITS_inpainting) + 1. [MAT](https://github.com/fenglinglwb/MAT) - Support CPU & GPU - Various high-resolution image processing [strategy](#high-resolution-strategy) - Run as a desktop APP @@ -36,7 +37,7 @@ | ---------------------- | --------------------------------------------- | --------------------------------------------------- | | Remove unwanted things | ![unwant_object2](./assets/unwant_object.jpg) | ![unwant_object2](./assets/unwant_object_clean.jpg) | | Remove unwanted person | ![unwant_person](./assets/unwant_person.jpg) | ![unwant_person](./assets/unwant_person_clean.jpg) | -| Remove Text | ![text](./assets/unwant_text.jpg) | ![watermark_clean](./assets/unwant_text_clean.jpg) | +| Remove Text | ![text](./assets/unwant_text.jpg) | ![text](./assets/unwant_text_clean.jpg) | | Remove watermark | ![watermark](./assets/watermark.jpg) | ![watermark_clean](./assets/watermark_cleanup.jpg) | | Fix old photo | ![oldphoto](./assets/old_photo.jpg) | ![oldphoto_clean](./assets/old_photo_clean.jpg) | @@ -69,6 +70,7 @@ Available arguments: | LaMa | :+1: Generalizes well on high resolutions(~2k)
| | | LDM | :+1: Possiblablity to get better and more detail result
:+1: The balance of time and quality can be achieved by adjusting `steps`
:neutral_face: Slower than GAN model
:neutral_face: Need more GPU memory | `Steps`: You can get better result with large steps, but it will be more time-consuming
`Sampler`: ddim or [plms](https://arxiv.org/abs/2202.09778). In general plms can get [better results](https://github.com/Sanster/lama-cleaner/releases/tag/0.13.0) with fewer steps | | ZITS | :+1: Better holistic structures compared with previous methods
:neutral_face: Wireframe module is **very** slow on CPU | `Wireframe`: Enable edge and line detect | +| MAT | TODO | | ### LaMa vs LDM diff --git a/lama_cleaner/app/src/components/Settings/ModelSettingBlock.tsx b/lama_cleaner/app/src/components/Settings/ModelSettingBlock.tsx index d87d1b7..af55fdf 100644 --- a/lama_cleaner/app/src/components/Settings/ModelSettingBlock.tsx +++ b/lama_cleaner/app/src/components/Settings/ModelSettingBlock.tsx @@ -131,6 +131,8 @@ function ModelSettingBlock() { return renderLDMModelDesc() case AIModel.ZITS: return renderZITSModelDesc() + case AIModel.MAT: + return undefined default: return <> } @@ -156,6 +158,12 @@ function ModelSettingBlock() { 'https://arxiv.org/abs/2203.00867', 'https://github.com/DQiaole/ZITS_inpainting' ) + case AIModel.MAT: + return renderModelDesc( + 'Mask-Aware Transformer for Large Hole Image Inpainting', + 'https://arxiv.org/pdf/2203.15270.pdf', + 'https://github.com/fenglinglwb/MAT' + ) default: return <> } diff --git a/lama_cleaner/app/src/store/Atoms.tsx b/lama_cleaner/app/src/store/Atoms.tsx index db212b5..927427c 100644 --- a/lama_cleaner/app/src/store/Atoms.tsx +++ b/lama_cleaner/app/src/store/Atoms.tsx @@ -7,6 +7,7 @@ export enum AIModel { LAMA = 'lama', LDM = 'ldm', ZITS = 'zits', + MAT = 'mat', } export const fileState = atom({ @@ -80,6 +81,12 @@ const defaultHDSettings: ModelsHDSettings = { hdStrategyCropTrigerSize: 1024, hdStrategyCropMargin: 128, }, + [AIModel.MAT]: { + hdStrategy: HDStrategy.CROP, + hdStrategyResizeLimit: 1024, + hdStrategyCropTrigerSize: 512, + hdStrategyCropMargin: 128, + }, } export const settingStateDefault: Settings = { diff --git a/lama_cleaner/helper.py b/lama_cleaner/helper.py index 5d477f0..fc86b63 100644 --- a/lama_cleaner/helper.py +++ b/lama_cleaner/helper.py @@ -53,6 +53,26 @@ def load_jit_model(url_or_path, device): return model +def load_model(model: torch.nn.Module, url_or_path, device): + if os.path.exists(url_or_path): + model_path = url_or_path + else: + model_path = download_model(url_or_path) + + try: + state_dict = torch.load(model_path, map_location='cpu') + model.load_state_dict(state_dict, strict=True) + model.to(device) + logger.info(f"Load model from: {model_path}") + except: + logger.error( + f"Failed to load {model_path}, delete model and restart lama-cleaner" + ) + exit(-1) + model.eval() + return model + + def numpy_to_bytes(image_numpy: np.ndarray, ext: str) -> bytes: data = cv2.imencode( f".{ext}", diff --git a/lama_cleaner/model/mat.py b/lama_cleaner/model/mat.py new file mode 100644 index 0000000..cb2fafb --- /dev/null +++ b/lama_cleaner/model/mat.py @@ -0,0 +1,2064 @@ +import collections +import os +from itertools import repeat +from typing import Any +import random + +import cv2 +import torch +import torch.nn as nn +import torch.nn.functional as F + +from lama_cleaner.helper import load_model, get_cache_path_by_url, norm_img +from lama_cleaner.model.base import InpaintModel +from torch.nn.functional import conv2d, conv_transpose2d +import torch.utils.checkpoint as checkpoint +import numpy as np + +from lama_cleaner.schema import Config + + +class EasyDict(dict): + """Convenience class that behaves like a dict but allows access with the attribute syntax.""" + + def __getattr__(self, name: str) -> Any: + try: + return self[name] + except KeyError: + raise AttributeError(name) + + def __setattr__(self, name: str, value: Any) -> None: + self[name] = value + + def __delattr__(self, name: str) -> None: + del self[name] + + +activation_funcs = { + 'linear': EasyDict(func=lambda x, **_: x, def_alpha=0, def_gain=1, cuda_idx=1, ref='', has_2nd_grad=False), + 'relu': EasyDict(func=lambda x, **_: torch.nn.functional.relu(x), def_alpha=0, def_gain=np.sqrt(2), cuda_idx=2, + ref='y', has_2nd_grad=False), + 'lrelu': EasyDict(func=lambda x, alpha, **_: torch.nn.functional.leaky_relu(x, alpha), def_alpha=0.2, + def_gain=np.sqrt(2), cuda_idx=3, ref='y', has_2nd_grad=False), + 'tanh': EasyDict(func=lambda x, **_: torch.tanh(x), def_alpha=0, def_gain=1, cuda_idx=4, ref='y', + has_2nd_grad=True), + 'sigmoid': EasyDict(func=lambda x, **_: torch.sigmoid(x), def_alpha=0, def_gain=1, cuda_idx=5, ref='y', + has_2nd_grad=True), + 'elu': EasyDict(func=lambda x, **_: torch.nn.functional.elu(x), def_alpha=0, def_gain=1, cuda_idx=6, ref='y', + has_2nd_grad=True), + 'selu': EasyDict(func=lambda x, **_: torch.nn.functional.selu(x), def_alpha=0, def_gain=1, cuda_idx=7, ref='y', + has_2nd_grad=True), + 'softplus': EasyDict(func=lambda x, **_: torch.nn.functional.softplus(x), def_alpha=0, def_gain=1, cuda_idx=8, + ref='y', has_2nd_grad=True), + 'swish': EasyDict(func=lambda x, **_: torch.sigmoid(x) * x, def_alpha=0, def_gain=np.sqrt(2), cuda_idx=9, ref='x', + has_2nd_grad=True), +} + + +def _ntuple(n): + def parse(x): + if isinstance(x, collections.abc.Iterable): + return x + return tuple(repeat(x, n)) + + return parse + + +to_2tuple = _ntuple(2) + + +def _bias_act_ref(x, b=None, dim=1, act='linear', alpha=None, gain=None, clamp=None): + """Slow reference implementation of `bias_act()` using standard TensorFlow ops. + """ + assert isinstance(x, torch.Tensor) + assert clamp is None or clamp >= 0 + spec = activation_funcs[act] + alpha = float(alpha if alpha is not None else spec.def_alpha) + gain = float(gain if gain is not None else spec.def_gain) + clamp = float(clamp if clamp is not None else -1) + + # Add bias. + if b is not None: + assert isinstance(b, torch.Tensor) and b.ndim == 1 + assert 0 <= dim < x.ndim + assert b.shape[0] == x.shape[dim] + x = x + b.reshape([-1 if i == dim else 1 for i in range(x.ndim)]) + + # Evaluate activation function. + alpha = float(alpha) + x = spec.func(x, alpha=alpha) + + # Scale by gain. + gain = float(gain) + if gain != 1: + x = x * gain + + # Clamp. + if clamp >= 0: + x = x.clamp(-clamp, clamp) # pylint: disable=invalid-unary-operand-type + return x + + +def bias_act(x, b=None, dim=1, act='linear', alpha=None, gain=None, clamp=None, impl='ref'): + r"""Fused bias and activation function. + + Adds bias `b` to activation tensor `x`, evaluates activation function `act`, + and scales the result by `gain`. Each of the steps is optional. In most cases, + the fused op is considerably more efficient than performing the same calculation + using standard PyTorch ops. It supports first and second order gradients, + but not third order gradients. + + Args: + x: Input activation tensor. Can be of any shape. + b: Bias vector, or `None` to disable. Must be a 1D tensor of the same type + as `x`. The shape must be known, and it must match the dimension of `x` + corresponding to `dim`. + dim: The dimension in `x` corresponding to the elements of `b`. + The value of `dim` is ignored if `b` is not specified. + act: Name of the activation function to evaluate, or `"linear"` to disable. + Can be e.g. `"relu"`, `"lrelu"`, `"tanh"`, `"sigmoid"`, `"swish"`, etc. + See `activation_funcs` for a full list. `None` is not allowed. + alpha: Shape parameter for the activation function, or `None` to use the default. + gain: Scaling factor for the output tensor, or `None` to use default. + See `activation_funcs` for the default scaling of each activation function. + If unsure, consider specifying 1. + clamp: Clamp the output values to `[-clamp, +clamp]`, or `None` to disable + the clamping (default). + impl: Name of the implementation to use. Can be `"ref"` or `"cuda"` (default). + + Returns: + Tensor of the same shape and datatype as `x`. + """ + assert isinstance(x, torch.Tensor) + assert impl in ['ref', 'cuda'] + return _bias_act_ref(x=x, b=b, dim=dim, act=act, alpha=alpha, gain=gain, clamp=clamp) + + +def _get_filter_size(f): + if f is None: + return 1, 1 + + assert isinstance(f, torch.Tensor) and f.ndim in [1, 2] + fw = f.shape[-1] + fh = f.shape[0] + + fw = int(fw) + fh = int(fh) + assert fw >= 1 and fh >= 1 + return fw, fh + + +def _get_weight_shape(w): + shape = [int(sz) for sz in w.shape] + return shape + + +def _parse_scaling(scaling): + if isinstance(scaling, int): + scaling = [scaling, scaling] + assert isinstance(scaling, (list, tuple)) + assert all(isinstance(x, int) for x in scaling) + sx, sy = scaling + assert sx >= 1 and sy >= 1 + return sx, sy + + +def _parse_padding(padding): + if isinstance(padding, int): + padding = [padding, padding] + assert isinstance(padding, (list, tuple)) + assert all(isinstance(x, int) for x in padding) + if len(padding) == 2: + padx, pady = padding + padding = [padx, padx, pady, pady] + padx0, padx1, pady0, pady1 = padding + return padx0, padx1, pady0, pady1 + + +def setup_filter(f, device=torch.device('cpu'), normalize=True, flip_filter=False, gain=1, separable=None): + r"""Convenience function to setup 2D FIR filter for `upfirdn2d()`. + + Args: + f: Torch tensor, numpy array, or python list of the shape + `[filter_height, filter_width]` (non-separable), + `[filter_taps]` (separable), + `[]` (impulse), or + `None` (identity). + device: Result device (default: cpu). + normalize: Normalize the filter so that it retains the magnitude + for constant input signal (DC)? (default: True). + flip_filter: Flip the filter? (default: False). + gain: Overall scaling factor for signal magnitude (default: 1). + separable: Return a separable filter? (default: select automatically). + + Returns: + Float32 tensor of the shape + `[filter_height, filter_width]` (non-separable) or + `[filter_taps]` (separable). + """ + # Validate. + if f is None: + f = 1 + f = torch.as_tensor(f, dtype=torch.float32) + assert f.ndim in [0, 1, 2] + assert f.numel() > 0 + if f.ndim == 0: + f = f[np.newaxis] + + # Separable? + if separable is None: + separable = (f.ndim == 1 and f.numel() >= 8) + if f.ndim == 1 and not separable: + f = f.ger(f) + assert f.ndim == (1 if separable else 2) + + # Apply normalize, flip, gain, and device. + if normalize: + f /= f.sum() + if flip_filter: + f = f.flip(list(range(f.ndim))) + f = f * (gain ** (f.ndim / 2)) + f = f.to(device=device) + return f + + +def upfirdn2d(x, f, up=1, down=1, padding=0, flip_filter=False, gain=1, impl='cuda'): + r"""Pad, upsample, filter, and downsample a batch of 2D images. + + Performs the following sequence of operations for each channel: + + 1. Upsample the image by inserting N-1 zeros after each pixel (`up`). + + 2. Pad the image with the specified number of zeros on each side (`padding`). + Negative padding corresponds to cropping the image. + + 3. Convolve the image with the specified 2D FIR filter (`f`), shrinking it + so that the footprint of all output pixels lies within the input image. + + 4. Downsample the image by keeping every Nth pixel (`down`). + + This sequence of operations bears close resemblance to scipy.signal.upfirdn(). + The fused op is considerably more efficient than performing the same calculation + using standard PyTorch ops. It supports gradients of arbitrary order. + + Args: + x: Float32/float64/float16 input tensor of the shape + `[batch_size, num_channels, in_height, in_width]`. + f: Float32 FIR filter of the shape + `[filter_height, filter_width]` (non-separable), + `[filter_taps]` (separable), or + `None` (identity). + up: Integer upsampling factor. Can be a single int or a list/tuple + `[x, y]` (default: 1). + down: Integer downsampling factor. Can be a single int or a list/tuple + `[x, y]` (default: 1). + padding: Padding with respect to the upsampled image. Can be a single number + or a list/tuple `[x, y]` or `[x_before, x_after, y_before, y_after]` + (default: 0). + flip_filter: False = convolution, True = correlation (default: False). + gain: Overall scaling factor for signal magnitude (default: 1). + impl: Implementation to use. Can be `'ref'` or `'cuda'` (default: `'cuda'`). + + Returns: + Tensor of the shape `[batch_size, num_channels, out_height, out_width]`. + """ + # assert isinstance(x, torch.Tensor) + # assert impl in ['ref', 'cuda'] + return _upfirdn2d_ref(x, f, up=up, down=down, padding=padding, flip_filter=flip_filter, gain=gain) + + +def _upfirdn2d_ref(x, f, up=1, down=1, padding=0, flip_filter=False, gain=1): + """Slow reference implementation of `upfirdn2d()` using standard PyTorch ops. + """ + # Validate arguments. + assert isinstance(x, torch.Tensor) and x.ndim == 4 + if f is None: + f = torch.ones([1, 1], dtype=torch.float32, device=x.device) + assert isinstance(f, torch.Tensor) and f.ndim in [1, 2] + assert f.dtype == torch.float32 and not f.requires_grad + batch_size, num_channels, in_height, in_width = x.shape + # upx, upy = _parse_scaling(up) + # downx, downy = _parse_scaling(down) + + upx, upy = up, up + downx, downy = down, down + + # padx0, padx1, pady0, pady1 = _parse_padding(padding) + padx0, padx1, pady0, pady1 = padding[0], padding[1], padding[2], padding[3] + + # Upsample by inserting zeros. + x = x.reshape([batch_size, num_channels, in_height, 1, in_width, 1]) + x = torch.nn.functional.pad(x, [0, upx - 1, 0, 0, 0, upy - 1]) + x = x.reshape([batch_size, num_channels, in_height * upy, in_width * upx]) + + # Pad or crop. + x = torch.nn.functional.pad(x, [max(padx0, 0), max(padx1, 0), max(pady0, 0), max(pady1, 0)]) + x = x[:, :, max(-pady0, 0): x.shape[2] - max(-pady1, 0), max(-padx0, 0): x.shape[3] - max(-padx1, 0)] + + # Setup filter. + f = f * (gain ** (f.ndim / 2)) + f = f.to(x.dtype) + if not flip_filter: + f = f.flip(list(range(f.ndim))) + + # Convolve with the filter. + f = f[np.newaxis, np.newaxis].repeat([num_channels, 1] + [1] * f.ndim) + if f.ndim == 4: + x = conv2d(input=x, weight=f, groups=num_channels) + else: + x = conv2d(input=x, weight=f.unsqueeze(2), groups=num_channels) + x = conv2d(input=x, weight=f.unsqueeze(3), groups=num_channels) + + # Downsample by throwing away pixels. + x = x[:, :, ::downy, ::downx] + return x + + +def upsample2d(x, f, up=2, padding=0, flip_filter=False, gain=1, impl='cuda'): + r"""Upsample a batch of 2D images using the given 2D FIR filter. + + By default, the result is padded so that its shape is a multiple of the input. + User-specified padding is applied on top of that, with negative values + indicating cropping. Pixels outside the image are assumed to be zero. + + Args: + x: Float32/float64/float16 input tensor of the shape + `[batch_size, num_channels, in_height, in_width]`. + f: Float32 FIR filter of the shape + `[filter_height, filter_width]` (non-separable), + `[filter_taps]` (separable), or + `None` (identity). + up: Integer upsampling factor. Can be a single int or a list/tuple + `[x, y]` (default: 1). + padding: Padding with respect to the output. Can be a single number or a + list/tuple `[x, y]` or `[x_before, x_after, y_before, y_after]` + (default: 0). + flip_filter: False = convolution, True = correlation (default: False). + gain: Overall scaling factor for signal magnitude (default: 1). + impl: Implementation to use. Can be `'ref'` or `'cuda'` (default: `'cuda'`). + + Returns: + Tensor of the shape `[batch_size, num_channels, out_height, out_width]`. + """ + upx, upy = _parse_scaling(up) + # upx, upy = up, up + padx0, padx1, pady0, pady1 = _parse_padding(padding) + # padx0, padx1, pady0, pady1 = padding, padding, padding, padding + fw, fh = _get_filter_size(f) + p = [ + padx0 + (fw + upx - 1) // 2, + padx1 + (fw - upx) // 2, + pady0 + (fh + upy - 1) // 2, + pady1 + (fh - upy) // 2, + ] + return upfirdn2d(x, f, up=up, padding=p, flip_filter=flip_filter, gain=gain * upx * upy, impl=impl) + + +def downsample2d(x, f, down=2, padding=0, flip_filter=False, gain=1, impl='cuda'): + r"""Downsample a batch of 2D images using the given 2D FIR filter. + + By default, the result is padded so that its shape is a fraction of the input. + User-specified padding is applied on top of that, with negative values + indicating cropping. Pixels outside the image are assumed to be zero. + + Args: + x: Float32/float64/float16 input tensor of the shape + `[batch_size, num_channels, in_height, in_width]`. + f: Float32 FIR filter of the shape + `[filter_height, filter_width]` (non-separable), + `[filter_taps]` (separable), or + `None` (identity). + down: Integer downsampling factor. Can be a single int or a list/tuple + `[x, y]` (default: 1). + padding: Padding with respect to the input. Can be a single number or a + list/tuple `[x, y]` or `[x_before, x_after, y_before, y_after]` + (default: 0). + flip_filter: False = convolution, True = correlation (default: False). + gain: Overall scaling factor for signal magnitude (default: 1). + impl: Implementation to use. Can be `'ref'` or `'cuda'` (default: `'cuda'`). + + Returns: + Tensor of the shape `[batch_size, num_channels, out_height, out_width]`. + """ + downx, downy = _parse_scaling(down) + # padx0, padx1, pady0, pady1 = _parse_padding(padding) + padx0, padx1, pady0, pady1 = padding, padding, padding, padding + + fw, fh = _get_filter_size(f) + p = [ + padx0 + (fw - downx + 1) // 2, + padx1 + (fw - downx) // 2, + pady0 + (fh - downy + 1) // 2, + pady1 + (fh - downy) // 2, + ] + return upfirdn2d(x, f, down=down, padding=p, flip_filter=flip_filter, gain=gain, impl=impl) + + +def _conv2d_wrapper(x, w, stride=1, padding=0, groups=1, transpose=False, flip_weight=True): + """Wrapper for the underlying `conv2d()` and `conv_transpose2d()` implementations. + """ + out_channels, in_channels_per_group, kh, kw = _get_weight_shape(w) + + # Flip weight if requested. + if not flip_weight: # conv2d() actually performs correlation (flip_weight=True) not convolution (flip_weight=False). + w = w.flip([2, 3]) + + # Workaround performance pitfall in cuDNN 8.0.5, triggered when using + # 1x1 kernel + memory_format=channels_last + less than 64 channels. + if kw == 1 and kh == 1 and stride == 1 and padding in [0, [0, 0], (0, 0)] and not transpose: + if x.stride()[1] == 1 and min(out_channels, in_channels_per_group) < 64: + if out_channels <= 4 and groups == 1: + in_shape = x.shape + x = w.squeeze(3).squeeze(2) @ x.reshape([in_shape[0], in_channels_per_group, -1]) + x = x.reshape([in_shape[0], out_channels, in_shape[2], in_shape[3]]) + else: + x = x.to(memory_format=torch.contiguous_format) + w = w.to(memory_format=torch.contiguous_format) + x = conv2d(x, w, groups=groups) + return x.to(memory_format=torch.channels_last) + + # Otherwise => execute using conv2d_gradfix. + op = conv_transpose2d if transpose else conv2d + return op(x, w, stride=stride, padding=padding, groups=groups) + + +def conv2d_resample(x, w, f=None, up=1, down=1, padding=0, groups=1, flip_weight=True, flip_filter=False): + r"""2D convolution with optional up/downsampling. + + Padding is performed only once at the beginning, not between the operations. + + Args: + x: Input tensor of shape + `[batch_size, in_channels, in_height, in_width]`. + w: Weight tensor of shape + `[out_channels, in_channels//groups, kernel_height, kernel_width]`. + f: Low-pass filter for up/downsampling. Must be prepared beforehand by + calling setup_filter(). None = identity (default). + up: Integer upsampling factor (default: 1). + down: Integer downsampling factor (default: 1). + padding: Padding with respect to the upsampled image. Can be a single number + or a list/tuple `[x, y]` or `[x_before, x_after, y_before, y_after]` + (default: 0). + groups: Split input channels into N groups (default: 1). + flip_weight: False = convolution, True = correlation (default: True). + flip_filter: False = convolution, True = correlation (default: False). + + Returns: + Tensor of the shape `[batch_size, num_channels, out_height, out_width]`. + """ + # Validate arguments. + assert isinstance(x, torch.Tensor) and (x.ndim == 4) + assert isinstance(w, torch.Tensor) and (w.ndim == 4) and (w.dtype == x.dtype) + assert f is None or (isinstance(f, torch.Tensor) and f.ndim in [1, 2] and f.dtype == torch.float32) + assert isinstance(up, int) and (up >= 1) + assert isinstance(down, int) and (down >= 1) + # assert isinstance(groups, int) and (groups >= 1), f"!!!!!! groups: {groups} isinstance(groups, int) {isinstance(groups, int)} {type(groups)}" + out_channels, in_channels_per_group, kh, kw = _get_weight_shape(w) + fw, fh = _get_filter_size(f) + # px0, px1, py0, py1 = _parse_padding(padding) + px0, px1, py0, py1 = padding, padding, padding, padding + + # Adjust padding to account for up/downsampling. + if up > 1: + px0 += (fw + up - 1) // 2 + px1 += (fw - up) // 2 + py0 += (fh + up - 1) // 2 + py1 += (fh - up) // 2 + if down > 1: + px0 += (fw - down + 1) // 2 + px1 += (fw - down) // 2 + py0 += (fh - down + 1) // 2 + py1 += (fh - down) // 2 + + # Fast path: 1x1 convolution with downsampling only => downsample first, then convolve. + if kw == 1 and kh == 1 and (down > 1 and up == 1): + x = upfirdn2d(x=x, f=f, down=down, padding=[px0, px1, py0, py1], flip_filter=flip_filter) + x = _conv2d_wrapper(x=x, w=w, groups=groups, flip_weight=flip_weight) + return x + + # Fast path: 1x1 convolution with upsampling only => convolve first, then upsample. + if kw == 1 and kh == 1 and (up > 1 and down == 1): + x = _conv2d_wrapper(x=x, w=w, groups=groups, flip_weight=flip_weight) + x = upfirdn2d(x=x, f=f, up=up, padding=[px0, px1, py0, py1], gain=up ** 2, flip_filter=flip_filter) + return x + + # Fast path: downsampling only => use strided convolution. + if down > 1 and up == 1: + x = upfirdn2d(x=x, f=f, padding=[px0, px1, py0, py1], flip_filter=flip_filter) + x = _conv2d_wrapper(x=x, w=w, stride=down, groups=groups, flip_weight=flip_weight) + return x + + # Fast path: upsampling with optional downsampling => use transpose strided convolution. + if up > 1: + if groups == 1: + w = w.transpose(0, 1) + else: + w = w.reshape(groups, out_channels // groups, in_channels_per_group, kh, kw) + w = w.transpose(1, 2) + w = w.reshape(groups * in_channels_per_group, out_channels // groups, kh, kw) + px0 -= kw - 1 + px1 -= kw - up + py0 -= kh - 1 + py1 -= kh - up + pxt = max(min(-px0, -px1), 0) + pyt = max(min(-py0, -py1), 0) + x = _conv2d_wrapper(x=x, w=w, stride=up, padding=[pyt, pxt], groups=groups, transpose=True, + flip_weight=(not flip_weight)) + x = upfirdn2d(x=x, f=f, padding=[px0 + pxt, px1 + pxt, py0 + pyt, py1 + pyt], gain=up ** 2, + flip_filter=flip_filter) + if down > 1: + x = upfirdn2d(x=x, f=f, down=down, flip_filter=flip_filter) + return x + + # Fast path: no up/downsampling, padding supported by the underlying implementation => use plain conv2d. + if up == 1 and down == 1: + if px0 == px1 and py0 == py1 and px0 >= 0 and py0 >= 0: + return _conv2d_wrapper(x=x, w=w, padding=[py0, px0], groups=groups, flip_weight=flip_weight) + + # Fallback: Generic reference implementation. + x = upfirdn2d(x=x, f=(f if up > 1 else None), up=up, padding=[px0, px1, py0, py1], gain=up ** 2, + flip_filter=flip_filter) + x = _conv2d_wrapper(x=x, w=w, groups=groups, flip_weight=flip_weight) + if down > 1: + x = upfirdn2d(x=x, f=f, down=down, flip_filter=flip_filter) + return x + + +# ---------------------------------------------------------------------------- + + +def normalize_2nd_moment(x, dim=1, eps=1e-8): + return x * (x.square().mean(dim=dim, keepdim=True) + eps).rsqrt() + + +class FullyConnectedLayer(nn.Module): + def __init__(self, + in_features, # Number of input features. + out_features, # Number of output features. + bias=True, # Apply additive bias before the activation function? + activation='linear', # Activation function: 'relu', 'lrelu', etc. + lr_multiplier=1, # Learning rate multiplier. + bias_init=0, # Initial value for the additive bias. + ): + super().__init__() + self.weight = torch.nn.Parameter(torch.randn([out_features, in_features]) / lr_multiplier) + self.bias = torch.nn.Parameter(torch.full([out_features], np.float32(bias_init))) if bias else None + self.activation = activation + + self.weight_gain = lr_multiplier / np.sqrt(in_features) + self.bias_gain = lr_multiplier + + def forward(self, x): + w = self.weight * self.weight_gain + b = self.bias + if b is not None and self.bias_gain != 1: + b = b * self.bias_gain + + if self.activation == 'linear' and b is not None: + # out = torch.addmm(b.unsqueeze(0), x, w.t()) + x = x.matmul(w.t()) + out = x + b.reshape([-1 if i == x.ndim - 1 else 1 for i in range(x.ndim)]) + else: + x = x.matmul(w.t()) + out = bias_act(x, b, act=self.activation, dim=x.ndim - 1) + return out + + +class Conv2dLayer(nn.Module): + def __init__(self, + in_channels, # Number of input channels. + out_channels, # Number of output channels. + kernel_size, # Width and height of the convolution kernel. + bias=True, # Apply additive bias before the activation function? + activation='linear', # Activation function: 'relu', 'lrelu', etc. + up=1, # Integer upsampling factor. + down=1, # Integer downsampling factor. + resample_filter=[1, 3, 3, 1], # Low-pass filter to apply when resampling activations. + conv_clamp=None, # Clamp the output to +-X, None = disable clamping. + trainable=True, # Update the weights of this layer during training? + ): + super().__init__() + self.activation = activation + self.up = up + self.down = down + self.register_buffer('resample_filter', setup_filter(resample_filter)) + self.conv_clamp = conv_clamp + self.padding = kernel_size // 2 + self.weight_gain = 1 / np.sqrt(in_channels * (kernel_size ** 2)) + self.act_gain = activation_funcs[activation].def_gain + + weight = torch.randn([out_channels, in_channels, kernel_size, kernel_size]) + bias = torch.zeros([out_channels]) if bias else None + if trainable: + self.weight = torch.nn.Parameter(weight) + self.bias = torch.nn.Parameter(bias) if bias is not None else None + else: + self.register_buffer('weight', weight) + if bias is not None: + self.register_buffer('bias', bias) + else: + self.bias = None + + def forward(self, x, gain=1): + w = self.weight * self.weight_gain + x = conv2d_resample(x=x, w=w, f=self.resample_filter, up=self.up, down=self.down, + padding=self.padding) + + act_gain = self.act_gain * gain + act_clamp = self.conv_clamp * gain if self.conv_clamp is not None else None + out = bias_act(x, self.bias, act=self.activation, gain=act_gain, clamp=act_clamp) + return out + + +class ModulatedConv2d(nn.Module): + def __init__(self, + in_channels, # Number of input channels. + out_channels, # Number of output channels. + kernel_size, # Width and height of the convolution kernel. + style_dim, # dimension of the style code + demodulate=True, # perfrom demodulation + up=1, # Integer upsampling factor. + down=1, # Integer downsampling factor. + resample_filter=[1, 3, 3, 1], # Low-pass filter to apply when resampling activations. + conv_clamp=None, # Clamp the output to +-X, None = disable clamping. + ): + super().__init__() + self.demodulate = demodulate + + self.weight = torch.nn.Parameter(torch.randn([1, out_channels, in_channels, kernel_size, kernel_size])) + self.out_channels = out_channels + self.kernel_size = kernel_size + self.weight_gain = 1 / np.sqrt(in_channels * (kernel_size ** 2)) + self.padding = self.kernel_size // 2 + self.up = up + self.down = down + self.register_buffer('resample_filter', setup_filter(resample_filter)) + self.conv_clamp = conv_clamp + + self.affine = FullyConnectedLayer(style_dim, in_channels, bias_init=1) + + def forward(self, x, style): + batch, in_channels, height, width = x.shape + style = self.affine(style).view(batch, 1, in_channels, 1, 1) + weight = self.weight * self.weight_gain * style + + if self.demodulate: + decoefs = (weight.pow(2).sum(dim=[2, 3, 4]) + 1e-8).rsqrt() + weight = weight * decoefs.view(batch, self.out_channels, 1, 1, 1) + + weight = weight.view(batch * self.out_channels, in_channels, self.kernel_size, self.kernel_size) + x = x.view(1, batch * in_channels, height, width) + x = conv2d_resample(x=x, w=weight, f=self.resample_filter, up=self.up, down=self.down, + padding=self.padding, groups=batch) + out = x.view(batch, self.out_channels, *x.shape[2:]) + + return out + + +class StyleConv(torch.nn.Module): + def __init__(self, + in_channels, # Number of input channels. + out_channels, # Number of output channels. + style_dim, # Intermediate latent (W) dimensionality. + resolution, # Resolution of this layer. + kernel_size=3, # Convolution kernel size. + up=1, # Integer upsampling factor. + use_noise=False, # Enable noise input? + activation='lrelu', # Activation function: 'relu', 'lrelu', etc. + resample_filter=[1, 3, 3, 1], # Low-pass filter to apply when resampling activations. + conv_clamp=None, # Clamp the output of convolution layers to +-X, None = disable clamping. + demodulate=True, # perform demodulation + ): + super().__init__() + + self.conv = ModulatedConv2d(in_channels=in_channels, + out_channels=out_channels, + kernel_size=kernel_size, + style_dim=style_dim, + demodulate=demodulate, + up=up, + resample_filter=resample_filter, + conv_clamp=conv_clamp) + + self.use_noise = use_noise + self.resolution = resolution + if use_noise: + self.register_buffer('noise_const', torch.randn([resolution, resolution])) + self.noise_strength = torch.nn.Parameter(torch.zeros([])) + + self.bias = torch.nn.Parameter(torch.zeros([out_channels])) + self.activation = activation + self.act_gain = activation_funcs[activation].def_gain + self.conv_clamp = conv_clamp + + def forward(self, x, style, noise_mode='random', gain=1): + x = self.conv(x, style) + + assert noise_mode in ['random', 'const', 'none'] + + if self.use_noise: + if noise_mode == 'random': + xh, xw = x.size()[-2:] + noise = torch.randn([x.shape[0], 1, xh, xw], device=x.device) \ + * self.noise_strength + if noise_mode == 'const': + noise = self.noise_const * self.noise_strength + x = x + noise + + act_gain = self.act_gain * gain + act_clamp = self.conv_clamp * gain if self.conv_clamp is not None else None + out = bias_act(x, self.bias, act=self.activation, gain=act_gain, clamp=act_clamp) + + return out + + +class ToRGB(torch.nn.Module): + def __init__(self, + in_channels, + out_channels, + style_dim, + kernel_size=1, + resample_filter=[1, 3, 3, 1], + conv_clamp=None, + demodulate=False): + super().__init__() + + self.conv = ModulatedConv2d(in_channels=in_channels, + out_channels=out_channels, + kernel_size=kernel_size, + style_dim=style_dim, + demodulate=demodulate, + resample_filter=resample_filter, + conv_clamp=conv_clamp) + self.bias = torch.nn.Parameter(torch.zeros([out_channels])) + self.register_buffer('resample_filter', setup_filter(resample_filter)) + self.conv_clamp = conv_clamp + + def forward(self, x, style, skip=None): + x = self.conv(x, style) + out = bias_act(x, self.bias, clamp=self.conv_clamp) + + if skip is not None: + if skip.shape != out.shape: + skip = upsample2d(skip, self.resample_filter) + out = out + skip + + return out + + +def get_style_code(a, b): + return torch.cat([a, b], dim=1) + + +class DecBlockFirst(nn.Module): + def __init__(self, in_channels, out_channels, activation, style_dim, use_noise, demodulate, img_channels): + super().__init__() + self.fc = FullyConnectedLayer(in_features=in_channels * 2, + out_features=in_channels * 4 ** 2, + activation=activation) + self.conv = StyleConv(in_channels=in_channels, + out_channels=out_channels, + style_dim=style_dim, + resolution=4, + kernel_size=3, + use_noise=use_noise, + activation=activation, + demodulate=demodulate, + ) + self.toRGB = ToRGB(in_channels=out_channels, + out_channels=img_channels, + style_dim=style_dim, + kernel_size=1, + demodulate=False, + ) + + def forward(self, x, ws, gs, E_features, noise_mode='random'): + x = self.fc(x).view(x.shape[0], -1, 4, 4) + x = x + E_features[2] + style = get_style_code(ws[:, 0], gs) + x = self.conv(x, style, noise_mode=noise_mode) + style = get_style_code(ws[:, 1], gs) + img = self.toRGB(x, style, skip=None) + + return x, img + + +class DecBlockFirstV2(nn.Module): + def __init__(self, in_channels, out_channels, activation, style_dim, use_noise, demodulate, img_channels): + super().__init__() + self.conv0 = Conv2dLayer(in_channels=in_channels, + out_channels=in_channels, + kernel_size=3, + activation=activation, + ) + self.conv1 = StyleConv(in_channels=in_channels, + out_channels=out_channels, + style_dim=style_dim, + resolution=4, + kernel_size=3, + use_noise=use_noise, + activation=activation, + demodulate=demodulate, + ) + self.toRGB = ToRGB(in_channels=out_channels, + out_channels=img_channels, + style_dim=style_dim, + kernel_size=1, + demodulate=False, + ) + + def forward(self, x, ws, gs, E_features, noise_mode='random'): + # x = self.fc(x).view(x.shape[0], -1, 4, 4) + x = self.conv0(x) + x = x + E_features[2] + style = get_style_code(ws[:, 0], gs) + x = self.conv1(x, style, noise_mode=noise_mode) + style = get_style_code(ws[:, 1], gs) + img = self.toRGB(x, style, skip=None) + + return x, img + + +class DecBlock(nn.Module): + def __init__(self, res, in_channels, out_channels, activation, style_dim, use_noise, demodulate, + img_channels): # res = 2, ..., resolution_log2 + super().__init__() + self.res = res + + self.conv0 = StyleConv(in_channels=in_channels, + out_channels=out_channels, + style_dim=style_dim, + resolution=2 ** res, + kernel_size=3, + up=2, + use_noise=use_noise, + activation=activation, + demodulate=demodulate, + ) + self.conv1 = StyleConv(in_channels=out_channels, + out_channels=out_channels, + style_dim=style_dim, + resolution=2 ** res, + kernel_size=3, + use_noise=use_noise, + activation=activation, + demodulate=demodulate, + ) + self.toRGB = ToRGB(in_channels=out_channels, + out_channels=img_channels, + style_dim=style_dim, + kernel_size=1, + demodulate=False, + ) + + def forward(self, x, img, ws, gs, E_features, noise_mode='random'): + style = get_style_code(ws[:, self.res * 2 - 5], gs) + x = self.conv0(x, style, noise_mode=noise_mode) + x = x + E_features[self.res] + style = get_style_code(ws[:, self.res * 2 - 4], gs) + x = self.conv1(x, style, noise_mode=noise_mode) + style = get_style_code(ws[:, self.res * 2 - 3], gs) + img = self.toRGB(x, style, skip=img) + + return x, img + + +class MappingNet(torch.nn.Module): + def __init__(self, + z_dim, # Input latent (Z) dimensionality, 0 = no latent. + c_dim, # Conditioning label (C) dimensionality, 0 = no label. + w_dim, # Intermediate latent (W) dimensionality. + num_ws, # Number of intermediate latents to output, None = do not broadcast. + num_layers=8, # Number of mapping layers. + embed_features=None, # Label embedding dimensionality, None = same as w_dim. + layer_features=None, # Number of intermediate features in the mapping layers, None = same as w_dim. + activation='lrelu', # Activation function: 'relu', 'lrelu', etc. + lr_multiplier=0.01, # Learning rate multiplier for the mapping layers. + w_avg_beta=0.995, # Decay for tracking the moving average of W during training, None = do not track. + ): + super().__init__() + self.z_dim = z_dim + self.c_dim = c_dim + self.w_dim = w_dim + self.num_ws = num_ws + self.num_layers = num_layers + self.w_avg_beta = w_avg_beta + + if embed_features is None: + embed_features = w_dim + if c_dim == 0: + embed_features = 0 + if layer_features is None: + layer_features = w_dim + features_list = [z_dim + embed_features] + [layer_features] * (num_layers - 1) + [w_dim] + + if c_dim > 0: + self.embed = FullyConnectedLayer(c_dim, embed_features) + for idx in range(num_layers): + in_features = features_list[idx] + out_features = features_list[idx + 1] + layer = FullyConnectedLayer(in_features, out_features, activation=activation, lr_multiplier=lr_multiplier) + setattr(self, f'fc{idx}', layer) + + if num_ws is not None and w_avg_beta is not None: + self.register_buffer('w_avg', torch.zeros([w_dim])) + + def forward(self, z, c, truncation_psi=1, truncation_cutoff=None, skip_w_avg_update=False): + # Embed, normalize, and concat inputs. + x = None + with torch.autograd.profiler.record_function('input'): + if self.z_dim > 0: + x = normalize_2nd_moment(z.to(torch.float32)) + if self.c_dim > 0: + y = normalize_2nd_moment(self.embed(c.to(torch.float32))) + x = torch.cat([x, y], dim=1) if x is not None else y + + # Main layers. + for idx in range(self.num_layers): + layer = getattr(self, f'fc{idx}') + x = layer(x) + + # Update moving average of W. + if self.w_avg_beta is not None and self.training and not skip_w_avg_update: + with torch.autograd.profiler.record_function('update_w_avg'): + self.w_avg.copy_(x.detach().mean(dim=0).lerp(self.w_avg, self.w_avg_beta)) + + # Broadcast. + if self.num_ws is not None: + with torch.autograd.profiler.record_function('broadcast'): + x = x.unsqueeze(1).repeat([1, self.num_ws, 1]) + + # Apply truncation. + if truncation_psi != 1: + with torch.autograd.profiler.record_function('truncate'): + assert self.w_avg_beta is not None + if self.num_ws is None or truncation_cutoff is None: + x = self.w_avg.lerp(x, truncation_psi) + else: + x[:, :truncation_cutoff] = self.w_avg.lerp(x[:, :truncation_cutoff], truncation_psi) + + return x + + +class DisFromRGB(nn.Module): + def __init__(self, in_channels, out_channels, activation): # res = 2, ..., resolution_log2 + super().__init__() + self.conv = Conv2dLayer(in_channels=in_channels, + out_channels=out_channels, + kernel_size=1, + activation=activation, + ) + + def forward(self, x): + return self.conv(x) + + +class DisBlock(nn.Module): + def __init__(self, in_channels, out_channels, activation): # res = 2, ..., resolution_log2 + super().__init__() + self.conv0 = Conv2dLayer(in_channels=in_channels, + out_channels=in_channels, + kernel_size=3, + activation=activation, + ) + self.conv1 = Conv2dLayer(in_channels=in_channels, + out_channels=out_channels, + kernel_size=3, + down=2, + activation=activation, + ) + self.skip = Conv2dLayer(in_channels=in_channels, + out_channels=out_channels, + kernel_size=1, + down=2, + bias=False, + ) + + def forward(self, x): + skip = self.skip(x, gain=np.sqrt(0.5)) + x = self.conv0(x) + x = self.conv1(x, gain=np.sqrt(0.5)) + out = skip + x + + return out + + +class MinibatchStdLayer(torch.nn.Module): + def __init__(self, group_size, num_channels=1): + super().__init__() + self.group_size = group_size + self.num_channels = num_channels + + def forward(self, x): + N, C, H, W = x.shape + G = torch.min(torch.as_tensor(self.group_size), + torch.as_tensor(N)) if self.group_size is not None else N + F = self.num_channels + c = C // F + + y = x.reshape(G, -1, F, c, H, + W) # [GnFcHW] Split minibatch N into n groups of size G, and channels C into F groups of size c. + y = y - y.mean(dim=0) # [GnFcHW] Subtract mean over group. + y = y.square().mean(dim=0) # [nFcHW] Calc variance over group. + y = (y + 1e-8).sqrt() # [nFcHW] Calc stddev over group. + y = y.mean(dim=[2, 3, 4]) # [nF] Take average over channels and pixels. + y = y.reshape(-1, F, 1, 1) # [nF11] Add missing dimensions. + y = y.repeat(G, 1, H, W) # [NFHW] Replicate over group and pixels. + x = torch.cat([x, y], dim=1) # [NCHW] Append to input as new channels. + return x + + +class Discriminator(torch.nn.Module): + def __init__(self, + c_dim, # Conditioning label (C) dimensionality. + img_resolution, # Input resolution. + img_channels, # Number of input color channels. + channel_base=32768, # Overall multiplier for the number of channels. + channel_max=512, # Maximum number of channels in any layer. + channel_decay=1, + cmap_dim=None, # Dimensionality of mapped conditioning label, None = default. + activation='lrelu', + mbstd_group_size=4, # Group size for the minibatch standard deviation layer, None = entire minibatch. + mbstd_num_channels=1, # Number of features for the minibatch standard deviation layer, 0 = disable. + ): + super().__init__() + self.c_dim = c_dim + self.img_resolution = img_resolution + self.img_channels = img_channels + + resolution_log2 = int(np.log2(img_resolution)) + assert img_resolution == 2 ** resolution_log2 and img_resolution >= 4 + self.resolution_log2 = resolution_log2 + + def nf(stage): + return np.clip(int(channel_base / 2 ** (stage * channel_decay)), 1, channel_max) + + if cmap_dim == None: + cmap_dim = nf(2) + if c_dim == 0: + cmap_dim = 0 + self.cmap_dim = cmap_dim + + if c_dim > 0: + self.mapping = MappingNet(z_dim=0, c_dim=c_dim, w_dim=cmap_dim, num_ws=None, w_avg_beta=None) + + Dis = [DisFromRGB(img_channels + 1, nf(resolution_log2), activation)] + for res in range(resolution_log2, 2, -1): + Dis.append(DisBlock(nf(res), nf(res - 1), activation)) + + if mbstd_num_channels > 0: + Dis.append(MinibatchStdLayer(group_size=mbstd_group_size, num_channels=mbstd_num_channels)) + Dis.append(Conv2dLayer(nf(2) + mbstd_num_channels, nf(2), kernel_size=3, activation=activation)) + self.Dis = nn.Sequential(*Dis) + + self.fc0 = FullyConnectedLayer(nf(2) * 4 ** 2, nf(2), activation=activation) + self.fc1 = FullyConnectedLayer(nf(2), 1 if cmap_dim == 0 else cmap_dim) + + def forward(self, images_in, masks_in, c): + x = torch.cat([masks_in - 0.5, images_in], dim=1) + x = self.Dis(x) + x = self.fc1(self.fc0(x.flatten(start_dim=1))) + + if self.c_dim > 0: + cmap = self.mapping(None, c) + + if self.cmap_dim > 0: + x = (x * cmap).sum(dim=1, keepdim=True) * (1 / np.sqrt(self.cmap_dim)) + + return x + + +def nf(stage, channel_base=32768, channel_decay=1.0, channel_max=512): + NF = {512: 64, 256: 128, 128: 256, 64: 512, 32: 512, 16: 512, 8: 512, 4: 512} + return NF[2 ** stage] + + +class Mlp(nn.Module): + def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.): + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + self.fc1 = FullyConnectedLayer(in_features=in_features, out_features=hidden_features, activation='lrelu') + self.fc2 = FullyConnectedLayer(in_features=hidden_features, out_features=out_features) + + def forward(self, x): + x = self.fc1(x) + x = self.fc2(x) + return x + + +def window_partition(x, window_size): + """ + Args: + x: (B, H, W, C) + window_size (int): window size + Returns: + windows: (num_windows*B, window_size, window_size, C) + """ + B, H, W, C = x.shape + x = x.view(B, H // window_size, window_size, W // window_size, window_size, C) + windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C) + return windows + + +def window_reverse(windows, window_size: int, H: int, W: int): + """ + Args: + windows: (num_windows*B, window_size, window_size, C) + window_size (int): Window size + H (int): Height of image + W (int): Width of image + Returns: + x: (B, H, W, C) + """ + B = int(windows.shape[0] / (H * W / window_size / window_size)) + # B = windows.shape[0] / (H * W / window_size / window_size) + x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1) + x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1) + return x + + +class Conv2dLayerPartial(nn.Module): + def __init__(self, + in_channels, # Number of input channels. + out_channels, # Number of output channels. + kernel_size, # Width and height of the convolution kernel. + bias=True, # Apply additive bias before the activation function? + activation='linear', # Activation function: 'relu', 'lrelu', etc. + up=1, # Integer upsampling factor. + down=1, # Integer downsampling factor. + resample_filter=[1, 3, 3, 1], # Low-pass filter to apply when resampling activations. + conv_clamp=None, # Clamp the output to +-X, None = disable clamping. + trainable=True, # Update the weights of this layer during training? + ): + super().__init__() + self.conv = Conv2dLayer(in_channels, out_channels, kernel_size, bias, activation, up, down, resample_filter, + conv_clamp, trainable) + + self.weight_maskUpdater = torch.ones(1, 1, kernel_size, kernel_size) + self.slide_winsize = kernel_size ** 2 + self.stride = down + self.padding = kernel_size // 2 if kernel_size % 2 == 1 else 0 + + def forward(self, x, mask=None): + if mask is not None: + with torch.no_grad(): + if self.weight_maskUpdater.type() != x.type(): + self.weight_maskUpdater = self.weight_maskUpdater.to(x) + update_mask = F.conv2d(mask, self.weight_maskUpdater, bias=None, stride=self.stride, + padding=self.padding) + mask_ratio = self.slide_winsize / (update_mask + 1e-8) + update_mask = torch.clamp(update_mask, 0, 1) # 0 or 1 + mask_ratio = torch.mul(mask_ratio, update_mask) + x = self.conv(x) + x = torch.mul(x, mask_ratio) + return x, update_mask + else: + x = self.conv(x) + return x, None + + +class WindowAttention(nn.Module): + r""" Window based multi-head self attention (W-MSA) module with relative position bias. + It supports both of shifted and non-shifted window. + Args: + dim (int): Number of input channels. + window_size (tuple[int]): The height and width of the window. + num_heads (int): Number of attention heads. + qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True + qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set + attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0 + proj_drop (float, optional): Dropout ratio of output. Default: 0.0 + """ + + def __init__(self, dim, window_size, num_heads, down_ratio=1, qkv_bias=True, qk_scale=None, attn_drop=0., + proj_drop=0.): + + super().__init__() + self.dim = dim + self.window_size = window_size # Wh, Ww + self.num_heads = num_heads + head_dim = dim // num_heads + self.scale = qk_scale or head_dim ** -0.5 + + self.q = FullyConnectedLayer(in_features=dim, out_features=dim) + self.k = FullyConnectedLayer(in_features=dim, out_features=dim) + self.v = FullyConnectedLayer(in_features=dim, out_features=dim) + self.proj = FullyConnectedLayer(in_features=dim, out_features=dim) + + self.softmax = nn.Softmax(dim=-1) + + def forward(self, x, mask_windows=None, mask=None): + """ + Args: + x: input features with shape of (num_windows*B, N, C) + mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None + """ + B_, N, C = x.shape + norm_x = F.normalize(x, p=2.0, dim=-1) + q = self.q(norm_x).reshape(B_, N, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3) + k = self.k(norm_x).view(B_, -1, self.num_heads, C // self.num_heads).permute(0, 2, 3, 1) + v = self.v(x).view(B_, -1, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3) + + attn = (q @ k) * self.scale + + if mask is not None: + nW = mask.shape[0] + attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0) + attn = attn.view(-1, self.num_heads, N, N) + + if mask_windows is not None: + attn_mask_windows = mask_windows.squeeze(-1).unsqueeze(1).unsqueeze(1) + attn = attn + attn_mask_windows.masked_fill(attn_mask_windows == 0, float(-100.0)).masked_fill( + attn_mask_windows == 1, float(0.0)) + with torch.no_grad(): + mask_windows = torch.clamp(torch.sum(mask_windows, dim=1, keepdim=True), 0, 1).repeat(1, N, 1) + + attn = self.softmax(attn) + + x = (attn @ v).transpose(1, 2).reshape(B_, N, C) + x = self.proj(x) + return x, mask_windows + + +class SwinTransformerBlock(nn.Module): + r""" Swin Transformer Block. + Args: + dim (int): Number of input channels. + input_resolution (tuple[int]): Input resulotion. + num_heads (int): Number of attention heads. + window_size (int): Window size. + shift_size (int): Shift size for SW-MSA. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True + qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set. + drop (float, optional): Dropout rate. Default: 0.0 + attn_drop (float, optional): Attention dropout rate. Default: 0.0 + drop_path (float, optional): Stochastic depth rate. Default: 0.0 + act_layer (nn.Module, optional): Activation layer. Default: nn.GELU + norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm + """ + + def __init__(self, dim, input_resolution, num_heads, down_ratio=1, window_size=7, shift_size=0, + mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., drop_path=0., + act_layer=nn.GELU, norm_layer=nn.LayerNorm): + super().__init__() + self.dim = dim + self.input_resolution = input_resolution + self.num_heads = num_heads + self.window_size = window_size + self.shift_size = shift_size + self.mlp_ratio = mlp_ratio + if min(self.input_resolution) <= self.window_size: + # if window size is larger than input resolution, we don't partition windows + self.shift_size = 0 + self.window_size = min(self.input_resolution) + assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size" + + if self.shift_size > 0: + down_ratio = 1 + self.attn = WindowAttention(dim, window_size=to_2tuple(self.window_size), num_heads=num_heads, + down_ratio=down_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, + proj_drop=drop) + + self.fuse = FullyConnectedLayer(in_features=dim * 2, out_features=dim, activation='lrelu') + + mlp_hidden_dim = int(dim * mlp_ratio) + self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) + + if self.shift_size > 0: + attn_mask = self.calculate_mask(self.input_resolution) + else: + attn_mask = None + + self.register_buffer("attn_mask", attn_mask) + + def calculate_mask(self, x_size): + # calculate attention mask for SW-MSA + H, W = x_size + img_mask = torch.zeros((1, H, W, 1)) # 1 H W 1 + h_slices = (slice(0, -self.window_size), + slice(-self.window_size, -self.shift_size), + slice(-self.shift_size, None)) + w_slices = (slice(0, -self.window_size), + slice(-self.window_size, -self.shift_size), + slice(-self.shift_size, None)) + cnt = 0 + for h in h_slices: + for w in w_slices: + img_mask[:, h, w, :] = cnt + cnt += 1 + + mask_windows = window_partition(img_mask, self.window_size) # nW, window_size, window_size, 1 + mask_windows = mask_windows.view(-1, self.window_size * self.window_size) + attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2) + attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0)) + + return attn_mask + + def forward(self, x, x_size, mask=None): + # H, W = self.input_resolution + H, W = x_size + B, L, C = x.shape + # assert L == H * W, "input feature has wrong size" + + shortcut = x + x = x.view(B, H, W, C) + if mask is not None: + mask = mask.view(B, H, W, 1) + + # cyclic shift + if self.shift_size > 0: + shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2)) + if mask is not None: + shifted_mask = torch.roll(mask, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2)) + else: + shifted_x = x + if mask is not None: + shifted_mask = mask + + # partition windows + x_windows = window_partition(shifted_x, self.window_size) # nW*B, window_size, window_size, C + x_windows = x_windows.view(-1, self.window_size * self.window_size, C) # nW*B, window_size*window_size, C + if mask is not None: + mask_windows = window_partition(shifted_mask, self.window_size) + mask_windows = mask_windows.view(-1, self.window_size * self.window_size, 1) + else: + mask_windows = None + + # W-MSA/SW-MSA (to be compatible for testing on images whose shapes are the multiple of window size + if self.input_resolution == x_size: + attn_windows, mask_windows = self.attn(x_windows, mask_windows, + mask=self.attn_mask) # nW*B, window_size*window_size, C + else: + attn_windows, mask_windows = self.attn(x_windows, mask_windows, mask=self.calculate_mask(x_size).to( + x.device)) # nW*B, window_size*window_size, C + + # merge windows + attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C) + shifted_x = window_reverse(attn_windows, self.window_size, H, W) # B H' W' C + if mask is not None: + mask_windows = mask_windows.view(-1, self.window_size, self.window_size, 1) + shifted_mask = window_reverse(mask_windows, self.window_size, H, W) + + # reverse cyclic shift + if self.shift_size > 0: + x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2)) + if mask is not None: + mask = torch.roll(shifted_mask, shifts=(self.shift_size, self.shift_size), dims=(1, 2)) + else: + x = shifted_x + if mask is not None: + mask = shifted_mask + x = x.view(B, H * W, C) + if mask is not None: + mask = mask.view(B, H * W, 1) + + # FFN + x = self.fuse(torch.cat([shortcut, x], dim=-1)) + x = self.mlp(x) + + return x, mask + + +class PatchMerging(nn.Module): + def __init__(self, in_channels, out_channels, down=2): + super().__init__() + self.conv = Conv2dLayerPartial(in_channels=in_channels, + out_channels=out_channels, + kernel_size=3, + activation='lrelu', + down=down, + ) + self.down = down + + def forward(self, x, x_size, mask=None): + x = token2feature(x, x_size) + if mask is not None: + mask = token2feature(mask, x_size) + x, mask = self.conv(x, mask) + if self.down != 1: + ratio = 1 / self.down + x_size = (int(x_size[0] * ratio), int(x_size[1] * ratio)) + x = feature2token(x) + if mask is not None: + mask = feature2token(mask) + return x, x_size, mask + + +class PatchUpsampling(nn.Module): + def __init__(self, in_channels, out_channels, up=2): + super().__init__() + self.conv = Conv2dLayerPartial(in_channels=in_channels, + out_channels=out_channels, + kernel_size=3, + activation='lrelu', + up=up, + ) + self.up = up + + def forward(self, x, x_size, mask=None): + x = token2feature(x, x_size) + if mask is not None: + mask = token2feature(mask, x_size) + x, mask = self.conv(x, mask) + if self.up != 1: + x_size = (int(x_size[0] * self.up), int(x_size[1] * self.up)) + x = feature2token(x) + if mask is not None: + mask = feature2token(mask) + return x, x_size, mask + + +class BasicLayer(nn.Module): + """ A basic Swin Transformer layer for one stage. + Args: + dim (int): Number of input channels. + input_resolution (tuple[int]): Input resolution. + depth (int): Number of blocks. + num_heads (int): Number of attention heads. + window_size (int): Local window size. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True + qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set. + drop (float, optional): Dropout rate. Default: 0.0 + attn_drop (float, optional): Attention dropout rate. Default: 0.0 + drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0 + norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm + downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None + use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False. + """ + + def __init__(self, dim, input_resolution, depth, num_heads, window_size, down_ratio=1, + mlp_ratio=2., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., + drop_path=0., norm_layer=nn.LayerNorm, downsample=None, use_checkpoint=False): + + super().__init__() + self.dim = dim + self.input_resolution = input_resolution + self.depth = depth + self.use_checkpoint = use_checkpoint + + # patch merging layer + if downsample is not None: + # self.downsample = downsample(input_resolution, dim=dim, norm_layer=norm_layer) + self.downsample = downsample + else: + self.downsample = None + + # build blocks + self.blocks = nn.ModuleList([ + SwinTransformerBlock(dim=dim, input_resolution=input_resolution, + num_heads=num_heads, down_ratio=down_ratio, window_size=window_size, + shift_size=0 if (i % 2 == 0) else window_size // 2, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, qk_scale=qk_scale, + drop=drop, attn_drop=attn_drop, + drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path, + norm_layer=norm_layer) + for i in range(depth)]) + + self.conv = Conv2dLayerPartial(in_channels=dim, out_channels=dim, kernel_size=3, activation='lrelu') + + def forward(self, x, x_size, mask=None): + if self.downsample is not None: + x, x_size, mask = self.downsample(x, x_size, mask) + identity = x + for blk in self.blocks: + if self.use_checkpoint: + x, mask = checkpoint.checkpoint(blk, x, x_size, mask) + else: + x, mask = blk(x, x_size, mask) + if mask is not None: + mask = token2feature(mask, x_size) + x, mask = self.conv(token2feature(x, x_size), mask) + x = feature2token(x) + identity + if mask is not None: + mask = feature2token(mask) + return x, x_size, mask + + +class ToToken(nn.Module): + def __init__(self, in_channels=3, dim=128, kernel_size=5, stride=1): + super().__init__() + + self.proj = Conv2dLayerPartial(in_channels=in_channels, out_channels=dim, kernel_size=kernel_size, + activation='lrelu') + + def forward(self, x, mask): + x, mask = self.proj(x, mask) + + return x, mask + + +class EncFromRGB(nn.Module): + def __init__(self, in_channels, out_channels, activation): # res = 2, ..., resolution_log2 + super().__init__() + self.conv0 = Conv2dLayer(in_channels=in_channels, + out_channels=out_channels, + kernel_size=1, + activation=activation, + ) + self.conv1 = Conv2dLayer(in_channels=out_channels, + out_channels=out_channels, + kernel_size=3, + activation=activation, + ) + + def forward(self, x): + x = self.conv0(x) + x = self.conv1(x) + + return x + + +class ConvBlockDown(nn.Module): + def __init__(self, in_channels, out_channels, activation): # res = 2, ..., resolution_log + super().__init__() + + self.conv0 = Conv2dLayer(in_channels=in_channels, + out_channels=out_channels, + kernel_size=3, + activation=activation, + down=2, + ) + self.conv1 = Conv2dLayer(in_channels=out_channels, + out_channels=out_channels, + kernel_size=3, + activation=activation, + ) + + def forward(self, x): + x = self.conv0(x) + x = self.conv1(x) + + return x + + +def token2feature(x, x_size): + B, N, C = x.shape + h, w = x_size + x = x.permute(0, 2, 1).reshape(B, C, h, w) + return x + + +def feature2token(x): + B, C, H, W = x.shape + x = x.view(B, C, -1).transpose(1, 2) + return x + + +class Encoder(nn.Module): + def __init__(self, res_log2, img_channels, activation, patch_size=5, channels=16, drop_path_rate=0.1): + super().__init__() + + self.resolution = [] + + for idx, i in enumerate(range(res_log2, 3, -1)): # from input size to 16x16 + res = 2 ** i + self.resolution.append(res) + if i == res_log2: + block = EncFromRGB(img_channels * 2 + 1, nf(i), activation) + else: + block = ConvBlockDown(nf(i + 1), nf(i), activation) + setattr(self, 'EncConv_Block_%dx%d' % (res, res), block) + + def forward(self, x): + out = {} + for res in self.resolution: + res_log2 = int(np.log2(res)) + x = getattr(self, 'EncConv_Block_%dx%d' % (res, res))(x) + out[res_log2] = x + + return out + + +class ToStyle(nn.Module): + def __init__(self, in_channels, out_channels, activation, drop_rate): + super().__init__() + self.conv = nn.Sequential( + Conv2dLayer(in_channels=in_channels, out_channels=in_channels, kernel_size=3, activation=activation, + down=2), + Conv2dLayer(in_channels=in_channels, out_channels=in_channels, kernel_size=3, activation=activation, + down=2), + Conv2dLayer(in_channels=in_channels, out_channels=in_channels, kernel_size=3, activation=activation, + down=2), + ) + + self.pool = nn.AdaptiveAvgPool2d(1) + self.fc = FullyConnectedLayer(in_features=in_channels, + out_features=out_channels, + activation=activation) + # self.dropout = nn.Dropout(drop_rate) + + def forward(self, x): + x = self.conv(x) + x = self.pool(x) + x = self.fc(x.flatten(start_dim=1)) + # x = self.dropout(x) + + return x + + +class DecBlockFirstV2(nn.Module): + def __init__(self, res, in_channels, out_channels, activation, style_dim, use_noise, demodulate, img_channels): + super().__init__() + self.res = res + + self.conv0 = Conv2dLayer(in_channels=in_channels, + out_channels=in_channels, + kernel_size=3, + activation=activation, + ) + self.conv1 = StyleConv(in_channels=in_channels, + out_channels=out_channels, + style_dim=style_dim, + resolution=2 ** res, + kernel_size=3, + use_noise=use_noise, + activation=activation, + demodulate=demodulate, + ) + self.toRGB = ToRGB(in_channels=out_channels, + out_channels=img_channels, + style_dim=style_dim, + kernel_size=1, + demodulate=False, + ) + + def forward(self, x, ws, gs, E_features, noise_mode='random'): + # x = self.fc(x).view(x.shape[0], -1, 4, 4) + x = self.conv0(x) + x = x + E_features[self.res] + style = get_style_code(ws[:, 0], gs) + x = self.conv1(x, style, noise_mode=noise_mode) + style = get_style_code(ws[:, 1], gs) + img = self.toRGB(x, style, skip=None) + + return x, img + + +class DecBlock(nn.Module): + def __init__(self, res, in_channels, out_channels, activation, style_dim, use_noise, demodulate, + img_channels): # res = 4, ..., resolution_log2 + super().__init__() + self.res = res + + self.conv0 = StyleConv(in_channels=in_channels, + out_channels=out_channels, + style_dim=style_dim, + resolution=2 ** res, + kernel_size=3, + up=2, + use_noise=use_noise, + activation=activation, + demodulate=demodulate, + ) + self.conv1 = StyleConv(in_channels=out_channels, + out_channels=out_channels, + style_dim=style_dim, + resolution=2 ** res, + kernel_size=3, + use_noise=use_noise, + activation=activation, + demodulate=demodulate, + ) + self.toRGB = ToRGB(in_channels=out_channels, + out_channels=img_channels, + style_dim=style_dim, + kernel_size=1, + demodulate=False, + ) + + def forward(self, x, img, ws, gs, E_features, noise_mode='random'): + style = get_style_code(ws[:, self.res * 2 - 9], gs) + x = self.conv0(x, style, noise_mode=noise_mode) + x = x + E_features[self.res] + style = get_style_code(ws[:, self.res * 2 - 8], gs) + x = self.conv1(x, style, noise_mode=noise_mode) + style = get_style_code(ws[:, self.res * 2 - 7], gs) + img = self.toRGB(x, style, skip=img) + + return x, img + + +class Decoder(nn.Module): + def __init__(self, res_log2, activation, style_dim, use_noise, demodulate, img_channels): + super().__init__() + self.Dec_16x16 = DecBlockFirstV2(4, nf(4), nf(4), activation, style_dim, use_noise, demodulate, img_channels) + for res in range(5, res_log2 + 1): + setattr(self, 'Dec_%dx%d' % (2 ** res, 2 ** res), + DecBlock(res, nf(res - 1), nf(res), activation, style_dim, use_noise, demodulate, img_channels)) + self.res_log2 = res_log2 + + def forward(self, x, ws, gs, E_features, noise_mode='random'): + x, img = self.Dec_16x16(x, ws, gs, E_features, noise_mode=noise_mode) + for res in range(5, self.res_log2 + 1): + block = getattr(self, 'Dec_%dx%d' % (2 ** res, 2 ** res)) + x, img = block(x, img, ws, gs, E_features, noise_mode=noise_mode) + + return img + + +class DecStyleBlock(nn.Module): + def __init__(self, res, in_channels, out_channels, activation, style_dim, use_noise, demodulate, img_channels): + super().__init__() + self.res = res + + self.conv0 = StyleConv(in_channels=in_channels, + out_channels=out_channels, + style_dim=style_dim, + resolution=2 ** res, + kernel_size=3, + up=2, + use_noise=use_noise, + activation=activation, + demodulate=demodulate, + ) + self.conv1 = StyleConv(in_channels=out_channels, + out_channels=out_channels, + style_dim=style_dim, + resolution=2 ** res, + kernel_size=3, + use_noise=use_noise, + activation=activation, + demodulate=demodulate, + ) + self.toRGB = ToRGB(in_channels=out_channels, + out_channels=img_channels, + style_dim=style_dim, + kernel_size=1, + demodulate=False, + ) + + def forward(self, x, img, style, skip, noise_mode='random'): + x = self.conv0(x, style, noise_mode=noise_mode) + x = x + skip + x = self.conv1(x, style, noise_mode=noise_mode) + img = self.toRGB(x, style, skip=img) + + return x, img + + +class FirstStage(nn.Module): + def __init__(self, img_channels, img_resolution=256, dim=180, w_dim=512, use_noise=False, demodulate=True, + activation='lrelu'): + super().__init__() + res = 64 + + self.conv_first = Conv2dLayerPartial(in_channels=img_channels + 1, out_channels=dim, kernel_size=3, + activation=activation) + self.enc_conv = nn.ModuleList() + down_time = int(np.log2(img_resolution // res)) + # 根据图片尺寸构建 swim transformer 的层数 + for i in range(down_time): # from input size to 64 + self.enc_conv.append( + Conv2dLayerPartial(in_channels=dim, out_channels=dim, kernel_size=3, down=2, activation=activation) + ) + + # from 64 -> 16 -> 64 + depths = [2, 3, 4, 3, 2] + ratios = [1, 1 / 2, 1 / 2, 2, 2] + num_heads = 6 + window_sizes = [8, 16, 16, 16, 8] + drop_path_rate = 0.1 + dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] + + self.tran = nn.ModuleList() + for i, depth in enumerate(depths): + res = int(res * ratios[i]) + if ratios[i] < 1: + merge = PatchMerging(dim, dim, down=int(1 / ratios[i])) + elif ratios[i] > 1: + merge = PatchUpsampling(dim, dim, up=ratios[i]) + else: + merge = None + self.tran.append( + BasicLayer(dim=dim, input_resolution=[res, res], depth=depth, num_heads=num_heads, + window_size=window_sizes[i], drop_path=dpr[sum(depths[:i]):sum(depths[:i + 1])], + downsample=merge) + ) + + # global style + down_conv = [] + for i in range(int(np.log2(16))): + down_conv.append( + Conv2dLayer(in_channels=dim, out_channels=dim, kernel_size=3, down=2, activation=activation)) + down_conv.append(nn.AdaptiveAvgPool2d((1, 1))) + self.down_conv = nn.Sequential(*down_conv) + self.to_style = FullyConnectedLayer(in_features=dim, out_features=dim * 2, activation=activation) + self.ws_style = FullyConnectedLayer(in_features=w_dim, out_features=dim, activation=activation) + self.to_square = FullyConnectedLayer(in_features=dim, out_features=16 * 16, activation=activation) + + style_dim = dim * 3 + self.dec_conv = nn.ModuleList() + for i in range(down_time): # from 64 to input size + res = res * 2 + self.dec_conv.append( + DecStyleBlock(res, dim, dim, activation, style_dim, use_noise, demodulate, img_channels)) + + def forward(self, images_in, masks_in, ws, noise_mode='random'): + x = torch.cat([masks_in - 0.5, images_in * masks_in], dim=1) + + skips = [] + x, mask = self.conv_first(x, masks_in) # input size + skips.append(x) + for i, block in enumerate(self.enc_conv): # input size to 64 + x, mask = block(x, mask) + if i != len(self.enc_conv) - 1: + skips.append(x) + + x_size = x.size()[-2:] + x = feature2token(x) + mask = feature2token(mask) + mid = len(self.tran) // 2 + for i, block in enumerate(self.tran): # 64 to 16 + if i < mid: + x, x_size, mask = block(x, x_size, mask) + skips.append(x) + elif i > mid: + x, x_size, mask = block(x, x_size, None) + x = x + skips[mid - i] + else: + x, x_size, mask = block(x, x_size, None) + + mul_map = torch.ones_like(x) * 0.5 + mul_map = F.dropout(mul_map, training=True) + ws = self.ws_style(ws[:, -1]) + add_n = self.to_square(ws).unsqueeze(1) + add_n = F.interpolate(add_n, size=x.size(1), mode='linear', align_corners=False).squeeze(1).unsqueeze( + -1) + x = x * mul_map + add_n * (1 - mul_map) + gs = self.to_style(self.down_conv(token2feature(x, x_size)).flatten(start_dim=1)) + style = torch.cat([gs, ws], dim=1) + + x = token2feature(x, x_size).contiguous() + img = None + for i, block in enumerate(self.dec_conv): + x, img = block(x, img, style, skips[len(self.dec_conv) - i - 1], noise_mode=noise_mode) + + # ensemble + img = img * (1 - masks_in) + images_in * masks_in + + return img + + +class SynthesisNet(nn.Module): + def __init__(self, + w_dim, # Intermediate latent (W) dimensionality. + img_resolution, # Output image resolution. + img_channels=3, # Number of color channels. + channel_base=32768, # Overall multiplier for the number of channels. + channel_decay=1.0, + channel_max=512, # Maximum number of channels in any layer. + activation='lrelu', # Activation function: 'relu', 'lrelu', etc. + drop_rate=0.5, + use_noise=False, + demodulate=True, + ): + super().__init__() + resolution_log2 = int(np.log2(img_resolution)) + assert img_resolution == 2 ** resolution_log2 and img_resolution >= 4 + + self.num_layers = resolution_log2 * 2 - 3 * 2 + self.img_resolution = img_resolution + self.resolution_log2 = resolution_log2 + + # first stage + self.first_stage = FirstStage(img_channels, img_resolution=img_resolution, w_dim=w_dim, use_noise=False, + demodulate=demodulate) + + # second stage + self.enc = Encoder(resolution_log2, img_channels, activation, patch_size=5, channels=16) + self.to_square = FullyConnectedLayer(in_features=w_dim, out_features=16 * 16, activation=activation) + self.to_style = ToStyle(in_channels=nf(4), out_channels=nf(2) * 2, activation=activation, drop_rate=drop_rate) + style_dim = w_dim + nf(2) * 2 + self.dec = Decoder(resolution_log2, activation, style_dim, use_noise, demodulate, img_channels) + + def forward(self, images_in, masks_in, ws, noise_mode='random', return_stg1=False): + out_stg1 = self.first_stage(images_in, masks_in, ws, noise_mode=noise_mode) + + # encoder + x = images_in * masks_in + out_stg1 * (1 - masks_in) + x = torch.cat([masks_in - 0.5, x, images_in * masks_in], dim=1) + E_features = self.enc(x) + + fea_16 = E_features[4] + mul_map = torch.ones_like(fea_16) * 0.5 + mul_map = F.dropout(mul_map, training=True) + add_n = self.to_square(ws[:, 0]).view(-1, 16, 16).unsqueeze(1) + add_n = F.interpolate(add_n, size=fea_16.size()[-2:], mode='bilinear', align_corners=False) + fea_16 = fea_16 * mul_map + add_n * (1 - mul_map) + E_features[4] = fea_16 + + # style + gs = self.to_style(fea_16) + + # decoder + img = self.dec(fea_16, ws, gs, E_features, noise_mode=noise_mode) + + # ensemble + img = img * (1 - masks_in) + images_in * masks_in + + if not return_stg1: + return img + else: + return img, out_stg1 + + +class Generator(nn.Module): + def __init__(self, + z_dim, # Input latent (Z) dimensionality, 0 = no latent. + c_dim, # Conditioning label (C) dimensionality, 0 = no label. + w_dim, # Intermediate latent (W) dimensionality. + img_resolution, # resolution of generated image + img_channels, # Number of input color channels. + synthesis_kwargs={}, # Arguments for SynthesisNetwork. + mapping_kwargs={}, # Arguments for MappingNetwork. + ): + super().__init__() + self.z_dim = z_dim + self.c_dim = c_dim + self.w_dim = w_dim + self.img_resolution = img_resolution + self.img_channels = img_channels + + self.synthesis = SynthesisNet(w_dim=w_dim, + img_resolution=img_resolution, + img_channels=img_channels, + **synthesis_kwargs) + self.mapping = MappingNet(z_dim=z_dim, + c_dim=c_dim, + w_dim=w_dim, + num_ws=self.synthesis.num_layers, + **mapping_kwargs) + + def forward(self, images_in, masks_in, z, c, truncation_psi=1, truncation_cutoff=None, skip_w_avg_update=False, + noise_mode='none', return_stg1=False): + ws = self.mapping(z, c, truncation_psi=truncation_psi, truncation_cutoff=truncation_cutoff, + skip_w_avg_update=skip_w_avg_update) + img = self.synthesis(images_in, masks_in, ws, noise_mode=noise_mode) + return img + + +class Discriminator(torch.nn.Module): + def __init__(self, + c_dim, # Conditioning label (C) dimensionality. + img_resolution, # Input resolution. + img_channels, # Number of input color channels. + channel_base=32768, # Overall multiplier for the number of channels. + channel_max=512, # Maximum number of channels in any layer. + channel_decay=1, + cmap_dim=None, # Dimensionality of mapped conditioning label, None = default. + activation='lrelu', + mbstd_group_size=4, # Group size for the minibatch standard deviation layer, None = entire minibatch. + mbstd_num_channels=1, # Number of features for the minibatch standard deviation layer, 0 = disable. + ): + super().__init__() + self.c_dim = c_dim + self.img_resolution = img_resolution + self.img_channels = img_channels + + resolution_log2 = int(np.log2(img_resolution)) + assert img_resolution == 2 ** resolution_log2 and img_resolution >= 4 + self.resolution_log2 = resolution_log2 + + if cmap_dim == None: + cmap_dim = nf(2) + if c_dim == 0: + cmap_dim = 0 + self.cmap_dim = cmap_dim + + if c_dim > 0: + self.mapping = MappingNet(z_dim=0, c_dim=c_dim, w_dim=cmap_dim, num_ws=None, w_avg_beta=None) + + Dis = [DisFromRGB(img_channels + 1, nf(resolution_log2), activation)] + for res in range(resolution_log2, 2, -1): + Dis.append(DisBlock(nf(res), nf(res - 1), activation)) + + if mbstd_num_channels > 0: + Dis.append(MinibatchStdLayer(group_size=mbstd_group_size, num_channels=mbstd_num_channels)) + Dis.append(Conv2dLayer(nf(2) + mbstd_num_channels, nf(2), kernel_size=3, activation=activation)) + self.Dis = nn.Sequential(*Dis) + + self.fc0 = FullyConnectedLayer(nf(2) * 4 ** 2, nf(2), activation=activation) + self.fc1 = FullyConnectedLayer(nf(2), 1 if cmap_dim == 0 else cmap_dim) + + # for 64x64 + Dis_stg1 = [DisFromRGB(img_channels + 1, nf(resolution_log2) // 2, activation)] + for res in range(resolution_log2, 2, -1): + Dis_stg1.append(DisBlock(nf(res) // 2, nf(res - 1) // 2, activation)) + + if mbstd_num_channels > 0: + Dis_stg1.append(MinibatchStdLayer(group_size=mbstd_group_size, num_channels=mbstd_num_channels)) + Dis_stg1.append(Conv2dLayer(nf(2) // 2 + mbstd_num_channels, nf(2) // 2, kernel_size=3, activation=activation)) + self.Dis_stg1 = nn.Sequential(*Dis_stg1) + + self.fc0_stg1 = FullyConnectedLayer(nf(2) // 2 * 4 ** 2, nf(2) // 2, activation=activation) + self.fc1_stg1 = FullyConnectedLayer(nf(2) // 2, 1 if cmap_dim == 0 else cmap_dim) + + def forward(self, images_in, masks_in, images_stg1, c): + x = self.Dis(torch.cat([masks_in - 0.5, images_in], dim=1)) + x = self.fc1(self.fc0(x.flatten(start_dim=1))) + + x_stg1 = self.Dis_stg1(torch.cat([masks_in - 0.5, images_stg1], dim=1)) + x_stg1 = self.fc1_stg1(self.fc0_stg1(x_stg1.flatten(start_dim=1))) + + if self.c_dim > 0: + cmap = self.mapping(None, c) + + if self.cmap_dim > 0: + x = (x * cmap).sum(dim=1, keepdim=True) * (1 / np.sqrt(self.cmap_dim)) + x_stg1 = (x_stg1 * cmap).sum(dim=1, keepdim=True) * (1 / np.sqrt(self.cmap_dim)) + + return x, x_stg1 + + +MAT_MODEL_URL = os.environ.get( + "MAT_MODEL_URL", + "https://github.com/Sanster/models/releases/download/add_mat/Places_512_FullData_G.pth", +) + + +class MAT(InpaintModel): + min_size = 512 + pad_mod = 512 + pad_to_square = True + + def init_model(self, device): + seed = 240 # pick up a random number + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + + G = Generator(z_dim=512, c_dim=0, w_dim=512, img_resolution=512, img_channels=3) + self.model = load_model(G, MAT_MODEL_URL, device) + self.z = torch.from_numpy(np.random.randn(1, G.z_dim)).to(device) # [1., 512] + self.label = torch.zeros([1, self.model.c_dim], device=device) + + @staticmethod + def is_downloaded() -> bool: + return os.path.exists(get_cache_path_by_url(MAT_MODEL_URL)) + + def forward(self, image, mask, config: Config): + """Input images and output images have same size + images: [H, W, C] RGB + masks: [H, W] mask area == 255 + return: BGR IMAGE + """ + + image = norm_img(image) # [0, 1] + image = image * 2 - 1 # [0, 1] -> [-1, 1] + + mask = (mask > 127) * 255 + mask = 255 - mask + mask = norm_img(mask) + + image = torch.from_numpy(image).unsqueeze(0).to(self.device) + mask = torch.from_numpy(mask).unsqueeze(0).to(self.device) + + output = self.model(image, mask, self.z, self.label, truncation_psi=1, noise_mode='none') + output = (output.permute(0, 2, 3, 1) * 127.5 + 127.5).round().clamp(0, 255).to(torch.uint8) + output = output[0].cpu().numpy() + cur_res = cv2.cvtColor(output, cv2.COLOR_RGB2BGR) + return cur_res diff --git a/lama_cleaner/model_manager.py b/lama_cleaner/model_manager.py index 108c727..0b4152f 100644 --- a/lama_cleaner/model_manager.py +++ b/lama_cleaner/model_manager.py @@ -1,12 +1,14 @@ from lama_cleaner.model.lama import LaMa from lama_cleaner.model.ldm import LDM +from lama_cleaner.model.mat import MAT from lama_cleaner.model.zits import ZITS from lama_cleaner.schema import Config models = { 'lama': LaMa, 'ldm': LDM, - 'zits': ZITS + 'zits': ZITS, + 'mat': MAT } diff --git a/lama_cleaner/parse_args.py b/lama_cleaner/parse_args.py index 1813bd2..4cad49d 100644 --- a/lama_cleaner/parse_args.py +++ b/lama_cleaner/parse_args.py @@ -7,7 +7,7 @@ def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("--host", default="127.0.0.1") parser.add_argument("--port", default=8080, type=int) - parser.add_argument("--model", default="lama", choices=["lama", "ldm", "zits"]) + parser.add_argument("--model", default="lama", choices=["lama", "ldm", "zits", "mat"]) parser.add_argument("--device", default="cuda", type=str, choices=["cuda", "cpu"]) parser.add_argument("--gui", action="store_true", help="Launch as desktop app") parser.add_argument( diff --git a/lama_cleaner/tests/test_model.py b/lama_cleaner/tests/test_model.py index bfccac8..e3205c3 100644 --- a/lama_cleaner/tests/test_model.py +++ b/lama_cleaner/tests/test_model.py @@ -11,13 +11,19 @@ from lama_cleaner.schema import Config, HDStrategy, LDMSampler current_dir = Path(__file__).parent.absolute().resolve() -def get_data(fx=1): +def get_data(fx=1, fy=1.0): img = cv2.imread(str(current_dir / "image.png")) img = cv2.cvtColor(img, cv2.COLOR_BGRA2RGB) mask = cv2.imread(str(current_dir / "mask.png"), cv2.IMREAD_GRAYSCALE) + + # img = cv2.imread("/Users/qing/code/github/MAT/test_sets/Places/images/test1.jpg") + # img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) + # mask = cv2.imread("/Users/qing/code/github/MAT/test_sets/Places/masks/mask1.png", cv2.IMREAD_GRAYSCALE) + # mask = 255 - mask + if fx != 1: - img = cv2.resize(img, None, fx=fx, fy=1) - mask = cv2.resize(mask, None, fx=fx, fy=1) + img = cv2.resize(img, None, fx=fx, fy=fy) + mask = cv2.resize(mask, None, fx=fx, fy=fy) return img, mask @@ -34,8 +40,8 @@ def get_config(strategy, **kwargs): return Config(**data) -def assert_equal(model, config, gt_name, fx=1): - img, mask = get_data(fx=fx) +def assert_equal(model, config, gt_name, fx=1, fy=1): + img, mask = get_data(fx=fx, fy=fy) res = model(img, mask, config) cv2.imwrite( str(current_dir / gt_name), @@ -111,6 +117,20 @@ def test_zits(strategy, zits_wireframe): assert_equal( model, cfg, - f"zits_{strategy[0].upper() + strategy[1:]}_wireframe_{zits_wireframe}_fx_{fx}_result.png", + f"zits_{strategy.capitalize()}_wireframe_{zits_wireframe}_fx_{fx}_result.png", fx=fx, ) + + +@pytest.mark.parametrize( + "strategy", [HDStrategy.ORIGINAL] +) +def test_mat(strategy): + model = ModelManager(name="mat", device="cpu") + cfg = get_config(strategy) + + assert_equal( + model, + cfg, + f"mat_{strategy.capitalize()}_result.png", + ) From 80366ebb5538631d3a77c741d789a51dcac4af03 Mon Sep 17 00:00:00 2001 From: Qing Date: Wed, 24 Aug 2022 21:30:45 +0800 Subject: [PATCH 3/3] 0.16.0 --- lama_cleaner/app/build/asset-manifest.json | 10 +++++----- lama_cleaner/app/build/index.html | 2 +- lama_cleaner/app/build/static/js/2.3a92b865.chunk.js | 2 -- lama_cleaner/app/build/static/js/2.cf2e9421.chunk.js | 2 ++ ....js.LICENSE.txt => 2.cf2e9421.chunk.js.LICENSE.txt} | 0 .../app/build/static/js/main.4e53814e.chunk.js | 1 + .../app/build/static/js/main.5fe518c4.chunk.js | 1 - setup.py | 2 +- 8 files changed, 10 insertions(+), 10 deletions(-) delete mode 100644 lama_cleaner/app/build/static/js/2.3a92b865.chunk.js create mode 100644 lama_cleaner/app/build/static/js/2.cf2e9421.chunk.js rename lama_cleaner/app/build/static/js/{2.3a92b865.chunk.js.LICENSE.txt => 2.cf2e9421.chunk.js.LICENSE.txt} (100%) create mode 100644 lama_cleaner/app/build/static/js/main.4e53814e.chunk.js delete mode 100644 lama_cleaner/app/build/static/js/main.5fe518c4.chunk.js diff --git a/lama_cleaner/app/build/asset-manifest.json b/lama_cleaner/app/build/asset-manifest.json index 2712a04..79975a8 100644 --- a/lama_cleaner/app/build/asset-manifest.json +++ b/lama_cleaner/app/build/asset-manifest.json @@ -1,17 +1,17 @@ { "files": { "main.css": "/static/css/main.eb627daf.chunk.css", - "main.js": "/static/js/main.5fe518c4.chunk.js", + "main.js": "/static/js/main.4e53814e.chunk.js", "runtime-main.js": "/static/js/runtime-main.5e86ac81.js", - "static/js/2.3a92b865.chunk.js": "/static/js/2.3a92b865.chunk.js", + "static/js/2.cf2e9421.chunk.js": "/static/js/2.cf2e9421.chunk.js", "index.html": "/index.html", - "static/js/2.3a92b865.chunk.js.LICENSE.txt": "/static/js/2.3a92b865.chunk.js.LICENSE.txt", + "static/js/2.cf2e9421.chunk.js.LICENSE.txt": "/static/js/2.cf2e9421.chunk.js.LICENSE.txt", "static/media/_index.scss": "/static/media/WorkSans-SemiBold.1e98db4e.ttf" }, "entrypoints": [ "static/js/runtime-main.5e86ac81.js", - "static/js/2.3a92b865.chunk.js", + "static/js/2.cf2e9421.chunk.js", "static/css/main.eb627daf.chunk.css", - "static/js/main.5fe518c4.chunk.js" + "static/js/main.4e53814e.chunk.js" ] } \ No newline at end of file diff --git a/lama_cleaner/app/build/index.html b/lama_cleaner/app/build/index.html index 5240ba6..342dbf6 100644 --- a/lama_cleaner/app/build/index.html +++ b/lama_cleaner/app/build/index.html @@ -1 +1 @@ -lama-cleaner - Image inpainting powered by LaMa
\ No newline at end of file +lama-cleaner - Image inpainting powered by LaMa
\ No newline at end of file diff --git a/lama_cleaner/app/build/static/js/2.3a92b865.chunk.js b/lama_cleaner/app/build/static/js/2.3a92b865.chunk.js deleted file mode 100644 index 58e99b7..0000000 --- a/lama_cleaner/app/build/static/js/2.3a92b865.chunk.js +++ /dev/null @@ -1,2 +0,0 @@ -/*! For license information please see 2.3a92b865.chunk.js.LICENSE.txt */ -(this["webpackJsonplama-cleaner"]=this["webpackJsonplama-cleaner"]||[]).push([[2],[function(e,t,n){"use strict";e.exports=n(53)},function(e,t,n){"use strict";e.exports=n(61)},function(e,t,n){"use strict";n.d(t,"a",(function(){return i}));var r=n(33);var o=n(24),a=n(35);function i(e,t){return Object(r.a)(e)||function(e,t){if("undefined"!==typeof Symbol&&Symbol.iterator in Object(e)){var n=[],r=!0,o=!1,a=void 0;try{for(var i,u=e[Symbol.iterator]();!(r=(i=u.next()).done)&&(n.push(i.value),!t||n.length!==t);r=!0);}catch(c){o=!0,a=c}finally{try{r||null==u.return||u.return()}finally{if(o)throw a}}return n}}(e,t)||Object(o.a)(e,t)||Object(a.a)()}},function(e,t,n){"use strict";n.d(t,"a",(function(){return a}));var r=n(10);function o(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function a(e){for(var t=1;t=0||(o[n]=e[n]);return o}(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(o[n]=e[n])}return o}n.d(t,"a",(function(){return r}))},function(e,t,n){"use strict";function r(){return r=Object.assign||function(e){for(var t=1;t=e.length?{done:!0}:{done:!1,value:e[o++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,u=!0,c=!1;return{s:function(){n=e[Symbol.iterator]()},n:function(){var e=n.next();return u=e.done,e},e:function(e){c=!0,i=e},f:function(){try{u||null==n.return||n.return()}finally{if(c)throw i}}}}},function(e,t,n){"use strict";n.d(t,"a",(function(){return i}));var r=n(29);var o=n(34),a=n(24);function i(e){return function(e){if(Array.isArray(e))return Object(r.a)(e)}(e)||Object(o.a)(e)||Object(a.a)(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}},function(e,t,n){"use strict";function r(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=n.checkForDefaultPrevented,o=void 0===r||r;return function(n){if(null==e||e(n),!1===o||!n.defaultPrevented)return null==t?void 0:t(n)}}n.d(t,"a",(function(){return r}))},function(e,t,n){"use strict";n.d(t,"a",(function(){return Pu})),n.d(t,"b",(function(){return Au})),n.d(t,"c",(function(){return Lu})),n.d(t,"d",(function(){return Mu})),n.d(t,"e",(function(){return Nu})),n.d(t,"f",(function(){return Du}));var r=n(28),o=n(7),a=n(4),i=n(15),u=n(2);function c(e){return c=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},c(e)}function l(e,t){return l=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},l(e,t)}function s(){if("undefined"===typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"===typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(e){return!1}}function f(e,t,n){return f=s()?Reflect.construct:function(e,t,n){var r=[null];r.push.apply(r,t);var o=new(Function.bind.apply(e,r));return n&&l(o,n.prototype),o},f.apply(null,arguments)}function d(e){var t="function"===typeof Map?new Map:void 0;return d=function(e){if(null===e||(n=e,-1===Function.toString.call(n).indexOf("[native code]")))return e;var n;if("function"!==typeof e)throw new TypeError("Super expression must either be null or a function");if("undefined"!==typeof t){if(t.has(e))return t.get(e);t.set(e,r)}function r(){return f(e,arguments,c(this).constructor)}return r.prototype=Object.create(e.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),l(r,e)},d(e)}var p=n(11),v=n.n(p),h=n(6),m=n(10),b=n(3);function y(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function g(e,t){if("function"!==typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&l(e,t)}function w(e){return w="function"===typeof Symbol&&"symbol"===typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"===typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},w(e)}function _(e,t){return!t||"object"!==w(t)&&"function"!==typeof t?y(e):t}function O(e){var t=s();return function(){var n,r=c(e);if(t){var o=c(this).constructor;n=Reflect.construct(r,arguments,o)}else n=r.apply(this,arguments);return _(this,n)}}function S(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function E(e,t){for(var n=0;n2&&void 0!==arguments[2]?arguments[2]:{};return n.error,null},ge=ye,we=function e(){S(this,e)},_e=new we,Oe=function(e){g(n,e);var t=O(n);function n(e){return S(this,n),t.call(this,"Tried to set the value of Recoil selector ".concat(e," using an updater function, but it is an async selector in a pending or error state; this is not supported."))}return n}(d(Error)),Se=new Map,Ee=new Map;var je=function(e){g(n,e);var t=O(n);function n(){return S(this,n),t.apply(this,arguments)}return n}(d(Error));var ke=new Map;function Ce(e){return ke.get(e)}var xe={nodes:Se,recoilValues:Ee,registerNode:function(e){if(Se.has(e.key)){var t='Duplicate atom key "'.concat(e.key,'". This is a FATAL ERROR in\n production. But it is safe to ignore this warning if it occurred because of\n hot module replacement.');console.warn(t)}Se.set(e.key,e);var n=null==e.set?new de.RecoilValueReadOnly(e.key):new de.RecoilState(e.key);return Ee.set(e.key,n),n},getNode:function(e){var t=Se.get(e);if(null==t)throw new je('Missing definition for RecoilValue: "'.concat(e,'""'));return t},getNodeMaybe:function(e){return Se.get(e)},deleteNodeConfigIfPossible:function(e){var t;if(me("recoil_memory_managament_2020")){var n,r=Se.get(e);if(null!==r&&void 0!==r&&null!==(t=r.shouldDeleteConfigOnRelease)&&void 0!==t&&t.call(r))Se.delete(e),null===(n=Ce(e))||void 0===n||n(),ke.delete(e)}},setConfigDeletionHandler:function(e,t){me("recoil_memory_managament_2020")&&(void 0===t?ke.delete(e):ke.set(e,t))},getConfigDeletionHandler:Ce,recoilValuesForKeys:function(e){return be(e,(function(e){return I(Ee.get(e))}))},NodeMissingError:je,DefaultValue:we,DEFAULT_VALUE:_e,RecoilValueNotReady:Oe};var Te={enqueueExecution:function(e,t){t()}};var Re=function(e,t){return e(t={exports:{}},t.exports),t.exports}((function(e){var t="function"===typeof Symbol&&"symbol"===typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"===typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n={},r=Math.pow(2,5),o=r-1,a=r/2,i=r/4,u={},c=function(e){return function(){return e}},l=n.hash=function(e){var n="undefined"===typeof e?"undefined":t(e);if("number"===n)return e;"string"!==n&&(e+="");for(var r=0,o=0,a=e.length;o>>e&o},f=function(e){return 1<>1&1431655765))+(n>>2&858993459))+(n>>4)&252645135,127&(n+=n>>8)+(n>>16);var n},p=function(e,t,n,r){var o=r;if(!e){var a=r.length;o=new Array(a);for(var i=0;i1?y(e,this.hash,c):c[0]}var l=r();return l===u?this:(++i.value,_(e,n,this.hash,this,o,b(e,o,a,l)))},j=function(e,t,n,r,o,i,u){var c=this.mask,l=this.children,b=s(n,o),y=f(b),_=d(c,y),S=c&y,E=S?l[_]:h,j=E._modify(e,t,n+5,r,o,i,u);if(E===j)return this;var k,C=O(e,this),x=c,T=void 0;if(S&&m(j)){if(!(x&=~y))return h;if(l.length<=2&&((k=l[1^_])===h||1===k.type||2===k.type))return l[1^_];T=v(C,_,l)}else if(S||m(j))T=p(C,_,j,l);else{if(l.length>=a)return function(e,t,n,r,o){for(var a=[],i=r,u=0,c=0;i;++c)1&i&&(a[c]=o[u++]),i>>>=1;return a[t]=n,w(e,u+1,a)}(e,b,j,c,l);x|=y,T=function(e,t,n,r){var o=r.length;if(e){for(var a=o;a>=t;)r[a--]=r[a];return r[t]=n,r}for(var i=0,u=0,c=new Array(o+1);i1?n-1:0),o=1;o2&&void 0!==arguments[2]?arguments[2]:e.getState().currentTree,i=e.getState();a.version!==i.currentTree.version&&a.version!==(null===(n=i.nextTree)||void 0===n?void 0:n.version)&&a.version!==(null===(r=i.previousTree)||void 0===r?void 0:r.version)&&ge("Tried to read from a discarded tree");var u=Pt(e,a,o);return"loading"===u.state&&u.contents.catch((function(){})),u},setRecoilValue:Qt,setRecoilValueLoadable:function(e,t,n){if(n instanceof Dt)return Qt(e,t,n);Kt(e,{type:"setLoadable",recoilValue:t,loadable:n})},markRecoilValueModified:function(e,t){Kt(e,{type:"markModified",recoilValue:t})},setUnvalidatedRecoilValue:function(e,t,n){Kt(e,{type:"setUnvalidated",recoilValue:t,unvalidatedValue:n})},subscribeToRecoilValue:function(e,t,n){var r=t.key,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,a=Lt(),i=e.getState();i.nodeToComponentSubscriptions.has(r)||i.nodeToComponentSubscriptions.set(r,new Map),I(i.nodeToComponentSubscriptions.get(r)).set(a,[null!==o&&void 0!==o?o:"",n]);var u=zt();if(u.early&&("LEGACY"===u.mode||"MUTABLE_SOURCE"===u.mode)){var c=e.getState().nextTree;c&&c.dirtyAtoms.has(r)&&n(c)}return{release:function(){var t=e.getState(),n=t.nodeToComponentSubscriptions.get(r);void 0!==n&&n.has(a)?(n.delete(a),0===n.size&&t.nodeToComponentSubscriptions.delete(r)):ge("Subscription missing at release time for atom ".concat(r,". This is a bug in Recoil."))}}},isRecoilValue:Bt,applyAtomValueWrites:function(e,t){var n=e.clone();return t.forEach((function(e,t){"hasValue"===e.state&&e.contents instanceof Dt?n.delete(t):n.set(t,e)})),n},batchStart:function(){var e=new Map;return qt.push(e),function(){var t,n=Object(h.a)(e);try{for(n.s();!(t=n.n()).done;){var r=Object(u.a)(t.value,2);Yt(r[0],r[1])}}catch(o){n.e(o)}finally{n.f()}qt.pop()!==e&&ge("Incorrect order of batch popping")}},writeLoadableToTreeState:Ht,invalidateDownstreams:$t,copyTreeState:Xt,refreshRecoilValue:function(e,t){var n,r=e.getState().currentTree,o=Nt(t.key);null===(n=o.clearCache)||void 0===n||n.call(o,e,r)},invalidateDownstreams_FOR_TESTING:$t};var Zt=function(e,t,n){for(var r=e.entries(),o=r.next();!o.done;){var a=o.value;if(t.call(n,a[1],a[0],e))return!0;o=r.next()}return!1},Jt=Ot,en=xe.deleteNodeConfigIfPossible,tn=xe.getNode,nn=Je,rn=new Set;function on(e,t){var n=e.getState(),r=n.currentTree;if(n.nextTree)ge("releaseNodesNowOnCurrentTree should only be called at the end of a batch");else{var o,a=new Set,i=Object(h.a)(t);try{for(i.s();!(o=i.n()).done;){var u=o.value;if(u instanceof nn){var c,l=Object(h.a)(un(n,u));try{for(l.s();!(c=l.n()).done;){var s=c.value;a.add(s)}}catch(v){l.e(v)}finally{l.f()}}else a.add(u)}}catch(v){i.e(v)}finally{i.f()}var f,d=function(e,t){var n=e.getState(),r=n.currentTree,o=e.getGraph(r.version),a=new Set,i=new Set;return u(t),a;function u(t){var c,l=new Set,s=function(e,t,n,r,o){var a=e.getGraph(t.version),i=[],u=new Set;for(;n.size>0;)c(I(n.values().next().value));return i;function c(e){if(r.has(e)||o.has(e))n.delete(e);else if(!u.has(e)){var t=a.nodeToNodeSubscriptions.get(e);if(t){var l,s=Object(h.a)(t);try{for(s.s();!(l=s.n()).done;){c(l.value)}}catch(v){s.e(v)}finally{s.f()}}u.add(e),n.delete(e),i.push(e)}}}(e,r,t,a,i),f=Object(h.a)(s);try{for(f.s();!(c=f.n()).done;){var d,p=c.value;if("recoilRoot"!==tn(p).retainedBy)if((null!==(d=n.retention.referenceCounts.get(p))&&void 0!==d?d:0)>0)i.add(p);else if(cn(p).some((function(e){return n.retention.referenceCounts.get(e)})))i.add(p);else{var m=o.nodeToNodeSubscriptions.get(p);m&&Zt(m,(function(e){return i.has(e)}))?i.add(p):(a.add(p),l.add(p))}else i.add(p)}}catch(v){f.e(v)}finally{f.f()}var b,y=new Set,g=Object(h.a)(l);try{for(g.s();!(b=g.n()).done;){var w,_=b.value,O=Object(h.a)(null!==(S=o.nodeDeps.get(_))&&void 0!==S?S:rn);try{for(O.s();!(w=O.n()).done;){var S,E=w.value;a.has(E)||y.add(E)}}catch(v){O.e(v)}finally{O.f()}}}catch(v){g.e(v)}finally{g.f()}y.size&&u(y)}}(e,a),p=Object(h.a)(d);try{for(p.s();!(f=p.n()).done;){an(e,r,f.value)}}catch(v){p.e(v)}finally{p.f()}}}function an(e,t,n){if(me("recoil_memory_managament_2020")){Jt(e,n);var r=e.getState();r.knownAtoms.delete(n),r.knownSelectors.delete(n),r.nodeTransactionSubscriptions.delete(n),r.retention.referenceCounts.delete(n);var o,a=cn(n),i=Object(h.a)(a);try{for(i.s();!(o=i.n()).done;){var u,c=o.value;null===(u=r.retention.nodesRetainedByZone.get(c))||void 0===u||u.delete(n)}}catch(m){i.e(m)}finally{i.f()}t.atomValues.delete(n),t.dirtyAtoms.delete(n),t.nonvalidatedAtoms.delete(n);var l=r.graphsByVersion.get(t.version);if(l){var s=l.nodeDeps.get(n);if(void 0!==s){l.nodeDeps.delete(n);var f,d=Object(h.a)(s);try{for(d.s();!(f=d.n()).done;){var p,v=f.value;null===(p=l.nodeToNodeSubscriptions.get(v))||void 0===p||p.delete(n)}}catch(m){d.e(m)}finally{d.f()}}l.nodeToNodeSubscriptions.delete(n)}en(n)}}function un(e,t){var n;return null!==(n=e.retention.nodesRetainedByZone.get(t))&&void 0!==n?n:rn}function cn(e){var t=tn(e).retainedBy;return void 0===t||"components"===t||"recoilRoot"===t?[]:t instanceof nn?[t]:t}function ln(e,t){me("recoil_memory_managament_2020")&&(e.getState().retention.referenceCounts.delete(t),function(e,t){var n=e.getState();n.nextTree?n.retention.retainablesToCheckForRelease.add(t):on(e,new Set([t]))}(e,t))}var sn=12e4,fn=function(e,t,n){var r;if(me("recoil_memory_managament_2020")){var o=e.getState().retention.referenceCounts,a=(null!==(r=o.get(t))&&void 0!==r?r:0)+n;0===a?ln(e,t):o.set(t,a)}},dn=function(e){if(me("recoil_memory_managament_2020")){var t=e.getState();on(e,t.retention.retainablesToCheckForRelease),t.retention.retainablesToCheckForRelease.clear()}},pn=function(e){return void 0===e?"recoilRoot":e},vn=T.a.unstable_batchedUpdates,hn=Gt.batchStart,mn={unstable_batchedUpdates:{unstable_batchedUpdates:vn}.unstable_batchedUpdates}.unstable_batchedUpdates,bn=function(e){mn((function(){var t=function(){};try{t=hn(),e()}finally{t()}}))};function yn(e){var t,n,r,o,a,i;return v.a.wrap((function(u){for(;;)switch(u.prev=u.next){case 0:t=Object(h.a)(e),u.prev=1,t.s();case 3:if((n=t.n()).done){u.next=24;break}r=n.value,o=Object(h.a)(r),u.prev=6,o.s();case 8:if((a=o.n()).done){u.next=14;break}return i=a.value,u.next=12,i;case 12:u.next=8;break;case 14:u.next=19;break;case 16:u.prev=16,u.t0=u.catch(6),o.e(u.t0);case 19:return u.prev=19,o.f(),u.finish(19);case 22:u.next=3;break;case 24:u.next=29;break;case 26:u.prev=26,u.t1=u.catch(1),t.e(u.t1);case 29:return u.prev=29,t.f(),u.finish(29);case 32:case"end":return u.stop()}}),N,null,[[1,26,29,32],[6,16,19,22]])}var gn=yn,wn={isSSR:"undefined"===typeof window,isReactNative:"undefined"!==typeof navigator&&"ReactNative"===navigator.product};var _n=function(e,t){var n,r,o=this;return[function(){for(var a=arguments.length,i=new Array(a),u=0;u0}},{key:"checkRefCount_INTERNAL",value:function(){me("recoil_memory_managament_2020")&&this._refCount}},{key:"getStore_INTERNAL",value:function(){return this.checkRefCount_INTERNAL(),this._store}},{key:"getID",value:function(){return this.checkRefCount_INTERNAL(),this._store.getState().currentTree.stateID}}]),e}();function Vn(e,t){var n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=e.getState(),o=n?Mn():t.version;return{currentTree:n?{version:o,stateID:o,transactionMetadata:Object(b.a)({},t.transactionMetadata),dirtyAtoms:new Set(t.dirtyAtoms),atomValues:t.atomValues.clone(),nonvalidatedAtoms:t.nonvalidatedAtoms.clone()}:t,commitDepth:0,nextTree:null,previousTree:null,knownAtoms:new Set(r.knownAtoms),knownSelectors:new Set(r.knownSelectors),transactionSubscriptions:new Map,nodeTransactionSubscriptions:new Map,nodeToComponentSubscriptions:new Map,queuedComponentCallbacks_DEPRECATED:[],suspendedComponentResolvers:new Set,graphsByVersion:(new Map).set(o,e.getGraph(t.version)),retention:{referenceCounts:new Map,nodesRetainedByZone:new Map,retainablesToCheckForRelease:new Set},nodeCleanupFunctions:new Map(be(r.nodeCleanupFunctions.entries(),(function(e){return[Object(u.a)(e,1)[0],function(){}]})))}}var Un=zn((function(e,t){var n=e.getState(),r="current"===t?n.currentTree:I(n.previousTree);return new Fn(Vn(e,r))}),(function(e,t){var n;return String(t)+String(e.storeID)+String(e.getState().currentTree.version)+String(null===(n=e.getState().previousTree)||void 0===n?void 0:n.version)})),Bn=Object(u.a)(Un,2),Wn=Bn[0],Hn=Bn[1];var Yn=function(e){g(n,e);var t=O(n);function n(e,r){var o;return S(this,n),z(y(o=t.call(this,Vn(e.getStore_INTERNAL(),e.getStore_INTERNAL().getState().currentTree,!0))),"_batch",void 0),z(y(o),"set",(function(e,t){o.checkRefCount_INTERNAL();var n=o.getStore_INTERNAL();o._batch((function(){Nn(n,e.key,1),An(o.getStore_INTERNAL(),e,t)}))})),z(y(o),"reset",(function(e){o.checkRefCount_INTERNAL();var t=o.getStore_INTERNAL();o._batch((function(){Nn(t,e.key,1),An(o.getStore_INTERNAL(),e,Cn)}))})),z(y(o),"setUnvalidatedAtomValues_DEPRECATED",(function(e){o.checkRefCount_INTERNAL();var t=o.getStore_INTERNAL();On((function(){var n,r=Object(h.a)(e.entries());try{for(r.s();!(n=r.n()).done;){var o=Object(u.a)(n.value,2),a=o[0],i=o[1];Nn(t,a,1),Ln(t,new Rn(a),i)}}catch(c){r.e(c)}finally{r.f()}}))})),o._batch=r,o}return n}(Fn),Kn={Snapshot:Fn,MutableSnapshot:Yn,freshSnapshot:function(e){var t=new Fn(Dn());return null!=e?t.map(e):t},cloneSnapshot:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"current",n=Wn(e,t);return n.isRetained()?n:(Hn(),Wn(e,t))}},qn=Kn.Snapshot,Xn=Kn.MutableSnapshot,$n=Kn.freshSnapshot,Qn=Kn.cloneSnapshot,Gn=Object.freeze({__proto__:null,Snapshot:qn,MutableSnapshot:Xn,freshSnapshot:$n,cloneSnapshot:Qn});var Zn=function(){for(var e=new Set,t=arguments.length,n=new Array(t),r=0;r component.")}var Sr=Object.freeze({storeID:sr(),getState:Or,replaceState:Or,getGraph:Or,subscribeToTransactions:Or,addTransactionMetadata:Or}),Er=!1;function jr(e){if(Er)throw M("An atom update was triggered within the execution of a state updater function. State updater functions provided to Recoil must be pure functions.");var t=e.getState();if(null===t.nextTree){me("recoil_memory_managament_2020")&&me("recoil_release_on_cascading_update_killswitch_2021")&&t.commitDepth>0&&vr(e);var n=t.currentTree.version,r=tr();t.nextTree=Object(b.a)(Object(b.a)({},t.currentTree),{},{version:r,stateID:r,dirtyAtoms:new Set,transactionMetadata:{}}),t.graphsByVersion.set(r,lr(I(t.graphsByVersion.get(n))))}}var kr=C.a.createContext({current:Sr}),Cr=function(){return br(kr)},xr=C.a.createContext(null);function Tr(e,t,n){var r,o=or(e,n,n.dirtyAtoms),a=Object(h.a)(o);try{for(a.s();!(r=a.n()).done;){var i=r.value,c=t.nodeToComponentSubscriptions.get(i);if(c){var l,s=Object(h.a)(c);try{for(s.s();!(l=s.n()).done;){var f=Object(u.a)(l.value,2),d=(f[0],Object(u.a)(f[1],2));d[0];(0,d[1])(n)}}catch(p){s.e(p)}finally{s.f()}}}}catch(p){a.e(p)}finally{a.f()}}function Rr(e){var t=e.getState(),n=t.currentTree,r=n.dirtyAtoms;if(r.size){var o,a=Object(h.a)(t.nodeTransactionSubscriptions);try{for(a.s();!(o=a.n()).done;){var i=Object(u.a)(o.value,2),c=i[0],l=i[1];if(r.has(c)){var s,f=Object(h.a)(l);try{for(f.s();!(s=f.n()).done;){var d=Object(u.a)(s.value,2);d[0];(0,d[1])(e)}}catch(b){f.e(b)}finally{f.f()}}}}catch(b){a.e(b)}finally{a.f()}var p,v=Object(h.a)(t.transactionSubscriptions);try{for(v.s();!(p=v.n()).done;){var m=Object(u.a)(p.value,2);m[0];(0,m[1])(e)}}catch(b){v.e(b)}finally{v.f()}(!dr().early||t.suspendedComponentResolvers.size>0)&&(Tr(e,t,n),t.suspendedComponentResolvers.forEach((function(e){return e()})),t.suspendedComponentResolvers.clear())}t.queuedComponentCallbacks_DEPRECATED.forEach((function(e){return e(n)})),t.queuedComponentCallbacks_DEPRECATED.splice(0,t.queuedComponentCallbacks_DEPRECATED.length)}function Pr(e){var t=e.setNotifyBatcherOfChange,n=Cr(),r=_r([]),o=Object(u.a)(r,2)[1];return t((function(){return o({})})),yr((function(){return t((function(){return o({})})),function(){t((function(){}))}}),[t]),yr((function(){Te.enqueueExecution("Batcher",(function(){!function(e){var t=e.getState();t.commitDepth++;try{var n=t.nextTree;if(null===n)return;t.previousTree=t.currentTree,t.currentTree=n,t.nextTree=null,Rr(e),null!=t.previousTree?t.graphsByVersion.delete(t.previousTree.version):ge("Ended batch with no previous state, which is unexpected","recoil"),t.previousTree=null,me("recoil_memory_managament_2020")&&vr(e)}finally{t.commitDepth--}}(n.current)}))})),null}var Ar=0;function Lr(e){var t,n=e.initializeState_DEPRECATED,r=e.initializeState,o=e.store_INTERNAL,a=e.children,i=function(e){var n=t.current.graphsByVersion;if(n.has(e))return I(n.get(e));var r=cr();return n.set(e,r),r},u=function(e,t){if(null==t){var n=d.current.getState().transactionSubscriptions,r=Ar++;return n.set(r,e),{release:function(){n.delete(r)}}}var o=d.current.getState().nodeTransactionSubscriptions;o.has(t)||o.set(t,new Map);var a=Ar++;return I(o.get(t)).set(a,e),{release:function(){var e=o.get(t);e&&(e.delete(a),0===e.size&&o.delete(t))}}},c=function(e){jr(d.current);for(var t=0,n=Object.keys(e);t. must be an ancestor of any component that uses Recoil hooks."),e},Ir=function(){return Cr().current.storeID};var zr=function(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(var n=0,r=e.length;n"},Zr=xe.DEFAULT_VALUE,Jr=Tt.reactMode,eo=Tt.useMutableSource,to=Tt.useSyncExternalStore,no=Dr,ro=Mr,oo=(de.isRecoilValue,Gt.getRecoilValueAsLoadable),ao=Gt.setRecoilValue,io=Gt.subscribeToRecoilValue,uo=C.a.useCallback,co=C.a.useEffect,lo=C.a.useMemo,so=C.a.useRef,fo=C.a.useState;function po(e,t,n){if("hasValue"===e.state)return e.contents;if("loading"===e.state)throw new Promise((function(e){n.current.getState().suspendedComponentResolvers.add(e)}));throw"hasError"===e.state?e.contents:M('Invalid value of loadable atom "'.concat(t.key,'"'))}function vo(e){var t=ro(),n=Gr(),r=uo((function(){var n;var r=t.current,o=r.getState(),a=Jr().early&&null!==(n=o.nextTree)&&void 0!==n?n:o.currentTree;return{loadable:oo(r,e,a),key:e.key}}),[t,e]),o=uo((function(e){var t;return function(){var n,r,o=e();return null!==(n=t)&&void 0!==n&&n.loadable.is(o.loadable)&&(null===(r=t)||void 0===r?void 0:r.key)===o.key?t:(t=o,o)}}),[]),a=lo((function(){return o(r)}),[r,o]),i=uo((function(r){var o=t.current;return io(o,e,r,n).release}),[t,e,n]);return to(i,a,a).loadable}function ho(e){var t=ro(),n=uo((function(){var n,r=t.current,o=r.getState(),a=Jr().early&&null!==(n=o.nextTree)&&void 0!==n?n:o.currentTree;return oo(r,e,a)}),[t,e]),r=uo((function(){return n()}),[n]),o=Gr(),a=uo((function(r,a){var i=t.current;return io(i,e,(function(){if(!me("recoil_suppress_rerender_in_callback"))return a();var e=n();c.current.is(e)||a(),c.current=e}),o).release}),[t,e,o,n]),i=no();if(null==i)throw M("Recoil hooks must be used in components contained within a component.");var u=eo(i,r,a),c=so(u);return co((function(){c.current=u})),u}function mo(e){var t=ro(),n=Gr(),r=uo((function(){var n;var r=t.current,o=r.getState(),a=Jr().early&&null!==(n=o.nextTree)&&void 0!==n?n:o.currentTree;return oo(r,e,a)}),[t,e]),o=uo((function(){return{loadable:r(),key:e.key}}),[r,e.key]),a=uo((function(e){var t=o();return e.loadable.is(t.loadable)&&e.key===t.key?e:t}),[o]);co((function(){var r=io(t.current,e,(function(e){s(a)}),n);return s(a),r.release}),[n,e,t,a]);var i=fo(o),c=Object(u.a)(i,2),l=c[0],s=c[1];return l.key!==e.key?o().loadable:l.loadable}function bo(e){var t=ro(),n=fo([]),r=Object(u.a)(n,2)[1],o=Gr(),a=uo((function(){var n;var r=t.current,o=r.getState(),a=Jr().early&&null!==(n=o.nextTree)&&void 0!==n?n:o.currentTree;return oo(r,e,a)}),[t,e]),i=a(),c=so(i);return co((function(){c.current=i})),co((function(){var n=t.current,i=n.getState(),u=io(n,e,(function(e){var t;if(!me("recoil_suppress_rerender_in_callback"))return r([]);var n=a();null!==(t=c.current)&&void 0!==t&&t.is(n)||r(n),c.current=n}),o);if(i.nextTree)n.getState().queuedComponentCallbacks_DEPRECATED.push((function(){c.current=null,r([])}));else{var l;if(!me("recoil_suppress_rerender_in_callback"))return r([]);var s=a();null!==(l=c.current)&&void 0!==l&&l.is(s)||r(s),c.current=s}return u.release}),[o,a,e,t]),i}function yo(e){return me("recoil_memory_managament_2020")&&$r(e),{TRANSITION_SUPPORT:mo,SYNC_EXTERNAL_STORE:vo,MUTABLE_SOURCE:ho,LEGACY:bo}[Jr().mode](e)}function go(e){var t=ro();return po(yo(e),e,t)}function wo(e){var t=ro();return uo((function(n){ao(t.current,e,n)}),[t,e])}function _o(e){return me("recoil_memory_managament_2020")&&$r(e),mo(e)}function Oo(e){var t=ro();return po(_o(e),e,t)}var So=function(e){return[go(e),wo(e)]},Eo=function(e){return[yo(e),wo(e)]},jo=go,ko=yo,Co=function(e){var t=ro();return uo((function(){ao(t.current,e,Zr)}),[t,e])},xo=wo,To=_o,Ro=Oo,Po=function(e){return[Oo(e),wo(e)]};var Ao=bn,Lo=xe.DEFAULT_VALUE,No=xe.getNode,Mo=Mr,Do=Gt.AbstractRecoilValue,Io=Gt.setRecoilValueLoadable,zo=sn,Fo=Gn.cloneSnapshot,Vo=C.a.useCallback,Uo=C.a.useEffect,Bo=C.a.useRef,Wo=C.a.useState,Ho=wn.isSSR;function Yo(e){var t=Mo();Uo((function(){return t.current.subscribeToTransactions(e).release}),[e,t])}function Ko(e,t){var n,r=e.getState(),o=null!==(n=r.nextTree)&&void 0!==n?n:r.currentTree,a=t.getStore_INTERNAL().getState().currentTree;Ao((function(){for(var n=new Set,r=0,i=[o.atomValues.keys(),a.atomValues.keys()];rthis.maxSize()&&this.deleteLru()}},{key:"deleteLru",value:function(){var e=this.tail();e&&this.delete(e.key)}},{key:"delete",value:function(e){var t=this._keyMapper(e);if(this._size&&this._map.has(t)){var n=I(this._map.get(t)),r=n.right,o=n.left;r&&(r.left=n.left),o&&(o.right=n.right),n===this.head()&&(this._head=r),n===this.tail()&&(this._tail=o),this._map.delete(t),this._size--}}},{key:"clear",value:function(){this._size=0,this._head=null,this._tail=null,this._map=new Map}}]),e}()}.LRUCache,$a=Object.freeze({__proto__:null,LRUCache:Xa}),Qa=$a.LRUCache,Ga=qa.TreeCache;var Za=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(e){return e},n=new Qa({maxSize:e}),r=new Ga({mapNodeValue:t,onHit:function(e){n.set(e,!0)},onSet:function(t){var o=n.tail();n.set(t,!0),o&&r.size()>e&&r.delete(o.key)}});return r};function Ja(e,t,n){if("string"===typeof e&&!e.includes('"')&&!e.includes("\\"))return'"'.concat(e,'"');switch(typeof e){case"undefined":return"";case"boolean":return e?"true":"false";case"number":case"symbol":return String(e);case"string":return JSON.stringify(e);case"function":if(!0!==(null===t||void 0===t?void 0:t.allowFunctions))throw M("Attempt to serialize function in a Recoil cache key");return"__FUNCTION(".concat(e.name,")__")}if(null===e)return"null";var r;if("object"!==typeof e)return null!==(r=JSON.stringify(e))&&void 0!==r?r:"";if(D(e))return"__PROMISE__";if(Array.isArray(e))return"[".concat(e.map((function(e,n){return Ja(e,t,n.toString())})),"]");if("function"===typeof e.toJSON)return Ja(e.toJSON(n),t,n);if(e instanceof Map){var o,a={},i=Object(h.a)(e);try{for(i.s();!(o=i.n()).done;){var c=Object(u.a)(o.value,2),l=c[0],s=c[1];a["string"===typeof l?l:Ja(l,t)]=s}}catch(f){i.e(f)}finally{i.f()}return Ja(a,t,n)}return e instanceof Set?Ja(Array.from(e).sort((function(e,n){return Ja(e,t).localeCompare(Ja(n,t))})),t,n):void 0!==Symbol&&null!=e[Symbol.iterator]&&"function"===typeof e[Symbol.iterator]?Ja(Array.from(e),t,n):"{".concat(Object.keys(e).filter((function(t){return void 0!==e[t]})).sort().map((function(n){return"".concat(Ja(n,t),":").concat(Ja(e[n],t,n))})).join(","),"}")}var ei=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{allowFunctions:!1};return Ja(e,t)},ti=qa.TreeCache,ni={equality:"reference",eviction:"keep-all",maxSize:1/0};function ri(e){switch(e){case"reference":return function(e){return e};case"value":return function(e){return ei(e)}}throw M("Unrecognized equality policy ".concat(e))}function oi(e,t,n){switch(e){case"keep-all":return new ti({mapNodeValue:n});case"lru":return Za(I(t),n);case"most-recent":return Za(1,n)}throw M("Unrecognized eviction policy ".concat(e))}var ai=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ni,t=e.equality,n=void 0===t?ni.equality:t,r=e.eviction,o=void 0===r?ni.eviction:r,a=e.maxSize,i=void 0===a?ni.maxSize:a,u=ri(n),c=oi(o,i,u);return c};var ii=function(e){return function(){return null}},ui=re.loadableWithError,ci=re.loadableWithPromise,li=re.loadableWithValue,si=yt,fi=gt,di=wt,pi=Ve,vi=xe.DEFAULT_VALUE,hi=xe.RecoilValueNotReady,mi=xe.getConfigDeletionHandler,bi=xe.getNode,yi=xe.registerNode,gi=de.isRecoilValue,wi=Gt.markRecoilValueModified,_i=pn,Oi=Ra,Si=ii,Ei=function e(){S(this,e)},ji=new Ei,ki=[],Ci=new Map,xi=function(){var e=0;return function(){return e++}}();var Ti=function(e){var t=null,n=e.key,r=e.get,o=e.cachePolicy_UNSTABLE,a=null!=e.set?e.set:void 0,i=new Set,c=ai(null!==o&&void 0!==o?o:{equality:"reference",eviction:"keep-all"}),l=_i(e.retainedBy_UNSTABLE),s=new Map,f=0;function d(){return!me("recoil_memory_managament_2020")||f>0}function p(e){return e.getState().knownSelectors.add(n),f++,function(){f--}}function v(){return void 0!==mi(n)&&!d()}function m(e,t,n,r,o){P(t,r,o),_(e,t,new Set(o.keys()),n),b(e,n)}function b(e,n){R(e,n)&&T(e);var r=Ci.get(n);if(void 0!==r){var o,a=Object(h.a)(r);try{for(a.s();!(o=a.n()).done;){var i=o.value;wi(i,I(t))}}catch(u){a.e(u)}finally{a.f()}Ci.delete(n)}}function y(e,t){var n=Ci.get(t);null==n&&Ci.set(t,n=new Set),n.add(e)}function g(e,t,n){var r=e.getState().knownSelectors.has(n);if(r&&t.atomValues.has(n))return I(t.atomValues.get(n));var o=si(e,t,n);return"loading"!==o.state&&r&&t.atomValues.set(n,o),o}function w(e,t,n,r,o,a){return t.then((function(r){if(!d())throw T(e),ji;null!=a.loadingDepKey&&a.loadingDepPromise===t?n.atomValues.set(a.loadingDepKey,li(r)):e.getState().knownSelectors.forEach((function(e){n.atomValues.delete(e)}));var i=S(e,n);if(i&&"loading"!==i.state){if((R(e,o)||null==C(e))&&b(e,o),"hasValue"===i.state)return i.contents;throw i.contents}if(!R(e,o)){var c=j(n);if("loading"===(null===c||void 0===c?void 0:c.latestLoadable.state))return c.latestLoadable.contents}var l=O(e,n,o),s=Object(u.a)(l,2),f=s[0],p=s[1];if(x(e,o,p),"loading"!==f.state&&m(e,n,o,f,p),"hasError"===f.state)throw f.contents;return f.contents})).catch((function(t){if(t instanceof Ei)throw ji;if(!d())throw T(e),ji;var a=ui(t);throw m(e,n,o,a,r),t}))}function _(e,t,r,o){var a,u,c,l,s,f,d;(R(e,o)||t.version===(null===(a=e.getState())||void 0===a||null===(u=a.currentTree)||void 0===u?void 0:u.version)||t.version===(null===(c=e.getState())||void 0===c||null===(l=c.nextTree)||void 0===l?void 0:l.version))&&(pi(new Map([[n,r]]),e,null!==(s=null===(f=e.getState())||void 0===f||null===(d=f.nextTree)||void 0===d?void 0:d.version)&&void 0!==s?s:e.getState().currentTree.version),r.forEach((function(e){return i.add(e)})))}function O(e,o,a){var i,u=Si(n),c=!0,l=function(){u(),c=!1},s=!1,f={loadingDepKey:null,loadingDepPromise:null},p=new Map,v=new Set;function h(t){var n=t.key;!function(e,t,n,r,o){n.add(r),_(e,t,n,o)}(e,o,v,n,a);var r=g(e,o,n);switch(p.set(n,r),r.state){case"hasValue":return r.contents;case"hasError":throw r.contents;case"loading":throw f.loadingDepKey=n,f.loadingDepPromise=r.contents,r.contents}throw M("Invalid Loadable state")}_(e,o,v,a);try{i=r({get:h,getCallback:function(n){return function(){if(c)throw M("Callbacks from getCallback() should only be called asynchronously after the selector is evalutated. It can be used for selectors to return objects with callbacks that can work with Recoil state without a subscription.");null==t&&ba(!1);for(var r=arguments.length,o=new Array(r),a=0;a0&&void 0!==arguments[0]?arguments[0]:Zi,t=e.equality,n=void 0===t?Zi.equality:t,r=e.eviction,o=void 0===r?Zi.eviction:r,a=e.maxSize,i=void 0===a?Zi.maxSize:a,u=Ji(n),c=eu(o,i,u);return c},nu=xe.setConfigDeletionHandler;var ru=function(e){var t,n,r=tu({equality:null!==(t=null===(n=e.cachePolicyForParams_UNSTABLE)||void 0===n?void 0:n.equality)&&void 0!==t?t:"value",eviction:"keep-all"});return function(t){var n,o,i=r.get(t);if(null!=i)return i;e.cachePolicyForParams_UNSTABLE;var u=Object(a.a)(e,A),c=qi(Object(b.a)(Object(b.a)({},u),{},{key:"".concat(e.key,"__").concat(null!==(n=ei(t))&&void 0!==n?n:"void"),default:"function"===typeof e.default?e.default(t):e.default,retainedBy_UNSTABLE:"function"===typeof e.retainedBy_UNSTABLE?e.retainedBy_UNSTABLE(t):e.retainedBy_UNSTABLE,effects:"function"===typeof e.effects?e.effects(t):"function"===typeof e.effects_UNSTABLE?e.effects_UNSTABLE(t):null!==(o=e.effects)&&void 0!==o?o:e.effects_UNSTABLE}));return r.set(t,c),nu(c.key,(function(){r.delete(t)})),c}},ou=xe.setConfigDeletionHandler,au=0;var iu=function(e){var t,n,r=tu({equality:null!==(t=null===(n=e.cachePolicyForParams_UNSTABLE)||void 0===n?void 0:n.equality)&&void 0!==t?t:"value",eviction:"keep-all"});return function(t){var n,o=r.get(t);if(null!=o)return o;var a,i="".concat(e.key,"__selectorFamily/").concat(null!==(n=ei(t,{allowFunctions:!0}))&&void 0!==n?n:"void","/").concat(au++),u=function(n){return e.get(t)(n)},c=e.cachePolicy_UNSTABLE,l="function"===typeof e.retainedBy_UNSTABLE?e.retainedBy_UNSTABLE(t):e.retainedBy_UNSTABLE;if(null!=e.set){var s=e.set;a=Ti({key:i,get:u,set:function(e,n){return s(t)(e,n)},cachePolicy_UNSTABLE:c,dangerouslyAllowMutability:e.dangerouslyAllowMutability,retainedBy_UNSTABLE:l})}else a=Ti({key:i,get:u,cachePolicy_UNSTABLE:c,dangerouslyAllowMutability:e.dangerouslyAllowMutability,retainedBy_UNSTABLE:l});return r.set(t,a),ou(a.key,(function(){r.delete(t)})),a}},uu=iu({key:"__constant",get:function(e){return function(){return e}},cachePolicyForParams_UNSTABLE:{equality:"reference"}});var cu=function(e){return uu(e)},lu=iu({key:"__error",get:function(e){return function(){throw M(e)}},cachePolicyForParams_UNSTABLE:{equality:"reference"}});var su=function(e){return lu(e)};var fu=function(e){return e},du=re.loadableWithError,pu=re.loadableWithPromise,vu=re.loadableWithValue;function hu(e,t){var n,r=Array(t.length).fill(void 0),o=Array(t.length).fill(void 0),a=Object(h.a)(t.entries());try{for(a.s();!(n=a.n()).done;){var i=Object(u.a)(n.value,2),c=i[0],l=i[1];try{r[c]=e(l)}catch(s){o[c]=s}}}catch(f){a.e(f)}finally{a.f()}return[r,o]}function mu(e){return null!=e&&!D(e)}function bu(e){return Array.isArray(e)?e:Object.getOwnPropertyNames(e).map((function(t){return e[t]}))}function yu(e,t){return Array.isArray(e)?t:Object.getOwnPropertyNames(e).reduce((function(e,n,r){return Object(b.a)(Object(b.a)({},e),{},Object(m.a)({},n,t[r]))}),{})}function gu(e,t,n){return yu(e,n.map((function(e,n){return null==e?vu(t[n]):D(e)?pu(e):du(e)})))}var wu=iu({key:"__waitForNone",get:function(e){return function(t){var n=hu(t.get,bu(e)),r=Object(u.a)(n,2),o=r[0],a=r[1];return gu(e,o,a)}},dangerouslyAllowMutability:!0}),_u=iu({key:"__waitForAny",get:function(e){return function(t){var n=hu(t.get,bu(e)),r=Object(u.a)(n,2),o=r[0],a=r[1];return a.some((function(e){return!D(e)}))?gu(e,o,a):new Promise((function(t){var n,r=Object(h.a)(a.entries());try{var i=function(){var r=Object(u.a)(n.value,2),i=r[0],c=r[1];D(c)&&c.then((function(n){o[i]=n,a[i]=void 0,t(gu(e,o,a))})).catch((function(n){a[i]=n,t(gu(e,o,a))}))};for(r.s();!(n=r.n()).done;)i()}catch(c){r.e(c)}finally{r.f()}}))}},dangerouslyAllowMutability:!0}),Ou={waitForNone:wu,waitForAny:_u,waitForAll:iu({key:"__waitForAll",get:function(e){return function(t){var n=hu(t.get,bu(e)),r=Object(u.a)(n,2),o=r[0],a=r[1];if(a.every((function(e){return null==e})))return yu(e,o);var i=a.find(mu);if(null!=i)throw i;return Promise.all(a).then((function(t){return yu(e,(n=o,t.map((function(e,t){return void 0===e?n[t]:e}))));var n}))}},dangerouslyAllowMutability:!0}),waitForAllSettled:iu({key:"__waitForAllSettled",get:function(e){return function(t){var n=hu(t.get,bu(e)),r=Object(u.a)(n,2),o=r[0],a=r[1];return a.every((function(e){return!D(e)}))?gu(e,o,a):Promise.all(a.map((function(e,t){return D(e)?e.then((function(e){o[t]=e,a[t]=void 0})).catch((function(e){o[t]=void 0,a[t]=e})):null}))).then((function(){return gu(e,o,a)}))}},dangerouslyAllowMutability:!0}),noWait:iu({key:"__noWait",get:function(e){return function(t){var n=t.get;try{return vu(n(e))}catch(r){return D(r)?pu(r):du(r)}}},dangerouslyAllowMutability:!0})},Su=re.RecoilLoadable,Eu=xe.DefaultValue,ju=Nr,ku=Ir,Cu=de.isRecoilValue,xu=et,Tu=Gn.freshSnapshot,Ru={DefaultValue:Eu,isRecoilValue:Cu,RecoilLoadable:Su,RecoilRoot:ju,useRecoilStoreID:ku,useRecoilBridgeAcrossReactRoots_UNSTABLE:oa,atom:qi,selector:Ti,atomFamily:ru,selectorFamily:iu,constSelector:cu,errorSelector:su,readOnlySelector:fu,noWait:Ou.noWait,waitForNone:Ou.waitForNone,waitForAny:Ou.waitForAny,waitForAll:Ou.waitForAll,waitForAllSettled:Ou.waitForAllSettled,useRecoilValue:jo,useRecoilValueLoadable:ko,useRecoilState:So,useRecoilStateLoadable:Eo,useSetRecoilState:xo,useResetRecoilState:Co,useGetRecoilValueInfo_UNSTABLE:Jo,useRecoilRefresher_UNSTABLE:Ma,useRecoilValueLoadable_TRANSITION_SUPPORT_UNSTABLE:To,useRecoilValue_TRANSITION_SUPPORT_UNSTABLE:Ro,useRecoilState_TRANSITION_SUPPORT_UNSTABLE:Po,useRecoilCallback:Pa,useRecoilTransaction_UNSTABLE:Fa,useGotoRecoilSnapshot:$o,useRecoilSnapshot:qo,useRecoilTransactionObserver_UNSTABLE:Qo,snapshot_UNSTABLE:Tu,useRetain:$r,retentionZone:xu},Pu=Ru.RecoilRoot,Au=Ru.atom,Lu=Ru.selector,Nu=Ru.useRecoilValue,Mu=Ru.useRecoilState,Du=Ru.useSetRecoilState},function(e,t,n){"use strict";function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}n.d(t,"a",(function(){return r}))},function(e,t,n){e.exports=n(58)},function(e,t,n){"use strict";!function e(){if("undefined"!==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"===typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE)try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}(),e.exports=n(54)},function(e,t,n){"use strict";n.d(t,"a",(function(){return m}));var r=n(10),o=n(4),a=n(3),i=n(14),u=n(0),c=n(5),l=["children"],s=["children"],f=u.forwardRef((function(e,t){var n=e.children,r=Object(o.a)(e,l);return u.Children.toArray(n).some(v)?u.createElement(u.Fragment,null,u.Children.map(n,(function(e){return v(e)?u.createElement(d,Object(c.a)({},r,{ref:t}),e.props.children):e}))):u.createElement(d,Object(c.a)({},r,{ref:t}),n)}));f.displayName="Slot";var d=u.forwardRef((function(e,t){var n=e.children,r=Object(o.a)(e,s);return u.isValidElement(n)?u.cloneElement(n,Object(a.a)(Object(a.a)({},function(e,t){var n=Object(a.a)({},t),r=function(r){var o=e[r],i=t[r];/^on[A-Z]/.test(r)?n[r]=function(){null==i||i.apply(void 0,arguments),null==o||o.apply(void 0,arguments)}:"style"===r?n[r]=Object(a.a)(Object(a.a)({},o),i):"className"===r&&(n[r]=[o,i].filter(Boolean).join(" "))};for(var o in t)r(o);return Object(a.a)(Object(a.a)({},e),n)}(r,n.props)),{},{ref:Object(i.a)(t,n.ref)})):u.Children.count(n)>1?u.Children.only(null):null}));d.displayName="SlotClone";var p=function(e){var t=e.children;return u.createElement(u.Fragment,null,t)};function v(e){return u.isValidElement(e)&&e.type===p}var h=["asChild"],m=["a","button","div","h2","h3","img","li","nav","ol","p","span","svg","ul"].reduce((function(e,t){return Object(a.a)(Object(a.a)({},e),{},Object(r.a)({},t,u.forwardRef((function(e,n){var r=e.asChild,a=Object(o.a)(e,h),i=r?f:t;return u.useEffect((function(){window[Symbol.for("radix-ui")]=!0}),[]),u.createElement(i,Object(c.a)({},a,{ref:n}))}))))}),{})},function(e,t,n){"use strict";n.d(t,"a",(function(){return o})),n.d(t,"b",(function(){return a}));var r=n(0);function o(){for(var e=arguments.length,t=new Array(e),n=0;n1?i.Children.only(null):Object(i.isValidElement)(l)?l.props.children:null:e}));return Object(i.createElement)(b,Object(a.a)({},r,{ref:t}),Object(i.isValidElement)(l)?Object(i.cloneElement)(l,void 0,s):null)}return Object(i.createElement)(b,Object(a.a)({},r,{ref:t}),n)}));m.displayName="Slot";var b=Object(i.forwardRef)((function(e,t){var n=e.children,a=Object(o.a)(e,p);return Object(i.isValidElement)(n)?Object(i.cloneElement)(n,Object(r.a)(Object(r.a)({},function(e,t){var n=Object(r.a)({},t),o=function(o){var a=e[o],i=t[o];/^on[A-Z]/.test(o)?n[o]=function(){null===i||void 0===i||i.apply(void 0,arguments),null===a||void 0===a||a.apply(void 0,arguments)}:"style"===o?n[o]=Object(r.a)(Object(r.a)({},a),i):"className"===o&&(n[o]=[a,i].filter(Boolean).join(" "))};for(var a in t)o(a);return Object(r.a)(Object(r.a)({},e),n)}(a,n.props)),{},{ref:s(t,n.ref)})):i.Children.count(n)>1?i.Children.only(null):null}));b.displayName="SlotClone";var y=function(e){var t=e.children;return Object(i.createElement)(i.Fragment,null,t)};function g(e){return Object(i.isValidElement)(e)&&e.type===y}var w=m},function(e,t,n){"use strict";n.d(t,"b",(function(){return r})),n.d(t,"d",(function(){return o})),n.d(t,"c",(function(){return a})),n.d(t,"a",(function(){return i}));var r=function(){};function o(e){for(var t=[],n=1;n1&&void 0!==arguments[1]?arguments[1]:[],n=[],c=function(){var t=n.map((function(e){return u.createContext(e)}));return function(n){var r=(null==n?void 0:n[e])||t;return u.useMemo((function(){return Object(o.a)({},"__scope".concat(e),Object(a.a)(Object(a.a)({},n),{},Object(o.a)({},e,r)))}),[n,r])}};return c.scopeName=e,[function(t,o){var a=u.createContext(o),c=n.length;function s(t){var n=t.scope,r=t.children,o=Object(i.a)(t,l),s=(null==n?void 0:n[e][c])||a,f=u.useMemo((function(){return o}),Object.values(o));return u.createElement(s.Provider,{value:f},r)}return n=[].concat(Object(r.a)(n),[o]),s.displayName=t+"Provider",[s,function(n,r){var i=(null==r?void 0:r[e][c])||a,l=u.useContext(i);if(l)return l;if(void 0!==o)return o;throw new Error("`".concat(n,"` must be used within `").concat(t,"`"))}]},d.apply(void 0,[c].concat(Object(r.a)(t)))]}function d(){for(var e=arguments.length,t=new Array(e),n=0;n1&&void 0!==arguments[1]?arguments[1]:[],n=[];function o(t,r){var o=Object(l.createContext)(r),a=n.length;function u(t){var n=t.scope,r=t.children,u=Object(i.a)(t,y),c=(null===n||void 0===n?void 0:n[e][a])||o,s=Object(l.useMemo)((function(){return u}),Object.values(u));return Object(l.createElement)(c.Provider,{value:s},r)}return n=[].concat(Object(m.a)(n),[r]),u.displayName=t+"Provider",[u,function(n,i){var u=(null===i||void 0===i?void 0:i[e][a])||o,c=Object(l.useContext)(u);if(c)return c;if(void 0!==r)return r;throw new Error("`".concat(n,"` must be used within `").concat(t,"`"))}]}var a=function(){var t=n.map((function(e){return Object(l.createContext)(e)}));return function(n){var o=(null===n||void 0===n?void 0:n[e])||t;return Object(l.useMemo)((function(){return Object(h.a)({},"__scope".concat(e),Object(r.a)(Object(r.a)({},n),{},Object(h.a)({},e,o)))}),[n,o])}};return a.scopeName=e,[o,S.apply(void 0,[a].concat(Object(m.a)(t)))]}function S(){for(var e=arguments.length,t=new Array(e),n=0;n1&&void 0!==arguments[1]?arguments[1]:[],n=[];function o(t,r){var o=Object(l.createContext)(r),a=n.length;function u(t){var n=t.scope,r=t.children,u=Object(i.a)(t,B),c=(null===n||void 0===n?void 0:n[e][a])||o,s=Object(l.useMemo)((function(){return u}),Object.values(u));return Object(l.createElement)(c.Provider,{value:s},r)}return n=[].concat(Object(m.a)(n),[r]),u.displayName=t+"Provider",[u,function(n,i){var u=(null===i||void 0===i?void 0:i[e][a])||o,c=Object(l.useContext)(u);if(c)return c;if(void 0!==r)return r;throw new Error("`".concat(n,"` must be used within `").concat(t,"`"))}]}var a=function(){var t=n.map((function(e){return Object(l.createContext)(e)}));return function(n){var o=(null===n||void 0===n?void 0:n[e])||t;return Object(l.useMemo)((function(){return Object(h.a)({},"__scope".concat(e),Object(r.a)(Object(r.a)({},n),{},Object(h.a)({},e,o)))}),[n,o])}};return a.scopeName=e,[o,q.apply(void 0,[a].concat(Object(m.a)(t)))]}function q(){for(var e=arguments.length,t=new Array(e),n=0;n1&&t.preventDefault()},onClick:function(t){var n;if(null===(n=e.onClick)||void 0===n||n.call(e,t),a.current&&!t.defaultPrevented){var r=a.current.contains(t.target),o=!0===t.isTrusted;!r&&o&&(a.current.click(),a.current.focus())}}})))})),de=function(e){var t=se("LabelConsumer"),n=t.controlRef;return Object(l.useEffect)((function(){e&&(n.current=e)}),[e,n]),t.id},pe=fe;!function(e,t,n,r){Object.defineProperty(e,t,{get:n,set:r,enumerable:!0,configurable:!0})}({},"useLayoutEffect",(function(){return ve}));var ve=Boolean(null===globalThis||void 0===globalThis?void 0:globalThis.document)?l.useLayoutEffect:function(){},he=["containerRef","style"],me=["container"];function be(e,t,n,r){Object.defineProperty(e,t,{get:n,set:r,enumerable:!0,configurable:!0})}var ye={};be(ye,"Portal",(function(){return ge})),be(ye,"UnstablePortal",(function(){return we})),be(ye,"Root",(function(){return _e}));var ge=Object(l.forwardRef)((function(e,t){var n,o,a=e.containerRef,s=e.style,f=Object(i.a)(e,he),p=null!==(n=null===a||void 0===a?void 0:a.current)&&void 0!==n?n:null===globalThis||void 0===globalThis||null===(o=globalThis.document)||void 0===o?void 0:o.body,v=Object(l.useState)({}),h=Object(u.a)(v,2)[1];return ve((function(){h({})}),[]),p?d.a.createPortal(Object(l.createElement)(ee.div,Object(c.a)({"data-radix-portal":""},f,{ref:t,style:p===document.body?Object(r.a)({position:"absolute",top:0,left:0,zIndex:2147483647},s):void 0})),p):null})),we=Object(l.forwardRef)((function(e,t){var n,r=e.container,o=void 0===r?null===globalThis||void 0===globalThis||null===(n=globalThis.document)||void 0===n?void 0:n.body:r,a=Object(i.a)(e,me);return o?d.a.createPortal(Object(l.createElement)(ee.div,Object(c.a)({},a,{ref:t})),o):null})),_e=ge;function Oe(e,t,n,r){Object.defineProperty(e,t,{get:n,set:r,enumerable:!0,configurable:!0})}var Se={};Oe(Se,"DirectionProvider",(function(){return je})),Oe(Se,"useDirection",(function(){return ke})),Oe(Se,"Provider",(function(){return Ce}));var Ee=Object(l.createContext)(void 0),je=function(e){var t=e.dir,n=e.children;return Object(l.createElement)(Ee.Provider,{value:t},n)};function ke(e){var t=Object(l.useContext)(Ee);return e||t||"ltr"}var Ce=je,xe=n(17);function Te(e){var t=e.prop,n=e.defaultProp,r=e.onChange,o=void 0===r?function(){}:r,a=function(e){var t=e.defaultProp,n=e.onChange,r=Object(l.useState)(t),o=Object(u.a)(r,1)[0],a=Object(l.useRef)(o),i=Object(xe.a)(n);return Object(l.useEffect)((function(){a.current!==o&&(i(o),a.current=o)}),[o,a,i]),r}({defaultProp:n,onChange:o}),i=Object(u.a)(a,2),c=i[0],s=i[1],f=void 0!==t,d=f?t:c,p=Object(xe.a)(o);return[d,Object(l.useCallback)((function(e){if(f){var n="function"===typeof e?e(t):e;n!==t&&p(n)}else s(e)}),[f,t,s,p])]}!function(e,t,n,r){Object.defineProperty(e,t,{get:n,set:r,enumerable:!0,configurable:!0})}({},"useControllableState",(function(){return Te}));function Re(e){var t=Object(l.useRef)({value:e,previous:e});return Object(l.useMemo)((function(){return t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous}),[e])}function Pe(e,t,n,r){Object.defineProperty(e,t,{get:n,set:r,enumerable:!0,configurable:!0})}!function(e,t,n,r){Object.defineProperty(e,t,{get:n,set:r,enumerable:!0,configurable:!0})}({},"usePrevious",(function(){return Re}));var Ae={};Pe(Ae,"VisuallyHidden",(function(){return Le})),Pe(Ae,"Root",(function(){return Ne}));var Le=Object(l.forwardRef)((function(e,t){return Object(l.createElement)(ee.span,Object(c.a)({},e,{ref:t,style:Object(r.a)({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"},e.style)}))})),Ne=Le,Me=n(36),De=n(64),Ie=["__scopeSelect","disabled","aria-labelledby"],ze=["__scopeSelect","className","style","children","placeholder"],Fe=["__scopeSelect","children"],Ve=["__scopeSelect","onCloseAutoFocus"],Ue=["__scopeSelect"],Be=["__scopeSelect"],We=["__scopeSelect"],He=["__scopeSelect","value","disabled","textValue"],Ye=["__scopeSelect","className","style"],Ke=["__scopeSelect"],qe=["__scopeSelect","onAutoScroll"],Xe=["__scopeSelect"],$e=["value"];function Qe(e,t,n,r){Object.defineProperty(e,t,{get:n,set:r,enumerable:!0,configurable:!0})}var Ge={};Qe(Ge,"createSelectScope",(function(){return ct})),Qe(Ge,"Select",(function(){return pt})),Qe(Ge,"SelectTrigger",(function(){return ht})),Qe(Ge,"SelectValue",(function(){return bt})),Qe(Ge,"SelectIcon",(function(){return yt})),Qe(Ge,"SelectContent",(function(){return wt})),Qe(Ge,"SelectViewport",(function(){return xt})),Qe(Ge,"SelectGroup",(function(){return Nt})),Qe(Ge,"SelectLabel",(function(){return Dt})),Qe(Ge,"SelectItem",(function(){return Bt})),Qe(Ge,"SelectItemText",(function(){return Ht})),Qe(Ge,"SelectItemIndicator",(function(){return Kt})),Qe(Ge,"SelectScrollUpButton",(function(){return Xt})),Qe(Ge,"SelectScrollDownButton",(function(){return Qt})),Qe(Ge,"SelectSeparator",(function(){return Zt})),Qe(Ge,"Root",(function(){return nn})),Qe(Ge,"Trigger",(function(){return rn})),Qe(Ge,"Value",(function(){return on})),Qe(Ge,"Icon",(function(){return an})),Qe(Ge,"Content",(function(){return un})),Qe(Ge,"Viewport",(function(){return cn})),Qe(Ge,"Group",(function(){return ln})),Qe(Ge,"Label",(function(){return sn})),Qe(Ge,"Item",(function(){return fn})),Qe(Ge,"ItemText",(function(){return dn})),Qe(Ge,"ItemIndicator",(function(){return pn})),Qe(Ge,"ScrollUpButton",(function(){return vn})),Qe(Ge,"ScrollDownButton",(function(){return hn})),Qe(Ge,"Separator",(function(){return mn}));var Ze=[" ","Enter","ArrowUp","ArrowDown"],Je=[" ","Enter"],et="Select",tt=M(et),nt=Object(u.a)(tt,3),rt=nt[0],ot=nt[1],at=K(et,[nt[2]]),it=Object(u.a)(at,2),ut=it[0],ct=it[1],lt=ut(et),st=Object(u.a)(lt,2),ft=st[0],dt=st[1],pt=function(e){var t=e.__scopeSelect,n=e.children,r=e.open,o=e.defaultOpen,a=e.onOpenChange,i=e.value,c=e.defaultValue,s=e.onValueChange,f=e.dir,d=e.name,p=e.autoComplete,v=Object(l.useState)(null),h=Object(u.a)(v,2),m=h[0],b=h[1],y=Object(l.useState)(null),g=Object(u.a)(y,2),w=g[0],_=g[1],O=Object(l.useState)(!1),S=Object(u.a)(O,2),E=S[0],j=S[1],k=ke(f),C=Te({prop:r,defaultProp:o,onChange:a}),x=Object(u.a)(C,2),T=x[0],R=void 0!==T&&T,P=x[1],A=Te({prop:i,defaultProp:c,onChange:s}),L=Object(u.a)(A,2),N=L[0],M=L[1],D=!m||Boolean(m.closest("form")),I=Object(l.useState)(null),z=Object(u.a)(I,2),F=z[0],V=z[1],U=Object(l.useRef)(null);return Object(l.createElement)(ft,{scope:t,trigger:m,onTriggerChange:b,valueNode:w,onValueNodeChange:_,valueNodeHasChildren:E,onValueNodeHasChildrenChange:j,contentId:Object(Q.a)(),value:N,onValueChange:M,open:R,onOpenChange:P,dir:k,bubbleSelect:F,triggerPointerDownPosRef:U},Object(l.createElement)(rt.Provider,{scope:t},n),D?Object(l.createElement)(Jt,{ref:V,"aria-hidden":!0,tabIndex:-1,name:d,autoComplete:p,value:N,onChange:function(e){return M(e.target.value)}}):null)},vt="SelectTrigger",ht=Object(l.forwardRef)((function(e,t){var n=e.__scopeSelect,r=e.disabled,o=void 0!==r&&r,a=e["aria-labelledby"],s=Object(i.a)(e,Ie),f=dt(vt,n),d=V(t,f.onTriggerChange),p=ot(n),h=de(f.trigger),m=a||h,b=en((function(e){var t=p().filter((function(e){return!e.disabled})),n=t.find((function(e){return e.value===f.value})),r=tn(t,e,n);void 0!==r&&f.onValueChange(r.value)})),y=Object(u.a)(b,3),g=y[0],w=y[1],_=y[2],O=function(){o||(f.onOpenChange(!0),_())};return Object(l.createElement)(ee.button,Object(c.a)({type:"button",role:"combobox","aria-controls":f.contentId,"aria-expanded":f.open,"aria-autocomplete":"none","aria-labelledby":m,dir:f.dir,"data-state":f.open?"open":"closed",disabled:o,"data-disabled":o?"":void 0,"data-placeholder":void 0===f.value?"":void 0},s,{ref:d,onPointerDown:Object(v.a)(s.onPointerDown,(function(e){e.target.releasePointerCapture(e.pointerId),0===e.button&&!1===e.ctrlKey&&(O(),f.triggerPointerDownPosRef.current={x:Math.round(e.pageX),y:Math.round(e.pageY)},e.preventDefault())})),onKeyDown:Object(v.a)(s.onKeyDown,(function(e){var t=""!==g.current;e.ctrlKey||e.altKey||e.metaKey||1!==e.key.length||w(e.key),t&&" "===e.key||Ze.includes(e.key)&&(O(),e.preventDefault())}))}))})),mt="SelectValue",bt=Object(l.forwardRef)((function(e,t){var n=e.__scopeSelect,r=(e.className,e.style,e.children),o=e.placeholder,a=Object(i.a)(e,ze),u=dt(mt,n),s=u.onValueNodeHasChildrenChange,f=void 0!==r,d=V(t,u.onValueNodeChange);return ve((function(){s(f)}),[s,f]),Object(l.createElement)(ee.span,Object(c.a)({},a,{ref:d,style:{pointerEvents:"none"}}),void 0===u.value&&void 0!==o?o:r)})),yt=Object(l.forwardRef)((function(e,t){e.__scopeSelect;var n=e.children,r=Object(i.a)(e,Fe);return Object(l.createElement)(ee.span,Object(c.a)({"aria-hidden":!0},r,{ref:t}),n||"\u25bc")})),gt="SelectContent",wt=Object(l.forwardRef)((function(e,t){var n=dt(gt,e.__scopeSelect),r=Object(l.useState)(),o=Object(u.a)(r,2),a=o[0],i=o[1];return ve((function(){i(new DocumentFragment)}),[]),n.open?Object(l.createElement)(kt,Object(c.a)({},e,{ref:t})):a?Object(f.createPortal)(Object(l.createElement)(Et,{scope:e.__scopeSelect},Object(l.createElement)(rt.Slot,{scope:e.__scopeSelect},Object(l.createElement)("div",null,e.children))),a):null})),_t=10,Ot=ut(gt),St=Object(u.a)(Ot,2),Et=St[0],jt=St[1],kt=Object(l.forwardRef)((function(e,t){var n=e.__scopeSelect,s=e.onCloseAutoFocus,f=Object(i.a)(e,Ve),d=dt(gt,n),h=Object(l.useState)(null),m=Object(u.a)(h,2),b=m[0],y=m[1],g=Object(l.useState)(null),w=Object(u.a)(g,2),_=w[0],O=w[1],S=Object(l.useState)(null),E=Object(u.a)(S,2),j=E[0],k=E[1],C=V(t,(function(e){return O(e)})),x=Object(l.useState)(null),T=Object(u.a)(x,2),R=T[0],P=T[1],A=Object(l.useState)(null),L=Object(u.a)(A,2),N=L[0],M=L[1],D=ot(n),I=Object(l.useState)(!1),z=Object(u.a)(I,2),F=z[0],U=z[1],B=Object(l.useRef)(!0),W=Object(l.useRef)(!1),H=Object(l.useRef)(!1);Object(l.useEffect)((function(){if(_)return Object(Me.a)(_)}),[_]);var Y=Object(l.useCallback)((function(e){var t,n=D().map((function(e){return e.ref.current})),r=Object(a.a)(n),i=r[0],c=r.slice(1).slice(-1),l=Object(u.a)(c,1)[0],s=document.activeElement,f=Object(o.a)(e);try{for(f.s();!(t=f.n()).done;){var d=t.value;if(d===s)return;if(null===d||void 0===d||d.scrollIntoView({block:"nearest"}),d===i&&j&&(j.scrollTop=0),d===l&&j&&(j.scrollTop=j.scrollHeight),null===d||void 0===d||d.focus(),document.activeElement!==s)return}}catch(p){f.e(p)}finally{f.f()}}),[D,j]),K=Object(l.useCallback)((function(){if(d.trigger&&d.valueNode&&b&&_&&j&&R&&N){var e=d.trigger.getBoundingClientRect(),t=_.getBoundingClientRect(),n=d.valueNode.getBoundingClientRect(),r=N.getBoundingClientRect();if("rtl"!==d.dir){var o=r.left-t.left,a=n.left-o,i=e.left-a,u=e.width+i,c=Math.max(u,t.width),l=window.innerWidth-_t,s=p(a,[_t,l-c]);b.style.minWidth=u+"px",b.style.left=s+"px"}else{var f=t.right-r.right,v=window.innerWidth-n.right-f,h=window.innerWidth-e.right-v,m=e.width+h,y=Math.max(m,t.width),g=window.innerWidth-_t,w=p(v,[_t,g-y]);b.style.minWidth=m+"px",b.style.right=w+"px"}var O=D(),S=window.innerHeight-20,E=j.scrollHeight,k=window.getComputedStyle(_),C=parseInt(k.borderTopWidth,10),x=parseInt(k.paddingTop,10),T=parseInt(k.borderBottomWidth,10),P=C+x+E+parseInt(k.paddingBottom,10)+T,A=Math.min(5*R.offsetHeight,P),L=window.getComputedStyle(j),M=parseInt(L.paddingTop,10),I=parseInt(L.paddingBottom,10),z=e.top+e.height/2-_t,F=S-z,V=R.offsetHeight/2,B=C+x+(R.offsetTop+V),H=P-B;if(B<=z){var Y=R===O[O.length-1].ref.current;b.style.bottom="0px";var K=_.clientHeight-j.offsetTop-j.offsetHeight,q=B+Math.max(F,V+(Y?I:0)+K+T);b.style.height=q+"px"}else{var X=R===O[0].ref.current;b.style.top="0px";var $=Math.max(z,C+j.offsetTop+(X?M:0)+V)+H;b.style.height=$+"px",j.scrollTop=B-z+j.offsetTop}b.style.margin="".concat(_t,"px 0"),b.style.minHeight=A+"px",b.style.maxHeight=S+"px",U(!0),requestAnimationFrame((function(){return W.current=!0}))}}),[D,d.trigger,d.valueNode,b,_,j,R,N,d.dir]);ve((function(){return K()}),[K]);var q=Object(l.useCallback)((function(){return Y([R,_])}),[Y,R,_]);Object(l.useEffect)((function(){F&&q()}),[F,q]);var Q=Object(l.useCallback)((function(e){e&&!0===B.current&&(K(),q(),B.current=!1)}),[K,q]),G=d.onOpenChange,Z=d.triggerPointerDownPosRef;Object(l.useEffect)((function(){if(_){var e={x:0,y:0},t=function(t){var n,r,o,a;e={x:Math.abs(Math.round(t.pageX)-(null!==(n=null===(r=Z.current)||void 0===r?void 0:r.x)&&void 0!==n?n:0)),y:Math.abs(Math.round(t.pageY)-(null!==(o=null===(a=Z.current)||void 0===a?void 0:a.y)&&void 0!==o?o:0))}},n=function(n){e.x<=10&&e.y<=10?n.preventDefault():_.contains(n.target)||G(!1),document.removeEventListener("pointermove",t),Z.current=null};return null!==Z.current&&(document.addEventListener("pointermove",t),document.addEventListener("pointerup",n,{capture:!0,once:!0})),function(){document.removeEventListener("pointermove",t),document.removeEventListener("pointerup",n,{capture:!0})}}}),[_,G,Z]),Object(l.useEffect)((function(){var e=function(){return G(!1)};return window.addEventListener("blur",e),window.addEventListener("resize",e),function(){window.removeEventListener("blur",e),window.removeEventListener("resize",e)}}),[G]);var J=en((function(e){var t=D().filter((function(e){return!e.disabled})),n=t.find((function(e){return e.ref.current===document.activeElement})),r=tn(t,e,n);r&&setTimeout((function(){return r.ref.current.focus()}))})),ee=Object(u.a)(J,2),te=ee[0],ne=ee[1],re=Object(l.useCallback)((function(e,t,n){var r=!H.current&&!n;(void 0!==d.value&&d.value===t||r)&&(P(e),r&&(H.current=!0))}),[d.value]),oe=Object(l.useCallback)((function(){return null===_||void 0===_?void 0:_.focus()}),[_]),ae=Object(l.useCallback)((function(e,t,n){var r=!H.current&&!n;(void 0!==d.value&&d.value===t||r)&&M(e)}),[d.value]);return Object(l.createElement)(Et,{scope:n,contentWrapper:b,content:_,viewport:j,onViewportChange:k,itemRefCallback:re,selectedItem:R,onItemLeave:oe,itemTextRefCallback:ae,selectedItemText:N,onScrollButtonChange:Q,isPositioned:F,shouldExpandOnScrollRef:W,searchRef:te},Object(l.createElement)(ge,null,Object(l.createElement)(De.a,null,Object(l.createElement)("div",{ref:y,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:0}},Object(l.createElement)($.a,{asChild:!0,trapped:d.open,onMountAutoFocus:function(e){e.preventDefault()},onUnmountAutoFocus:Object(v.a)(s,(function(e){var t;null===(t=d.trigger)||void 0===t||t.focus({preventScroll:!0}),e.preventDefault()}))},Object(l.createElement)(X.a,Object(c.a)({role:"listbox",id:d.contentId,"data-state":d.open?"open":"closed",dir:d.dir,onContextMenu:function(e){return e.preventDefault()}},f,{ref:C,style:Object(r.a)({display:"flex",flexDirection:"column",boxSizing:"border-box",maxHeight:"100%",outline:"none"},f.style),disableOutsidePointerEvents:!0,onFocusOutside:function(e){return e.preventDefault()},onDismiss:function(){return d.onOpenChange(!1)},onKeyDown:Object(v.a)(f.onKeyDown,(function(e){var t=e.ctrlKey||e.altKey||e.metaKey;if("Tab"===e.key&&e.preventDefault(),t||1!==e.key.length||ne(e.key),["ArrowUp","ArrowDown","Home","End"].includes(e.key)){var n=D().filter((function(e){return!e.disabled})).map((function(e){return e.ref.current}));if(["ArrowUp","End"].includes(e.key)&&(n=n.slice().reverse()),["ArrowUp","ArrowDown"].includes(e.key)){var r=e.target,o=n.indexOf(r);n=n.slice(o+1)}setTimeout((function(){return Y(n)})),e.preventDefault()}}))})))))))})),Ct="SelectViewport",xt=Object(l.forwardRef)((function(e,t){var n=e.__scopeSelect,o=Object(i.a)(e,Ue),a=jt(Ct,n),u=V(t,a.onViewportChange),s=Object(l.useRef)(0);return Object(l.createElement)(l.Fragment,null,Object(l.createElement)("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"}}),Object(l.createElement)(rt.Slot,{scope:n},Object(l.createElement)(ee.div,Object(c.a)({"data-radix-select-viewport":"",role:"presentation"},o,{ref:u,style:Object(r.a)({position:"relative",flex:1,overflow:"auto"},o.style),onScroll:Object(v.a)(o.onScroll,(function(e){var t=e.currentTarget,n=a.contentWrapper,r=a.shouldExpandOnScrollRef;if(null!==r&&void 0!==r&&r.current&&n){var o=Math.abs(s.current-t.scrollTop);if(o>0){var i=window.innerHeight-20,u=parseFloat(n.style.minHeight),c=parseFloat(n.style.height),l=Math.max(u,c);if(l0?p:0,n.style.justifyContent="flex-end")}}}s.current=t.scrollTop}))}))))})),Tt="SelectGroup",Rt=ut(Tt),Pt=Object(u.a)(Rt,2),At=Pt[0],Lt=Pt[1],Nt=Object(l.forwardRef)((function(e,t){var n=e.__scopeSelect,r=Object(i.a)(e,Be),o=Object(Q.a)();return Object(l.createElement)(At,{scope:n,id:o},Object(l.createElement)(ee.div,Object(c.a)({role:"group","aria-labelledby":o},r,{ref:t})))})),Mt="SelectLabel",Dt=Object(l.forwardRef)((function(e,t){var n=e.__scopeSelect,r=Object(i.a)(e,We),o=Lt(Mt,n);return Object(l.createElement)(ee.div,Object(c.a)({id:o.id},r,{ref:t}))})),It="SelectItem",zt=ut(It),Ft=Object(u.a)(zt,2),Vt=Ft[0],Ut=Ft[1],Bt=Object(l.forwardRef)((function(e,t){var n=e.__scopeSelect,r=e.value,o=e.disabled,a=void 0!==o&&o,s=e.textValue,f=Object(i.a)(e,He),d=dt(It,n),p=jt(It,n),h=d.value===r,m=Object(l.useState)(null!==s&&void 0!==s?s:""),b=Object(u.a)(m,2),y=b[0],g=b[1],w=Object(l.useState)(!1),_=Object(u.a)(w,2),O=_[0],S=_[1],E=V(t,(function(e){var t;return null===(t=p.itemRefCallback)||void 0===t?void 0:t.call(p,e,r,a)})),j=Object(Q.a)(),k=function(){a||(d.onValueChange(r),d.onOpenChange(!1))};return Object(l.createElement)(Vt,{scope:n,value:r,disabled:a,textId:j,isSelected:h,onItemTextChange:Object(l.useCallback)((function(e){g((function(t){var n;return t||(null!==(n=null===e||void 0===e?void 0:e.textContent)&&void 0!==n?n:"").trim()}))}),[])},Object(l.createElement)(rt.ItemSlot,{scope:n,value:r,disabled:a,textValue:y},Object(l.createElement)(ee.div,Object(c.a)({role:"option","aria-labelledby":j,"data-highlighted":O?"":void 0,"aria-selected":h&&O,"data-state":h?"checked":"unchecked","aria-disabled":a||void 0,"data-disabled":a?"":void 0,tabIndex:a?void 0:-1},f,{ref:E,onFocus:Object(v.a)(f.onFocus,(function(){return S(!0)})),onBlur:Object(v.a)(f.onBlur,(function(){return S(!1)})),onPointerUp:Object(v.a)(f.onPointerUp,k),onPointerMove:Object(v.a)(f.onPointerMove,(function(e){var t;a?null===(t=p.onItemLeave)||void 0===t||t.call(p):e.currentTarget.focus({preventScroll:!0})})),onPointerLeave:Object(v.a)(f.onPointerLeave,(function(e){var t;e.currentTarget===document.activeElement&&(null===(t=p.onItemLeave)||void 0===t||t.call(p))})),onKeyDown:Object(v.a)(f.onKeyDown,(function(e){var t;""!==(null===(t=p.searchRef)||void 0===t?void 0:t.current)&&" "===e.key||(Je.includes(e.key)&&k()," "===e.key&&e.preventDefault())}))}))))})),Wt="SelectItemText",Ht=Object(l.forwardRef)((function(e,t){var n,r=e.__scopeSelect,o=(e.className,e.style,Object(i.a)(e,Ye)),a=dt(Wt,r),u=jt(Wt,r),s=Ut(Wt,r),d=Object(l.useRef)(null),p=V(t,d,s.onItemTextChange,(function(e){var t;return null===(t=u.itemTextRefCallback)||void 0===t?void 0:t.call(u,e,s.value,s.disabled)}));return Object(l.createElement)(l.Fragment,null,Object(l.createElement)(ee.span,Object(c.a)({id:s.textId},o,{ref:p})),s.isSelected&&a.valueNode&&!a.valueNodeHasChildren?Object(f.createPortal)(o.children,a.valueNode):null,a.bubbleSelect?Object(f.createPortal)(Object(l.createElement)("option",{value:s.value},null===(n=d.current)||void 0===n?void 0:n.textContent),a.bubbleSelect):null)})),Yt="SelectItemIndicator",Kt=Object(l.forwardRef)((function(e,t){var n=e.__scopeSelect,r=Object(i.a)(e,Ke);return Ut(Yt,n).isSelected?Object(l.createElement)(ee.span,Object(c.a)({"aria-hidden":!0},r,{ref:t})):null})),qt="SelectScrollUpButton",Xt=Object(l.forwardRef)((function(e,t){var n=jt(qt,e.__scopeSelect),r=Object(l.useState)(!1),o=Object(u.a)(r,2),a=o[0],i=o[1],s=V(t,n.onScrollButtonChange);return ve((function(){if(n.viewport&&n.isPositioned){var e=function(){var e=t.scrollTop>0;i(e)},t=n.viewport;return e(),t.addEventListener("scroll",e),function(){return t.removeEventListener("scroll",e)}}}),[n.viewport,n.isPositioned]),a?Object(l.createElement)(Gt,Object(c.a)({},e,{ref:s,onAutoScroll:function(){var e=n.viewport,t=n.selectedItem;e&&t&&(e.scrollTop=e.scrollTop-t.offsetHeight)}})):null})),$t="SelectScrollDownButton",Qt=Object(l.forwardRef)((function(e,t){var n=jt($t,e.__scopeSelect),r=Object(l.useState)(!1),o=Object(u.a)(r,2),a=o[0],i=o[1],s=V(t,n.onScrollButtonChange);return ve((function(){if(n.viewport&&n.isPositioned){var e=function(){var e=t.scrollHeight-t.clientHeight,n=Math.ceil(t.scrollTop)1&&Array.from(t).every((function(e){return e===t[0]}))?t[0]:t,i=n?e.indexOf(n):-1,u=(r=e,o=Math.max(i,0),r.map((function(e,t){return r[(o+t)%r.length]})));1===a.length&&(u=u.filter((function(e){return e!==n})));var c=u.find((function(e){return e.textValue.toLowerCase().startsWith(a.toLowerCase())}));return c!==n?c:void 0}var nn=pt,rn=ht,on=bt,an=yt,un=wt,cn=xt,ln=Nt,sn=Dt,fn=Bt,dn=Ht,pn=Kt,vn=Xt,hn=Qt,mn=Zt},function(e,t,n){"use strict";n.d(t,"a",(function(){return o}));var r=n(29);function o(e,t){if(e){if("string"===typeof e)return Object(r.a)(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Object(r.a)(e,t):void 0}}},function(e,t,n){"use strict";n.d(t,"a",(function(){return i}));var r=n(2),o=n(0);function a(e){var t=o.useRef(e);return o.useEffect((function(){t.current=e})),o.useMemo((function(){return function(){for(var e,n,r=arguments.length,o=new Array(r),a=0;a1&&void 0!==arguments[1]?arguments[1]:[],n=[];function a(t,r){var a=Object(u.createContext)(r),i=n.length;function c(t){var n=t.scope,r=t.children,c=Object(o.a)(t,b),l=(null===n||void 0===n?void 0:n[e][i])||a,s=Object(u.useMemo)((function(){return c}),Object.values(c));return Object(u.createElement)(l.Provider,{value:s},r)}return n=[].concat(Object(h.a)(n),[r]),c.displayName=t+"Provider",[c,function(n,o){var c=(null===o||void 0===o?void 0:o[e][i])||a,l=Object(u.useContext)(c);if(l)return l;if(void 0!==r)return r;throw new Error("`".concat(n,"` must be used within `").concat(t,"`"))}]}var i=function(){var t=n.map((function(e){return Object(u.createContext)(e)}));return function(n){var o=(null===n||void 0===n?void 0:n[e])||t;return Object(u.useMemo)((function(){return Object(v.a)({},"__scope".concat(e),Object(r.a)(Object(r.a)({},n),{},Object(v.a)({},e,o)))}),[n,o])}};return i.scopeName=e,[a,O.apply(void 0,[i].concat(Object(h.a)(t)))]}function O(){for(var e=arguments.length,t=new Array(e),n=0;n1?u.Children.only(null):null}));m.displayName="SlotClone";var b=function(e){var t=e.children;return u.createElement(u.Fragment,null,t)};function y(e){return u.isValidElement(e)&&e.type===b}var g,w=n(38),_=n(13),O=["children","width","height"],S=u.forwardRef((function(e,t){var n=e.children,r=e.width,a=void 0===r?10:r,i=e.height,c=void 0===i?5:i,l=Object(o.a)(e,O);return u.createElement(_.a.svg,Object(d.a)({},l,{ref:t,width:a,height:c,viewBox:"0 0 30 10",preserveAspectRatio:"none"}),e.asChild?n:u.createElement("polygon",{points:"0,0 30,0 15,10"}))})),E=n(30);var j=new Map;function k(){var e=[];j.forEach((function(t,n){var r,o,a=n.getBoundingClientRect();o=a,((r=t.rect).width!==o.width||r.height!==o.height||r.top!==o.top||r.right!==o.right||r.bottom!==o.bottom||r.left!==o.left)&&(t.rect=a,e.push(t))})),e.forEach((function(e){e.callbacks.forEach((function(t){return t(e.rect)}))})),g=requestAnimationFrame(k)}function C(e){var t=u.useState(),n=Object(a.a)(t,2),r=n[0],o=n[1];return u.useEffect((function(){if(e){var t=function(e,t){var n=j.get(e);return void 0===n?(j.set(e,{rect:{},callbacks:[t]}),1===j.size&&(g=requestAnimationFrame(k))):(n.callbacks.push(t),t(e.getBoundingClientRect())),function(){var n=j.get(e);if(void 0!==n){var r=n.callbacks.indexOf(t);r>-1&&n.callbacks.splice(r,1),0===n.callbacks.length&&(j.delete(e),0===j.size&&cancelAnimationFrame(g))}}}(e,o);return function(){o(void 0),t()}}}),[e]),r}var x=n(21),T=n(10);function R(e,t,n){var r=e["x"===n?"left":"top"],o="x"===n?"width":"height",a=e[o],i=t[o];return{before:r-i,start:r,center:r+(a-i)/2,end:r+a-i,after:r+a}}function P(e){return{position:"absolute",top:0,left:0,minWidth:"max-content",willChange:"transform",transform:"translate3d(".concat(Math.round(e.x+window.scrollX),"px, ").concat(Math.round(e.y+window.scrollY),"px, 0)")}}function A(e,t,n,r,o){var a="top"===t||"bottom"===t,i=o?o.width:0,u=o?o.height:0,c=i/2+r,l="",s="";return a?(l={start:"".concat(c,"px"),center:"center",end:e.width-c+"px"}[n],s="top"===t?"".concat(e.height+u,"px"):-u+"px"):(l="left"===t?"".concat(e.width+u,"px"):-u+"px",s={start:"".concat(c,"px"),center:"center",end:e.height-c+"px"}[n]),"".concat(l," ").concat(s)}var L={position:"fixed",top:0,left:0,opacity:0,transform:"translate3d(0, -200%, 0)"},N={position:"absolute",opacity:0};function M(e){var t,n=e.popperSize,r=e.arrowSize,o=e.arrowOffset,a=e.side,i=e.align,u=(n.width-r.width)/2,c=(n.height-r.width)/2,l={top:0,right:90,bottom:180,left:-90}[a],s=Math.max(r.width,r.height),f=(t={width:"".concat(s,"px"),height:"".concat(s,"px"),transform:"rotate(".concat(l,"deg)"),willChange:"transform",position:"absolute"},Object(T.a)(t,a,"100%"),Object(T.a)(t,"direction",function(e,t){return("top"!==e&&"right"!==e||"end"!==t)&&("bottom"!==e&&"left"!==e||"end"===t)?"ltr":"rtl"}(a,i)),t);return"top"!==a&&"bottom"!==a||("start"===i&&(f.left="".concat(o,"px")),"center"===i&&(f.left="".concat(u,"px")),"end"===i&&(f.right="".concat(o,"px"))),"left"!==a&&"right"!==a||("start"===i&&(f.top="".concat(o,"px")),"center"===i&&(f.top="".concat(c,"px")),"end"===i&&(f.bottom="".concat(o,"px"))),f}function D(e){return{top:"bottom",right:"left",bottom:"top",left:"right"}[e]}function I(e,t){return{top:e.topt.right,bottom:e.bottom>t.bottom,left:e.left2&&void 0!==arguments[2]?arguments[2]:0,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,o=arguments.length>4?arguments[4]:void 0,a=o?o.height:0,i=R(t,e,"x"),u=R(t,e,"y"),c=u.before-n-a,l=u.after+n+a,s=i.before-n-a,f=i.after+n+a;return{top:{start:{x:i.start+r,y:c},center:{x:i.center,y:c},end:{x:i.end-r,y:c}},right:{start:{x:f,y:u.start+r},center:{x:f,y:u.center},end:{x:f,y:u.end-r}},bottom:{start:{x:i.start+r,y:l},center:{x:i.center,y:l},end:{x:i.end-r,y:l}},left:{start:{x:s,y:u.start+r},center:{x:s,y:u.center},end:{x:s,y:u.end-r}}}}(n,t,l,d,o),g=y[u][s];if(!1===v){var w=P(g),_=N;return o&&(_=M({popperSize:n,arrowSize:o,arrowOffset:i,side:u,align:s})),{popperStyles:Object(r.a)(Object(r.a)({},w),{},{"--radix-popper-transform-origin":A(n,u,s,i,o)}),arrowStyles:_,placedSide:u,placedAlign:s}}var O,S,E=DOMRect.fromRect(Object(r.a)(Object(r.a)({},n),g)),j=(O=h,S=b,DOMRect.fromRect({width:O.width-2*S,height:O.height-2*S,x:O.left+S,y:O.top+S})),k=I(E,j),C=y[D(u)][s],x=function(e,t,n){var r=D(e);return t[e]&&!n[r]?r:e}(u,k,I(DOMRect.fromRect(Object(r.a)(Object(r.a)({},n),C)),j)),T=function(e,t,n,r,o){var a="top"===n||"bottom"===n,i=a?"left":"top",u=a?"right":"bottom",c=a?"width":"height",l=t[c]>e[c];return"start"!==r&&"center"!==r||!(o[i]&&l||o[u]&&!l)?"end"!==r&&"center"!==r||!(o[u]&&l||o[i]&&!l)?r:"start":"end"}(n,t,u,s,k),z=P(y[x][T]),F=N;return o&&(F=M({popperSize:n,arrowSize:o,arrowOffset:i,side:x,align:T})),{popperStyles:Object(r.a)(Object(r.a)({},z),{},{"--radix-popper-transform-origin":A(n,x,T,i,o)}),arrowStyles:F,placedSide:x,placedAlign:T}}({anchorRect:k,popperSize:U,arrowSize:K,arrowOffset:S,side:c,sideOffset:l,align:p,alignOffset:v,shouldAvoidCollisions:b,collisionBoundariesRect:$?DOMRect.fromRect(Object(r.a)(Object(r.a)({},$),{},{x:0,y:0})):void 0,collisionTolerance:h}),G=Q.popperStyles,J=Q.arrowStyles,ee=Q.placedSide,te=Q.placedAlign,ne=void 0!==ee;return u.createElement("div",{style:G,"data-radix-popper-content-wrapper":""},u.createElement(Z,{scope:n,arrowStyles:J,onArrowChange:Y,onArrowOffsetChange:j},u.createElement(_.a.div,Object(d.a)({"data-side":ee,"data-align":te},y,{style:Object(r.a)(Object(r.a)({},y.style),{},{animation:ne?void 0:"none"}),ref:q}))))})),te=function(e){var t=e.__scopePopper,n=e.children,r=u.useState(null),o=Object(a.a)(r,2),i=o[0],c=o[1];return u.createElement(q,{scope:t,anchor:i,onAnchorChange:c},n)},ne=$,re=ee,oe=u.forwardRef((function(e,t){var n=e.__scopePopper,a=e.offset,i=Object(o.a)(e,V),c=J("PopperArrow",n),l=c.onArrowOffsetChange;return u.useEffect((function(){return l(a)}),[l,a]),u.createElement("span",{style:Object(r.a)(Object(r.a)({},c.arrowStyles),{},{pointerEvents:"none"})},u.createElement("span",{ref:c.onArrowChange,style:{display:"inline-block",verticalAlign:"top",pointerEvents:"auto"}},u.createElement(S,Object(d.a)({},i,{ref:t,style:Object(r.a)(Object(r.a)({},i.style),{},{display:"block"})}))))})),ae=n(37),ie=n(31),ue=n(42),ce=n(25),le=n(8),se=["__scopeTooltip"],fe=["forceMount"],de=["__scopeTooltip","children","aria-label","portalled"],pe=["__scopeTooltip"],ve=Object(x.b)("Tooltip",[H]),he=Object(a.a)(ve,2),me=he[0],be=(he[1],H()),ye=me("TooltipProvider",{isOpenDelayed:!0,delayDuration:700,onOpen:function(){},onClose:function(){}}),ge=Object(a.a)(ye,2),we=ge[0],_e=ge[1],Oe=me("Tooltip"),Se=Object(a.a)(Oe,2),Ee=Se[0],je=Se[1],ke=u.forwardRef((function(e,t){var n=e.__scopeTooltip,r=Object(o.a)(e,se),a=je("TooltipTrigger",n),i=be(n),c=Object(f.b)(t,a.onTriggerChange),l=u.useRef(!1),s=u.useCallback((function(){return l.current=!1}),[]);return u.useEffect((function(){return function(){return document.removeEventListener("mouseup",s)}}),[s]),u.createElement(ne,Object(d.a)({asChild:!0},i),u.createElement(_.a.button,Object(d.a)({"aria-describedby":a.open?a.contentId:void 0,"data-state":a.stateAttribute},r,{ref:c,onMouseEnter:Object(le.a)(e.onMouseEnter,a.onTriggerEnter),onMouseLeave:Object(le.a)(e.onMouseLeave,a.onClose),onMouseDown:Object(le.a)(e.onMouseDown,(function(){a.onClose(),l.current=!0,document.addEventListener("mouseup",s,{once:!0})})),onFocus:Object(le.a)(e.onFocus,(function(){l.current||a.onOpen()})),onBlur:Object(le.a)(e.onBlur,a.onClose),onClick:Object(le.a)(e.onClick,(function(e){0===e.detail&&a.onClose()}))})))})),Ce=u.forwardRef((function(e,t){var n=e.forceMount,r=Object(o.a)(e,fe),a=je("TooltipContent",e.__scopeTooltip);return u.createElement(ae.a,{present:n||a.open},u.createElement(xe,Object(d.a)({ref:t},r)))})),xe=u.forwardRef((function(e,t){var n=e.__scopeTooltip,a=e.children,i=e["aria-label"],c=e.portalled,l=void 0===c||c,f=Object(o.a)(e,de),p=je("TooltipContent",n),v=be(n),h=l?w.a:u.Fragment,m=p.onClose;return Object(ue.a)((function(){return m()})),u.useEffect((function(){return document.addEventListener("tooltip.open",m),function(){return document.removeEventListener("tooltip.open",m)}}),[m]),u.createElement(h,null,u.createElement(Te,{__scopeTooltip:n}),u.createElement(re,Object(d.a)({"data-state":p.stateAttribute},v,f,{ref:t,style:Object(r.a)(Object(r.a)({},f.style),{},{"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)"})}),u.createElement(b,null,a),u.createElement(s.a,{id:p.contentId,role:"tooltip"},i||a)))}));function Te(e){var t=e.__scopeTooltip,n=je("CheckTriggerMoved",t),r=C(n.trigger),o=null==r?void 0:r.left,a=Object(ie.a)(o),i=null==r?void 0:r.top,c=Object(ie.a)(i),l=n.onClose;return u.useEffect((function(){(void 0!==a&&a!==o||void 0!==c&&c!==i)&&l()}),[l,a,c,o,i]),null}var Re=function(e){var t=e.__scopeTooltip,n=e.delayDuration,r=void 0===n?700:n,o=e.skipDelayDuration,i=void 0===o?300:o,c=e.children,l=u.useState(!0),s=Object(a.a)(l,2),f=s[0],d=s[1],p=u.useRef(0);return u.useEffect((function(){var e=p.current;return function(){return window.clearTimeout(e)}}),[]),u.createElement(we,{scope:t,isOpenDelayed:f,delayDuration:r,onOpen:u.useCallback((function(){window.clearTimeout(p.current),d(!1)}),[]),onClose:u.useCallback((function(){window.clearTimeout(p.current),p.current=window.setTimeout((function(){return d(!0)}),i)}),[i])},c)},Pe=function(e){var t=e.__scopeTooltip,n=e.children,r=e.open,o=e.defaultOpen,s=void 0!==o&&o,f=e.onOpenChange,d=e.delayDuration,p=_e("Tooltip",t),v=be(t),h=u.useState(null),m=Object(a.a)(h,2),b=m[0],y=m[1],g=function(e){var t=u.useState(c()),n=Object(a.a)(t,2),r=n[0],o=n[1];return Object(i.a)((function(){e||o((function(e){return null!=e?e:String(l++)}))}),[e]),e||(r?"radix-".concat(r):"")}(),w=u.useRef(0),_=null!=d?d:p.delayDuration,O=u.useRef(!1),S=p.onOpen,E=p.onClose,j=Object(ce.a)({prop:r,defaultProp:s,onChange:function(e){e&&(document.dispatchEvent(new CustomEvent("tooltip.open")),S()),null==f||f(e)}}),k=Object(a.a)(j,2),C=k[0],x=void 0!==C&&C,T=k[1],R=u.useMemo((function(){return x?O.current?"delayed-open":"instant-open":"closed"}),[x]),P=u.useCallback((function(){window.clearTimeout(w.current),O.current=!1,T(!0)}),[T]),A=u.useCallback((function(){window.clearTimeout(w.current),w.current=window.setTimeout((function(){O.current=!0,T(!0)}),_)}),[_,T]);return u.useEffect((function(){return function(){return window.clearTimeout(w.current)}}),[]),u.createElement(te,v,u.createElement(Ee,{scope:t,contentId:g,open:x,stateAttribute:R,trigger:b,onTriggerChange:y,onTriggerEnter:u.useCallback((function(){p.isOpenDelayed?A():P()}),[p.isOpenDelayed,A,P]),onOpen:u.useCallback(P,[P]),onClose:u.useCallback((function(){window.clearTimeout(w.current),T(!1),E()}),[T,E])},n))},Ae=ke,Le=Ce,Ne=u.forwardRef((function(e,t){var n=e.__scopeTooltip,r=Object(o.a)(e,pe),a=be(n);return u.createElement(oe,Object(d.a)({},a,r,{ref:t}))}))},function(e,t,n){"use strict";n.d(t,"a",(function(){return u}));var r=n(33),o=n(34),a=n(24),i=n(35);function u(e){return Object(r.a)(e)||Object(o.a)(e)||Object(a.a)(e)||Object(i.a)()}},function(e,t,n){"use strict";function r(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n0,B=V>=F,W=function(e){var t=f((function(e){var t=e.target,n=Object(o.a)(x.branches).some((function(e){return e.contains(t)}));B&&!n&&(null==v||v(e),null==j||j(e),e.defaultPrevented||null==k||k())})),n=s.useRef(!1);return s.useEffect((function(){var e=function(e){e.target&&!n.current&&E("dismissableLayer.pointerDownOutside",t,{originalEvent:e}),n.current=!1},r=window.setTimeout((function(){document.addEventListener("pointerdown",e)}),0);return function(){window.clearTimeout(r),document.removeEventListener("pointerdown",e)}}),[t]),{onPointerDownCapture:function(){return n.current=!0}}}(),H=function(e){var t=f((function(e){var t=e.target;Object(o.a)(x.branches).some((function(e){return e.contains(t)}))||(null==h||h(e),null==j||j(e),e.defaultPrevented||null==k||k())})),n=s.useRef(!1);return s.useEffect((function(){var e=function(e){e.target&&!n.current&&E("dismissableLayer.focusOutside",t,{originalEvent:e})};return document.addEventListener("focusin",e),function(){return document.removeEventListener("focusin",e)}}),[t]),{onFocusCapture:function(){return n.current=!0},onBlurCapture:function(){return n.current=!1}}}();return Object(m.a)((function(e){V===x.layers.size-1&&(null==l||l(e),e.defaultPrevented||null==k||k())})),function(e){var t=e.disabled,n=s.useRef(!1);Object(c.a)((function(){if(t){var e=function(){0===--b&&(document.body.style.pointerEvents=d)},r=function(e){n.current="mouse"!==e.pointerType};return 0===b&&(d=document.body.style.pointerEvents),document.body.style.pointerEvents="none",b++,document.addEventListener("pointerup",r),function(){n.current?document.addEventListener("click",e,{once:!0}):e(),document.removeEventListener("pointerup",r)}}}),[t])}({disabled:u}),s.useEffect((function(){P&&(u&&x.layersWithOutsidePointerEventsDisabled.add(P),x.layers.add(P),S())}),[P,u,x]),s.useEffect((function(){return function(){P&&(x.layers.delete(P),x.layersWithOutsidePointerEventsDisabled.delete(P),S())}}),[P,x]),s.useEffect((function(){var e=function(){return N({})};return document.addEventListener("dismissableLayer.update",e),function(){return document.removeEventListener("dismissableLayer.update",e)}}),[]),s.createElement(p.a.div,Object(w.a)({},C,{ref:M,style:Object(r.a)({pointerEvents:U?B?"auto":"none":void 0},e.style),onFocusCapture:Object(g.a)(e.onFocusCapture,H.onFocusCapture),onBlurCapture:Object(g.a)(e.onBlurCapture,H.onBlurCapture),onPointerDownCapture:Object(g.a)(e.onPointerDownCapture,W.onPointerDownCapture)}))})),k=s.forwardRef((function(e,t){var n=s.useContext(O),r=s.useRef(null),o=Object(y.b)(t,r);return s.useEffect((function(){var e=r.current;if(e)return n.branches.add(e),function(){n.branches.delete(e)}}),[n.branches]),s.createElement(p.a.div,Object(w.a)({},e,{ref:o}))})),C=n(21),x=n(12),T=["__scopeToast","hotkey","label"],R=["forceMount","open","defaultOpen","onOpenChange"],P=["__scopeToast","type","duration","open","onClose","onEscapeKeyDown","onSwipeStart","onSwipeMove","onSwipeCancel","onSwipeEnd"],A=["__scopeToast"],L=["__scopeToast"],N=["altText"],M=["__scopeToast"],D=Object(C.b)("Toast"),I=Object(i.a)(D,2),z=I[0],F=(I[1],z("ToastProvider")),V=Object(i.a)(F,2),U=V[0],B=V[1],W=["F8"],H=s.forwardRef((function(e,t){var n=e.__scopeToast,r=e.hotkey,u=void 0===r?W:r,c=e.label,l=void 0===c?"Notifications ({hotkey})":c,f=Object(a.a)(e,T),d=B("ToastViewport",n),v=s.useRef(null),h=s.useRef(null),m=Object(y.b)(t,h,d.onViewportChange),b=u.join("+").replace(/Key/g,"").replace(/Digit/g,"");return s.useEffect((function(){var e=function(e){var t;u.every((function(t){return e[t]||e.code===t}))&&(null===(t=h.current)||void 0===t||t.focus())};return document.addEventListener("keydown",e),function(){return document.removeEventListener("keydown",e)}}),[u]),s.useEffect((function(){var e=v.current,t=h.current;if(e&&t){var n=function(){var e=new Event("toast.viewportPause");t.dispatchEvent(e),d.isClosePausedRef.current=!0},r=function(){var e=new Event("toast.viewportResume");t.dispatchEvent(e),d.isClosePausedRef.current=!1};return e.addEventListener("focusin",n),e.addEventListener("focusout",r),e.addEventListener("pointerenter",n),e.addEventListener("pointerleave",r),window.addEventListener("blur",n),window.addEventListener("focus",r),function(){e.removeEventListener("focusin",n),e.removeEventListener("focusout",r),e.removeEventListener("pointerenter",n),e.removeEventListener("pointerleave",r),window.removeEventListener("blur",n),window.removeEventListener("focus",r)}}}),[d.isClosePausedRef]),s.useEffect((function(){var e=h.current;if(e){var t=[],n=new MutationObserver((function(n){Object(i.a)(n,1)[0].addedNodes.forEach((function(n){t.includes(n)||(e.prepend(n),t=[].concat(Object(o.a)(t),[n]))}))}));return n.observe(e,{childList:!0}),function(){return n.disconnect()}}}),[]),s.createElement(k,{ref:v,role:"region","aria-label":l.replace("{hotkey}",b),tabIndex:-1,style:{pointerEvents:d.toastCount>0?void 0:"none"}},s.createElement(p.a.ol,Object(w.a)({tabIndex:-1},f,{ref:m})))})),Y=s.forwardRef((function(e,t){var n=e.forceMount,r=e.open,o=e.defaultOpen,u=e.onOpenChange,c=Object(a.a)(e,R),f=Object(l.a)({prop:r,defaultProp:o,onChange:u}),d=Object(i.a)(f,2),p=d[0],h=void 0===p||p,m=d[1];return s.createElement(v.a,{present:n||h},s.createElement(Q,Object(w.a)({open:h},c,{ref:t,onClose:function(){return m(!1)},onSwipeStart:Object(g.a)(e.onSwipeStart,(function(e){e.currentTarget.setAttribute("data-swipe","start")})),onSwipeMove:Object(g.a)(e.onSwipeMove,(function(e){var t=e.detail.delta,n=t.x,r=t.y;e.currentTarget.setAttribute("data-swipe","move"),e.currentTarget.style.setProperty("--radix-toast-swipe-move-x","".concat(n,"px")),e.currentTarget.style.setProperty("--radix-toast-swipe-move-y","".concat(r,"px"))})),onSwipeCancel:Object(g.a)(e.onSwipeCancel,(function(e){e.currentTarget.setAttribute("data-swipe","cancel"),e.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),e.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),e.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),e.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")})),onSwipeEnd:Object(g.a)(e.onSwipeEnd,(function(e){var t=e.detail.delta,n=t.x,r=t.y;e.currentTarget.setAttribute("data-swipe","end"),e.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),e.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),e.currentTarget.style.setProperty("--radix-toast-swipe-end-x","".concat(n,"px")),e.currentTarget.style.setProperty("--radix-toast-swipe-end-y","".concat(r,"px")),m(!1)}))})))})),K=z("Toast",{isInteractive:!1,onClose:function(){}}),q=Object(i.a)(K,2),X=q[0],$=q[1],Q=s.forwardRef((function(e,t){var n=e.__scopeToast,o=e.type,i=void 0===o?"foreground":o,u=e.duration,c=e.open,l=e.onClose,d=e.onEscapeKeyDown,v=e.onSwipeStart,h=e.onSwipeMove,m=e.onSwipeCancel,b=e.onSwipeEnd,_=Object(a.a)(e,P),O=B("Toast",n),S=s.useRef(null),E=Object(y.b)(t,S),k=s.useRef(null),C=s.useRef(null),T=u||O.duration,R=s.useRef(0),A=s.useRef(T),L=s.useRef(0),N=O.onToastAdd,M=O.onToastRemove,D=f((function(){var e,t;(null===(e=S.current)||void 0===e?void 0:e.contains(document.activeElement))&&(null===(t=O.viewport)||void 0===t||t.focus()),l()})),I=s.useCallback((function(e){e&&e!==1/0&&(window.clearTimeout(L.current),R.current=(new Date).getTime(),L.current=window.setTimeout(D,e))}),[D]);return s.useEffect((function(){var e=O.viewport;if(e){var t=function(){I(A.current)},n=function(){var e=(new Date).getTime()-R.current;A.current=A.current-e,window.clearTimeout(L.current)};return e.addEventListener("toast.viewportPause",n),e.addEventListener("toast.viewportResume",t),function(){e.removeEventListener("toast.viewportPause",n),e.removeEventListener("toast.viewportResume",t)}}}),[O.viewport,T,I]),s.useEffect((function(){c&&!O.isClosePausedRef.current&&I(T)}),[c,T,O.isClosePausedRef,I]),s.useEffect((function(){return N(),function(){return M()}}),[N,M]),O.viewport?s.createElement(s.Fragment,null,s.createElement(G,{__scopeToast:n,role:"status","aria-live":"foreground"===i?"assertive":"polite","aria-atomic":!0},e.children),s.createElement(X,{scope:n,isInteractive:!0,onClose:D},x.createPortal(s.createElement(j,{asChild:!0,onEscapeKeyDown:Object(g.a)(d,(function(){O.isFocusedToastEscapeKeyDownRef.current||D(),O.isFocusedToastEscapeKeyDownRef.current=!1}))},s.createElement(p.a.li,Object(w.a)({role:"status","aria-live":"off","aria-atomic":!0,tabIndex:0,"data-state":c?"open":"closed","data-swipe-direction":O.swipeDirection},_,{ref:E,style:Object(r.a)({userSelect:"none",touchAction:"none"},e.style),onKeyDown:Object(g.a)(e.onKeyDown,(function(e){"Escape"===e.key&&(null==d||d(e.nativeEvent),e.nativeEvent.defaultPrevented||(O.isFocusedToastEscapeKeyDownRef.current=!0,D()))})),onPointerDown:Object(g.a)(e.onPointerDown,(function(e){0===e.button&&(k.current={x:e.clientX,y:e.clientY})})),onPointerMove:Object(g.a)(e.onPointerMove,(function(e){if(k.current){var t=e.clientX-k.current.x,n=e.clientY-k.current.y,r=Boolean(C.current),o=["left","right"].includes(O.swipeDirection),a=["left","up"].includes(O.swipeDirection)?Math.min:Math.max,i=o?a(0,t):0,u=o?0:a(0,n),c="touch"===e.pointerType?10:2,l={x:i,y:u},s={originalEvent:e,delta:l};r?(C.current=l,te("toast.swipeMove",h,s)):ne(l,O.swipeDirection,c)?(C.current=l,te("toast.swipeStart",v,s),e.target.setPointerCapture(e.pointerId)):(Math.abs(t)>c||Math.abs(n)>c)&&(k.current=null)}})),onPointerUp:Object(g.a)(e.onPointerUp,(function(e){var t=C.current;if(e.target.releasePointerCapture(e.pointerId),C.current=null,k.current=null,t){var n=e.currentTarget,r={originalEvent:e,delta:t};ne(t,O.swipeDirection,O.swipeThreshold)?te("toast.swipeEnd",b,r):te("toast.swipeCancel",m,r),n.addEventListener("click",(function(e){return e.preventDefault()}),{once:!0})}}))}))),O.viewport))):null}));Q.propTypes={type:function(e){if(e.type&&!["foreground","background"].includes(e.type))throw new Error("Invalid prop `type` supplied to `Toast`. Expected `foreground | background`.");return null}};var G=function(e){var t=e.__scopeToast,n=Object(a.a)(e,A),r=B("Toast",t),o=s.useState(!1),l=Object(i.a)(o,2),d=l[0],p=l[1],v=s.useState(!1),m=Object(i.a)(v,2),b=m[0],y=m[1];return function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:function(){},t=f(e);Object(c.a)((function(){var e,n=0;return e=window.requestAnimationFrame((function(){return n=window.requestAnimationFrame(t)})),function(){window.cancelAnimationFrame(e),window.cancelAnimationFrame(n)}}),[t])}((function(){return p(!0)})),s.useEffect((function(){var e=window.setTimeout((function(){return y(!0)}),1e3);return function(){return window.clearTimeout(e)}}),[]),b?null:s.createElement(h.b,{asChild:!0},s.createElement(u.b,{asChild:!0},s.createElement("div",n,d&&s.createElement(s.Fragment,null,r.label," ",e.children))))},Z=s.forwardRef((function(e,t){e.__scopeToast;var n=Object(a.a)(e,L);return s.createElement(p.a.div,Object(w.a)({},n,{ref:t}))})),J=s.forwardRef((function(e,t){var n=e.altText,r=Object(a.a)(e,N),o=$("ToastAction",e.__scopeToast);return n?o.isInteractive?s.createElement(ee,Object(w.a)({},r,{ref:t})):s.createElement("span",null,n):null}));J.propTypes={altText:function(e){if(!e.altText)throw new Error("Missing prop `altText` expected on `ToastAction`");return null}};var ee=s.forwardRef((function(e,t){var n=e.__scopeToast,r=Object(a.a)(e,M),o=$("ToastClose",n);return o.isInteractive?s.createElement(p.a.button,Object(w.a)({type:"button"},r,{ref:t,onClick:Object(g.a)(e.onClick,o.onClose)})):null}));function te(e,t,n){var r=n.originalEvent.currentTarget,o=new CustomEvent(e,{bubbles:!0,cancelable:!0,detail:n});t&&r.addEventListener(e,t,{once:!0}),r.dispatchEvent(o)}var ne=function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,r=Math.abs(e.x),o=Math.abs(e.y),a=r>o;return"left"===t||"right"===t?a&&r>n:!a&&o>n},re=function(e){var t=e.__scopeToast,n=e.label,r=void 0===n?"Notification":n,o=e.duration,a=void 0===o?5e3:o,u=e.swipeDirection,c=void 0===u?"right":u,l=e.swipeThreshold,f=void 0===l?50:l,d=e.children,p=s.useState(null),v=Object(i.a)(p,2),h=v[0],m=v[1],b=s.useState(0),y=Object(i.a)(b,2),g=y[0],w=y[1],_=s.useRef(!1),O=s.useRef(!1);return s.createElement(U,{scope:t,label:r,duration:a,swipeDirection:c,swipeThreshold:f,toastCount:g,viewport:h,onViewportChange:m,onToastAdd:s.useCallback((function(){return w((function(e){return e+1}))}),[]),onToastRemove:s.useCallback((function(){return w((function(e){return e-1}))}),[]),isFocusedToastEscapeKeyDownRef:_,isClosePausedRef:O},d)},oe=H,ae=Y,ie=Z},function(e,t,n){"use strict";function r(e){if(Array.isArray(e))return e}n.d(t,"a",(function(){return r}))},function(e,t,n){"use strict";function r(e){if("undefined"!==typeof Symbol&&Symbol.iterator in Object(e))return Array.from(e)}n.d(t,"a",(function(){return r}))},function(e,t,n){"use strict";function r(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}n.d(t,"a",(function(){return r}))},function(e,t,n){"use strict";n.d(t,"a",(function(){return u}));var r=new WeakMap,o=new WeakMap,a={},i=0,u=function(e,t,n){void 0===t&&(t=function(e){return"undefined"===typeof document?null:(Array.isArray(e)?e[0]:e).ownerDocument.body}(e)),void 0===n&&(n="data-aria-hidden");var u=Array.isArray(e)?e:[e];a[n]||(a[n]=new WeakMap);var c=a[n],l=[],s=new Set;u.forEach((function e(t){t&&!s.has(t)&&(s.add(t),e(t.parentNode))}));return function e(t){!t||u.indexOf(t)>=0||Array.prototype.forEach.call(t.children,(function(t){if(s.has(t))e(t);else{var a=t.getAttribute("aria-hidden"),i=null!==a&&"false"!==a,u=(r.get(t)||0)+1,f=(c.get(t)||0)+1;r.set(t,u),c.set(t,f),l.push(t),1===u&&i&&o.set(t,!0),1===f&&t.setAttribute(n,"true"),i||t.setAttribute("aria-hidden","true")}}))}(t),s.clear(),i++,function(){l.forEach((function(e){var t=r.get(e)-1,a=c.get(e)-1;r.set(e,t),c.set(e,a),t||(o.has(e)||e.removeAttribute("aria-hidden"),o.delete(e)),a||e.removeAttribute(n)})),--i||(r=new WeakMap,r=new WeakMap,o=new WeakMap,a={})}}},function(e,t,n){"use strict";n.d(t,"a",(function(){return u}));var r=n(2),o=n(18),a=n(14),i=n(0),u=function(e){var t=e.present,n=e.children,u=function(e){var t=i.useState(),n=Object(r.a)(t,2),a=n[0],u=n[1],l=i.useRef({}),s=i.useRef(e),f=i.useRef("none"),d=function(e,t){return i.useReducer((function(e,n){var r=t[e][n];return null!=r?r:e}),e)}(e?"mounted":"unmounted",{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}}),p=Object(r.a)(d,2),v=p[0],h=p[1];return i.useEffect((function(){var e=c(l.current);f.current="mounted"===v?e:"none"}),[v]),Object(o.a)((function(){var t=l.current,n=s.current;if(n!==e){var r=f.current,o=c(t);if(e)h("MOUNT");else if("none"===o||"none"===(null==t?void 0:t.display))h("UNMOUNT");else{h(n&&r!==o?"ANIMATION_OUT":"UNMOUNT")}s.current=e}}),[e,h]),Object(o.a)((function(){if(a){var e=function(e){var t=c(l.current).includes(e.animationName);e.target===a&&t&&h("ANIMATION_END")},t=function(e){e.target===a&&(f.current=c(l.current))};return a.addEventListener("animationstart",t),a.addEventListener("animationcancel",e),a.addEventListener("animationend",e),function(){a.removeEventListener("animationstart",t),a.removeEventListener("animationcancel",e),a.removeEventListener("animationend",e)}}h("ANIMATION_END")}),[a,h]),{isPresent:["mounted","unmountSuspended"].includes(v),ref:i.useCallback((function(e){e&&(l.current=getComputedStyle(e)),u(e)}),[])}}(t),l="function"==typeof n?n({present:u.isPresent}):i.Children.only(n),s=Object(a.b)(u.ref,l.ref);return"function"==typeof n||u.isPresent?i.cloneElement(l,{ref:s}):null};function c(e){return(null==e?void 0:e.animationName)||"none"}u.displayName="Presence"},function(e,t,n){"use strict";n.d(t,"a",(function(){return v})),n.d(t,"b",(function(){return h}));var r=n(3),o=n(2),a=n(4),i=n(13),u=n(18),c=n(12),l=n.n(c),s=n(0),f=n(5),d=["containerRef","style"],p=["container"],v=s.forwardRef((function(e,t){var n,c,p=e.containerRef,v=e.style,h=Object(a.a)(e,d),m=null!==(n=null==p?void 0:p.current)&&void 0!==n?n:null===globalThis||void 0===globalThis||null===(c=globalThis.document)||void 0===c?void 0:c.body,b=s.useState({}),y=Object(o.a)(b,2)[1];return Object(u.a)((function(){y({})}),[]),m?l.a.createPortal(s.createElement(i.a.div,Object(f.a)({"data-radix-portal":""},h,{ref:t,style:m===document.body?Object(r.a)({position:"absolute",top:0,left:0,zIndex:2147483647},v):void 0})),m):null})),h=s.forwardRef((function(e,t){var n,r=e.container,o=void 0===r?null===globalThis||void 0===globalThis||null===(n=globalThis.document)||void 0===n?void 0:n.body:r,u=Object(a.a)(e,p);return o?l.a.createPortal(s.createElement(i.a.div,Object(f.a)({},u,{ref:t})),o):null}))},function(e,t,n){"use strict";n.d(t,"b",(function(){return u})),n.d(t,"a",(function(){return c}));var r=n(3),o=n(13),a=n(0),i=n(5),u=a.forwardRef((function(e,t){return a.createElement(o.a.span,Object(i.a)({},e,{ref:t,style:Object(r.a)({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"},e.style)}))})),c=u},function(e,t,n){"use strict";n.d(t,"a",(function(){return U}));var r=n(3),o=n(7),a=n(2),i=n(4),u=n(5),c=n(0),l=n(8),s=n(10),f=n(12),d=n(19),p=["asChild"];function v(e,t,n,r){Object.defineProperty(e,t,{get:n,set:r,enumerable:!0,configurable:!0})}var h={};v(h,"Primitive",(function(){return m})),v(h,"dispatchDiscreteCustomEvent",(function(){return b})),v(h,"Root",(function(){return y}));var m=["a","button","div","h2","h3","img","li","nav","ol","p","span","svg","ul"].reduce((function(e,t){return Object(r.a)(Object(r.a)({},e),{},Object(s.a)({},t,Object(c.forwardRef)((function(e,n){var r=e.asChild,o=Object(i.a)(e,p),a=r?d.a:t;return Object(c.useEffect)((function(){window[Symbol.for("radix-ui")]=!0}),[]),Object(c.createElement)(a,Object(u.a)({},o,{ref:n}))}))))}),{});function b(e,t){e&&Object(f.flushSync)((function(){return e.dispatchEvent(t)}))}var y=m;function g(e,t,n,r){Object.defineProperty(e,t,{get:n,set:r,enumerable:!0,configurable:!0})}var w={};function _(e,t){"function"===typeof e?e(t):null!==e&&void 0!==e&&(e.current=t)}function O(){for(var e=arguments.length,t=new Array(e),n=0;n0,U=M>=R,B=function(e){var t=Object(A.a)(e),n=Object(c.useRef)(!1);return Object(c.useEffect)((function(){var e=function(e){e.target&&!n.current&&H(z,t,{originalEvent:e},{discrete:!0});n.current=!1},r=window.setTimeout((function(){document.addEventListener("pointerdown",e)}),0);return function(){window.clearTimeout(r),document.removeEventListener("pointerdown",e)}}),[t]),{onPointerDownCapture:function(){return n.current=!0}}}((function(e){var t=e.target,n=Object(o.a)(y.branches).some((function(e){return e.contains(t)}));U&&!n&&(null===d||void 0===d||d(e),null===v||void 0===v||v(e),e.defaultPrevented||null===h||void 0===h||h())})),Y=function(e){var t=Object(A.a)(e),n=Object(c.useRef)(!1);return Object(c.useEffect)((function(){var e=function(e){e.target&&!n.current&&H(F,t,{originalEvent:e},{discrete:!1})};return document.addEventListener("focusin",e),function(){return document.removeEventListener("focusin",e)}}),[t]),{onFocusCapture:function(){return n.current=!0},onBlurCapture:function(){return n.current=!1}}}((function(e){var t=e.target;Object(o.a)(y.branches).some((function(e){return e.contains(t)}))||(null===p||void 0===p||p(e),null===v||void 0===v||v(e),e.defaultPrevented||null===h||void 0===h||h())}));return L((function(e){M===y.layers.size-1&&(null===f||void 0===f||f(e),e.defaultPrevented||null===h||void 0===h||h())})),P({disabled:s}),Object(c.useEffect)((function(){_&&(s&&y.layersWithOutsidePointerEventsDisabled.add(_),y.layers.add(_),W())}),[_,s,y]),Object(c.useEffect)((function(){return function(){_&&(y.layers.delete(_),y.layersWithOutsidePointerEventsDisabled.delete(_),W())}}),[_,y]),Object(c.useEffect)((function(){var e=function(){return j({})};return document.addEventListener(I,e),function(){return document.removeEventListener(I,e)}}),[]),Object(c.createElement)(m.div,Object(u.a)({},b,{ref:k,style:Object(r.a)({pointerEvents:D?U?"auto":"none":void 0},e.style),onFocusCapture:Object(l.a)(e.onFocusCapture,Y.onFocusCapture),onBlurCapture:Object(l.a)(e.onBlurCapture,Y.onBlurCapture),onPointerDownCapture:Object(l.a)(e.onPointerDownCapture,B.onPointerDownCapture)}))})),B=Object(c.forwardRef)((function(e,t){var n=Object(c.useContext)(V),r=Object(c.useRef)(null),o=S(t,r);return Object(c.useEffect)((function(){var e=r.current;if(e)return n.branches.add(e),function(){n.branches.delete(e)}}),[n.branches]),Object(c.createElement)(m.div,Object(u.a)({},e,{ref:o}))}));function W(){var e=new CustomEvent(I);document.dispatchEvent(e)}function H(e,t,n,r){var o=r.discrete,a=n.originalEvent.target,i=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&a.addEventListener(e,t,{once:!0}),o?b(a,i):a.dispatchEvent(i)}var Y=U,K=B},function(e,t,n){"use strict";n.d(t,"a",(function(){return P}));var r=n(7),o=n(6),a=n(2),i=n(4),u=n(5),c=n(0);function l(e,t,n,r){Object.defineProperty(e,t,{get:n,set:r,enumerable:!0,configurable:!0})}var s={};function f(e,t){"function"===typeof e?e(t):null!==e&&void 0!==e&&(e.current=t)}function d(){for(var e=arguments.length,t=new Array(e),n=0;n1&&void 0!==arguments[1]?arguments[1]:{}).select,r=void 0!==n&&n,a=document.activeElement,i=Object(o.a)(e);try{for(i.s();!(t=i.n()).done;){if(D(t.value,{select:r}),document.activeElement!==a)return}}catch(u){i.e(u)}finally{i.f()}}((n=A(b),n.filter((function(e){return"A"!==e.tagName}))),{select:!0}),document.activeElement===e&&D(b))}return function(){b.removeEventListener(x,g),setTimeout((function(){var t=new CustomEvent(T,R);b.addEventListener(T,w),b.dispatchEvent(t),t.defaultPrevented||D(null!==e&&void 0!==e?e:document.body,{select:!0}),b.removeEventListener(T,w),I.remove(k)}),0)}}var n}),[b,g,w,k]);var C=Object(c.useCallback)((function(e){if((r||s)&&!k.paused){var t="Tab"===e.key&&!e.altKey&&!e.ctrlKey&&!e.metaKey,n=document.activeElement;if(t&&n){var o=e.currentTarget,i=function(e){var t=A(e),n=L(t,e),r=L(t.reverse(),e);return[n,r]}(o),u=Object(a.a)(i,2),c=u[0],l=u[1];c&&l?e.shiftKey||n!==l?e.shiftKey&&n===c&&(e.preventDefault(),r&&D(l,{select:!0})):(e.preventDefault(),r&&D(c,{select:!0})):n===o&&e.preventDefault()}}}),[r,s,k.paused]);return Object(c.createElement)(_.div,Object(u.a)({tabIndex:-1},v,{ref:S,onKeyDown:C}))}));function A(e){for(var t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:function(e){var t="INPUT"===e.tagName&&"hidden"===e.type;return e.disabled||e.hidden||t?NodeFilter.FILTER_SKIP:e.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});n.nextNode();)t.push(n.currentNode);return t}function L(e,t){var n,r=Object(o.a)(e);try{for(r.s();!(n=r.n()).done;){var a=n.value;if(!N(a,{upTo:t}))return a}}catch(i){r.e(i)}finally{r.f()}}function N(e,t){var n=t.upTo;if("hidden"===getComputedStyle(e).visibility)return!0;for(;e;){if(void 0!==n&&e===n)return!1;if("none"===getComputedStyle(e).display)return!0;e=e.parentElement}return!1}function M(e){return e instanceof HTMLInputElement&&"select"in e}function D(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.select,r=void 0!==n&&n;if(e&&e.focus){var o=document.activeElement;e.focus({preventScroll:!0}),e!==o&&M(e)&&r&&e.select()}}var I=function(){var e=[];return{add:function(t){var n=e[0];t!==n&&(null===n||void 0===n||n.pause()),(e=z(e,t)).unshift(t)},remove:function(t){var n;null===(n=(e=z(e,t))[0])||void 0===n||n.resume()}}}();function z(e,t){var n=Object(r.a)(e),o=n.indexOf(t);return-1!==o&&n.splice(o,1),n}var F=P},function(e,t,n){"use strict";n.d(t,"a",(function(){return o}));var r=n(0);function o(e){var t=function(e){var t=r.useRef(e);return r.useEffect((function(){t.current=e})),r.useMemo((function(){return function(){for(var e,n,r=arguments.length,o=new Array(r),a=0;a"']/g,G=RegExp($.source),Z=RegExp(Q.source),J=/<%-([\s\S]+?)%>/g,ee=/<%([\s\S]+?)%>/g,te=/<%=([\s\S]+?)%>/g,ne=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,re=/^\w*$/,oe=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,ae=/[\\^$.*+?()[\]{}|]/g,ie=RegExp(ae.source),ue=/^\s+/,ce=/\s/,le=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,se=/\{\n\/\* \[wrapped with (.+)\] \*/,fe=/,? & /,de=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,pe=/[()=,{}\[\]\/\s]/,ve=/\\(\\)?/g,he=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,me=/\w*$/,be=/^[-+]0x[0-9a-f]+$/i,ye=/^0b[01]+$/i,ge=/^\[object .+?Constructor\]$/,we=/^0o[0-7]+$/i,_e=/^(?:0|[1-9]\d*)$/,Oe=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,Se=/($^)/,Ee=/['\n\r\u2028\u2029\\]/g,je="\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff",ke="\\u2700-\\u27bf",Ce="a-z\\xdf-\\xf6\\xf8-\\xff",xe="A-Z\\xc0-\\xd6\\xd8-\\xde",Te="\\ufe0e\\ufe0f",Re="\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",Pe="['\u2019]",Ae="[\\ud800-\\udfff]",Le="["+Re+"]",Ne="["+je+"]",Me="\\d+",De="[\\u2700-\\u27bf]",Ie="["+Ce+"]",ze="[^\\ud800-\\udfff"+Re+Me+ke+Ce+xe+"]",Fe="\\ud83c[\\udffb-\\udfff]",Ve="[^\\ud800-\\udfff]",Ue="(?:\\ud83c[\\udde6-\\uddff]){2}",Be="[\\ud800-\\udbff][\\udc00-\\udfff]",We="["+xe+"]",He="(?:"+Ie+"|"+ze+")",Ye="(?:"+We+"|"+ze+")",Ke="(?:['\u2019](?:d|ll|m|re|s|t|ve))?",qe="(?:['\u2019](?:D|LL|M|RE|S|T|VE))?",Xe="(?:"+Ne+"|"+Fe+")"+"?",$e="[\\ufe0e\\ufe0f]?",Qe=$e+Xe+("(?:\\u200d(?:"+[Ve,Ue,Be].join("|")+")"+$e+Xe+")*"),Ge="(?:"+[De,Ue,Be].join("|")+")"+Qe,Ze="(?:"+[Ve+Ne+"?",Ne,Ue,Be,Ae].join("|")+")",Je=RegExp(Pe,"g"),et=RegExp(Ne,"g"),tt=RegExp(Fe+"(?="+Fe+")|"+Ze+Qe,"g"),nt=RegExp([We+"?"+Ie+"+"+Ke+"(?="+[Le,We,"$"].join("|")+")",Ye+"+"+qe+"(?="+[Le,We+He,"$"].join("|")+")",We+"?"+He+"+"+Ke,We+"+"+qe,"\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])","\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",Me,Ge].join("|"),"g"),rt=RegExp("[\\u200d\\ud800-\\udfff"+je+Te+"]"),ot=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,at=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],it=-1,ut={};ut[I]=ut[z]=ut[F]=ut[V]=ut[U]=ut[B]=ut[W]=ut[H]=ut[Y]=!0,ut[g]=ut[w]=ut[M]=ut[_]=ut[D]=ut[O]=ut[S]=ut[E]=ut[k]=ut[C]=ut[x]=ut[R]=ut[P]=ut[A]=ut[N]=!1;var ct={};ct[g]=ct[w]=ct[M]=ct[D]=ct[_]=ct[O]=ct[I]=ct[z]=ct[F]=ct[V]=ct[U]=ct[k]=ct[C]=ct[x]=ct[R]=ct[P]=ct[A]=ct[L]=ct[B]=ct[W]=ct[H]=ct[Y]=!0,ct[S]=ct[E]=ct[N]=!1;var lt={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},st=parseFloat,ft=parseInt,dt="object"==typeof e&&e&&e.Object===Object&&e,pt="object"==typeof self&&self&&self.Object===Object&&self,vt=dt||pt||Function("return this")(),ht=t&&!t.nodeType&&t,mt=ht&&"object"==typeof r&&r&&!r.nodeType&&r,bt=mt&&mt.exports===ht,yt=bt&&dt.process,gt=function(){try{var e=mt&&mt.require&&mt.require("util").types;return e||yt&&yt.binding&&yt.binding("util")}catch(t){}}(),wt=gt&>.isArrayBuffer,_t=gt&>.isDate,Ot=gt&>.isMap,St=gt&>.isRegExp,Et=gt&>.isSet,jt=gt&>.isTypedArray;function kt(e,t,n){switch(n.length){case 0:return e.call(t);case 1:return e.call(t,n[0]);case 2:return e.call(t,n[0],n[1]);case 3:return e.call(t,n[0],n[1],n[2])}return e.apply(t,n)}function Ct(e,t,n,r){for(var o=-1,a=null==e?0:e.length;++o-1}function Lt(e,t,n){for(var r=-1,o=null==e?0:e.length;++r-1;);return n}function nn(e,t){for(var n=e.length;n--&&Bt(t,e[n],0)>-1;);return n}function rn(e,t){for(var n=e.length,r=0;n--;)e[n]===t&&++r;return r}var on=qt({"\xc0":"A","\xc1":"A","\xc2":"A","\xc3":"A","\xc4":"A","\xc5":"A","\xe0":"a","\xe1":"a","\xe2":"a","\xe3":"a","\xe4":"a","\xe5":"a","\xc7":"C","\xe7":"c","\xd0":"D","\xf0":"d","\xc8":"E","\xc9":"E","\xca":"E","\xcb":"E","\xe8":"e","\xe9":"e","\xea":"e","\xeb":"e","\xcc":"I","\xcd":"I","\xce":"I","\xcf":"I","\xec":"i","\xed":"i","\xee":"i","\xef":"i","\xd1":"N","\xf1":"n","\xd2":"O","\xd3":"O","\xd4":"O","\xd5":"O","\xd6":"O","\xd8":"O","\xf2":"o","\xf3":"o","\xf4":"o","\xf5":"o","\xf6":"o","\xf8":"o","\xd9":"U","\xda":"U","\xdb":"U","\xdc":"U","\xf9":"u","\xfa":"u","\xfb":"u","\xfc":"u","\xdd":"Y","\xfd":"y","\xff":"y","\xc6":"Ae","\xe6":"ae","\xde":"Th","\xfe":"th","\xdf":"ss","\u0100":"A","\u0102":"A","\u0104":"A","\u0101":"a","\u0103":"a","\u0105":"a","\u0106":"C","\u0108":"C","\u010a":"C","\u010c":"C","\u0107":"c","\u0109":"c","\u010b":"c","\u010d":"c","\u010e":"D","\u0110":"D","\u010f":"d","\u0111":"d","\u0112":"E","\u0114":"E","\u0116":"E","\u0118":"E","\u011a":"E","\u0113":"e","\u0115":"e","\u0117":"e","\u0119":"e","\u011b":"e","\u011c":"G","\u011e":"G","\u0120":"G","\u0122":"G","\u011d":"g","\u011f":"g","\u0121":"g","\u0123":"g","\u0124":"H","\u0126":"H","\u0125":"h","\u0127":"h","\u0128":"I","\u012a":"I","\u012c":"I","\u012e":"I","\u0130":"I","\u0129":"i","\u012b":"i","\u012d":"i","\u012f":"i","\u0131":"i","\u0134":"J","\u0135":"j","\u0136":"K","\u0137":"k","\u0138":"k","\u0139":"L","\u013b":"L","\u013d":"L","\u013f":"L","\u0141":"L","\u013a":"l","\u013c":"l","\u013e":"l","\u0140":"l","\u0142":"l","\u0143":"N","\u0145":"N","\u0147":"N","\u014a":"N","\u0144":"n","\u0146":"n","\u0148":"n","\u014b":"n","\u014c":"O","\u014e":"O","\u0150":"O","\u014d":"o","\u014f":"o","\u0151":"o","\u0154":"R","\u0156":"R","\u0158":"R","\u0155":"r","\u0157":"r","\u0159":"r","\u015a":"S","\u015c":"S","\u015e":"S","\u0160":"S","\u015b":"s","\u015d":"s","\u015f":"s","\u0161":"s","\u0162":"T","\u0164":"T","\u0166":"T","\u0163":"t","\u0165":"t","\u0167":"t","\u0168":"U","\u016a":"U","\u016c":"U","\u016e":"U","\u0170":"U","\u0172":"U","\u0169":"u","\u016b":"u","\u016d":"u","\u016f":"u","\u0171":"u","\u0173":"u","\u0174":"W","\u0175":"w","\u0176":"Y","\u0177":"y","\u0178":"Y","\u0179":"Z","\u017b":"Z","\u017d":"Z","\u017a":"z","\u017c":"z","\u017e":"z","\u0132":"IJ","\u0133":"ij","\u0152":"Oe","\u0153":"oe","\u0149":"'n","\u017f":"s"}),an=qt({"&":"&","<":"<",">":">",'"':""","'":"'"});function un(e){return"\\"+lt[e]}function cn(e){return rt.test(e)}function ln(e){var t=-1,n=Array(e.size);return e.forEach((function(e,r){n[++t]=[r,e]})),n}function sn(e,t){return function(n){return e(t(n))}}function fn(e,t){for(var n=-1,r=e.length,o=0,a=[];++n",""":'"',"'":"'"});var yn=function e(t){var n=(t=null==t?vt:yn.defaults(vt.Object(),t,yn.pick(vt,at))).Array,r=t.Date,o=t.Error,ce=t.Function,je=t.Math,ke=t.Object,Ce=t.RegExp,xe=t.String,Te=t.TypeError,Re=n.prototype,Pe=ce.prototype,Ae=ke.prototype,Le=t["__core-js_shared__"],Ne=Pe.toString,Me=Ae.hasOwnProperty,De=0,Ie=function(){var e=/[^.]+$/.exec(Le&&Le.keys&&Le.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}(),ze=Ae.toString,Fe=Ne.call(ke),Ve=vt._,Ue=Ce("^"+Ne.call(Me).replace(ae,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Be=bt?t.Buffer:a,We=t.Symbol,He=t.Uint8Array,Ye=Be?Be.allocUnsafe:a,Ke=sn(ke.getPrototypeOf,ke),qe=ke.create,Xe=Ae.propertyIsEnumerable,$e=Re.splice,Qe=We?We.isConcatSpreadable:a,Ge=We?We.iterator:a,Ze=We?We.toStringTag:a,tt=function(){try{var e=pa(ke,"defineProperty");return e({},"",{}),e}catch(t){}}(),rt=t.clearTimeout!==vt.clearTimeout&&t.clearTimeout,lt=r&&r.now!==vt.Date.now&&r.now,dt=t.setTimeout!==vt.setTimeout&&t.setTimeout,pt=je.ceil,ht=je.floor,mt=ke.getOwnPropertySymbols,yt=Be?Be.isBuffer:a,gt=t.isFinite,Ft=Re.join,qt=sn(ke.keys,ke),gn=je.max,wn=je.min,_n=r.now,On=t.parseInt,Sn=je.random,En=Re.reverse,jn=pa(t,"DataView"),kn=pa(t,"Map"),Cn=pa(t,"Promise"),xn=pa(t,"Set"),Tn=pa(t,"WeakMap"),Rn=pa(ke,"create"),Pn=Tn&&new Tn,An={},Ln=Va(jn),Nn=Va(kn),Mn=Va(Cn),Dn=Va(xn),In=Va(Tn),zn=We?We.prototype:a,Fn=zn?zn.valueOf:a,Vn=zn?zn.toString:a;function Un(e){if(ru(e)&&!Ki(e)&&!(e instanceof Yn)){if(e instanceof Hn)return e;if(Me.call(e,"__wrapped__"))return Ua(e)}return new Hn(e)}var Bn=function(){function e(){}return function(t){if(!nu(t))return{};if(qe)return qe(t);e.prototype=t;var n=new e;return e.prototype=a,n}}();function Wn(){}function Hn(e,t){this.__wrapped__=e,this.__actions__=[],this.__chain__=!!t,this.__index__=0,this.__values__=a}function Yn(e){this.__wrapped__=e,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=b,this.__views__=[]}function Kn(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t=t?e:t)),e}function lr(e,t,n,r,o,i){var u,c=1&t,l=2&t,s=4&t;if(n&&(u=o?n(e,r,o,i):n(e)),u!==a)return u;if(!nu(e))return e;var f=Ki(e);if(f){if(u=function(e){var t=e.length,n=new e.constructor(t);t&&"string"==typeof e[0]&&Me.call(e,"index")&&(n.index=e.index,n.input=e.input);return n}(e),!c)return Po(e,u)}else{var d=ma(e),p=d==E||d==j;if(Qi(e))return jo(e,c);if(d==x||d==g||p&&!o){if(u=l||p?{}:ya(e),!c)return l?function(e,t){return Ao(e,ha(e),t)}(e,function(e,t){return e&&Ao(t,Nu(t),e)}(u,e)):function(e,t){return Ao(e,va(e),t)}(e,ar(u,e))}else{if(!ct[d])return o?e:{};u=function(e,t,n){var r=e.constructor;switch(t){case M:return ko(e);case _:case O:return new r(+e);case D:return function(e,t){var n=t?ko(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.byteLength)}(e,n);case I:case z:case F:case V:case U:case B:case W:case H:case Y:return Co(e,n);case k:case P:return new r;case C:case A:return new r(e);case R:return function(e){var t=new e.constructor(e.source,me.exec(e));return t.lastIndex=e.lastIndex,t}(e);case L:return o=e,Fn?ke(Fn.call(o)):{}}var o}(e,d,c)}}i||(i=new Qn);var v=i.get(e);if(v)return v;i.set(e,u),cu(e)?e.forEach((function(r){u.add(lr(r,t,n,r,e,i))})):ou(e)&&e.forEach((function(r,o){u.set(o,lr(r,t,n,o,e,i))}));var h=f?a:(s?l?ia:aa:l?Nu:Lu)(e);return xt(h||e,(function(r,o){h&&(r=e[o=r]),nr(u,o,lr(r,t,n,o,e,i))})),u}function sr(e,t,n){var r=n.length;if(null==e)return!r;for(e=ke(e);r--;){var o=n[r],i=t[o],u=e[o];if(u===a&&!(o in e)||!i(u))return!1}return!0}function fr(e,t,n){if("function"!=typeof e)throw new Te(i);return La((function(){e.apply(a,n)}),t)}function dr(e,t,n,r){var o=-1,a=At,i=!0,u=e.length,c=[],l=t.length;if(!u)return c;n&&(t=Nt(t,Zt(n))),r?(a=Lt,i=!1):t.length>=200&&(a=en,i=!1,t=new $n(t));e:for(;++o-1},qn.prototype.set=function(e,t){var n=this.__data__,r=rr(n,e);return r<0?(++this.size,n.push([e,t])):n[r][1]=t,this},Xn.prototype.clear=function(){this.size=0,this.__data__={hash:new Kn,map:new(kn||qn),string:new Kn}},Xn.prototype.delete=function(e){var t=fa(this,e).delete(e);return this.size-=t?1:0,t},Xn.prototype.get=function(e){return fa(this,e).get(e)},Xn.prototype.has=function(e){return fa(this,e).has(e)},Xn.prototype.set=function(e,t){var n=fa(this,e),r=n.size;return n.set(e,t),this.size+=n.size==r?0:1,this},$n.prototype.add=$n.prototype.push=function(e){return this.__data__.set(e,u),this},$n.prototype.has=function(e){return this.__data__.has(e)},Qn.prototype.clear=function(){this.__data__=new qn,this.size=0},Qn.prototype.delete=function(e){var t=this.__data__,n=t.delete(e);return this.size=t.size,n},Qn.prototype.get=function(e){return this.__data__.get(e)},Qn.prototype.has=function(e){return this.__data__.has(e)},Qn.prototype.set=function(e,t){var n=this.__data__;if(n instanceof qn){var r=n.__data__;if(!kn||r.length<199)return r.push([e,t]),this.size=++n.size,this;n=this.__data__=new Xn(r)}return n.set(e,t),this.size=n.size,this};var pr=Mo(_r),vr=Mo(Or,!0);function hr(e,t){var n=!0;return pr(e,(function(e,r,o){return n=!!t(e,r,o)})),n}function mr(e,t,n){for(var r=-1,o=e.length;++r0&&n(u)?t>1?yr(u,t-1,n,r,o):Mt(o,u):r||(o[o.length]=u)}return o}var gr=Do(),wr=Do(!0);function _r(e,t){return e&&gr(e,t,Lu)}function Or(e,t){return e&&wr(e,t,Lu)}function Sr(e,t){return Pt(t,(function(t){return Ji(e[t])}))}function Er(e,t){for(var n=0,r=(t=_o(t,e)).length;null!=e&&nt}function xr(e,t){return null!=e&&Me.call(e,t)}function Tr(e,t){return null!=e&&t in ke(e)}function Rr(e,t,r){for(var o=r?Lt:At,i=e[0].length,u=e.length,c=u,l=n(u),s=1/0,f=[];c--;){var d=e[c];c&&t&&(d=Nt(d,Zt(t))),s=wn(d.length,s),l[c]=!r&&(t||i>=120&&d.length>=120)?new $n(c&&d):a}d=e[0];var p=-1,v=l[0];e:for(;++p=u?c:c*("desc"==n[r]?-1:1)}return e.index-t.index}(e,t,n)}))}function Kr(e,t,n){for(var r=-1,o=t.length,a={};++r-1;)u!==e&&$e.call(u,c,1),$e.call(e,c,1);return e}function Xr(e,t){for(var n=e?t.length:0,r=n-1;n--;){var o=t[n];if(n==r||o!==a){var a=o;wa(o)?$e.call(e,o,1):po(e,o)}}return e}function $r(e,t){return e+ht(Sn()*(t-e+1))}function Qr(e,t){var n="";if(!e||t<1||t>h)return n;do{t%2&&(n+=e),(t=ht(t/2))&&(e+=e)}while(t);return n}function Gr(e,t){return Na(xa(e,t,ac),e+"")}function Zr(e){return Zn(Bu(e))}function Jr(e,t){var n=Bu(e);return Ia(n,cr(t,0,n.length))}function eo(e,t,n,r){if(!nu(e))return e;for(var o=-1,i=(t=_o(t,e)).length,u=i-1,c=e;null!=c&&++oa?0:a+t),(r=r>a?a:r)<0&&(r+=a),a=t>r?0:r-t>>>0,t>>>=0;for(var i=n(a);++o>>1,i=e[a];null!==i&&!su(i)&&(n?i<=t:i=200){var l=t?null:Go(e);if(l)return dn(l);i=!1,o=en,c=new $n}else c=t?[]:u;e:for(;++r=r?e:oo(e,t,n)}var Eo=rt||function(e){return vt.clearTimeout(e)};function jo(e,t){if(t)return e.slice();var n=e.length,r=Ye?Ye(n):new e.constructor(n);return e.copy(r),r}function ko(e){var t=new e.constructor(e.byteLength);return new He(t).set(new He(e)),t}function Co(e,t){var n=t?ko(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.length)}function xo(e,t){if(e!==t){var n=e!==a,r=null===e,o=e===e,i=su(e),u=t!==a,c=null===t,l=t===t,s=su(t);if(!c&&!s&&!i&&e>t||i&&u&&l&&!c&&!s||r&&u&&l||!n&&l||!o)return 1;if(!r&&!i&&!s&&e1?n[o-1]:a,u=o>2?n[2]:a;for(i=e.length>3&&"function"==typeof i?(o--,i):a,u&&_a(n[0],n[1],u)&&(i=o<3?a:i,o=1),t=ke(t);++r-1?o[i?t[u]:u]:a}}function Uo(e){return oa((function(t){var n=t.length,r=n,o=Hn.prototype.thru;for(e&&t.reverse();r--;){var u=t[r];if("function"!=typeof u)throw new Te(i);if(o&&!c&&"wrapper"==ca(u))var c=new Hn([],!0)}for(r=c?r:n;++r1&&g.reverse(),p&&sc))return!1;var s=i.get(e),f=i.get(t);if(s&&f)return s==t&&f==e;var d=-1,p=!0,v=2&n?new $n:a;for(i.set(e,t),i.set(t,e);++d-1&&e%1==0&&e1?"& ":"")+t[r],t=t.join(n>2?", ":" "),e.replace(le,"{\n/* [wrapped with "+t+"] */\n")}(r,function(e,t){return xt(y,(function(n){var r="_."+n[0];t&n[1]&&!At(e,r)&&e.push(r)})),e.sort()}(function(e){var t=e.match(se);return t?t[1].split(fe):[]}(r),n)))}function Da(e){var t=0,n=0;return function(){var r=_n(),o=16-(r-n);if(n=r,o>0){if(++t>=800)return arguments[0]}else t=0;return e.apply(a,arguments)}}function Ia(e,t){var n=-1,r=e.length,o=r-1;for(t=t===a?r:t;++n1?e[t-1]:a;return n="function"==typeof n?(e.pop(),n):a,ui(e,n)}));function vi(e){var t=Un(e);return t.__chain__=!0,t}function hi(e,t){return t(e)}var mi=oa((function(e){var t=e.length,n=t?e[0]:0,r=this.__wrapped__,o=function(t){return ur(t,e)};return!(t>1||this.__actions__.length)&&r instanceof Yn&&wa(n)?((r=r.slice(n,+n+(t?1:0))).__actions__.push({func:hi,args:[o],thisArg:a}),new Hn(r,this.__chain__).thru((function(e){return t&&!e.length&&e.push(a),e}))):this.thru(o)}));var bi=Lo((function(e,t,n){Me.call(e,n)?++e[n]:ir(e,n,1)}));var yi=Vo(Ya),gi=Vo(Ka);function wi(e,t){return(Ki(e)?xt:pr)(e,sa(t,3))}function _i(e,t){return(Ki(e)?Tt:vr)(e,sa(t,3))}var Oi=Lo((function(e,t,n){Me.call(e,n)?e[n].push(t):ir(e,n,[t])}));var Si=Gr((function(e,t,r){var o=-1,a="function"==typeof t,i=Xi(e)?n(e.length):[];return pr(e,(function(e){i[++o]=a?kt(t,e,r):Pr(e,t,r)})),i})),Ei=Lo((function(e,t,n){ir(e,n,t)}));function ji(e,t){return(Ki(e)?Nt:Vr)(e,sa(t,3))}var ki=Lo((function(e,t,n){e[n?0:1].push(t)}),(function(){return[[],[]]}));var Ci=Gr((function(e,t){if(null==e)return[];var n=t.length;return n>1&&_a(e,t[0],t[1])?t=[]:n>2&&_a(t[0],t[1],t[2])&&(t=[t[0]]),Yr(e,yr(t,1),[])})),xi=lt||function(){return vt.Date.now()};function Ti(e,t,n){return t=n?a:t,t=e&&null==t?e.length:t,Jo(e,d,a,a,a,a,t)}function Ri(e,t){var n;if("function"!=typeof t)throw new Te(i);return e=mu(e),function(){return--e>0&&(n=t.apply(this,arguments)),e<=1&&(t=a),n}}var Pi=Gr((function(e,t,n){var r=1;if(n.length){var o=fn(n,la(Pi));r|=s}return Jo(e,r,t,n,o)})),Ai=Gr((function(e,t,n){var r=3;if(n.length){var o=fn(n,la(Ai));r|=s}return Jo(t,r,e,n,o)}));function Li(e,t,n){var r,o,u,c,l,s,f=0,d=!1,p=!1,v=!0;if("function"!=typeof e)throw new Te(i);function h(t){var n=r,i=o;return r=o=a,f=t,c=e.apply(i,n)}function m(e){return f=e,l=La(y,t),d?h(e):c}function b(e){var n=e-s;return s===a||n>=t||n<0||p&&e-f>=u}function y(){var e=xi();if(b(e))return g(e);l=La(y,function(e){var n=t-(e-s);return p?wn(n,u-(e-f)):n}(e))}function g(e){return l=a,v&&r?h(e):(r=o=a,c)}function w(){var e=xi(),n=b(e);if(r=arguments,o=this,s=e,n){if(l===a)return m(s);if(p)return Eo(l),l=La(y,t),h(s)}return l===a&&(l=La(y,t)),c}return t=yu(t)||0,nu(n)&&(d=!!n.leading,u=(p="maxWait"in n)?gn(yu(n.maxWait)||0,t):u,v="trailing"in n?!!n.trailing:v),w.cancel=function(){l!==a&&Eo(l),f=0,r=s=o=l=a},w.flush=function(){return l===a?c:g(xi())},w}var Ni=Gr((function(e,t){return fr(e,1,t)})),Mi=Gr((function(e,t,n){return fr(e,yu(t)||0,n)}));function Di(e,t){if("function"!=typeof e||null!=t&&"function"!=typeof t)throw new Te(i);var n=function n(){var r=arguments,o=t?t.apply(this,r):r[0],a=n.cache;if(a.has(o))return a.get(o);var i=e.apply(this,r);return n.cache=a.set(o,i)||a,i};return n.cache=new(Di.Cache||Xn),n}function Ii(e){if("function"!=typeof e)throw new Te(i);return function(){var t=arguments;switch(t.length){case 0:return!e.call(this);case 1:return!e.call(this,t[0]);case 2:return!e.call(this,t[0],t[1]);case 3:return!e.call(this,t[0],t[1],t[2])}return!e.apply(this,t)}}Di.Cache=Xn;var zi=Oo((function(e,t){var n=(t=1==t.length&&Ki(t[0])?Nt(t[0],Zt(sa())):Nt(yr(t,1),Zt(sa()))).length;return Gr((function(r){for(var o=-1,a=wn(r.length,n);++o=t})),Yi=Ar(function(){return arguments}())?Ar:function(e){return ru(e)&&Me.call(e,"callee")&&!Xe.call(e,"callee")},Ki=n.isArray,qi=wt?Zt(wt):function(e){return ru(e)&&kr(e)==M};function Xi(e){return null!=e&&tu(e.length)&&!Ji(e)}function $i(e){return ru(e)&&Xi(e)}var Qi=yt||yc,Gi=_t?Zt(_t):function(e){return ru(e)&&kr(e)==O};function Zi(e){if(!ru(e))return!1;var t=kr(e);return t==S||"[object DOMException]"==t||"string"==typeof e.message&&"string"==typeof e.name&&!iu(e)}function Ji(e){if(!nu(e))return!1;var t=kr(e);return t==E||t==j||"[object AsyncFunction]"==t||"[object Proxy]"==t}function eu(e){return"number"==typeof e&&e==mu(e)}function tu(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=h}function nu(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}function ru(e){return null!=e&&"object"==typeof e}var ou=Ot?Zt(Ot):function(e){return ru(e)&&ma(e)==k};function au(e){return"number"==typeof e||ru(e)&&kr(e)==C}function iu(e){if(!ru(e)||kr(e)!=x)return!1;var t=Ke(e);if(null===t)return!0;var n=Me.call(t,"constructor")&&t.constructor;return"function"==typeof n&&n instanceof n&&Ne.call(n)==Fe}var uu=St?Zt(St):function(e){return ru(e)&&kr(e)==R};var cu=Et?Zt(Et):function(e){return ru(e)&&ma(e)==P};function lu(e){return"string"==typeof e||!Ki(e)&&ru(e)&&kr(e)==A}function su(e){return"symbol"==typeof e||ru(e)&&kr(e)==L}var fu=jt?Zt(jt):function(e){return ru(e)&&tu(e.length)&&!!ut[kr(e)]};var du=Xo(Fr),pu=Xo((function(e,t){return e<=t}));function vu(e){if(!e)return[];if(Xi(e))return lu(e)?hn(e):Po(e);if(Ge&&e[Ge])return function(e){for(var t,n=[];!(t=e.next()).done;)n.push(t.value);return n}(e[Ge]());var t=ma(e);return(t==k?ln:t==P?dn:Bu)(e)}function hu(e){return e?(e=yu(e))===v||e===-1/0?17976931348623157e292*(e<0?-1:1):e===e?e:0:0===e?e:0}function mu(e){var t=hu(e),n=t%1;return t===t?n?t-n:t:0}function bu(e){return e?cr(mu(e),0,b):0}function yu(e){if("number"==typeof e)return e;if(su(e))return m;if(nu(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=nu(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=Gt(e);var n=ye.test(e);return n||we.test(e)?ft(e.slice(2),n?2:8):be.test(e)?m:+e}function gu(e){return Ao(e,Nu(e))}function wu(e){return null==e?"":so(e)}var _u=No((function(e,t){if(ja(t)||Xi(t))Ao(t,Lu(t),e);else for(var n in t)Me.call(t,n)&&nr(e,n,t[n])})),Ou=No((function(e,t){Ao(t,Nu(t),e)})),Su=No((function(e,t,n,r){Ao(t,Nu(t),e,r)})),Eu=No((function(e,t,n,r){Ao(t,Lu(t),e,r)})),ju=oa(ur);var ku=Gr((function(e,t){e=ke(e);var n=-1,r=t.length,o=r>2?t[2]:a;for(o&&_a(t[0],t[1],o)&&(r=1);++n1),t})),Ao(e,ia(e),n),r&&(n=lr(n,7,na));for(var o=t.length;o--;)po(n,t[o]);return n}));var zu=oa((function(e,t){return null==e?{}:function(e,t){return Kr(e,t,(function(t,n){return Tu(e,n)}))}(e,t)}));function Fu(e,t){if(null==e)return{};var n=Nt(ia(e),(function(e){return[e]}));return t=sa(t),Kr(e,n,(function(e,n){return t(e,n[0])}))}var Vu=Zo(Lu),Uu=Zo(Nu);function Bu(e){return null==e?[]:Jt(e,Lu(e))}var Wu=zo((function(e,t,n){return t=t.toLowerCase(),e+(n?Hu(t):t)}));function Hu(e){return Zu(wu(e).toLowerCase())}function Yu(e){return(e=wu(e))&&e.replace(Oe,on).replace(et,"")}var Ku=zo((function(e,t,n){return e+(n?"-":"")+t.toLowerCase()})),qu=zo((function(e,t,n){return e+(n?" ":"")+t.toLowerCase()})),Xu=Io("toLowerCase");var $u=zo((function(e,t,n){return e+(n?"_":"")+t.toLowerCase()}));var Qu=zo((function(e,t,n){return e+(n?" ":"")+Zu(t)}));var Gu=zo((function(e,t,n){return e+(n?" ":"")+t.toUpperCase()})),Zu=Io("toUpperCase");function Ju(e,t,n){return e=wu(e),(t=n?a:t)===a?function(e){return ot.test(e)}(e)?function(e){return e.match(nt)||[]}(e):function(e){return e.match(de)||[]}(e):e.match(t)||[]}var ec=Gr((function(e,t){try{return kt(e,a,t)}catch(n){return Zi(n)?n:new o(n)}})),tc=oa((function(e,t){return xt(t,(function(t){t=Fa(t),ir(e,t,Pi(e[t],e))})),e}));function nc(e){return function(){return e}}var rc=Uo(),oc=Uo(!0);function ac(e){return e}function ic(e){return Dr("function"==typeof e?e:lr(e,1))}var uc=Gr((function(e,t){return function(n){return Pr(n,e,t)}})),cc=Gr((function(e,t){return function(n){return Pr(e,n,t)}}));function lc(e,t,n){var r=Lu(t),o=Sr(t,r);null!=n||nu(t)&&(o.length||!r.length)||(n=t,t=e,e=this,o=Sr(t,Lu(t)));var a=!(nu(n)&&"chain"in n)||!!n.chain,i=Ji(e);return xt(o,(function(n){var r=t[n];e[n]=r,i&&(e.prototype[n]=function(){var t=this.__chain__;if(a||t){var n=e(this.__wrapped__),o=n.__actions__=Po(this.__actions__);return o.push({func:r,args:arguments,thisArg:e}),n.__chain__=t,n}return r.apply(e,Mt([this.value()],arguments))})})),e}function sc(){}var fc=Yo(Nt),dc=Yo(Rt),pc=Yo(zt);function vc(e){return Oa(e)?Kt(Fa(e)):function(e){return function(t){return Er(t,e)}}(e)}var hc=qo(),mc=qo(!0);function bc(){return[]}function yc(){return!1}var gc=Ho((function(e,t){return e+t}),0),wc=Qo("ceil"),_c=Ho((function(e,t){return e/t}),1),Oc=Qo("floor");var Sc=Ho((function(e,t){return e*t}),1),Ec=Qo("round"),jc=Ho((function(e,t){return e-t}),0);return Un.after=function(e,t){if("function"!=typeof t)throw new Te(i);return e=mu(e),function(){if(--e<1)return t.apply(this,arguments)}},Un.ary=Ti,Un.assign=_u,Un.assignIn=Ou,Un.assignInWith=Su,Un.assignWith=Eu,Un.at=ju,Un.before=Ri,Un.bind=Pi,Un.bindAll=tc,Un.bindKey=Ai,Un.castArray=function(){if(!arguments.length)return[];var e=arguments[0];return Ki(e)?e:[e]},Un.chain=vi,Un.chunk=function(e,t,r){t=(r?_a(e,t,r):t===a)?1:gn(mu(t),0);var o=null==e?0:e.length;if(!o||t<1)return[];for(var i=0,u=0,c=n(pt(o/t));io?0:o+n),(r=r===a||r>o?o:mu(r))<0&&(r+=o),r=n>r?0:bu(r);n>>0)?(e=wu(e))&&("string"==typeof t||null!=t&&!uu(t))&&!(t=so(t))&&cn(e)?So(hn(e),0,n):e.split(t,n):[]},Un.spread=function(e,t){if("function"!=typeof e)throw new Te(i);return t=null==t?0:gn(mu(t),0),Gr((function(n){var r=n[t],o=So(n,0,t);return r&&Mt(o,r),kt(e,this,o)}))},Un.tail=function(e){var t=null==e?0:e.length;return t?oo(e,1,t):[]},Un.take=function(e,t,n){return e&&e.length?oo(e,0,(t=n||t===a?1:mu(t))<0?0:t):[]},Un.takeRight=function(e,t,n){var r=null==e?0:e.length;return r?oo(e,(t=r-(t=n||t===a?1:mu(t)))<0?0:t,r):[]},Un.takeRightWhile=function(e,t){return e&&e.length?ho(e,sa(t,3),!1,!0):[]},Un.takeWhile=function(e,t){return e&&e.length?ho(e,sa(t,3)):[]},Un.tap=function(e,t){return t(e),e},Un.throttle=function(e,t,n){var r=!0,o=!0;if("function"!=typeof e)throw new Te(i);return nu(n)&&(r="leading"in n?!!n.leading:r,o="trailing"in n?!!n.trailing:o),Li(e,t,{leading:r,maxWait:t,trailing:o})},Un.thru=hi,Un.toArray=vu,Un.toPairs=Vu,Un.toPairsIn=Uu,Un.toPath=function(e){return Ki(e)?Nt(e,Fa):su(e)?[e]:Po(za(wu(e)))},Un.toPlainObject=gu,Un.transform=function(e,t,n){var r=Ki(e),o=r||Qi(e)||fu(e);if(t=sa(t,4),null==n){var a=e&&e.constructor;n=o?r?new a:[]:nu(e)&&Ji(a)?Bn(Ke(e)):{}}return(o?xt:_r)(e,(function(e,r,o){return t(n,e,r,o)})),n},Un.unary=function(e){return Ti(e,1)},Un.union=ri,Un.unionBy=oi,Un.unionWith=ai,Un.uniq=function(e){return e&&e.length?fo(e):[]},Un.uniqBy=function(e,t){return e&&e.length?fo(e,sa(t,2)):[]},Un.uniqWith=function(e,t){return t="function"==typeof t?t:a,e&&e.length?fo(e,a,t):[]},Un.unset=function(e,t){return null==e||po(e,t)},Un.unzip=ii,Un.unzipWith=ui,Un.update=function(e,t,n){return null==e?e:vo(e,t,wo(n))},Un.updateWith=function(e,t,n,r){return r="function"==typeof r?r:a,null==e?e:vo(e,t,wo(n),r)},Un.values=Bu,Un.valuesIn=function(e){return null==e?[]:Jt(e,Nu(e))},Un.without=ci,Un.words=Ju,Un.wrap=function(e,t){return Fi(wo(t),e)},Un.xor=li,Un.xorBy=si,Un.xorWith=fi,Un.zip=di,Un.zipObject=function(e,t){return yo(e||[],t||[],nr)},Un.zipObjectDeep=function(e,t){return yo(e||[],t||[],eo)},Un.zipWith=pi,Un.entries=Vu,Un.entriesIn=Uu,Un.extend=Ou,Un.extendWith=Su,lc(Un,Un),Un.add=gc,Un.attempt=ec,Un.camelCase=Wu,Un.capitalize=Hu,Un.ceil=wc,Un.clamp=function(e,t,n){return n===a&&(n=t,t=a),n!==a&&(n=(n=yu(n))===n?n:0),t!==a&&(t=(t=yu(t))===t?t:0),cr(yu(e),t,n)},Un.clone=function(e){return lr(e,4)},Un.cloneDeep=function(e){return lr(e,5)},Un.cloneDeepWith=function(e,t){return lr(e,5,t="function"==typeof t?t:a)},Un.cloneWith=function(e,t){return lr(e,4,t="function"==typeof t?t:a)},Un.conformsTo=function(e,t){return null==t||sr(e,t,Lu(t))},Un.deburr=Yu,Un.defaultTo=function(e,t){return null==e||e!==e?t:e},Un.divide=_c,Un.endsWith=function(e,t,n){e=wu(e),t=so(t);var r=e.length,o=n=n===a?r:cr(mu(n),0,r);return(n-=t.length)>=0&&e.slice(n,o)==t},Un.eq=Bi,Un.escape=function(e){return(e=wu(e))&&Z.test(e)?e.replace(Q,an):e},Un.escapeRegExp=function(e){return(e=wu(e))&&ie.test(e)?e.replace(ae,"\\$&"):e},Un.every=function(e,t,n){var r=Ki(e)?Rt:hr;return n&&_a(e,t,n)&&(t=a),r(e,sa(t,3))},Un.find=yi,Un.findIndex=Ya,Un.findKey=function(e,t){return Vt(e,sa(t,3),_r)},Un.findLast=gi,Un.findLastIndex=Ka,Un.findLastKey=function(e,t){return Vt(e,sa(t,3),Or)},Un.floor=Oc,Un.forEach=wi,Un.forEachRight=_i,Un.forIn=function(e,t){return null==e?e:gr(e,sa(t,3),Nu)},Un.forInRight=function(e,t){return null==e?e:wr(e,sa(t,3),Nu)},Un.forOwn=function(e,t){return e&&_r(e,sa(t,3))},Un.forOwnRight=function(e,t){return e&&Or(e,sa(t,3))},Un.get=xu,Un.gt=Wi,Un.gte=Hi,Un.has=function(e,t){return null!=e&&ba(e,t,xr)},Un.hasIn=Tu,Un.head=Xa,Un.identity=ac,Un.includes=function(e,t,n,r){e=Xi(e)?e:Bu(e),n=n&&!r?mu(n):0;var o=e.length;return n<0&&(n=gn(o+n,0)),lu(e)?n<=o&&e.indexOf(t,n)>-1:!!o&&Bt(e,t,n)>-1},Un.indexOf=function(e,t,n){var r=null==e?0:e.length;if(!r)return-1;var o=null==n?0:mu(n);return o<0&&(o=gn(r+o,0)),Bt(e,t,o)},Un.inRange=function(e,t,n){return t=hu(t),n===a?(n=t,t=0):n=hu(n),function(e,t,n){return e>=wn(t,n)&&e=-9007199254740991&&e<=h},Un.isSet=cu,Un.isString=lu,Un.isSymbol=su,Un.isTypedArray=fu,Un.isUndefined=function(e){return e===a},Un.isWeakMap=function(e){return ru(e)&&ma(e)==N},Un.isWeakSet=function(e){return ru(e)&&"[object WeakSet]"==kr(e)},Un.join=function(e,t){return null==e?"":Ft.call(e,t)},Un.kebabCase=Ku,Un.last=Za,Un.lastIndexOf=function(e,t,n){var r=null==e?0:e.length;if(!r)return-1;var o=r;return n!==a&&(o=(o=mu(n))<0?gn(r+o,0):wn(o,r-1)),t===t?function(e,t,n){for(var r=n+1;r--;)if(e[r]===t)return r;return r}(e,t,o):Ut(e,Ht,o,!0)},Un.lowerCase=qu,Un.lowerFirst=Xu,Un.lt=du,Un.lte=pu,Un.max=function(e){return e&&e.length?mr(e,ac,Cr):a},Un.maxBy=function(e,t){return e&&e.length?mr(e,sa(t,2),Cr):a},Un.mean=function(e){return Yt(e,ac)},Un.meanBy=function(e,t){return Yt(e,sa(t,2))},Un.min=function(e){return e&&e.length?mr(e,ac,Fr):a},Un.minBy=function(e,t){return e&&e.length?mr(e,sa(t,2),Fr):a},Un.stubArray=bc,Un.stubFalse=yc,Un.stubObject=function(){return{}},Un.stubString=function(){return""},Un.stubTrue=function(){return!0},Un.multiply=Sc,Un.nth=function(e,t){return e&&e.length?Hr(e,mu(t)):a},Un.noConflict=function(){return vt._===this&&(vt._=Ve),this},Un.noop=sc,Un.now=xi,Un.pad=function(e,t,n){e=wu(e);var r=(t=mu(t))?vn(e):0;if(!t||r>=t)return e;var o=(t-r)/2;return Ko(ht(o),n)+e+Ko(pt(o),n)},Un.padEnd=function(e,t,n){e=wu(e);var r=(t=mu(t))?vn(e):0;return t&&rt){var r=e;e=t,t=r}if(n||e%1||t%1){var o=Sn();return wn(e+o*(t-e+st("1e-"+((o+"").length-1))),t)}return $r(e,t)},Un.reduce=function(e,t,n){var r=Ki(e)?Dt:Xt,o=arguments.length<3;return r(e,sa(t,4),n,o,pr)},Un.reduceRight=function(e,t,n){var r=Ki(e)?It:Xt,o=arguments.length<3;return r(e,sa(t,4),n,o,vr)},Un.repeat=function(e,t,n){return t=(n?_a(e,t,n):t===a)?1:mu(t),Qr(wu(e),t)},Un.replace=function(){var e=arguments,t=wu(e[0]);return e.length<3?t:t.replace(e[1],e[2])},Un.result=function(e,t,n){var r=-1,o=(t=_o(t,e)).length;for(o||(o=1,e=a);++rh)return[];var n=b,r=wn(e,b);t=sa(t),e-=b;for(var o=Qt(r,t);++n=i)return e;var c=n-vn(r);if(c<1)return r;var l=u?So(u,0,c).join(""):e.slice(0,c);if(o===a)return l+r;if(u&&(c+=l.length-c),uu(o)){if(e.slice(c).search(o)){var s,f=l;for(o.global||(o=Ce(o.source,wu(me.exec(o))+"g")),o.lastIndex=0;s=o.exec(f);)var d=s.index;l=l.slice(0,d===a?c:d)}}else if(e.indexOf(so(o),c)!=c){var p=l.lastIndexOf(o);p>-1&&(l=l.slice(0,p))}return l+r},Un.unescape=function(e){return(e=wu(e))&&G.test(e)?e.replace($,bn):e},Un.uniqueId=function(e){var t=++De;return wu(e)+t},Un.upperCase=Gu,Un.upperFirst=Zu,Un.each=wi,Un.eachRight=_i,Un.first=Xa,lc(Un,function(){var e={};return _r(Un,(function(t,n){Me.call(Un.prototype,n)||(e[n]=t)})),e}(),{chain:!1}),Un.VERSION="4.17.21",xt(["bind","bindKey","curry","curryRight","partial","partialRight"],(function(e){Un[e].placeholder=Un})),xt(["drop","take"],(function(e,t){Yn.prototype[e]=function(n){n=n===a?1:gn(mu(n),0);var r=this.__filtered__&&!t?new Yn(this):this.clone();return r.__filtered__?r.__takeCount__=wn(n,r.__takeCount__):r.__views__.push({size:wn(n,b),type:e+(r.__dir__<0?"Right":"")}),r},Yn.prototype[e+"Right"]=function(t){return this.reverse()[e](t).reverse()}})),xt(["filter","map","takeWhile"],(function(e,t){var n=t+1,r=1==n||3==n;Yn.prototype[e]=function(e){var t=this.clone();return t.__iteratees__.push({iteratee:sa(e,3),type:n}),t.__filtered__=t.__filtered__||r,t}})),xt(["head","last"],(function(e,t){var n="take"+(t?"Right":"");Yn.prototype[e]=function(){return this[n](1).value()[0]}})),xt(["initial","tail"],(function(e,t){var n="drop"+(t?"":"Right");Yn.prototype[e]=function(){return this.__filtered__?new Yn(this):this[n](1)}})),Yn.prototype.compact=function(){return this.filter(ac)},Yn.prototype.find=function(e){return this.filter(e).head()},Yn.prototype.findLast=function(e){return this.reverse().find(e)},Yn.prototype.invokeMap=Gr((function(e,t){return"function"==typeof e?new Yn(this):this.map((function(n){return Pr(n,e,t)}))})),Yn.prototype.reject=function(e){return this.filter(Ii(sa(e)))},Yn.prototype.slice=function(e,t){e=mu(e);var n=this;return n.__filtered__&&(e>0||t<0)?new Yn(n):(e<0?n=n.takeRight(-e):e&&(n=n.drop(e)),t!==a&&(n=(t=mu(t))<0?n.dropRight(-t):n.take(t-e)),n)},Yn.prototype.takeRightWhile=function(e){return this.reverse().takeWhile(e).reverse()},Yn.prototype.toArray=function(){return this.take(b)},_r(Yn.prototype,(function(e,t){var n=/^(?:filter|find|map|reject)|While$/.test(t),r=/^(?:head|last)$/.test(t),o=Un[r?"take"+("last"==t?"Right":""):t],i=r||/^find/.test(t);o&&(Un.prototype[t]=function(){var t=this.__wrapped__,u=r?[1]:arguments,c=t instanceof Yn,l=u[0],s=c||Ki(t),f=function(e){var t=o.apply(Un,Mt([e],u));return r&&d?t[0]:t};s&&n&&"function"==typeof l&&1!=l.length&&(c=s=!1);var d=this.__chain__,p=!!this.__actions__.length,v=i&&!d,h=c&&!p;if(!i&&s){t=h?t:new Yn(this);var m=e.apply(t,u);return m.__actions__.push({func:hi,args:[f],thisArg:a}),new Hn(m,d)}return v&&h?e.apply(this,u):(m=this.thru(f),v?r?m.value()[0]:m.value():m)})})),xt(["pop","push","shift","sort","splice","unshift"],(function(e){var t=Re[e],n=/^(?:push|sort|unshift)$/.test(e)?"tap":"thru",r=/^(?:pop|shift)$/.test(e);Un.prototype[e]=function(){var e=arguments;if(r&&!this.__chain__){var o=this.value();return t.apply(Ki(o)?o:[],e)}return this[n]((function(n){return t.apply(Ki(n)?n:[],e)}))}})),_r(Yn.prototype,(function(e,t){var n=Un[t];if(n){var r=n.name+"";Me.call(An,r)||(An[r]=[]),An[r].push({name:t,func:n})}})),An[Bo(a,2).name]=[{name:"wrapper",func:a}],Yn.prototype.clone=function(){var e=new Yn(this.__wrapped__);return e.__actions__=Po(this.__actions__),e.__dir__=this.__dir__,e.__filtered__=this.__filtered__,e.__iteratees__=Po(this.__iteratees__),e.__takeCount__=this.__takeCount__,e.__views__=Po(this.__views__),e},Yn.prototype.reverse=function(){if(this.__filtered__){var e=new Yn(this);e.__dir__=-1,e.__filtered__=!0}else(e=this.clone()).__dir__*=-1;return e},Yn.prototype.value=function(){var e=this.__wrapped__.value(),t=this.__dir__,n=Ki(e),r=t<0,o=n?e.length:0,a=function(e,t,n){var r=-1,o=n.length;for(;++r=this.__values__.length;return{done:e,value:e?a:this.__values__[this.__index__++]}},Un.prototype.plant=function(e){for(var t,n=this;n instanceof Wn;){var r=Ua(n);r.__index__=0,r.__values__=a,t?o.__wrapped__=r:t=r;var o=r;n=n.__wrapped__}return o.__wrapped__=e,t},Un.prototype.reverse=function(){var e=this.__wrapped__;if(e instanceof Yn){var t=e;return this.__actions__.length&&(t=new Yn(this)),(t=t.reverse()).__actions__.push({func:hi,args:[ni],thisArg:a}),new Hn(t,this.__chain__)}return this.thru(ni)},Un.prototype.toJSON=Un.prototype.valueOf=Un.prototype.value=function(){return mo(this.__wrapped__,this.__actions__)},Un.prototype.first=Un.prototype.head,Ge&&(Un.prototype[Ge]=function(){return this}),Un}();vt._=yn,(o=function(){return yn}.call(t,n,t,r))===a||(r.exports=o)}).call(this)}).call(this,n(59),n(60)(e))},function(e,t,n){"use strict";n.d(t,"a",(function(){return me})),n.d(t,"b",(function(){return pe}));var r=n(0),o=n.n(r),a=function(e,t){return a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},a(e,t)};var i=function(){return i=Object.assign||function(e){for(var t,n=1,r=arguments.length;n=n?(r(1),e.animation=null):e.animation&&(r(i),requestAnimationFrame(e.animation))},requestAnimationFrame(e.animation)}}function v(e,t,n,r){var o=function(e){var t=e.scale,n=e.positionX,r=e.positionY;if(isNaN(t)||isNaN(n)||isNaN(r))return!1;return!0}(t);if(e.mounted&&o){var a=e.setTransformState,i=e.transformState,u=i.scale,c=i.positionX,l=i.positionY,s=t.scale-u,f=t.positionX-c,d=t.positionY-l;0===n?a(t.scale,t.positionX,t.positionY):p(e,r,n,(function(e){a(u+s*e,c+f*e,l+d*e)}))}}var h=function(e,t){var n=e.wrapperComponent,r=e.contentComponent,o=e.setup.centerZoomedOut;if(!n||!r)throw new Error("Components are not mounted");var a=function(e,t,n){var r=e.offsetWidth,o=e.offsetHeight,a=t.offsetWidth*n,i=t.offsetHeight*n;return{wrapperWidth:r,wrapperHeight:o,newContentWidth:a,newDiffWidth:r-a,newContentHeight:i,newDiffHeight:o-i}}(n,r,t),i=a.wrapperWidth,u=a.wrapperHeight,c=function(e,t,n,r,o,a,i){var u=e>t?n*(i?1:.5):0,c=r>o?a*(i?1:.5):0;return{minPositionX:e-t-u,maxPositionX:u,minPositionY:r-o-c,maxPositionY:c}}(i,a.newContentWidth,a.newDiffWidth,u,a.newContentHeight,a.newDiffHeight,Boolean(o));return c},m=function(e,t){var n=h(e,t);return e.bounds=n,n};function b(e,t,n,r,o,a,i){var u=n.minPositionX,c=n.minPositionY,l=n.maxPositionX,s=n.maxPositionY,f=0,d=0;return i&&(f=o,d=a),{x:y(e,u-f,l+f,r),y:y(t,c-d,s+d,r)}}var y=function(e,t,n,r){return c(r?en?n:e:e,2)};function g(e,t,n,r,o,a){var i=e.transformState,u=i.scale,c=i.positionX,l=i.positionY,s=r-u;return"number"!==typeof t||"number"!==typeof n?(console.error("Mouse X and Y position were not provided!"),{x:c,y:l}):b(c-t*s,l-n*s,o,a,0,0,null)}function w(e,t,n,r,o){var a=t-(o?r:0);return!isNaN(n)&&e>=n?n:!isNaN(t)&&e<=a?a:e}var _=function(e,t){var n=e.setup.panning.excluded,r=e.isInitialized,o=e.wrapperComponent,a=t.target,i=null===o||void 0===o?void 0:o.contains(a);return!!(r&&a&&i)&&!X(a,n)},O=function(e){var t=e.isInitialized,n=e.isPanning,r=e.setup.panning.disabled;return!(!t||!n||r)};var S=function(e,t){var n=e.setup,r=e.transformState.scale,o=n.minScale;return t>0&&r>=o?t:0};function E(e,t,n,r,o,a,i,u,c,l){if(o){var s;if(t>i&&n>i)return(s=i+(e-i)*l)>c?c:sa?a:s}return r?t:y(e,a,i,o)}function j(e,t){var n=function(e){var t=e.mounted,n=e.setup,r=n.disabled,o=n.velocityAnimation,a=e.transformState.scale;return!(o.disabled&&!(a>1)&&r&&!t)}(e);if(n){var r=e.lastMousePosition,o=e.velocityTime,a=e.setup,i=e.wrapperComponent,u=a.velocityAnimation.equalToMove,c=Date.now();if(r&&o&&i){var l=function(e,t){return t?Math.min(1,e.offsetWidth/window.innerWidth):1}(i,u),s=t.x-r.x,f=t.y-r.y,d=s/l,p=f/l,v=c-o,h=s*s+f*f,m=Math.sqrt(h)/v;e.velocity={velocityX:d,velocityY:p,total:m}}e.lastMousePosition=t,e.velocityTime=c}}function k(e,t){var n=e.transformState.scale;d(e),m(e,n),t.touches?function(e,t){var n=t.touches,r=e.transformState,o=r.positionX,a=r.positionY;if(e.isPanning=!0,1===n.length){var i=n[0].clientX,u=n[0].clientY;e.startCoords={x:i-o,y:u-a}}}(e,t):function(e,t){var n=e.transformState,r=n.positionX,o=n.positionY;e.isPanning=!0;var a=t.clientX,i=t.clientY;e.startCoords={x:a-r,y:i-o}}(e,t)}function C(e,t,n){var r=e.startCoords,o=e.setup.alignmentAnimation,a=o.sizeX,i=o.sizeY;if(r){var u=function(e,t,n){var r=e.startCoords,o=e.transformState,a=e.setup.panning,i=a.lockAxisX,u=a.lockAxisY,c=o.positionX,l=o.positionY;if(!r)return{x:c,y:l};var s=t-r.x,f=n-r.y;return{x:i?c:s,y:u?l:f}}(e,t,n),c=u.x,l=u.y,s=S(e,a),f=S(e,i);j(e,{x:c,y:l}),function(e,t,n,r,o){var a=e.setup.limitToBounds,i=e.wrapperComponent,u=e.bounds,c=e.transformState,l=c.scale,s=c.positionX,f=c.positionY;if(i&&t!==s&&n!==f&&u){var d=b(t,n,u,a,r,o,i),p=d.x,v=d.y;e.setTransformState(l,p,v)}}(e,c,l,s,f)}}function x(e){if(e.isPanning){var t=e.setup.panning.velocityDisabled,n=e.velocity,r=e.wrapperComponent,o=e.contentComponent;e.isPanning=!1,e.animate=!1,e.animation=null;var a=null===r||void 0===r?void 0:r.getBoundingClientRect(),i=null===o||void 0===o?void 0:o.getBoundingClientRect(),u=(null===a||void 0===a?void 0:a.width)||0,c=(null===a||void 0===a?void 0:a.height)||0,l=(null===i||void 0===i?void 0:i.width)||0,f=(null===i||void 0===i?void 0:i.height)||0,d=u.1&&d?function(e){var t=e.velocity,n=e.bounds,r=e.setup,o=e.wrapperComponent,a=function(e){var t=e.mounted,n=e.velocity,r=e.bounds,o=e.setup,a=o.disabled,i=o.velocityAnimation,u=e.transformState.scale;return!(i.disabled&&!(u>1)&&a&&!t)&&!(!n||!r)}(e);if(a&&t&&n&&o){var i=t.velocityX,u=t.velocityY,c=t.total,l=n.maxPositionX,f=n.minPositionX,d=n.maxPositionY,v=n.minPositionY,h=r.limitToBounds,m=r.alignmentAnimation,b=r.zoomAnimation,y=r.panning,g=y.lockAxisY,w=y.lockAxisX,_=b.animationType,O=m.sizeX,j=m.sizeY,k=m.velocityAlignmentTime,C=function(e,t){var n=e.setup.velocityAnimation,r=n.equalToMove,o=n.animationTime,a=n.sensitivity;return r?o*t*a:o}(e,c),x=Math.max(C,k),T=S(e,O),R=S(e,j),P=T*o.offsetWidth/100,A=R*o.offsetHeight/100,L=l+P,N=f-P,M=d+A,D=v-A,I=e.transformState,z=(new Date).getTime();p(e,_,x,(function(t){var n=e.transformState,r=n.scale,o=n.positionX,a=n.positionY,c=((new Date).getTime()-z)/k,p=1-(0,s[m.animationType])(Math.min(1,c)),b=1-t,y=o+i*b,_=a+u*b,O=E(y,I.positionX,o,w,h,f,l,N,L,p),S=E(_,I.positionY,a,g,h,v,d,D,M,p);o===y&&a===_||e.setTransformState(r,O,S)}))}}(e):T(e)}}function T(e){var t=e.transformState.scale,n=e.setup,r=n.minScale,o=n.alignmentAnimation,a=o.disabled,i=o.sizeX,u=o.sizeY,c=o.animationTime,l=o.animationType;if(!(a||tf||np||rf?l.offsetWidth:e.setup.minPositionX||0,r>p?l.offsetHeight:e.setup.minPositionY||0,o,e.bounds,u||c),y=b.x,w=b.y;return{scale:o,positionX:h?y:n,positionY:m?w:r}}}(e);s&&v(e,s,c,l)}}function R(e,t,n){var r=e.transformState.scale,o=e.wrapperComponent,a=e.setup,i=a.minScale,u=a.limitToBounds,c=a.zoomAnimation,l=c.disabled,s=c.animationTime,f=c.animationType,d=l||r>=i;if((r>=1||u)&&T(e),!d&&o&&e.mounted){var p=P(e,i,t||o.offsetWidth/2,n||o.offsetHeight/2);p&&v(e,p,s,f)}}function P(e,t,n,r){var o=e.setup,a=o.minScale,i=o.maxScale,u=o.limitToBounds,l=w(c(t,2),a,i,0,!1),s=g(e,n,r,l,m(e,l),u);return{scale:l,positionX:s.x,positionY:s.y}}var A={previousScale:1,scale:1,positionX:0,positionY:0},L=i(i({},A),{setComponents:function(){},contextInstance:null}),N={disabled:!1,minPositionX:null,maxPositionX:null,minPositionY:null,maxPositionY:null,minScale:1,maxScale:8,limitToBounds:!0,centerZoomedOut:!1,centerOnInit:!1,wheel:{step:.2,disabled:!1,wheelDisabled:!1,touchPadDisabled:!1,activationKeys:[],excluded:[]},panning:{disabled:!1,velocityDisabled:!1,lockAxisX:!1,lockAxisY:!1,activationKeys:[],excluded:[]},pinch:{step:5,disabled:!1,excluded:[]},doubleClick:{disabled:!1,step:.7,mode:"zoomIn",animationType:"easeOut",animationTime:200,excluded:[]},zoomAnimation:{disabled:!1,size:.4,animationTime:200,animationType:"easeOut"},alignmentAnimation:{disabled:!1,sizeX:100,sizeY:100,animationTime:200,velocityAlignmentTime:400,animationType:"easeOut"},velocityAnimation:{disabled:!1,sensitivity:1,animationTime:400,animationType:"easeOut",equalToMove:!0}},M=function(e){var t,n,r,o;return{previousScale:null!==(t=e.initialScale)&&void 0!==t?t:A.scale,scale:null!==(n=e.initialScale)&&void 0!==n?n:A.scale,positionX:null!==(r=e.initialPositionX)&&void 0!==r?r:A.positionX,positionY:null!==(o=e.initialPositionY)&&void 0!==o?o:A.positionY}},D=function(e){var t=i({},N);return Object.keys(e).forEach((function(n){var r="undefined"!==typeof e[n];if("undefined"!==typeof N[n]&&r){var o=Object.prototype.toString.call(N[n]),a="[object Object]"===o,c="[object Array]"===o;t[n]=a?i(i({},N[n]),e[n]):c?u(u([],N[n]),e[n]):e[n]}})),t},I=function(e,t,n){var r=e.transformState.scale,o=e.wrapperComponent,a=e.setup,i=a.maxScale,u=a.minScale,l=a.zoomAnimation.size;if(!o)throw new Error("Wrapper is not mounted");var s=r*Math.exp(t*n);return w(c(s,3),u,i,l,!1)};function z(e,t,n,r,o){var a=e.wrapperComponent,i=e.transformState,u=i.scale,c=i.positionX,l=i.positionY;if(!a)return console.error("No WrapperComponent found");var s=(a.offsetWidth/2-c)/u,f=(a.offsetHeight/2-l)/u,d=P(e,I(e,t,n),s,f);if(!d)return console.error("Error during zoom event. New transformation state was not calculated.");v(e,d,r,o)}function F(e,t,n){var r=e.setup,o=e.wrapperComponent,a=r.limitToBounds,i=M(e.props),u=e.transformState,c=u.scale,l=u.positionX,s=u.positionY;if(o){var f=h(e,i.scale),d=b(i.positionX,i.positionY,f,a,0,0,o),p={scale:i.scale,positionX:d.x,positionY:d.y};c===i.scale&&l===i.positionX&&s===i.positionY||v(e,p,t,n)}}var V=function(e){return function(t,n,r){void 0===t&&(t=.5),void 0===n&&(n=300),void 0===r&&(r="easeOut"),z(e,1,t,n,r)}},U=function(e){return function(t,n,r){void 0===t&&(t=.5),void 0===n&&(n=300),void 0===r&&(r="easeOut"),z(e,-1,t,n,r)}},B=function(e){return function(t,n,r,o,a){void 0===o&&(o=300),void 0===a&&(a="easeOut");var i=e.transformState,u=i.positionX,c=i.positionY,l=i.scale,s=e.wrapperComponent,f=e.contentComponent;if(!e.setup.disabled&&s&&f){var d={positionX:isNaN(t)?u:t,positionY:isNaN(n)?c:n,scale:isNaN(r)?l:r};v(e,d,o,a)}}},W=function(e){return function(t,n){void 0===t&&(t=200),void 0===n&&(n="easeOut"),F(e,t,n)}},H=function(e){return function(t,n,r){void 0===n&&(n=200),void 0===r&&(r="easeOut");var o=e.transformState,a=e.wrapperComponent,i=e.contentComponent;if(a&&i){var u=G(t||o.scale,a,i);v(e,u,n,r)}}},Y=function(e){return function(t,n,r,o){void 0===r&&(r=600),void 0===o&&(o="easeOut"),d(e);var a=e.wrapperComponent,i="string"===typeof t?document.getElementById(t):t;if(a&&function(e){return e?void 0!==(null===e||void 0===e?void 0:e.offsetWidth)&&void 0!==(null===e||void 0===e?void 0:e.offsetHeight)||(console.error("Zoom node is not valid - it must contain offsetWidth and offsetHeight"),!1):(console.error("Zoom node not found"),!1)}(i)&&i&&a.contains(i)){var u=function(e,t,n){var r=e.wrapperComponent,o=e.setup,a=o.limitToBounds,i=o.minScale,u=o.maxScale;if(!r)return A;var c=r.getBoundingClientRect(),l=function(e){for(var t=e,n=0,r=0;t;)n+=t.offsetLeft,r+=t.offsetTop,t=t.offsetParent;return{x:n,y:r}}(t),s=l.x,f=l.y,d=t.offsetWidth,p=t.offsetHeight,v=r.offsetWidth/d,m=r.offsetHeight/p,y=w(n||Math.min(v,m),i,u,0,!1),g=(c.width-d*y)/2,_=(c.height-p*y)/2,O=b((c.left-s)*y+g,(c.top-f)*y+_,h(e,y),a,0,0,r);return{positionX:O.x,positionY:O.y,scale:y}}(e,i,n);v(e,u,r,o)}}},K=function(e){return{instance:e,state:e.transformState,zoomIn:V(e),zoomOut:U(e),setTransform:B(e),resetTransform:W(e),centerView:H(e),zoomToElement:Y(e)}};function q(){try{return{get passive(){return!0,!1}}}catch(e){return!1}}var X=function(e,t){var n=e.tagName.toUpperCase();return!!t.find((function(e){return e.toUpperCase()===n}))||!!t.find((function(t){return e.classList.contains(t)}))},$=function(e){e&&clearTimeout(e)},Q=function(e,t,n){return"translate3d("+e+"px, "+t+"px, 0) scale("+n+")"},G=function(e,t,n){var r=n.offsetWidth*e,o=n.offsetHeight*e;return{scale:e,positionX:(t.offsetWidth-r)/2,positionY:(t.offsetHeight-o)/2}},Z=function(e,t){var n=e.setup.wheel,r=n.disabled,o=n.wheelDisabled,a=n.touchPadDisabled,i=n.excluded,u=e.isInitialized,c=e.isPanning,l=t.target;return!(!u||c||r||!l)&&(!(o&&!t.ctrlKey)&&((!a||!t.ctrlKey)&&!X(l,i)))};function J(e,t,n){var r=t.getBoundingClientRect(),o=0,a=0;if("clientX"in e)o=(e.clientX-r.left)/n,a=(e.clientY-r.top)/n;else{var i=e.touches[0];o=(i.clientX-r.left)/n,a=(i.clientY-r.top)/n}return(isNaN(o)||isNaN(a))&&console.error("No mouse or touch offset found"),{x:o,y:a}}var ee=function(e,t){var n=e.setup.pinch,r=n.disabled,o=n.excluded,a=e.isInitialized,i=t.target;return!(!a||r||!i)&&!X(i,o)},te=function(e){var t=e.setup.pinch.disabled,n=e.isInitialized,r=e.pinchStartDistance;return!(!n||t||!r)},ne=function(e){return Math.sqrt(Math.pow(e.touches[0].pageX-e.touches[1].pageX,2)+Math.pow(e.touches[0].pageY-e.touches[1].pageY,2))},re=function(e,t){var n=e.props,r=n.onWheelStart,o=n.onZoomStart;e.wheelStopEventTimer||(d(e),l(K(e),t,r),l(K(e),t,o))},oe=function(e,t){var n=e.props,r=n.onWheel,o=n.onZoom,a=e.contentComponent,i=e.setup,u=e.transformState.scale,s=i.limitToBounds,f=i.centerZoomedOut,d=i.zoomAnimation,p=i.wheel,v=d.size,h=d.disabled,b=p.step;if(!a)throw new Error("Component not mounted");t.preventDefault(),t.stopPropagation();var y=function(e,t){var n,r,o=e?e.deltaY<0?1:-1:0;return r=o,"number"===typeof(n=t)?n:r}(t,null),_=function(e,t,n,r,o){var a=e.transformState.scale,i=e.wrapperComponent,u=e.setup,l=u.maxScale,s=u.minScale,f=u.zoomAnimation,d=f.size,p=f.disabled;if(!i)throw new Error("Wrapper is not mounted");var v=a+t*(a-a*n)*n;if(o)return v;var h=!r&&!p;return w(c(v,3),s,l,d,h)}(e,y,b,!t.ctrlKey);if(u!==_){var O=m(e,_),S=J(t,a,u),E=s&&(h||0===v||f),j=g(e,S.x,S.y,_,O,E),k=j.x,C=j.y;e.previousWheelEvent=t,e.setTransformState(_,k,C),l(K(e),t,r),l(K(e),t,o)}},ae=function(e,t){var n=e.props,r=n.onWheelStop,o=n.onZoomStop;$(e.wheelAnimationTimer),e.wheelAnimationTimer=setTimeout((function(){e.mounted&&(R(e,t.x,t.y),e.wheelAnimationTimer=null)}),100);var a=function(e,t){var n=e.previousWheelEvent,r=e.transformState.scale,o=e.setup,a=o.maxScale,i=o.minScale;return!!n&&(ri||Math.sign(n.deltaY)!==Math.sign(t.deltaY)||n.deltaY>0&&n.deltaYt.deltaY||Math.sign(n.deltaY)!==Math.sign(t.deltaY))}(e,t);a&&($(e.wheelStopEventTimer),e.wheelStopEventTimer=setTimeout((function(){e.mounted&&(e.wheelStopEventTimer=null,l(K(e),t,r),l(K(e),t,o))}),160))},ie=function(e,t){var n=ne(t);e.pinchStartDistance=n,e.lastDistance=n,e.pinchStartScale=e.transformState.scale,e.isPanning=!1,d(e)},ue=function(e,t){var n=e.contentComponent,r=e.pinchStartDistance,o=e.transformState.scale,a=e.setup,i=a.limitToBounds,u=a.centerZoomedOut,l=a.zoomAnimation,s=l.disabled,f=l.size;if(null!==r&&n){var d=function(e,t,n){var r=n.getBoundingClientRect(),o=e.touches,a=c(o[0].clientX-r.left,5),i=c(o[0].clientY-r.top,5);return{x:(a+c(o[1].clientX-r.left,5))/2/t,y:(i+c(o[1].clientY-r.top,5))/2/t}}(t,o,n);if(isFinite(d.x)&&isFinite(d.y)){var p=ne(t),v=function(e,t){var n=e.pinchStartScale,r=e.pinchStartDistance,o=e.setup,a=o.maxScale,i=o.minScale,u=o.zoomAnimation,l=u.size,s=u.disabled;if(!n||null===r||!t)throw new Error("Pinch touches distance was not provided");return t<0?e.transformState.scale:w(c(t/r*n,2),i,a,l,!s)}(e,p);if(v!==o){var h=m(e,v),b=i&&(s||0===f||u),y=g(e,d.x,d.y,v,h,b),_=y.x,O=y.y;e.pinchMidpoint=d,e.lastDistance=p,e.setTransformState(v,_,O)}}}},ce=function(e){var t=e.pinchMidpoint;e.velocity=null,e.lastDistance=null,e.pinchMidpoint=null,e.pinchStartScale=null,e.pinchStartDistance=null,R(e,null===t||void 0===t?void 0:t.x,null===t||void 0===t?void 0:t.y)};function le(e,t){var n=e.setup.doubleClick,r=n.disabled,o=n.mode,a=n.step,i=n.animationTime,u=n.animationType;if(!r){if("reset"===o)return F(e,i,u);var c=e.transformState.scale,l=e.contentComponent;if(!l)return console.error("No ContentComponent found");var s=I(e,"zoomOut"===o?-1:1,a),f=J(t,l,c),d=P(e,s,f.x,f.y);if(!d)return console.error("Error during zoom event. New transformation state was not calculated.");v(e,d,i,u)}}var se=function(e,t){var n=e.isInitialized,r=e.setup,o=e.wrapperComponent,a=r.doubleClick,i=a.disabled,u=a.excluded,c=t.target,l=null===o||void 0===o?void 0:o.contains(c),s=n&&c&&l&&!i;return!!s&&(!X(c,u)&&!!s)},fe=o.a.createContext(L),de=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.mounted=!0,t.transformState=M(t.props),t.setup=D(t.props),t.wrapperComponent=null,t.contentComponent=null,t.isInitialized=!1,t.bounds=null,t.previousWheelEvent=null,t.wheelStopEventTimer=null,t.wheelAnimationTimer=null,t.isPanning=!1,t.startCoords=null,t.lastTouch=null,t.distance=null,t.lastDistance=null,t.pinchStartDistance=null,t.pinchStartScale=null,t.pinchMidpoint=null,t.velocity=null,t.velocityTime=null,t.lastMousePosition=null,t.animate=!1,t.animation=null,t.maxBounds=null,t.pressedKeys={},t.handleInitializeWrapperEvents=function(e){var n=q();e.addEventListener("wheel",t.onWheelZoom,n),e.addEventListener("dblclick",t.onDoubleClick,n),e.addEventListener("touchstart",t.onTouchPanningStart,n),e.addEventListener("touchmove",t.onTouchPanning,n),e.addEventListener("touchend",t.onTouchPanningStop,n)},t.handleInitialize=function(){var e=t.setup.centerOnInit;t.applyTransformation(),t.forceUpdate(),e&&(setTimeout((function(){t.mounted&&t.setCenter()}),50),setTimeout((function(){t.mounted&&t.setCenter()}),100),setTimeout((function(){t.mounted&&t.setCenter()}),200))},t.onWheelZoom=function(e){t.setup.disabled||Z(t,e)&&t.isPressingKeys(t.setup.wheel.activationKeys)&&(re(t,e),oe(t,e),ae(t,e))},t.onPanningStart=function(e){var n=t.setup.disabled,r=t.props.onPanningStart;n||_(t,e)&&t.isPressingKeys(t.setup.panning.activationKeys)&&(e.preventDefault(),e.stopPropagation(),d(t),k(t,e),l(K(t),e,r))},t.onPanning=function(e){var n=t.setup.disabled,r=t.props.onPanning;n||O(t)&&t.isPressingKeys(t.setup.panning.activationKeys)&&(e.preventDefault(),e.stopPropagation(),C(t,e.clientX,e.clientY),l(K(t),e,r))},t.onPanningStop=function(e){var n=t.props.onPanningStop;t.isPanning&&(x(t),l(K(t),e,n))},t.onPinchStart=function(e){var n=t.setup.disabled,r=t.props,o=r.onPinchingStart,a=r.onZoomStart;n||ee(t,e)&&(ie(t,e),d(t),l(K(t),e,o),l(K(t),e,a))},t.onPinch=function(e){var n=t.setup.disabled,r=t.props,o=r.onPinching,a=r.onZoom;n||te(t)&&(e.preventDefault(),e.stopPropagation(),ue(t,e),l(K(t),e,o),l(K(t),e,a))},t.onPinchStop=function(e){var n=t.props,r=n.onPinchingStop,o=n.onZoomStop;t.pinchStartScale&&(ce(t),l(K(t),e,r),l(K(t),e,o))},t.onTouchPanningStart=function(e){var n=t.setup.disabled,r=t.props.onPanningStart;if(!n&&_(t,e))if(t.lastTouch&&+new Date-t.lastTouch<200&&1===e.touches.length)t.onDoubleClick(e);else{t.lastTouch=+new Date,d(t);var o=e.touches,a=1===o.length,i=2===o.length;a&&(d(t),k(t,e),l(K(t),e,r)),i&&t.onPinchStart(e)}},t.onTouchPanning=function(e){var n=t.setup.disabled,r=t.props.onPanning;if(t.isPanning&&1===e.touches.length){if(n)return;if(!O(t))return;e.preventDefault(),e.stopPropagation();var o=e.touches[0];C(t,o.clientX,o.clientY),l(K(t),e,r)}else e.touches.length>1&&t.onPinch(e)},t.onTouchPanningStop=function(e){t.onPanningStop(e),t.onPinchStop(e)},t.onDoubleClick=function(e){t.setup.disabled||se(t,e)&&le(t,e)},t.clearPanning=function(e){t.isPanning&&t.onPanningStop(e)},t.setKeyPressed=function(e){t.pressedKeys[e.key]=!0},t.setKeyUnPressed=function(e){t.pressedKeys[e.key]=!1},t.isPressingKeys=function(e){return!e.length||Boolean(e.find((function(e){return t.pressedKeys[e]})))},t.setComponents=function(e,n){t.wrapperComponent=e,t.contentComponent=n,m(t,t.transformState.scale),t.handleInitializeWrapperEvents(e),t.handleInitialize(),t.handleRef(),t.isInitialized=!0,l(K(t),void 0,t.props.onInit)},t.setTransformState=function(e,n,r){isNaN(e)||isNaN(n)||isNaN(r)?console.error("Detected NaN set state values"):(e!==t.transformState.scale&&(t.transformState.previousScale=t.transformState.scale,t.transformState.scale=e),t.transformState.positionX=n,t.transformState.positionY=r,t.applyTransformation())},t.setCenter=function(){if(t.wrapperComponent&&t.contentComponent){var e=G(t.transformState.scale,t.wrapperComponent,t.contentComponent);t.setTransformState(e.scale,e.positionX,e.positionY)}},t.applyTransformation=function(){if(t.mounted&&t.contentComponent){var e=t.transformState,n=e.scale,r=e.positionX,o=e.positionY,a=Q(r,o,n);t.contentComponent.style.transform=a,t.handleRef()}},t.handleRef=function(){t.props.setRef(K(t))},t}return function(e,t){if("function"!==typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}a(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}(t,e),t.prototype.componentDidMount=function(){var e=q();window.addEventListener("mousedown",this.onPanningStart,e),window.addEventListener("mousemove",this.onPanning,e),window.addEventListener("mouseup",this.onPanningStop,e),document.addEventListener("mouseleave",this.clearPanning,e),window.addEventListener("keyup",this.setKeyUnPressed,e),window.addEventListener("keydown",this.setKeyPressed,e),this.handleRef()},t.prototype.componentWillUnmount=function(){var e=q();window.removeEventListener("mousedown",this.onPanningStart,e),window.removeEventListener("mousemove",this.onPanning,e),window.removeEventListener("mouseup",this.onPanningStop,e),window.removeEventListener("keyup",this.setKeyUnPressed,e),window.removeEventListener("keydown",this.setKeyPressed,e),d(this)},t.prototype.componentDidUpdate=function(e){e!==this.props&&(m(this,this.transformState.scale),this.setup=D(this.props))},t.prototype.render=function(){var e=K(this),t=this.props.children,n="function"===typeof t?t(e):t;return o.a.createElement(fe.Provider,{value:i(i({},this.transformState),{setComponents:this.setComponents,contextInstance:this})},n)},t}(r.Component),pe=o.a.forwardRef((function(e,t){var n=Object(r.useState)(null),a=n[0],u=n[1];return Object(r.useImperativeHandle)(t,(function(){return a}),[a]),o.a.createElement(de,i({},e,{setRef:u}))}));var ve="transform-component-module_wrapper__1_Fgj",he="transform-component-module_content__2jYgh";!function(e,t){void 0===t&&(t={});var n=t.insertAt;if(e&&"undefined"!==typeof document){var r=document.head||document.getElementsByTagName("head")[0],o=document.createElement("style");o.type="text/css","top"===n&&r.firstChild?r.insertBefore(o,r.firstChild):r.appendChild(o),o.styleSheet?o.styleSheet.cssText=e:o.appendChild(document.createTextNode(e))}}(".transform-component-module_wrapper__1_Fgj {\n position: relative;\n width: -moz-fit-content;\n width: fit-content;\n height: -moz-fit-content;\n height: fit-content;\n overflow: hidden;\n -webkit-touch-callout: none; /* iOS Safari */\n -webkit-user-select: none; /* Safari */\n -khtml-user-select: none; /* Konqueror HTML */\n -moz-user-select: none; /* Firefox */\n -ms-user-select: none; /* Internet Explorer/Edge */\n user-select: none;\n margin: 0;\n padding: 0;\n}\n.transform-component-module_content__2jYgh {\n display: flex;\n flex-wrap: wrap;\n width: -moz-fit-content;\n width: fit-content;\n height: -moz-fit-content;\n height: fit-content;\n margin: 0;\n padding: 0;\n transform-origin: 0% 0%;\n}\n.transform-component-module_content__2jYgh img {\n pointer-events: none;\n}\n");var me=function(e){var t=e.children,n=e.wrapperClass,a=void 0===n?"":n,i=e.contentClass,u=void 0===i?"":i,c=e.wrapperStyle,l=e.contentStyle,s=Object(r.useContext)(fe).setComponents,f=Object(r.useRef)(null),d=Object(r.useRef)(null);return Object(r.useEffect)((function(){var e=f.current,t=d.current;null!==e&&null!==t&&s&&s(e,t)}),[]),o.a.createElement("div",{ref:f,className:"react-transform-wrapper "+ve+" "+a,style:c},o.a.createElement("div",{ref:d,className:"react-transform-component "+he+" "+u,style:l},t))}},function(e,t,n){"use strict";n.d(t,"a",(function(){return P})),n.d(t,"b",(function(){return A}));var r=n(3),o=n(4),a=n(2),i=(n(18),n(0));i["useId".toString()];var u=n(13),c=n(14),l=n(21),s=n(5),f=Object(l.a)("Label",{id:void 0,controlRef:{current:null}}),d=Object(a.a)(f,2),p=(d[0],d[1]),v=n(30),h=n(31),m=n(25),b=n(8),y=["__scopeSwitch","aria-labelledby","name","checked","defaultChecked","required","disabled","value","onCheckedChange"],g=["__scopeSwitch"],w=["control","checked","bubbles"],_=Object(l.b)("Switch"),O=Object(a.a)(_,2),S=O[0],E=(O[1],S("Switch")),j=Object(a.a)(E,2),k=j[0],C=j[1],x=i.forwardRef((function(e,t){var n=e.__scopeSwitch,r=e["aria-labelledby"],l=e.name,f=e.checked,d=e.defaultChecked,v=e.required,h=e.disabled,g=e.value,w=void 0===g?"on":g,_=e.onCheckedChange,O=Object(o.a)(e,y),S=i.useState(null),E=Object(a.a)(S,2),j=E[0],C=E[1],x=Object(c.b)(t,(function(e){return C(e)})),P=function(e){var t=p("LabelConsumer"),n=t.controlRef;return i.useEffect((function(){e&&(n.current=e)}),[e,n]),t.id}(j),A=r||P,L=i.useRef(!1),N=!j||Boolean(j.closest("form")),M=Object(m.a)({prop:f,defaultProp:d,onChange:_}),D=Object(a.a)(M,2),I=D[0],z=void 0!==I&&I,F=D[1];return i.createElement(k,{scope:n,checked:z,disabled:h},i.createElement(u.a.button,Object(s.a)({type:"button",role:"switch","aria-checked":z,"aria-labelledby":A,"aria-required":v,"data-state":R(z),"data-disabled":h?"":void 0,disabled:h,value:w},O,{ref:x,onClick:Object(b.a)(e.onClick,(function(e){F((function(e){return!e})),N&&(L.current=e.isPropagationStopped(),L.current||e.stopPropagation())}))})),N&&i.createElement(T,{control:j,bubbles:!L.current,name:l,value:w,checked:z,required:v,disabled:h,style:{transform:"translateX(-100%)"}}))})),T=function(e){var t=e.control,n=e.checked,a=e.bubbles,u=void 0===a||a,c=Object(o.a)(e,w),l=i.useRef(null),f=Object(h.a)(n),d=Object(v.a)(t);return i.useEffect((function(){var e=l.current,t=window.HTMLInputElement.prototype,r=Object.getOwnPropertyDescriptor(t,"checked").set;if(f!==n&&r){var o=new Event("click",{bubbles:u});r.call(e,n),e.dispatchEvent(o)}}),[f,n,u]),i.createElement("input",Object(s.a)({type:"checkbox","aria-hidden":!0,defaultChecked:n},c,{tabIndex:-1,ref:l,style:Object(r.a)(Object(r.a)(Object(r.a)({},e.style),d),{},{position:"absolute",pointerEvents:"none",opacity:0,margin:0})}))};function R(e){return e?"checked":"unchecked"}var P=x,A=i.forwardRef((function(e,t){var n=e.__scopeSwitch,r=Object(o.a)(e,g),a=C("SwitchThumb",n);return i.createElement(u.a.span,Object(s.a)({"data-state":R(a.checked),"data-disabled":a.disabled?"":void 0},r,{ref:t}))}))},function(e,t,n){"use strict";var r=n(0),o=n(20),a=o.a?window:null,i=function(e){return!!e.addEventListener},u=function(e){return!!e.on},c=function(e,t,n,c){void 0===n&&(n=a),Object(r.useEffect)((function(){if(t&&n)return i(n)?Object(o.d)(n,e,t,c):u(n)&&n.on(e,t,c),function(){i(n)?Object(o.c)(n,e,t,c):u(n)&&n.off(e,t,c)}}),[e,t,n,JSON.stringify(c)])};t.a=function(e,t,n,a){void 0===t&&(t=o.b),void 0===n&&(n={}),void 0===a&&(a=[e]);var i=n.event,u=void 0===i?"keydown":i,l=n.target,s=n.options,f=Object(r.useMemo)((function(){var n,r="function"===typeof(n=e)?n:"string"===typeof n?function(e){return e.key===n}:n?function(){return!0}:function(){return!1};return function(e){if(r(e))return t(e)}}),a);c(u,f,l,s)}},,function(e,t,n){"use strict";n.d(t,"a",(function(){return r}));var r=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:21;return crypto.getRandomValues(new Uint8Array(e)).reduce((function(e,t){return e+=(t&=63)<36?t.toString(36):t<62?(t-26).toString(36).toUpperCase():t>62?"-":"_"}),"")}},,,,function(e,t,n){"use strict";var r=n(43),o=60103,a=60106;t.Fragment=60107,t.StrictMode=60108,t.Profiler=60114;var i=60109,u=60110,c=60112;t.Suspense=60113;var l=60115,s=60116;if("function"===typeof Symbol&&Symbol.for){var f=Symbol.for;o=f("react.element"),a=f("react.portal"),t.Fragment=f("react.fragment"),t.StrictMode=f("react.strict_mode"),t.Profiler=f("react.profiler"),i=f("react.provider"),u=f("react.context"),c=f("react.forward_ref"),t.Suspense=f("react.suspense"),l=f("react.memo"),s=f("react.lazy")}var d="function"===typeof Symbol&&Symbol.iterator;function p(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n