diff --git a/.ci/update_windows/update.py b/.ci/update_windows/update.py index cc79a914e..6a04e5e16 100755 --- a/.ci/update_windows/update.py +++ b/.ci/update_windows/update.py @@ -75,6 +75,25 @@ else: print("pulling latest changes") pull(repo) +if "--stable" in sys.argv: + def latest_tag(repo): + versions = [] + for k in repo.references: + try: + prefix = "refs/tags/v" + if k.startswith(prefix): + version = list(map(int, k[len(prefix):].split("."))) + versions.append((version[0] * 10000000000 + version[1] * 100000 + version[2], k)) + except: + pass + versions.sort() + if len(versions) > 0: + return versions[-1][1] + return None + latest_tag = latest_tag(repo) + if latest_tag is not None: + repo.checkout(latest_tag) + print("Done!") self_update = True @@ -115,3 +134,13 @@ if not os.path.exists(req_path) or not files_equal(repo_req_path, req_path): shutil.copy(repo_req_path, req_path) except: pass + + +stable_update_script = os.path.join(repo_path, ".ci/update_windows/update_comfyui_stable.bat") +stable_update_script_to = os.path.join(cur_path, "update_comfyui_stable.bat") + +try: + if not file_size(stable_update_script_to) > 10: + shutil.copy(stable_update_script, stable_update_script_to) +except: + pass diff --git a/.ci/update_windows/update_comfyui_stable.bat b/.ci/update_windows/update_comfyui_stable.bat new file mode 100755 index 000000000..e18010da3 --- /dev/null +++ b/.ci/update_windows/update_comfyui_stable.bat @@ -0,0 +1,8 @@ +@echo off +..\python_embeded\python.exe .\update.py ..\ComfyUI\ --stable +if exist update_new.py ( + move /y update_new.py update.py + echo Running updater again since it got updated. + ..\python_embeded\python.exe .\update.py ..\ComfyUI\ --skip_self_update --stable +) +if "%~1"=="" pause diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000..4391de678 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +/web/assets/** linguist-generated +/web/** linguist-vendored diff --git a/.github/workflows/pullrequest-ci-run.yml b/.github/workflows/pullrequest-ci-run.yml new file mode 100644 index 000000000..691480bcf --- /dev/null +++ b/.github/workflows/pullrequest-ci-run.yml @@ -0,0 +1,53 @@ +# This is the GitHub Workflow that drives full-GPU-enabled tests of pull requests to ComfyUI, when the 'Run-CI-Test' label is added +# Results are reported as checkmarks on the commits, as well as onto https://ci.comfy.org/ +name: Pull Request CI Workflow Runs +on: + pull_request_target: + types: [labeled] + +jobs: + pr-test-stable: + if: ${{ github.event.label.name == 'Run-CI-Test' }} + strategy: + fail-fast: false + matrix: + os: [macos, linux, windows] + python_version: ["3.9", "3.10", "3.11", "3.12"] + cuda_version: ["12.1"] + torch_version: ["stable"] + include: + - os: macos + runner_label: [self-hosted, macOS] + flags: "--use-pytorch-cross-attention" + - os: linux + runner_label: [self-hosted, Linux] + flags: "" + - os: windows + runner_label: [self-hosted, win] + flags: "" + runs-on: ${{ matrix.runner_label }} + steps: + - name: Test Workflows + uses: comfy-org/comfy-action@main + with: + os: ${{ matrix.os }} + python_version: ${{ matrix.python_version }} + torch_version: ${{ matrix.torch_version }} + google_credentials: ${{ secrets.GCS_SERVICE_ACCOUNT_JSON }} + comfyui_flags: ${{ matrix.flags }} + use_prior_commit: 'true' + comment: + if: ${{ github.event.label.name == 'Run-CI-Test' }} + runs-on: ubuntu-latest + permissions: + pull-requests: write + steps: + - uses: actions/github-script@v6 + with: + script: | + github.rest.issues.createComment({ + issue_number: context.issue.number, + owner: context.repo.owner, + repo: context.repo.repo, + body: '(Automated Bot Message) CI Tests are running, you can view the results at https://ci.comfy.org/?branch=${{ github.event.pull_request.number }}%2Fmerge' + }) diff --git a/.github/workflows/test-ci.yml b/.github/workflows/test-ci.yml new file mode 100644 index 000000000..be7622907 --- /dev/null +++ b/.github/workflows/test-ci.yml @@ -0,0 +1,95 @@ +# This is the GitHub Workflow that drives automatic full-GPU-enabled tests of all new commits to the master branch of ComfyUI +# Results are reported as checkmarks on the commits, as well as onto https://ci.comfy.org/ +name: Full Comfy CI Workflow Runs +on: + push: + branches: + - master + paths-ignore: + - 'app/**' + - 'input/**' + - 'output/**' + - 'notebooks/**' + - 'script_examples/**' + - '.github/**' + - 'web/**' + workflow_dispatch: + +jobs: + test-stable: + strategy: + fail-fast: false + matrix: + os: [macos, linux, windows] + python_version: ["3.9", "3.10", "3.11", "3.12"] + cuda_version: ["12.1"] + torch_version: ["stable"] + include: + - os: macos + runner_label: [self-hosted, macOS] + flags: "--use-pytorch-cross-attention" + - os: linux + runner_label: [self-hosted, Linux] + flags: "" + - os: windows + runner_label: [self-hosted, win] + flags: "" + runs-on: ${{ matrix.runner_label }} + steps: + - name: Test Workflows + uses: comfy-org/comfy-action@main + with: + os: ${{ matrix.os }} + python_version: ${{ matrix.python_version }} + torch_version: ${{ matrix.torch_version }} + google_credentials: ${{ secrets.GCS_SERVICE_ACCOUNT_JSON }} + comfyui_flags: ${{ matrix.flags }} + + test-win-nightly: + strategy: + fail-fast: true + matrix: + os: [windows] + python_version: ["3.9", "3.10", "3.11", "3.12"] + cuda_version: ["12.1"] + torch_version: ["nightly"] + include: + - os: windows + runner_label: [self-hosted, win] + flags: "" + runs-on: ${{ matrix.runner_label }} + steps: + - name: Test Workflows + uses: comfy-org/comfy-action@main + with: + os: ${{ matrix.os }} + python_version: ${{ matrix.python_version }} + torch_version: ${{ matrix.torch_version }} + google_credentials: ${{ secrets.GCS_SERVICE_ACCOUNT_JSON }} + comfyui_flags: ${{ matrix.flags }} + + test-unix-nightly: + strategy: + fail-fast: false + matrix: + os: [macos, linux] + python_version: ["3.11"] + cuda_version: ["12.1"] + torch_version: ["nightly"] + include: + - os: macos + runner_label: [self-hosted, macOS] + flags: "--use-pytorch-cross-attention" + - os: linux + runner_label: [self-hosted, Linux] + flags: "" + runs-on: ${{ matrix.runner_label }} + steps: + - name: Test Workflows + uses: comfy-org/comfy-action@main + with: + os: ${{ matrix.os }} + python_version: ${{ matrix.python_version }} + torch_version: ${{ matrix.torch_version }} + google_credentials: ${{ secrets.GCS_SERVICE_ACCOUNT_JSON }} + comfyui_flags: ${{ matrix.flags }} diff --git a/.github/workflows/test-browser.yml b/.github/workflows/test-launch.yml similarity index 50% rename from .github/workflows/test-browser.yml rename to .github/workflows/test-launch.yml index ce0bc37a3..42f1dbe99 100644 --- a/.github/workflows/test-browser.yml +++ b/.github/workflows/test-launch.yml @@ -1,10 +1,4 @@ -# This is a temporary action during frontend TS migration. -# This file should be removed after TS migration is completed. -# The browser test is here to ensure TS repo is working the same way as the -# current JS code. -# If you are adding UI feature, please sync your changes to the TS repo: -# huchenlei/ComfyUI_frontend and update test expectation files accordingly. -name: Playwright Browser Tests CI +name: Test server launches without errors on: push: @@ -21,15 +15,6 @@ jobs: with: repository: "comfyanonymous/ComfyUI" path: "ComfyUI" - - name: Checkout ComfyUI_frontend - uses: actions/checkout@v4 - with: - repository: "huchenlei/ComfyUI_frontend" - path: "ComfyUI_frontend" - ref: "fcc54d803e5b6a9b08a462a1d94899318c96dcbb" - - uses: actions/setup-node@v3 - with: - node-version: lts/* - uses: actions/setup-python@v4 with: python-version: '3.8' @@ -45,16 +30,6 @@ jobs: python main.py --cpu 2>&1 | tee console_output.log & wait-for-it --service 127.0.0.1:8188 -t 600 working-directory: ComfyUI - - name: Install ComfyUI_frontend dependencies - run: | - npm ci - working-directory: ComfyUI_frontend - - name: Install Playwright Browsers - run: npx playwright install --with-deps - working-directory: ComfyUI_frontend - - name: Run Playwright tests - run: npx playwright test - working-directory: ComfyUI_frontend - name: Check for unhandled exceptions in server log run: | if grep -qE "Exception|Error" console_output.log; then @@ -62,12 +37,6 @@ jobs: exit 1 fi working-directory: ComfyUI - - uses: actions/upload-artifact@v4 - if: always() - with: - name: playwright-report - path: ComfyUI_frontend/playwright-report/ - retention-days: 30 - uses: actions/upload-artifact@v4 if: always() with: diff --git a/.github/workflows/test-ui.yaml b/.github/workflows/test-ui.yaml deleted file mode 100644 index d947e9d5f..000000000 --- a/.github/workflows/test-ui.yaml +++ /dev/null @@ -1,30 +0,0 @@ -name: Tests CI - -on: [push, pull_request] - -jobs: - test: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v3 - with: - node-version: 18 - - uses: actions/setup-python@v4 - with: - python-version: '3.10' - - name: Install requirements - run: | - python -m pip install --upgrade pip - pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu - pip install -r requirements.txt - - name: Run Tests - run: | - npm ci - npm run test:generate - npm test -- --verbose - working-directory: ./tests-ui - - name: Run Unit Tests - run: | - pip install -r tests-unit/requirements.txt - python -m pytest tests-unit diff --git a/.gitignore b/.gitignore index 9613759e4..7bfa6731d 100644 --- a/.gitignore +++ b/.gitignore @@ -21,5 +21,5 @@ desktop_shortcut comfyui.log comfyui.prev.log *.log - web_custom_versions/ +.DS_Store diff --git a/comfy/cli_args.py b/comfy/cli_args.py index 2397de3d6..a895c7e10 100644 --- a/comfy/cli_args.py +++ b/comfy/cli_args.py @@ -92,6 +92,10 @@ class LatentPreviewMethod(enum.Enum): parser.add_argument("--preview-method", type=LatentPreviewMethod, default=LatentPreviewMethod.NoPreviews, help="Default preview method for sampler nodes.", action=EnumAction) +cache_group = parser.add_mutually_exclusive_group() +cache_group.add_argument("--cache-classic", action="store_true", help="Use the old style (aggressive) caching.") +cache_group.add_argument("--cache-lru", type=int, default=0, help="Use LRU caching with a maximum of N node results cached. May use more RAM/VRAM.") + attn_group = parser.add_mutually_exclusive_group() attn_group.add_argument("--use-split-cross-attention", action="store_true", help="Use the split cross attention optimization. Ignored when xformers is used.") attn_group.add_argument("--use-quad-cross-attention", action="store_true", help="Use the sub-quadratic cross attention optimization . Ignored when xformers is used.") diff --git a/comfy/controlnet.py b/comfy/controlnet.py index 12e5f16c8..dcfe492ce 100644 --- a/comfy/controlnet.py +++ b/comfy/controlnet.py @@ -1,4 +1,24 @@ +""" + This file is part of ComfyUI. + Copyright (C) 2024 Comfy + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +""" + + import torch +from enum import Enum import math import os import logging @@ -13,6 +33,8 @@ import comfy.cldm.cldm import comfy.t2i_adapter.adapter import comfy.ldm.cascade.controlnet import comfy.cldm.mmdit +import comfy.ldm.hydit.controlnet +import comfy.ldm.flux.controlnet_xlabs def broadcast_image_to(tensor, target_batch_size, batched_number): @@ -33,6 +55,10 @@ def broadcast_image_to(tensor, target_batch_size, batched_number): else: return torch.cat([tensor] * batched_number, dim=0) +class StrengthType(Enum): + CONSTANT = 1 + LINEAR_UP = 2 + class ControlBase: def __init__(self, device=None): self.cond_hint_original = None @@ -51,6 +77,8 @@ class ControlBase: device = comfy.model_management.get_torch_device() self.device = device self.previous_controlnet = None + self.extra_conds = [] + self.strength_type = StrengthType.CONSTANT def set_cond_hint(self, cond_hint, strength=1.0, timestep_percent_range=(0.0, 1.0), vae=None): self.cond_hint_original = cond_hint @@ -93,6 +121,8 @@ class ControlBase: c.latent_format = self.latent_format c.extra_args = self.extra_args.copy() c.vae = self.vae + c.extra_conds = self.extra_conds.copy() + c.strength_type = self.strength_type def inference_memory_requirements(self, dtype): if self.previous_controlnet is not None: @@ -113,7 +143,10 @@ class ControlBase: if x not in applied_to: #memory saving strategy, allow shared tensors and only apply strength to shared tensors once applied_to.add(x) - x *= self.strength + if self.strength_type == StrengthType.CONSTANT: + x *= self.strength + elif self.strength_type == StrengthType.LINEAR_UP: + x *= (self.strength ** float(len(control_output) - i)) if x.dtype != output_dtype: x = x.to(output_dtype) @@ -142,7 +175,7 @@ class ControlBase: class ControlNet(ControlBase): - def __init__(self, control_model=None, global_average_pooling=False, compression_ratio=8, latent_format=None, device=None, load_device=None, manual_cast_dtype=None): + def __init__(self, control_model=None, global_average_pooling=False, compression_ratio=8, latent_format=None, device=None, load_device=None, manual_cast_dtype=None, extra_conds=["y"], strength_type=StrengthType.CONSTANT): super().__init__(device) self.control_model = control_model self.load_device = load_device @@ -154,6 +187,8 @@ class ControlNet(ControlBase): self.model_sampling_current = None self.manual_cast_dtype = manual_cast_dtype self.latent_format = latent_format + self.extra_conds += extra_conds + self.strength_type = strength_type def get_control(self, x_noisy, t, cond, batched_number): control_prev = None @@ -191,13 +226,16 @@ class ControlNet(ControlBase): self.cond_hint = broadcast_image_to(self.cond_hint, x_noisy.shape[0], batched_number) context = cond.get('crossattn_controlnet', cond['c_crossattn']) - y = cond.get('y', None) - if y is not None: - y = y.to(dtype) + extra = self.extra_args.copy() + for c in self.extra_conds: + temp = cond.get(c, None) + if temp is not None: + extra[c] = temp.to(dtype) + timestep = self.model_sampling_current.timestep(t) x_noisy = self.model_sampling_current.calculate_input(t, x_noisy) - control = self.control_model(x=x_noisy.to(dtype), hint=self.cond_hint, timesteps=timestep.float(), context=context.to(dtype), y=y, **self.extra_args) + control = self.control_model(x=x_noisy.to(dtype), hint=self.cond_hint, timesteps=timestep.to(dtype), context=context.to(dtype), **extra) return self.control_merge(control, control_prev, output_dtype) def copy(self): @@ -286,6 +324,7 @@ class ControlLora(ControlNet): ControlBase.__init__(self, device) self.control_weights = control_weights self.global_average_pooling = global_average_pooling + self.extra_conds += ["y"] def pre_run(self, model, percent_to_timestep_function): super().pre_run(model, percent_to_timestep_function) @@ -338,12 +377,8 @@ class ControlLora(ControlNet): def inference_memory_requirements(self, dtype): return comfy.utils.calculate_parameters(self.control_weights) * comfy.model_management.dtype_size(dtype) + ControlBase.inference_memory_requirements(self, dtype) -def load_controlnet_mmdit(sd): - new_sd = comfy.model_detection.convert_diffusers_mmdit(sd, "") - model_config = comfy.model_detection.model_config_from_unet(new_sd, "", True) - num_blocks = comfy.model_detection.count_blocks(new_sd, 'joint_blocks.{}.') - for k in sd: - new_sd[k] = sd[k] +def controlnet_config(sd): + model_config = comfy.model_detection.model_config_from_unet(sd, "", True) supported_inference_dtypes = model_config.supported_inference_dtypes @@ -356,14 +391,27 @@ def load_controlnet_mmdit(sd): else: operations = comfy.ops.disable_weight_init - control_model = comfy.cldm.mmdit.ControlNet(num_blocks=num_blocks, operations=operations, device=load_device, dtype=unet_dtype, **controlnet_config) - missing, unexpected = control_model.load_state_dict(new_sd, strict=False) + return model_config, operations, load_device, unet_dtype, manual_cast_dtype + +def controlnet_load_state_dict(control_model, sd): + missing, unexpected = control_model.load_state_dict(sd, strict=False) if len(missing) > 0: logging.warning("missing controlnet keys: {}".format(missing)) if len(unexpected) > 0: logging.debug("unexpected controlnet keys: {}".format(unexpected)) + return control_model + +def load_controlnet_mmdit(sd): + new_sd = comfy.model_detection.convert_diffusers_mmdit(sd, "") + model_config, operations, load_device, unet_dtype, manual_cast_dtype = controlnet_config(new_sd) + num_blocks = comfy.model_detection.count_blocks(new_sd, 'joint_blocks.{}.') + for k in sd: + new_sd[k] = sd[k] + + control_model = comfy.cldm.mmdit.ControlNet(num_blocks=num_blocks, operations=operations, device=load_device, dtype=unet_dtype, **model_config.unet_config) + control_model = controlnet_load_state_dict(control_model, new_sd) latent_format = comfy.latent_formats.SD3() latent_format.shift_factor = 0 #SD3 controlnet weirdness @@ -371,8 +419,31 @@ def load_controlnet_mmdit(sd): return control +def load_controlnet_hunyuandit(controlnet_data): + model_config, operations, load_device, unet_dtype, manual_cast_dtype = controlnet_config(controlnet_data) + + control_model = comfy.ldm.hydit.controlnet.HunYuanControlNet(operations=operations, device=load_device, dtype=unet_dtype) + control_model = controlnet_load_state_dict(control_model, controlnet_data) + + latent_format = comfy.latent_formats.SDXL() + extra_conds = ['text_embedding_mask', 'encoder_hidden_states_t5', 'text_embedding_mask_t5', 'image_meta_size', 'style', 'cos_cis_img', 'sin_cis_img'] + control = ControlNet(control_model, compression_ratio=1, latent_format=latent_format, load_device=load_device, manual_cast_dtype=manual_cast_dtype, extra_conds=extra_conds, strength_type=StrengthType.CONSTANT) + return control + +def load_controlnet_flux_xlabs(sd): + model_config, operations, load_device, unet_dtype, manual_cast_dtype = controlnet_config(sd) + control_model = comfy.ldm.flux.controlnet_xlabs.ControlNetFlux(operations=operations, device=load_device, dtype=unet_dtype, **model_config.unet_config) + control_model = controlnet_load_state_dict(control_model, sd) + extra_conds = ['y', 'guidance'] + control = ControlNet(control_model, load_device=load_device, manual_cast_dtype=manual_cast_dtype, extra_conds=extra_conds) + return control + + def load_controlnet(ckpt_path, model=None): controlnet_data = comfy.utils.load_torch_file(ckpt_path, safe_load=True) + if 'after_proj_list.18.bias' in controlnet_data.keys(): #Hunyuan DiT + return load_controlnet_hunyuandit(controlnet_data) + if "lora_controlnet" in controlnet_data: return ControlLora(controlnet_data) @@ -430,7 +501,10 @@ def load_controlnet(ckpt_path, model=None): logging.warning("leftover keys: {}".format(leftover_keys)) controlnet_data = new_sd elif "controlnet_blocks.0.weight" in controlnet_data: #SD3 diffusers format - return load_controlnet_mmdit(controlnet_data) + if "double_blocks.0.img_attn.norm.key_norm.scale" in controlnet_data: + return load_controlnet_flux_xlabs(controlnet_data) + else: + return load_controlnet_mmdit(controlnet_data) pth_key = 'control_model.zero_convs.0.0.weight' pth = False diff --git a/comfy/diffusers_load.py b/comfy/diffusers_load.py index 98b888a19..56e63a756 100644 --- a/comfy/diffusers_load.py +++ b/comfy/diffusers_load.py @@ -22,7 +22,7 @@ def load_diffusers(model_path, output_vae=True, output_clip=True, embedding_dire if text_encoder2_path is not None: text_encoder_paths.append(text_encoder2_path) - unet = comfy.sd.load_unet(unet_path) + unet = comfy.sd.load_diffusion_model(unet_path) clip = None if output_clip: diff --git a/comfy/ldm/flux/controlnet_xlabs.py b/comfy/ldm/flux/controlnet_xlabs.py new file mode 100644 index 000000000..3f40021b2 --- /dev/null +++ b/comfy/ldm/flux/controlnet_xlabs.py @@ -0,0 +1,104 @@ +#Original code can be found on: https://github.com/XLabs-AI/x-flux/blob/main/src/flux/controlnet.py + +import torch +from torch import Tensor, nn +from einops import rearrange, repeat + +from .layers import (DoubleStreamBlock, EmbedND, LastLayer, + MLPEmbedder, SingleStreamBlock, + timestep_embedding) + +from .model import Flux +import comfy.ldm.common_dit + + +class ControlNetFlux(Flux): + def __init__(self, image_model=None, dtype=None, device=None, operations=None, **kwargs): + super().__init__(final_layer=False, dtype=dtype, device=device, operations=operations, **kwargs) + + # add ControlNet blocks + self.controlnet_blocks = nn.ModuleList([]) + for _ in range(self.params.depth): + controlnet_block = operations.Linear(self.hidden_size, self.hidden_size, dtype=dtype, device=device) + # controlnet_block = zero_module(controlnet_block) + self.controlnet_blocks.append(controlnet_block) + self.pos_embed_input = operations.Linear(self.in_channels, self.hidden_size, bias=True, dtype=dtype, device=device) + self.gradient_checkpointing = False + self.input_hint_block = nn.Sequential( + operations.Conv2d(3, 16, 3, padding=1, dtype=dtype, device=device), + nn.SiLU(), + operations.Conv2d(16, 16, 3, padding=1, dtype=dtype, device=device), + nn.SiLU(), + operations.Conv2d(16, 16, 3, padding=1, stride=2, dtype=dtype, device=device), + nn.SiLU(), + operations.Conv2d(16, 16, 3, padding=1, dtype=dtype, device=device), + nn.SiLU(), + operations.Conv2d(16, 16, 3, padding=1, stride=2, dtype=dtype, device=device), + nn.SiLU(), + operations.Conv2d(16, 16, 3, padding=1, dtype=dtype, device=device), + nn.SiLU(), + operations.Conv2d(16, 16, 3, padding=1, stride=2, dtype=dtype, device=device), + nn.SiLU(), + operations.Conv2d(16, 16, 3, padding=1, dtype=dtype, device=device) + ) + + def forward_orig( + self, + img: Tensor, + img_ids: Tensor, + controlnet_cond: Tensor, + txt: Tensor, + txt_ids: Tensor, + timesteps: Tensor, + y: Tensor, + guidance: Tensor = None, + ) -> Tensor: + if img.ndim != 3 or txt.ndim != 3: + raise ValueError("Input img and txt tensors must have 3 dimensions.") + + # running on sequences img + img = self.img_in(img) + controlnet_cond = self.input_hint_block(controlnet_cond) + controlnet_cond = rearrange(controlnet_cond, "b c (h ph) (w pw) -> b (h w) (c ph pw)", ph=2, pw=2) + controlnet_cond = self.pos_embed_input(controlnet_cond) + img = img + controlnet_cond + vec = self.time_in(timestep_embedding(timesteps, 256)) + if self.params.guidance_embed: + vec = vec + self.guidance_in(timestep_embedding(guidance, 256)) + vec = vec + self.vector_in(y) + txt = self.txt_in(txt) + + ids = torch.cat((txt_ids, img_ids), dim=1) + pe = self.pe_embedder(ids) + + block_res_samples = () + + for block in self.double_blocks: + img, txt = block(img=img, txt=txt, vec=vec, pe=pe) + block_res_samples = block_res_samples + (img,) + + controlnet_block_res_samples = () + for block_res_sample, controlnet_block in zip(block_res_samples, self.controlnet_blocks): + block_res_sample = controlnet_block(block_res_sample) + controlnet_block_res_samples = controlnet_block_res_samples + (block_res_sample,) + + return {"output": (controlnet_block_res_samples * 10)[:19]} + + def forward(self, x, timesteps, context, y, guidance=None, hint=None, **kwargs): + hint = hint * 2.0 - 1.0 + + bs, c, h, w = x.shape + patch_size = 2 + x = comfy.ldm.common_dit.pad_to_patch_size(x, (patch_size, patch_size)) + + img = rearrange(x, "b c (h ph) (w pw) -> b (h w) (c ph pw)", ph=patch_size, pw=patch_size) + + h_len = ((h + (patch_size // 2)) // patch_size) + w_len = ((w + (patch_size // 2)) // patch_size) + img_ids = torch.zeros((h_len, w_len, 3), device=x.device, dtype=x.dtype) + img_ids[..., 1] = img_ids[..., 1] + torch.linspace(0, h_len - 1, steps=h_len, device=x.device, dtype=x.dtype)[:, None] + img_ids[..., 2] = img_ids[..., 2] + torch.linspace(0, w_len - 1, steps=w_len, device=x.device, dtype=x.dtype)[None, :] + img_ids = repeat(img_ids, "h w c -> b (h w) c", b=bs) + + txt_ids = torch.zeros((bs, context.shape[1], 3), device=x.device, dtype=x.dtype) + return self.forward_orig(img, img_ids, hint, context, txt_ids, timesteps, y, guidance) diff --git a/comfy/ldm/flux/layers.py b/comfy/ldm/flux/layers.py index 99f498106..da0cf61b1 100644 --- a/comfy/ldm/flux/layers.py +++ b/comfy/ldm/flux/layers.py @@ -2,12 +2,12 @@ import math from dataclasses import dataclass import torch -from einops import rearrange from torch import Tensor, nn from .math import attention, rope import comfy.ops + class EmbedND(nn.Module): def __init__(self, dim: int, theta: int, axes_dim: list): super().__init__() @@ -36,9 +36,7 @@ def timestep_embedding(t: Tensor, dim, max_period=10000, time_factor: float = 10 """ t = time_factor * t half = dim // 2 - freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half).to( - t.device - ) + freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32, device=t.device) / half) args = t[:, None].float() * freqs[None] embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1) @@ -48,7 +46,6 @@ def timestep_embedding(t: Tensor, dim, max_period=10000, time_factor: float = 10 embedding = embedding.to(t) return embedding - class MLPEmbedder(nn.Module): def __init__(self, in_dim: int, hidden_dim: int, dtype=None, device=None, operations=None): super().__init__() @@ -94,14 +91,6 @@ class SelfAttention(nn.Module): self.norm = QKNorm(head_dim, dtype=dtype, device=device, operations=operations) self.proj = operations.Linear(dim, dim, dtype=dtype, device=device) - def forward(self, x: Tensor, pe: Tensor) -> Tensor: - qkv = self.qkv(x) - q, k, v = rearrange(qkv, "B L (K H D) -> K B H L D", K=3, H=self.num_heads) - q, k = self.norm(q, k, v) - x = attention(q, k, v, pe=pe) - x = self.proj(x) - return x - @dataclass class ModulationOut: @@ -163,22 +152,21 @@ class DoubleStreamBlock(nn.Module): img_modulated = self.img_norm1(img) img_modulated = (1 + img_mod1.scale) * img_modulated + img_mod1.shift img_qkv = self.img_attn.qkv(img_modulated) - img_q, img_k, img_v = rearrange(img_qkv, "B L (K H D) -> K B H L D", K=3, H=self.num_heads) + img_q, img_k, img_v = img_qkv.view(img_qkv.shape[0], img_qkv.shape[1], 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) img_q, img_k = self.img_attn.norm(img_q, img_k, img_v) # prepare txt for attention txt_modulated = self.txt_norm1(txt) txt_modulated = (1 + txt_mod1.scale) * txt_modulated + txt_mod1.shift txt_qkv = self.txt_attn.qkv(txt_modulated) - txt_q, txt_k, txt_v = rearrange(txt_qkv, "B L (K H D) -> K B H L D", K=3, H=self.num_heads) + txt_q, txt_k, txt_v = txt_qkv.view(txt_qkv.shape[0], txt_qkv.shape[1], 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) txt_q, txt_k = self.txt_attn.norm(txt_q, txt_k, txt_v) # run actual attention - q = torch.cat((txt_q, img_q), dim=2) - k = torch.cat((txt_k, img_k), dim=2) - v = torch.cat((txt_v, img_v), dim=2) + attn = attention(torch.cat((txt_q, img_q), dim=2), + torch.cat((txt_k, img_k), dim=2), + torch.cat((txt_v, img_v), dim=2), pe=pe) - attn = attention(q, k, v, pe=pe) txt_attn, img_attn = attn[:, : txt.shape[1]], attn[:, txt.shape[1] :] # calculate the img bloks @@ -186,8 +174,12 @@ class DoubleStreamBlock(nn.Module): img = img + img_mod2.gate * self.img_mlp((1 + img_mod2.scale) * self.img_norm2(img) + img_mod2.shift) # calculate the txt bloks - txt = txt + txt_mod1.gate * self.txt_attn.proj(txt_attn) - txt = txt + txt_mod2.gate * self.txt_mlp((1 + txt_mod2.scale) * self.txt_norm2(txt) + txt_mod2.shift) + txt += txt_mod1.gate * self.txt_attn.proj(txt_attn) + txt += txt_mod2.gate * self.txt_mlp((1 + txt_mod2.scale) * self.txt_norm2(txt) + txt_mod2.shift) + + if txt.dtype == torch.float16: + txt = txt.clip(-65504, 65504) + return img, txt @@ -232,14 +224,17 @@ class SingleStreamBlock(nn.Module): x_mod = (1 + mod.scale) * self.pre_norm(x) + mod.shift qkv, mlp = torch.split(self.linear1(x_mod), [3 * self.hidden_size, self.mlp_hidden_dim], dim=-1) - q, k, v = rearrange(qkv, "B L (K H D) -> K B H L D", K=3, H=self.num_heads) + q, k, v = qkv.view(qkv.shape[0], qkv.shape[1], 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) q, k = self.norm(q, k, v) # compute attention attn = attention(q, k, v, pe=pe) # compute activation in mlp stream, cat again and run second linear layer output = self.linear2(torch.cat((attn, self.mlp_act(mlp)), 2)) - return x + mod.gate * output + x += mod.gate * output + if x.dtype == torch.float16: + x = x.clip(-65504, 65504) + return x class LastLayer(nn.Module): diff --git a/comfy/ldm/flux/model.py b/comfy/ldm/flux/model.py index db6cf3d22..b5373540a 100644 --- a/comfy/ldm/flux/model.py +++ b/comfy/ldm/flux/model.py @@ -38,7 +38,7 @@ class Flux(nn.Module): Transformer model for flow matching on sequences. """ - def __init__(self, image_model=None, dtype=None, device=None, operations=None, **kwargs): + def __init__(self, image_model=None, final_layer=True, dtype=None, device=None, operations=None, **kwargs): super().__init__() self.dtype = dtype params = FluxParams(**kwargs) @@ -83,7 +83,8 @@ class Flux(nn.Module): ] ) - self.final_layer = LastLayer(self.hidden_size, 1, self.out_channels, dtype=dtype, device=device, operations=operations) + if final_layer: + self.final_layer = LastLayer(self.hidden_size, 1, self.out_channels, dtype=dtype, device=device, operations=operations) def forward_orig( self, @@ -94,6 +95,7 @@ class Flux(nn.Module): timesteps: Tensor, y: Tensor, guidance: Tensor = None, + control=None, ) -> Tensor: if img.ndim != 3 or txt.ndim != 3: raise ValueError("Input img and txt tensors must have 3 dimensions.") @@ -112,8 +114,15 @@ class Flux(nn.Module): ids = torch.cat((txt_ids, img_ids), dim=1) pe = self.pe_embedder(ids) - for block in self.double_blocks: - img, txt = block(img=img, txt=txt, vec=vec, pe=pe) + for i in range(len(self.double_blocks)): + img, txt = self.double_blocks[i](img=img, txt=txt, vec=vec, pe=pe) + + if control is not None: #Controlnet + control_o = control.get("output") + if i < len(control_o): + add = control_o[i] + if add is not None: + img += add img = torch.cat((txt, img), 1) for block in self.single_blocks: @@ -123,7 +132,7 @@ class Flux(nn.Module): img = self.final_layer(img, vec) # (N, T, patch_size ** 2 * out_channels) return img - def forward(self, x, timestep, context, y, guidance, **kwargs): + def forward(self, x, timestep, context, y, guidance, control=None, **kwargs): bs, c, h, w = x.shape patch_size = 2 x = comfy.ldm.common_dit.pad_to_patch_size(x, (patch_size, patch_size)) @@ -138,5 +147,5 @@ class Flux(nn.Module): img_ids = repeat(img_ids, "h w c -> b (h w) c", b=bs) txt_ids = torch.zeros((bs, context.shape[1], 3), device=x.device, dtype=x.dtype) - out = self.forward_orig(img, img_ids, context, txt_ids, timestep, y, guidance) + out = self.forward_orig(img, img_ids, context, txt_ids, timestep, y, guidance, control) return rearrange(out, "b (h w) (c ph pw) -> b c (h ph) (w pw)", h=h_len, w=w_len, ph=2, pw=2)[:,:,:h,:w] diff --git a/comfy/ldm/hydit/attn_layers.py b/comfy/ldm/hydit/attn_layers.py index 920b84286..e2801f714 100644 --- a/comfy/ldm/hydit/attn_layers.py +++ b/comfy/ldm/hydit/attn_layers.py @@ -47,7 +47,7 @@ def reshape_for_broadcast(freqs_cis: Union[torch.Tensor, Tuple[torch.Tensor]], x def rotate_half(x): - x_real, x_imag = x.float().reshape(*x.shape[:-1], -1, 2).unbind(-1) # [B, S, H, D//2] + x_real, x_imag = x.reshape(*x.shape[:-1], -1, 2).unbind(-1) # [B, S, H, D//2] return torch.stack([-x_imag, x_real], dim=-1).flatten(3) @@ -78,10 +78,9 @@ def apply_rotary_emb( xk_out = None if isinstance(freqs_cis, tuple): cos, sin = reshape_for_broadcast(freqs_cis, xq, head_first) # [S, D] - cos, sin = cos.to(xq.device), sin.to(xq.device) - xq_out = (xq.float() * cos + rotate_half(xq.float()) * sin).type_as(xq) + xq_out = (xq * cos + rotate_half(xq) * sin) if xk is not None: - xk_out = (xk.float() * cos + rotate_half(xk.float()) * sin).type_as(xk) + xk_out = (xk * cos + rotate_half(xk) * sin) else: xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2)) # [B, S, H, D//2] freqs_cis = reshape_for_broadcast(freqs_cis, xq_, head_first).to(xq.device) # [S, D//2] --> [1, S, 1, D//2] diff --git a/comfy/ldm/hydit/controlnet.py b/comfy/ldm/hydit/controlnet.py new file mode 100644 index 000000000..cd71fca31 --- /dev/null +++ b/comfy/ldm/hydit/controlnet.py @@ -0,0 +1,321 @@ +from typing import Any, Optional + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from torch.utils import checkpoint + +from comfy.ldm.modules.diffusionmodules.mmdit import ( + Mlp, + TimestepEmbedder, + PatchEmbed, + RMSNorm, +) +from comfy.ldm.modules.diffusionmodules.util import timestep_embedding +from .poolers import AttentionPool + +import comfy.latent_formats +from .models import HunYuanDiTBlock, calc_rope + +from .posemb_layers import get_2d_rotary_pos_embed, get_fill_resize_and_crop + + +class HunYuanControlNet(nn.Module): + """ + HunYuanDiT: Diffusion model with a Transformer backbone. + + Inherit ModelMixin and ConfigMixin to be compatible with the sampler StableDiffusionPipeline of diffusers. + + Inherit PeftAdapterMixin to be compatible with the PEFT training pipeline. + + Parameters + ---------- + args: argparse.Namespace + The arguments parsed by argparse. + input_size: tuple + The size of the input image. + patch_size: int + The size of the patch. + in_channels: int + The number of input channels. + hidden_size: int + The hidden size of the transformer backbone. + depth: int + The number of transformer blocks. + num_heads: int + The number of attention heads. + mlp_ratio: float + The ratio of the hidden size of the MLP in the transformer block. + log_fn: callable + The logging function. + """ + + def __init__( + self, + input_size: tuple = 128, + patch_size: int = 2, + in_channels: int = 4, + hidden_size: int = 1408, + depth: int = 40, + num_heads: int = 16, + mlp_ratio: float = 4.3637, + text_states_dim=1024, + text_states_dim_t5=2048, + text_len=77, + text_len_t5=256, + qk_norm=True, # See http://arxiv.org/abs/2302.05442 for details. + size_cond=False, + use_style_cond=False, + learn_sigma=True, + norm="layer", + log_fn: callable = print, + attn_precision=None, + dtype=None, + device=None, + operations=None, + **kwargs, + ): + super().__init__() + self.log_fn = log_fn + self.depth = depth + self.learn_sigma = learn_sigma + self.in_channels = in_channels + self.out_channels = in_channels * 2 if learn_sigma else in_channels + self.patch_size = patch_size + self.num_heads = num_heads + self.hidden_size = hidden_size + self.text_states_dim = text_states_dim + self.text_states_dim_t5 = text_states_dim_t5 + self.text_len = text_len + self.text_len_t5 = text_len_t5 + self.size_cond = size_cond + self.use_style_cond = use_style_cond + self.norm = norm + self.dtype = dtype + self.latent_format = comfy.latent_formats.SDXL + + self.mlp_t5 = nn.Sequential( + nn.Linear( + self.text_states_dim_t5, + self.text_states_dim_t5 * 4, + bias=True, + dtype=dtype, + device=device, + ), + nn.SiLU(), + nn.Linear( + self.text_states_dim_t5 * 4, + self.text_states_dim, + bias=True, + dtype=dtype, + device=device, + ), + ) + # learnable replace + self.text_embedding_padding = nn.Parameter( + torch.randn( + self.text_len + self.text_len_t5, + self.text_states_dim, + dtype=dtype, + device=device, + ) + ) + + # Attention pooling + pooler_out_dim = 1024 + self.pooler = AttentionPool( + self.text_len_t5, + self.text_states_dim_t5, + num_heads=8, + output_dim=pooler_out_dim, + dtype=dtype, + device=device, + operations=operations, + ) + + # Dimension of the extra input vectors + self.extra_in_dim = pooler_out_dim + + if self.size_cond: + # Image size and crop size conditions + self.extra_in_dim += 6 * 256 + + if self.use_style_cond: + # Here we use a default learned embedder layer for future extension. + self.style_embedder = nn.Embedding( + 1, hidden_size, dtype=dtype, device=device + ) + self.extra_in_dim += hidden_size + + # Text embedding for `add` + self.x_embedder = PatchEmbed( + input_size, + patch_size, + in_channels, + hidden_size, + dtype=dtype, + device=device, + operations=operations, + ) + self.t_embedder = TimestepEmbedder( + hidden_size, dtype=dtype, device=device, operations=operations + ) + self.extra_embedder = nn.Sequential( + operations.Linear( + self.extra_in_dim, hidden_size * 4, dtype=dtype, device=device + ), + nn.SiLU(), + operations.Linear( + hidden_size * 4, hidden_size, bias=True, dtype=dtype, device=device + ), + ) + + # Image embedding + num_patches = self.x_embedder.num_patches + + # HUnYuanDiT Blocks + self.blocks = nn.ModuleList( + [ + HunYuanDiTBlock( + hidden_size=hidden_size, + c_emb_size=hidden_size, + num_heads=num_heads, + mlp_ratio=mlp_ratio, + text_states_dim=self.text_states_dim, + qk_norm=qk_norm, + norm_type=self.norm, + skip=False, + attn_precision=attn_precision, + dtype=dtype, + device=device, + operations=operations, + ) + for _ in range(19) + ] + ) + + # Input zero linear for the first block + self.before_proj = operations.Linear(self.hidden_size, self.hidden_size, dtype=dtype, device=device) + + + # Output zero linear for the every block + self.after_proj_list = nn.ModuleList( + [ + + operations.Linear( + self.hidden_size, self.hidden_size, dtype=dtype, device=device + ) + for _ in range(len(self.blocks)) + ] + ) + + def forward( + self, + x, + hint, + timesteps, + context,#encoder_hidden_states=None, + text_embedding_mask=None, + encoder_hidden_states_t5=None, + text_embedding_mask_t5=None, + image_meta_size=None, + style=None, + return_dict=False, + **kwarg, + ): + """ + Forward pass of the encoder. + + Parameters + ---------- + x: torch.Tensor + (B, D, H, W) + t: torch.Tensor + (B) + encoder_hidden_states: torch.Tensor + CLIP text embedding, (B, L_clip, D) + text_embedding_mask: torch.Tensor + CLIP text embedding mask, (B, L_clip) + encoder_hidden_states_t5: torch.Tensor + T5 text embedding, (B, L_t5, D) + text_embedding_mask_t5: torch.Tensor + T5 text embedding mask, (B, L_t5) + image_meta_size: torch.Tensor + (B, 6) + style: torch.Tensor + (B) + cos_cis_img: torch.Tensor + sin_cis_img: torch.Tensor + return_dict: bool + Whether to return a dictionary. + """ + condition = hint + if condition.shape[0] == 1: + condition = torch.repeat_interleave(condition, x.shape[0], dim=0) + + text_states = context # 2,77,1024 + text_states_t5 = encoder_hidden_states_t5 # 2,256,2048 + text_states_mask = text_embedding_mask.bool() # 2,77 + text_states_t5_mask = text_embedding_mask_t5.bool() # 2,256 + b_t5, l_t5, c_t5 = text_states_t5.shape + text_states_t5 = self.mlp_t5(text_states_t5.view(-1, c_t5)).view(b_t5, l_t5, -1) + + padding = comfy.ops.cast_to_input(self.text_embedding_padding, text_states) + + text_states[:, -self.text_len :] = torch.where( + text_states_mask[:, -self.text_len :].unsqueeze(2), + text_states[:, -self.text_len :], + padding[: self.text_len], + ) + text_states_t5[:, -self.text_len_t5 :] = torch.where( + text_states_t5_mask[:, -self.text_len_t5 :].unsqueeze(2), + text_states_t5[:, -self.text_len_t5 :], + padding[self.text_len :], + ) + + text_states = torch.cat([text_states, text_states_t5], dim=1) # 2,205,1024 + + # _, _, oh, ow = x.shape + # th, tw = oh // self.patch_size, ow // self.patch_size + + # Get image RoPE embedding according to `reso`lution. + freqs_cis_img = calc_rope( + x, self.patch_size, self.hidden_size // self.num_heads + ) # (cos_cis_img, sin_cis_img) + + # ========================= Build time and image embedding ========================= + t = self.t_embedder(timesteps, dtype=self.dtype) + x = self.x_embedder(x) + + # ========================= Concatenate all extra vectors ========================= + # Build text tokens with pooling + extra_vec = self.pooler(encoder_hidden_states_t5) + + # Build image meta size tokens if applicable + # if image_meta_size is not None: + # image_meta_size = timestep_embedding(image_meta_size.view(-1), 256) # [B * 6, 256] + # if image_meta_size.dtype != self.dtype: + # image_meta_size = image_meta_size.half() + # image_meta_size = image_meta_size.view(-1, 6 * 256) + # extra_vec = torch.cat([extra_vec, image_meta_size], dim=1) # [B, D + 6 * 256] + + # Build style tokens + if style is not None: + style_embedding = self.style_embedder(style) + extra_vec = torch.cat([extra_vec, style_embedding], dim=1) + + # Concatenate all extra vectors + c = t + self.extra_embedder(extra_vec) # [B, D] + + # ========================= Deal with Condition ========================= + condition = self.x_embedder(condition) + + # ========================= Forward pass through HunYuanDiT blocks ========================= + controls = [] + x = x + self.before_proj(condition) # add condition + for layer, block in enumerate(self.blocks): + x = block(x, c, text_states, freqs_cis_img) + controls.append(self.after_proj_list[layer](x)) # zero linear for output + + return {"output": controls} diff --git a/comfy/ldm/hydit/models.py b/comfy/ldm/hydit/models.py index c70dbf92a..f3afaad34 100644 --- a/comfy/ldm/hydit/models.py +++ b/comfy/ldm/hydit/models.py @@ -21,6 +21,7 @@ def calc_rope(x, patch_size, head_size): sub_args = [start, stop, (th, tw)] # head_size = HUNYUAN_DIT_CONFIG['DiT-g/2']['hidden_size'] // HUNYUAN_DIT_CONFIG['DiT-g/2']['num_heads'] rope = get_2d_rotary_pos_embed(head_size, *sub_args) + rope = (rope[0].to(x), rope[1].to(x)) return rope @@ -91,6 +92,8 @@ class HunYuanDiTBlock(nn.Module): # Long Skip Connection if self.skip_linear is not None: cat = torch.cat([x, skip], dim=-1) + if cat.dtype != x.dtype: + cat = cat.to(x.dtype) cat = self.skip_norm(cat) x = self.skip_linear(cat) @@ -362,6 +365,8 @@ class HunYuanDiT(nn.Module): c = t + self.extra_embedder(extra_vec) # [B, D] controls = None + if control: + controls = control.get("output", None) # ========================= Forward pass through HunYuanDiT blocks ========================= skips = [] for layer, block in enumerate(self.blocks): diff --git a/comfy/ldm/modules/attention.py b/comfy/ldm/modules/attention.py index 65a8bcf42..85ea406e0 100644 --- a/comfy/ldm/modules/attention.py +++ b/comfy/ldm/modules/attention.py @@ -358,7 +358,7 @@ def attention_xformers(q, k, v, heads, mask=None, attn_precision=None, skip_resh disabled_xformers = True if disabled_xformers: - return attention_pytorch(q, k, v, heads, mask) + return attention_pytorch(q, k, v, heads, mask, skip_reshape=skip_reshape) if skip_reshape: q, k, v = map( diff --git a/comfy/lora.py b/comfy/lora.py index 04e8861c9..3b8b6c162 100644 --- a/comfy/lora.py +++ b/comfy/lora.py @@ -1,3 +1,21 @@ +""" + This file is part of ComfyUI. + Copyright (C) 2024 Comfy + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +""" + import comfy.utils import logging @@ -218,11 +236,17 @@ def model_lora_keys_clip(model, key_map={}): lora_key = "lora_prior_te_text_model_encoder_layers_{}_{}".format(b, LORA_CLIP_MAP[c]) #cascade lora: TODO put lora key prefix in the model config key_map[lora_key] = k - for k in sdk: #OneTrainer SD3 lora - if k.startswith("t5xxl.transformer.") and k.endswith(".weight"): - l_key = k[len("t5xxl.transformer."):-len(".weight")] - lora_key = "lora_te3_{}".format(l_key.replace(".", "_")) - key_map[lora_key] = k + for k in sdk: + if k.endswith(".weight"): + if k.startswith("t5xxl.transformer."):#OneTrainer SD3 lora + l_key = k[len("t5xxl.transformer."):-len(".weight")] + lora_key = "lora_te3_{}".format(l_key.replace(".", "_")) + key_map[lora_key] = k + elif k.startswith("hydit_clip.transformer.bert."): #HunyuanDiT Lora + l_key = k[len("hydit_clip.transformer.bert."):-len(".weight")] + lora_key = "lora_te1_{}".format(l_key.replace(".", "_")) + key_map[lora_key] = k + k = "clip_g.transformer.text_projection.weight" if k in sdk: @@ -245,6 +269,7 @@ def model_lora_keys_unet(model, key_map={}): key_lora = k[len("diffusion_model."):-len(".weight")].replace(".", "_") key_map["lora_unet_{}".format(key_lora)] = k key_map["lora_prior_unet_{}".format(key_lora)] = k #cascade lora: TODO put lora key prefix in the model config + key_map["{}".format(k[:-len(".weight")])] = k #generic lora format without any weird key names diffusers_keys = comfy.utils.unet_to_diffusers(model.model_config.unet_config) for k in diffusers_keys: diff --git a/comfy/model_base.py b/comfy/model_base.py index cb6949649..830bcc68c 100644 --- a/comfy/model_base.py +++ b/comfy/model_base.py @@ -1,3 +1,21 @@ +""" + This file is part of ComfyUI. + Copyright (C) 2024 Comfy + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +""" + import torch import logging from comfy.ldm.modules.diffusionmodules.openaimodel import UNetModel, Timestep @@ -77,10 +95,13 @@ class BaseModel(torch.nn.Module): self.device = device if not unet_config.get("disable_unet_model_creation", False): - if self.manual_cast_dtype is not None: - operations = comfy.ops.manual_cast + if model_config.custom_operations is None: + if self.manual_cast_dtype is not None: + operations = comfy.ops.manual_cast + else: + operations = comfy.ops.disable_weight_init else: - operations = comfy.ops.disable_weight_init + operations = model_config.custom_operations self.diffusion_model = unet_model(**unet_config, device=device, operations=operations) if comfy.model_management.force_channels_last(): self.diffusion_model.to(memory_format=torch.channels_last) diff --git a/comfy/model_detection.py b/comfy/model_detection.py index c47119686..c05975cc9 100644 --- a/comfy/model_detection.py +++ b/comfy/model_detection.py @@ -137,8 +137,8 @@ def detect_unet_config(state_dict, key_prefix): dit_config["hidden_size"] = 3072 dit_config["mlp_ratio"] = 4.0 dit_config["num_heads"] = 24 - dit_config["depth"] = 19 - dit_config["depth_single_blocks"] = 38 + dit_config["depth"] = count_blocks(state_dict_keys, '{}double_blocks.'.format(key_prefix) + '{}.') + dit_config["depth_single_blocks"] = count_blocks(state_dict_keys, '{}single_blocks.'.format(key_prefix) + '{}.') dit_config["axes_dim"] = [16, 56, 56] dit_config["theta"] = 10000 dit_config["qkv_bias"] = True @@ -495,7 +495,12 @@ def model_config_from_diffusers_unet(state_dict): def convert_diffusers_mmdit(state_dict, output_prefix=""): out_sd = {} - if 'transformer_blocks.0.attn.add_q_proj.weight' in state_dict: #SD3 + if 'transformer_blocks.0.attn.norm_added_k.weight' in state_dict: #Flux + depth = count_blocks(state_dict, 'transformer_blocks.{}.') + depth_single_blocks = count_blocks(state_dict, 'single_transformer_blocks.{}.') + hidden_size = state_dict["x_embedder.bias"].shape[0] + sd_map = comfy.utils.flux_to_diffusers({"depth": depth, "depth_single_blocks": depth_single_blocks, "hidden_size": hidden_size}, output_prefix=output_prefix) + elif 'transformer_blocks.0.attn.add_q_proj.weight' in state_dict: #SD3 num_blocks = count_blocks(state_dict, 'transformer_blocks.{}.') depth = state_dict["pos_embed.proj.weight"].shape[0] // 64 sd_map = comfy.utils.mmdit_to_diffusers({"depth": depth, "num_blocks": num_blocks}, output_prefix=output_prefix) @@ -521,7 +526,12 @@ def convert_diffusers_mmdit(state_dict, output_prefix=""): old_weight = out_sd.get(t[0], None) if old_weight is None: old_weight = torch.empty_like(weight) - old_weight = old_weight.repeat([3] + [1] * (len(old_weight.shape) - 1)) + if old_weight.shape[offset[0]] < offset[1] + offset[2]: + exp = list(weight.shape) + exp[offset[0]] = offset[1] + offset[2] + new = torch.empty(exp, device=weight.device, dtype=weight.dtype) + new[:old_weight.shape[0]] = old_weight + old_weight = new w = old_weight.narrow(offset[0], offset[1], offset[2]) else: diff --git a/comfy/model_management.py b/comfy/model_management.py index 994fcd83b..a6996709b 100644 --- a/comfy/model_management.py +++ b/comfy/model_management.py @@ -1,3 +1,21 @@ +""" + This file is part of ComfyUI. + Copyright (C) 2024 Comfy + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +""" + import psutil import logging from enum import Enum @@ -273,9 +291,12 @@ class LoadedModel: def model_memory(self): return self.model.model_size() + def model_offloaded_memory(self): + return self.model.model_size() - self.model.loaded_size() + def model_memory_required(self, device): if device == self.model.current_loaded_device(): - return 0 + return self.model_offloaded_memory() else: return self.model_memory() @@ -287,15 +308,21 @@ class LoadedModel: load_weights = not self.weights_loaded - try: - if lowvram_model_memory > 0 and load_weights: - self.real_model = self.model.patch_model_lowvram(device_to=patch_model_to, lowvram_model_memory=lowvram_model_memory, force_patch_weights=force_patch_weights) - else: - self.real_model = self.model.patch_model(device_to=patch_model_to, patch_weights=load_weights) - except Exception as e: - self.model.unpatch_model(self.model.offload_device) - self.model_unload() - raise e + if self.model.loaded_size() > 0: + use_more_vram = lowvram_model_memory + if use_more_vram == 0: + use_more_vram = 1e32 + self.model_use_more_vram(use_more_vram) + else: + try: + if lowvram_model_memory > 0 and load_weights: + self.real_model = self.model.patch_model_lowvram(device_to=patch_model_to, lowvram_model_memory=lowvram_model_memory, force_patch_weights=force_patch_weights) + else: + self.real_model = self.model.patch_model(device_to=patch_model_to, patch_weights=load_weights) + except Exception as e: + self.model.unpatch_model(self.model.offload_device) + self.model_unload() + raise e if is_intel_xpu() and not args.disable_ipex_optimize: self.real_model = ipex.optimize(self.real_model.eval(), graph_mode=True, concat_linear=True) @@ -304,19 +331,42 @@ class LoadedModel: return self.real_model def should_reload_model(self, force_patch_weights=False): - if force_patch_weights and self.model.lowvram_patch_counter > 0: + if force_patch_weights and self.model.lowvram_patch_counter() > 0: return True return False - def model_unload(self, unpatch_weights=True): + def model_unload(self, memory_to_free=None, unpatch_weights=True): + if memory_to_free is not None: + if memory_to_free < self.model.loaded_size(): + freed = self.model.partially_unload(self.model.offload_device, memory_to_free) + if freed >= memory_to_free: + return False self.model.unpatch_model(self.model.offload_device, unpatch_weights=unpatch_weights) self.model.model_patches_to(self.model.offload_device) self.weights_loaded = self.weights_loaded and not unpatch_weights self.real_model = None + return True + + def model_use_more_vram(self, extra_memory): + return self.model.partially_load(self.device, extra_memory) def __eq__(self, other): return self.model is other.model +def use_more_memory(extra_memory, loaded_models, device): + for m in loaded_models: + if m.device == device: + extra_memory -= m.model_use_more_vram(extra_memory) + if extra_memory <= 0: + break + +def offloaded_memory(loaded_models, device): + offloaded_mem = 0 + for m in loaded_models: + if m.device == device: + offloaded_mem += m.model_offloaded_memory() + return offloaded_mem + def minimum_inference_memory(): return (1024 * 1024 * 1024) * 1.2 @@ -363,11 +413,15 @@ def free_memory(memory_required, device, keep_loaded=[]): for x in sorted(can_unload): i = x[-1] + memory_to_free = None if not DISABLE_SMART_MEMORY: - if get_free_memory(device) > memory_required: + free_mem = get_free_memory(device) + if free_mem > memory_required: break - current_loaded_models[i].model_unload() - unloaded_model.append(i) + memory_to_free = memory_required - free_mem + logging.debug(f"Unloading {current_loaded_models[i].model.model.__class__.__name__}") + if current_loaded_models[i].model_unload(memory_to_free): + unloaded_model.append(i) for i in sorted(unloaded_model, reverse=True): unloaded_models.append(current_loaded_models.pop(i)) @@ -381,15 +435,15 @@ def free_memory(memory_required, device, keep_loaded=[]): soft_empty_cache() return unloaded_models -def load_models_gpu(models, memory_required=0, force_patch_weights=False, minimum_memory_required=None): +def load_models_gpu(models, memory_required=0, force_patch_weights=False, minimum_memory_required=None, force_full_load=False): global vram_state inference_memory = minimum_inference_memory() - extra_mem = max(inference_memory, memory_required) + extra_mem = max(inference_memory, memory_required + 300 * 1024 * 1024) if minimum_memory_required is None: minimum_memory_required = extra_mem else: - minimum_memory_required = max(inference_memory, minimum_memory_required) + minimum_memory_required = max(inference_memory, minimum_memory_required + 300 * 1024 * 1024) models = set(models) @@ -422,12 +476,14 @@ def load_models_gpu(models, memory_required=0, force_patch_weights=False, minimu devs = set(map(lambda a: a.device, models_already_loaded)) for d in devs: if d != torch.device("cpu"): - free_memory(extra_mem, d, models_already_loaded) + free_memory(extra_mem + offloaded_memory(models_already_loaded, d), d, models_already_loaded) free_mem = get_free_memory(d) if free_mem < minimum_memory_required: logging.info("Unloading models for lowram load.") #TODO: partial model unloading when this case happens, also handle the opposite case where models can be unlowvramed. models_to_load = free_memory(minimum_memory_required, d) logging.info("{} models unloaded.".format(len(models_to_load))) + else: + use_more_memory(free_mem - minimum_memory_required, models_already_loaded, d) if len(models_to_load) == 0: return @@ -435,18 +491,21 @@ def load_models_gpu(models, memory_required=0, force_patch_weights=False, minimu total_memory_required = {} for loaded_model in models_to_load: - if unload_model_clones(loaded_model.model, unload_weights_only=True, force_unload=False) == True:#unload clones where the weights are different - total_memory_required[loaded_model.device] = total_memory_required.get(loaded_model.device, 0) + loaded_model.model_memory_required(loaded_model.device) + unload_model_clones(loaded_model.model, unload_weights_only=True, force_unload=False) #unload clones where the weights are different + total_memory_required[loaded_model.device] = total_memory_required.get(loaded_model.device, 0) + loaded_model.model_memory_required(loaded_model.device) - for device in total_memory_required: - if device != torch.device("cpu"): - free_memory(total_memory_required[device] * 1.3 + extra_mem, device, models_already_loaded) + for loaded_model in models_already_loaded: + total_memory_required[loaded_model.device] = total_memory_required.get(loaded_model.device, 0) + loaded_model.model_memory_required(loaded_model.device) for loaded_model in models_to_load: weights_unloaded = unload_model_clones(loaded_model.model, unload_weights_only=False, force_unload=False) #unload the rest of the clones where the weights can stay loaded if weights_unloaded is not None: loaded_model.weights_loaded = not weights_unloaded + for device in total_memory_required: + if device != torch.device("cpu"): + free_memory(total_memory_required[device] * 1.1 + extra_mem, device, models_already_loaded) + for loaded_model in models_to_load: model = loaded_model.model torch_dev = model.load_device @@ -455,7 +514,7 @@ def load_models_gpu(models, memory_required=0, force_patch_weights=False, minimu else: vram_set_state = vram_state lowvram_model_memory = 0 - if lowvram_available and (vram_set_state == VRAMState.LOW_VRAM or vram_set_state == VRAMState.NORMAL_VRAM): + if lowvram_available and (vram_set_state == VRAMState.LOW_VRAM or vram_set_state == VRAMState.NORMAL_VRAM) and not force_full_load: model_size = loaded_model.model_memory_required(torch_dev) current_free_mem = get_free_memory(torch_dev) lowvram_model_memory = max(64 * (1024 * 1024), (current_free_mem - minimum_memory_required), min(current_free_mem * 0.4, current_free_mem - minimum_inference_memory())) @@ -467,6 +526,14 @@ def load_models_gpu(models, memory_required=0, force_patch_weights=False, minimu cur_loaded_model = loaded_model.model_load(lowvram_model_memory, force_patch_weights=force_patch_weights) current_loaded_models.insert(0, loaded_model) + + + devs = set(map(lambda a: a.device, models_already_loaded)) + for d in devs: + if d != torch.device("cpu"): + free_mem = get_free_memory(d) + if free_mem > minimum_memory_required: + use_more_memory(free_mem - minimum_memory_required, models_already_loaded, d) return @@ -562,12 +629,22 @@ def unet_dtype(device=None, model_params=0, supported_dtypes=[torch.float16, tor if model_params * 2 > free_model_memory: return fp8_dtype - if should_use_fp16(device=device, model_params=model_params, manual_cast=True): - if torch.float16 in supported_dtypes: - return torch.float16 - if should_use_bf16(device, model_params=model_params, manual_cast=True): - if torch.bfloat16 in supported_dtypes: - return torch.bfloat16 + for dt in supported_dtypes: + if dt == torch.float16 and should_use_fp16(device=device, model_params=model_params): + if torch.float16 in supported_dtypes: + return torch.float16 + if dt == torch.bfloat16 and should_use_bf16(device, model_params=model_params): + if torch.bfloat16 in supported_dtypes: + return torch.bfloat16 + + for dt in supported_dtypes: + if dt == torch.float16 and should_use_fp16(device=device, model_params=model_params, manual_cast=True): + if torch.float16 in supported_dtypes: + return torch.float16 + if dt == torch.bfloat16 and should_use_bf16(device, model_params=model_params, manual_cast=True): + if torch.bfloat16 in supported_dtypes: + return torch.bfloat16 + return torch.float32 # None means no manual cast @@ -583,13 +660,13 @@ def unet_manual_cast(weight_dtype, inference_device, supported_dtypes=[torch.flo if bf16_supported and weight_dtype == torch.bfloat16: return None - if fp16_supported and torch.float16 in supported_dtypes: - return torch.float16 + for dt in supported_dtypes: + if dt == torch.float16 and fp16_supported: + return torch.float16 + if dt == torch.bfloat16 and bf16_supported: + return torch.bfloat16 - elif bf16_supported and torch.bfloat16 in supported_dtypes: - return torch.bfloat16 - else: - return torch.float32 + return torch.float32 def text_encoder_offload_device(): if args.gpu_only: @@ -608,6 +685,20 @@ def text_encoder_device(): else: return torch.device("cpu") +def text_encoder_initial_device(load_device, offload_device, model_size=0): + if load_device == offload_device or model_size <= 1024 * 1024 * 1024: + return offload_device + + if is_device_mps(load_device): + return offload_device + + mem_l = get_free_memory(load_device) + mem_o = get_free_memory(offload_device) + if mem_l > (mem_o * 0.5) and model_size * 1.2 < mem_l: + return load_device + else: + return offload_device + def text_encoder_dtype(device=None): if args.fp8_e4m3fn_text_enc: return torch.float8_e4m3fn diff --git a/comfy/model_patcher.py b/comfy/model_patcher.py index 430b59879..1edbf24ab 100644 --- a/comfy/model_patcher.py +++ b/comfy/model_patcher.py @@ -1,8 +1,27 @@ +""" + This file is part of ComfyUI. + Copyright (C) 2024 Comfy + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +""" + import torch import copy import inspect import logging import uuid +import collections import comfy.utils import comfy.model_management @@ -63,12 +82,27 @@ def set_model_options_pre_cfg_function(model_options, pre_cfg_function, disable_ model_options["disable_cfg1_optimization"] = True return model_options +def wipe_lowvram_weight(m): + if hasattr(m, "prev_comfy_cast_weights"): + m.comfy_cast_weights = m.prev_comfy_cast_weights + del m.prev_comfy_cast_weights + m.weight_function = None + m.bias_function = None + +class LowVramPatch: + def __init__(self, key, model_patcher): + self.key = key + self.model_patcher = model_patcher + def __call__(self, weight): + return self.model_patcher.calculate_weight(self.model_patcher.patches[self.key], weight, self.key) + + class ModelPatcher: def __init__(self, model, load_device, offload_device, size=0, weight_inplace_update=False): self.size = size self.model = model if not hasattr(self.model, 'device'): - logging.info("Model doesn't have a device attribute.") + logging.debug("Model doesn't have a device attribute.") self.model.device = offload_device elif self.model.device is None: self.model.device = offload_device @@ -82,16 +116,29 @@ class ModelPatcher: self.load_device = load_device self.offload_device = offload_device self.weight_inplace_update = weight_inplace_update - self.model_lowvram = False - self.lowvram_patch_counter = 0 self.patches_uuid = uuid.uuid4() + if not hasattr(self.model, 'model_loaded_weight_memory'): + self.model.model_loaded_weight_memory = 0 + + if not hasattr(self.model, 'lowvram_patch_counter'): + self.model.lowvram_patch_counter = 0 + + if not hasattr(self.model, 'model_lowvram'): + self.model.model_lowvram = False + def model_size(self): if self.size > 0: return self.size self.size = comfy.model_management.module_size(self.model) return self.size + def loaded_size(self): + return self.model.model_loaded_weight_memory + + def lowvram_patch_counter(self): + return self.model.lowvram_patch_counter + def clone(self): n = ModelPatcher(self.model, self.load_device, self.offload_device, self.size, weight_inplace_update=self.weight_inplace_update) n.patches = {} @@ -265,16 +312,16 @@ class ModelPatcher: sd.pop(k) return sd - def patch_weight_to_device(self, key, device_to=None): + def patch_weight_to_device(self, key, device_to=None, inplace_update=False): if key not in self.patches: return weight = comfy.utils.get_attr(self.model, key) - inplace_update = self.weight_inplace_update + inplace_update = self.weight_inplace_update or inplace_update if key not in self.backup: - self.backup[key] = weight.to(device=self.offload_device, copy=inplace_update) + self.backup[key] = collections.namedtuple('Dimension', ['weight', 'inplace_update'])(weight.to(device=self.offload_device, copy=inplace_update), inplace_update) if device_to is not None: temp_weight = comfy.model_management.cast_to_device(weight, device_to, torch.float32, copy=True) @@ -304,28 +351,24 @@ class ModelPatcher: if device_to is not None: self.model.to(device_to) self.model.device = device_to + self.model.model_loaded_weight_memory = self.model_size() return self.model - def patch_model_lowvram(self, device_to=None, lowvram_model_memory=0, force_patch_weights=False): - self.patch_model(device_to, patch_weights=False) - - logging.info("loading in lowvram mode {}".format(lowvram_model_memory/(1024 * 1024))) - class LowVramPatch: - def __init__(self, key, model_patcher): - self.key = key - self.model_patcher = model_patcher - def __call__(self, weight): - return self.model_patcher.calculate_weight(self.model_patcher.patches[self.key], weight, self.key) - + def lowvram_load(self, device_to=None, lowvram_model_memory=0, force_patch_weights=False, full_load=False): mem_counter = 0 patch_counter = 0 + lowvram_counter = 0 for n, m in self.model.named_modules(): lowvram_weight = False - if hasattr(m, "comfy_cast_weights"): + + if not full_load and hasattr(m, "comfy_cast_weights"): module_mem = comfy.model_management.module_size(m) if mem_counter + module_mem >= lowvram_model_memory: lowvram_weight = True + lowvram_counter += 1 + if m.comfy_cast_weights: + continue weight_key = "{}.weight".format(n) bias_key = "{}.bias".format(n) @@ -347,16 +390,40 @@ class ModelPatcher: m.prev_comfy_cast_weights = m.comfy_cast_weights m.comfy_cast_weights = True else: + if hasattr(m, "comfy_cast_weights"): + if m.comfy_cast_weights: + wipe_lowvram_weight(m) + if hasattr(m, "weight"): - self.patch_weight_to_device(weight_key, device_to) - self.patch_weight_to_device(bias_key, device_to) - m.to(device_to) mem_counter += comfy.model_management.module_size(m) + param = list(m.parameters()) + if len(param) > 0: + weight = param[0] + if weight.device == device_to: + continue + + weight_to = None + if full_load:#TODO + weight_to = device_to + self.patch_weight_to_device(weight_key, device_to=weight_to) #TODO: speed this up without OOM + self.patch_weight_to_device(bias_key, device_to=weight_to) + m.to(device_to) logging.debug("lowvram: loaded module regularly {} {}".format(n, m)) - self.model_lowvram = True - self.lowvram_patch_counter = patch_counter + if lowvram_counter > 0: + logging.info("loaded partially {} {} {}".format(lowvram_model_memory / (1024 * 1024), mem_counter / (1024 * 1024), patch_counter)) + self.model.model_lowvram = True + else: + logging.info("loaded completely {} {}".format(lowvram_model_memory / (1024 * 1024), mem_counter / (1024 * 1024))) + self.model.model_lowvram = False + self.model.lowvram_patch_counter += patch_counter self.model.device = device_to + self.model.model_loaded_weight_memory = mem_counter + + + def patch_model_lowvram(self, device_to=None, lowvram_model_memory=0, force_patch_weights=False): + self.patch_model(device_to, patch_weights=False) + self.lowvram_load(device_to, lowvram_model_memory=lowvram_model_memory, force_patch_weights=force_patch_weights) return self.model def calculate_weight(self, patches, weight, key): @@ -529,31 +596,28 @@ class ModelPatcher: def unpatch_model(self, device_to=None, unpatch_weights=True): if unpatch_weights: - if self.model_lowvram: + if self.model.model_lowvram: for m in self.model.modules(): - if hasattr(m, "prev_comfy_cast_weights"): - m.comfy_cast_weights = m.prev_comfy_cast_weights - del m.prev_comfy_cast_weights - m.weight_function = None - m.bias_function = None + wipe_lowvram_weight(m) - self.model_lowvram = False - self.lowvram_patch_counter = 0 + self.model.model_lowvram = False + self.model.lowvram_patch_counter = 0 keys = list(self.backup.keys()) - if self.weight_inplace_update: - for k in keys: - comfy.utils.copy_to_param(self.model, k, self.backup[k]) - else: - for k in keys: - comfy.utils.set_attr_param(self.model, k, self.backup[k]) + for k in keys: + bk = self.backup[k] + if bk.inplace_update: + comfy.utils.copy_to_param(self.model, k, bk.weight) + else: + comfy.utils.set_attr_param(self.model, k, bk.weight) self.backup.clear() if device_to is not None: self.model.to(device_to) self.model.device = device_to + self.model.model_loaded_weight_memory = 0 keys = list(self.object_patches_backup.keys()) for k in keys: @@ -561,5 +625,60 @@ class ModelPatcher: self.object_patches_backup.clear() + def partially_unload(self, device_to, memory_to_free=0): + memory_freed = 0 + patch_counter = 0 + + for n, m in list(self.model.named_modules())[::-1]: + if memory_to_free < memory_freed: + break + + shift_lowvram = False + if hasattr(m, "comfy_cast_weights"): + module_mem = comfy.model_management.module_size(m) + weight_key = "{}.weight".format(n) + bias_key = "{}.bias".format(n) + + + if m.weight is not None and m.weight.device != device_to: + for key in [weight_key, bias_key]: + bk = self.backup.get(key, None) + if bk is not None: + if bk.inplace_update: + comfy.utils.copy_to_param(self.model, key, bk.weight) + else: + comfy.utils.set_attr_param(self.model, key, bk.weight) + self.backup.pop(key) + + m.to(device_to) + if weight_key in self.patches: + m.weight_function = LowVramPatch(weight_key, self) + patch_counter += 1 + if bias_key in self.patches: + m.bias_function = LowVramPatch(bias_key, self) + patch_counter += 1 + + m.prev_comfy_cast_weights = m.comfy_cast_weights + m.comfy_cast_weights = True + memory_freed += module_mem + logging.debug("freed {}".format(n)) + + self.model.model_lowvram = True + self.model.lowvram_patch_counter += patch_counter + self.model.model_loaded_weight_memory -= memory_freed + return memory_freed + + def partially_load(self, device_to, extra_memory=0): + self.unpatch_model(unpatch_weights=False) + self.patch_model(patch_weights=False) + full_load = False + if self.model.model_lowvram == False: + return 0 + if self.model.model_loaded_weight_memory + extra_memory > self.model_size(): + full_load = True + current_used = self.model.model_loaded_weight_memory + self.lowvram_load(device_to, lowvram_model_memory=current_used + extra_memory, full_load=full_load) + return self.model.model_loaded_weight_memory - current_used + def current_loaded_device(self): return self.model.device diff --git a/comfy/sd.py b/comfy/sd.py index 94fc4e590..edd0b51d8 100644 --- a/comfy/sd.py +++ b/comfy/sd.py @@ -62,7 +62,7 @@ def load_lora_for_models(model, clip, lora, strength_model, strength_clip): class CLIP: - def __init__(self, target=None, embedding_directory=None, no_init=False, tokenizer_data={}): + def __init__(self, target=None, embedding_directory=None, no_init=False, tokenizer_data={}, parameters=0): if no_init: return params = target.params.copy() @@ -71,20 +71,24 @@ class CLIP: load_device = model_management.text_encoder_device() offload_device = model_management.text_encoder_offload_device() - params['device'] = offload_device dtype = model_management.text_encoder_dtype(load_device) params['dtype'] = dtype - + params['device'] = model_management.text_encoder_initial_device(load_device, offload_device, parameters * model_management.dtype_size(dtype)) self.cond_stage_model = clip(**(params)) for dt in self.cond_stage_model.dtypes: if not model_management.supports_cast(load_device, dt): load_device = offload_device + if params['device'] != offload_device: + self.cond_stage_model.to(offload_device) + logging.warning("Had to shift TE back.") self.tokenizer = tokenizer(embedding_directory=embedding_directory, tokenizer_data=tokenizer_data) self.patcher = comfy.model_patcher.ModelPatcher(self.cond_stage_model, load_device=load_device, offload_device=offload_device) + if params['device'] == load_device: + model_management.load_models_gpu([self.patcher], force_full_load=True) self.layer_idx = None - logging.debug("CLIP model load device: {}, offload device: {}".format(load_device, offload_device)) + logging.debug("CLIP model load device: {}, offload device: {}, current: {}".format(load_device, offload_device, params['device'])) def clone(self): n = CLIP(no_init=True) @@ -456,7 +460,11 @@ def load_clip(ckpt_paths, embedding_directory=None, clip_type=CLIPType.STABLE_DI clip_target.clip = comfy.text_encoders.sd3_clip.SD3ClipModel clip_target.tokenizer = comfy.text_encoders.sd3_clip.SD3Tokenizer - clip = CLIP(clip_target, embedding_directory=embedding_directory) + parameters = 0 + for c in clip_data: + parameters += comfy.utils.calculate_parameters(c) + + clip = CLIP(clip_target, embedding_directory=embedding_directory, parameters=parameters) for c in clip_data: m, u = clip.load_sd(c) if len(m) > 0: @@ -498,15 +506,19 @@ def load_checkpoint(config_path=None, ckpt_path=None, output_vae=True, output_cl return (model, clip, vae) -def load_checkpoint_guess_config(ckpt_path, output_vae=True, output_clip=True, output_clipvision=False, embedding_directory=None, output_model=True): +def load_checkpoint_guess_config(ckpt_path, output_vae=True, output_clip=True, output_clipvision=False, embedding_directory=None, output_model=True, model_options={}): sd = comfy.utils.load_torch_file(ckpt_path) - sd_keys = sd.keys() + out = load_state_dict_guess_config(sd, output_vae, output_clip, output_clipvision, embedding_directory, output_model, model_options) + if out is None: + raise RuntimeError("ERROR: Could not detect model type of: {}".format(ckpt_path)) + return out + +def load_state_dict_guess_config(sd, output_vae=True, output_clip=True, output_clipvision=False, embedding_directory=None, output_model=True, model_options={}): clip = None clipvision = None vae = None model = None model_patcher = None - clip_target = None diffusion_model_prefix = model_detection.unet_prefix_from_state_dict(sd) parameters = comfy.utils.calculate_parameters(sd, diffusion_model_prefix) @@ -515,13 +527,18 @@ def load_checkpoint_guess_config(ckpt_path, output_vae=True, output_clip=True, o model_config = model_detection.model_config_from_unet(sd, diffusion_model_prefix) if model_config is None: - raise RuntimeError("ERROR: Could not detect model type of: {}".format(ckpt_path)) + return None unet_weight_dtype = list(model_config.supported_inference_dtypes) if weight_dtype is not None: unet_weight_dtype.append(weight_dtype) - unet_dtype = model_management.unet_dtype(model_params=parameters, supported_dtypes=unet_weight_dtype) + model_config.custom_operations = model_options.get("custom_operations", None) + unet_dtype = model_options.get("weight_dtype", None) + + if unet_dtype is None: + unet_dtype = model_management.unet_dtype(model_params=parameters, supported_dtypes=unet_weight_dtype) + manual_cast_dtype = model_management.unet_manual_cast(unet_dtype, load_device, model_config.supported_inference_dtypes) model_config.set_inference_dtype(unet_dtype, manual_cast_dtype) @@ -545,7 +562,8 @@ def load_checkpoint_guess_config(ckpt_path, output_vae=True, output_clip=True, o if clip_target is not None: clip_sd = model_config.process_clip_state_dict(sd) if len(clip_sd) > 0: - clip = CLIP(clip_target, embedding_directory=embedding_directory, tokenizer_data=clip_sd) + parameters = comfy.utils.calculate_parameters(clip_sd) + clip = CLIP(clip_target, embedding_directory=embedding_directory, tokenizer_data=clip_sd, parameters=parameters) m, u = clip.load_sd(clip_sd, full_model=True) if len(m) > 0: m_filter = list(filter(lambda a: ".logit_scale" not in a and ".transformer.text_projection.weight" not in a, m)) @@ -567,12 +585,13 @@ def load_checkpoint_guess_config(ckpt_path, output_vae=True, output_clip=True, o model_patcher = comfy.model_patcher.ModelPatcher(model, load_device=load_device, offload_device=model_management.unet_offload_device()) if inital_load_device != torch.device("cpu"): logging.info("loaded straight to GPU") - model_management.load_model_gpu(model_patcher) + model_management.load_models_gpu([model_patcher], force_full_load=True) return (model_patcher, clip, vae, clipvision) -def load_unet_state_dict(sd, dtype=None): #load unet in diffusers or regular format +def load_diffusion_model_state_dict(sd, model_options={}): #load unet in diffusers or regular format + dtype = model_options.get("dtype", None) #Allow loading unets from checkpoint files diffusion_model_prefix = model_detection.unet_prefix_from_state_dict(sd) @@ -614,6 +633,7 @@ def load_unet_state_dict(sd, dtype=None): #load unet in diffusers or regular for manual_cast_dtype = model_management.unet_manual_cast(unet_dtype, load_device, model_config.supported_inference_dtypes) model_config.set_inference_dtype(unet_dtype, manual_cast_dtype) + model_config.custom_operations = model_options.get("custom_operations", None) model = model_config.get_model(new_sd, "") model = model.to(offload_device) model.load_model_weights(new_sd, "") @@ -622,14 +642,23 @@ def load_unet_state_dict(sd, dtype=None): #load unet in diffusers or regular for logging.info("left over keys in unet: {}".format(left_over)) return comfy.model_patcher.ModelPatcher(model, load_device=load_device, offload_device=offload_device) -def load_unet(unet_path, dtype=None): + +def load_diffusion_model(unet_path, model_options={}): sd = comfy.utils.load_torch_file(unet_path) - model = load_unet_state_dict(sd, dtype=dtype) + model = load_diffusion_model_state_dict(sd, model_options=model_options) if model is None: logging.error("ERROR UNSUPPORTED UNET {}".format(unet_path)) raise RuntimeError("ERROR: Could not detect model type of: {}".format(unet_path)) return model +def load_unet(unet_path, dtype=None): + print("WARNING: the load_unet function has been deprecated and will be removed please switch to: load_diffusion_model") + return load_diffusion_model(unet_path, model_options={"dtype": dtype}) + +def load_unet_state_dict(sd, dtype=None): + print("WARNING: the load_unet_state_dict function has been deprecated and will be removed please switch to: load_diffusion_model_state_dict") + return load_diffusion_model_state_dict(sd, model_options={"dtype": dtype}) + def save_checkpoint(output_path, model, clip=None, vae=None, clip_vision=None, metadata=None, extra_keys={}): clip_sd = None load_models = [model] diff --git a/comfy/sd1_clip.py b/comfy/sd1_clip.py index 6f3a7fd9a..e65cab285 100644 --- a/comfy/sd1_clip.py +++ b/comfy/sd1_clip.py @@ -313,17 +313,14 @@ def expand_directory_list(directories): dirs.add(root) return list(dirs) -def bundled_embed(embed, key): #bundled embedding in lora format +def bundled_embed(embed, prefix, suffix): #bundled embedding in lora format i = 0 out_list = [] - while True: - i += 1 - k = key.format(i) - w = embed.get(k, None) - if w is None: - break - else: - out_list.append(w) + for k in embed: + if k.startswith(prefix) and k.endswith(suffix): + out_list.append(embed[k]) + if len(out_list) == 0: + return None return torch.cat(out_list, dim=0) @@ -392,13 +389,13 @@ def load_embed(embedding_name, embedding_directory, embedding_size, embed_key=No embed_out = torch.cat(out_list, dim=0) elif embed_key is not None and embed_key in embed: embed_out = embed[embed_key] - elif 'bundle_emb.place1.string_to_param.*' in embed: - embed_out = bundled_embed(embed, 'bundle_emb.place{}.string_to_param.*') - elif 'bundle_emb.place1.{}'.format(embed_key) in embed: - embed_out = bundled_embed(embed, 'bundle_emb.place{}.{}'.format('{}', embed_key)) else: - values = embed.values() - embed_out = next(iter(values)) + embed_out = bundled_embed(embed, 'bundle_emb.', '.string_to_param.*') + if embed_out is None: + embed_out = bundled_embed(embed, 'bundle_emb.', '.{}'.format(embed_key)) + if embed_out is None: + values = embed.values() + embed_out = next(iter(values)) return embed_out class SDTokenizer: diff --git a/comfy/supported_models.py b/comfy/supported_models.py index 6cecb9a02..98aa8056b 100644 --- a/comfy/supported_models.py +++ b/comfy/supported_models.py @@ -181,7 +181,7 @@ class SDXL(supported_models_base.BASE): latent_format = latent_formats.SDXL - memory_usage_factor = 0.7 + memory_usage_factor = 0.8 def model_type(self, state_dict, prefix=""): if 'edm_mean' in state_dict and 'edm_std' in state_dict: #Playground V2.5 @@ -642,7 +642,7 @@ class Flux(supported_models_base.BASE): memory_usage_factor = 2.8 - supported_inference_dtypes = [torch.bfloat16, torch.float32] + supported_inference_dtypes = [torch.bfloat16, torch.float16, torch.float32] vae_key_prefix = ["vae."] text_encoder_key_prefix = ["text_encoders."] diff --git a/comfy/supported_models_base.py b/comfy/supported_models_base.py index bc0a7e311..7a2152f91 100644 --- a/comfy/supported_models_base.py +++ b/comfy/supported_models_base.py @@ -1,3 +1,21 @@ +""" + This file is part of ComfyUI. + Copyright (C) 2024 Comfy + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +""" + import torch from . import model_base from . import utils @@ -30,6 +48,7 @@ class BASE: memory_usage_factor = 2.0 manual_cast_dtype = None + custom_operations = None @classmethod def matches(s, unet_config, state_dict=None): diff --git a/comfy/utils.py b/comfy/utils.py index ec7d36607..d0d410d97 100644 --- a/comfy/utils.py +++ b/comfy/utils.py @@ -1,3 +1,22 @@ +""" + This file is part of ComfyUI. + Copyright (C) 2024 Comfy + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +""" + + import torch import math import struct @@ -432,8 +451,33 @@ def flux_to_diffusers(mmdit_config, output_prefix=""): key_map["{}to_k.{}".format(k, end)] = (qkv, (0, hidden_size, hidden_size)) key_map["{}to_v.{}".format(k, end)] = (qkv, (0, hidden_size * 2, hidden_size)) - block_map = {"attn.to_out.0.weight": "img_attn.proj.weight", - "attn.to_out.0.bias": "img_attn.proj.bias", + k = "{}.attn.".format(prefix_from) + qkv = "{}.txt_attn.qkv.{}".format(prefix_to, end) + key_map["{}add_q_proj.{}".format(k, end)] = (qkv, (0, 0, hidden_size)) + key_map["{}add_k_proj.{}".format(k, end)] = (qkv, (0, hidden_size, hidden_size)) + key_map["{}add_v_proj.{}".format(k, end)] = (qkv, (0, hidden_size * 2, hidden_size)) + + block_map = { + "attn.to_out.0.weight": "img_attn.proj.weight", + "attn.to_out.0.bias": "img_attn.proj.bias", + "norm1.linear.weight": "img_mod.lin.weight", + "norm1.linear.bias": "img_mod.lin.bias", + "norm1_context.linear.weight": "txt_mod.lin.weight", + "norm1_context.linear.bias": "txt_mod.lin.bias", + "attn.to_add_out.weight": "txt_attn.proj.weight", + "attn.to_add_out.bias": "txt_attn.proj.bias", + "ff.net.0.proj.weight": "img_mlp.0.weight", + "ff.net.0.proj.bias": "img_mlp.0.bias", + "ff.net.2.weight": "img_mlp.2.weight", + "ff.net.2.bias": "img_mlp.2.bias", + "ff_context.net.0.proj.weight": "txt_mlp.0.weight", + "ff_context.net.0.proj.bias": "txt_mlp.0.bias", + "ff_context.net.2.weight": "txt_mlp.2.weight", + "ff_context.net.2.bias": "txt_mlp.2.bias", + "attn.norm_q.weight": "img_attn.norm.query_norm.scale", + "attn.norm_k.weight": "img_attn.norm.key_norm.scale", + "attn.norm_added_q.weight": "txt_attn.norm.query_norm.scale", + "attn.norm_added_k.weight": "txt_attn.norm.key_norm.scale", } for k in block_map: @@ -449,15 +493,41 @@ def flux_to_diffusers(mmdit_config, output_prefix=""): key_map["{}to_q.{}".format(k, end)] = (qkv, (0, 0, hidden_size)) key_map["{}to_k.{}".format(k, end)] = (qkv, (0, hidden_size, hidden_size)) key_map["{}to_v.{}".format(k, end)] = (qkv, (0, hidden_size * 2, hidden_size)) - key_map["{}proj_mlp.{}".format(k, end)] = (qkv, (0, hidden_size * 3, hidden_size)) + key_map["{}.proj_mlp.{}".format(prefix_from, end)] = (qkv, (0, hidden_size * 3, hidden_size * 4)) - block_map = {#TODO + block_map = { + "norm.linear.weight": "modulation.lin.weight", + "norm.linear.bias": "modulation.lin.bias", + "proj_out.weight": "linear2.weight", + "proj_out.bias": "linear2.bias", + "attn.norm_q.weight": "norm.query_norm.scale", + "attn.norm_k.weight": "norm.key_norm.scale", } for k in block_map: key_map["{}.{}".format(prefix_from, k)] = "{}.{}".format(prefix_to, block_map[k]) - MAP_BASIC = { #TODO + MAP_BASIC = { + ("final_layer.linear.bias", "proj_out.bias"), + ("final_layer.linear.weight", "proj_out.weight"), + ("img_in.bias", "x_embedder.bias"), + ("img_in.weight", "x_embedder.weight"), + ("time_in.in_layer.bias", "time_text_embed.timestep_embedder.linear_1.bias"), + ("time_in.in_layer.weight", "time_text_embed.timestep_embedder.linear_1.weight"), + ("time_in.out_layer.bias", "time_text_embed.timestep_embedder.linear_2.bias"), + ("time_in.out_layer.weight", "time_text_embed.timestep_embedder.linear_2.weight"), + ("txt_in.bias", "context_embedder.bias"), + ("txt_in.weight", "context_embedder.weight"), + ("vector_in.in_layer.bias", "time_text_embed.text_embedder.linear_1.bias"), + ("vector_in.in_layer.weight", "time_text_embed.text_embedder.linear_1.weight"), + ("vector_in.out_layer.bias", "time_text_embed.text_embedder.linear_2.bias"), + ("vector_in.out_layer.weight", "time_text_embed.text_embedder.linear_2.weight"), + ("guidance_in.in_layer.bias", "time_text_embed.guidance_embedder.linear_1.bias"), + ("guidance_in.in_layer.weight", "time_text_embed.guidance_embedder.linear_1.weight"), + ("guidance_in.out_layer.bias", "time_text_embed.guidance_embedder.linear_2.bias"), + ("guidance_in.out_layer.weight", "time_text_embed.guidance_embedder.linear_2.weight"), + ("final_layer.adaLN_modulation.1.bias", "norm_out.linear.bias", swap_scale_shift), + ("final_layer.adaLN_modulation.1.weight", "norm_out.linear.weight", swap_scale_shift), } for k in MAP_BASIC: diff --git a/comfy_execution/caching.py b/comfy_execution/caching.py new file mode 100644 index 000000000..6664a3428 --- /dev/null +++ b/comfy_execution/caching.py @@ -0,0 +1,299 @@ +import itertools +from typing import Sequence, Mapping +from comfy_execution.graph import DynamicPrompt + +import nodes + +from comfy_execution.graph_utils import is_link + +class CacheKeySet: + def __init__(self, dynprompt, node_ids, is_changed_cache): + self.keys = {} + self.subcache_keys = {} + + def add_keys(self, node_ids): + raise NotImplementedError() + + def all_node_ids(self): + return set(self.keys.keys()) + + def get_used_keys(self): + return self.keys.values() + + def get_used_subcache_keys(self): + return self.subcache_keys.values() + + def get_data_key(self, node_id): + return self.keys.get(node_id, None) + + def get_subcache_key(self, node_id): + return self.subcache_keys.get(node_id, None) + +class Unhashable: + def __init__(self): + self.value = float("NaN") + +def to_hashable(obj): + # So that we don't infinitely recurse since frozenset and tuples + # are Sequences. + if isinstance(obj, (int, float, str, bool, type(None))): + return obj + elif isinstance(obj, Mapping): + return frozenset([(to_hashable(k), to_hashable(v)) for k, v in sorted(obj.items())]) + elif isinstance(obj, Sequence): + return frozenset(zip(itertools.count(), [to_hashable(i) for i in obj])) + else: + # TODO - Support other objects like tensors? + return Unhashable() + +class CacheKeySetID(CacheKeySet): + def __init__(self, dynprompt, node_ids, is_changed_cache): + super().__init__(dynprompt, node_ids, is_changed_cache) + self.dynprompt = dynprompt + self.add_keys(node_ids) + + def add_keys(self, node_ids): + for node_id in node_ids: + if node_id in self.keys: + continue + node = self.dynprompt.get_node(node_id) + self.keys[node_id] = (node_id, node["class_type"]) + self.subcache_keys[node_id] = (node_id, node["class_type"]) + +class CacheKeySetInputSignature(CacheKeySet): + def __init__(self, dynprompt, node_ids, is_changed_cache): + super().__init__(dynprompt, node_ids, is_changed_cache) + self.dynprompt = dynprompt + self.is_changed_cache = is_changed_cache + self.add_keys(node_ids) + + def include_node_id_in_input(self) -> bool: + return False + + def add_keys(self, node_ids): + for node_id in node_ids: + if node_id in self.keys: + continue + node = self.dynprompt.get_node(node_id) + self.keys[node_id] = self.get_node_signature(self.dynprompt, node_id) + self.subcache_keys[node_id] = (node_id, node["class_type"]) + + def get_node_signature(self, dynprompt, node_id): + signature = [] + ancestors, order_mapping = self.get_ordered_ancestry(dynprompt, node_id) + signature.append(self.get_immediate_node_signature(dynprompt, node_id, order_mapping)) + for ancestor_id in ancestors: + signature.append(self.get_immediate_node_signature(dynprompt, ancestor_id, order_mapping)) + return to_hashable(signature) + + def get_immediate_node_signature(self, dynprompt, node_id, ancestor_order_mapping): + node = dynprompt.get_node(node_id) + class_type = node["class_type"] + class_def = nodes.NODE_CLASS_MAPPINGS[class_type] + signature = [class_type, self.is_changed_cache.get(node_id)] + if self.include_node_id_in_input() or (hasattr(class_def, "NOT_IDEMPOTENT") and class_def.NOT_IDEMPOTENT): + signature.append(node_id) + inputs = node["inputs"] + for key in sorted(inputs.keys()): + if is_link(inputs[key]): + (ancestor_id, ancestor_socket) = inputs[key] + ancestor_index = ancestor_order_mapping[ancestor_id] + signature.append((key,("ANCESTOR", ancestor_index, ancestor_socket))) + else: + signature.append((key, inputs[key])) + return signature + + # This function returns a list of all ancestors of the given node. The order of the list is + # deterministic based on which specific inputs the ancestor is connected by. + def get_ordered_ancestry(self, dynprompt, node_id): + ancestors = [] + order_mapping = {} + self.get_ordered_ancestry_internal(dynprompt, node_id, ancestors, order_mapping) + return ancestors, order_mapping + + def get_ordered_ancestry_internal(self, dynprompt, node_id, ancestors, order_mapping): + inputs = dynprompt.get_node(node_id)["inputs"] + input_keys = sorted(inputs.keys()) + for key in input_keys: + if is_link(inputs[key]): + ancestor_id = inputs[key][0] + if ancestor_id not in order_mapping: + ancestors.append(ancestor_id) + order_mapping[ancestor_id] = len(ancestors) - 1 + self.get_ordered_ancestry_internal(dynprompt, ancestor_id, ancestors, order_mapping) + +class BasicCache: + def __init__(self, key_class): + self.key_class = key_class + self.initialized = False + self.dynprompt: DynamicPrompt + self.cache_key_set: CacheKeySet + self.cache = {} + self.subcaches = {} + + def set_prompt(self, dynprompt, node_ids, is_changed_cache): + self.dynprompt = dynprompt + self.cache_key_set = self.key_class(dynprompt, node_ids, is_changed_cache) + self.is_changed_cache = is_changed_cache + self.initialized = True + + def all_node_ids(self): + assert self.initialized + node_ids = self.cache_key_set.all_node_ids() + for subcache in self.subcaches.values(): + node_ids = node_ids.union(subcache.all_node_ids()) + return node_ids + + def _clean_cache(self): + preserve_keys = set(self.cache_key_set.get_used_keys()) + to_remove = [] + for key in self.cache: + if key not in preserve_keys: + to_remove.append(key) + for key in to_remove: + del self.cache[key] + + def _clean_subcaches(self): + preserve_subcaches = set(self.cache_key_set.get_used_subcache_keys()) + + to_remove = [] + for key in self.subcaches: + if key not in preserve_subcaches: + to_remove.append(key) + for key in to_remove: + del self.subcaches[key] + + def clean_unused(self): + assert self.initialized + self._clean_cache() + self._clean_subcaches() + + def _set_immediate(self, node_id, value): + assert self.initialized + cache_key = self.cache_key_set.get_data_key(node_id) + self.cache[cache_key] = value + + def _get_immediate(self, node_id): + if not self.initialized: + return None + cache_key = self.cache_key_set.get_data_key(node_id) + if cache_key in self.cache: + return self.cache[cache_key] + else: + return None + + def _ensure_subcache(self, node_id, children_ids): + subcache_key = self.cache_key_set.get_subcache_key(node_id) + subcache = self.subcaches.get(subcache_key, None) + if subcache is None: + subcache = BasicCache(self.key_class) + self.subcaches[subcache_key] = subcache + subcache.set_prompt(self.dynprompt, children_ids, self.is_changed_cache) + return subcache + + def _get_subcache(self, node_id): + assert self.initialized + subcache_key = self.cache_key_set.get_subcache_key(node_id) + if subcache_key in self.subcaches: + return self.subcaches[subcache_key] + else: + return None + + def recursive_debug_dump(self): + result = [] + for key in self.cache: + result.append({"key": key, "value": self.cache[key]}) + for key in self.subcaches: + result.append({"subcache_key": key, "subcache": self.subcaches[key].recursive_debug_dump()}) + return result + +class HierarchicalCache(BasicCache): + def __init__(self, key_class): + super().__init__(key_class) + + def _get_cache_for(self, node_id): + assert self.dynprompt is not None + parent_id = self.dynprompt.get_parent_node_id(node_id) + if parent_id is None: + return self + + hierarchy = [] + while parent_id is not None: + hierarchy.append(parent_id) + parent_id = self.dynprompt.get_parent_node_id(parent_id) + + cache = self + for parent_id in reversed(hierarchy): + cache = cache._get_subcache(parent_id) + if cache is None: + return None + return cache + + def get(self, node_id): + cache = self._get_cache_for(node_id) + if cache is None: + return None + return cache._get_immediate(node_id) + + def set(self, node_id, value): + cache = self._get_cache_for(node_id) + assert cache is not None + cache._set_immediate(node_id, value) + + def ensure_subcache_for(self, node_id, children_ids): + cache = self._get_cache_for(node_id) + assert cache is not None + return cache._ensure_subcache(node_id, children_ids) + +class LRUCache(BasicCache): + def __init__(self, key_class, max_size=100): + super().__init__(key_class) + self.max_size = max_size + self.min_generation = 0 + self.generation = 0 + self.used_generation = {} + self.children = {} + + def set_prompt(self, dynprompt, node_ids, is_changed_cache): + super().set_prompt(dynprompt, node_ids, is_changed_cache) + self.generation += 1 + for node_id in node_ids: + self._mark_used(node_id) + + def clean_unused(self): + while len(self.cache) > self.max_size and self.min_generation < self.generation: + self.min_generation += 1 + to_remove = [key for key in self.cache if self.used_generation[key] < self.min_generation] + for key in to_remove: + del self.cache[key] + del self.used_generation[key] + if key in self.children: + del self.children[key] + self._clean_subcaches() + + def get(self, node_id): + self._mark_used(node_id) + return self._get_immediate(node_id) + + def _mark_used(self, node_id): + cache_key = self.cache_key_set.get_data_key(node_id) + if cache_key is not None: + self.used_generation[cache_key] = self.generation + + def set(self, node_id, value): + self._mark_used(node_id) + return self._set_immediate(node_id, value) + + def ensure_subcache_for(self, node_id, children_ids): + # Just uses subcaches for tracking 'live' nodes + super()._ensure_subcache(node_id, children_ids) + + self.cache_key_set.add_keys(children_ids) + self._mark_used(node_id) + cache_key = self.cache_key_set.get_data_key(node_id) + self.children[cache_key] = [] + for child_id in children_ids: + self._mark_used(child_id) + self.children[cache_key].append(self.cache_key_set.get_data_key(child_id)) + return self + diff --git a/comfy_execution/graph.py b/comfy_execution/graph.py new file mode 100644 index 000000000..303ccae31 --- /dev/null +++ b/comfy_execution/graph.py @@ -0,0 +1,237 @@ +import nodes + +from comfy_execution.graph_utils import is_link + +class DependencyCycleError(Exception): + pass + +class NodeInputError(Exception): + pass + +class NodeNotFoundError(Exception): + pass + +class DynamicPrompt: + def __init__(self, original_prompt): + # The original prompt provided by the user + self.original_prompt = original_prompt + # Any extra pieces of the graph created during execution + self.ephemeral_prompt = {} + self.ephemeral_parents = {} + self.ephemeral_display = {} + + def get_node(self, node_id): + if node_id in self.ephemeral_prompt: + return self.ephemeral_prompt[node_id] + if node_id in self.original_prompt: + return self.original_prompt[node_id] + raise NodeNotFoundError(f"Node {node_id} not found") + + def has_node(self, node_id): + return node_id in self.original_prompt or node_id in self.ephemeral_prompt + + def add_ephemeral_node(self, node_id, node_info, parent_id, display_id): + self.ephemeral_prompt[node_id] = node_info + self.ephemeral_parents[node_id] = parent_id + self.ephemeral_display[node_id] = display_id + + def get_real_node_id(self, node_id): + while node_id in self.ephemeral_parents: + node_id = self.ephemeral_parents[node_id] + return node_id + + def get_parent_node_id(self, node_id): + return self.ephemeral_parents.get(node_id, None) + + def get_display_node_id(self, node_id): + while node_id in self.ephemeral_display: + node_id = self.ephemeral_display[node_id] + return node_id + + def all_node_ids(self): + return set(self.original_prompt.keys()).union(set(self.ephemeral_prompt.keys())) + + def get_original_prompt(self): + return self.original_prompt + +def get_input_info(class_def, input_name): + valid_inputs = class_def.INPUT_TYPES() + input_info = None + input_category = None + if "required" in valid_inputs and input_name in valid_inputs["required"]: + input_category = "required" + input_info = valid_inputs["required"][input_name] + elif "optional" in valid_inputs and input_name in valid_inputs["optional"]: + input_category = "optional" + input_info = valid_inputs["optional"][input_name] + elif "hidden" in valid_inputs and input_name in valid_inputs["hidden"]: + input_category = "hidden" + input_info = valid_inputs["hidden"][input_name] + if input_info is None: + return None, None, None + input_type = input_info[0] + if len(input_info) > 1: + extra_info = input_info[1] + else: + extra_info = {} + return input_type, input_category, extra_info + +class TopologicalSort: + def __init__(self, dynprompt): + self.dynprompt = dynprompt + self.pendingNodes = {} + self.blockCount = {} # Number of nodes this node is directly blocked by + self.blocking = {} # Which nodes are blocked by this node + + def get_input_info(self, unique_id, input_name): + class_type = self.dynprompt.get_node(unique_id)["class_type"] + class_def = nodes.NODE_CLASS_MAPPINGS[class_type] + return get_input_info(class_def, input_name) + + def make_input_strong_link(self, to_node_id, to_input): + inputs = self.dynprompt.get_node(to_node_id)["inputs"] + if to_input not in inputs: + raise NodeInputError(f"Node {to_node_id} says it needs input {to_input}, but there is no input to that node at all") + value = inputs[to_input] + if not is_link(value): + raise NodeInputError(f"Node {to_node_id} says it needs input {to_input}, but that value is a constant") + from_node_id, from_socket = value + self.add_strong_link(from_node_id, from_socket, to_node_id) + + def add_strong_link(self, from_node_id, from_socket, to_node_id): + self.add_node(from_node_id) + if to_node_id not in self.blocking[from_node_id]: + self.blocking[from_node_id][to_node_id] = {} + self.blockCount[to_node_id] += 1 + self.blocking[from_node_id][to_node_id][from_socket] = True + + def add_node(self, unique_id, include_lazy=False, subgraph_nodes=None): + if unique_id in self.pendingNodes: + return + self.pendingNodes[unique_id] = True + self.blockCount[unique_id] = 0 + self.blocking[unique_id] = {} + + inputs = self.dynprompt.get_node(unique_id)["inputs"] + for input_name in inputs: + value = inputs[input_name] + if is_link(value): + from_node_id, from_socket = value + if subgraph_nodes is not None and from_node_id not in subgraph_nodes: + continue + input_type, input_category, input_info = self.get_input_info(unique_id, input_name) + is_lazy = input_info is not None and "lazy" in input_info and input_info["lazy"] + if include_lazy or not is_lazy: + self.add_strong_link(from_node_id, from_socket, unique_id) + + def get_ready_nodes(self): + return [node_id for node_id in self.pendingNodes if self.blockCount[node_id] == 0] + + def pop_node(self, unique_id): + del self.pendingNodes[unique_id] + for blocked_node_id in self.blocking[unique_id]: + self.blockCount[blocked_node_id] -= 1 + del self.blocking[unique_id] + + def is_empty(self): + return len(self.pendingNodes) == 0 + +class ExecutionList(TopologicalSort): + """ + ExecutionList implements a topological dissolve of the graph. After a node is staged for execution, + it can still be returned to the graph after having further dependencies added. + """ + def __init__(self, dynprompt, output_cache): + super().__init__(dynprompt) + self.output_cache = output_cache + self.staged_node_id = None + + def add_strong_link(self, from_node_id, from_socket, to_node_id): + if self.output_cache.get(from_node_id) is not None: + # Nothing to do + return + super().add_strong_link(from_node_id, from_socket, to_node_id) + + def stage_node_execution(self): + assert self.staged_node_id is None + if self.is_empty(): + return None, None, None + available = self.get_ready_nodes() + if len(available) == 0: + cycled_nodes = self.get_nodes_in_cycle() + # Because cycles composed entirely of static nodes are caught during initial validation, + # we will 'blame' the first node in the cycle that is not a static node. + blamed_node = cycled_nodes[0] + for node_id in cycled_nodes: + display_node_id = self.dynprompt.get_display_node_id(node_id) + if display_node_id != node_id: + blamed_node = display_node_id + break + ex = DependencyCycleError("Dependency cycle detected") + error_details = { + "node_id": blamed_node, + "exception_message": str(ex), + "exception_type": "graph.DependencyCycleError", + "traceback": [], + "current_inputs": [] + } + return None, error_details, ex + next_node = available[0] + # If an output node is available, do that first. + # Technically this has no effect on the overall length of execution, but it feels better as a user + # for a PreviewImage to display a result as soon as it can + # Some other heuristics could probably be used here to improve the UX further. + for node_id in available: + class_type = self.dynprompt.get_node(node_id)["class_type"] + class_def = nodes.NODE_CLASS_MAPPINGS[class_type] + if hasattr(class_def, 'OUTPUT_NODE') and class_def.OUTPUT_NODE == True: + next_node = node_id + break + self.staged_node_id = next_node + return self.staged_node_id, None, None + + def unstage_node_execution(self): + assert self.staged_node_id is not None + self.staged_node_id = None + + def complete_node_execution(self): + node_id = self.staged_node_id + self.pop_node(node_id) + self.staged_node_id = None + + def get_nodes_in_cycle(self): + # We'll dissolve the graph in reverse topological order to leave only the nodes in the cycle. + # We're skipping some of the performance optimizations from the original TopologicalSort to keep + # the code simple (and because having a cycle in the first place is a catastrophic error) + blocked_by = { node_id: {} for node_id in self.pendingNodes } + for from_node_id in self.blocking: + for to_node_id in self.blocking[from_node_id]: + if True in self.blocking[from_node_id][to_node_id].values(): + blocked_by[to_node_id][from_node_id] = True + to_remove = [node_id for node_id in blocked_by if len(blocked_by[node_id]) == 0] + while len(to_remove) > 0: + for node_id in to_remove: + for to_node_id in blocked_by: + if node_id in blocked_by[to_node_id]: + del blocked_by[to_node_id][node_id] + del blocked_by[node_id] + to_remove = [node_id for node_id in blocked_by if len(blocked_by[node_id]) == 0] + return list(blocked_by.keys()) + +class ExecutionBlocker: + """ + Return this from a node and any users will be blocked with the given error message. + If the message is None, execution will be blocked silently instead. + Generally, you should avoid using this functionality unless absolutely necessary. Whenever it's + possible, a lazy input will be more efficient and have a better user experience. + This functionality is useful in two cases: + 1. You want to conditionally prevent an output node from executing. (Particularly a built-in node + like SaveImage. For your own output nodes, I would recommend just adding a BOOL input and using + lazy evaluation to let it conditionally disable itself.) + 2. You have a node with multiple possible outputs, some of which are invalid and should not be used. + (I would recommend not making nodes like this in the future -- instead, make multiple nodes with + different outputs. Unfortunately, there are several popular existing nodes using this pattern.) + """ + def __init__(self, message): + self.message = message + diff --git a/comfy_execution/graph_utils.py b/comfy_execution/graph_utils.py new file mode 100644 index 000000000..8595e942d --- /dev/null +++ b/comfy_execution/graph_utils.py @@ -0,0 +1,139 @@ +def is_link(obj): + if not isinstance(obj, list): + return False + if len(obj) != 2: + return False + if not isinstance(obj[0], str): + return False + if not isinstance(obj[1], int) and not isinstance(obj[1], float): + return False + return True + +# The GraphBuilder is just a utility class that outputs graphs in the form expected by the ComfyUI back-end +class GraphBuilder: + _default_prefix_root = "" + _default_prefix_call_index = 0 + _default_prefix_graph_index = 0 + + def __init__(self, prefix = None): + if prefix is None: + self.prefix = GraphBuilder.alloc_prefix() + else: + self.prefix = prefix + self.nodes = {} + self.id_gen = 1 + + @classmethod + def set_default_prefix(cls, prefix_root, call_index, graph_index = 0): + cls._default_prefix_root = prefix_root + cls._default_prefix_call_index = call_index + cls._default_prefix_graph_index = graph_index + + @classmethod + def alloc_prefix(cls, root=None, call_index=None, graph_index=None): + if root is None: + root = GraphBuilder._default_prefix_root + if call_index is None: + call_index = GraphBuilder._default_prefix_call_index + if graph_index is None: + graph_index = GraphBuilder._default_prefix_graph_index + result = f"{root}.{call_index}.{graph_index}." + GraphBuilder._default_prefix_graph_index += 1 + return result + + def node(self, class_type, id=None, **kwargs): + if id is None: + id = str(self.id_gen) + self.id_gen += 1 + id = self.prefix + id + if id in self.nodes: + return self.nodes[id] + + node = Node(id, class_type, kwargs) + self.nodes[id] = node + return node + + def lookup_node(self, id): + id = self.prefix + id + return self.nodes.get(id) + + def finalize(self): + output = {} + for node_id, node in self.nodes.items(): + output[node_id] = node.serialize() + return output + + def replace_node_output(self, node_id, index, new_value): + node_id = self.prefix + node_id + to_remove = [] + for node in self.nodes.values(): + for key, value in node.inputs.items(): + if is_link(value) and value[0] == node_id and value[1] == index: + if new_value is None: + to_remove.append((node, key)) + else: + node.inputs[key] = new_value + for node, key in to_remove: + del node.inputs[key] + + def remove_node(self, id): + id = self.prefix + id + del self.nodes[id] + +class Node: + def __init__(self, id, class_type, inputs): + self.id = id + self.class_type = class_type + self.inputs = inputs + self.override_display_id = None + + def out(self, index): + return [self.id, index] + + def set_input(self, key, value): + if value is None: + if key in self.inputs: + del self.inputs[key] + else: + self.inputs[key] = value + + def get_input(self, key): + return self.inputs.get(key) + + def set_override_display_id(self, override_display_id): + self.override_display_id = override_display_id + + def serialize(self): + serialized = { + "class_type": self.class_type, + "inputs": self.inputs + } + if self.override_display_id is not None: + serialized["override_display_id"] = self.override_display_id + return serialized + +def add_graph_prefix(graph, outputs, prefix): + # Change the node IDs and any internal links + new_graph = {} + for node_id, node_info in graph.items(): + # Make sure the added nodes have unique IDs + new_node_id = prefix + node_id + new_node = { "class_type": node_info["class_type"], "inputs": {} } + for input_name, input_value in node_info.get("inputs", {}).items(): + if is_link(input_value): + new_node["inputs"][input_name] = [prefix + input_value[0], input_value[1]] + else: + new_node["inputs"][input_name] = input_value + new_graph[new_node_id] = new_node + + # Change the node IDs in the outputs + new_outputs = [] + for n in range(len(outputs)): + output = outputs[n] + if is_link(output): + new_outputs.append([prefix + output[0], output[1]]) + else: + new_outputs.append(output) + + return new_graph, tuple(new_outputs) + diff --git a/comfy_extras/nodes_hunyuan.py b/comfy_extras/nodes_hunyuan.py index a3ac8cb06..b03eaf6a2 100644 --- a/comfy_extras/nodes_hunyuan.py +++ b/comfy_extras/nodes_hunyuan.py @@ -19,6 +19,7 @@ class CLIPTextEncodeHunyuanDiT: cond = output.pop("cond") return ([[cond, output]], ) + NODE_CLASS_MAPPINGS = { "CLIPTextEncodeHunyuanDiT": CLIPTextEncodeHunyuanDiT, } diff --git a/comfy_extras/nodes_sd3.py b/comfy_extras/nodes_sd3.py index ae9b85981..046096cba 100644 --- a/comfy_extras/nodes_sd3.py +++ b/comfy_extras/nodes_sd3.py @@ -100,3 +100,8 @@ NODE_CLASS_MAPPINGS = { "CLIPTextEncodeSD3": CLIPTextEncodeSD3, "ControlNetApplySD3": ControlNetApplySD3, } + +NODE_DISPLAY_NAME_MAPPINGS = { + # Sampling + "ControlNetApplySD3": "ControlNetApply SD3 and HunyuanDiT", +} diff --git a/custom_nodes/example_node.py.example b/custom_nodes/example_node.py.example index 72ca3688c..9c68ab769 100644 --- a/custom_nodes/example_node.py.example +++ b/custom_nodes/example_node.py.example @@ -54,7 +54,8 @@ class Example: "min": 0, #Minimum value "max": 4096, #Maximum value "step": 64, #Slider's step - "display": "number" # Cosmetic only: display as "number" or "slider" + "display": "number", # Cosmetic only: display as "number" or "slider" + "lazy": True # Will only be evaluated if check_lazy_status requires it }), "float_field": ("FLOAT", { "default": 1.0, @@ -62,11 +63,14 @@ class Example: "max": 10.0, "step": 0.01, "round": 0.001, #The value representing the precision to round to, will be set to the step value by default. Can be set to False to disable rounding. - "display": "number"}), + "display": "number", + "lazy": True + }), "print_to_screen": (["enable", "disable"],), "string_field": ("STRING", { "multiline": False, #True if you want the field to look like the one on the ClipTextEncode node - "default": "Hello World!" + "default": "Hello World!", + "lazy": True }), }, } @@ -80,6 +84,23 @@ class Example: CATEGORY = "Example" + def check_lazy_status(self, image, string_field, int_field, float_field, print_to_screen): + """ + Return a list of input names that need to be evaluated. + + This function will be called if there are any lazy inputs which have not yet been + evaluated. As long as you return at least one field which has not yet been evaluated + (and more exist), this function will be called again once the value of the requested + field is available. + + Any evaluated inputs will be passed as arguments to this function. Any unevaluated + inputs will have the value None. + """ + if print_to_screen == "enable": + return ["int_field", "float_field", "string_field"] + else: + return [] + def test(self, image, string_field, int_field, float_field, print_to_screen): if print_to_screen == "enable": print(f"""Your input contains: diff --git a/execution.py b/execution.py index d207e1b9e..9018ddabb 100644 --- a/execution.py +++ b/execution.py @@ -5,6 +5,7 @@ import threading import heapq import time import traceback +from enum import Enum import inspect from typing import List, Literal, NamedTuple, Optional @@ -12,102 +13,215 @@ import torch import nodes import comfy.model_management +from comfy_execution.graph import get_input_info, ExecutionList, DynamicPrompt, ExecutionBlocker +from comfy_execution.graph_utils import is_link, GraphBuilder +from comfy_execution.caching import HierarchicalCache, LRUCache, CacheKeySetInputSignature, CacheKeySetID +from comfy.cli_args import args -def get_input_data(inputs, class_def, unique_id, outputs={}, prompt={}, extra_data={}): +class ExecutionResult(Enum): + SUCCESS = 0 + FAILURE = 1 + PENDING = 2 + +class DuplicateNodeError(Exception): + pass + +class IsChangedCache: + def __init__(self, dynprompt, outputs_cache): + self.dynprompt = dynprompt + self.outputs_cache = outputs_cache + self.is_changed = {} + + def get(self, node_id): + if node_id in self.is_changed: + return self.is_changed[node_id] + + node = self.dynprompt.get_node(node_id) + class_type = node["class_type"] + class_def = nodes.NODE_CLASS_MAPPINGS[class_type] + if not hasattr(class_def, "IS_CHANGED"): + self.is_changed[node_id] = False + return self.is_changed[node_id] + + if "is_changed" in node: + self.is_changed[node_id] = node["is_changed"] + return self.is_changed[node_id] + + input_data_all, _ = get_input_data(node["inputs"], class_def, node_id, self.outputs_cache) + try: + is_changed = map_node_over_list(class_def, input_data_all, "IS_CHANGED") + node["is_changed"] = [None if isinstance(x, ExecutionBlocker) else x for x in is_changed] + except: + node["is_changed"] = float("NaN") + finally: + self.is_changed[node_id] = node["is_changed"] + return self.is_changed[node_id] + +class CacheSet: + def __init__(self, lru_size=None): + if lru_size is None or lru_size == 0: + self.init_classic_cache() + else: + self.init_lru_cache(lru_size) + self.all = [self.outputs, self.ui, self.objects] + + # Useful for those with ample RAM/VRAM -- allows experimenting without + # blowing away the cache every time + def init_lru_cache(self, cache_size): + self.outputs = LRUCache(CacheKeySetInputSignature, max_size=cache_size) + self.ui = LRUCache(CacheKeySetInputSignature, max_size=cache_size) + self.objects = HierarchicalCache(CacheKeySetID) + + # Performs like the old cache -- dump data ASAP + def init_classic_cache(self): + self.outputs = HierarchicalCache(CacheKeySetInputSignature) + self.ui = HierarchicalCache(CacheKeySetInputSignature) + self.objects = HierarchicalCache(CacheKeySetID) + + def recursive_debug_dump(self): + result = { + "outputs": self.outputs.recursive_debug_dump(), + "ui": self.ui.recursive_debug_dump(), + } + return result + +def get_input_data(inputs, class_def, unique_id, outputs=None, dynprompt=None, extra_data={}): valid_inputs = class_def.INPUT_TYPES() input_data_all = {} + missing_keys = {} for x in inputs: input_data = inputs[x] - if isinstance(input_data, list): + input_type, input_category, input_info = get_input_info(class_def, x) + def mark_missing(): + missing_keys[x] = True + input_data_all[x] = (None,) + if is_link(input_data) and (not input_info or not input_info.get("rawLink", False)): input_unique_id = input_data[0] output_index = input_data[1] - if input_unique_id not in outputs: - input_data_all[x] = (None,) + if outputs is None: + mark_missing() + continue # This might be a lazily-evaluated input + cached_output = outputs.get(input_unique_id) + if cached_output is None: + mark_missing() continue - obj = outputs[input_unique_id][output_index] + if output_index >= len(cached_output): + mark_missing() + continue + obj = cached_output[output_index] input_data_all[x] = obj - else: - if ("required" in valid_inputs and x in valid_inputs["required"]) or ("optional" in valid_inputs and x in valid_inputs["optional"]): - input_data_all[x] = [input_data] + elif input_category is not None: + input_data_all[x] = [input_data] if "hidden" in valid_inputs: h = valid_inputs["hidden"] for x in h: if h[x] == "PROMPT": - input_data_all[x] = [prompt] + input_data_all[x] = [dynprompt.get_original_prompt() if dynprompt is not None else {}] + if h[x] == "DYNPROMPT": + input_data_all[x] = [dynprompt] if h[x] == "EXTRA_PNGINFO": input_data_all[x] = [extra_data.get('extra_pnginfo', None)] if h[x] == "UNIQUE_ID": input_data_all[x] = [unique_id] - return input_data_all + return input_data_all, missing_keys -def map_node_over_list(obj, input_data_all, func, allow_interrupt=False): +def map_node_over_list(obj, input_data_all, func, allow_interrupt=False, execution_block_cb=None, pre_execute_cb=None): # check if node wants the lists - input_is_list = False - if hasattr(obj, "INPUT_IS_LIST"): - input_is_list = obj.INPUT_IS_LIST + input_is_list = getattr(obj, "INPUT_IS_LIST", False) if len(input_data_all) == 0: max_len_input = 0 else: - max_len_input = max([len(x) for x in input_data_all.values()]) + max_len_input = max(len(x) for x in input_data_all.values()) # get a slice of inputs, repeat last input when list isn't long enough def slice_dict(d, i): - d_new = dict() - for k,v in d.items(): - d_new[k] = v[i if len(v) > i else -1] - return d_new + return {k: v[i if len(v) > i else -1] for k, v in d.items()} results = [] + def process_inputs(inputs, index=None): + if allow_interrupt: + nodes.before_node_execution() + execution_block = None + for k, v in inputs.items(): + if isinstance(v, ExecutionBlocker): + execution_block = execution_block_cb(v) if execution_block_cb else v + break + if execution_block is None: + if pre_execute_cb is not None and index is not None: + pre_execute_cb(index) + results.append(getattr(obj, func)(**inputs)) + else: + results.append(execution_block) + if input_is_list: - if allow_interrupt: - nodes.before_node_execution() - results.append(getattr(obj, func)(**input_data_all)) + process_inputs(input_data_all, 0) elif max_len_input == 0: - if allow_interrupt: - nodes.before_node_execution() - results.append(getattr(obj, func)()) - else: + process_inputs({}) + else: for i in range(max_len_input): - if allow_interrupt: - nodes.before_node_execution() - results.append(getattr(obj, func)(**slice_dict(input_data_all, i))) + input_dict = slice_dict(input_data_all, i) + process_inputs(input_dict, i) return results -def get_output_data(obj, input_data_all): +def merge_result_data(results, obj): + # check which outputs need concatenating + output = [] + output_is_list = [False] * len(results[0]) + if hasattr(obj, "OUTPUT_IS_LIST"): + output_is_list = obj.OUTPUT_IS_LIST + + # merge node execution results + for i, is_list in zip(range(len(results[0])), output_is_list): + if is_list: + output.append([x for o in results for x in o[i]]) + else: + output.append([o[i] for o in results]) + return output + +def get_output_data(obj, input_data_all, execution_block_cb=None, pre_execute_cb=None): results = [] uis = [] - return_values = map_node_over_list(obj, input_data_all, obj.FUNCTION, allow_interrupt=True) - - for r in return_values: + subgraph_results = [] + return_values = map_node_over_list(obj, input_data_all, obj.FUNCTION, allow_interrupt=True, execution_block_cb=execution_block_cb, pre_execute_cb=pre_execute_cb) + has_subgraph = False + for i in range(len(return_values)): + r = return_values[i] if isinstance(r, dict): if 'ui' in r: uis.append(r['ui']) - if 'result' in r: - results.append(r['result']) + if 'expand' in r: + # Perform an expansion, but do not append results + has_subgraph = True + new_graph = r['expand'] + result = r.get("result", None) + if isinstance(result, ExecutionBlocker): + result = tuple([result] * len(obj.RETURN_TYPES)) + subgraph_results.append((new_graph, result)) + elif 'result' in r: + result = r.get("result", None) + if isinstance(result, ExecutionBlocker): + result = tuple([result] * len(obj.RETURN_TYPES)) + results.append(result) + subgraph_results.append((None, result)) else: + if isinstance(r, ExecutionBlocker): + r = tuple([r] * len(obj.RETURN_TYPES)) results.append(r) + subgraph_results.append((None, r)) - output = [] - if len(results) > 0: - # check which outputs need concatenating - output_is_list = [False] * len(results[0]) - if hasattr(obj, "OUTPUT_IS_LIST"): - output_is_list = obj.OUTPUT_IS_LIST - - # merge node execution results - for i, is_list in zip(range(len(results[0])), output_is_list): - if is_list: - output.append([x for o in results for x in o[i]]) - else: - output.append([o[i] for o in results]) - + if has_subgraph: + output = subgraph_results + elif len(results) > 0: + output = merge_result_data(results, obj) + else: + output = [] ui = dict() if len(uis) > 0: ui = {k: [y for x in uis for y in x[k]] for k in uis[0].keys()} - return output, ui + return output, ui, has_subgraph def format_value(x): if x is None: @@ -117,53 +231,145 @@ def format_value(x): else: return str(x) -def recursive_execute(server, prompt, outputs, current_item, extra_data, executed, prompt_id, outputs_ui, object_storage): +def execute(server, dynprompt, caches, current_item, extra_data, executed, prompt_id, execution_list, pending_subgraph_results): unique_id = current_item - inputs = prompt[unique_id]['inputs'] - class_type = prompt[unique_id]['class_type'] + real_node_id = dynprompt.get_real_node_id(unique_id) + display_node_id = dynprompt.get_display_node_id(unique_id) + parent_node_id = dynprompt.get_parent_node_id(unique_id) + inputs = dynprompt.get_node(unique_id)['inputs'] + class_type = dynprompt.get_node(unique_id)['class_type'] class_def = nodes.NODE_CLASS_MAPPINGS[class_type] - if unique_id in outputs: - return (True, None, None) - - for x in inputs: - input_data = inputs[x] - - if isinstance(input_data, list): - input_unique_id = input_data[0] - output_index = input_data[1] - if input_unique_id not in outputs: - result = recursive_execute(server, prompt, outputs, input_unique_id, extra_data, executed, prompt_id, outputs_ui, object_storage) - if result[0] is not True: - # Another node failed further upstream - return result + if caches.outputs.get(unique_id) is not None: + if server.client_id is not None: + cached_output = caches.ui.get(unique_id) or {} + server.send_sync("executed", { "node": unique_id, "display_node": display_node_id, "output": cached_output.get("output",None), "prompt_id": prompt_id }, server.client_id) + return (ExecutionResult.SUCCESS, None, None) input_data_all = None try: - input_data_all = get_input_data(inputs, class_def, unique_id, outputs, prompt, extra_data) - if server.client_id is not None: - server.last_node_id = unique_id - server.send_sync("executing", { "node": unique_id, "prompt_id": prompt_id }, server.client_id) + if unique_id in pending_subgraph_results: + cached_results = pending_subgraph_results[unique_id] + resolved_outputs = [] + for is_subgraph, result in cached_results: + if not is_subgraph: + resolved_outputs.append(result) + else: + resolved_output = [] + for r in result: + if is_link(r): + source_node, source_output = r[0], r[1] + node_output = caches.outputs.get(source_node)[source_output] + for o in node_output: + resolved_output.append(o) - obj = object_storage.get((unique_id, class_type), None) - if obj is None: - obj = class_def() - object_storage[(unique_id, class_type)] = obj - - output_data, output_ui = get_output_data(obj, input_data_all) - outputs[unique_id] = output_data - if len(output_ui) > 0: - outputs_ui[unique_id] = output_ui + else: + resolved_output.append(r) + resolved_outputs.append(tuple(resolved_output)) + output_data = merge_result_data(resolved_outputs, class_def) + output_ui = [] + has_subgraph = False + else: + input_data_all, missing_keys = get_input_data(inputs, class_def, unique_id, caches.outputs, dynprompt, extra_data) if server.client_id is not None: - server.send_sync("executed", { "node": unique_id, "output": output_ui, "prompt_id": prompt_id }, server.client_id) + server.last_node_id = display_node_id + server.send_sync("executing", { "node": unique_id, "display_node": display_node_id, "prompt_id": prompt_id }, server.client_id) + + obj = caches.objects.get(unique_id) + if obj is None: + obj = class_def() + caches.objects.set(unique_id, obj) + + if hasattr(obj, "check_lazy_status"): + required_inputs = map_node_over_list(obj, input_data_all, "check_lazy_status", allow_interrupt=True) + required_inputs = set(sum([r for r in required_inputs if isinstance(r,list)], [])) + required_inputs = [x for x in required_inputs if isinstance(x,str) and ( + x not in input_data_all or x in missing_keys + )] + if len(required_inputs) > 0: + for i in required_inputs: + execution_list.make_input_strong_link(unique_id, i) + return (ExecutionResult.PENDING, None, None) + + def execution_block_cb(block): + if block.message is not None: + mes = { + "prompt_id": prompt_id, + "node_id": unique_id, + "node_type": class_type, + "executed": list(executed), + + "exception_message": f"Execution Blocked: {block.message}", + "exception_type": "ExecutionBlocked", + "traceback": [], + "current_inputs": [], + "current_outputs": [], + } + server.send_sync("execution_error", mes, server.client_id) + return ExecutionBlocker(None) + else: + return block + def pre_execute_cb(call_index): + GraphBuilder.set_default_prefix(unique_id, call_index, 0) + output_data, output_ui, has_subgraph = get_output_data(obj, input_data_all, execution_block_cb=execution_block_cb, pre_execute_cb=pre_execute_cb) + if len(output_ui) > 0: + caches.ui.set(unique_id, { + "meta": { + "node_id": unique_id, + "display_node": display_node_id, + "parent_node": parent_node_id, + "real_node_id": real_node_id, + }, + "output": output_ui + }) + if server.client_id is not None: + server.send_sync("executed", { "node": unique_id, "display_node": display_node_id, "output": output_ui, "prompt_id": prompt_id }, server.client_id) + if has_subgraph: + cached_outputs = [] + new_node_ids = [] + new_output_ids = [] + new_output_links = [] + for i in range(len(output_data)): + new_graph, node_outputs = output_data[i] + if new_graph is None: + cached_outputs.append((False, node_outputs)) + else: + # Check for conflicts + for node_id in new_graph.keys(): + if dynprompt.has_node(node_id): + raise DuplicateNodeError(f"Attempt to add duplicate node {node_id}. Ensure node ids are unique and deterministic or use graph_utils.GraphBuilder.") + for node_id, node_info in new_graph.items(): + new_node_ids.append(node_id) + display_id = node_info.get("override_display_id", unique_id) + dynprompt.add_ephemeral_node(node_id, node_info, unique_id, display_id) + # Figure out if the newly created node is an output node + class_type = node_info["class_type"] + class_def = nodes.NODE_CLASS_MAPPINGS[class_type] + if hasattr(class_def, 'OUTPUT_NODE') and class_def.OUTPUT_NODE == True: + new_output_ids.append(node_id) + for i in range(len(node_outputs)): + if is_link(node_outputs[i]): + from_node_id, from_socket = node_outputs[i][0], node_outputs[i][1] + new_output_links.append((from_node_id, from_socket)) + cached_outputs.append((True, node_outputs)) + new_node_ids = set(new_node_ids) + for cache in caches.all: + cache.ensure_subcache_for(unique_id, new_node_ids).clean_unused() + for node_id in new_output_ids: + execution_list.add_node(node_id) + for link in new_output_links: + execution_list.add_strong_link(link[0], link[1], unique_id) + pending_subgraph_results[unique_id] = cached_outputs + return (ExecutionResult.PENDING, None, None) + caches.outputs.set(unique_id, output_data) except comfy.model_management.InterruptProcessingException as iex: logging.info("Processing interrupted") # skip formatting inputs/outputs error_details = { - "node_id": unique_id, + "node_id": real_node_id, } - return (False, error_details, iex) + return (ExecutionResult.FAILURE, error_details, iex) except Exception as ex: typ, _, tb = sys.exc_info() exception_type = full_type_name(typ) @@ -173,121 +379,36 @@ def recursive_execute(server, prompt, outputs, current_item, extra_data, execute for name, inputs in input_data_all.items(): input_data_formatted[name] = [format_value(x) for x in inputs] - output_data_formatted = {} - for node_id, node_outputs in outputs.items(): - output_data_formatted[node_id] = [[format_value(x) for x in l] for l in node_outputs] - - logging.error(f"!!! Exception during processing!!! {ex}") + logging.error(f"!!! Exception during processing !!! {ex}") logging.error(traceback.format_exc()) error_details = { - "node_id": unique_id, + "node_id": real_node_id, "exception_message": str(ex), "exception_type": exception_type, "traceback": traceback.format_tb(tb), - "current_inputs": input_data_formatted, - "current_outputs": output_data_formatted + "current_inputs": input_data_formatted } - if isinstance(ex, comfy.model_management.OOM_EXCEPTION): logging.error("Got an OOM, unloading all loaded models.") comfy.model_management.unload_all_models() - return (False, error_details, ex) + return (ExecutionResult.FAILURE, error_details, ex) executed.add(unique_id) - return (True, None, None) - -def recursive_will_execute(prompt, outputs, current_item, memo={}): - unique_id = current_item - - if unique_id in memo: - return memo[unique_id] - - inputs = prompt[unique_id]['inputs'] - will_execute = [] - if unique_id in outputs: - return [] - - for x in inputs: - input_data = inputs[x] - if isinstance(input_data, list): - input_unique_id = input_data[0] - output_index = input_data[1] - if input_unique_id not in outputs: - will_execute += recursive_will_execute(prompt, outputs, input_unique_id, memo) - - memo[unique_id] = will_execute + [unique_id] - return memo[unique_id] - -def recursive_output_delete_if_changed(prompt, old_prompt, outputs, current_item): - unique_id = current_item - inputs = prompt[unique_id]['inputs'] - class_type = prompt[unique_id]['class_type'] - class_def = nodes.NODE_CLASS_MAPPINGS[class_type] - - is_changed_old = '' - is_changed = '' - to_delete = False - if hasattr(class_def, 'IS_CHANGED'): - if unique_id in old_prompt and 'is_changed' in old_prompt[unique_id]: - is_changed_old = old_prompt[unique_id]['is_changed'] - if 'is_changed' not in prompt[unique_id]: - input_data_all = get_input_data(inputs, class_def, unique_id, outputs) - if input_data_all is not None: - try: - #is_changed = class_def.IS_CHANGED(**input_data_all) - is_changed = map_node_over_list(class_def, input_data_all, "IS_CHANGED") - prompt[unique_id]['is_changed'] = is_changed - except: - to_delete = True - else: - is_changed = prompt[unique_id]['is_changed'] - - if unique_id not in outputs: - return True - - if not to_delete: - if is_changed != is_changed_old: - to_delete = True - elif unique_id not in old_prompt: - to_delete = True - elif class_type != old_prompt[unique_id]['class_type']: - to_delete = True - elif inputs == old_prompt[unique_id]['inputs']: - for x in inputs: - input_data = inputs[x] - - if isinstance(input_data, list): - input_unique_id = input_data[0] - output_index = input_data[1] - if input_unique_id in outputs: - to_delete = recursive_output_delete_if_changed(prompt, old_prompt, outputs, input_unique_id) - else: - to_delete = True - if to_delete: - break - else: - to_delete = True - - if to_delete: - d = outputs.pop(unique_id) - del d - return to_delete + return (ExecutionResult.SUCCESS, None, None) class PromptExecutor: - def __init__(self, server): + def __init__(self, server, lru_size=None): + self.lru_size = lru_size self.server = server self.reset() def reset(self): - self.outputs = {} - self.object_storage = {} - self.outputs_ui = {} + self.caches = CacheSet(self.lru_size) self.status_messages = [] self.success = True - self.old_prompt = {} def add_message(self, event, data: dict, broadcast: bool): data = { @@ -318,27 +439,14 @@ class PromptExecutor: "node_id": node_id, "node_type": class_type, "executed": list(executed), - "exception_message": error["exception_message"], "exception_type": error["exception_type"], "traceback": error["traceback"], "current_inputs": error["current_inputs"], - "current_outputs": error["current_outputs"], + "current_outputs": list(current_outputs), } self.add_message("execution_error", mes, broadcast=False) - # Next, remove the subsequent outputs since they will not be executed - to_delete = [] - for o in self.outputs: - if (o not in current_outputs) and (o not in executed): - to_delete += [o] - if o in self.old_prompt: - d = self.old_prompt.pop(o) - del d - for o in to_delete: - d = self.outputs.pop(o) - del d - def execute(self, prompt, prompt_id, extra_data={}, execute_outputs=[]): nodes.interrupt_processing(False) @@ -351,65 +459,58 @@ class PromptExecutor: self.add_message("execution_start", { "prompt_id": prompt_id}, broadcast=False) with torch.inference_mode(): - #delete cached outputs if nodes don't exist for them - to_delete = [] - for o in self.outputs: - if o not in prompt: - to_delete += [o] - for o in to_delete: - d = self.outputs.pop(o) - del d - to_delete = [] - for o in self.object_storage: - if o[0] not in prompt: - to_delete += [o] - else: - p = prompt[o[0]] - if o[1] != p['class_type']: - to_delete += [o] - for o in to_delete: - d = self.object_storage.pop(o) - del d + dynamic_prompt = DynamicPrompt(prompt) + is_changed_cache = IsChangedCache(dynamic_prompt, self.caches.outputs) + for cache in self.caches.all: + cache.set_prompt(dynamic_prompt, prompt.keys(), is_changed_cache) + cache.clean_unused() - for x in prompt: - recursive_output_delete_if_changed(prompt, self.old_prompt, self.outputs, x) - - current_outputs = set(self.outputs.keys()) - for x in list(self.outputs_ui.keys()): - if x not in current_outputs: - d = self.outputs_ui.pop(x) - del d + cached_nodes = [] + for node_id in prompt: + if self.caches.outputs.get(node_id) is not None: + cached_nodes.append(node_id) comfy.model_management.cleanup_models(keep_clone_weights_loaded=True) self.add_message("execution_cached", - { "nodes": list(current_outputs) , "prompt_id": prompt_id}, + { "nodes": cached_nodes, "prompt_id": prompt_id}, broadcast=False) + pending_subgraph_results = {} executed = set() - output_node_id = None - to_execute = [] - + execution_list = ExecutionList(dynamic_prompt, self.caches.outputs) + current_outputs = self.caches.outputs.all_node_ids() for node_id in list(execute_outputs): - to_execute += [(0, node_id)] + execution_list.add_node(node_id) - while len(to_execute) > 0: - #always execute the output that depends on the least amount of unexecuted nodes first - memo = {} - to_execute = sorted(list(map(lambda a: (len(recursive_will_execute(prompt, self.outputs, a[-1], memo)), a[-1]), to_execute))) - output_node_id = to_execute.pop(0)[-1] - - # This call shouldn't raise anything if there's an error deep in - # the actual SD code, instead it will report the node where the - # error was raised - self.success, error, ex = recursive_execute(self.server, prompt, self.outputs, output_node_id, extra_data, executed, prompt_id, self.outputs_ui, self.object_storage) - if self.success is not True: - self.handle_execution_error(prompt_id, prompt, current_outputs, executed, error, ex) + while not execution_list.is_empty(): + node_id, error, ex = execution_list.stage_node_execution() + if error is not None: + self.handle_execution_error(prompt_id, dynamic_prompt.original_prompt, current_outputs, executed, error, ex) break + + result, error, ex = execute(self.server, dynamic_prompt, self.caches, node_id, extra_data, executed, prompt_id, execution_list, pending_subgraph_results) + if result == ExecutionResult.FAILURE: + self.handle_execution_error(prompt_id, dynamic_prompt.original_prompt, current_outputs, executed, error, ex) + break + elif result == ExecutionResult.PENDING: + execution_list.unstage_node_execution() + else: # result == ExecutionResult.SUCCESS: + execution_list.complete_node_execution() else: # Only execute when the while-loop ends without break self.add_message("execution_success", { "prompt_id": prompt_id }, broadcast=False) - for x in executed: - self.old_prompt[x] = copy.deepcopy(prompt[x]) + ui_outputs = {} + meta_outputs = {} + all_node_ids = self.caches.ui.all_node_ids() + for node_id in all_node_ids: + ui_info = self.caches.ui.get(node_id) + if ui_info is not None: + ui_outputs[node_id] = ui_info["output"] + meta_outputs[node_id] = ui_info["meta"] + self.history_result = { + "outputs": ui_outputs, + "meta": meta_outputs, + } self.server.last_node_id = None if comfy.model_management.DISABLE_SMART_MEMORY: comfy.model_management.unload_all_models() @@ -426,31 +527,37 @@ def validate_inputs(prompt, item, validated): obj_class = nodes.NODE_CLASS_MAPPINGS[class_type] class_inputs = obj_class.INPUT_TYPES() - required_inputs = class_inputs['required'] + valid_inputs = set(class_inputs.get('required',{})).union(set(class_inputs.get('optional',{}))) errors = [] valid = True validate_function_inputs = [] + validate_has_kwargs = False if hasattr(obj_class, "VALIDATE_INPUTS"): - validate_function_inputs = inspect.getfullargspec(obj_class.VALIDATE_INPUTS).args + argspec = inspect.getfullargspec(obj_class.VALIDATE_INPUTS) + validate_function_inputs = argspec.args + validate_has_kwargs = argspec.varkw is not None + received_types = {} - for x in required_inputs: + for x in valid_inputs: + type_input, input_category, extra_info = get_input_info(obj_class, x) + assert extra_info is not None if x not in inputs: - error = { - "type": "required_input_missing", - "message": "Required input is missing", - "details": f"{x}", - "extra_info": { - "input_name": x + if input_category == "required": + error = { + "type": "required_input_missing", + "message": "Required input is missing", + "details": f"{x}", + "extra_info": { + "input_name": x + } } - } - errors.append(error) + errors.append(error) continue val = inputs[x] - info = required_inputs[x] - type_input = info[0] + info = (type_input, extra_info) if isinstance(val, list): if len(val) != 2: error = { @@ -469,8 +576,9 @@ def validate_inputs(prompt, item, validated): o_id = val[0] o_class_type = prompt[o_id]['class_type'] r = nodes.NODE_CLASS_MAPPINGS[o_class_type].RETURN_TYPES - if r[val[1]] != type_input: - received_type = r[val[1]] + received_type = r[val[1]] + received_types[x] = received_type + if 'input_types' not in validate_function_inputs and received_type != type_input: details = f"{x}, {received_type} != {type_input}" error = { "type": "return_type_mismatch", @@ -521,6 +629,9 @@ def validate_inputs(prompt, item, validated): if type_input == "STRING": val = str(val) inputs[x] = val + if type_input == "BOOLEAN": + val = bool(val) + inputs[x] = val except Exception as ex: error = { "type": "invalid_input_type", @@ -536,11 +647,11 @@ def validate_inputs(prompt, item, validated): errors.append(error) continue - if len(info) > 1: - if "min" in info[1] and val < info[1]["min"]: + if x not in validate_function_inputs and not validate_has_kwargs: + if "min" in extra_info and val < extra_info["min"]: error = { "type": "value_smaller_than_min", - "message": "Value {} smaller than min of {}".format(val, info[1]["min"]), + "message": "Value {} smaller than min of {}".format(val, extra_info["min"]), "details": f"{x}", "extra_info": { "input_name": x, @@ -550,10 +661,10 @@ def validate_inputs(prompt, item, validated): } errors.append(error) continue - if "max" in info[1] and val > info[1]["max"]: + if "max" in extra_info and val > extra_info["max"]: error = { "type": "value_bigger_than_max", - "message": "Value {} bigger than max of {}".format(val, info[1]["max"]), + "message": "Value {} bigger than max of {}".format(val, extra_info["max"]), "details": f"{x}", "extra_info": { "input_name": x, @@ -564,7 +675,6 @@ def validate_inputs(prompt, item, validated): errors.append(error) continue - if x not in validate_function_inputs: if isinstance(type_input, list): if val not in type_input: input_config = info @@ -591,18 +701,20 @@ def validate_inputs(prompt, item, validated): errors.append(error) continue - if len(validate_function_inputs) > 0: - input_data_all = get_input_data(inputs, obj_class, unique_id) + if len(validate_function_inputs) > 0 or validate_has_kwargs: + input_data_all, _ = get_input_data(inputs, obj_class, unique_id) input_filtered = {} for x in input_data_all: - if x in validate_function_inputs: + if x in validate_function_inputs or validate_has_kwargs: input_filtered[x] = input_data_all[x] + if 'input_types' in validate_function_inputs: + input_filtered['input_types'] = [received_types] #ret = obj_class.VALIDATE_INPUTS(**input_filtered) ret = map_node_over_list(obj_class, input_filtered, "VALIDATE_INPUTS") for x in input_filtered: for i, r in enumerate(ret): - if r is not True: + if r is not True and not isinstance(r, ExecutionBlocker): details = f"{x}" if r is not False: details += f" - {str(r)}" @@ -613,8 +725,6 @@ def validate_inputs(prompt, item, validated): "details": details, "extra_info": { "input_name": x, - "input_config": info, - "received_value": val, } } errors.append(error) @@ -780,7 +890,7 @@ class PromptQueue: completed: bool messages: List[str] - def task_done(self, item_id, outputs, + def task_done(self, item_id, history_result, status: Optional['PromptQueue.ExecutionStatus']): with self.mutex: prompt = self.currently_running.pop(item_id) @@ -793,9 +903,10 @@ class PromptQueue: self.history[prompt[1]] = { "prompt": prompt, - "outputs": copy.deepcopy(outputs), + "outputs": {}, 'status': status_dict, } + self.history[prompt[1]].update(history_result) self.server.queue_updated() def get_current_queue(self): diff --git a/main.py b/main.py index 479643b84..e9d6ed209 100644 --- a/main.py +++ b/main.py @@ -101,7 +101,7 @@ def cuda_malloc_warning(): logging.warning("\nWARNING: this card most likely does not support cuda-malloc, if you get \"CUDA error\" please run ComfyUI with: --disable-cuda-malloc\n") def prompt_worker(q, server): - e = execution.PromptExecutor(server) + e = execution.PromptExecutor(server, lru_size=args.cache_lru) last_gc_collect = 0 need_gc = False gc_collect_interval = 10.0 @@ -121,7 +121,7 @@ def prompt_worker(q, server): e.execute(item[2], prompt_id, item[3], item[4]) need_gc = True q.task_done(item_id, - e.outputs_ui, + e.history_result, status=execution.PromptQueue.ExecutionStatus( status_str='success' if e.success else 'error', completed=e.success, @@ -261,6 +261,7 @@ if __name__ == "__main__": call_on_start = startup_server try: + loop.run_until_complete(server.setup()) loop.run_until_complete(run(server, address=args.listen, port=args.port, verbose=not args.dont_print_server, call_on_start=call_on_start)) except KeyboardInterrupt: logging.info("\nStopped server") diff --git a/model_filemanager/__init__.py b/model_filemanager/__init__.py new file mode 100644 index 000000000..e318351c0 --- /dev/null +++ b/model_filemanager/__init__.py @@ -0,0 +1,2 @@ +# model_manager/__init__.py +from .download_models import download_model, DownloadModelStatus, DownloadStatusType, create_model_path, check_file_exists, track_download_progress, validate_model_subdirectory, validate_filename diff --git a/model_filemanager/download_models.py b/model_filemanager/download_models.py new file mode 100644 index 000000000..712d59328 --- /dev/null +++ b/model_filemanager/download_models.py @@ -0,0 +1,240 @@ +from __future__ import annotations +import aiohttp +import os +import traceback +import logging +from folder_paths import models_dir +import re +from typing import Callable, Any, Optional, Awaitable, Dict +from enum import Enum +import time +from dataclasses import dataclass + + +class DownloadStatusType(Enum): + PENDING = "pending" + IN_PROGRESS = "in_progress" + COMPLETED = "completed" + ERROR = "error" + +@dataclass +class DownloadModelStatus(): + status: str + progress_percentage: float + message: str + already_existed: bool = False + + def __init__(self, status: DownloadStatusType, progress_percentage: float, message: str, already_existed: bool): + self.status = status.value # Store the string value of the Enum + self.progress_percentage = progress_percentage + self.message = message + self.already_existed = already_existed + + def to_dict(self) -> Dict[str, Any]: + return { + "status": self.status, + "progress_percentage": self.progress_percentage, + "message": self.message, + "already_existed": self.already_existed + } + +async def download_model(model_download_request: Callable[[str], Awaitable[aiohttp.ClientResponse]], + model_name: str, + model_url: str, + model_sub_directory: str, + progress_callback: Callable[[str, DownloadModelStatus], Awaitable[Any]], + progress_interval: float = 1.0) -> DownloadModelStatus: + """ + Download a model file from a given URL into the models directory. + + Args: + model_download_request (Callable[[str], Awaitable[aiohttp.ClientResponse]]): + A function that makes an HTTP request. This makes it easier to mock in unit tests. + model_name (str): + The name of the model file to be downloaded. This will be the filename on disk. + model_url (str): + The URL from which to download the model. + model_sub_directory (str): + The subdirectory within the main models directory where the model + should be saved (e.g., 'checkpoints', 'loras', etc.). + progress_callback (Callable[[str, DownloadModelStatus], Awaitable[Any]]): + An asynchronous function to call with progress updates. + + Returns: + DownloadModelStatus: The result of the download operation. + """ + if not validate_model_subdirectory(model_sub_directory): + return DownloadModelStatus( + DownloadStatusType.ERROR, + 0, + "Invalid model subdirectory", + False + ) + + if not validate_filename(model_name): + return DownloadModelStatus( + DownloadStatusType.ERROR, + 0, + "Invalid model name", + False + ) + + file_path, relative_path = create_model_path(model_name, model_sub_directory, models_dir) + existing_file = await check_file_exists(file_path, model_name, progress_callback, relative_path) + if existing_file: + return existing_file + + try: + status = DownloadModelStatus(DownloadStatusType.PENDING, 0, f"Starting download of {model_name}", False) + await progress_callback(relative_path, status) + + response = await model_download_request(model_url) + if response.status != 200: + error_message = f"Failed to download {model_name}. Status code: {response.status}" + logging.error(error_message) + status = DownloadModelStatus(DownloadStatusType.ERROR, 0, error_message, False) + await progress_callback(relative_path, status) + return DownloadModelStatus(DownloadStatusType.ERROR, 0, error_message, False) + + return await track_download_progress(response, file_path, model_name, progress_callback, relative_path, progress_interval) + + except Exception as e: + logging.error(f"Error in downloading model: {e}") + return await handle_download_error(e, model_name, progress_callback, relative_path) + + +def create_model_path(model_name: str, model_directory: str, models_base_dir: str) -> tuple[str, str]: + full_model_dir = os.path.join(models_base_dir, model_directory) + os.makedirs(full_model_dir, exist_ok=True) + file_path = os.path.join(full_model_dir, model_name) + + # Ensure the resulting path is still within the base directory + abs_file_path = os.path.abspath(file_path) + abs_base_dir = os.path.abspath(str(models_base_dir)) + if os.path.commonprefix([abs_file_path, abs_base_dir]) != abs_base_dir: + raise Exception(f"Invalid model directory: {model_directory}/{model_name}") + + + relative_path = '/'.join([model_directory, model_name]) + return file_path, relative_path + +async def check_file_exists(file_path: str, + model_name: str, + progress_callback: Callable[[str, DownloadModelStatus], Awaitable[Any]], + relative_path: str) -> Optional[DownloadModelStatus]: + if os.path.exists(file_path): + status = DownloadModelStatus(DownloadStatusType.COMPLETED, 100, f"{model_name} already exists", True) + await progress_callback(relative_path, status) + return status + return None + + +async def track_download_progress(response: aiohttp.ClientResponse, + file_path: str, + model_name: str, + progress_callback: Callable[[str, DownloadModelStatus], Awaitable[Any]], + relative_path: str, + interval: float = 1.0) -> DownloadModelStatus: + try: + total_size = int(response.headers.get('Content-Length', 0)) + downloaded = 0 + last_update_time = time.time() + + async def update_progress(): + nonlocal last_update_time + progress = (downloaded / total_size) * 100 if total_size > 0 else 0 + status = DownloadModelStatus(DownloadStatusType.IN_PROGRESS, progress, f"Downloading {model_name}", False) + await progress_callback(relative_path, status) + last_update_time = time.time() + + with open(file_path, 'wb') as f: + chunk_iterator = response.content.iter_chunked(8192) + while True: + try: + chunk = await chunk_iterator.__anext__() + except StopAsyncIteration: + break + f.write(chunk) + downloaded += len(chunk) + + if time.time() - last_update_time >= interval: + await update_progress() + + await update_progress() + + logging.info(f"Successfully downloaded {model_name}. Total downloaded: {downloaded}") + status = DownloadModelStatus(DownloadStatusType.COMPLETED, 100, f"Successfully downloaded {model_name}", False) + await progress_callback(relative_path, status) + + return status + except Exception as e: + logging.error(f"Error in track_download_progress: {e}") + logging.error(traceback.format_exc()) + return await handle_download_error(e, model_name, progress_callback, relative_path) + +async def handle_download_error(e: Exception, + model_name: str, + progress_callback: Callable[[str, DownloadModelStatus], Any], + relative_path: str) -> DownloadModelStatus: + error_message = f"Error downloading {model_name}: {str(e)}" + status = DownloadModelStatus(DownloadStatusType.ERROR, 0, error_message, False) + await progress_callback(relative_path, status) + return status + +def validate_model_subdirectory(model_subdirectory: str) -> bool: + """ + Validate that the model subdirectory is safe to install into. + Must not contain relative paths, nested paths or special characters + other than underscores and hyphens. + + Args: + model_subdirectory (str): The subdirectory for the specific model type. + + Returns: + bool: True if the subdirectory is safe, False otherwise. + """ + if len(model_subdirectory) > 50: + return False + + if '..' in model_subdirectory or '/' in model_subdirectory: + return False + + if not re.match(r'^[a-zA-Z0-9_-]+$', model_subdirectory): + return False + + return True + +def validate_filename(filename: str)-> bool: + """ + Validate a filename to ensure it's safe and doesn't contain any path traversal attempts. + + Args: + filename (str): The filename to validate + + Returns: + bool: True if the filename is valid, False otherwise + """ + if not filename.lower().endswith(('.sft', '.safetensors')): + return False + + # Check if the filename is empty, None, or just whitespace + if not filename or not filename.strip(): + return False + + # Check for any directory traversal attempts or invalid characters + if any(char in filename for char in ['..', '/', '\\', '\n', '\r', '\t', '\0']): + return False + + # Check if the filename starts with a dot (hidden file) + if filename.startswith('.'): + return False + + # Use a whitelist of allowed characters + if not re.match(r'^[a-zA-Z0-9_\-. ]+$', filename): + return False + + # Ensure the filename isn't too long + if len(filename) > 255: + return False + + return True diff --git a/nodes.py b/nodes.py index d4df08664..66a45a369 100644 --- a/nodes.py +++ b/nodes.py @@ -47,11 +47,18 @@ MAX_RESOLUTION=16384 class CLIPTextEncode: @classmethod def INPUT_TYPES(s): - return {"required": {"text": ("STRING", {"multiline": True, "dynamicPrompts": True}), "clip": ("CLIP", )}} + return { + "required": { + "text": ("STRING", {"multiline": True, "dynamicPrompts": True, "tooltip": "The text to be encoded."}), + "clip": ("CLIP", {"tooltip": "The CLIP model used for encoding the text."}) + } + } RETURN_TYPES = ("CONDITIONING",) + OUTPUT_TOOLTIPS = ("A conditioning containing the embedded text used to guide the diffusion model.",) FUNCTION = "encode" CATEGORY = "conditioning" + DESCRIPTION = "Encodes a text prompt using a CLIP model into an embedding that can be used to guide the diffusion model towards generating specific images." def encode(self, clip, text): tokens = clip.tokenize(text) @@ -260,11 +267,18 @@ class ConditioningSetTimestepRange: class VAEDecode: @classmethod def INPUT_TYPES(s): - return {"required": { "samples": ("LATENT", ), "vae": ("VAE", )}} + return { + "required": { + "samples": ("LATENT", {"tooltip": "The latent to be decoded."}), + "vae": ("VAE", {"tooltip": "The VAE model used for decoding the latent."}) + } + } RETURN_TYPES = ("IMAGE",) + OUTPUT_TOOLTIPS = ("The decoded image.",) FUNCTION = "decode" CATEGORY = "latent" + DESCRIPTION = "Decodes latent images back into pixel space images." def decode(self, vae, samples): return (vae.decode(samples["samples"]), ) @@ -506,12 +520,19 @@ class CheckpointLoader: class CheckpointLoaderSimple: @classmethod def INPUT_TYPES(s): - return {"required": { "ckpt_name": (folder_paths.get_filename_list("checkpoints"), ), - }} + return { + "required": { + "ckpt_name": (folder_paths.get_filename_list("checkpoints"), {"tooltip": "The name of the checkpoint (model) to load."}), + } + } RETURN_TYPES = ("MODEL", "CLIP", "VAE") + OUTPUT_TOOLTIPS = ("The model used for denoising latents.", + "The CLIP model used for encoding text prompts.", + "The VAE model used for encoding and decoding images to and from latent space.") FUNCTION = "load_checkpoint" CATEGORY = "loaders" + DESCRIPTION = "Loads a diffusion model checkpoint, diffusion models are used to denoise latents." def load_checkpoint(self, ckpt_name): ckpt_path = folder_paths.get_full_path("checkpoints", ckpt_name) @@ -582,16 +603,22 @@ class LoraLoader: @classmethod def INPUT_TYPES(s): - return {"required": { "model": ("MODEL",), - "clip": ("CLIP", ), - "lora_name": (folder_paths.get_filename_list("loras"), ), - "strength_model": ("FLOAT", {"default": 1.0, "min": -100.0, "max": 100.0, "step": 0.01}), - "strength_clip": ("FLOAT", {"default": 1.0, "min": -100.0, "max": 100.0, "step": 0.01}), - }} + return { + "required": { + "model": ("MODEL", {"tooltip": "The diffusion model the LoRA will be applied to."}), + "clip": ("CLIP", {"tooltip": "The CLIP model the LoRA will be applied to."}), + "lora_name": (folder_paths.get_filename_list("loras"), {"tooltip": "The name of the LoRA."}), + "strength_model": ("FLOAT", {"default": 1.0, "min": -100.0, "max": 100.0, "step": 0.01, "tooltip": "How strongly to modify the diffusion model. This value can be negative."}), + "strength_clip": ("FLOAT", {"default": 1.0, "min": -100.0, "max": 100.0, "step": 0.01, "tooltip": "How strongly to modify the CLIP model. This value can be negative."}), + } + } + RETURN_TYPES = ("MODEL", "CLIP") + OUTPUT_TOOLTIPS = ("The modified diffusion model.", "The modified CLIP model.") FUNCTION = "load_lora" CATEGORY = "loaders" + DESCRIPTION = "LoRAs are used to modify diffusion and CLIP models, altering the way in which latents are denoised such as applying styles. Multiple LoRA nodes can be linked together." def load_lora(self, model, clip, lora_name, strength_model, strength_clip): if strength_model == 0 and strength_clip == 0: @@ -826,14 +853,14 @@ class UNETLoader: CATEGORY = "advanced/loaders" def load_unet(self, unet_name, weight_dtype): - dtype = None + model_options = {} if weight_dtype == "fp8_e4m3fn": - dtype = torch.float8_e4m3fn + model_options["dtype"] = torch.float8_e4m3fn elif weight_dtype == "fp8_e5m2": - dtype = torch.float8_e5m2 + model_options["dtype"] = torch.float8_e5m2 unet_path = folder_paths.get_full_path("unet", unet_name) - model = comfy.sd.load_unet(unet_path, dtype=dtype) + model = comfy.sd.load_diffusion_model(unet_path, model_options=model_options) return (model,) class CLIPLoader: @@ -1033,13 +1060,19 @@ class EmptyLatentImage: @classmethod def INPUT_TYPES(s): - return {"required": { "width": ("INT", {"default": 512, "min": 16, "max": MAX_RESOLUTION, "step": 8}), - "height": ("INT", {"default": 512, "min": 16, "max": MAX_RESOLUTION, "step": 8}), - "batch_size": ("INT", {"default": 1, "min": 1, "max": 4096})}} + return { + "required": { + "width": ("INT", {"default": 512, "min": 16, "max": MAX_RESOLUTION, "step": 8, "tooltip": "The width of the latent images in pixels."}), + "height": ("INT", {"default": 512, "min": 16, "max": MAX_RESOLUTION, "step": 8, "tooltip": "The height of the latent images in pixels."}), + "batch_size": ("INT", {"default": 1, "min": 1, "max": 4096, "tooltip": "The number of latent images in the batch."}) + } + } RETURN_TYPES = ("LATENT",) + OUTPUT_TOOLTIPS = ("The empty latent image batch.",) FUNCTION = "generate" CATEGORY = "latent" + DESCRIPTION = "Create a new batch of empty latent images to be denoised via sampling." def generate(self, width, height, batch_size=1): latent = torch.zeros([batch_size, 4, height // 8, width // 8], device=self.device) @@ -1359,24 +1392,27 @@ def common_ksampler(model, seed, steps, cfg, sampler_name, scheduler, positive, class KSampler: @classmethod def INPUT_TYPES(s): - return {"required": - {"model": ("MODEL",), - "seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}), - "steps": ("INT", {"default": 20, "min": 1, "max": 10000}), - "cfg": ("FLOAT", {"default": 8.0, "min": 0.0, "max": 100.0, "step":0.1, "round": 0.01}), - "sampler_name": (comfy.samplers.KSampler.SAMPLERS, ), - "scheduler": (comfy.samplers.KSampler.SCHEDULERS, ), - "positive": ("CONDITIONING", ), - "negative": ("CONDITIONING", ), - "latent_image": ("LATENT", ), - "denoise": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}), - } - } + return { + "required": { + "model": ("MODEL", {"tooltip": "The model used for denoising the input latent."}), + "seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff, "tooltip": "The random seed used for creating the noise."}), + "steps": ("INT", {"default": 20, "min": 1, "max": 10000, "tooltip": "The number of steps used in the denoising process."}), + "cfg": ("FLOAT", {"default": 8.0, "min": 0.0, "max": 100.0, "step":0.1, "round": 0.01, "tooltip": "The Classifier-Free Guidance scale balances creativity and adherence to the prompt. Higher values result in images more closely matching the prompt however too high values will negatively impact quality."}), + "sampler_name": (comfy.samplers.KSampler.SAMPLERS, {"tooltip": "The algorithm used when sampling, this can affect the quality, speed, and style of the generated output."}), + "scheduler": (comfy.samplers.KSampler.SCHEDULERS, {"tooltip": "The scheduler controls how noise is gradually removed to form the image."}), + "positive": ("CONDITIONING", {"tooltip": "The conditioning describing the attributes you want to include in the image."}), + "negative": ("CONDITIONING", {"tooltip": "The conditioning describing the attributes you want to exclude from the image."}), + "latent_image": ("LATENT", {"tooltip": "The latent image to denoise."}), + "denoise": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01, "tooltip": "The amount of denoising applied, lower values will maintain the structure of the initial image allowing for image to image sampling."}), + } + } RETURN_TYPES = ("LATENT",) + OUTPUT_TOOLTIPS = ("The denoised latent.",) FUNCTION = "sample" CATEGORY = "sampling" + DESCRIPTION = "Uses the provided model, positive and negative conditioning to denoise the latent image." def sample(self, model, seed, steps, cfg, sampler_name, scheduler, positive, negative, latent_image, denoise=1.0): return common_ksampler(model, seed, steps, cfg, sampler_name, scheduler, positive, negative, latent_image, denoise=denoise) @@ -1424,11 +1460,15 @@ class SaveImage: @classmethod def INPUT_TYPES(s): - return {"required": - {"images": ("IMAGE", ), - "filename_prefix": ("STRING", {"default": "ComfyUI"})}, - "hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"}, - } + return { + "required": { + "images": ("IMAGE", {"tooltip": "The images to save."}), + "filename_prefix": ("STRING", {"default": "ComfyUI", "tooltip": "The prefix for the file to save. This may include formatting information such as %date:yyyy-MM-dd% or %Empty Latent Image.width% to include values from nodes."}) + }, + "hidden": { + "prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO" + }, + } RETURN_TYPES = () FUNCTION = "save_images" @@ -1436,6 +1476,7 @@ class SaveImage: OUTPUT_NODE = True CATEGORY = "image" + DESCRIPTION = "Saves the input images to your ComfyUI output directory." def save_images(self, images, filename_prefix="ComfyUI", prompt=None, extra_pnginfo=None, output_dir=None): # =========================== diff --git a/pytest.ini b/pytest.ini index 8b7a747e7..a224d8cbb 100644 --- a/pytest.ini +++ b/pytest.ini @@ -1,6 +1,7 @@ [pytest] markers = inference: mark as inference test (deselect with '-m "not inference"') + execution: mark as execution test (deselect with '-m "not execution"') testpaths = tests tests-unit diff --git a/server.py b/server.py index 1c07f9781..a2bb376a4 100644 --- a/server.py +++ b/server.py @@ -12,7 +12,6 @@ import json import glob import struct import ssl -import hashlib from PIL import Image, ImageOps from PIL.PngImagePlugin import PngInfo from io import BytesIO @@ -28,7 +27,8 @@ import comfy.model_management import node_helpers from app.frontend_management import FrontendManager from app.user_manager import UserManager - +from model_filemanager import download_model, DownloadModelStatus +from typing import Optional class BinaryEventTypes: PREVIEW_IMAGE = 1 @@ -76,6 +76,7 @@ class PromptServer(): self.prompt_queue = None self.loop = loop self.messages = asyncio.Queue() + self.client_session:Optional[aiohttp.ClientSession] = None self.number = 0 middlewares = [cache_control] @@ -422,6 +423,7 @@ class PromptServer(): obj_class = nodes.NODE_CLASS_MAPPINGS[node_class] info = {} info['input'] = obj_class.INPUT_TYPES() + info['input_order'] = {key: list(value.keys()) for (key, value) in obj_class.INPUT_TYPES().items()} info['output'] = obj_class.RETURN_TYPES info['output_is_list'] = obj_class.OUTPUT_IS_LIST if hasattr(obj_class, 'OUTPUT_IS_LIST') else [False] * len(obj_class.RETURN_TYPES) info['output_name'] = obj_class.RETURN_NAMES if hasattr(obj_class, 'RETURN_NAMES') else info['output'] @@ -437,6 +439,9 @@ class PromptServer(): if hasattr(obj_class, 'CATEGORY'): info['category'] = obj_class.CATEGORY + + if hasattr(obj_class, 'OUTPUT_TOOLTIPS'): + info['output_tooltips'] = obj_class.OUTPUT_TOOLTIPS return info @routes.get("/object_info") @@ -559,6 +564,36 @@ class PromptServer(): self.prompt_queue.delete_history_item(id_to_delete) return web.Response(status=200) + + # Internal route. Should not be depended upon and is subject to change at any time. + # TODO(robinhuang): Move to internal route table class once we refactor PromptServer to pass around Websocket. + @routes.post("/internal/models/download") + async def download_handler(request): + async def report_progress(filename: str, status: DownloadModelStatus): + await self.send_json("download_progress", status.to_dict()) + + data = await request.json() + url = data.get('url') + model_directory = data.get('model_directory') + model_filename = data.get('model_filename') + progress_interval = data.get('progress_interval', 1.0) # In seconds, how often to report download progress. + + if not url or not model_directory or not model_filename: + return web.json_response({"status": "error", "message": "Missing URL or folder path or filename"}, status=400) + + session = self.client_session + if session is None: + logging.error("Client session is not initialized") + return web.Response(status=500) + + task = asyncio.create_task(download_model(lambda url: session.get(url), model_filename, url, model_directory, report_progress, progress_interval)) + await task + + return web.json_response(task.result().to_dict()) + + async def setup(self): + timeout = aiohttp.ClientTimeout(total=None) # no timeout + self.client_session = aiohttp.ClientSession(timeout=timeout) def add_routes(self): self.user_manager.add_routes(self.routes) @@ -680,6 +715,9 @@ class PromptServer(): site = web.TCPSite(runner, address, port, ssl_context=ssl_ctx) await site.start() + self.address = address + self.port = port + if verbose: logging.info("Starting server\n") logging.info("To see the GUI go to: {}://{}:{}".format(scheme, address, port)) diff --git a/tests-ui/.gitignore b/tests-ui/.gitignore deleted file mode 100644 index b512c09d4..000000000 --- a/tests-ui/.gitignore +++ /dev/null @@ -1 +0,0 @@ -node_modules \ No newline at end of file diff --git a/tests-ui/afterSetup.js b/tests-ui/afterSetup.js deleted file mode 100644 index 983f3af64..000000000 --- a/tests-ui/afterSetup.js +++ /dev/null @@ -1,9 +0,0 @@ -const { start } = require("./utils"); -const lg = require("./utils/litegraph"); - -// Load things once per test file before to ensure its all warmed up for the tests -beforeAll(async () => { - lg.setup(global); - await start({ resetEnv: true }); - lg.teardown(global); -}); diff --git a/tests-ui/babel.config.json b/tests-ui/babel.config.json deleted file mode 100644 index f27d6c397..000000000 --- a/tests-ui/babel.config.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "presets": ["@babel/preset-env"], - "plugins": ["babel-plugin-transform-import-meta"] -} diff --git a/tests-ui/globalSetup.js b/tests-ui/globalSetup.js deleted file mode 100644 index b9d97f58a..000000000 --- a/tests-ui/globalSetup.js +++ /dev/null @@ -1,14 +0,0 @@ -module.exports = async function () { - global.ResizeObserver = class ResizeObserver { - observe() {} - unobserve() {} - disconnect() {} - }; - - const { nop } = require("./utils/nopProxy"); - global.enableWebGLCanvas = nop; - - HTMLCanvasElement.prototype.getContext = nop; - - localStorage["Comfy.Settings.Comfy.Logging.Enabled"] = "false"; -}; diff --git a/tests-ui/jest.config.js b/tests-ui/jest.config.js deleted file mode 100644 index 86fff5057..000000000 --- a/tests-ui/jest.config.js +++ /dev/null @@ -1,11 +0,0 @@ -/** @type {import('jest').Config} */ -const config = { - testEnvironment: "jsdom", - setupFiles: ["./globalSetup.js"], - setupFilesAfterEnv: ["./afterSetup.js"], - clearMocks: true, - resetModules: true, - testTimeout: 10000 -}; - -module.exports = config; diff --git a/tests-ui/package-lock.json b/tests-ui/package-lock.json deleted file mode 100644 index 0f409ca24..000000000 --- a/tests-ui/package-lock.json +++ /dev/null @@ -1,5586 +0,0 @@ -{ - "name": "comfui-tests", - "version": "1.0.0", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "comfui-tests", - "version": "1.0.0", - "license": "GPL-3.0", - "devDependencies": { - "@babel/preset-env": "^7.22.20", - "@types/jest": "^29.5.5", - "babel-plugin-transform-import-meta": "^2.2.1", - "jest": "^29.7.0", - "jest-environment-jsdom": "^29.7.0" - } - }, - "node_modules/@ampproject/remapping": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.2.1.tgz", - "integrity": "sha512-lFMjJTrFL3j7L9yBxwYfCq2k6qqwHyzuUl/XBnif78PWTJYyL/dfowQHWE3sp6U6ZzqWiiIZnpTMO96zhkjwtg==", - "dev": true, - "dependencies": { - "@jridgewell/gen-mapping": "^0.3.0", - "@jridgewell/trace-mapping": "^0.3.9" - }, - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/@babel/code-frame": { - "version": "7.22.13", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.22.13.tgz", - "integrity": "sha512-XktuhWlJ5g+3TJXc5upd9Ks1HutSArik6jf2eAjYFyIOf4ej3RN+184cZbzDvbPnuTJIUhPKKJE3cIsYTiAT3w==", - "dev": true, - "dependencies": { - "@babel/highlight": "^7.22.13", - "chalk": "^2.4.2" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/code-frame/node_modules/ansi-styles": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", - "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", - "dev": true, - "dependencies": { - "color-convert": "^1.9.0" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/@babel/code-frame/node_modules/chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "dependencies": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/@babel/code-frame/node_modules/color-convert": { - "version": "1.9.3", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", - "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", - "dev": true, - "dependencies": { - "color-name": "1.1.3" - } - }, - "node_modules/@babel/code-frame/node_modules/color-name": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", - "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", - "dev": true - }, - "node_modules/@babel/code-frame/node_modules/escape-string-regexp": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", - "dev": true, - "engines": { - "node": ">=0.8.0" - } - }, - "node_modules/@babel/code-frame/node_modules/has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", - "dev": true, - "engines": { - "node": ">=4" - } - }, - "node_modules/@babel/code-frame/node_modules/supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "dependencies": { - "has-flag": "^3.0.0" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/@babel/compat-data": { - "version": "7.22.20", - "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.22.20.tgz", - "integrity": "sha512-BQYjKbpXjoXwFW5jGqiizJQQT/aC7pFm9Ok1OWssonuguICi264lbgMzRp2ZMmRSlfkX6DsWDDcsrctK8Rwfiw==", - "dev": true, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/core": { - "version": "7.23.0", - "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.23.0.tgz", - "integrity": "sha512-97z/ju/Jy1rZmDxybphrBuI+jtJjFVoz7Mr9yUQVVVi+DNZE333uFQeMOqcCIy1x3WYBIbWftUSLmbNXNT7qFQ==", - "dev": true, - "dependencies": { - "@ampproject/remapping": "^2.2.0", - "@babel/code-frame": "^7.22.13", - "@babel/generator": "^7.23.0", - "@babel/helper-compilation-targets": "^7.22.15", - "@babel/helper-module-transforms": "^7.23.0", - "@babel/helpers": "^7.23.0", - "@babel/parser": "^7.23.0", - "@babel/template": "^7.22.15", - "@babel/traverse": "^7.23.0", - "@babel/types": "^7.23.0", - "convert-source-map": "^2.0.0", - "debug": "^4.1.0", - "gensync": "^1.0.0-beta.2", - "json5": "^2.2.3", - "semver": "^6.3.1" - }, - "engines": { - "node": ">=6.9.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/babel" - } - }, - "node_modules/@babel/generator": { - "version": "7.23.0", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.23.0.tgz", - "integrity": "sha512-lN85QRR+5IbYrMWM6Y4pE/noaQtg4pNiqeNGX60eqOfo6gtEj6uw/JagelB8vVztSd7R6M5n1+PQkDbHbBRU4g==", - "dev": true, - "dependencies": { - "@babel/types": "^7.23.0", - "@jridgewell/gen-mapping": "^0.3.2", - "@jridgewell/trace-mapping": "^0.3.17", - "jsesc": "^2.5.1" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-annotate-as-pure": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-7.22.5.tgz", - "integrity": "sha512-LvBTxu8bQSQkcyKOU+a1btnNFQ1dMAd0R6PyW3arXes06F6QLWLIrd681bxRPIXlrMGR3XYnW9JyML7dP3qgxg==", - "dev": true, - "dependencies": { - "@babel/types": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-builder-binary-assignment-operator-visitor": { - "version": "7.22.15", - "resolved": "https://registry.npmjs.org/@babel/helper-builder-binary-assignment-operator-visitor/-/helper-builder-binary-assignment-operator-visitor-7.22.15.tgz", - "integrity": "sha512-QkBXwGgaoC2GtGZRoma6kv7Szfv06khvhFav67ZExau2RaXzy8MpHSMO2PNoP2XtmQphJQRHFfg77Bq731Yizw==", - "dev": true, - "dependencies": { - "@babel/types": "^7.22.15" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-compilation-targets": { - "version": "7.22.15", - "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.22.15.tgz", - "integrity": "sha512-y6EEzULok0Qvz8yyLkCvVX+02ic+By2UdOhylwUOvOn9dvYc9mKICJuuU1n1XBI02YWsNsnrY1kc6DVbjcXbtw==", - "dev": true, - "dependencies": { - "@babel/compat-data": "^7.22.9", - "@babel/helper-validator-option": "^7.22.15", - "browserslist": "^4.21.9", - "lru-cache": "^5.1.1", - "semver": "^6.3.1" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-create-class-features-plugin": { - "version": "7.22.15", - "resolved": "https://registry.npmjs.org/@babel/helper-create-class-features-plugin/-/helper-create-class-features-plugin-7.22.15.tgz", - "integrity": "sha512-jKkwA59IXcvSaiK2UN45kKwSC9o+KuoXsBDvHvU/7BecYIp8GQ2UwrVvFgJASUT+hBnwJx6MhvMCuMzwZZ7jlg==", - "dev": true, - "dependencies": { - "@babel/helper-annotate-as-pure": "^7.22.5", - "@babel/helper-environment-visitor": "^7.22.5", - "@babel/helper-function-name": "^7.22.5", - "@babel/helper-member-expression-to-functions": "^7.22.15", - "@babel/helper-optimise-call-expression": "^7.22.5", - "@babel/helper-replace-supers": "^7.22.9", - "@babel/helper-skip-transparent-expression-wrappers": "^7.22.5", - "@babel/helper-split-export-declaration": "^7.22.6", - "semver": "^6.3.1" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0" - } - }, - "node_modules/@babel/helper-create-regexp-features-plugin": { - "version": "7.22.15", - "resolved": "https://registry.npmjs.org/@babel/helper-create-regexp-features-plugin/-/helper-create-regexp-features-plugin-7.22.15.tgz", - "integrity": "sha512-29FkPLFjn4TPEa3RE7GpW+qbE8tlsu3jntNYNfcGsc49LphF1PQIiD+vMZ1z1xVOKt+93khA9tc2JBs3kBjA7w==", - "dev": true, - "dependencies": { - "@babel/helper-annotate-as-pure": "^7.22.5", - "regexpu-core": "^5.3.1", - "semver": "^6.3.1" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0" - } - }, - "node_modules/@babel/helper-define-polyfill-provider": { - "version": "0.4.2", - "resolved": "https://registry.npmjs.org/@babel/helper-define-polyfill-provider/-/helper-define-polyfill-provider-0.4.2.tgz", - "integrity": "sha512-k0qnnOqHn5dK9pZpfD5XXZ9SojAITdCKRn2Lp6rnDGzIbaP0rHyMPk/4wsSxVBVz4RfN0q6VpXWP2pDGIoQ7hw==", - "dev": true, - "dependencies": { - "@babel/helper-compilation-targets": "^7.22.6", - "@babel/helper-plugin-utils": "^7.22.5", - "debug": "^4.1.1", - "lodash.debounce": "^4.0.8", - "resolve": "^1.14.2" - }, - "peerDependencies": { - "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0" - } - }, - "node_modules/@babel/helper-environment-visitor": { - "version": "7.22.20", - "resolved": "https://registry.npmjs.org/@babel/helper-environment-visitor/-/helper-environment-visitor-7.22.20.tgz", - "integrity": "sha512-zfedSIzFhat/gFhWfHtgWvlec0nqB9YEIVrpuwjruLlXfUSnA8cJB0miHKwqDnQ7d32aKo2xt88/xZptwxbfhA==", - "dev": true, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-function-name": { - "version": "7.23.0", - "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.23.0.tgz", - "integrity": "sha512-OErEqsrxjZTJciZ4Oo+eoZqeW9UIiOcuYKRJA4ZAgV9myA+pOXhhmpfNCKjEH/auVfEYVFJ6y1Tc4r0eIApqiw==", - "dev": true, - "dependencies": { - "@babel/template": "^7.22.15", - "@babel/types": "^7.23.0" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-hoist-variables": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/helper-hoist-variables/-/helper-hoist-variables-7.22.5.tgz", - "integrity": "sha512-wGjk9QZVzvknA6yKIUURb8zY3grXCcOZt+/7Wcy8O2uctxhplmUPkOdlgoNhmdVee2c92JXbf1xpMtVNbfoxRw==", - "dev": true, - "dependencies": { - "@babel/types": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-member-expression-to-functions": { - "version": "7.23.0", - "resolved": "https://registry.npmjs.org/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.23.0.tgz", - "integrity": "sha512-6gfrPwh7OuT6gZyJZvd6WbTfrqAo7vm4xCzAXOusKqq/vWdKXphTpj5klHKNmRUU6/QRGlBsyU9mAIPaWHlqJA==", - "dev": true, - "dependencies": { - "@babel/types": "^7.23.0" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-module-imports": { - "version": "7.22.15", - "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.22.15.tgz", - "integrity": "sha512-0pYVBnDKZO2fnSPCrgM/6WMc7eS20Fbok+0r88fp+YtWVLZrp4CkafFGIp+W0VKw4a22sgebPT99y+FDNMdP4w==", - "dev": true, - "dependencies": { - "@babel/types": "^7.22.15" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-module-transforms": { - "version": "7.23.0", - "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.23.0.tgz", - "integrity": "sha512-WhDWw1tdrlT0gMgUJSlX0IQvoO1eN279zrAUbVB+KpV2c3Tylz8+GnKOLllCS6Z/iZQEyVYxhZVUdPTqs2YYPw==", - "dev": true, - "dependencies": { - "@babel/helper-environment-visitor": "^7.22.20", - "@babel/helper-module-imports": "^7.22.15", - "@babel/helper-simple-access": "^7.22.5", - "@babel/helper-split-export-declaration": "^7.22.6", - "@babel/helper-validator-identifier": "^7.22.20" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0" - } - }, - "node_modules/@babel/helper-optimise-call-expression": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/helper-optimise-call-expression/-/helper-optimise-call-expression-7.22.5.tgz", - "integrity": "sha512-HBwaojN0xFRx4yIvpwGqxiV2tUfl7401jlok564NgB9EHS1y6QT17FmKWm4ztqjeVdXLuC4fSvHc5ePpQjoTbw==", - "dev": true, - "dependencies": { - "@babel/types": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-plugin-utils": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.22.5.tgz", - "integrity": "sha512-uLls06UVKgFG9QD4OeFYLEGteMIAa5kpTPcFL28yuCIIzsf6ZyKZMllKVOCZFhiZ5ptnwX4mtKdWCBE/uT4amg==", - "dev": true, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-remap-async-to-generator": { - "version": "7.22.20", - "resolved": "https://registry.npmjs.org/@babel/helper-remap-async-to-generator/-/helper-remap-async-to-generator-7.22.20.tgz", - "integrity": "sha512-pBGyV4uBqOns+0UvhsTO8qgl8hO89PmiDYv+/COyp1aeMcmfrfruz+/nCMFiYyFF/Knn0yfrC85ZzNFjembFTw==", - "dev": true, - "dependencies": { - "@babel/helper-annotate-as-pure": "^7.22.5", - "@babel/helper-environment-visitor": "^7.22.20", - "@babel/helper-wrap-function": "^7.22.20" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0" - } - }, - "node_modules/@babel/helper-replace-supers": { - "version": "7.22.20", - "resolved": "https://registry.npmjs.org/@babel/helper-replace-supers/-/helper-replace-supers-7.22.20.tgz", - "integrity": "sha512-qsW0In3dbwQUbK8kejJ4R7IHVGwHJlV6lpG6UA7a9hSa2YEiAib+N1T2kr6PEeUT+Fl7najmSOS6SmAwCHK6Tw==", - "dev": true, - "dependencies": { - "@babel/helper-environment-visitor": "^7.22.20", - "@babel/helper-member-expression-to-functions": "^7.22.15", - "@babel/helper-optimise-call-expression": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0" - } - }, - "node_modules/@babel/helper-simple-access": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.22.5.tgz", - "integrity": "sha512-n0H99E/K+Bika3++WNL17POvo4rKWZ7lZEp1Q+fStVbUi8nxPQEBOlTmCOxW/0JsS56SKKQ+ojAe2pHKJHN35w==", - "dev": true, - "dependencies": { - "@babel/types": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-skip-transparent-expression-wrappers": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/helper-skip-transparent-expression-wrappers/-/helper-skip-transparent-expression-wrappers-7.22.5.tgz", - "integrity": "sha512-tK14r66JZKiC43p8Ki33yLBVJKlQDFoA8GYN67lWCDCqoL6EMMSuM9b+Iff2jHaM/RRFYl7K+iiru7hbRqNx8Q==", - "dev": true, - "dependencies": { - "@babel/types": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-split-export-declaration": { - "version": "7.22.6", - "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.22.6.tgz", - "integrity": "sha512-AsUnxuLhRYsisFiaJwvp1QF+I3KjD5FOxut14q/GzovUe6orHLesW2C7d754kRm53h5gqrz6sFl6sxc4BVtE/g==", - "dev": true, - "dependencies": { - "@babel/types": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-string-parser": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.22.5.tgz", - "integrity": "sha512-mM4COjgZox8U+JcXQwPijIZLElkgEpO5rsERVDJTc2qfCDfERyob6k5WegS14SX18IIjv+XD+GrqNumY5JRCDw==", - "dev": true, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-validator-identifier": { - "version": "7.22.20", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.22.20.tgz", - "integrity": "sha512-Y4OZ+ytlatR8AI+8KZfKuL5urKp7qey08ha31L8b3BwewJAoJamTzyvxPR/5D+KkdJCGPq/+8TukHBlY10FX9A==", - "dev": true, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-validator-option": { - "version": "7.22.15", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.22.15.tgz", - "integrity": "sha512-bMn7RmyFjY/mdECUbgn9eoSY4vqvacUnS9i9vGAGttgFWesO6B4CYWA7XlpbWgBt71iv/hfbPlynohStqnu5hA==", - "dev": true, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-wrap-function": { - "version": "7.22.20", - "resolved": "https://registry.npmjs.org/@babel/helper-wrap-function/-/helper-wrap-function-7.22.20.tgz", - "integrity": "sha512-pms/UwkOpnQe/PDAEdV/d7dVCoBbB+R4FvYoHGZz+4VPcg7RtYy2KP7S2lbuWM6FCSgob5wshfGESbC/hzNXZw==", - "dev": true, - "dependencies": { - "@babel/helper-function-name": "^7.22.5", - "@babel/template": "^7.22.15", - "@babel/types": "^7.22.19" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helpers": { - "version": "7.23.1", - "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.23.1.tgz", - "integrity": "sha512-chNpneuK18yW5Oxsr+t553UZzzAs3aZnFm4bxhebsNTeshrC95yA7l5yl7GBAG+JG1rF0F7zzD2EixK9mWSDoA==", - "dev": true, - "dependencies": { - "@babel/template": "^7.22.15", - "@babel/traverse": "^7.23.0", - "@babel/types": "^7.23.0" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/highlight": { - "version": "7.22.20", - "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.22.20.tgz", - "integrity": "sha512-dkdMCN3py0+ksCgYmGG8jKeGA/8Tk+gJwSYYlFGxG5lmhfKNoAy004YpLxpS1W2J8m/EK2Ew+yOs9pVRwO89mg==", - "dev": true, - "dependencies": { - "@babel/helper-validator-identifier": "^7.22.20", - "chalk": "^2.4.2", - "js-tokens": "^4.0.0" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/highlight/node_modules/ansi-styles": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", - "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", - "dev": true, - "dependencies": { - "color-convert": "^1.9.0" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/@babel/highlight/node_modules/chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "dependencies": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/@babel/highlight/node_modules/color-convert": { - "version": "1.9.3", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", - "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", - "dev": true, - "dependencies": { - "color-name": "1.1.3" - } - }, - "node_modules/@babel/highlight/node_modules/color-name": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", - "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", - "dev": true - }, - "node_modules/@babel/highlight/node_modules/escape-string-regexp": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", - "dev": true, - "engines": { - "node": ">=0.8.0" - } - }, - "node_modules/@babel/highlight/node_modules/has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", - "dev": true, - "engines": { - "node": ">=4" - } - }, - "node_modules/@babel/highlight/node_modules/supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "dependencies": { - "has-flag": "^3.0.0" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/@babel/parser": { - "version": "7.23.0", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.23.0.tgz", - "integrity": "sha512-vvPKKdMemU85V9WE/l5wZEmImpCtLqbnTvqDS2U1fJ96KrxoW7KrXhNsNCblQlg8Ck4b85yxdTyelsMUgFUXiw==", - "dev": true, - "bin": { - "parser": "bin/babel-parser.js" - }, - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression": { - "version": "7.22.15", - "resolved": "https://registry.npmjs.org/@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression/-/plugin-bugfix-safari-id-destructuring-collision-in-function-expression-7.22.15.tgz", - "integrity": "sha512-FB9iYlz7rURmRJyXRKEnalYPPdn87H5no108cyuQQyMwlpJ2SJtpIUBI27kdTin956pz+LPypkPVPUTlxOmrsg==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0" - } - }, - "node_modules/@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining": { - "version": "7.22.15", - "resolved": "https://registry.npmjs.org/@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining/-/plugin-bugfix-v8-spread-parameters-in-optional-chaining-7.22.15.tgz", - "integrity": "sha512-Hyph9LseGvAeeXzikV88bczhsrLrIZqDPxO+sSmAunMPaGrBGhfMWzCPYTtiW9t+HzSE2wtV8e5cc5P6r1xMDQ==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.22.5", - "@babel/helper-skip-transparent-expression-wrappers": "^7.22.5", - "@babel/plugin-transform-optional-chaining": "^7.22.15" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.13.0" - } - }, - "node_modules/@babel/plugin-proposal-private-property-in-object": { - "version": "7.21.0-placeholder-for-preset-env.2", - "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-private-property-in-object/-/plugin-proposal-private-property-in-object-7.21.0-placeholder-for-preset-env.2.tgz", - "integrity": "sha512-SOSkfJDddaM7mak6cPEpswyTRnuRltl429hMraQEglW+OkovnCzsiszTmsrlY//qLFjCpQDFRvjdm2wA5pPm9w==", - "dev": true, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-async-generators": { - "version": "7.8.4", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-async-generators/-/plugin-syntax-async-generators-7.8.4.tgz", - "integrity": "sha512-tycmZxkGfZaxhMRbXlPXuVFpdWlXpir2W4AMhSJgRKzk/eDlIXOhb2LHWoLpDF7TEHylV5zNhykX6KAgHJmTNw==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.8.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-bigint": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-bigint/-/plugin-syntax-bigint-7.8.3.tgz", - "integrity": "sha512-wnTnFlG+YxQm3vDxpGE57Pj0srRU4sHE/mDkt1qv2YJJSeUAec2ma4WLUnUPeKjyrfntVwe/N6dCXpU+zL3Npg==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.8.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-class-properties": { - "version": "7.12.13", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-class-properties/-/plugin-syntax-class-properties-7.12.13.tgz", - "integrity": "sha512-fm4idjKla0YahUNgFNLCB0qySdsoPiZP3iQE3rky0mBUtMZ23yDJ9SJdg6dXTSDnulOVqiF3Hgr9nbXvXTQZYA==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.12.13" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-class-static-block": { - "version": "7.14.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-class-static-block/-/plugin-syntax-class-static-block-7.14.5.tgz", - "integrity": "sha512-b+YyPmr6ldyNnM6sqYeMWE+bgJcJpO6yS4QD7ymxgH34GBPNDM/THBh8iunyvKIZztiwLH4CJZ0RxTk9emgpjw==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.14.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-dynamic-import": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-dynamic-import/-/plugin-syntax-dynamic-import-7.8.3.tgz", - "integrity": "sha512-5gdGbFon+PszYzqs83S3E5mpi7/y/8M9eC90MRTZfduQOYW76ig6SOSPNe41IG5LoP3FGBn2N0RjVDSQiS94kQ==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.8.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-export-namespace-from": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-export-namespace-from/-/plugin-syntax-export-namespace-from-7.8.3.tgz", - "integrity": "sha512-MXf5laXo6c1IbEbegDmzGPwGNTsHZmEy6QGznu5Sh2UCWvueywb2ee+CCE4zQiZstxU9BMoQO9i6zUFSY0Kj0Q==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.8.3" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-import-assertions": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-assertions/-/plugin-syntax-import-assertions-7.22.5.tgz", - "integrity": "sha512-rdV97N7KqsRzeNGoWUOK6yUsWarLjE5Su/Snk9IYPU9CwkWHs4t+rTGOvffTR8XGkJMTAdLfO0xVnXm8wugIJg==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-import-attributes": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-attributes/-/plugin-syntax-import-attributes-7.22.5.tgz", - "integrity": "sha512-KwvoWDeNKPETmozyFE0P2rOLqh39EoQHNjqizrI5B8Vt0ZNS7M56s7dAiAqbYfiAYOuIzIh96z3iR2ktgu3tEg==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-import-meta": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-meta/-/plugin-syntax-import-meta-7.10.4.tgz", - "integrity": "sha512-Yqfm+XDx0+Prh3VSeEQCPU81yC+JWZ2pDPFSS4ZdpfZhp4MkFMaDC1UqseovEKwSUpnIL7+vK+Clp7bfh0iD7g==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.10.4" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-json-strings": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-json-strings/-/plugin-syntax-json-strings-7.8.3.tgz", - "integrity": "sha512-lY6kdGpWHvjoe2vk4WrAapEuBR69EMxZl+RoGRhrFGNYVK8mOPAW8VfbT/ZgrFbXlDNiiaxQnAtgVCZ6jv30EA==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.8.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-jsx": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.22.5.tgz", - "integrity": "sha512-gvyP4hZrgrs/wWMaocvxZ44Hw0b3W8Pe+cMxc8V1ULQ07oh8VNbIRaoD1LRZVTvD+0nieDKjfgKg89sD7rrKrg==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-logical-assignment-operators": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-logical-assignment-operators/-/plugin-syntax-logical-assignment-operators-7.10.4.tgz", - "integrity": "sha512-d8waShlpFDinQ5MtvGU9xDAOzKH47+FFoney2baFIoMr952hKOLp1HR7VszoZvOsV/4+RRszNY7D17ba0te0ig==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.10.4" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-nullish-coalescing-operator": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-nullish-coalescing-operator/-/plugin-syntax-nullish-coalescing-operator-7.8.3.tgz", - "integrity": "sha512-aSff4zPII1u2QD7y+F8oDsz19ew4IGEJg9SVW+bqwpwtfFleiQDMdzA/R+UlWDzfnHFCxxleFT0PMIrR36XLNQ==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.8.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-numeric-separator": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-numeric-separator/-/plugin-syntax-numeric-separator-7.10.4.tgz", - "integrity": "sha512-9H6YdfkcK/uOnY/K7/aA2xpzaAgkQn37yzWUMRK7OaPOqOpGS1+n0H5hxT9AUw9EsSjPW8SVyMJwYRtWs3X3ug==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.10.4" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-object-rest-spread": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-object-rest-spread/-/plugin-syntax-object-rest-spread-7.8.3.tgz", - "integrity": "sha512-XoqMijGZb9y3y2XskN+P1wUGiVwWZ5JmoDRwx5+3GmEplNyVM2s2Dg8ILFQm8rWM48orGy5YpI5Bl8U1y7ydlA==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.8.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-optional-catch-binding": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-catch-binding/-/plugin-syntax-optional-catch-binding-7.8.3.tgz", - "integrity": "sha512-6VPD0Pc1lpTqw0aKoeRTMiB+kWhAoT24PA+ksWSBrFtl5SIRVpZlwN3NNPQjehA2E/91FV3RjLWoVTglWcSV3Q==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.8.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-optional-chaining": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-chaining/-/plugin-syntax-optional-chaining-7.8.3.tgz", - "integrity": "sha512-KoK9ErH1MBlCPxV0VANkXW2/dw4vlbGDrFgz8bmUsBGYkFRcbRwMh6cIJubdPrkxRwuGdtCk0v/wPTKbQgBjkg==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.8.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-private-property-in-object": { - "version": "7.14.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-private-property-in-object/-/plugin-syntax-private-property-in-object-7.14.5.tgz", - "integrity": "sha512-0wVnp9dxJ72ZUJDV27ZfbSj6iHLoytYZmh3rFcxNnvsJF3ktkzLDZPy/mA17HGsaQT3/DQsWYX1f1QGWkCoVUg==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.14.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-top-level-await": { - "version": "7.14.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-top-level-await/-/plugin-syntax-top-level-await-7.14.5.tgz", - "integrity": "sha512-hx++upLv5U1rgYfwe1xBQUhRmU41NEvpUvrp8jkrSCdvGSnM5/qdRMtylJ6PG5OFkBaHkbTAKTnd3/YyESRHFw==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.14.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-typescript": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-7.22.5.tgz", - "integrity": "sha512-1mS2o03i7t1c6VzH6fdQ3OA8tcEIxwG18zIPRp+UY1Ihv6W+XZzBCVxExF9upussPXJ0xE9XRHwMoNs1ep/nRQ==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-unicode-sets-regex": { - "version": "7.18.6", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-unicode-sets-regex/-/plugin-syntax-unicode-sets-regex-7.18.6.tgz", - "integrity": "sha512-727YkEAPwSIQTv5im8QHz3upqp92JTWhidIC81Tdx4VJYIte/VndKf1qKrfnnhPLiPghStWfvC/iFaMCQu7Nqg==", - "dev": true, - "dependencies": { - "@babel/helper-create-regexp-features-plugin": "^7.18.6", - "@babel/helper-plugin-utils": "^7.18.6" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0" - } - }, - "node_modules/@babel/plugin-transform-arrow-functions": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-arrow-functions/-/plugin-transform-arrow-functions-7.22.5.tgz", - "integrity": "sha512-26lTNXoVRdAnsaDXPpvCNUq+OVWEVC6bx7Vvz9rC53F2bagUWW4u4ii2+h8Fejfh7RYqPxn+libeFBBck9muEw==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-async-generator-functions": { - "version": "7.22.15", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-async-generator-functions/-/plugin-transform-async-generator-functions-7.22.15.tgz", - "integrity": "sha512-jBm1Es25Y+tVoTi5rfd5t1KLmL8ogLKpXszboWOTTtGFGz2RKnQe2yn7HbZ+kb/B8N0FVSGQo874NSlOU1T4+w==", - "dev": true, - "dependencies": { - "@babel/helper-environment-visitor": "^7.22.5", - "@babel/helper-plugin-utils": "^7.22.5", - "@babel/helper-remap-async-to-generator": "^7.22.9", - "@babel/plugin-syntax-async-generators": "^7.8.4" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-async-to-generator": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-async-to-generator/-/plugin-transform-async-to-generator-7.22.5.tgz", - "integrity": "sha512-b1A8D8ZzE/VhNDoV1MSJTnpKkCG5bJo+19R4o4oy03zM7ws8yEMK755j61Dc3EyvdysbqH5BOOTquJ7ZX9C6vQ==", - "dev": true, - "dependencies": { - "@babel/helper-module-imports": "^7.22.5", - "@babel/helper-plugin-utils": "^7.22.5", - "@babel/helper-remap-async-to-generator": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-block-scoped-functions": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-block-scoped-functions/-/plugin-transform-block-scoped-functions-7.22.5.tgz", - "integrity": "sha512-tdXZ2UdknEKQWKJP1KMNmuF5Lx3MymtMN/pvA+p/VEkhK8jVcQ1fzSy8KM9qRYhAf2/lV33hoMPKI/xaI9sADA==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-block-scoping": { - "version": "7.23.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-block-scoping/-/plugin-transform-block-scoping-7.23.0.tgz", - "integrity": "sha512-cOsrbmIOXmf+5YbL99/S49Y3j46k/T16b9ml8bm9lP6N9US5iQ2yBK7gpui1pg0V/WMcXdkfKbTb7HXq9u+v4g==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-class-properties": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-class-properties/-/plugin-transform-class-properties-7.22.5.tgz", - "integrity": "sha512-nDkQ0NfkOhPTq8YCLiWNxp1+f9fCobEjCb0n8WdbNUBc4IB5V7P1QnX9IjpSoquKrXF5SKojHleVNs2vGeHCHQ==", - "dev": true, - "dependencies": { - "@babel/helper-create-class-features-plugin": "^7.22.5", - "@babel/helper-plugin-utils": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-class-static-block": { - "version": "7.22.11", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-class-static-block/-/plugin-transform-class-static-block-7.22.11.tgz", - "integrity": "sha512-GMM8gGmqI7guS/llMFk1bJDkKfn3v3C4KHK9Yg1ey5qcHcOlKb0QvcMrgzvxo+T03/4szNh5lghY+fEC98Kq9g==", - "dev": true, - "dependencies": { - "@babel/helper-create-class-features-plugin": "^7.22.11", - "@babel/helper-plugin-utils": "^7.22.5", - "@babel/plugin-syntax-class-static-block": "^7.14.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.12.0" - } - }, - "node_modules/@babel/plugin-transform-classes": { - "version": "7.22.15", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-classes/-/plugin-transform-classes-7.22.15.tgz", - "integrity": "sha512-VbbC3PGjBdE0wAWDdHM9G8Gm977pnYI0XpqMd6LrKISj8/DJXEsWqgRuTYaNE9Bv0JGhTZUzHDlMk18IpOuoqw==", - "dev": true, - "dependencies": { - "@babel/helper-annotate-as-pure": "^7.22.5", - "@babel/helper-compilation-targets": "^7.22.15", - "@babel/helper-environment-visitor": "^7.22.5", - "@babel/helper-function-name": "^7.22.5", - "@babel/helper-optimise-call-expression": "^7.22.5", - "@babel/helper-plugin-utils": "^7.22.5", - "@babel/helper-replace-supers": "^7.22.9", - "@babel/helper-split-export-declaration": "^7.22.6", - "globals": "^11.1.0" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-computed-properties": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-computed-properties/-/plugin-transform-computed-properties-7.22.5.tgz", - "integrity": "sha512-4GHWBgRf0krxPX+AaPtgBAlTgTeZmqDynokHOX7aqqAB4tHs3U2Y02zH6ETFdLZGcg9UQSD1WCmkVrE9ErHeOg==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.22.5", - "@babel/template": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-destructuring": { - "version": "7.23.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-destructuring/-/plugin-transform-destructuring-7.23.0.tgz", - "integrity": "sha512-vaMdgNXFkYrB+8lbgniSYWHsgqK5gjaMNcc84bMIOMRLH0L9AqYq3hwMdvnyqj1OPqea8UtjPEuS/DCenah1wg==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-dotall-regex": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-dotall-regex/-/plugin-transform-dotall-regex-7.22.5.tgz", - "integrity": "sha512-5/Yk9QxCQCl+sOIB1WelKnVRxTJDSAIxtJLL2/pqL14ZVlbH0fUQUZa/T5/UnQtBNgghR7mfB8ERBKyKPCi7Vw==", - "dev": true, - "dependencies": { - "@babel/helper-create-regexp-features-plugin": "^7.22.5", - "@babel/helper-plugin-utils": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-duplicate-keys": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-duplicate-keys/-/plugin-transform-duplicate-keys-7.22.5.tgz", - "integrity": "sha512-dEnYD+9BBgld5VBXHnF/DbYGp3fqGMsyxKbtD1mDyIA7AkTSpKXFhCVuj/oQVOoALfBs77DudA0BE4d5mcpmqw==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-dynamic-import": { - "version": "7.22.11", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-dynamic-import/-/plugin-transform-dynamic-import-7.22.11.tgz", - "integrity": "sha512-g/21plo58sfteWjaO0ZNVb+uEOkJNjAaHhbejrnBmu011l/eNDScmkbjCC3l4FKb10ViaGU4aOkFznSu2zRHgA==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.22.5", - "@babel/plugin-syntax-dynamic-import": "^7.8.3" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-exponentiation-operator": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-exponentiation-operator/-/plugin-transform-exponentiation-operator-7.22.5.tgz", - "integrity": "sha512-vIpJFNM/FjZ4rh1myqIya9jXwrwwgFRHPjT3DkUA9ZLHuzox8jiXkOLvwm1H+PQIP3CqfC++WPKeuDi0Sjdj1g==", - "dev": true, - "dependencies": { - "@babel/helper-builder-binary-assignment-operator-visitor": "^7.22.5", - "@babel/helper-plugin-utils": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-export-namespace-from": { - "version": "7.22.11", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-export-namespace-from/-/plugin-transform-export-namespace-from-7.22.11.tgz", - "integrity": "sha512-xa7aad7q7OiT8oNZ1mU7NrISjlSkVdMbNxn9IuLZyL9AJEhs1Apba3I+u5riX1dIkdptP5EKDG5XDPByWxtehw==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.22.5", - "@babel/plugin-syntax-export-namespace-from": "^7.8.3" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-for-of": { - "version": "7.22.15", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-for-of/-/plugin-transform-for-of-7.22.15.tgz", - "integrity": "sha512-me6VGeHsx30+xh9fbDLLPi0J1HzmeIIyenoOQHuw2D4m2SAU3NrspX5XxJLBpqn5yrLzrlw2Iy3RA//Bx27iOA==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-function-name": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-function-name/-/plugin-transform-function-name-7.22.5.tgz", - "integrity": "sha512-UIzQNMS0p0HHiQm3oelztj+ECwFnj+ZRV4KnguvlsD2of1whUeM6o7wGNj6oLwcDoAXQ8gEqfgC24D+VdIcevg==", - "dev": true, - "dependencies": { - "@babel/helper-compilation-targets": "^7.22.5", - "@babel/helper-function-name": "^7.22.5", - "@babel/helper-plugin-utils": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-json-strings": { - "version": "7.22.11", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-json-strings/-/plugin-transform-json-strings-7.22.11.tgz", - "integrity": "sha512-CxT5tCqpA9/jXFlme9xIBCc5RPtdDq3JpkkhgHQqtDdiTnTI0jtZ0QzXhr5DILeYifDPp2wvY2ad+7+hLMW5Pw==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.22.5", - "@babel/plugin-syntax-json-strings": "^7.8.3" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-literals": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-literals/-/plugin-transform-literals-7.22.5.tgz", - "integrity": "sha512-fTLj4D79M+mepcw3dgFBTIDYpbcB9Sm0bpm4ppXPaO+U+PKFFyV9MGRvS0gvGw62sd10kT5lRMKXAADb9pWy8g==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-logical-assignment-operators": { - "version": "7.22.11", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-logical-assignment-operators/-/plugin-transform-logical-assignment-operators-7.22.11.tgz", - "integrity": "sha512-qQwRTP4+6xFCDV5k7gZBF3C31K34ut0tbEcTKxlX/0KXxm9GLcO14p570aWxFvVzx6QAfPgq7gaeIHXJC8LswQ==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.22.5", - "@babel/plugin-syntax-logical-assignment-operators": "^7.10.4" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-member-expression-literals": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-member-expression-literals/-/plugin-transform-member-expression-literals-7.22.5.tgz", - "integrity": "sha512-RZEdkNtzzYCFl9SE9ATaUMTj2hqMb4StarOJLrZRbqqU4HSBE7UlBw9WBWQiDzrJZJdUWiMTVDI6Gv/8DPvfew==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-modules-amd": { - "version": "7.23.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-amd/-/plugin-transform-modules-amd-7.23.0.tgz", - "integrity": "sha512-xWT5gefv2HGSm4QHtgc1sYPbseOyf+FFDo2JbpE25GWl5BqTGO9IMwTYJRoIdjsF85GE+VegHxSCUt5EvoYTAw==", - "dev": true, - "dependencies": { - "@babel/helper-module-transforms": "^7.23.0", - "@babel/helper-plugin-utils": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-modules-commonjs": { - "version": "7.23.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-commonjs/-/plugin-transform-modules-commonjs-7.23.0.tgz", - "integrity": "sha512-32Xzss14/UVc7k9g775yMIvkVK8xwKE0DPdP5JTapr3+Z9w4tzeOuLNY6BXDQR6BdnzIlXnCGAzsk/ICHBLVWQ==", - "dev": true, - "dependencies": { - "@babel/helper-module-transforms": "^7.23.0", - "@babel/helper-plugin-utils": "^7.22.5", - "@babel/helper-simple-access": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-modules-systemjs": { - "version": "7.23.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-systemjs/-/plugin-transform-modules-systemjs-7.23.0.tgz", - "integrity": "sha512-qBej6ctXZD2f+DhlOC9yO47yEYgUh5CZNz/aBoH4j/3NOlRfJXJbY7xDQCqQVf9KbrqGzIWER1f23doHGrIHFg==", - "dev": true, - "dependencies": { - "@babel/helper-hoist-variables": "^7.22.5", - "@babel/helper-module-transforms": "^7.23.0", - "@babel/helper-plugin-utils": "^7.22.5", - "@babel/helper-validator-identifier": "^7.22.20" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-modules-umd": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-umd/-/plugin-transform-modules-umd-7.22.5.tgz", - "integrity": "sha512-+S6kzefN/E1vkSsKx8kmQuqeQsvCKCd1fraCM7zXm4SFoggI099Tr4G8U81+5gtMdUeMQ4ipdQffbKLX0/7dBQ==", - "dev": true, - "dependencies": { - "@babel/helper-module-transforms": "^7.22.5", - "@babel/helper-plugin-utils": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-named-capturing-groups-regex": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-named-capturing-groups-regex/-/plugin-transform-named-capturing-groups-regex-7.22.5.tgz", - "integrity": "sha512-YgLLKmS3aUBhHaxp5hi1WJTgOUb/NCuDHzGT9z9WTt3YG+CPRhJs6nprbStx6DnWM4dh6gt7SU3sZodbZ08adQ==", - "dev": true, - "dependencies": { - "@babel/helper-create-regexp-features-plugin": "^7.22.5", - "@babel/helper-plugin-utils": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0" - } - }, - "node_modules/@babel/plugin-transform-new-target": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-new-target/-/plugin-transform-new-target-7.22.5.tgz", - "integrity": "sha512-AsF7K0Fx/cNKVyk3a+DW0JLo+Ua598/NxMRvxDnkpCIGFh43+h/v2xyhRUYf6oD8gE4QtL83C7zZVghMjHd+iw==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-nullish-coalescing-operator": { - "version": "7.22.11", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-nullish-coalescing-operator/-/plugin-transform-nullish-coalescing-operator-7.22.11.tgz", - "integrity": "sha512-YZWOw4HxXrotb5xsjMJUDlLgcDXSfO9eCmdl1bgW4+/lAGdkjaEvOnQ4p5WKKdUgSzO39dgPl0pTnfxm0OAXcg==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.22.5", - "@babel/plugin-syntax-nullish-coalescing-operator": "^7.8.3" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-numeric-separator": { - "version": "7.22.11", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-numeric-separator/-/plugin-transform-numeric-separator-7.22.11.tgz", - "integrity": "sha512-3dzU4QGPsILdJbASKhF/V2TVP+gJya1PsueQCxIPCEcerqF21oEcrob4mzjsp2Py/1nLfF5m+xYNMDpmA8vffg==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.22.5", - "@babel/plugin-syntax-numeric-separator": "^7.10.4" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-object-rest-spread": { - "version": "7.22.15", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-object-rest-spread/-/plugin-transform-object-rest-spread-7.22.15.tgz", - "integrity": "sha512-fEB+I1+gAmfAyxZcX1+ZUwLeAuuf8VIg67CTznZE0MqVFumWkh8xWtn58I4dxdVf080wn7gzWoF8vndOViJe9Q==", - "dev": true, - "dependencies": { - "@babel/compat-data": "^7.22.9", - "@babel/helper-compilation-targets": "^7.22.15", - "@babel/helper-plugin-utils": "^7.22.5", - "@babel/plugin-syntax-object-rest-spread": "^7.8.3", - "@babel/plugin-transform-parameters": "^7.22.15" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-object-super": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-object-super/-/plugin-transform-object-super-7.22.5.tgz", - "integrity": "sha512-klXqyaT9trSjIUrcsYIfETAzmOEZL3cBYqOYLJxBHfMFFggmXOv+NYSX/Jbs9mzMVESw/WycLFPRx8ba/b2Ipw==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.22.5", - "@babel/helper-replace-supers": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-optional-catch-binding": { - "version": "7.22.11", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-optional-catch-binding/-/plugin-transform-optional-catch-binding-7.22.11.tgz", - "integrity": "sha512-rli0WxesXUeCJnMYhzAglEjLWVDF6ahb45HuprcmQuLidBJFWjNnOzssk2kuc6e33FlLaiZhG/kUIzUMWdBKaQ==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.22.5", - "@babel/plugin-syntax-optional-catch-binding": "^7.8.3" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-optional-chaining": { - "version": "7.23.0", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-optional-chaining/-/plugin-transform-optional-chaining-7.23.0.tgz", - "integrity": "sha512-sBBGXbLJjxTzLBF5rFWaikMnOGOk/BmK6vVByIdEggZ7Vn6CvWXZyRkkLFK6WE0IF8jSliyOkUN6SScFgzCM0g==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.22.5", - "@babel/helper-skip-transparent-expression-wrappers": "^7.22.5", - "@babel/plugin-syntax-optional-chaining": "^7.8.3" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-parameters": { - "version": "7.22.15", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-parameters/-/plugin-transform-parameters-7.22.15.tgz", - "integrity": "sha512-hjk7qKIqhyzhhUvRT683TYQOFa/4cQKwQy7ALvTpODswN40MljzNDa0YldevS6tGbxwaEKVn502JmY0dP7qEtQ==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-private-methods": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-private-methods/-/plugin-transform-private-methods-7.22.5.tgz", - "integrity": "sha512-PPjh4gyrQnGe97JTalgRGMuU4icsZFnWkzicB/fUtzlKUqvsWBKEpPPfr5a2JiyirZkHxnAqkQMO5Z5B2kK3fA==", - "dev": true, - "dependencies": { - "@babel/helper-create-class-features-plugin": "^7.22.5", - "@babel/helper-plugin-utils": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-private-property-in-object": { - "version": "7.22.11", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-private-property-in-object/-/plugin-transform-private-property-in-object-7.22.11.tgz", - "integrity": "sha512-sSCbqZDBKHetvjSwpyWzhuHkmW5RummxJBVbYLkGkaiTOWGxml7SXt0iWa03bzxFIx7wOj3g/ILRd0RcJKBeSQ==", - "dev": true, - "dependencies": { - "@babel/helper-annotate-as-pure": "^7.22.5", - "@babel/helper-create-class-features-plugin": "^7.22.11", - "@babel/helper-plugin-utils": "^7.22.5", - "@babel/plugin-syntax-private-property-in-object": "^7.14.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-property-literals": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-property-literals/-/plugin-transform-property-literals-7.22.5.tgz", - "integrity": "sha512-TiOArgddK3mK/x1Qwf5hay2pxI6wCZnvQqrFSqbtg1GLl2JcNMitVH/YnqjP+M31pLUeTfzY1HAXFDnUBV30rQ==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-regenerator": { - "version": "7.22.10", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-regenerator/-/plugin-transform-regenerator-7.22.10.tgz", - "integrity": "sha512-F28b1mDt8KcT5bUyJc/U9nwzw6cV+UmTeRlXYIl2TNqMMJif0Jeey9/RQ3C4NOd2zp0/TRsDns9ttj2L523rsw==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.22.5", - "regenerator-transform": "^0.15.2" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-reserved-words": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-reserved-words/-/plugin-transform-reserved-words-7.22.5.tgz", - "integrity": "sha512-DTtGKFRQUDm8svigJzZHzb/2xatPc6TzNvAIJ5GqOKDsGFYgAskjRulbR/vGsPKq3OPqtexnz327qYpP57RFyA==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-shorthand-properties": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-shorthand-properties/-/plugin-transform-shorthand-properties-7.22.5.tgz", - "integrity": "sha512-vM4fq9IXHscXVKzDv5itkO1X52SmdFBFcMIBZ2FRn2nqVYqw6dBexUgMvAjHW+KXpPPViD/Yo3GrDEBaRC0QYA==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-spread": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-spread/-/plugin-transform-spread-7.22.5.tgz", - "integrity": "sha512-5ZzDQIGyvN4w8+dMmpohL6MBo+l2G7tfC/O2Dg7/hjpgeWvUx8FzfeOKxGog9IimPa4YekaQ9PlDqTLOljkcxg==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.22.5", - "@babel/helper-skip-transparent-expression-wrappers": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-sticky-regex": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-sticky-regex/-/plugin-transform-sticky-regex-7.22.5.tgz", - "integrity": "sha512-zf7LuNpHG0iEeiyCNwX4j3gDg1jgt1k3ZdXBKbZSoA3BbGQGvMiSvfbZRR3Dr3aeJe3ooWFZxOOG3IRStYp2Bw==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-template-literals": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-template-literals/-/plugin-transform-template-literals-7.22.5.tgz", - "integrity": "sha512-5ciOehRNf+EyUeewo8NkbQiUs4d6ZxiHo6BcBcnFlgiJfu16q0bQUw9Jvo0b0gBKFG1SMhDSjeKXSYuJLeFSMA==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-typeof-symbol": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-typeof-symbol/-/plugin-transform-typeof-symbol-7.22.5.tgz", - "integrity": "sha512-bYkI5lMzL4kPii4HHEEChkD0rkc+nvnlR6+o/qdqR6zrm0Sv/nodmyLhlq2DO0YKLUNd2VePmPRjJXSBh9OIdA==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-unicode-escapes": { - "version": "7.22.10", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-escapes/-/plugin-transform-unicode-escapes-7.22.10.tgz", - "integrity": "sha512-lRfaRKGZCBqDlRU3UIFovdp9c9mEvlylmpod0/OatICsSfuQ9YFthRo1tpTkGsklEefZdqlEFdY4A2dwTb6ohg==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-unicode-property-regex": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-property-regex/-/plugin-transform-unicode-property-regex-7.22.5.tgz", - "integrity": "sha512-HCCIb+CbJIAE6sXn5CjFQXMwkCClcOfPCzTlilJ8cUatfzwHlWQkbtV0zD338u9dZskwvuOYTuuaMaA8J5EI5A==", - "dev": true, - "dependencies": { - "@babel/helper-create-regexp-features-plugin": "^7.22.5", - "@babel/helper-plugin-utils": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-unicode-regex": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-regex/-/plugin-transform-unicode-regex-7.22.5.tgz", - "integrity": "sha512-028laaOKptN5vHJf9/Arr/HiJekMd41hOEZYvNsrsXqJ7YPYuX2bQxh31fkZzGmq3YqHRJzYFFAVYvKfMPKqyg==", - "dev": true, - "dependencies": { - "@babel/helper-create-regexp-features-plugin": "^7.22.5", - "@babel/helper-plugin-utils": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-transform-unicode-sets-regex": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-unicode-sets-regex/-/plugin-transform-unicode-sets-regex-7.22.5.tgz", - "integrity": "sha512-lhMfi4FC15j13eKrh3DnYHjpGj6UKQHtNKTbtc1igvAhRy4+kLhV07OpLcsN0VgDEw/MjAvJO4BdMJsHwMhzCg==", - "dev": true, - "dependencies": { - "@babel/helper-create-regexp-features-plugin": "^7.22.5", - "@babel/helper-plugin-utils": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0" - } - }, - "node_modules/@babel/preset-env": { - "version": "7.22.20", - "resolved": "https://registry.npmjs.org/@babel/preset-env/-/preset-env-7.22.20.tgz", - "integrity": "sha512-11MY04gGC4kSzlPHRfvVkNAZhUxOvm7DCJ37hPDnUENwe06npjIRAfInEMTGSb4LZK5ZgDFkv5hw0lGebHeTyg==", - "dev": true, - "dependencies": { - "@babel/compat-data": "^7.22.20", - "@babel/helper-compilation-targets": "^7.22.15", - "@babel/helper-plugin-utils": "^7.22.5", - "@babel/helper-validator-option": "^7.22.15", - "@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression": "^7.22.15", - "@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining": "^7.22.15", - "@babel/plugin-proposal-private-property-in-object": "7.21.0-placeholder-for-preset-env.2", - "@babel/plugin-syntax-async-generators": "^7.8.4", - "@babel/plugin-syntax-class-properties": "^7.12.13", - "@babel/plugin-syntax-class-static-block": "^7.14.5", - "@babel/plugin-syntax-dynamic-import": "^7.8.3", - "@babel/plugin-syntax-export-namespace-from": "^7.8.3", - "@babel/plugin-syntax-import-assertions": "^7.22.5", - "@babel/plugin-syntax-import-attributes": "^7.22.5", - "@babel/plugin-syntax-import-meta": "^7.10.4", - "@babel/plugin-syntax-json-strings": "^7.8.3", - "@babel/plugin-syntax-logical-assignment-operators": "^7.10.4", - "@babel/plugin-syntax-nullish-coalescing-operator": "^7.8.3", - "@babel/plugin-syntax-numeric-separator": "^7.10.4", - "@babel/plugin-syntax-object-rest-spread": "^7.8.3", - "@babel/plugin-syntax-optional-catch-binding": "^7.8.3", - "@babel/plugin-syntax-optional-chaining": "^7.8.3", - "@babel/plugin-syntax-private-property-in-object": "^7.14.5", - "@babel/plugin-syntax-top-level-await": "^7.14.5", - "@babel/plugin-syntax-unicode-sets-regex": "^7.18.6", - "@babel/plugin-transform-arrow-functions": "^7.22.5", - "@babel/plugin-transform-async-generator-functions": "^7.22.15", - "@babel/plugin-transform-async-to-generator": "^7.22.5", - "@babel/plugin-transform-block-scoped-functions": "^7.22.5", - "@babel/plugin-transform-block-scoping": "^7.22.15", - "@babel/plugin-transform-class-properties": "^7.22.5", - "@babel/plugin-transform-class-static-block": "^7.22.11", - "@babel/plugin-transform-classes": "^7.22.15", - "@babel/plugin-transform-computed-properties": "^7.22.5", - "@babel/plugin-transform-destructuring": "^7.22.15", - "@babel/plugin-transform-dotall-regex": "^7.22.5", - "@babel/plugin-transform-duplicate-keys": "^7.22.5", - "@babel/plugin-transform-dynamic-import": "^7.22.11", - "@babel/plugin-transform-exponentiation-operator": "^7.22.5", - "@babel/plugin-transform-export-namespace-from": "^7.22.11", - "@babel/plugin-transform-for-of": "^7.22.15", - "@babel/plugin-transform-function-name": "^7.22.5", - "@babel/plugin-transform-json-strings": "^7.22.11", - "@babel/plugin-transform-literals": "^7.22.5", - "@babel/plugin-transform-logical-assignment-operators": "^7.22.11", - "@babel/plugin-transform-member-expression-literals": "^7.22.5", - "@babel/plugin-transform-modules-amd": "^7.22.5", - "@babel/plugin-transform-modules-commonjs": "^7.22.15", - "@babel/plugin-transform-modules-systemjs": "^7.22.11", - "@babel/plugin-transform-modules-umd": "^7.22.5", - "@babel/plugin-transform-named-capturing-groups-regex": "^7.22.5", - "@babel/plugin-transform-new-target": "^7.22.5", - "@babel/plugin-transform-nullish-coalescing-operator": "^7.22.11", - "@babel/plugin-transform-numeric-separator": "^7.22.11", - "@babel/plugin-transform-object-rest-spread": "^7.22.15", - "@babel/plugin-transform-object-super": "^7.22.5", - "@babel/plugin-transform-optional-catch-binding": "^7.22.11", - "@babel/plugin-transform-optional-chaining": "^7.22.15", - "@babel/plugin-transform-parameters": "^7.22.15", - "@babel/plugin-transform-private-methods": "^7.22.5", - "@babel/plugin-transform-private-property-in-object": "^7.22.11", - "@babel/plugin-transform-property-literals": "^7.22.5", - "@babel/plugin-transform-regenerator": "^7.22.10", - "@babel/plugin-transform-reserved-words": "^7.22.5", - "@babel/plugin-transform-shorthand-properties": "^7.22.5", - "@babel/plugin-transform-spread": "^7.22.5", - "@babel/plugin-transform-sticky-regex": "^7.22.5", - "@babel/plugin-transform-template-literals": "^7.22.5", - "@babel/plugin-transform-typeof-symbol": "^7.22.5", - "@babel/plugin-transform-unicode-escapes": "^7.22.10", - "@babel/plugin-transform-unicode-property-regex": "^7.22.5", - "@babel/plugin-transform-unicode-regex": "^7.22.5", - "@babel/plugin-transform-unicode-sets-regex": "^7.22.5", - "@babel/preset-modules": "0.1.6-no-external-plugins", - "@babel/types": "^7.22.19", - "babel-plugin-polyfill-corejs2": "^0.4.5", - "babel-plugin-polyfill-corejs3": "^0.8.3", - "babel-plugin-polyfill-regenerator": "^0.5.2", - "core-js-compat": "^3.31.0", - "semver": "^6.3.1" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/preset-modules": { - "version": "0.1.6-no-external-plugins", - "resolved": "https://registry.npmjs.org/@babel/preset-modules/-/preset-modules-0.1.6-no-external-plugins.tgz", - "integrity": "sha512-HrcgcIESLm9aIR842yhJ5RWan/gebQUJ6E/E5+rf0y9o6oj7w0Br+sWuL6kEQ/o/AdfvR1Je9jG18/gnpwjEyA==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.0.0", - "@babel/types": "^7.4.4", - "esutils": "^2.0.2" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0 || ^8.0.0-0 <8.0.0" - } - }, - "node_modules/@babel/regjsgen": { - "version": "0.8.0", - "resolved": "https://registry.npmjs.org/@babel/regjsgen/-/regjsgen-0.8.0.tgz", - "integrity": "sha512-x/rqGMdzj+fWZvCOYForTghzbtqPDZ5gPwaoNGHdgDfF2QA/XZbCBp4Moo5scrkAMPhB7z26XM/AaHuIJdgauA==", - "dev": true - }, - "node_modules/@babel/runtime": { - "version": "7.23.1", - "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.23.1.tgz", - "integrity": "sha512-hC2v6p8ZSI/W0HUzh3V8C5g+NwSKzKPtJwSpTjwl0o297GP9+ZLQSkdvHz46CM3LqyoXxq+5G9komY+eSqSO0g==", - "dev": true, - "dependencies": { - "regenerator-runtime": "^0.14.0" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/template": { - "version": "7.22.15", - "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.22.15.tgz", - "integrity": "sha512-QPErUVm4uyJa60rkI73qneDacvdvzxshT3kksGqlGWYdOTIUOwJ7RDUL8sGqslY1uXWSL6xMFKEXDS3ox2uF0w==", - "dev": true, - "dependencies": { - "@babel/code-frame": "^7.22.13", - "@babel/parser": "^7.22.15", - "@babel/types": "^7.22.15" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/traverse": { - "version": "7.23.2", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.23.2.tgz", - "integrity": "sha512-azpe59SQ48qG6nu2CzcMLbxUudtN+dOM9kDbUqGq3HXUJRlo7i8fvPoxQUzYgLZ4cMVmuZgm8vvBpNeRhd6XSw==", - "dev": true, - "dependencies": { - "@babel/code-frame": "^7.22.13", - "@babel/generator": "^7.23.0", - "@babel/helper-environment-visitor": "^7.22.20", - "@babel/helper-function-name": "^7.23.0", - "@babel/helper-hoist-variables": "^7.22.5", - "@babel/helper-split-export-declaration": "^7.22.6", - "@babel/parser": "^7.23.0", - "@babel/types": "^7.23.0", - "debug": "^4.1.0", - "globals": "^11.1.0" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/types": { - "version": "7.23.0", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.23.0.tgz", - "integrity": "sha512-0oIyUfKoI3mSqMvsxBdclDwxXKXAUA8v/apZbc+iSyARYou1o8ZGDxbUYyLFoW2arqS2jDGqJuZvv1d/io1axg==", - "dev": true, - "dependencies": { - "@babel/helper-string-parser": "^7.22.5", - "@babel/helper-validator-identifier": "^7.22.20", - "to-fast-properties": "^2.0.0" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@bcoe/v8-coverage": { - "version": "0.2.3", - "resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz", - "integrity": "sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==", - "dev": true - }, - "node_modules/@istanbuljs/load-nyc-config": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz", - "integrity": "sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==", - "dev": true, - "dependencies": { - "camelcase": "^5.3.1", - "find-up": "^4.1.0", - "get-package-type": "^0.1.0", - "js-yaml": "^3.13.1", - "resolve-from": "^5.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/@istanbuljs/schema": { - "version": "0.1.3", - "resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.3.tgz", - "integrity": "sha512-ZXRY4jNvVgSVQ8DL3LTcakaAtXwTVUxE81hslsyD2AtoXW/wVob10HkOJ1X/pAlcI7D+2YoZKg5do8G/w6RYgA==", - "dev": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/@jest/console": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/console/-/console-29.7.0.tgz", - "integrity": "sha512-5Ni4CU7XHQi32IJ398EEP4RrB8eV09sXP2ROqD4bksHrnTree52PsxvX8tpL8LvTZ3pFzXyPbNQReSN41CAhOg==", - "dev": true, - "dependencies": { - "@jest/types": "^29.6.3", - "@types/node": "*", - "chalk": "^4.0.0", - "jest-message-util": "^29.7.0", - "jest-util": "^29.7.0", - "slash": "^3.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/core": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/core/-/core-29.7.0.tgz", - "integrity": "sha512-n7aeXWKMnGtDA48y8TLWJPJmLmmZ642Ceo78cYWEpiD7FzDgmNDV/GCVRorPABdXLJZ/9wzzgZAlHjXjxDHGsg==", - "dev": true, - "dependencies": { - "@jest/console": "^29.7.0", - "@jest/reporters": "^29.7.0", - "@jest/test-result": "^29.7.0", - "@jest/transform": "^29.7.0", - "@jest/types": "^29.6.3", - "@types/node": "*", - "ansi-escapes": "^4.2.1", - "chalk": "^4.0.0", - "ci-info": "^3.2.0", - "exit": "^0.1.2", - "graceful-fs": "^4.2.9", - "jest-changed-files": "^29.7.0", - "jest-config": "^29.7.0", - "jest-haste-map": "^29.7.0", - "jest-message-util": "^29.7.0", - "jest-regex-util": "^29.6.3", - "jest-resolve": "^29.7.0", - "jest-resolve-dependencies": "^29.7.0", - "jest-runner": "^29.7.0", - "jest-runtime": "^29.7.0", - "jest-snapshot": "^29.7.0", - "jest-util": "^29.7.0", - "jest-validate": "^29.7.0", - "jest-watcher": "^29.7.0", - "micromatch": "^4.0.4", - "pretty-format": "^29.7.0", - "slash": "^3.0.0", - "strip-ansi": "^6.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - }, - "peerDependencies": { - "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" - }, - "peerDependenciesMeta": { - "node-notifier": { - "optional": true - } - } - }, - "node_modules/@jest/environment": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/environment/-/environment-29.7.0.tgz", - "integrity": "sha512-aQIfHDq33ExsN4jP1NWGXhxgQ/wixs60gDiKO+XVMd8Mn0NWPWgc34ZQDTb2jKaUWQ7MuwoitXAsN2XVXNMpAw==", - "dev": true, - "dependencies": { - "@jest/fake-timers": "^29.7.0", - "@jest/types": "^29.6.3", - "@types/node": "*", - "jest-mock": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/expect": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/expect/-/expect-29.7.0.tgz", - "integrity": "sha512-8uMeAMycttpva3P1lBHB8VciS9V0XAr3GymPpipdyQXbBcuhkLQOSe8E/p92RyAdToS6ZD1tFkX+CkhoECE0dQ==", - "dev": true, - "dependencies": { - "expect": "^29.7.0", - "jest-snapshot": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/expect-utils": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/expect-utils/-/expect-utils-29.7.0.tgz", - "integrity": "sha512-GlsNBWiFQFCVi9QVSx7f5AgMeLxe9YCCs5PuP2O2LdjDAA8Jh9eX7lA1Jq/xdXw3Wb3hyvlFNfZIfcRetSzYcA==", - "dev": true, - "dependencies": { - "jest-get-type": "^29.6.3" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/fake-timers": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/fake-timers/-/fake-timers-29.7.0.tgz", - "integrity": "sha512-q4DH1Ha4TTFPdxLsqDXK1d3+ioSL7yL5oCMJZgDYm6i+6CygW5E5xVr/D1HdsGxjt1ZWSfUAs9OxSB/BNelWrQ==", - "dev": true, - "dependencies": { - "@jest/types": "^29.6.3", - "@sinonjs/fake-timers": "^10.0.2", - "@types/node": "*", - "jest-message-util": "^29.7.0", - "jest-mock": "^29.7.0", - "jest-util": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/globals": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/globals/-/globals-29.7.0.tgz", - "integrity": "sha512-mpiz3dutLbkW2MNFubUGUEVLkTGiqW6yLVTA+JbP6fI6J5iL9Y0Nlg8k95pcF8ctKwCS7WVxteBs29hhfAotzQ==", - "dev": true, - "dependencies": { - "@jest/environment": "^29.7.0", - "@jest/expect": "^29.7.0", - "@jest/types": "^29.6.3", - "jest-mock": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/reporters": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/reporters/-/reporters-29.7.0.tgz", - "integrity": "sha512-DApq0KJbJOEzAFYjHADNNxAE3KbhxQB1y5Kplb5Waqw6zVbuWatSnMjE5gs8FUgEPmNsnZA3NCWl9NG0ia04Pg==", - "dev": true, - "dependencies": { - "@bcoe/v8-coverage": "^0.2.3", - "@jest/console": "^29.7.0", - "@jest/test-result": "^29.7.0", - "@jest/transform": "^29.7.0", - "@jest/types": "^29.6.3", - "@jridgewell/trace-mapping": "^0.3.18", - "@types/node": "*", - "chalk": "^4.0.0", - "collect-v8-coverage": "^1.0.0", - "exit": "^0.1.2", - "glob": "^7.1.3", - "graceful-fs": "^4.2.9", - "istanbul-lib-coverage": "^3.0.0", - "istanbul-lib-instrument": "^6.0.0", - "istanbul-lib-report": "^3.0.0", - "istanbul-lib-source-maps": "^4.0.0", - "istanbul-reports": "^3.1.3", - "jest-message-util": "^29.7.0", - "jest-util": "^29.7.0", - "jest-worker": "^29.7.0", - "slash": "^3.0.0", - "string-length": "^4.0.1", - "strip-ansi": "^6.0.0", - "v8-to-istanbul": "^9.0.1" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - }, - "peerDependencies": { - "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" - }, - "peerDependenciesMeta": { - "node-notifier": { - "optional": true - } - } - }, - "node_modules/@jest/schemas": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-29.6.3.tgz", - "integrity": "sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA==", - "dev": true, - "dependencies": { - "@sinclair/typebox": "^0.27.8" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/source-map": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/@jest/source-map/-/source-map-29.6.3.tgz", - "integrity": "sha512-MHjT95QuipcPrpLM+8JMSzFx6eHp5Bm+4XeFDJlwsvVBjmKNiIAvasGK2fxz2WbGRlnvqehFbh07MMa7n3YJnw==", - "dev": true, - "dependencies": { - "@jridgewell/trace-mapping": "^0.3.18", - "callsites": "^3.0.0", - "graceful-fs": "^4.2.9" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/test-result": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/test-result/-/test-result-29.7.0.tgz", - "integrity": "sha512-Fdx+tv6x1zlkJPcWXmMDAG2HBnaR9XPSd5aDWQVsfrZmLVT3lU1cwyxLgRmXR9yrq4NBoEm9BMsfgFzTQAbJYA==", - "dev": true, - "dependencies": { - "@jest/console": "^29.7.0", - "@jest/types": "^29.6.3", - "@types/istanbul-lib-coverage": "^2.0.0", - "collect-v8-coverage": "^1.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/test-sequencer": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/test-sequencer/-/test-sequencer-29.7.0.tgz", - "integrity": "sha512-GQwJ5WZVrKnOJuiYiAF52UNUJXgTZx1NHjFSEB0qEMmSZKAkdMoIzw/Cj6x6NF4AvV23AUqDpFzQkN/eYCYTxw==", - "dev": true, - "dependencies": { - "@jest/test-result": "^29.7.0", - "graceful-fs": "^4.2.9", - "jest-haste-map": "^29.7.0", - "slash": "^3.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/transform": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/transform/-/transform-29.7.0.tgz", - "integrity": "sha512-ok/BTPFzFKVMwO5eOHRrvnBVHdRy9IrsrW1GpMaQ9MCnilNLXQKmAX8s1YXDFaai9xJpac2ySzV0YeRRECr2Vw==", - "dev": true, - "dependencies": { - "@babel/core": "^7.11.6", - "@jest/types": "^29.6.3", - "@jridgewell/trace-mapping": "^0.3.18", - "babel-plugin-istanbul": "^6.1.1", - "chalk": "^4.0.0", - "convert-source-map": "^2.0.0", - "fast-json-stable-stringify": "^2.1.0", - "graceful-fs": "^4.2.9", - "jest-haste-map": "^29.7.0", - "jest-regex-util": "^29.6.3", - "jest-util": "^29.7.0", - "micromatch": "^4.0.4", - "pirates": "^4.0.4", - "slash": "^3.0.0", - "write-file-atomic": "^4.0.2" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/types": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/@jest/types/-/types-29.6.3.tgz", - "integrity": "sha512-u3UPsIilWKOM3F9CXtrG8LEJmNxwoCQC/XVj4IKYXvvpx7QIi/Kg1LI5uDmDpKlac62NUtX7eLjRh+jVZcLOzw==", - "dev": true, - "dependencies": { - "@jest/schemas": "^29.6.3", - "@types/istanbul-lib-coverage": "^2.0.0", - "@types/istanbul-reports": "^3.0.0", - "@types/node": "*", - "@types/yargs": "^17.0.8", - "chalk": "^4.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jridgewell/gen-mapping": { - "version": "0.3.3", - "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.3.tgz", - "integrity": "sha512-HLhSWOLRi875zjjMG/r+Nv0oCW8umGb0BgEhyX3dDX3egwZtB8PqLnjz3yedt8R5StBrzcg4aBpnh8UA9D1BoQ==", - "dev": true, - "dependencies": { - "@jridgewell/set-array": "^1.0.1", - "@jridgewell/sourcemap-codec": "^1.4.10", - "@jridgewell/trace-mapping": "^0.3.9" - }, - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/@jridgewell/resolve-uri": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.1.tgz", - "integrity": "sha512-dSYZh7HhCDtCKm4QakX0xFpsRDqjjtZf/kjI/v3T3Nwt5r8/qz/M19F9ySyOqU94SXBmeG9ttTul+YnR4LOxFA==", - "dev": true, - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/@jridgewell/set-array": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/@jridgewell/set-array/-/set-array-1.1.2.tgz", - "integrity": "sha512-xnkseuNADM0gt2bs+BvhO0p78Mk762YnZdsuzFV018NoG1Sj1SCQvpSqa7XUaTam5vAGasABV9qXASMKnFMwMw==", - "dev": true, - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/@jridgewell/sourcemap-codec": { - "version": "1.4.15", - "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz", - "integrity": "sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==", - "dev": true - }, - "node_modules/@jridgewell/trace-mapping": { - "version": "0.3.19", - "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.19.tgz", - "integrity": "sha512-kf37QtfW+Hwx/buWGMPcR60iF9ziHa6r/CZJIHbmcm4+0qrXiVdxegAH0F6yddEVQ7zdkjcGCgCzUu+BcbhQxw==", - "dev": true, - "dependencies": { - "@jridgewell/resolve-uri": "^3.1.0", - "@jridgewell/sourcemap-codec": "^1.4.14" - } - }, - "node_modules/@sinclair/typebox": { - "version": "0.27.8", - "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.8.tgz", - "integrity": "sha512-+Fj43pSMwJs4KRrH/938Uf+uAELIgVBmQzg/q1YG10djyfA3TnrU8N8XzqCh/okZdszqBQTZf96idMfE5lnwTA==", - "dev": true - }, - "node_modules/@sinonjs/commons": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/@sinonjs/commons/-/commons-3.0.0.tgz", - "integrity": "sha512-jXBtWAF4vmdNmZgD5FoKsVLv3rPgDnLgPbU84LIJ3otV44vJlDRokVng5v8NFJdCf/da9legHcKaRuZs4L7faA==", - "dev": true, - "dependencies": { - "type-detect": "4.0.8" - } - }, - "node_modules/@sinonjs/fake-timers": { - "version": "10.3.0", - "resolved": "https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-10.3.0.tgz", - "integrity": "sha512-V4BG07kuYSUkTCSBHG8G8TNhM+F19jXFWnQtzj+we8DrkpSBCee9Z3Ms8yiGer/dlmhe35/Xdgyo3/0rQKg7YA==", - "dev": true, - "dependencies": { - "@sinonjs/commons": "^3.0.0" - } - }, - "node_modules/@tootallnate/once": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-2.0.0.tgz", - "integrity": "sha512-XCuKFP5PS55gnMVu3dty8KPatLqUoy/ZYzDzAGCQ8JNFCkLXzmI7vNHCR+XpbZaMWQK/vQubr7PkYq8g470J/A==", - "dev": true, - "engines": { - "node": ">= 10" - } - }, - "node_modules/@types/babel__core": { - "version": "7.20.2", - "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.2.tgz", - "integrity": "sha512-pNpr1T1xLUc2l3xJKuPtsEky3ybxN3m4fJkknfIpTCTfIZCDW57oAg+EfCgIIp2rvCe0Wn++/FfodDS4YXxBwA==", - "dev": true, - "dependencies": { - "@babel/parser": "^7.20.7", - "@babel/types": "^7.20.7", - "@types/babel__generator": "*", - "@types/babel__template": "*", - "@types/babel__traverse": "*" - } - }, - "node_modules/@types/babel__generator": { - "version": "7.6.5", - "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.6.5.tgz", - "integrity": "sha512-h9yIuWbJKdOPLJTbmSpPzkF67e659PbQDba7ifWm5BJ8xTv+sDmS7rFmywkWOvXedGTivCdeGSIIX8WLcRTz8w==", - "dev": true, - "dependencies": { - "@babel/types": "^7.0.0" - } - }, - "node_modules/@types/babel__template": { - "version": "7.4.2", - "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.2.tgz", - "integrity": "sha512-/AVzPICMhMOMYoSx9MoKpGDKdBRsIXMNByh1PXSZoa+v6ZoLa8xxtsT/uLQ/NJm0XVAWl/BvId4MlDeXJaeIZQ==", - "dev": true, - "dependencies": { - "@babel/parser": "^7.1.0", - "@babel/types": "^7.0.0" - } - }, - "node_modules/@types/babel__traverse": { - "version": "7.20.2", - "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.20.2.tgz", - "integrity": "sha512-ojlGK1Hsfce93J0+kn3H5R73elidKUaZonirN33GSmgTUMpzI/MIFfSpF3haANe3G1bEBS9/9/QEqwTzwqFsKw==", - "dev": true, - "dependencies": { - "@babel/types": "^7.20.7" - } - }, - "node_modules/@types/graceful-fs": { - "version": "4.1.7", - "resolved": "https://registry.npmjs.org/@types/graceful-fs/-/graceful-fs-4.1.7.tgz", - "integrity": "sha512-MhzcwU8aUygZroVwL2jeYk6JisJrPl/oov/gsgGCue9mkgl9wjGbzReYQClxiUgFDnib9FuHqTndccKeZKxTRw==", - "dev": true, - "dependencies": { - "@types/node": "*" - } - }, - "node_modules/@types/istanbul-lib-coverage": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.4.tgz", - "integrity": "sha512-z/QT1XN4K4KYuslS23k62yDIDLwLFkzxOuMplDtObz0+y7VqJCaO2o+SPwHCvLFZh7xazvvoor2tA/hPz9ee7g==", - "dev": true - }, - "node_modules/@types/istanbul-lib-report": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/@types/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz", - "integrity": "sha512-gPQuzaPR5h/djlAv2apEG1HVOyj1IUs7GpfMZixU0/0KXT3pm64ylHuMUI1/Akh+sq/iikxg6Z2j+fcMDXaaTQ==", - "dev": true, - "dependencies": { - "@types/istanbul-lib-coverage": "*" - } - }, - "node_modules/@types/istanbul-reports": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.2.tgz", - "integrity": "sha512-kv43F9eb3Lhj+lr/Hn6OcLCs/sSM8bt+fIaP11rCYngfV6NVjzWXJ17owQtDQTL9tQ8WSLUrGsSJ6rJz0F1w1A==", - "dev": true, - "dependencies": { - "@types/istanbul-lib-report": "*" - } - }, - "node_modules/@types/jest": { - "version": "29.5.5", - "resolved": "https://registry.npmjs.org/@types/jest/-/jest-29.5.5.tgz", - "integrity": "sha512-ebylz2hnsWR9mYvmBFbXJXr+33UPc4+ZdxyDXh5w0FlPBTfCVN3wPL+kuOiQt3xvrK419v7XWeAs+AeOksafXg==", - "dev": true, - "dependencies": { - "expect": "^29.0.0", - "pretty-format": "^29.0.0" - } - }, - "node_modules/@types/jsdom": { - "version": "20.0.1", - "resolved": "https://registry.npmjs.org/@types/jsdom/-/jsdom-20.0.1.tgz", - "integrity": "sha512-d0r18sZPmMQr1eG35u12FZfhIXNrnsPU/g5wvRKCUf/tOGilKKwYMYGqh33BNR6ba+2gkHw1EUiHoN3mn7E5IQ==", - "dev": true, - "dependencies": { - "@types/node": "*", - "@types/tough-cookie": "*", - "parse5": "^7.0.0" - } - }, - "node_modules/@types/node": { - "version": "20.8.3", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.8.3.tgz", - "integrity": "sha512-jxiZQFpb+NlH5kjW49vXxvxTjeeqlbsnTAdBTKpzEdPs9itay7MscYXz3Fo9VYFEsfQ6LJFitHad3faerLAjCw==", - "dev": true - }, - "node_modules/@types/stack-utils": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-2.0.1.tgz", - "integrity": "sha512-Hl219/BT5fLAaz6NDkSuhzasy49dwQS/DSdu4MdggFB8zcXv7vflBI3xp7FEmkmdDkBUI2bPUNeMttp2knYdxw==", - "dev": true - }, - "node_modules/@types/tough-cookie": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/@types/tough-cookie/-/tough-cookie-4.0.3.tgz", - "integrity": "sha512-THo502dA5PzG/sfQH+42Lw3fvmYkceefOspdCwpHRul8ik2Jv1K8I5OZz1AT3/rs46kwgMCe9bSBmDLYkkOMGg==", - "dev": true - }, - "node_modules/@types/yargs": { - "version": "17.0.28", - "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.28.tgz", - "integrity": "sha512-N3e3fkS86hNhtk6BEnc0rj3zcehaxx8QWhCROJkqpl5Zaoi7nAic3jH8q94jVD3zu5LGk+PUB6KAiDmimYOEQw==", - "dev": true, - "dependencies": { - "@types/yargs-parser": "*" - } - }, - "node_modules/@types/yargs-parser": { - "version": "21.0.1", - "resolved": "https://registry.npmjs.org/@types/yargs-parser/-/yargs-parser-21.0.1.tgz", - "integrity": "sha512-axdPBuLuEJt0c4yI5OZssC19K2Mq1uKdrfZBzuxLvaztgqUtFYZUNw7lETExPYJR9jdEoIg4mb7RQKRQzOkeGQ==", - "dev": true - }, - "node_modules/abab": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/abab/-/abab-2.0.6.tgz", - "integrity": "sha512-j2afSsaIENvHZN2B8GOpF566vZ5WVk5opAiMTvWgaQT8DkbOqsTfvNAvHoRGU2zzP8cPoqys+xHTRDWW8L+/BA==", - "dev": true - }, - "node_modules/acorn": { - "version": "8.10.0", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.10.0.tgz", - "integrity": "sha512-F0SAmZ8iUtS//m8DmCTA0jlh6TDKkHQyK6xc6V4KDTyZKA9dnvX9/3sRTVQrWm79glUAZbnmmNcdYwUIHWVybw==", - "dev": true, - "bin": { - "acorn": "bin/acorn" - }, - "engines": { - "node": ">=0.4.0" - } - }, - "node_modules/acorn-globals": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/acorn-globals/-/acorn-globals-7.0.1.tgz", - "integrity": "sha512-umOSDSDrfHbTNPuNpC2NSnnA3LUrqpevPb4T9jRx4MagXNS0rs+gwiTcAvqCRmsD6utzsrzNt+ebm00SNWiC3Q==", - "dev": true, - "dependencies": { - "acorn": "^8.1.0", - "acorn-walk": "^8.0.2" - } - }, - "node_modules/acorn-walk": { - "version": "8.2.0", - "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.2.0.tgz", - "integrity": "sha512-k+iyHEuPgSw6SbuDpGQM+06HQUa04DZ3o+F6CSzXMvvI5KMvnaEqXe+YVe555R9nn6GPt404fos4wcgpw12SDA==", - "dev": true, - "engines": { - "node": ">=0.4.0" - } - }, - "node_modules/agent-base": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", - "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", - "dev": true, - "dependencies": { - "debug": "4" - }, - "engines": { - "node": ">= 6.0.0" - } - }, - "node_modules/ansi-escapes": { - "version": "4.3.2", - "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", - "integrity": "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==", - "dev": true, - "dependencies": { - "type-fest": "^0.21.3" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dev": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/ansi-styles": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", - "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", - "dev": true, - "dependencies": { - "color-convert": "^2.0.1" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, - "node_modules/anymatch": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", - "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", - "dev": true, - "dependencies": { - "normalize-path": "^3.0.0", - "picomatch": "^2.0.4" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/argparse": { - "version": "1.0.10", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", - "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", - "dev": true, - "dependencies": { - "sprintf-js": "~1.0.2" - } - }, - "node_modules/asynckit": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", - "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", - "dev": true - }, - "node_modules/babel-jest": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/babel-jest/-/babel-jest-29.7.0.tgz", - "integrity": "sha512-BrvGY3xZSwEcCzKvKsCi2GgHqDqsYkOP4/by5xCgIwGXQxIEh+8ew3gmrE1y7XRR6LHZIj6yLYnUi/mm2KXKBg==", - "dev": true, - "dependencies": { - "@jest/transform": "^29.7.0", - "@types/babel__core": "^7.1.14", - "babel-plugin-istanbul": "^6.1.1", - "babel-preset-jest": "^29.6.3", - "chalk": "^4.0.0", - "graceful-fs": "^4.2.9", - "slash": "^3.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - }, - "peerDependencies": { - "@babel/core": "^7.8.0" - } - }, - "node_modules/babel-plugin-istanbul": { - "version": "6.1.1", - "resolved": "https://registry.npmjs.org/babel-plugin-istanbul/-/babel-plugin-istanbul-6.1.1.tgz", - "integrity": "sha512-Y1IQok9821cC9onCx5otgFfRm7Lm+I+wwxOx738M/WLPZ9Q42m4IG5W0FNX8WLL2gYMZo3JkuXIH2DOpWM+qwA==", - "dev": true, - "dependencies": { - "@babel/helper-plugin-utils": "^7.0.0", - "@istanbuljs/load-nyc-config": "^1.0.0", - "@istanbuljs/schema": "^0.1.2", - "istanbul-lib-instrument": "^5.0.4", - "test-exclude": "^6.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/babel-plugin-istanbul/node_modules/istanbul-lib-instrument": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-5.2.1.tgz", - "integrity": "sha512-pzqtp31nLv/XFOzXGuvhCb8qhjmTVo5vjVk19XE4CRlSWz0KoeJ3bw9XsA7nOp9YBf4qHjwBxkDzKcME/J29Yg==", - "dev": true, - "dependencies": { - "@babel/core": "^7.12.3", - "@babel/parser": "^7.14.7", - "@istanbuljs/schema": "^0.1.2", - "istanbul-lib-coverage": "^3.2.0", - "semver": "^6.3.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/babel-plugin-jest-hoist": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/babel-plugin-jest-hoist/-/babel-plugin-jest-hoist-29.6.3.tgz", - "integrity": "sha512-ESAc/RJvGTFEzRwOTT4+lNDk/GNHMkKbNzsvT0qKRfDyyYTskxB5rnU2njIDYVxXCBHHEI1c0YwHob3WaYujOg==", - "dev": true, - "dependencies": { - "@babel/template": "^7.3.3", - "@babel/types": "^7.3.3", - "@types/babel__core": "^7.1.14", - "@types/babel__traverse": "^7.0.6" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/babel-plugin-polyfill-corejs2": { - "version": "0.4.5", - "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-corejs2/-/babel-plugin-polyfill-corejs2-0.4.5.tgz", - "integrity": "sha512-19hwUH5FKl49JEsvyTcoHakh6BE0wgXLLptIyKZ3PijHc/Ci521wygORCUCCred+E/twuqRyAkE02BAWPmsHOg==", - "dev": true, - "dependencies": { - "@babel/compat-data": "^7.22.6", - "@babel/helper-define-polyfill-provider": "^0.4.2", - "semver": "^6.3.1" - }, - "peerDependencies": { - "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0" - } - }, - "node_modules/babel-plugin-polyfill-corejs3": { - "version": "0.8.4", - "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-corejs3/-/babel-plugin-polyfill-corejs3-0.8.4.tgz", - "integrity": "sha512-9l//BZZsPR+5XjyJMPtZSK4jv0BsTO1zDac2GC6ygx9WLGlcsnRd1Co0B2zT5fF5Ic6BZy+9m3HNZ3QcOeDKfg==", - "dev": true, - "dependencies": { - "@babel/helper-define-polyfill-provider": "^0.4.2", - "core-js-compat": "^3.32.2" - }, - "peerDependencies": { - "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0" - } - }, - "node_modules/babel-plugin-polyfill-regenerator": { - "version": "0.5.2", - "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-regenerator/-/babel-plugin-polyfill-regenerator-0.5.2.tgz", - "integrity": "sha512-tAlOptU0Xj34V1Y2PNTL4Y0FOJMDB6bZmoW39FeCQIhigGLkqu3Fj6uiXpxIf6Ij274ENdYx64y6Au+ZKlb1IA==", - "dev": true, - "dependencies": { - "@babel/helper-define-polyfill-provider": "^0.4.2" - }, - "peerDependencies": { - "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0" - } - }, - "node_modules/babel-plugin-transform-import-meta": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/babel-plugin-transform-import-meta/-/babel-plugin-transform-import-meta-2.2.1.tgz", - "integrity": "sha512-AxNh27Pcg8Kt112RGa3Vod2QS2YXKKJ6+nSvRtv7qQTJAdx0MZa4UHZ4lnxHUWA2MNbLuZQv5FVab4P1CoLOWw==", - "dev": true, - "dependencies": { - "@babel/template": "^7.4.4", - "tslib": "^2.4.0" - }, - "peerDependencies": { - "@babel/core": "^7.10.0" - } - }, - "node_modules/babel-preset-current-node-syntax": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/babel-preset-current-node-syntax/-/babel-preset-current-node-syntax-1.0.1.tgz", - "integrity": "sha512-M7LQ0bxarkxQoN+vz5aJPsLBn77n8QgTFmo8WK0/44auK2xlCXrYcUxHFxgU7qW5Yzw/CjmLRK2uJzaCd7LvqQ==", - "dev": true, - "dependencies": { - "@babel/plugin-syntax-async-generators": "^7.8.4", - "@babel/plugin-syntax-bigint": "^7.8.3", - "@babel/plugin-syntax-class-properties": "^7.8.3", - "@babel/plugin-syntax-import-meta": "^7.8.3", - "@babel/plugin-syntax-json-strings": "^7.8.3", - "@babel/plugin-syntax-logical-assignment-operators": "^7.8.3", - "@babel/plugin-syntax-nullish-coalescing-operator": "^7.8.3", - "@babel/plugin-syntax-numeric-separator": "^7.8.3", - "@babel/plugin-syntax-object-rest-spread": "^7.8.3", - "@babel/plugin-syntax-optional-catch-binding": "^7.8.3", - "@babel/plugin-syntax-optional-chaining": "^7.8.3", - "@babel/plugin-syntax-top-level-await": "^7.8.3" - }, - "peerDependencies": { - "@babel/core": "^7.0.0" - } - }, - "node_modules/babel-preset-jest": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/babel-preset-jest/-/babel-preset-jest-29.6.3.tgz", - "integrity": "sha512-0B3bhxR6snWXJZtR/RliHTDPRgn1sNHOR0yVtq/IiQFyuOVjFS+wuio/R4gSNkyYmKmJB4wGZv2NZanmKmTnNA==", - "dev": true, - "dependencies": { - "babel-plugin-jest-hoist": "^29.6.3", - "babel-preset-current-node-syntax": "^1.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0" - } - }, - "node_modules/balanced-match": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", - "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", - "dev": true - }, - "node_modules/brace-expansion": { - "version": "1.1.11", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", - "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", - "dev": true, - "dependencies": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" - } - }, - "node_modules/braces": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", - "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", - "dev": true, - "dependencies": { - "fill-range": "^7.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/browserslist": { - "version": "4.22.1", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.22.1.tgz", - "integrity": "sha512-FEVc202+2iuClEhZhrWy6ZiAcRLvNMyYcxZ8raemul1DYVOVdFsbqckWLdsixQZCpJlwe77Z3UTalE7jsjnKfQ==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/browserslist" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/browserslist" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "dependencies": { - "caniuse-lite": "^1.0.30001541", - "electron-to-chromium": "^1.4.535", - "node-releases": "^2.0.13", - "update-browserslist-db": "^1.0.13" - }, - "bin": { - "browserslist": "cli.js" - }, - "engines": { - "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" - } - }, - "node_modules/bser": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/bser/-/bser-2.1.1.tgz", - "integrity": "sha512-gQxTNE/GAfIIrmHLUE3oJyp5FO6HRBfhjnw4/wMmA63ZGDJnWBmgY/lyQBpnDUkGmAhbSe39tx2d/iTOAfglwQ==", - "dev": true, - "dependencies": { - "node-int64": "^0.4.0" - } - }, - "node_modules/buffer-from": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", - "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", - "dev": true - }, - "node_modules/callsites": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", - "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", - "dev": true, - "engines": { - "node": ">=6" - } - }, - "node_modules/camelcase": { - "version": "5.3.1", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", - "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", - "dev": true, - "engines": { - "node": ">=6" - } - }, - "node_modules/caniuse-lite": { - "version": "1.0.30001546", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001546.tgz", - "integrity": "sha512-zvtSJwuQFpewSyRrI3AsftF6rM0X80mZkChIt1spBGEvRglCrjTniXvinc8JKRoqTwXAgvqTImaN9igfSMtUBw==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/browserslist" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/caniuse-lite" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ] - }, - "node_modules/chalk": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", - "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", - "dev": true, - "dependencies": { - "ansi-styles": "^4.1.0", - "supports-color": "^7.1.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/chalk?sponsor=1" - } - }, - "node_modules/char-regex": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/char-regex/-/char-regex-1.0.2.tgz", - "integrity": "sha512-kWWXztvZ5SBQV+eRgKFeh8q5sLuZY2+8WUIzlxWVTg+oGwY14qylx1KbKzHd8P6ZYkAg0xyIDU9JMHhyJMZ1jw==", - "dev": true, - "engines": { - "node": ">=10" - } - }, - "node_modules/ci-info": { - "version": "3.9.0", - "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.9.0.tgz", - "integrity": "sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/sibiraj-s" - } - ], - "engines": { - "node": ">=8" - } - }, - "node_modules/cjs-module-lexer": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/cjs-module-lexer/-/cjs-module-lexer-1.2.3.tgz", - "integrity": "sha512-0TNiGstbQmCFwt4akjjBg5pLRTSyj/PkWQ1ZoO2zntmg9yLqSRxwEa4iCfQLGjqhiqBfOJa7W/E8wfGrTDmlZQ==", - "dev": true - }, - "node_modules/cliui": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", - "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", - "dev": true, - "dependencies": { - "string-width": "^4.2.0", - "strip-ansi": "^6.0.1", - "wrap-ansi": "^7.0.0" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/co": { - "version": "4.6.0", - "resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz", - "integrity": "sha512-QVb0dM5HvG+uaxitm8wONl7jltx8dqhfU33DcqtOZcLSVIKSDDLDi7+0LbAKiyI8hD9u42m2YxXSkMGWThaecQ==", - "dev": true, - "engines": { - "iojs": ">= 1.0.0", - "node": ">= 0.12.0" - } - }, - "node_modules/collect-v8-coverage": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/collect-v8-coverage/-/collect-v8-coverage-1.0.2.tgz", - "integrity": "sha512-lHl4d5/ONEbLlJvaJNtsF/Lz+WvB07u2ycqTYbdrq7UypDXailES4valYb2eWiJFxZlVmpGekfqoxQhzyFdT4Q==", - "dev": true - }, - "node_modules/color-convert": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", - "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", - "dev": true, - "dependencies": { - "color-name": "~1.1.4" - }, - "engines": { - "node": ">=7.0.0" - } - }, - "node_modules/color-name": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", - "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", - "dev": true - }, - "node_modules/combined-stream": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", - "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", - "dev": true, - "dependencies": { - "delayed-stream": "~1.0.0" - }, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/concat-map": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", - "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", - "dev": true - }, - "node_modules/convert-source-map": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", - "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", - "dev": true - }, - "node_modules/core-js-compat": { - "version": "3.33.0", - "resolved": "https://registry.npmjs.org/core-js-compat/-/core-js-compat-3.33.0.tgz", - "integrity": "sha512-0w4LcLXsVEuNkIqwjjf9rjCoPhK8uqA4tMRh4Ge26vfLtUutshn+aRJU21I9LCJlh2QQHfisNToLjw1XEJLTWw==", - "dev": true, - "dependencies": { - "browserslist": "^4.22.1" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/core-js" - } - }, - "node_modules/create-jest": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/create-jest/-/create-jest-29.7.0.tgz", - "integrity": "sha512-Adz2bdH0Vq3F53KEMJOoftQFutWCukm6J24wbPWRO4k1kMY7gS7ds/uoJkNuV8wDCtWWnuwGcJwpWcih+zEW1Q==", - "dev": true, - "dependencies": { - "@jest/types": "^29.6.3", - "chalk": "^4.0.0", - "exit": "^0.1.2", - "graceful-fs": "^4.2.9", - "jest-config": "^29.7.0", - "jest-util": "^29.7.0", - "prompts": "^2.0.1" - }, - "bin": { - "create-jest": "bin/create-jest.js" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/cross-spawn": { - "version": "7.0.3", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", - "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", - "dev": true, - "dependencies": { - "path-key": "^3.1.0", - "shebang-command": "^2.0.0", - "which": "^2.0.1" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/cssom": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/cssom/-/cssom-0.5.0.tgz", - "integrity": "sha512-iKuQcq+NdHqlAcwUY0o/HL69XQrUaQdMjmStJ8JFmUaiiQErlhrmuigkg/CU4E2J0IyUKUrMAgl36TvN67MqTw==", - "dev": true - }, - "node_modules/cssstyle": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-2.3.0.tgz", - "integrity": "sha512-AZL67abkUzIuvcHqk7c09cezpGNcxUxU4Ioi/05xHk4DQeTkWmGYftIE6ctU6AEt+Gn4n1lDStOtj7FKycP71A==", - "dev": true, - "dependencies": { - "cssom": "~0.3.6" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/cssstyle/node_modules/cssom": { - "version": "0.3.8", - "resolved": "https://registry.npmjs.org/cssom/-/cssom-0.3.8.tgz", - "integrity": "sha512-b0tGHbfegbhPJpxpiBPU2sCkigAqtM9O121le6bbOlgyV+NyGyCmVfJ6QW9eRjz8CpNfWEOYBIMIGRYkLwsIYg==", - "dev": true - }, - "node_modules/data-urls": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-3.0.2.tgz", - "integrity": "sha512-Jy/tj3ldjZJo63sVAvg6LHt2mHvl4V6AgRAmNDtLdm7faqtsx+aJG42rsyCo9JCoRVKwPFzKlIPx3DIibwSIaQ==", - "dev": true, - "dependencies": { - "abab": "^2.0.6", - "whatwg-mimetype": "^3.0.0", - "whatwg-url": "^11.0.0" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/debug": { - "version": "4.3.4", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", - "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", - "dev": true, - "dependencies": { - "ms": "2.1.2" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, - "node_modules/decimal.js": { - "version": "10.4.3", - "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.4.3.tgz", - "integrity": "sha512-VBBaLc1MgL5XpzgIP7ny5Z6Nx3UrRkIViUkPUdtl9aya5amy3De1gsUUSB1g3+3sExYNjCAsAznmukyxCb1GRA==", - "dev": true - }, - "node_modules/dedent": { - "version": "1.5.1", - "resolved": "https://registry.npmjs.org/dedent/-/dedent-1.5.1.tgz", - "integrity": "sha512-+LxW+KLWxu3HW3M2w2ympwtqPrqYRzU8fqi6Fhd18fBALe15blJPI/I4+UHveMVG6lJqB4JNd4UG0S5cnVHwIg==", - "dev": true, - "peerDependencies": { - "babel-plugin-macros": "^3.1.0" - }, - "peerDependenciesMeta": { - "babel-plugin-macros": { - "optional": true - } - } - }, - "node_modules/deepmerge": { - "version": "4.3.1", - "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz", - "integrity": "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==", - "dev": true, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/delayed-stream": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", - "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", - "dev": true, - "engines": { - "node": ">=0.4.0" - } - }, - "node_modules/detect-newline": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/detect-newline/-/detect-newline-3.1.0.tgz", - "integrity": "sha512-TLz+x/vEXm/Y7P7wn1EJFNLxYpUD4TgMosxY6fAVJUnJMbupHBOncxyWUG9OpTaH9EBD7uFI5LfEgmMOc54DsA==", - "dev": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/diff-sequences": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.6.3.tgz", - "integrity": "sha512-EjePK1srD3P08o2j4f0ExnylqRs5B9tJjcp9t1krH2qRi8CCdsYfwe9JgSLurFBWwq4uOlipzfk5fHNvwFKr8Q==", - "dev": true, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/domexception": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/domexception/-/domexception-4.0.0.tgz", - "integrity": "sha512-A2is4PLG+eeSfoTMA95/s4pvAoSo2mKtiM5jlHkAVewmiO8ISFTFKZjH7UAM1Atli/OT/7JHOrJRJiMKUZKYBw==", - "dev": true, - "dependencies": { - "webidl-conversions": "^7.0.0" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/electron-to-chromium": { - "version": "1.4.544", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.544.tgz", - "integrity": "sha512-54z7squS1FyFRSUqq/knOFSptjjogLZXbKcYk3B0qkE1KZzvqASwRZnY2KzZQJqIYLVD38XZeoiMRflYSwyO4w==", - "dev": true - }, - "node_modules/emittery": { - "version": "0.13.1", - "resolved": "https://registry.npmjs.org/emittery/-/emittery-0.13.1.tgz", - "integrity": "sha512-DeWwawk6r5yR9jFgnDKYt4sLS0LmHJJi3ZOnb5/JdbYwj3nW+FxQnHIjhBKz8YLC7oRNPVM9NQ47I3CVx34eqQ==", - "dev": true, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sindresorhus/emittery?sponsor=1" - } - }, - "node_modules/emoji-regex": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", - "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", - "dev": true - }, - "node_modules/entities": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", - "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==", - "dev": true, - "engines": { - "node": ">=0.12" - }, - "funding": { - "url": "https://github.com/fb55/entities?sponsor=1" - } - }, - "node_modules/error-ex": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", - "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", - "dev": true, - "dependencies": { - "is-arrayish": "^0.2.1" - } - }, - "node_modules/escalade": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.1.tgz", - "integrity": "sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==", - "dev": true, - "engines": { - "node": ">=6" - } - }, - "node_modules/escape-string-regexp": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", - "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", - "dev": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/escodegen": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-2.1.0.tgz", - "integrity": "sha512-2NlIDTwUWJN0mRPQOdtQBzbUHvdGY2P1VXSyU83Q3xKxM7WHX2Ql8dKq782Q9TgQUNOLEzEYu9bzLNj1q88I5w==", - "dev": true, - "dependencies": { - "esprima": "^4.0.1", - "estraverse": "^5.2.0", - "esutils": "^2.0.2" - }, - "bin": { - "escodegen": "bin/escodegen.js", - "esgenerate": "bin/esgenerate.js" - }, - "engines": { - "node": ">=6.0" - }, - "optionalDependencies": { - "source-map": "~0.6.1" - } - }, - "node_modules/esprima": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", - "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", - "dev": true, - "bin": { - "esparse": "bin/esparse.js", - "esvalidate": "bin/esvalidate.js" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/estraverse": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", - "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", - "dev": true, - "engines": { - "node": ">=4.0" - } - }, - "node_modules/esutils": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", - "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", - "dev": true, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/execa": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz", - "integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==", - "dev": true, - "dependencies": { - "cross-spawn": "^7.0.3", - "get-stream": "^6.0.0", - "human-signals": "^2.1.0", - "is-stream": "^2.0.0", - "merge-stream": "^2.0.0", - "npm-run-path": "^4.0.1", - "onetime": "^5.1.2", - "signal-exit": "^3.0.3", - "strip-final-newline": "^2.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sindresorhus/execa?sponsor=1" - } - }, - "node_modules/exit": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/exit/-/exit-0.1.2.tgz", - "integrity": "sha512-Zk/eNKV2zbjpKzrsQ+n1G6poVbErQxJ0LBOJXaKZ1EViLzH+hrLu9cdXI4zw9dBQJslwBEpbQ2P1oS7nDxs6jQ==", - "dev": true, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/expect": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/expect/-/expect-29.7.0.tgz", - "integrity": "sha512-2Zks0hf1VLFYI1kbh0I5jP3KHHyCHpkfyHBzsSXRFgl/Bg9mWYfMW8oD+PdMPlEwy5HNsR9JutYy6pMeOh61nw==", - "dev": true, - "dependencies": { - "@jest/expect-utils": "^29.7.0", - "jest-get-type": "^29.6.3", - "jest-matcher-utils": "^29.7.0", - "jest-message-util": "^29.7.0", - "jest-util": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/fast-json-stable-stringify": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", - "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", - "dev": true - }, - "node_modules/fb-watchman": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/fb-watchman/-/fb-watchman-2.0.2.tgz", - "integrity": "sha512-p5161BqbuCaSnB8jIbzQHOlpgsPmK5rJVDfDKO91Axs5NC1uu3HRQm6wt9cd9/+GtQQIO53JdGXXoyDpTAsgYA==", - "dev": true, - "dependencies": { - "bser": "2.1.1" - } - }, - "node_modules/fill-range": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", - "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", - "dev": true, - "dependencies": { - "to-regex-range": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/find-up": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", - "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", - "dev": true, - "dependencies": { - "locate-path": "^5.0.0", - "path-exists": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/form-data": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", - "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", - "dev": true, - "dependencies": { - "asynckit": "^0.4.0", - "combined-stream": "^1.0.8", - "mime-types": "^2.1.12" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/fs.realpath": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", - "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", - "dev": true - }, - "node_modules/fsevents": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", - "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", - "dev": true, - "hasInstallScript": true, - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^8.16.0 || ^10.6.0 || >=11.0.0" - } - }, - "node_modules/gensync": { - "version": "1.0.0-beta.2", - "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", - "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", - "dev": true, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/get-caller-file": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", - "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", - "dev": true, - "engines": { - "node": "6.* || 8.* || >= 10.*" - } - }, - "node_modules/get-package-type": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/get-package-type/-/get-package-type-0.1.0.tgz", - "integrity": "sha512-pjzuKtY64GYfWizNAJ0fr9VqttZkNiK2iS430LtIHzjBEr6bX8Am2zm4sW4Ro5wjWW5cAlRL1qAMTcXbjNAO2Q==", - "dev": true, - "engines": { - "node": ">=8.0.0" - } - }, - "node_modules/get-stream": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz", - "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==", - "dev": true, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/glob": { - "version": "7.2.3", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", - "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", - "dev": true, - "dependencies": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.1.1", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - }, - "engines": { - "node": "*" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/globals": { - "version": "11.12.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz", - "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==", - "dev": true, - "engines": { - "node": ">=4" - } - }, - "node_modules/graceful-fs": { - "version": "4.2.11", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", - "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", - "dev": true - }, - "node_modules/has": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/has/-/has-1.0.4.tgz", - "integrity": "sha512-qdSAmqLF6209RFj4VVItywPMbm3vWylknmB3nvNiUIs72xAimcM8nVYxYr7ncvZq5qzk9MKIZR8ijqD/1QuYjQ==", - "dev": true, - "engines": { - "node": ">= 0.4.0" - } - }, - "node_modules/has-flag": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", - "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", - "dev": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/html-encoding-sniffer": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-3.0.0.tgz", - "integrity": "sha512-oWv4T4yJ52iKrufjnyZPkrN0CH3QnrUqdB6In1g5Fe1mia8GmF36gnfNySxoZtxD5+NmYw1EElVXiBk93UeskA==", - "dev": true, - "dependencies": { - "whatwg-encoding": "^2.0.0" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/html-escaper": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz", - "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==", - "dev": true - }, - "node_modules/http-proxy-agent": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-5.0.0.tgz", - "integrity": "sha512-n2hY8YdoRE1i7r6M0w9DIw5GgZN0G25P8zLCRQ8rjXtTU3vsNFBI/vWK/UIeE6g5MUUz6avwAPXmL6Fy9D/90w==", - "dev": true, - "dependencies": { - "@tootallnate/once": "2", - "agent-base": "6", - "debug": "4" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/https-proxy-agent": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", - "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", - "dev": true, - "dependencies": { - "agent-base": "6", - "debug": "4" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/human-signals": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz", - "integrity": "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==", - "dev": true, - "engines": { - "node": ">=10.17.0" - } - }, - "node_modules/iconv-lite": { - "version": "0.6.3", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", - "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", - "dev": true, - "dependencies": { - "safer-buffer": ">= 2.1.2 < 3.0.0" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/import-local": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/import-local/-/import-local-3.1.0.tgz", - "integrity": "sha512-ASB07uLtnDs1o6EHjKpX34BKYDSqnFerfTOJL2HvMqF70LnxpjkzDB8J44oT9pu4AMPkQwf8jl6szgvNd2tRIg==", - "dev": true, - "dependencies": { - "pkg-dir": "^4.2.0", - "resolve-cwd": "^3.0.0" - }, - "bin": { - "import-local-fixture": "fixtures/cli.js" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/imurmurhash": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", - "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", - "dev": true, - "engines": { - "node": ">=0.8.19" - } - }, - "node_modules/inflight": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", - "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", - "dev": true, - "dependencies": { - "once": "^1.3.0", - "wrappy": "1" - } - }, - "node_modules/inherits": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "dev": true - }, - "node_modules/is-arrayish": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", - "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==", - "dev": true - }, - "node_modules/is-core-module": { - "version": "2.13.0", - "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.13.0.tgz", - "integrity": "sha512-Z7dk6Qo8pOCp3l4tsX2C5ZVas4V+UxwQodwZhLopL91TX8UyyHEXafPcyoeeWuLrwzHcr3igO78wNLwHJHsMCQ==", - "dev": true, - "dependencies": { - "has": "^1.0.3" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/is-fullwidth-code-point": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", - "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", - "dev": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/is-generator-fn": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/is-generator-fn/-/is-generator-fn-2.1.0.tgz", - "integrity": "sha512-cTIB4yPYL/Grw0EaSzASzg6bBy9gqCofvWN8okThAYIxKJZC+udlRAmGbM0XLeniEJSs8uEgHPGuHSe1XsOLSQ==", - "dev": true, - "engines": { - "node": ">=6" - } - }, - "node_modules/is-number": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", - "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", - "dev": true, - "engines": { - "node": ">=0.12.0" - } - }, - "node_modules/is-potential-custom-element-name": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", - "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", - "dev": true - }, - "node_modules/is-stream": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", - "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", - "dev": true, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/isexe": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", - "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", - "dev": true - }, - "node_modules/istanbul-lib-coverage": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.0.tgz", - "integrity": "sha512-eOeJ5BHCmHYvQK7xt9GkdHuzuCGS1Y6g9Gvnx3Ym33fz/HpLRYxiS0wHNr+m/MBC8B647Xt608vCDEvhl9c6Mw==", - "dev": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/istanbul-lib-instrument": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-6.0.1.tgz", - "integrity": "sha512-EAMEJBsYuyyztxMxW3g7ugGPkrZsV57v0Hmv3mm1uQsmB+QnZuepg731CRaIgeUVSdmsTngOkSnauNF8p7FIhA==", - "dev": true, - "dependencies": { - "@babel/core": "^7.12.3", - "@babel/parser": "^7.14.7", - "@istanbuljs/schema": "^0.1.2", - "istanbul-lib-coverage": "^3.2.0", - "semver": "^7.5.4" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/istanbul-lib-instrument/node_modules/lru-cache": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", - "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", - "dev": true, - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/istanbul-lib-instrument/node_modules/semver": { - "version": "7.5.4", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", - "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", - "dev": true, - "dependencies": { - "lru-cache": "^6.0.0" - }, - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/istanbul-lib-instrument/node_modules/yallist": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", - "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", - "dev": true - }, - "node_modules/istanbul-lib-report": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz", - "integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==", - "dev": true, - "dependencies": { - "istanbul-lib-coverage": "^3.0.0", - "make-dir": "^4.0.0", - "supports-color": "^7.1.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/istanbul-lib-source-maps": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-4.0.1.tgz", - "integrity": "sha512-n3s8EwkdFIJCG3BPKBYvskgXGoy88ARzvegkitk60NxRdwltLOTaH7CUiMRXvwYorl0Q712iEjcWB+fK/MrWVw==", - "dev": true, - "dependencies": { - "debug": "^4.1.1", - "istanbul-lib-coverage": "^3.0.0", - "source-map": "^0.6.1" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/istanbul-reports": { - "version": "3.1.6", - "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.1.6.tgz", - "integrity": "sha512-TLgnMkKg3iTDsQ9PbPTdpfAK2DzjF9mqUG7RMgcQl8oFjad8ob4laGxv5XV5U9MAfx8D6tSJiUyuAwzLicaxlg==", - "dev": true, - "dependencies": { - "html-escaper": "^2.0.0", - "istanbul-lib-report": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/jest": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest/-/jest-29.7.0.tgz", - "integrity": "sha512-NIy3oAFp9shda19hy4HK0HRTWKtPJmGdnvywu01nOqNC2vZg+Z+fvJDxpMQA88eb2I9EcafcdjYgsDthnYTvGw==", - "dev": true, - "dependencies": { - "@jest/core": "^29.7.0", - "@jest/types": "^29.6.3", - "import-local": "^3.0.2", - "jest-cli": "^29.7.0" - }, - "bin": { - "jest": "bin/jest.js" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - }, - "peerDependencies": { - "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" - }, - "peerDependenciesMeta": { - "node-notifier": { - "optional": true - } - } - }, - "node_modules/jest-changed-files": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-changed-files/-/jest-changed-files-29.7.0.tgz", - "integrity": "sha512-fEArFiwf1BpQ+4bXSprcDc3/x4HSzL4al2tozwVpDFpsxALjLYdyiIK4e5Vz66GQJIbXJ82+35PtysofptNX2w==", - "dev": true, - "dependencies": { - "execa": "^5.0.0", - "jest-util": "^29.7.0", - "p-limit": "^3.1.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-circus": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-circus/-/jest-circus-29.7.0.tgz", - "integrity": "sha512-3E1nCMgipcTkCocFwM90XXQab9bS+GMsjdpmPrlelaxwD93Ad8iVEjX/vvHPdLPnFf+L40u+5+iutRdA1N9myw==", - "dev": true, - "dependencies": { - "@jest/environment": "^29.7.0", - "@jest/expect": "^29.7.0", - "@jest/test-result": "^29.7.0", - "@jest/types": "^29.6.3", - "@types/node": "*", - "chalk": "^4.0.0", - "co": "^4.6.0", - "dedent": "^1.0.0", - "is-generator-fn": "^2.0.0", - "jest-each": "^29.7.0", - "jest-matcher-utils": "^29.7.0", - "jest-message-util": "^29.7.0", - "jest-runtime": "^29.7.0", - "jest-snapshot": "^29.7.0", - "jest-util": "^29.7.0", - "p-limit": "^3.1.0", - "pretty-format": "^29.7.0", - "pure-rand": "^6.0.0", - "slash": "^3.0.0", - "stack-utils": "^2.0.3" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-cli": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-cli/-/jest-cli-29.7.0.tgz", - "integrity": "sha512-OVVobw2IubN/GSYsxETi+gOe7Ka59EFMR/twOU3Jb2GnKKeMGJB5SGUUrEz3SFVmJASUdZUzy83sLNNQ2gZslg==", - "dev": true, - "dependencies": { - "@jest/core": "^29.7.0", - "@jest/test-result": "^29.7.0", - "@jest/types": "^29.6.3", - "chalk": "^4.0.0", - "create-jest": "^29.7.0", - "exit": "^0.1.2", - "import-local": "^3.0.2", - "jest-config": "^29.7.0", - "jest-util": "^29.7.0", - "jest-validate": "^29.7.0", - "yargs": "^17.3.1" - }, - "bin": { - "jest": "bin/jest.js" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - }, - "peerDependencies": { - "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" - }, - "peerDependenciesMeta": { - "node-notifier": { - "optional": true - } - } - }, - "node_modules/jest-config": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-config/-/jest-config-29.7.0.tgz", - "integrity": "sha512-uXbpfeQ7R6TZBqI3/TxCU4q4ttk3u0PJeC+E0zbfSoSjq6bJ7buBPxzQPL0ifrkY4DNu4JUdk0ImlBUYi840eQ==", - "dev": true, - "dependencies": { - "@babel/core": "^7.11.6", - "@jest/test-sequencer": "^29.7.0", - "@jest/types": "^29.6.3", - "babel-jest": "^29.7.0", - "chalk": "^4.0.0", - "ci-info": "^3.2.0", - "deepmerge": "^4.2.2", - "glob": "^7.1.3", - "graceful-fs": "^4.2.9", - "jest-circus": "^29.7.0", - "jest-environment-node": "^29.7.0", - "jest-get-type": "^29.6.3", - "jest-regex-util": "^29.6.3", - "jest-resolve": "^29.7.0", - "jest-runner": "^29.7.0", - "jest-util": "^29.7.0", - "jest-validate": "^29.7.0", - "micromatch": "^4.0.4", - "parse-json": "^5.2.0", - "pretty-format": "^29.7.0", - "slash": "^3.0.0", - "strip-json-comments": "^3.1.1" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - }, - "peerDependencies": { - "@types/node": "*", - "ts-node": ">=9.0.0" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - }, - "ts-node": { - "optional": true - } - } - }, - "node_modules/jest-diff": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-29.7.0.tgz", - "integrity": "sha512-LMIgiIrhigmPrs03JHpxUh2yISK3vLFPkAodPeo0+BuF7wA2FoQbkEg1u8gBYBThncu7e1oEDUfIXVuTqLRUjw==", - "dev": true, - "dependencies": { - "chalk": "^4.0.0", - "diff-sequences": "^29.6.3", - "jest-get-type": "^29.6.3", - "pretty-format": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-docblock": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-docblock/-/jest-docblock-29.7.0.tgz", - "integrity": "sha512-q617Auw3A612guyaFgsbFeYpNP5t2aoUNLwBUbc/0kD1R4t9ixDbyFTHd1nok4epoVFpr7PmeWHrhvuV3XaJ4g==", - "dev": true, - "dependencies": { - "detect-newline": "^3.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-each": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-each/-/jest-each-29.7.0.tgz", - "integrity": "sha512-gns+Er14+ZrEoC5fhOfYCY1LOHHr0TI+rQUHZS8Ttw2l7gl+80eHc/gFf2Ktkw0+SIACDTeWvpFcv3B04VembQ==", - "dev": true, - "dependencies": { - "@jest/types": "^29.6.3", - "chalk": "^4.0.0", - "jest-get-type": "^29.6.3", - "jest-util": "^29.7.0", - "pretty-format": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-environment-jsdom": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-environment-jsdom/-/jest-environment-jsdom-29.7.0.tgz", - "integrity": "sha512-k9iQbsf9OyOfdzWH8HDmrRT0gSIcX+FLNW7IQq94tFX0gynPwqDTW0Ho6iMVNjGz/nb+l/vW3dWM2bbLLpkbXA==", - "dev": true, - "dependencies": { - "@jest/environment": "^29.7.0", - "@jest/fake-timers": "^29.7.0", - "@jest/types": "^29.6.3", - "@types/jsdom": "^20.0.0", - "@types/node": "*", - "jest-mock": "^29.7.0", - "jest-util": "^29.7.0", - "jsdom": "^20.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - }, - "peerDependencies": { - "canvas": "^2.5.0" - }, - "peerDependenciesMeta": { - "canvas": { - "optional": true - } - } - }, - "node_modules/jest-environment-node": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-environment-node/-/jest-environment-node-29.7.0.tgz", - "integrity": "sha512-DOSwCRqXirTOyheM+4d5YZOrWcdu0LNZ87ewUoywbcb2XR4wKgqiG8vNeYwhjFMbEkfju7wx2GYH0P2gevGvFw==", - "dev": true, - "dependencies": { - "@jest/environment": "^29.7.0", - "@jest/fake-timers": "^29.7.0", - "@jest/types": "^29.6.3", - "@types/node": "*", - "jest-mock": "^29.7.0", - "jest-util": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-get-type": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-29.6.3.tgz", - "integrity": "sha512-zrteXnqYxfQh7l5FHyL38jL39di8H8rHoecLH3JNxH3BwOrBsNeabdap5e0I23lD4HHI8W5VFBZqG4Eaq5LNcw==", - "dev": true, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-haste-map": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-haste-map/-/jest-haste-map-29.7.0.tgz", - "integrity": "sha512-fP8u2pyfqx0K1rGn1R9pyE0/KTn+G7PxktWidOBTqFPLYX0b9ksaMFkhK5vrS3DVun09pckLdlx90QthlW7AmA==", - "dev": true, - "dependencies": { - "@jest/types": "^29.6.3", - "@types/graceful-fs": "^4.1.3", - "@types/node": "*", - "anymatch": "^3.0.3", - "fb-watchman": "^2.0.0", - "graceful-fs": "^4.2.9", - "jest-regex-util": "^29.6.3", - "jest-util": "^29.7.0", - "jest-worker": "^29.7.0", - "micromatch": "^4.0.4", - "walker": "^1.0.8" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - }, - "optionalDependencies": { - "fsevents": "^2.3.2" - } - }, - "node_modules/jest-leak-detector": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-leak-detector/-/jest-leak-detector-29.7.0.tgz", - "integrity": "sha512-kYA8IJcSYtST2BY9I+SMC32nDpBT3J2NvWJx8+JCuCdl/CR1I4EKUJROiP8XtCcxqgTTBGJNdbB1A8XRKbTetw==", - "dev": true, - "dependencies": { - "jest-get-type": "^29.6.3", - "pretty-format": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-matcher-utils": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-29.7.0.tgz", - "integrity": "sha512-sBkD+Xi9DtcChsI3L3u0+N0opgPYnCRPtGcQYrgXmR+hmt/fYfWAL0xRXYU8eWOdfuLgBe0YCW3AFtnRLagq/g==", - "dev": true, - "dependencies": { - "chalk": "^4.0.0", - "jest-diff": "^29.7.0", - "jest-get-type": "^29.6.3", - "pretty-format": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-message-util": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-29.7.0.tgz", - "integrity": "sha512-GBEV4GRADeP+qtB2+6u61stea8mGcOT4mCtrYISZwfu9/ISHFJ/5zOMXYbpBE9RsS5+Gb63DW4FgmnKJ79Kf6w==", - "dev": true, - "dependencies": { - "@babel/code-frame": "^7.12.13", - "@jest/types": "^29.6.3", - "@types/stack-utils": "^2.0.0", - "chalk": "^4.0.0", - "graceful-fs": "^4.2.9", - "micromatch": "^4.0.4", - "pretty-format": "^29.7.0", - "slash": "^3.0.0", - "stack-utils": "^2.0.3" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-mock": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-mock/-/jest-mock-29.7.0.tgz", - "integrity": "sha512-ITOMZn+UkYS4ZFh83xYAOzWStloNzJFO2s8DWrE4lhtGD+AorgnbkiKERe4wQVBydIGPx059g6riW5Btp6Llnw==", - "dev": true, - "dependencies": { - "@jest/types": "^29.6.3", - "@types/node": "*", - "jest-util": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-pnp-resolver": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/jest-pnp-resolver/-/jest-pnp-resolver-1.2.3.tgz", - "integrity": "sha512-+3NpwQEnRoIBtx4fyhblQDPgJI0H1IEIkX7ShLUjPGA7TtUTvI1oiKi3SR4oBR0hQhQR80l4WAe5RrXBwWMA8w==", - "dev": true, - "engines": { - "node": ">=6" - }, - "peerDependencies": { - "jest-resolve": "*" - }, - "peerDependenciesMeta": { - "jest-resolve": { - "optional": true - } - } - }, - "node_modules/jest-regex-util": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/jest-regex-util/-/jest-regex-util-29.6.3.tgz", - "integrity": "sha512-KJJBsRCyyLNWCNBOvZyRDnAIfUiRJ8v+hOBQYGn8gDyF3UegwiP4gwRR3/SDa42g1YbVycTidUF3rKjyLFDWbg==", - "dev": true, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-resolve": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-resolve/-/jest-resolve-29.7.0.tgz", - "integrity": "sha512-IOVhZSrg+UvVAshDSDtHyFCCBUl/Q3AAJv8iZ6ZjnZ74xzvwuzLXid9IIIPgTnY62SJjfuupMKZsZQRsCvxEgA==", - "dev": true, - "dependencies": { - "chalk": "^4.0.0", - "graceful-fs": "^4.2.9", - "jest-haste-map": "^29.7.0", - "jest-pnp-resolver": "^1.2.2", - "jest-util": "^29.7.0", - "jest-validate": "^29.7.0", - "resolve": "^1.20.0", - "resolve.exports": "^2.0.0", - "slash": "^3.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-resolve-dependencies": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-resolve-dependencies/-/jest-resolve-dependencies-29.7.0.tgz", - "integrity": "sha512-un0zD/6qxJ+S0et7WxeI3H5XSe9lTBBR7bOHCHXkKR6luG5mwDDlIzVQ0V5cZCuoTgEdcdwzTghYkTWfubi+nA==", - "dev": true, - "dependencies": { - "jest-regex-util": "^29.6.3", - "jest-snapshot": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-runner": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-runner/-/jest-runner-29.7.0.tgz", - "integrity": "sha512-fsc4N6cPCAahybGBfTRcq5wFR6fpLznMg47sY5aDpsoejOcVYFb07AHuSnR0liMcPTgBsA3ZJL6kFOjPdoNipQ==", - "dev": true, - "dependencies": { - "@jest/console": "^29.7.0", - "@jest/environment": "^29.7.0", - "@jest/test-result": "^29.7.0", - "@jest/transform": "^29.7.0", - "@jest/types": "^29.6.3", - "@types/node": "*", - "chalk": "^4.0.0", - "emittery": "^0.13.1", - "graceful-fs": "^4.2.9", - "jest-docblock": "^29.7.0", - "jest-environment-node": "^29.7.0", - "jest-haste-map": "^29.7.0", - "jest-leak-detector": "^29.7.0", - "jest-message-util": "^29.7.0", - "jest-resolve": "^29.7.0", - "jest-runtime": "^29.7.0", - "jest-util": "^29.7.0", - "jest-watcher": "^29.7.0", - "jest-worker": "^29.7.0", - "p-limit": "^3.1.0", - "source-map-support": "0.5.13" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-runtime": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-runtime/-/jest-runtime-29.7.0.tgz", - "integrity": "sha512-gUnLjgwdGqW7B4LvOIkbKs9WGbn+QLqRQQ9juC6HndeDiezIwhDP+mhMwHWCEcfQ5RUXa6OPnFF8BJh5xegwwQ==", - "dev": true, - "dependencies": { - "@jest/environment": "^29.7.0", - "@jest/fake-timers": "^29.7.0", - "@jest/globals": "^29.7.0", - "@jest/source-map": "^29.6.3", - "@jest/test-result": "^29.7.0", - "@jest/transform": "^29.7.0", - "@jest/types": "^29.6.3", - "@types/node": "*", - "chalk": "^4.0.0", - "cjs-module-lexer": "^1.0.0", - "collect-v8-coverage": "^1.0.0", - "glob": "^7.1.3", - "graceful-fs": "^4.2.9", - "jest-haste-map": "^29.7.0", - "jest-message-util": "^29.7.0", - "jest-mock": "^29.7.0", - "jest-regex-util": "^29.6.3", - "jest-resolve": "^29.7.0", - "jest-snapshot": "^29.7.0", - "jest-util": "^29.7.0", - "slash": "^3.0.0", - "strip-bom": "^4.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-snapshot": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-snapshot/-/jest-snapshot-29.7.0.tgz", - "integrity": "sha512-Rm0BMWtxBcioHr1/OX5YCP8Uov4riHvKPknOGs804Zg9JGZgmIBkbtlxJC/7Z4msKYVbIJtfU+tKb8xlYNfdkw==", - "dev": true, - "dependencies": { - "@babel/core": "^7.11.6", - "@babel/generator": "^7.7.2", - "@babel/plugin-syntax-jsx": "^7.7.2", - "@babel/plugin-syntax-typescript": "^7.7.2", - "@babel/types": "^7.3.3", - "@jest/expect-utils": "^29.7.0", - "@jest/transform": "^29.7.0", - "@jest/types": "^29.6.3", - "babel-preset-current-node-syntax": "^1.0.0", - "chalk": "^4.0.0", - "expect": "^29.7.0", - "graceful-fs": "^4.2.9", - "jest-diff": "^29.7.0", - "jest-get-type": "^29.6.3", - "jest-matcher-utils": "^29.7.0", - "jest-message-util": "^29.7.0", - "jest-util": "^29.7.0", - "natural-compare": "^1.4.0", - "pretty-format": "^29.7.0", - "semver": "^7.5.3" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-snapshot/node_modules/lru-cache": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", - "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", - "dev": true, - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/jest-snapshot/node_modules/semver": { - "version": "7.5.4", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", - "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", - "dev": true, - "dependencies": { - "lru-cache": "^6.0.0" - }, - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/jest-snapshot/node_modules/yallist": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", - "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", - "dev": true - }, - "node_modules/jest-util": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-29.7.0.tgz", - "integrity": "sha512-z6EbKajIpqGKU56y5KBUgy1dt1ihhQJgWzUlZHArA/+X2ad7Cb5iF+AK1EWVL/Bo7Rz9uurpqw6SiBCefUbCGA==", - "dev": true, - "dependencies": { - "@jest/types": "^29.6.3", - "@types/node": "*", - "chalk": "^4.0.0", - "ci-info": "^3.2.0", - "graceful-fs": "^4.2.9", - "picomatch": "^2.2.3" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-validate": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-validate/-/jest-validate-29.7.0.tgz", - "integrity": "sha512-ZB7wHqaRGVw/9hST/OuFUReG7M8vKeq0/J2egIGLdvjHCmYqGARhzXmtgi+gVeZ5uXFF219aOc3Ls2yLg27tkw==", - "dev": true, - "dependencies": { - "@jest/types": "^29.6.3", - "camelcase": "^6.2.0", - "chalk": "^4.0.0", - "jest-get-type": "^29.6.3", - "leven": "^3.1.0", - "pretty-format": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-validate/node_modules/camelcase": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz", - "integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==", - "dev": true, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/jest-watcher": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-watcher/-/jest-watcher-29.7.0.tgz", - "integrity": "sha512-49Fg7WXkU3Vl2h6LbLtMQ/HyB6rXSIX7SqvBLQmssRBGN9I0PNvPmAmCWSOY6SOvrjhI/F7/bGAv9RtnsPA03g==", - "dev": true, - "dependencies": { - "@jest/test-result": "^29.7.0", - "@jest/types": "^29.6.3", - "@types/node": "*", - "ansi-escapes": "^4.2.1", - "chalk": "^4.0.0", - "emittery": "^0.13.1", - "jest-util": "^29.7.0", - "string-length": "^4.0.1" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-worker": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-29.7.0.tgz", - "integrity": "sha512-eIz2msL/EzL9UFTFFx7jBTkeZfku0yUAyZZZmJ93H2TYEiroIx2PQjEXcwYtYl8zXCxb+PAmA2hLIt/6ZEkPHw==", - "dev": true, - "dependencies": { - "@types/node": "*", - "jest-util": "^29.7.0", - "merge-stream": "^2.0.0", - "supports-color": "^8.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-worker/node_modules/supports-color": { - "version": "8.1.1", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", - "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", - "dev": true, - "dependencies": { - "has-flag": "^4.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/supports-color?sponsor=1" - } - }, - "node_modules/js-tokens": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", - "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", - "dev": true - }, - "node_modules/js-yaml": { - "version": "3.14.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz", - "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", - "dev": true, - "dependencies": { - "argparse": "^1.0.7", - "esprima": "^4.0.0" - }, - "bin": { - "js-yaml": "bin/js-yaml.js" - } - }, - "node_modules/jsdom": { - "version": "20.0.3", - "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-20.0.3.tgz", - "integrity": "sha512-SYhBvTh89tTfCD/CRdSOm13mOBa42iTaTyfyEWBdKcGdPxPtLFBXuHR8XHb33YNYaP+lLbmSvBTsnoesCNJEsQ==", - "dev": true, - "dependencies": { - "abab": "^2.0.6", - "acorn": "^8.8.1", - "acorn-globals": "^7.0.0", - "cssom": "^0.5.0", - "cssstyle": "^2.3.0", - "data-urls": "^3.0.2", - "decimal.js": "^10.4.2", - "domexception": "^4.0.0", - "escodegen": "^2.0.0", - "form-data": "^4.0.0", - "html-encoding-sniffer": "^3.0.0", - "http-proxy-agent": "^5.0.0", - "https-proxy-agent": "^5.0.1", - "is-potential-custom-element-name": "^1.0.1", - "nwsapi": "^2.2.2", - "parse5": "^7.1.1", - "saxes": "^6.0.0", - "symbol-tree": "^3.2.4", - "tough-cookie": "^4.1.2", - "w3c-xmlserializer": "^4.0.0", - "webidl-conversions": "^7.0.0", - "whatwg-encoding": "^2.0.0", - "whatwg-mimetype": "^3.0.0", - "whatwg-url": "^11.0.0", - "ws": "^8.11.0", - "xml-name-validator": "^4.0.0" - }, - "engines": { - "node": ">=14" - }, - "peerDependencies": { - "canvas": "^2.5.0" - }, - "peerDependenciesMeta": { - "canvas": { - "optional": true - } - } - }, - "node_modules/jsesc": { - "version": "2.5.2", - "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz", - "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==", - "dev": true, - "bin": { - "jsesc": "bin/jsesc" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/json-parse-even-better-errors": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", - "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", - "dev": true - }, - "node_modules/json5": { - "version": "2.2.3", - "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", - "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", - "dev": true, - "bin": { - "json5": "lib/cli.js" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/kleur": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/kleur/-/kleur-3.0.3.tgz", - "integrity": "sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==", - "dev": true, - "engines": { - "node": ">=6" - } - }, - "node_modules/leven": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/leven/-/leven-3.1.0.tgz", - "integrity": "sha512-qsda+H8jTaUaN/x5vzW2rzc+8Rw4TAQ/4KjB46IwK5VH+IlVeeeje/EoZRpiXvIqjFgK84QffqPztGI3VBLG1A==", - "dev": true, - "engines": { - "node": ">=6" - } - }, - "node_modules/lines-and-columns": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", - "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", - "dev": true - }, - "node_modules/locate-path": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", - "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", - "dev": true, - "dependencies": { - "p-locate": "^4.1.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/lodash.debounce": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/lodash.debounce/-/lodash.debounce-4.0.8.tgz", - "integrity": "sha512-FT1yDzDYEoYWhnSGnpE/4Kj1fLZkDFyqRb7fNt6FdYOSxlUWAtp42Eh6Wb0rGIv/m9Bgo7x4GhQbm5Ys4SG5ow==", - "dev": true - }, - "node_modules/lru-cache": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", - "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", - "dev": true, - "dependencies": { - "yallist": "^3.0.2" - } - }, - "node_modules/make-dir": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz", - "integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==", - "dev": true, - "dependencies": { - "semver": "^7.5.3" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/make-dir/node_modules/lru-cache": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", - "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", - "dev": true, - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/make-dir/node_modules/semver": { - "version": "7.5.4", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", - "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", - "dev": true, - "dependencies": { - "lru-cache": "^6.0.0" - }, - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/make-dir/node_modules/yallist": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", - "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", - "dev": true - }, - "node_modules/makeerror": { - "version": "1.0.12", - "resolved": "https://registry.npmjs.org/makeerror/-/makeerror-1.0.12.tgz", - "integrity": "sha512-JmqCvUhmt43madlpFzG4BQzG2Z3m6tvQDNKdClZnO3VbIudJYmxsT0FNJMeiB2+JTSlTQTSbU8QdesVmwJcmLg==", - "dev": true, - "dependencies": { - "tmpl": "1.0.5" - } - }, - "node_modules/merge-stream": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", - "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", - "dev": true - }, - "node_modules/micromatch": { - "version": "4.0.5", - "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.5.tgz", - "integrity": "sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA==", - "dev": true, - "dependencies": { - "braces": "^3.0.2", - "picomatch": "^2.3.1" - }, - "engines": { - "node": ">=8.6" - } - }, - "node_modules/mime-db": { - "version": "1.52.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", - "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", - "dev": true, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/mime-types": { - "version": "2.1.35", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", - "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", - "dev": true, - "dependencies": { - "mime-db": "1.52.0" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/mimic-fn": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", - "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", - "dev": true, - "engines": { - "node": ">=6" - } - }, - "node_modules/minimatch": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", - "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", - "dev": true, - "dependencies": { - "brace-expansion": "^1.1.7" - }, - "engines": { - "node": "*" - } - }, - "node_modules/ms": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", - "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", - "dev": true - }, - "node_modules/natural-compare": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", - "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", - "dev": true - }, - "node_modules/node-int64": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz", - "integrity": "sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw==", - "dev": true - }, - "node_modules/node-releases": { - "version": "2.0.13", - "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.13.tgz", - "integrity": "sha512-uYr7J37ae/ORWdZeQ1xxMJe3NtdmqMC/JZK+geofDrkLUApKRHPd18/TxtBOJ4A0/+uUIliorNrfYV6s1b02eQ==", - "dev": true - }, - "node_modules/normalize-path": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", - "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", - "dev": true, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/npm-run-path": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz", - "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==", - "dev": true, - "dependencies": { - "path-key": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/nwsapi": { - "version": "2.2.7", - "resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.7.tgz", - "integrity": "sha512-ub5E4+FBPKwAZx0UwIQOjYWGHTEq5sPqHQNRN8Z9e4A7u3Tj1weLJsL59yH9vmvqEtBHaOmT6cYQKIZOxp35FQ==", - "dev": true - }, - "node_modules/once": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", - "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", - "dev": true, - "dependencies": { - "wrappy": "1" - } - }, - "node_modules/onetime": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", - "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", - "dev": true, - "dependencies": { - "mimic-fn": "^2.1.0" - }, - "engines": { - "node": ">=6" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/p-limit": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", - "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", - "dev": true, - "dependencies": { - "yocto-queue": "^0.1.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/p-locate": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", - "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", - "dev": true, - "dependencies": { - "p-limit": "^2.2.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/p-locate/node_modules/p-limit": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", - "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", - "dev": true, - "dependencies": { - "p-try": "^2.0.0" - }, - "engines": { - "node": ">=6" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/p-try": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", - "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", - "dev": true, - "engines": { - "node": ">=6" - } - }, - "node_modules/parse-json": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", - "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", - "dev": true, - "dependencies": { - "@babel/code-frame": "^7.0.0", - "error-ex": "^1.3.1", - "json-parse-even-better-errors": "^2.3.0", - "lines-and-columns": "^1.1.6" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/parse5": { - "version": "7.1.2", - "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.1.2.tgz", - "integrity": "sha512-Czj1WaSVpaoj0wbhMzLmWD69anp2WH7FXMB9n1Sy8/ZFF9jolSQVMu1Ij5WIyGmcBmhk7EOndpO4mIpihVqAXw==", - "dev": true, - "dependencies": { - "entities": "^4.4.0" - }, - "funding": { - "url": "https://github.com/inikulin/parse5?sponsor=1" - } - }, - "node_modules/path-exists": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", - "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", - "dev": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/path-is-absolute": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", - "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", - "dev": true, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/path-key": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", - "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", - "dev": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/path-parse": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", - "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", - "dev": true - }, - "node_modules/picocolors": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.0.tgz", - "integrity": "sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==", - "dev": true - }, - "node_modules/picomatch": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", - "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", - "dev": true, - "engines": { - "node": ">=8.6" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, - "node_modules/pirates": { - "version": "4.0.6", - "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.6.tgz", - "integrity": "sha512-saLsH7WeYYPiD25LDuLRRY/i+6HaPYr6G1OUlN39otzkSTxKnubR9RTxS3/Kk50s1g2JTgFwWQDQyplC5/SHZg==", - "dev": true, - "engines": { - "node": ">= 6" - } - }, - "node_modules/pkg-dir": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz", - "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==", - "dev": true, - "dependencies": { - "find-up": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/pretty-format": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.7.0.tgz", - "integrity": "sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ==", - "dev": true, - "dependencies": { - "@jest/schemas": "^29.6.3", - "ansi-styles": "^5.0.0", - "react-is": "^18.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/pretty-format/node_modules/ansi-styles": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", - "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", - "dev": true, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, - "node_modules/prompts": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/prompts/-/prompts-2.4.2.tgz", - "integrity": "sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q==", - "dev": true, - "dependencies": { - "kleur": "^3.0.3", - "sisteransi": "^1.0.5" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/psl": { - "version": "1.9.0", - "resolved": "https://registry.npmjs.org/psl/-/psl-1.9.0.tgz", - "integrity": "sha512-E/ZsdU4HLs/68gYzgGTkMicWTLPdAftJLfJFlLUAAKZGkStNU72sZjT66SnMDVOfOWY/YAoiD7Jxa9iHvngcag==", - "dev": true - }, - "node_modules/punycode": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.0.tgz", - "integrity": "sha512-rRV+zQD8tVFys26lAGR9WUuS4iUAngJScM+ZRSKtvl5tKeZ2t5bvdNFdNHBW9FWR4guGHlgmsZ1G7BSm2wTbuA==", - "dev": true, - "engines": { - "node": ">=6" - } - }, - "node_modules/pure-rand": { - "version": "6.0.4", - "resolved": "https://registry.npmjs.org/pure-rand/-/pure-rand-6.0.4.tgz", - "integrity": "sha512-LA0Y9kxMYv47GIPJy6MI84fqTd2HmYZI83W/kM/SkKfDlajnZYfmXFTxkbY+xSBPkLJxltMa9hIkmdc29eguMA==", - "dev": true, - "funding": [ - { - "type": "individual", - "url": "https://github.com/sponsors/dubzzz" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fast-check" - } - ] - }, - "node_modules/querystringify": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.2.0.tgz", - "integrity": "sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ==", - "dev": true - }, - "node_modules/react-is": { - "version": "18.2.0", - "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.2.0.tgz", - "integrity": "sha512-xWGDIW6x921xtzPkhiULtthJHoJvBbF3q26fzloPCK0hsvxtPVelvftw3zjbHWSkR2km9Z+4uxbDDK/6Zw9B8w==", - "dev": true - }, - "node_modules/regenerate": { - "version": "1.4.2", - "resolved": "https://registry.npmjs.org/regenerate/-/regenerate-1.4.2.tgz", - "integrity": "sha512-zrceR/XhGYU/d/opr2EKO7aRHUeiBI8qjtfHqADTwZd6Szfy16la6kqD0MIUs5z5hx6AaKa+PixpPrR289+I0A==", - "dev": true - }, - "node_modules/regenerate-unicode-properties": { - "version": "10.1.1", - "resolved": "https://registry.npmjs.org/regenerate-unicode-properties/-/regenerate-unicode-properties-10.1.1.tgz", - "integrity": "sha512-X007RyZLsCJVVrjgEFVpLUTZwyOZk3oiL75ZcuYjlIWd6rNJtOjkBwQc5AsRrpbKVkxN6sklw/k/9m2jJYOf8Q==", - "dev": true, - "dependencies": { - "regenerate": "^1.4.2" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/regenerator-runtime": { - "version": "0.14.0", - "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.14.0.tgz", - "integrity": "sha512-srw17NI0TUWHuGa5CFGGmhfNIeja30WMBfbslPNhf6JrqQlLN5gcrvig1oqPxiVaXb0oW0XRKtH6Nngs5lKCIA==", - "dev": true - }, - "node_modules/regenerator-transform": { - "version": "0.15.2", - "resolved": "https://registry.npmjs.org/regenerator-transform/-/regenerator-transform-0.15.2.tgz", - "integrity": "sha512-hfMp2BoF0qOk3uc5V20ALGDS2ddjQaLrdl7xrGXvAIow7qeWRM2VA2HuCHkUKk9slq3VwEwLNK3DFBqDfPGYtg==", - "dev": true, - "dependencies": { - "@babel/runtime": "^7.8.4" - } - }, - "node_modules/regexpu-core": { - "version": "5.3.2", - "resolved": "https://registry.npmjs.org/regexpu-core/-/regexpu-core-5.3.2.tgz", - "integrity": "sha512-RAM5FlZz+Lhmo7db9L298p2vHP5ZywrVXmVXpmAD9GuL5MPH6t9ROw1iA/wfHkQ76Qe7AaPF0nGuim96/IrQMQ==", - "dev": true, - "dependencies": { - "@babel/regjsgen": "^0.8.0", - "regenerate": "^1.4.2", - "regenerate-unicode-properties": "^10.1.0", - "regjsparser": "^0.9.1", - "unicode-match-property-ecmascript": "^2.0.0", - "unicode-match-property-value-ecmascript": "^2.1.0" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/regjsparser": { - "version": "0.9.1", - "resolved": "https://registry.npmjs.org/regjsparser/-/regjsparser-0.9.1.tgz", - "integrity": "sha512-dQUtn90WanSNl+7mQKcXAgZxvUe7Z0SqXlgzv0za4LwiUhyzBC58yQO3liFoUgu8GiJVInAhJjkj1N0EtQ5nkQ==", - "dev": true, - "dependencies": { - "jsesc": "~0.5.0" - }, - "bin": { - "regjsparser": "bin/parser" - } - }, - "node_modules/regjsparser/node_modules/jsesc": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-0.5.0.tgz", - "integrity": "sha512-uZz5UnB7u4T9LvwmFqXii7pZSouaRPorGs5who1Ip7VO0wxanFvBL7GkM6dTHlgX+jhBApRetaWpnDabOeTcnA==", - "dev": true, - "bin": { - "jsesc": "bin/jsesc" - } - }, - "node_modules/require-directory": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", - "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", - "dev": true, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/requires-port": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", - "integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==", - "dev": true - }, - "node_modules/resolve": { - "version": "1.22.6", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.6.tgz", - "integrity": "sha512-njhxM7mV12JfufShqGy3Rz8j11RPdLy4xi15UurGJeoHLfJpVXKdh3ueuOqbYUcDZnffr6X739JBo5LzyahEsw==", - "dev": true, - "dependencies": { - "is-core-module": "^2.13.0", - "path-parse": "^1.0.7", - "supports-preserve-symlinks-flag": "^1.0.0" - }, - "bin": { - "resolve": "bin/resolve" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/resolve-cwd": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/resolve-cwd/-/resolve-cwd-3.0.0.tgz", - "integrity": "sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg==", - "dev": true, - "dependencies": { - "resolve-from": "^5.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/resolve-from": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", - "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", - "dev": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/resolve.exports": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/resolve.exports/-/resolve.exports-2.0.2.tgz", - "integrity": "sha512-X2UW6Nw3n/aMgDVy+0rSqgHlv39WZAlZrXCdnbyEiKm17DSqHX4MmQMaST3FbeWR5FTuRcUwYAziZajji0Y7mg==", - "dev": true, - "engines": { - "node": ">=10" - } - }, - "node_modules/safer-buffer": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", - "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", - "dev": true - }, - "node_modules/saxes": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", - "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==", - "dev": true, - "dependencies": { - "xmlchars": "^2.2.0" - }, - "engines": { - "node": ">=v12.22.7" - } - }, - "node_modules/semver": { - "version": "6.3.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", - "dev": true, - "bin": { - "semver": "bin/semver.js" - } - }, - "node_modules/shebang-command": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", - "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", - "dev": true, - "dependencies": { - "shebang-regex": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/shebang-regex": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", - "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", - "dev": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/signal-exit": { - "version": "3.0.7", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", - "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", - "dev": true - }, - "node_modules/sisteransi": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz", - "integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==", - "dev": true - }, - "node_modules/slash": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", - "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", - "dev": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/source-map": { - "version": "0.6.1", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", - "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", - "dev": true, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/source-map-support": { - "version": "0.5.13", - "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.13.tgz", - "integrity": "sha512-SHSKFHadjVA5oR4PPqhtAVdcBWwRYVd6g6cAXnIbRiIwc2EhPrTuKUBdSLvlEKyIP3GCf89fltvcZiP9MMFA1w==", - "dev": true, - "dependencies": { - "buffer-from": "^1.0.0", - "source-map": "^0.6.0" - } - }, - "node_modules/sprintf-js": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", - "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==", - "dev": true - }, - "node_modules/stack-utils": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.6.tgz", - "integrity": "sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ==", - "dev": true, - "dependencies": { - "escape-string-regexp": "^2.0.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/string-length": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/string-length/-/string-length-4.0.2.tgz", - "integrity": "sha512-+l6rNN5fYHNhZZy41RXsYptCjA2Igmq4EG7kZAYFQI1E1VTXarr6ZPXBg6eq7Y6eK4FEhY6AJlyuFIb/v/S0VQ==", - "dev": true, - "dependencies": { - "char-regex": "^1.0.2", - "strip-ansi": "^6.0.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/string-width": { - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", - "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "dev": true, - "dependencies": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dev": true, - "dependencies": { - "ansi-regex": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/strip-bom": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-4.0.0.tgz", - "integrity": "sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w==", - "dev": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/strip-final-newline": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz", - "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==", - "dev": true, - "engines": { - "node": ">=6" - } - }, - "node_modules/strip-json-comments": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", - "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", - "dev": true, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/supports-color": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", - "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", - "dev": true, - "dependencies": { - "has-flag": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/supports-preserve-symlinks-flag": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", - "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", - "dev": true, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/symbol-tree": { - "version": "3.2.4", - "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", - "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", - "dev": true - }, - "node_modules/test-exclude": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-6.0.0.tgz", - "integrity": "sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==", - "dev": true, - "dependencies": { - "@istanbuljs/schema": "^0.1.2", - "glob": "^7.1.4", - "minimatch": "^3.0.4" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/tmpl": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/tmpl/-/tmpl-1.0.5.tgz", - "integrity": "sha512-3f0uOEAQwIqGuWW2MVzYg8fV/QNnc/IpuJNG837rLuczAaLVHslWHZQj4IGiEl5Hs3kkbhwL9Ab7Hrsmuj+Smw==", - "dev": true - }, - "node_modules/to-fast-properties": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz", - "integrity": "sha512-/OaKK0xYrs3DmxRYqL/yDc+FxFUVYhDlXMhRmv3z915w2HF1tnN1omB354j8VUGO/hbRzyD6Y3sA7v7GS/ceog==", - "dev": true, - "engines": { - "node": ">=4" - } - }, - "node_modules/to-regex-range": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", - "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", - "dev": true, - "dependencies": { - "is-number": "^7.0.0" - }, - "engines": { - "node": ">=8.0" - } - }, - "node_modules/tough-cookie": { - "version": "4.1.3", - "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-4.1.3.tgz", - "integrity": "sha512-aX/y5pVRkfRnfmuX+OdbSdXvPe6ieKX/G2s7e98f4poJHnqH3281gDPm/metm6E/WRamfx7WC4HUqkWHfQHprw==", - "dev": true, - "dependencies": { - "psl": "^1.1.33", - "punycode": "^2.1.1", - "universalify": "^0.2.0", - "url-parse": "^1.5.3" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/tr46": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/tr46/-/tr46-3.0.0.tgz", - "integrity": "sha512-l7FvfAHlcmulp8kr+flpQZmVwtu7nfRV7NZujtN0OqES8EL4O4e0qqzL0DC5gAvx/ZC/9lk6rhcUwYvkBnBnYA==", - "dev": true, - "dependencies": { - "punycode": "^2.1.1" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/tslib": { - "version": "2.6.2", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.6.2.tgz", - "integrity": "sha512-AEYxH93jGFPn/a2iVAwW87VuUIkR1FVUKB77NwMF7nBTDkDrrT/Hpt/IrCJ0QXhW27jTBDcf5ZY7w6RiqTMw2Q==", - "dev": true - }, - "node_modules/type-detect": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", - "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", - "dev": true, - "engines": { - "node": ">=4" - } - }, - "node_modules/type-fest": { - "version": "0.21.3", - "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.21.3.tgz", - "integrity": "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==", - "dev": true, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/unicode-canonical-property-names-ecmascript": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/unicode-canonical-property-names-ecmascript/-/unicode-canonical-property-names-ecmascript-2.0.0.tgz", - "integrity": "sha512-yY5PpDlfVIU5+y/BSCxAJRBIS1Zc2dDG3Ujq+sR0U+JjUevW2JhocOF+soROYDSaAezOzOKuyyixhD6mBknSmQ==", - "dev": true, - "engines": { - "node": ">=4" - } - }, - "node_modules/unicode-match-property-ecmascript": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/unicode-match-property-ecmascript/-/unicode-match-property-ecmascript-2.0.0.tgz", - "integrity": "sha512-5kaZCrbp5mmbz5ulBkDkbY0SsPOjKqVS35VpL9ulMPfSl0J0Xsm+9Evphv9CoIZFwre7aJoa94AY6seMKGVN5Q==", - "dev": true, - "dependencies": { - "unicode-canonical-property-names-ecmascript": "^2.0.0", - "unicode-property-aliases-ecmascript": "^2.0.0" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/unicode-match-property-value-ecmascript": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/unicode-match-property-value-ecmascript/-/unicode-match-property-value-ecmascript-2.1.0.tgz", - "integrity": "sha512-qxkjQt6qjg/mYscYMC0XKRn3Rh0wFPlfxB0xkt9CfyTvpX1Ra0+rAmdX2QyAobptSEvuy4RtpPRui6XkV+8wjA==", - "dev": true, - "engines": { - "node": ">=4" - } - }, - "node_modules/unicode-property-aliases-ecmascript": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/unicode-property-aliases-ecmascript/-/unicode-property-aliases-ecmascript-2.1.0.tgz", - "integrity": "sha512-6t3foTQI9qne+OZoVQB/8x8rk2k1eVy1gRXhV3oFQ5T6R1dqQ1xtin3XqSlx3+ATBkliTaR/hHyJBm+LVPNM8w==", - "dev": true, - "engines": { - "node": ">=4" - } - }, - "node_modules/universalify": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.2.0.tgz", - "integrity": "sha512-CJ1QgKmNg3CwvAv/kOFmtnEN05f0D/cn9QntgNOQlQF9dgvVTHj3t+8JPdjqawCHk7V/KA+fbUqzZ9XWhcqPUg==", - "dev": true, - "engines": { - "node": ">= 4.0.0" - } - }, - "node_modules/update-browserslist-db": { - "version": "1.0.13", - "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.0.13.tgz", - "integrity": "sha512-xebP81SNcPuNpPP3uzeW1NYXxI3rxyJzF3pD6sH4jE7o/IX+WtSpwnVU+qIsDPyk0d3hmFQ7mjqc6AtV604hbg==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/browserslist" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/browserslist" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "dependencies": { - "escalade": "^3.1.1", - "picocolors": "^1.0.0" - }, - "bin": { - "update-browserslist-db": "cli.js" - }, - "peerDependencies": { - "browserslist": ">= 4.21.0" - } - }, - "node_modules/url-parse": { - "version": "1.5.10", - "resolved": "https://registry.npmjs.org/url-parse/-/url-parse-1.5.10.tgz", - "integrity": "sha512-WypcfiRhfeUP9vvF0j6rw0J3hrWrw6iZv3+22h6iRMJ/8z1Tj6XfLP4DsUix5MhMPnXpiHDoKyoZ/bdCkwBCiQ==", - "dev": true, - "dependencies": { - "querystringify": "^2.1.1", - "requires-port": "^1.0.0" - } - }, - "node_modules/v8-to-istanbul": { - "version": "9.1.3", - "resolved": "https://registry.npmjs.org/v8-to-istanbul/-/v8-to-istanbul-9.1.3.tgz", - "integrity": "sha512-9lDD+EVI2fjFsMWXc6dy5JJzBsVTcQ2fVkfBvncZ6xJWG9wtBhOldG+mHkSL0+V1K/xgZz0JDO5UT5hFwHUghg==", - "dev": true, - "dependencies": { - "@jridgewell/trace-mapping": "^0.3.12", - "@types/istanbul-lib-coverage": "^2.0.1", - "convert-source-map": "^2.0.0" - }, - "engines": { - "node": ">=10.12.0" - } - }, - "node_modules/w3c-xmlserializer": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-4.0.0.tgz", - "integrity": "sha512-d+BFHzbiCx6zGfz0HyQ6Rg69w9k19nviJspaj4yNscGjrHu94sVP+aRm75yEbCh+r2/yR+7q6hux9LVtbuTGBw==", - "dev": true, - "dependencies": { - "xml-name-validator": "^4.0.0" - }, - "engines": { - "node": ">=14" - } - }, - "node_modules/walker": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/walker/-/walker-1.0.8.tgz", - "integrity": "sha512-ts/8E8l5b7kY0vlWLewOkDXMmPdLcVV4GmOQLyxuSswIJsweeFZtAsMF7k1Nszz+TYBQrlYRmzOnr398y1JemQ==", - "dev": true, - "dependencies": { - "makeerror": "1.0.12" - } - }, - "node_modules/webidl-conversions": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", - "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==", - "dev": true, - "engines": { - "node": ">=12" - } - }, - "node_modules/whatwg-encoding": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-2.0.0.tgz", - "integrity": "sha512-p41ogyeMUrw3jWclHWTQg1k05DSVXPLcVxRTYsXUk+ZooOCZLcoYgPZ/HL/D/N+uQPOtcp1me1WhBEaX02mhWg==", - "dev": true, - "dependencies": { - "iconv-lite": "0.6.3" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/whatwg-mimetype": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-3.0.0.tgz", - "integrity": "sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==", - "dev": true, - "engines": { - "node": ">=12" - } - }, - "node_modules/whatwg-url": { - "version": "11.0.0", - "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-11.0.0.tgz", - "integrity": "sha512-RKT8HExMpoYx4igMiVMY83lN6UeITKJlBQ+vR/8ZJ8OCdSiN3RwCq+9gH0+Xzj0+5IrM6i4j/6LuvzbZIQgEcQ==", - "dev": true, - "dependencies": { - "tr46": "^3.0.0", - "webidl-conversions": "^7.0.0" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/which": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", - "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", - "dev": true, - "dependencies": { - "isexe": "^2.0.0" - }, - "bin": { - "node-which": "bin/node-which" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/wrap-ansi": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", - "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", - "dev": true, - "dependencies": { - "ansi-styles": "^4.0.0", - "string-width": "^4.1.0", - "strip-ansi": "^6.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/wrap-ansi?sponsor=1" - } - }, - "node_modules/wrappy": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", - "dev": true - }, - "node_modules/write-file-atomic": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-4.0.2.tgz", - "integrity": "sha512-7KxauUdBmSdWnmpaGFg+ppNjKF8uNLry8LyzjauQDOVONfFLNKrKvQOxZ/VuTIcS/gge/YNahf5RIIQWTSarlg==", - "dev": true, - "dependencies": { - "imurmurhash": "^0.1.4", - "signal-exit": "^3.0.7" - }, - "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" - } - }, - "node_modules/ws": { - "version": "8.14.2", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.14.2.tgz", - "integrity": "sha512-wEBG1ftX4jcglPxgFCMJmZ2PLtSbJ2Peg6TmpJFTbe9GZYOQCDPdMYu/Tm0/bGZkw8paZnJY45J4K2PZrLYq8g==", - "dev": true, - "engines": { - "node": ">=10.0.0" - }, - "peerDependencies": { - "bufferutil": "^4.0.1", - "utf-8-validate": ">=5.0.2" - }, - "peerDependenciesMeta": { - "bufferutil": { - "optional": true - }, - "utf-8-validate": { - "optional": true - } - } - }, - "node_modules/xml-name-validator": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-4.0.0.tgz", - "integrity": "sha512-ICP2e+jsHvAj2E2lIHxa5tjXRlKDJo4IdvPvCXbXQGdzSfmSpNVyIKMvoZHjDY9DP0zV17iI85o90vRFXNccRw==", - "dev": true, - "engines": { - "node": ">=12" - } - }, - "node_modules/xmlchars": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", - "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", - "dev": true - }, - "node_modules/y18n": { - "version": "5.0.8", - "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", - "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", - "dev": true, - "engines": { - "node": ">=10" - } - }, - "node_modules/yallist": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", - "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", - "dev": true - }, - "node_modules/yargs": { - "version": "17.7.2", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", - "integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==", - "dev": true, - "dependencies": { - "cliui": "^8.0.1", - "escalade": "^3.1.1", - "get-caller-file": "^2.0.5", - "require-directory": "^2.1.1", - "string-width": "^4.2.3", - "y18n": "^5.0.5", - "yargs-parser": "^21.1.1" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/yargs-parser": { - "version": "21.1.1", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", - "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", - "dev": true, - "engines": { - "node": ">=12" - } - }, - "node_modules/yocto-queue": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", - "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", - "dev": true, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - } - } -} diff --git a/tests-ui/package.json b/tests-ui/package.json deleted file mode 100644 index ae7e49084..000000000 --- a/tests-ui/package.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "comfui-tests", - "version": "1.0.0", - "description": "UI tests", - "main": "index.js", - "scripts": { - "test": "jest", - "test:generate": "node setup.js" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/comfyanonymous/ComfyUI.git" - }, - "keywords": [ - "comfyui", - "test" - ], - "author": "comfyanonymous", - "license": "GPL-3.0", - "bugs": { - "url": "https://github.com/comfyanonymous/ComfyUI/issues" - }, - "homepage": "https://github.com/comfyanonymous/ComfyUI#readme", - "devDependencies": { - "@babel/preset-env": "^7.22.20", - "@types/jest": "^29.5.5", - "babel-plugin-transform-import-meta": "^2.2.1", - "jest": "^29.7.0", - "jest-environment-jsdom": "^29.7.0" - } -} diff --git a/tests-ui/setup.js b/tests-ui/setup.js deleted file mode 100644 index 8bbd9dcdf..000000000 --- a/tests-ui/setup.js +++ /dev/null @@ -1,88 +0,0 @@ -const { spawn } = require("child_process"); -const { resolve } = require("path"); -const { existsSync, mkdirSync, writeFileSync } = require("fs"); -const http = require("http"); - -async function setup() { - // Wait up to 30s for it to start - let success = false; - let child; - for (let i = 0; i < 30; i++) { - try { - await new Promise((res, rej) => { - http - .get("http://127.0.0.1:8188/object_info", (resp) => { - let data = ""; - resp.on("data", (chunk) => { - data += chunk; - }); - resp.on("end", () => { - // Modify the response data to add some checkpoints - const objectInfo = JSON.parse(data); - objectInfo.CheckpointLoaderSimple.input.required.ckpt_name[0] = ["model1.safetensors", "model2.ckpt"]; - objectInfo.VAELoader.input.required.vae_name[0] = ["vae1.safetensors", "vae2.ckpt"]; - - data = JSON.stringify(objectInfo, undefined, "\t"); - - const outDir = resolve("./data"); - if (!existsSync(outDir)) { - mkdirSync(outDir); - } - - const outPath = resolve(outDir, "object_info.json"); - console.log(`Writing ${Object.keys(objectInfo).length} nodes to ${outPath}`); - writeFileSync(outPath, data, { - encoding: "utf8", - }); - res(); - }); - }) - .on("error", rej); - }); - success = true; - break; - } catch (error) { - console.log(i + "/30", error); - if (i === 0) { - // Start the server on first iteration if it fails to connect - console.log("Starting ComfyUI server..."); - - let python = resolve("../../python_embeded/python.exe"); - let args; - let cwd; - if (existsSync(python)) { - args = ["-s", "ComfyUI/main.py"]; - cwd = "../.."; - } else { - python = "python"; - args = ["main.py"]; - cwd = ".."; - } - args.push("--cpu"); - console.log(python, ...args); - child = spawn(python, args, { cwd }); - child.on("error", (err) => { - console.log(`Server error (${err})`); - i = 30; - }); - child.on("exit", (code) => { - if (!success) { - console.log(`Server exited (${code})`); - i = 30; - } - }); - } - await new Promise((r) => { - setTimeout(r, 1000); - }); - } - } - - child?.kill(); - - if (!success) { - throw new Error("Waiting for server failed..."); - } -} - - setup(); \ No newline at end of file diff --git a/tests-ui/tests/extensions.test.js b/tests-ui/tests/extensions.test.js deleted file mode 100644 index 159e5113a..000000000 --- a/tests-ui/tests/extensions.test.js +++ /dev/null @@ -1,196 +0,0 @@ -// @ts-check -/// -const { start } = require("../utils"); -const lg = require("../utils/litegraph"); - -describe("extensions", () => { - beforeEach(() => { - lg.setup(global); - }); - - afterEach(() => { - lg.teardown(global); - }); - - it("calls each extension hook", async () => { - const mockExtension = { - name: "TestExtension", - init: jest.fn(), - setup: jest.fn(), - addCustomNodeDefs: jest.fn(), - getCustomWidgets: jest.fn(), - beforeRegisterNodeDef: jest.fn(), - registerCustomNodes: jest.fn(), - loadedGraphNode: jest.fn(), - nodeCreated: jest.fn(), - beforeConfigureGraph: jest.fn(), - afterConfigureGraph: jest.fn(), - }; - - const { app, ez, graph } = await start({ - async preSetup(app) { - app.registerExtension(mockExtension); - }, - }); - - // Basic initialisation hooks should be called once, with app - expect(mockExtension.init).toHaveBeenCalledTimes(1); - expect(mockExtension.init).toHaveBeenCalledWith(app); - - // Adding custom node defs should be passed the full list of nodes - expect(mockExtension.addCustomNodeDefs).toHaveBeenCalledTimes(1); - expect(mockExtension.addCustomNodeDefs.mock.calls[0][1]).toStrictEqual(app); - const defs = mockExtension.addCustomNodeDefs.mock.calls[0][0]; - expect(defs).toHaveProperty("KSampler"); - expect(defs).toHaveProperty("LoadImage"); - - // Get custom widgets is called once and should return new widget types - expect(mockExtension.getCustomWidgets).toHaveBeenCalledTimes(1); - expect(mockExtension.getCustomWidgets).toHaveBeenCalledWith(app); - - // Before register node def will be called once per node type - const nodeNames = Object.keys(defs); - const nodeCount = nodeNames.length; - expect(mockExtension.beforeRegisterNodeDef).toHaveBeenCalledTimes(nodeCount); - for (let i = 0; i < 10; i++) { - // It should be send the JS class and the original JSON definition - const nodeClass = mockExtension.beforeRegisterNodeDef.mock.calls[i][0]; - const nodeDef = mockExtension.beforeRegisterNodeDef.mock.calls[i][1]; - - expect(nodeClass.name).toBe("ComfyNode"); - expect(nodeClass.comfyClass).toBe(nodeNames[i]); - expect(nodeDef.name).toBe(nodeNames[i]); - expect(nodeDef).toHaveProperty("input"); - expect(nodeDef).toHaveProperty("output"); - } - - // Register custom nodes is called once after registerNode defs to allow adding other frontend nodes - expect(mockExtension.registerCustomNodes).toHaveBeenCalledTimes(1); - - // Before configure graph will be called here as the default graph is being loaded - expect(mockExtension.beforeConfigureGraph).toHaveBeenCalledTimes(1); - // it gets sent the graph data that is going to be loaded - const graphData = mockExtension.beforeConfigureGraph.mock.calls[0][0]; - - // A node created is fired for each node constructor that is called - expect(mockExtension.nodeCreated).toHaveBeenCalledTimes(graphData.nodes.length); - for (let i = 0; i < graphData.nodes.length; i++) { - expect(mockExtension.nodeCreated.mock.calls[i][0].type).toBe(graphData.nodes[i].type); - } - - // Each node then calls loadedGraphNode to allow them to be updated - expect(mockExtension.loadedGraphNode).toHaveBeenCalledTimes(graphData.nodes.length); - for (let i = 0; i < graphData.nodes.length; i++) { - expect(mockExtension.loadedGraphNode.mock.calls[i][0].type).toBe(graphData.nodes[i].type); - } - - // After configure is then called once all the setup is done - expect(mockExtension.afterConfigureGraph).toHaveBeenCalledTimes(1); - - expect(mockExtension.setup).toHaveBeenCalledTimes(1); - expect(mockExtension.setup).toHaveBeenCalledWith(app); - - // Ensure hooks are called in the correct order - const callOrder = [ - "init", - "addCustomNodeDefs", - "getCustomWidgets", - "beforeRegisterNodeDef", - "registerCustomNodes", - "beforeConfigureGraph", - "nodeCreated", - "loadedGraphNode", - "afterConfigureGraph", - "setup", - ]; - for (let i = 1; i < callOrder.length; i++) { - const fn1 = mockExtension[callOrder[i - 1]]; - const fn2 = mockExtension[callOrder[i]]; - expect(fn1.mock.invocationCallOrder[0]).toBeLessThan(fn2.mock.invocationCallOrder[0]); - } - - graph.clear(); - - // Ensure adding a new node calls the correct callback - ez.LoadImage(); - expect(mockExtension.loadedGraphNode).toHaveBeenCalledTimes(graphData.nodes.length); - expect(mockExtension.nodeCreated).toHaveBeenCalledTimes(graphData.nodes.length + 1); - expect(mockExtension.nodeCreated.mock.lastCall[0].type).toBe("LoadImage"); - - // Reload the graph to ensure correct hooks are fired - await graph.reload(); - - // These hooks should not be fired again - expect(mockExtension.init).toHaveBeenCalledTimes(1); - expect(mockExtension.addCustomNodeDefs).toHaveBeenCalledTimes(1); - expect(mockExtension.getCustomWidgets).toHaveBeenCalledTimes(1); - expect(mockExtension.registerCustomNodes).toHaveBeenCalledTimes(1); - expect(mockExtension.beforeRegisterNodeDef).toHaveBeenCalledTimes(nodeCount); - expect(mockExtension.setup).toHaveBeenCalledTimes(1); - - // These should be called again - expect(mockExtension.beforeConfigureGraph).toHaveBeenCalledTimes(2); - expect(mockExtension.nodeCreated).toHaveBeenCalledTimes(graphData.nodes.length + 2); - expect(mockExtension.loadedGraphNode).toHaveBeenCalledTimes(graphData.nodes.length + 1); - expect(mockExtension.afterConfigureGraph).toHaveBeenCalledTimes(2); - }, 15000); - - it("allows custom nodeDefs and widgets to be registered", async () => { - const widgetMock = jest.fn((node, inputName, inputData, app) => { - expect(node.constructor.comfyClass).toBe("TestNode"); - expect(inputName).toBe("test_input"); - expect(inputData[0]).toBe("CUSTOMWIDGET"); - expect(inputData[1]?.hello).toBe("world"); - expect(app).toStrictEqual(app); - - return { - widget: node.addWidget("button", inputName, "hello", () => {}), - }; - }); - - // Register our extension that adds a custom node + widget type - const mockExtension = { - name: "TestExtension", - addCustomNodeDefs: (nodeDefs) => { - nodeDefs["TestNode"] = { - output: [], - output_name: [], - output_is_list: [], - name: "TestNode", - display_name: "TestNode", - category: "Test", - input: { - required: { - test_input: ["CUSTOMWIDGET", { hello: "world" }], - }, - }, - }; - }, - getCustomWidgets: jest.fn(() => { - return { - CUSTOMWIDGET: widgetMock, - }; - }), - }; - - const { graph, ez } = await start({ - async preSetup(app) { - app.registerExtension(mockExtension); - }, - }); - - expect(mockExtension.getCustomWidgets).toBeCalledTimes(1); - - graph.clear(); - expect(widgetMock).toBeCalledTimes(0); - const node = ez.TestNode(); - expect(widgetMock).toBeCalledTimes(1); - - // Ensure our custom widget is created - expect(node.inputs.length).toBe(0); - expect(node.widgets.length).toBe(1); - const w = node.widgets[0].widget; - expect(w.name).toBe("test_input"); - expect(w.type).toBe("button"); - }); -}); diff --git a/tests-ui/tests/groupNode.test.js b/tests-ui/tests/groupNode.test.js deleted file mode 100644 index 53a5828d1..000000000 --- a/tests-ui/tests/groupNode.test.js +++ /dev/null @@ -1,1005 +0,0 @@ -// @ts-check -/// - -const { start, createDefaultWorkflow, getNodeDef, checkBeforeAndAfterReload } = require("../utils"); -const lg = require("../utils/litegraph"); - -describe("group node", () => { - beforeEach(() => { - lg.setup(global); - }); - - afterEach(() => { - lg.teardown(global); - }); - - /** - * - * @param {*} app - * @param {*} graph - * @param {*} name - * @param {*} nodes - * @returns { Promise> } - */ - async function convertToGroup(app, graph, name, nodes) { - // Select the nodes we are converting - for (const n of nodes) { - n.select(true); - } - - expect(Object.keys(app.canvas.selected_nodes).sort((a, b) => +a - +b)).toEqual( - nodes.map((n) => n.id + "").sort((a, b) => +a - +b) - ); - - global.prompt = jest.fn().mockImplementation(() => name); - const groupNode = await nodes[0].menu["Convert to Group Node"].call(false); - - // Check group name was requested - expect(window.prompt).toHaveBeenCalled(); - - // Ensure old nodes are removed - for (const n of nodes) { - expect(n.isRemoved).toBeTruthy(); - } - - expect(groupNode.type).toEqual("workflow/" + name); - - return graph.find(groupNode); - } - - /** - * @param { Record | number[] } idMap - * @param { Record> } valueMap - */ - function getOutput(idMap = {}, valueMap = {}) { - if (idMap instanceof Array) { - idMap = idMap.reduce((p, n) => { - p[n] = n + ""; - return p; - }, {}); - } - const expected = { - 1: { inputs: { ckpt_name: "model1.safetensors", ...valueMap?.[1] }, class_type: "CheckpointLoaderSimple" }, - 2: { inputs: { text: "positive", clip: ["1", 1], ...valueMap?.[2] }, class_type: "CLIPTextEncode" }, - 3: { inputs: { text: "negative", clip: ["1", 1], ...valueMap?.[3] }, class_type: "CLIPTextEncode" }, - 4: { inputs: { width: 512, height: 512, batch_size: 1, ...valueMap?.[4] }, class_type: "EmptyLatentImage" }, - 5: { - inputs: { - seed: 0, - steps: 20, - cfg: 8, - sampler_name: "euler", - scheduler: "normal", - denoise: 1, - model: ["1", 0], - positive: ["2", 0], - negative: ["3", 0], - latent_image: ["4", 0], - ...valueMap?.[5], - }, - class_type: "KSampler", - }, - 6: { inputs: { samples: ["5", 0], vae: ["1", 2], ...valueMap?.[6] }, class_type: "VAEDecode" }, - 7: { inputs: { filename_prefix: "ComfyUI", images: ["6", 0], ...valueMap?.[7] }, class_type: "SaveImage" }, - }; - - // Map old IDs to new at the top level - const mapped = {}; - for (const oldId in idMap) { - mapped[idMap[oldId]] = expected[oldId]; - delete expected[oldId]; - } - Object.assign(mapped, expected); - - // Map old IDs to new inside links - for (const k in mapped) { - for (const input in mapped[k].inputs) { - const v = mapped[k].inputs[input]; - if (v instanceof Array) { - if (v[0] in idMap) { - v[0] = idMap[v[0]] + ""; - } - } - } - } - - return mapped; - } - - test("can be created from selected nodes", async () => { - const { ez, graph, app } = await start(); - const nodes = createDefaultWorkflow(ez, graph); - const group = await convertToGroup(app, graph, "test", [nodes.pos, nodes.neg, nodes.empty]); - - // Ensure links are now to the group node - expect(group.inputs).toHaveLength(2); - expect(group.outputs).toHaveLength(3); - - expect(group.inputs.map((i) => i.input.name)).toEqual(["clip", "CLIPTextEncode clip"]); - expect(group.outputs.map((i) => i.output.name)).toEqual(["LATENT", "CONDITIONING", "CLIPTextEncode CONDITIONING"]); - - // ckpt clip to both clip inputs on the group - expect(nodes.ckpt.outputs.CLIP.connections.map((t) => [t.targetNode.id, t.targetInput.index])).toEqual([ - [group.id, 0], - [group.id, 1], - ]); - - // group conditioning to sampler - expect(group.outputs["CONDITIONING"].connections.map((t) => [t.targetNode.id, t.targetInput.index])).toEqual([ - [nodes.sampler.id, 1], - ]); - // group conditioning 2 to sampler - expect( - group.outputs["CLIPTextEncode CONDITIONING"].connections.map((t) => [t.targetNode.id, t.targetInput.index]) - ).toEqual([[nodes.sampler.id, 2]]); - // group latent to sampler - expect(group.outputs["LATENT"].connections.map((t) => [t.targetNode.id, t.targetInput.index])).toEqual([ - [nodes.sampler.id, 3], - ]); - }); - - test("maintains all output links on conversion", async () => { - const { ez, graph, app } = await start(); - const nodes = createDefaultWorkflow(ez, graph); - const save2 = ez.SaveImage(...nodes.decode.outputs); - const save3 = ez.SaveImage(...nodes.decode.outputs); - // Ensure an output with multiple links maintains them on convert to group - const group = await convertToGroup(app, graph, "test", [nodes.sampler, nodes.decode]); - expect(group.outputs[0].connections.length).toBe(3); - expect(group.outputs[0].connections[0].targetNode.id).toBe(nodes.save.id); - expect(group.outputs[0].connections[1].targetNode.id).toBe(save2.id); - expect(group.outputs[0].connections[2].targetNode.id).toBe(save3.id); - - // and they're still linked when converting back to nodes - const newNodes = group.menu["Convert to nodes"].call(); - const decode = graph.find(newNodes.find((n) => n.type === "VAEDecode")); - expect(decode.outputs[0].connections.length).toBe(3); - expect(decode.outputs[0].connections[0].targetNode.id).toBe(nodes.save.id); - expect(decode.outputs[0].connections[1].targetNode.id).toBe(save2.id); - expect(decode.outputs[0].connections[2].targetNode.id).toBe(save3.id); - }); - test("can be be converted back to nodes", async () => { - const { ez, graph, app } = await start(); - const nodes = createDefaultWorkflow(ez, graph); - const toConvert = [nodes.pos, nodes.neg, nodes.empty, nodes.sampler]; - const group = await convertToGroup(app, graph, "test", toConvert); - - // Edit some values to ensure they are set back onto the converted nodes - expect(group.widgets["text"].value).toBe("positive"); - group.widgets["text"].value = "pos"; - expect(group.widgets["CLIPTextEncode text"].value).toBe("negative"); - group.widgets["CLIPTextEncode text"].value = "neg"; - expect(group.widgets["width"].value).toBe(512); - group.widgets["width"].value = 1024; - expect(group.widgets["sampler_name"].value).toBe("euler"); - group.widgets["sampler_name"].value = "ddim"; - expect(group.widgets["control_after_generate"].value).toBe("randomize"); - group.widgets["control_after_generate"].value = "fixed"; - - /** @type { Array } */ - group.menu["Convert to nodes"].call(); - - // ensure widget values are set - const pos = graph.find(nodes.pos.id); - expect(pos.node.type).toBe("CLIPTextEncode"); - expect(pos.widgets["text"].value).toBe("pos"); - const neg = graph.find(nodes.neg.id); - expect(neg.node.type).toBe("CLIPTextEncode"); - expect(neg.widgets["text"].value).toBe("neg"); - const empty = graph.find(nodes.empty.id); - expect(empty.node.type).toBe("EmptyLatentImage"); - expect(empty.widgets["width"].value).toBe(1024); - const sampler = graph.find(nodes.sampler.id); - expect(sampler.node.type).toBe("KSampler"); - expect(sampler.widgets["sampler_name"].value).toBe("ddim"); - expect(sampler.widgets["control_after_generate"].value).toBe("fixed"); - - // validate links - expect(nodes.ckpt.outputs.CLIP.connections.map((t) => [t.targetNode.id, t.targetInput.index])).toEqual([ - [pos.id, 0], - [neg.id, 0], - ]); - - expect(pos.outputs["CONDITIONING"].connections.map((t) => [t.targetNode.id, t.targetInput.index])).toEqual([ - [nodes.sampler.id, 1], - ]); - - expect(neg.outputs["CONDITIONING"].connections.map((t) => [t.targetNode.id, t.targetInput.index])).toEqual([ - [nodes.sampler.id, 2], - ]); - - expect(empty.outputs["LATENT"].connections.map((t) => [t.targetNode.id, t.targetInput.index])).toEqual([ - [nodes.sampler.id, 3], - ]); - }); - test("it can embed reroutes as inputs", async () => { - const { ez, graph, app } = await start(); - const nodes = createDefaultWorkflow(ez, graph); - - // Add and connect a reroute to the clip text encodes - const reroute = ez.Reroute(); - nodes.ckpt.outputs.CLIP.connectTo(reroute.inputs[0]); - reroute.outputs[0].connectTo(nodes.pos.inputs[0]); - reroute.outputs[0].connectTo(nodes.neg.inputs[0]); - - // Convert to group and ensure we only have 1 input of the correct type - const group = await convertToGroup(app, graph, "test", [nodes.pos, nodes.neg, nodes.empty, reroute]); - expect(group.inputs).toHaveLength(1); - expect(group.inputs[0].input.type).toEqual("CLIP"); - - expect((await graph.toPrompt()).output).toEqual(getOutput()); - }); - test("it can embed reroutes as outputs", async () => { - const { ez, graph, app } = await start(); - const nodes = createDefaultWorkflow(ez, graph); - - // Add a reroute with no output so we output IMAGE even though its used internally - const reroute = ez.Reroute(); - nodes.decode.outputs.IMAGE.connectTo(reroute.inputs[0]); - - // Convert to group and ensure there is an IMAGE output - const group = await convertToGroup(app, graph, "test", [nodes.decode, nodes.save, reroute]); - expect(group.outputs).toHaveLength(1); - expect(group.outputs[0].output.type).toEqual("IMAGE"); - expect((await graph.toPrompt()).output).toEqual(getOutput([nodes.decode.id, nodes.save.id])); - }); - test("it can embed reroutes as pipes", async () => { - const { ez, graph, app } = await start(); - const nodes = createDefaultWorkflow(ez, graph); - - // Use reroutes as a pipe - const rerouteModel = ez.Reroute(); - const rerouteClip = ez.Reroute(); - const rerouteVae = ez.Reroute(); - nodes.ckpt.outputs.MODEL.connectTo(rerouteModel.inputs[0]); - nodes.ckpt.outputs.CLIP.connectTo(rerouteClip.inputs[0]); - nodes.ckpt.outputs.VAE.connectTo(rerouteVae.inputs[0]); - - const group = await convertToGroup(app, graph, "test", [rerouteModel, rerouteClip, rerouteVae]); - - expect(group.outputs).toHaveLength(3); - expect(group.outputs.map((o) => o.output.type)).toEqual(["MODEL", "CLIP", "VAE"]); - - expect(group.outputs).toHaveLength(3); - expect(group.outputs.map((o) => o.output.type)).toEqual(["MODEL", "CLIP", "VAE"]); - - group.outputs[0].connectTo(nodes.sampler.inputs.model); - group.outputs[1].connectTo(nodes.pos.inputs.clip); - group.outputs[1].connectTo(nodes.neg.inputs.clip); - }); - test("can handle reroutes used internally", async () => { - const { ez, graph, app } = await start(); - const nodes = createDefaultWorkflow(ez, graph); - - let reroutes = []; - let prevNode = nodes.ckpt; - for (let i = 0; i < 5; i++) { - const reroute = ez.Reroute(); - prevNode.outputs[0].connectTo(reroute.inputs[0]); - prevNode = reroute; - reroutes.push(reroute); - } - prevNode.outputs[0].connectTo(nodes.sampler.inputs.model); - - const group = await convertToGroup(app, graph, "test", [...reroutes, ...Object.values(nodes)]); - expect((await graph.toPrompt()).output).toEqual(getOutput()); - - group.menu["Convert to nodes"].call(); - expect((await graph.toPrompt()).output).toEqual(getOutput()); - }); - test("creates with widget values from inner nodes", async () => { - const { ez, graph, app } = await start(); - const nodes = createDefaultWorkflow(ez, graph); - - nodes.ckpt.widgets.ckpt_name.value = "model2.ckpt"; - nodes.pos.widgets.text.value = "hello"; - nodes.neg.widgets.text.value = "world"; - nodes.empty.widgets.width.value = 256; - nodes.empty.widgets.height.value = 1024; - nodes.sampler.widgets.seed.value = 1; - nodes.sampler.widgets.control_after_generate.value = "increment"; - nodes.sampler.widgets.steps.value = 8; - nodes.sampler.widgets.cfg.value = 4.5; - nodes.sampler.widgets.sampler_name.value = "uni_pc"; - nodes.sampler.widgets.scheduler.value = "karras"; - nodes.sampler.widgets.denoise.value = 0.9; - - const group = await convertToGroup(app, graph, "test", [ - nodes.ckpt, - nodes.pos, - nodes.neg, - nodes.empty, - nodes.sampler, - ]); - - expect(group.widgets["ckpt_name"].value).toEqual("model2.ckpt"); - expect(group.widgets["text"].value).toEqual("hello"); - expect(group.widgets["CLIPTextEncode text"].value).toEqual("world"); - expect(group.widgets["width"].value).toEqual(256); - expect(group.widgets["height"].value).toEqual(1024); - expect(group.widgets["seed"].value).toEqual(1); - expect(group.widgets["control_after_generate"].value).toEqual("increment"); - expect(group.widgets["steps"].value).toEqual(8); - expect(group.widgets["cfg"].value).toEqual(4.5); - expect(group.widgets["sampler_name"].value).toEqual("uni_pc"); - expect(group.widgets["scheduler"].value).toEqual("karras"); - expect(group.widgets["denoise"].value).toEqual(0.9); - - expect((await graph.toPrompt()).output).toEqual( - getOutput([nodes.ckpt.id, nodes.pos.id, nodes.neg.id, nodes.empty.id, nodes.sampler.id], { - [nodes.ckpt.id]: { ckpt_name: "model2.ckpt" }, - [nodes.pos.id]: { text: "hello" }, - [nodes.neg.id]: { text: "world" }, - [nodes.empty.id]: { width: 256, height: 1024 }, - [nodes.sampler.id]: { - seed: 1, - steps: 8, - cfg: 4.5, - sampler_name: "uni_pc", - scheduler: "karras", - denoise: 0.9, - }, - }) - ); - }); - test("group inputs can be reroutes", async () => { - const { ez, graph, app } = await start(); - const nodes = createDefaultWorkflow(ez, graph); - const group = await convertToGroup(app, graph, "test", [nodes.pos, nodes.neg]); - - const reroute = ez.Reroute(); - nodes.ckpt.outputs.CLIP.connectTo(reroute.inputs[0]); - - reroute.outputs[0].connectTo(group.inputs[0]); - reroute.outputs[0].connectTo(group.inputs[1]); - - expect((await graph.toPrompt()).output).toEqual(getOutput([nodes.pos.id, nodes.neg.id])); - }); - test("group outputs can be reroutes", async () => { - const { ez, graph, app } = await start(); - const nodes = createDefaultWorkflow(ez, graph); - const group = await convertToGroup(app, graph, "test", [nodes.pos, nodes.neg]); - - const reroute1 = ez.Reroute(); - const reroute2 = ez.Reroute(); - group.outputs[0].connectTo(reroute1.inputs[0]); - group.outputs[1].connectTo(reroute2.inputs[0]); - - reroute1.outputs[0].connectTo(nodes.sampler.inputs.positive); - reroute2.outputs[0].connectTo(nodes.sampler.inputs.negative); - - expect((await graph.toPrompt()).output).toEqual(getOutput([nodes.pos.id, nodes.neg.id])); - }); - test("groups can connect to each other", async () => { - const { ez, graph, app } = await start(); - const nodes = createDefaultWorkflow(ez, graph); - const group1 = await convertToGroup(app, graph, "test", [nodes.pos, nodes.neg]); - const group2 = await convertToGroup(app, graph, "test2", [nodes.empty, nodes.sampler]); - - group1.outputs[0].connectTo(group2.inputs["positive"]); - group1.outputs[1].connectTo(group2.inputs["negative"]); - - expect((await graph.toPrompt()).output).toEqual( - getOutput([nodes.pos.id, nodes.neg.id, nodes.empty.id, nodes.sampler.id]) - ); - }); - test("groups can connect to each other via internal reroutes", async () => { - const { ez, graph, app } = await start(); - - const latent = ez.EmptyLatentImage(); - const vae = ez.VAELoader(); - const latentReroute = ez.Reroute(); - const vaeReroute = ez.Reroute(); - - latent.outputs[0].connectTo(latentReroute.inputs[0]); - vae.outputs[0].connectTo(vaeReroute.inputs[0]); - - const group1 = await convertToGroup(app, graph, "test", [latentReroute, vaeReroute]); - group1.menu.Clone.call(); - expect(app.graph._nodes).toHaveLength(4); - const group2 = graph.find(app.graph._nodes[3]); - expect(group2.node.type).toEqual("workflow/test"); - expect(group2.id).not.toEqual(group1.id); - - group1.outputs.VAE.connectTo(group2.inputs.VAE); - group1.outputs.LATENT.connectTo(group2.inputs.LATENT); - - const decode = ez.VAEDecode(group2.outputs.LATENT, group2.outputs.VAE); - const preview = ez.PreviewImage(decode.outputs[0]); - - const output = { - [latent.id]: { inputs: { width: 512, height: 512, batch_size: 1 }, class_type: "EmptyLatentImage" }, - [vae.id]: { inputs: { vae_name: "vae1.safetensors" }, class_type: "VAELoader" }, - [decode.id]: { inputs: { samples: [latent.id + "", 0], vae: [vae.id + "", 0] }, class_type: "VAEDecode" }, - [preview.id]: { inputs: { images: [decode.id + "", 0] }, class_type: "PreviewImage" }, - }; - expect((await graph.toPrompt()).output).toEqual(output); - - // Ensure missing connections dont cause errors - group2.inputs.VAE.disconnect(); - delete output[decode.id].inputs.vae; - expect((await graph.toPrompt()).output).toEqual(output); - }); - test("displays generated image on group node", async () => { - const { ez, graph, app } = await start(); - const nodes = createDefaultWorkflow(ez, graph); - let group = await convertToGroup(app, graph, "test", [ - nodes.pos, - nodes.neg, - nodes.empty, - nodes.sampler, - nodes.decode, - nodes.save, - ]); - - const { api } = require("../../web/scripts/api"); - - api.dispatchEvent(new CustomEvent("execution_start", {})); - api.dispatchEvent(new CustomEvent("executing", { detail: `${nodes.save.id}` })); - // Event should be forwarded to group node id - expect(+app.runningNodeId).toEqual(group.id); - expect(group.node["imgs"]).toBeFalsy(); - api.dispatchEvent( - new CustomEvent("executed", { - detail: { - node: `${nodes.save.id}`, - output: { - images: [ - { - filename: "test.png", - type: "output", - }, - ], - }, - }, - }) - ); - - // Trigger paint - group.node.onDrawBackground?.(app.canvas.ctx, app.canvas.canvas); - - expect(group.node["images"]).toEqual([ - { - filename: "test.png", - type: "output", - }, - ]); - - // Reload - const workflow = JSON.stringify((await graph.toPrompt()).workflow); - await app.loadGraphData(JSON.parse(workflow)); - group = graph.find(group); - - // Trigger inner nodes to get created - group.node["getInnerNodes"](); - - // Check it works for internal node ids - api.dispatchEvent(new CustomEvent("execution_start", {})); - api.dispatchEvent(new CustomEvent("executing", { detail: `${group.id}:5` })); - // Event should be forwarded to group node id - expect(+app.runningNodeId).toEqual(group.id); - expect(group.node["imgs"]).toBeFalsy(); - api.dispatchEvent( - new CustomEvent("executed", { - detail: { - node: `${group.id}:5`, - output: { - images: [ - { - filename: "test2.png", - type: "output", - }, - ], - }, - }, - }) - ); - - // Trigger paint - group.node.onDrawBackground?.(app.canvas.ctx, app.canvas.canvas); - - expect(group.node["images"]).toEqual([ - { - filename: "test2.png", - type: "output", - }, - ]); - }); - test("allows widgets to be converted to inputs", async () => { - const { ez, graph, app } = await start(); - const nodes = createDefaultWorkflow(ez, graph); - const group = await convertToGroup(app, graph, "test", [nodes.pos, nodes.neg]); - group.widgets[0].convertToInput(); - - const primitive = ez.PrimitiveNode(); - primitive.outputs[0].connectTo(group.inputs["text"]); - primitive.widgets[0].value = "hello"; - - expect((await graph.toPrompt()).output).toEqual( - getOutput([nodes.pos.id, nodes.neg.id], { - [nodes.pos.id]: { text: "hello" }, - }) - ); - }); - test("can be copied", async () => { - const { ez, graph, app } = await start(); - const nodes = createDefaultWorkflow(ez, graph); - - const group1 = await convertToGroup(app, graph, "test", [ - nodes.pos, - nodes.neg, - nodes.empty, - nodes.sampler, - nodes.decode, - nodes.save, - ]); - - group1.widgets["text"].value = "hello"; - group1.widgets["width"].value = 256; - group1.widgets["seed"].value = 1; - - // Clone the node - group1.menu.Clone.call(); - expect(app.graph._nodes).toHaveLength(3); - const group2 = graph.find(app.graph._nodes[2]); - expect(group2.node.type).toEqual("workflow/test"); - expect(group2.id).not.toEqual(group1.id); - - // Reconnect ckpt - nodes.ckpt.outputs.MODEL.connectTo(group2.inputs["model"]); - nodes.ckpt.outputs.CLIP.connectTo(group2.inputs["clip"]); - nodes.ckpt.outputs.CLIP.connectTo(group2.inputs["CLIPTextEncode clip"]); - nodes.ckpt.outputs.VAE.connectTo(group2.inputs["vae"]); - - group2.widgets["text"].value = "world"; - group2.widgets["width"].value = 1024; - group2.widgets["seed"].value = 100; - - let i = 0; - expect((await graph.toPrompt()).output).toEqual({ - ...getOutput([nodes.empty.id, nodes.pos.id, nodes.neg.id, nodes.sampler.id, nodes.decode.id, nodes.save.id], { - [nodes.empty.id]: { width: 256 }, - [nodes.pos.id]: { text: "hello" }, - [nodes.sampler.id]: { seed: 1 }, - }), - ...getOutput( - { - [nodes.empty.id]: `${group2.id}:${i++}`, - [nodes.pos.id]: `${group2.id}:${i++}`, - [nodes.neg.id]: `${group2.id}:${i++}`, - [nodes.sampler.id]: `${group2.id}:${i++}`, - [nodes.decode.id]: `${group2.id}:${i++}`, - [nodes.save.id]: `${group2.id}:${i++}`, - }, - { - [nodes.empty.id]: { width: 1024 }, - [nodes.pos.id]: { text: "world" }, - [nodes.sampler.id]: { seed: 100 }, - } - ), - }); - - graph.arrange(); - }); - test("is embedded in workflow", async () => { - let { ez, graph, app } = await start(); - const nodes = createDefaultWorkflow(ez, graph); - let group = await convertToGroup(app, graph, "test", [nodes.pos, nodes.neg]); - const workflow = JSON.stringify((await graph.toPrompt()).workflow); - - // Clear the environment - ({ ez, graph, app } = await start({ - resetEnv: true, - })); - // Ensure the node isnt registered - expect(() => ez["workflow/test"]).toThrow(); - - // Reload the workflow - await app.loadGraphData(JSON.parse(workflow)); - - // Ensure the node is found - group = graph.find(group); - - // Generate prompt and ensure it is as expected - expect((await graph.toPrompt()).output).toEqual( - getOutput({ - [nodes.pos.id]: `${group.id}:0`, - [nodes.neg.id]: `${group.id}:1`, - }) - ); - }); - test("shows missing node error on missing internal node when loading graph data", async () => { - const { graph } = await start(); - - const dialogShow = jest.spyOn(graph.app.ui.dialog, "show"); - await graph.app.loadGraphData({ - last_node_id: 3, - last_link_id: 1, - nodes: [ - { - id: 3, - type: "workflow/testerror", - }, - ], - links: [], - groups: [], - config: {}, - extra: { - groupNodes: { - testerror: { - nodes: [ - { - type: "NotKSampler", - }, - { - type: "NotVAEDecode", - }, - ], - }, - }, - }, - }); - - expect(dialogShow).toBeCalledTimes(1); - const call = dialogShow.mock.calls[0][0].innerHTML; - expect(call).toContain("the following node types were not found"); - expect(call).toContain("NotKSampler"); - expect(call).toContain("NotVAEDecode"); - expect(call).toContain("workflow/testerror"); - }); - test("maintains widget inputs on conversion back to nodes", async () => { - const { ez, graph, app } = await start(); - let pos = ez.CLIPTextEncode({ text: "positive" }); - pos.node.title = "Positive"; - let neg = ez.CLIPTextEncode({ text: "negative" }); - neg.node.title = "Negative"; - pos.widgets.text.convertToInput(); - neg.widgets.text.convertToInput(); - - let primitive = ez.PrimitiveNode(); - primitive.outputs[0].connectTo(pos.inputs.text); - primitive.outputs[0].connectTo(neg.inputs.text); - - const group = await convertToGroup(app, graph, "test", [pos, neg, primitive]); - // This will use a primitive widget named 'value' - expect(group.widgets.length).toBe(1); - expect(group.widgets["value"].value).toBe("positive"); - - const newNodes = group.menu["Convert to nodes"].call(); - pos = graph.find(newNodes.find((n) => n.title === "Positive")); - neg = graph.find(newNodes.find((n) => n.title === "Negative")); - primitive = graph.find(newNodes.find((n) => n.type === "PrimitiveNode")); - - expect(pos.inputs).toHaveLength(2); - expect(neg.inputs).toHaveLength(2); - expect(primitive.outputs[0].connections).toHaveLength(2); - - expect((await graph.toPrompt()).output).toEqual({ - 1: { inputs: { text: "positive" }, class_type: "CLIPTextEncode" }, - 2: { inputs: { text: "positive" }, class_type: "CLIPTextEncode" }, - }); - }); - test("correctly handles widget inputs", async () => { - const { ez, graph, app } = await start(); - const upscaleMethods = (await getNodeDef("ImageScaleBy")).input.required["upscale_method"][0]; - - const image = ez.LoadImage(); - const scale1 = ez.ImageScaleBy(image.outputs[0]); - const scale2 = ez.ImageScaleBy(image.outputs[0]); - const preview1 = ez.PreviewImage(scale1.outputs[0]); - const preview2 = ez.PreviewImage(scale2.outputs[0]); - scale1.widgets.upscale_method.value = upscaleMethods[1]; - scale1.widgets.upscale_method.convertToInput(); - - const group = await convertToGroup(app, graph, "test", [scale1, scale2]); - expect(group.inputs.length).toBe(3); - expect(group.inputs[0].input.type).toBe("IMAGE"); - expect(group.inputs[1].input.type).toBe("IMAGE"); - expect(group.inputs[2].input.type).toBe("COMBO"); - - // Ensure links are maintained - expect(group.inputs[0].connection?.originNode?.id).toBe(image.id); - expect(group.inputs[1].connection?.originNode?.id).toBe(image.id); - expect(group.inputs[2].connection).toBeFalsy(); - - // Ensure primitive gets correct type - const primitive = ez.PrimitiveNode(); - primitive.outputs[0].connectTo(group.inputs[2]); - expect(primitive.widgets.value.widget.options.values).toBe(upscaleMethods); - expect(primitive.widgets.value.value).toBe(upscaleMethods[1]); // Ensure value is copied - primitive.widgets.value.value = upscaleMethods[1]; - - await checkBeforeAndAfterReload(graph, async (r) => { - const scale1id = r ? `${group.id}:0` : scale1.id; - const scale2id = r ? `${group.id}:1` : scale2.id; - // Ensure widget value is applied to prompt - expect((await graph.toPrompt()).output).toStrictEqual({ - [image.id]: { inputs: { image: "example.png", upload: "image" }, class_type: "LoadImage" }, - [scale1id]: { - inputs: { upscale_method: upscaleMethods[1], scale_by: 1, image: [`${image.id}`, 0] }, - class_type: "ImageScaleBy", - }, - [scale2id]: { - inputs: { upscale_method: "nearest-exact", scale_by: 1, image: [`${image.id}`, 0] }, - class_type: "ImageScaleBy", - }, - [preview1.id]: { inputs: { images: [`${scale1id}`, 0] }, class_type: "PreviewImage" }, - [preview2.id]: { inputs: { images: [`${scale2id}`, 0] }, class_type: "PreviewImage" }, - }); - }); - }); - test("adds widgets in node execution order", async () => { - const { ez, graph, app } = await start(); - const scale = ez.LatentUpscale(); - const save = ez.SaveImage(); - const empty = ez.EmptyLatentImage(); - const decode = ez.VAEDecode(); - - scale.outputs.LATENT.connectTo(decode.inputs.samples); - decode.outputs.IMAGE.connectTo(save.inputs.images); - empty.outputs.LATENT.connectTo(scale.inputs.samples); - - const group = await convertToGroup(app, graph, "test", [scale, save, empty, decode]); - const widgets = group.widgets.map((w) => w.widget.name); - expect(widgets).toStrictEqual([ - "width", - "height", - "batch_size", - "upscale_method", - "LatentUpscale width", - "LatentUpscale height", - "crop", - "filename_prefix", - ]); - }); - test("adds output for external links when converting to group", async () => { - const { ez, graph, app } = await start(); - const img = ez.EmptyLatentImage(); - let decode = ez.VAEDecode(...img.outputs); - const preview1 = ez.PreviewImage(...decode.outputs); - const preview2 = ez.PreviewImage(...decode.outputs); - - const group = await convertToGroup(app, graph, "test", [img, decode, preview1]); - - // Ensure we have an output connected to the 2nd preview node - expect(group.outputs.length).toBe(1); - expect(group.outputs[0].connections.length).toBe(1); - expect(group.outputs[0].connections[0].targetNode.id).toBe(preview2.id); - - // Convert back and ensure bothe previews are still connected - group.menu["Convert to nodes"].call(); - decode = graph.find(decode); - expect(decode.outputs[0].connections.length).toBe(2); - expect(decode.outputs[0].connections[0].targetNode.id).toBe(preview1.id); - expect(decode.outputs[0].connections[1].targetNode.id).toBe(preview2.id); - }); - test("adds output for external links when converting to group when nodes are not in execution order", async () => { - const { ez, graph, app } = await start(); - const sampler = ez.KSampler(); - const ckpt = ez.CheckpointLoaderSimple(); - const empty = ez.EmptyLatentImage(); - const pos = ez.CLIPTextEncode(ckpt.outputs.CLIP, { text: "positive" }); - const neg = ez.CLIPTextEncode(ckpt.outputs.CLIP, { text: "negative" }); - const decode1 = ez.VAEDecode(sampler.outputs.LATENT, ckpt.outputs.VAE); - const save = ez.SaveImage(decode1.outputs.IMAGE); - ckpt.outputs.MODEL.connectTo(sampler.inputs.model); - pos.outputs.CONDITIONING.connectTo(sampler.inputs.positive); - neg.outputs.CONDITIONING.connectTo(sampler.inputs.negative); - empty.outputs.LATENT.connectTo(sampler.inputs.latent_image); - - const encode = ez.VAEEncode(decode1.outputs.IMAGE); - const vae = ez.VAELoader(); - const decode2 = ez.VAEDecode(encode.outputs.LATENT, vae.outputs.VAE); - const preview = ez.PreviewImage(decode2.outputs.IMAGE); - vae.outputs.VAE.connectTo(encode.inputs.vae); - - const group = await convertToGroup(app, graph, "test", [vae, decode1, encode, sampler]); - - expect(group.outputs.length).toBe(3); - expect(group.outputs[0].output.name).toBe("VAE"); - expect(group.outputs[0].output.type).toBe("VAE"); - expect(group.outputs[1].output.name).toBe("IMAGE"); - expect(group.outputs[1].output.type).toBe("IMAGE"); - expect(group.outputs[2].output.name).toBe("LATENT"); - expect(group.outputs[2].output.type).toBe("LATENT"); - - expect(group.outputs[0].connections.length).toBe(1); - expect(group.outputs[0].connections[0].targetNode.id).toBe(decode2.id); - expect(group.outputs[0].connections[0].targetInput.index).toBe(1); - - expect(group.outputs[1].connections.length).toBe(1); - expect(group.outputs[1].connections[0].targetNode.id).toBe(save.id); - expect(group.outputs[1].connections[0].targetInput.index).toBe(0); - - expect(group.outputs[2].connections.length).toBe(1); - expect(group.outputs[2].connections[0].targetNode.id).toBe(decode2.id); - expect(group.outputs[2].connections[0].targetInput.index).toBe(0); - - expect((await graph.toPrompt()).output).toEqual({ - ...getOutput({ 1: ckpt.id, 2: pos.id, 3: neg.id, 4: empty.id, 5: sampler.id, 6: decode1.id, 7: save.id }), - [vae.id]: { inputs: { vae_name: "vae1.safetensors" }, class_type: vae.node.type }, - [encode.id]: { inputs: { pixels: ["6", 0], vae: [vae.id + "", 0] }, class_type: encode.node.type }, - [decode2.id]: { inputs: { samples: [encode.id + "", 0], vae: [vae.id + "", 0] }, class_type: decode2.node.type }, - [preview.id]: { inputs: { images: [decode2.id + "", 0] }, class_type: preview.node.type }, - }); - }); - test("works with IMAGEUPLOAD widget", async () => { - const { ez, graph, app } = await start(); - const img = ez.LoadImage(); - const preview1 = ez.PreviewImage(img.outputs[0]); - - const group = await convertToGroup(app, graph, "test", [img, preview1]); - const widget = group.widgets["upload"]; - expect(widget).toBeTruthy(); - expect(widget.widget.type).toBe("button"); - }); - test("internal primitive populates widgets for all linked inputs", async () => { - const { ez, graph, app } = await start(); - const img = ez.LoadImage(); - const scale1 = ez.ImageScale(img.outputs[0]); - const scale2 = ez.ImageScale(img.outputs[0]); - ez.PreviewImage(scale1.outputs[0]); - ez.PreviewImage(scale2.outputs[0]); - - scale1.widgets.width.convertToInput(); - scale2.widgets.height.convertToInput(); - - const primitive = ez.PrimitiveNode(); - primitive.outputs[0].connectTo(scale1.inputs.width); - primitive.outputs[0].connectTo(scale2.inputs.height); - - const group = await convertToGroup(app, graph, "test", [img, primitive, scale1, scale2]); - group.widgets.value.value = 100; - expect((await graph.toPrompt()).output).toEqual({ - 1: { - inputs: { image: img.widgets.image.value, upload: "image" }, - class_type: "LoadImage", - }, - 2: { - inputs: { upscale_method: "nearest-exact", width: 100, height: 512, crop: "disabled", image: ["1", 0] }, - class_type: "ImageScale", - }, - 3: { - inputs: { upscale_method: "nearest-exact", width: 512, height: 100, crop: "disabled", image: ["1", 0] }, - class_type: "ImageScale", - }, - 4: { inputs: { images: ["2", 0] }, class_type: "PreviewImage" }, - 5: { inputs: { images: ["3", 0] }, class_type: "PreviewImage" }, - }); - }); - test("primitive control widgets values are copied on convert", async () => { - const { ez, graph, app } = await start(); - const sampler = ez.KSampler(); - sampler.widgets.seed.convertToInput(); - sampler.widgets.sampler_name.convertToInput(); - - let p1 = ez.PrimitiveNode(); - let p2 = ez.PrimitiveNode(); - p1.outputs[0].connectTo(sampler.inputs.seed); - p2.outputs[0].connectTo(sampler.inputs.sampler_name); - - p1.widgets.control_after_generate.value = "increment"; - p2.widgets.control_after_generate.value = "decrement"; - p2.widgets.control_filter_list.value = "/.*/"; - - p2.node.title = "p2"; - - const group = await convertToGroup(app, graph, "test", [sampler, p1, p2]); - expect(group.widgets.control_after_generate.value).toBe("increment"); - expect(group.widgets["p2 control_after_generate"].value).toBe("decrement"); - expect(group.widgets["p2 control_filter_list"].value).toBe("/.*/"); - - group.widgets.control_after_generate.value = "fixed"; - group.widgets["p2 control_after_generate"].value = "randomize"; - group.widgets["p2 control_filter_list"].value = "/.+/"; - - group.menu["Convert to nodes"].call(); - p1 = graph.find(p1); - p2 = graph.find(p2); - - expect(p1.widgets.control_after_generate.value).toBe("fixed"); - expect(p2.widgets.control_after_generate.value).toBe("randomize"); - expect(p2.widgets.control_filter_list.value).toBe("/.+/"); - }); - test("internal reroutes work with converted inputs and merge options", async () => { - const { ez, graph, app } = await start(); - const vae = ez.VAELoader(); - const latent = ez.EmptyLatentImage(); - const decode = ez.VAEDecode(latent.outputs.LATENT, vae.outputs.VAE); - const scale = ez.ImageScale(decode.outputs.IMAGE); - ez.PreviewImage(scale.outputs.IMAGE); - - const r1 = ez.Reroute(); - const r2 = ez.Reroute(); - - latent.widgets.width.value = 64; - latent.widgets.height.value = 128; - - latent.widgets.width.convertToInput(); - latent.widgets.height.convertToInput(); - latent.widgets.batch_size.convertToInput(); - - scale.widgets.width.convertToInput(); - scale.widgets.height.convertToInput(); - - r1.inputs[0].input.label = "hbw"; - r1.outputs[0].connectTo(latent.inputs.height); - r1.outputs[0].connectTo(latent.inputs.batch_size); - r1.outputs[0].connectTo(scale.inputs.width); - - r2.inputs[0].input.label = "wh"; - r2.outputs[0].connectTo(latent.inputs.width); - r2.outputs[0].connectTo(scale.inputs.height); - - const group = await convertToGroup(app, graph, "test", [r1, r2, latent, decode, scale]); - - expect(group.inputs[0].input.type).toBe("VAE"); - expect(group.inputs[1].input.type).toBe("INT"); - expect(group.inputs[2].input.type).toBe("INT"); - - const p1 = ez.PrimitiveNode(); - const p2 = ez.PrimitiveNode(); - p1.outputs[0].connectTo(group.inputs[1]); - p2.outputs[0].connectTo(group.inputs[2]); - - expect(p1.widgets.value.widget.options?.min).toBe(16); // width/height min - expect(p1.widgets.value.widget.options?.max).toBe(4096); // batch max - expect(p1.widgets.value.widget.options?.step).toBe(80); // width/height step * 10 - - expect(p2.widgets.value.widget.options?.min).toBe(16); // width/height min - expect(p2.widgets.value.widget.options?.max).toBe(16384); // width/height max - expect(p2.widgets.value.widget.options?.step).toBe(80); // width/height step * 10 - - expect(p1.widgets.value.value).toBe(128); - expect(p2.widgets.value.value).toBe(64); - - p1.widgets.value.value = 16; - p2.widgets.value.value = 32; - - await checkBeforeAndAfterReload(graph, async (r) => { - const id = (v) => (r ? `${group.id}:` : "") + v; - expect((await graph.toPrompt()).output).toStrictEqual({ - 1: { inputs: { vae_name: "vae1.safetensors" }, class_type: "VAELoader" }, - [id(2)]: { inputs: { width: 32, height: 16, batch_size: 16 }, class_type: "EmptyLatentImage" }, - [id(3)]: { inputs: { samples: [id(2), 0], vae: ["1", 0] }, class_type: "VAEDecode" }, - [id(4)]: { - inputs: { upscale_method: "nearest-exact", width: 16, height: 32, crop: "disabled", image: [id(3), 0] }, - class_type: "ImageScale", - }, - 5: { inputs: { images: [id(4), 0] }, class_type: "PreviewImage" }, - }); - }); - }); - test("converted inputs with linked widgets map values correctly on creation", async () => { - const { ez, graph, app } = await start(); - const k1 = ez.KSampler(); - const k2 = ez.KSampler(); - k1.widgets.seed.convertToInput(); - k2.widgets.seed.convertToInput(); - - const rr = ez.Reroute(); - rr.outputs[0].connectTo(k1.inputs.seed); - rr.outputs[0].connectTo(k2.inputs.seed); - - const group = await convertToGroup(app, graph, "test", [k1, k2, rr]); - expect(group.widgets.steps.value).toBe(20); - expect(group.widgets.cfg.value).toBe(8); - expect(group.widgets.scheduler.value).toBe("normal"); - expect(group.widgets["KSampler steps"].value).toBe(20); - expect(group.widgets["KSampler cfg"].value).toBe(8); - expect(group.widgets["KSampler scheduler"].value).toBe("normal"); - }); - test("allow multiple of the same node type to be added", async () => { - const { ez, graph, app } = await start(); - const nodes = [...Array(10)].map(() => ez.ImageScaleBy()); - const group = await convertToGroup(app, graph, "test", nodes); - expect(group.inputs.length).toBe(10); - expect(group.outputs.length).toBe(10); - expect(group.widgets.length).toBe(20); - expect(group.widgets.map((w) => w.widget.name)).toStrictEqual( - [...Array(10)] - .map((_, i) => `${i > 0 ? "ImageScaleBy " : ""}${i > 1 ? i + " " : ""}`) - .flatMap((p) => [`${p}upscale_method`, `${p}scale_by`]) - ); - }); -}); diff --git a/tests-ui/tests/users.test.js b/tests-ui/tests/users.test.js deleted file mode 100644 index 5e0730730..000000000 --- a/tests-ui/tests/users.test.js +++ /dev/null @@ -1,295 +0,0 @@ -// @ts-check -/// -const { start } = require("../utils"); -const lg = require("../utils/litegraph"); - -describe("users", () => { - beforeEach(() => { - lg.setup(global); - }); - - afterEach(() => { - lg.teardown(global); - }); - - function expectNoUserScreen() { - // Ensure login isnt visible - const selection = document.querySelectorAll("#comfy-user-selection")?.[0]; - expect(selection["style"].display).toBe("none"); - const menu = document.querySelectorAll(".comfy-menu")?.[0]; - expect(window.getComputedStyle(menu)?.display).not.toBe("none"); - } - - describe("multi-user", () => { - function mockAddStylesheet() { - const utils = require("../../web/scripts/utils"); - utils.addStylesheet = jest.fn().mockReturnValue(Promise.resolve()); - } - - async function waitForUserScreenShow() { - mockAddStylesheet(); - - // Wait for "show" to be called - const { UserSelectionScreen } = require("../../web/scripts/ui/userSelection"); - let resolve, reject; - const fn = UserSelectionScreen.prototype.show; - const p = new Promise((res, rej) => { - resolve = res; - reject = rej; - }); - jest.spyOn(UserSelectionScreen.prototype, "show").mockImplementation(async (...args) => { - const res = fn(...args); - await new Promise(process.nextTick); // wait for promises to resolve - resolve(); - return res; - }); - // @ts-ignore - setTimeout(() => reject("timeout waiting for UserSelectionScreen to be shown."), 500); - await p; - await new Promise(process.nextTick); // wait for promises to resolve - } - - async function testUserScreen(onShown, users) { - if (!users) { - users = {}; - } - const starting = start({ - resetEnv: true, - userConfig: { storage: "server", users }, - }); - - // Ensure no current user - expect(localStorage["Comfy.userId"]).toBeFalsy(); - expect(localStorage["Comfy.userName"]).toBeFalsy(); - - await waitForUserScreenShow(); - - const selection = document.querySelectorAll("#comfy-user-selection")?.[0]; - expect(selection).toBeTruthy(); - - // Ensure login is visible - expect(window.getComputedStyle(selection)?.display).not.toBe("none"); - // Ensure menu is hidden - const menu = document.querySelectorAll(".comfy-menu")?.[0]; - expect(window.getComputedStyle(menu)?.display).toBe("none"); - - const isCreate = await onShown(selection); - - // Submit form - selection.querySelectorAll("form")[0].submit(); - await new Promise(process.nextTick); // wait for promises to resolve - - // Wait for start - const s = await starting; - - // Ensure login is removed - expect(document.querySelectorAll("#comfy-user-selection")).toHaveLength(0); - expect(window.getComputedStyle(menu)?.display).not.toBe("none"); - - // Ensure settings + templates are saved - const { api } = require("../../web/scripts/api"); - expect(api.createUser).toHaveBeenCalledTimes(+isCreate); - expect(api.storeSettings).toHaveBeenCalledTimes(+isCreate); - expect(api.storeUserData).toHaveBeenCalledTimes(+isCreate); - if (isCreate) { - expect(api.storeUserData).toHaveBeenCalledWith("comfy.templates.json", null, { stringify: false }); - expect(s.app.isNewUserSession).toBeTruthy(); - } else { - expect(s.app.isNewUserSession).toBeFalsy(); - } - - return { users, selection, ...s }; - } - - it("allows user creation if no users", async () => { - const { users } = await testUserScreen((selection) => { - // Ensure we have no users flag added - expect(selection.classList.contains("no-users")).toBeTruthy(); - - // Enter a username - const input = selection.getElementsByTagName("input")[0]; - input.focus(); - input.value = "Test User"; - - return true; - }); - - expect(users).toStrictEqual({ - "Test User!": "Test User", - }); - - expect(localStorage["Comfy.userId"]).toBe("Test User!"); - expect(localStorage["Comfy.userName"]).toBe("Test User"); - }); - it("allows user creation if no current user but other users", async () => { - const users = { - "Test User 2!": "Test User 2", - }; - - await testUserScreen((selection) => { - expect(selection.classList.contains("no-users")).toBeFalsy(); - - // Enter a username - const input = selection.getElementsByTagName("input")[0]; - input.focus(); - input.value = "Test User 3"; - return true; - }, users); - - expect(users).toStrictEqual({ - "Test User 2!": "Test User 2", - "Test User 3!": "Test User 3", - }); - - expect(localStorage["Comfy.userId"]).toBe("Test User 3!"); - expect(localStorage["Comfy.userName"]).toBe("Test User 3"); - }); - it("allows user selection if no current user but other users", async () => { - const users = { - "A!": "A", - "B!": "B", - "C!": "C", - }; - - await testUserScreen((selection) => { - expect(selection.classList.contains("no-users")).toBeFalsy(); - - // Check user list - const select = selection.getElementsByTagName("select")[0]; - const options = select.getElementsByTagName("option"); - expect( - [...options] - .filter((o) => !o.disabled) - .reduce((p, n) => { - p[n.getAttribute("value")] = n.textContent; - return p; - }, {}) - ).toStrictEqual(users); - - // Select an option - select.focus(); - select.value = options[2].value; - - return false; - }, users); - - expect(users).toStrictEqual(users); - - expect(localStorage["Comfy.userId"]).toBe("B!"); - expect(localStorage["Comfy.userName"]).toBe("B"); - }); - it("doesnt show user screen if current user", async () => { - const starting = start({ - resetEnv: true, - userConfig: { - storage: "server", - users: { - "User!": "User", - }, - }, - localStorage: { - "Comfy.userId": "User!", - "Comfy.userName": "User", - }, - }); - await new Promise(process.nextTick); // wait for promises to resolve - - expectNoUserScreen(); - - await starting; - }); - it("allows user switching", async () => { - const { app } = await start({ - resetEnv: true, - userConfig: { - storage: "server", - users: { - "User!": "User", - }, - }, - localStorage: { - "Comfy.userId": "User!", - "Comfy.userName": "User", - }, - }); - - // cant actually test switching user easily but can check the setting is present - expect(app.ui.settings.settingsLookup["Comfy.SwitchUser"]).toBeTruthy(); - }); - }); - describe("single-user", () => { - it("doesnt show user creation if no default user", async () => { - const { app } = await start({ - resetEnv: true, - userConfig: { migrated: false, storage: "server" }, - }); - expectNoUserScreen(); - - // It should store the settings - const { api } = require("../../web/scripts/api"); - expect(api.storeSettings).toHaveBeenCalledTimes(1); - expect(api.storeUserData).toHaveBeenCalledTimes(1); - expect(api.storeUserData).toHaveBeenCalledWith("comfy.templates.json", null, { stringify: false }); - expect(app.isNewUserSession).toBeTruthy(); - }); - it("doesnt show user creation if default user", async () => { - const { app } = await start({ - resetEnv: true, - userConfig: { migrated: true, storage: "server" }, - }); - expectNoUserScreen(); - - // It should store the settings - const { api } = require("../../web/scripts/api"); - expect(api.storeSettings).toHaveBeenCalledTimes(0); - expect(api.storeUserData).toHaveBeenCalledTimes(0); - expect(app.isNewUserSession).toBeFalsy(); - }); - it("doesnt allow user switching", async () => { - const { app } = await start({ - resetEnv: true, - userConfig: { migrated: true, storage: "server" }, - }); - expectNoUserScreen(); - - expect(app.ui.settings.settingsLookup["Comfy.SwitchUser"]).toBeFalsy(); - }); - }); - describe("browser-user", () => { - it("doesnt show user creation if no default user", async () => { - const { app } = await start({ - resetEnv: true, - userConfig: { migrated: false, storage: "browser" }, - }); - expectNoUserScreen(); - - // It should store the settings - const { api } = require("../../web/scripts/api"); - expect(api.storeSettings).toHaveBeenCalledTimes(0); - expect(api.storeUserData).toHaveBeenCalledTimes(0); - expect(app.isNewUserSession).toBeFalsy(); - }); - it("doesnt show user creation if default user", async () => { - const { app } = await start({ - resetEnv: true, - userConfig: { migrated: true, storage: "server" }, - }); - expectNoUserScreen(); - - // It should store the settings - const { api } = require("../../web/scripts/api"); - expect(api.storeSettings).toHaveBeenCalledTimes(0); - expect(api.storeUserData).toHaveBeenCalledTimes(0); - expect(app.isNewUserSession).toBeFalsy(); - }); - it("doesnt allow user switching", async () => { - const { app } = await start({ - resetEnv: true, - userConfig: { migrated: true, storage: "browser" }, - }); - expectNoUserScreen(); - - expect(app.ui.settings.settingsLookup["Comfy.SwitchUser"]).toBeFalsy(); - }); - }); -}); diff --git a/tests-ui/tests/widgetInputs.test.js b/tests-ui/tests/widgetInputs.test.js deleted file mode 100644 index 67e3fa341..000000000 --- a/tests-ui/tests/widgetInputs.test.js +++ /dev/null @@ -1,557 +0,0 @@ -// @ts-check -/// - -const { - start, - makeNodeDef, - checkBeforeAndAfterReload, - assertNotNullOrUndefined, - createDefaultWorkflow, -} = require("../utils"); -const lg = require("../utils/litegraph"); - -/** - * @typedef { import("../utils/ezgraph") } Ez - * @typedef { ReturnType["ez"] } EzNodeFactory - */ - -/** - * @param { EzNodeFactory } ez - * @param { InstanceType } graph - * @param { InstanceType } input - * @param { string } widgetType - * @param { number } controlWidgetCount - * @returns - */ -async function connectPrimitiveAndReload(ez, graph, input, widgetType, controlWidgetCount = 0) { - // Connect to primitive and ensure its still connected after - let primitive = ez.PrimitiveNode(); - primitive.outputs[0].connectTo(input); - - await checkBeforeAndAfterReload(graph, async () => { - primitive = graph.find(primitive); - let { connections } = primitive.outputs[0]; - expect(connections).toHaveLength(1); - expect(connections[0].targetNode.id).toBe(input.node.node.id); - - // Ensure widget is correct type - const valueWidget = primitive.widgets.value; - expect(valueWidget.widget.type).toBe(widgetType); - - // Check if control_after_generate should be added - if (controlWidgetCount) { - const controlWidget = primitive.widgets.control_after_generate; - expect(controlWidget.widget.type).toBe("combo"); - if (widgetType === "combo") { - const filterWidget = primitive.widgets.control_filter_list; - expect(filterWidget.widget.type).toBe("string"); - } - } - - // Ensure we dont have other widgets - expect(primitive.node.widgets).toHaveLength(1 + controlWidgetCount); - }); - - return primitive; -} - -describe("widget inputs", () => { - beforeEach(() => { - lg.setup(global); - }); - - afterEach(() => { - lg.teardown(global); - }); - - [ - { name: "int", type: "INT", widget: "number", control: 1 }, - { name: "float", type: "FLOAT", widget: "number", control: 1 }, - { name: "text", type: "STRING" }, - { - name: "customtext", - type: "STRING", - opt: { multiline: true }, - }, - { name: "toggle", type: "BOOLEAN" }, - { name: "combo", type: ["a", "b", "c"], control: 2 }, - ].forEach((c) => { - test(`widget conversion + primitive works on ${c.name}`, async () => { - const { ez, graph } = await start({ - mockNodeDefs: makeNodeDef("TestNode", { [c.name]: [c.type, c.opt ?? {}] }), - }); - - // Create test node and convert to input - const n = ez.TestNode(); - const w = n.widgets[c.name]; - w.convertToInput(); - expect(w.isConvertedToInput).toBeTruthy(); - const input = w.getConvertedInput(); - expect(input).toBeTruthy(); - - // @ts-ignore : input is valid here - await connectPrimitiveAndReload(ez, graph, input, c.widget ?? c.name, c.control); - }); - }); - - test("converted widget works after reload", async () => { - const { ez, graph } = await start(); - let n = ez.CheckpointLoaderSimple(); - - const inputCount = n.inputs.length; - - // Convert ckpt name to an input - n.widgets.ckpt_name.convertToInput(); - expect(n.widgets.ckpt_name.isConvertedToInput).toBeTruthy(); - expect(n.inputs.ckpt_name).toBeTruthy(); - expect(n.inputs.length).toEqual(inputCount + 1); - - // Convert back to widget and ensure input is removed - n.widgets.ckpt_name.convertToWidget(); - expect(n.widgets.ckpt_name.isConvertedToInput).toBeFalsy(); - expect(n.inputs.ckpt_name).toBeFalsy(); - expect(n.inputs.length).toEqual(inputCount); - - // Convert again and reload the graph to ensure it maintains state - n.widgets.ckpt_name.convertToInput(); - expect(n.inputs.length).toEqual(inputCount + 1); - - const primitive = await connectPrimitiveAndReload(ez, graph, n.inputs.ckpt_name, "combo", 2); - - // Disconnect & reconnect - primitive.outputs[0].connections[0].disconnect(); - let { connections } = primitive.outputs[0]; - expect(connections).toHaveLength(0); - - primitive.outputs[0].connectTo(n.inputs.ckpt_name); - ({ connections } = primitive.outputs[0]); - expect(connections).toHaveLength(1); - expect(connections[0].targetNode.id).toBe(n.node.id); - - // Convert back to widget and ensure input is removed - n.widgets.ckpt_name.convertToWidget(); - expect(n.widgets.ckpt_name.isConvertedToInput).toBeFalsy(); - expect(n.inputs.ckpt_name).toBeFalsy(); - expect(n.inputs.length).toEqual(inputCount); - }); - - test("converted widget works on clone", async () => { - const { graph, ez } = await start(); - let n = ez.CheckpointLoaderSimple(); - - // Convert the widget to an input - n.widgets.ckpt_name.convertToInput(); - expect(n.widgets.ckpt_name.isConvertedToInput).toBeTruthy(); - - // Clone the node - n.menu["Clone"].call(); - expect(graph.nodes).toHaveLength(2); - const clone = graph.nodes[1]; - expect(clone.id).not.toEqual(n.id); - - // Ensure the clone has an input - expect(clone.widgets.ckpt_name.isConvertedToInput).toBeTruthy(); - expect(clone.inputs.ckpt_name).toBeTruthy(); - - // Ensure primitive connects to both nodes - let primitive = ez.PrimitiveNode(); - primitive.outputs[0].connectTo(n.inputs.ckpt_name); - primitive.outputs[0].connectTo(clone.inputs.ckpt_name); - expect(primitive.outputs[0].connections).toHaveLength(2); - - // Convert back to widget and ensure input is removed - clone.widgets.ckpt_name.convertToWidget(); - expect(clone.widgets.ckpt_name.isConvertedToInput).toBeFalsy(); - expect(clone.inputs.ckpt_name).toBeFalsy(); - }); - - test("shows missing node error on custom node with converted input", async () => { - const { graph } = await start(); - - const dialogShow = jest.spyOn(graph.app.ui.dialog, "show"); - - await graph.app.loadGraphData({ - last_node_id: 3, - last_link_id: 4, - nodes: [ - { - id: 1, - type: "TestNode", - pos: [41.87329101561909, 389.7381480823742], - size: { 0: 220, 1: 374 }, - flags: {}, - order: 1, - mode: 0, - inputs: [{ name: "test", type: "FLOAT", link: 4, widget: { name: "test" }, slot_index: 0 }], - outputs: [], - properties: { "Node name for S&R": "TestNode" }, - widgets_values: [1], - }, - { - id: 3, - type: "PrimitiveNode", - pos: [-312, 433], - size: { 0: 210, 1: 82 }, - flags: {}, - order: 0, - mode: 0, - outputs: [{ links: [4], widget: { name: "test" } }], - title: "test", - properties: {}, - }, - ], - links: [[4, 3, 0, 1, 6, "FLOAT"]], - groups: [], - config: {}, - extra: {}, - version: 0.4, - }); - - expect(dialogShow).toBeCalledTimes(1); - expect(dialogShow.mock.calls[0][0].innerHTML).toContain("the following node types were not found"); - expect(dialogShow.mock.calls[0][0].innerHTML).toContain("TestNode"); - }); - - test("defaultInput widgets can be converted back to inputs", async () => { - const { graph, ez } = await start({ - mockNodeDefs: makeNodeDef("TestNode", { example: ["INT", { defaultInput: true }] }), - }); - - // Create test node and ensure it starts as an input - let n = ez.TestNode(); - let w = n.widgets.example; - expect(w.isConvertedToInput).toBeTruthy(); - let input = w.getConvertedInput(); - expect(input).toBeTruthy(); - - // Ensure it can be converted to - w.convertToWidget(); - expect(w.isConvertedToInput).toBeFalsy(); - expect(n.inputs.length).toEqual(0); - // and from - w.convertToInput(); - expect(w.isConvertedToInput).toBeTruthy(); - input = w.getConvertedInput(); - - // Reload and ensure it still only has 1 converted widget - if (!assertNotNullOrUndefined(input)) return; - - await connectPrimitiveAndReload(ez, graph, input, "number", 1); - n = graph.find(n); - expect(n.widgets).toHaveLength(1); - w = n.widgets.example; - expect(w.isConvertedToInput).toBeTruthy(); - - // Convert back to widget and ensure it is still a widget after reload - w.convertToWidget(); - await graph.reload(); - n = graph.find(n); - expect(n.widgets).toHaveLength(1); - expect(n.widgets[0].isConvertedToInput).toBeFalsy(); - expect(n.inputs.length).toEqual(0); - }); - - test("forceInput widgets can not be converted back to inputs", async () => { - const { graph, ez } = await start({ - mockNodeDefs: makeNodeDef("TestNode", { example: ["INT", { forceInput: true }] }), - }); - - // Create test node and ensure it starts as an input - let n = ez.TestNode(); - let w = n.widgets.example; - expect(w.isConvertedToInput).toBeTruthy(); - const input = w.getConvertedInput(); - expect(input).toBeTruthy(); - - // Convert to widget should error - expect(() => w.convertToWidget()).toThrow(); - - // Reload and ensure it still only has 1 converted widget - if (assertNotNullOrUndefined(input)) { - await connectPrimitiveAndReload(ez, graph, input, "number", 1); - n = graph.find(n); - expect(n.widgets).toHaveLength(1); - expect(n.widgets.example.isConvertedToInput).toBeTruthy(); - } - }); - - test("primitive can connect to matching combos on converted widgets", async () => { - const { ez } = await start({ - mockNodeDefs: { - ...makeNodeDef("TestNode1", { example: [["A", "B", "C"], { forceInput: true }] }), - ...makeNodeDef("TestNode2", { example: [["A", "B", "C"], { forceInput: true }] }), - }, - }); - - const n1 = ez.TestNode1(); - const n2 = ez.TestNode2(); - const p = ez.PrimitiveNode(); - p.outputs[0].connectTo(n1.inputs[0]); - p.outputs[0].connectTo(n2.inputs[0]); - expect(p.outputs[0].connections).toHaveLength(2); - const valueWidget = p.widgets.value; - expect(valueWidget.widget.type).toBe("combo"); - expect(valueWidget.widget.options.values).toEqual(["A", "B", "C"]); - }); - - test("primitive can not connect to non matching combos on converted widgets", async () => { - const { ez } = await start({ - mockNodeDefs: { - ...makeNodeDef("TestNode1", { example: [["A", "B", "C"], { forceInput: true }] }), - ...makeNodeDef("TestNode2", { example: [["A", "B"], { forceInput: true }] }), - }, - }); - - const n1 = ez.TestNode1(); - const n2 = ez.TestNode2(); - const p = ez.PrimitiveNode(); - p.outputs[0].connectTo(n1.inputs[0]); - expect(() => p.outputs[0].connectTo(n2.inputs[0])).toThrow(); - expect(p.outputs[0].connections).toHaveLength(1); - }); - - test("combo output can not connect to non matching combos list input", async () => { - const { ez } = await start({ - mockNodeDefs: { - ...makeNodeDef("TestNode1", {}, [["A", "B"]]), - ...makeNodeDef("TestNode2", { example: [["A", "B"], { forceInput: true }] }), - ...makeNodeDef("TestNode3", { example: [["A", "B", "C"], { forceInput: true }] }), - }, - }); - - const n1 = ez.TestNode1(); - const n2 = ez.TestNode2(); - const n3 = ez.TestNode3(); - - n1.outputs[0].connectTo(n2.inputs[0]); - expect(() => n1.outputs[0].connectTo(n3.inputs[0])).toThrow(); - }); - - test("combo primitive can filter list when control_after_generate called", async () => { - const { ez } = await start({ - mockNodeDefs: { - ...makeNodeDef("TestNode1", { example: [["A", "B", "C", "D", "AA", "BB", "CC", "DD", "AAA", "BBB"], {}] }), - }, - }); - - const n1 = ez.TestNode1(); - n1.widgets.example.convertToInput(); - const p = ez.PrimitiveNode(); - p.outputs[0].connectTo(n1.inputs[0]); - - const value = p.widgets.value; - const control = p.widgets.control_after_generate.widget; - const filter = p.widgets.control_filter_list; - - expect(p.widgets.length).toBe(3); - control.value = "increment"; - expect(value.value).toBe("A"); - - // Manually trigger after queue when set to increment - control["afterQueued"](); - expect(value.value).toBe("B"); - - // Filter to items containing D - filter.value = "D"; - control["afterQueued"](); - expect(value.value).toBe("D"); - control["afterQueued"](); - expect(value.value).toBe("DD"); - - // Check decrement - value.value = "BBB"; - control.value = "decrement"; - filter.value = "B"; - control["afterQueued"](); - expect(value.value).toBe("BB"); - control["afterQueued"](); - expect(value.value).toBe("B"); - - // Check regex works - value.value = "BBB"; - filter.value = "/[AB]|^C$/"; - control["afterQueued"](); - expect(value.value).toBe("AAA"); - control["afterQueued"](); - expect(value.value).toBe("BB"); - control["afterQueued"](); - expect(value.value).toBe("AA"); - control["afterQueued"](); - expect(value.value).toBe("C"); - control["afterQueued"](); - expect(value.value).toBe("B"); - control["afterQueued"](); - expect(value.value).toBe("A"); - - // Check random - control.value = "randomize"; - filter.value = "/D/"; - for (let i = 0; i < 100; i++) { - control["afterQueued"](); - expect(value.value === "D" || value.value === "DD").toBeTruthy(); - } - - // Ensure it doesnt apply when fixed - control.value = "fixed"; - value.value = "B"; - filter.value = "C"; - control["afterQueued"](); - expect(value.value).toBe("B"); - }); - - describe("reroutes", () => { - async function checkOutput(graph, values) { - expect((await graph.toPrompt()).output).toStrictEqual({ - 1: { inputs: { ckpt_name: "model1.safetensors" }, class_type: "CheckpointLoaderSimple" }, - 2: { inputs: { text: "positive", clip: ["1", 1] }, class_type: "CLIPTextEncode" }, - 3: { inputs: { text: "negative", clip: ["1", 1] }, class_type: "CLIPTextEncode" }, - 4: { - inputs: { width: values.width ?? 512, height: values.height ?? 512, batch_size: values?.batch_size ?? 1 }, - class_type: "EmptyLatentImage", - }, - 5: { - inputs: { - seed: 0, - steps: 20, - cfg: 8, - sampler_name: "euler", - scheduler: values?.scheduler ?? "normal", - denoise: 1, - model: ["1", 0], - positive: ["2", 0], - negative: ["3", 0], - latent_image: ["4", 0], - }, - class_type: "KSampler", - }, - 6: { inputs: { samples: ["5", 0], vae: ["1", 2] }, class_type: "VAEDecode" }, - 7: { - inputs: { filename_prefix: values.filename_prefix ?? "ComfyUI", images: ["6", 0] }, - class_type: "SaveImage", - }, - }); - } - - async function waitForWidget(node) { - // widgets are created slightly after the graph is ready - // hard to find an exact hook to get these so just wait for them to be ready - for (let i = 0; i < 10; i++) { - await new Promise((r) => setTimeout(r, 10)); - if (node.widgets?.value) { - return; - } - } - } - - it("can connect primitive via a reroute path to a widget input", async () => { - const { ez, graph } = await start(); - const nodes = createDefaultWorkflow(ez, graph); - - nodes.empty.widgets.width.convertToInput(); - nodes.sampler.widgets.scheduler.convertToInput(); - nodes.save.widgets.filename_prefix.convertToInput(); - - let widthReroute = ez.Reroute(); - let schedulerReroute = ez.Reroute(); - let fileReroute = ez.Reroute(); - - let widthNext = widthReroute; - let schedulerNext = schedulerReroute; - let fileNext = fileReroute; - - for (let i = 0; i < 5; i++) { - let next = ez.Reroute(); - widthNext.outputs[0].connectTo(next.inputs[0]); - widthNext = next; - - next = ez.Reroute(); - schedulerNext.outputs[0].connectTo(next.inputs[0]); - schedulerNext = next; - - next = ez.Reroute(); - fileNext.outputs[0].connectTo(next.inputs[0]); - fileNext = next; - } - - widthNext.outputs[0].connectTo(nodes.empty.inputs.width); - schedulerNext.outputs[0].connectTo(nodes.sampler.inputs.scheduler); - fileNext.outputs[0].connectTo(nodes.save.inputs.filename_prefix); - - let widthPrimitive = ez.PrimitiveNode(); - let schedulerPrimitive = ez.PrimitiveNode(); - let filePrimitive = ez.PrimitiveNode(); - - widthPrimitive.outputs[0].connectTo(widthReroute.inputs[0]); - schedulerPrimitive.outputs[0].connectTo(schedulerReroute.inputs[0]); - filePrimitive.outputs[0].connectTo(fileReroute.inputs[0]); - expect(widthPrimitive.widgets.value.value).toBe(512); - widthPrimitive.widgets.value.value = 1024; - expect(schedulerPrimitive.widgets.value.value).toBe("normal"); - schedulerPrimitive.widgets.value.value = "simple"; - expect(filePrimitive.widgets.value.value).toBe("ComfyUI"); - filePrimitive.widgets.value.value = "ComfyTest"; - - await checkBeforeAndAfterReload(graph, async () => { - widthPrimitive = graph.find(widthPrimitive); - schedulerPrimitive = graph.find(schedulerPrimitive); - filePrimitive = graph.find(filePrimitive); - await waitForWidget(filePrimitive); - expect(widthPrimitive.widgets.length).toBe(2); - expect(schedulerPrimitive.widgets.length).toBe(3); - expect(filePrimitive.widgets.length).toBe(1); - - await checkOutput(graph, { - width: 1024, - scheduler: "simple", - filename_prefix: "ComfyTest", - }); - }); - }); - it("can connect primitive via a reroute path to multiple widget inputs", async () => { - const { ez, graph } = await start(); - const nodes = createDefaultWorkflow(ez, graph); - - nodes.empty.widgets.width.convertToInput(); - nodes.empty.widgets.height.convertToInput(); - nodes.empty.widgets.batch_size.convertToInput(); - - let reroute = ez.Reroute(); - let prevReroute = reroute; - for (let i = 0; i < 5; i++) { - const next = ez.Reroute(); - prevReroute.outputs[0].connectTo(next.inputs[0]); - prevReroute = next; - } - - const r1 = ez.Reroute(prevReroute.outputs[0]); - const r2 = ez.Reroute(prevReroute.outputs[0]); - const r3 = ez.Reroute(r2.outputs[0]); - const r4 = ez.Reroute(r2.outputs[0]); - - r1.outputs[0].connectTo(nodes.empty.inputs.width); - r3.outputs[0].connectTo(nodes.empty.inputs.height); - r4.outputs[0].connectTo(nodes.empty.inputs.batch_size); - - let primitive = ez.PrimitiveNode(); - primitive.outputs[0].connectTo(reroute.inputs[0]); - expect(primitive.widgets.value.value).toBe(1); - primitive.widgets.value.value = 64; - - await checkBeforeAndAfterReload(graph, async (r) => { - primitive = graph.find(primitive); - await waitForWidget(primitive); - - // Ensure widget configs are merged - expect(primitive.widgets.value.widget.options?.min).toBe(16); // width/height min - expect(primitive.widgets.value.widget.options?.max).toBe(4096); // batch max - expect(primitive.widgets.value.widget.options?.step).toBe(80); // width/height step * 10 - - await checkOutput(graph, { - width: 64, - height: 64, - batch_size: 64, - }); - }); - }); - }); -}); diff --git a/tests-ui/utils/ezgraph.js b/tests-ui/utils/ezgraph.js deleted file mode 100644 index 97be7aa72..000000000 --- a/tests-ui/utils/ezgraph.js +++ /dev/null @@ -1,452 +0,0 @@ -// @ts-check -/// - -/** - * @typedef { import("../../web/scripts/app")["app"] } app - * @typedef { import("../../web/types/litegraph") } LG - * @typedef { import("../../web/types/litegraph").IWidget } IWidget - * @typedef { import("../../web/types/litegraph").ContextMenuItem } ContextMenuItem - * @typedef { import("../../web/types/litegraph").INodeInputSlot } INodeInputSlot - * @typedef { import("../../web/types/litegraph").INodeOutputSlot } INodeOutputSlot - * @typedef { InstanceType & { widgets?: Array } } LGNode - * @typedef { (...args: EzOutput[] | [...EzOutput[], Record]) => EzNode } EzNodeFactory - */ - -export class EzConnection { - /** @type { app } */ - app; - /** @type { InstanceType } */ - link; - - get originNode() { - return new EzNode(this.app, this.app.graph.getNodeById(this.link.origin_id)); - } - - get originOutput() { - return this.originNode.outputs[this.link.origin_slot]; - } - - get targetNode() { - return new EzNode(this.app, this.app.graph.getNodeById(this.link.target_id)); - } - - get targetInput() { - return this.targetNode.inputs[this.link.target_slot]; - } - - /** - * @param { app } app - * @param { InstanceType } link - */ - constructor(app, link) { - this.app = app; - this.link = link; - } - - disconnect() { - this.targetInput.disconnect(); - } -} - -export class EzSlot { - /** @type { EzNode } */ - node; - /** @type { number } */ - index; - - /** - * @param { EzNode } node - * @param { number } index - */ - constructor(node, index) { - this.node = node; - this.index = index; - } -} - -export class EzInput extends EzSlot { - /** @type { INodeInputSlot } */ - input; - - /** - * @param { EzNode } node - * @param { number } index - * @param { INodeInputSlot } input - */ - constructor(node, index, input) { - super(node, index); - this.input = input; - } - - get connection() { - const link = this.node.node.inputs?.[this.index]?.link; - if (link == null) { - return null; - } - return new EzConnection(this.node.app, this.node.app.graph.links[link]); - } - - disconnect() { - this.node.node.disconnectInput(this.index); - } -} - -export class EzOutput extends EzSlot { - /** @type { INodeOutputSlot } */ - output; - - /** - * @param { EzNode } node - * @param { number } index - * @param { INodeOutputSlot } output - */ - constructor(node, index, output) { - super(node, index); - this.output = output; - } - - get connections() { - return (this.node.node.outputs?.[this.index]?.links ?? []).map( - (l) => new EzConnection(this.node.app, this.node.app.graph.links[l]) - ); - } - - /** - * @param { EzInput } input - */ - connectTo(input) { - if (!input) throw new Error("Invalid input"); - - /** - * @type { LG["LLink"] | null } - */ - const link = this.node.node.connect(this.index, input.node.node, input.index); - if (!link) { - const inp = input.input; - const inName = inp.name || inp.label || inp.type; - throw new Error( - `Connecting from ${input.node.node.type}#${input.node.id}[${inName}#${input.index}] -> ${this.node.node.type}#${this.node.id}[${ - this.output.name ?? this.output.type - }#${this.index}] failed.` - ); - } - return link; - } -} - -export class EzNodeMenuItem { - /** @type { EzNode } */ - node; - /** @type { number } */ - index; - /** @type { ContextMenuItem } */ - item; - - /** - * @param { EzNode } node - * @param { number } index - * @param { ContextMenuItem } item - */ - constructor(node, index, item) { - this.node = node; - this.index = index; - this.item = item; - } - - call(selectNode = true) { - if (!this.item?.callback) throw new Error(`Menu Item ${this.item?.content ?? "[null]"} has no callback.`); - if (selectNode) { - this.node.select(); - } - return this.item.callback.call(this.node.node, undefined, undefined, undefined, undefined, this.node.node); - } -} - -export class EzWidget { - /** @type { EzNode } */ - node; - /** @type { number } */ - index; - /** @type { IWidget } */ - widget; - - /** - * @param { EzNode } node - * @param { number } index - * @param { IWidget } widget - */ - constructor(node, index, widget) { - this.node = node; - this.index = index; - this.widget = widget; - } - - get value() { - return this.widget.value; - } - - set value(v) { - this.widget.value = v; - this.widget.callback?.call?.(this.widget, v) - } - - get isConvertedToInput() { - // @ts-ignore : this type is valid for converted widgets - return this.widget.type === "converted-widget"; - } - - getConvertedInput() { - if (!this.isConvertedToInput) throw new Error(`Widget ${this.widget.name} is not converted to input.`); - - return this.node.inputs.find((inp) => inp.input["widget"]?.name === this.widget.name); - } - - convertToWidget() { - if (!this.isConvertedToInput) - throw new Error(`Widget ${this.widget.name} cannot be converted as it is already a widget.`); - var menu = this.node.menu["Convert Input to Widget"].item.submenu.options; - var index = menu.findIndex(a => a.content == `Convert ${this.widget.name} to widget`); - menu[index].callback.call(); - } - - convertToInput() { - if (this.isConvertedToInput) - throw new Error(`Widget ${this.widget.name} cannot be converted as it is already an input.`); - var menu = this.node.menu["Convert Widget to Input"].item.submenu.options; - var index = menu.findIndex(a => a.content == `Convert ${this.widget.name} to input`); - menu[index].callback.call(); - } -} - -export class EzNode { - /** @type { app } */ - app; - /** @type { LGNode } */ - node; - - /** - * @param { app } app - * @param { LGNode } node - */ - constructor(app, node) { - this.app = app; - this.node = node; - } - - get id() { - return this.node.id; - } - - get inputs() { - return this.#makeLookupArray("inputs", "name", EzInput); - } - - get outputs() { - return this.#makeLookupArray("outputs", "name", EzOutput); - } - - get widgets() { - return this.#makeLookupArray("widgets", "name", EzWidget); - } - - get menu() { - return this.#makeLookupArray(() => this.app.canvas.getNodeMenuOptions(this.node), "content", EzNodeMenuItem); - } - - get isRemoved() { - return !this.app.graph.getNodeById(this.id); - } - - select(addToSelection = false) { - this.app.canvas.selectNode(this.node, addToSelection); - } - - // /** - // * @template { "inputs" | "outputs" } T - // * @param { T } type - // * @returns { Record & (type extends "inputs" ? EzInput [] : EzOutput[]) } - // */ - // #getSlotItems(type) { - // // @ts-ignore : these items are correct - // return (this.node[type] ?? []).reduce((p, s, i) => { - // if (s.name in p) { - // throw new Error(`Unable to store input ${s.name} on array as name conflicts.`); - // } - // // @ts-ignore - // p.push((p[s.name] = new (type === "inputs" ? EzInput : EzOutput)(this, i, s))); - // return p; - // }, Object.assign([], { $: this })); - // } - - /** - * @template { { new(node: EzNode, index: number, obj: any): any } } T - * @param { "inputs" | "outputs" | "widgets" | (() => Array) } nodeProperty - * @param { string } nameProperty - * @param { T } ctor - * @returns { Record> & Array> } - */ - #makeLookupArray(nodeProperty, nameProperty, ctor) { - const items = typeof nodeProperty === "function" ? nodeProperty() : this.node[nodeProperty]; - // @ts-ignore - return (items ?? []).reduce((p, s, i) => { - if (!s) return p; - - const name = s[nameProperty]; - const item = new ctor(this, i, s); - // @ts-ignore - p.push(item); - if (name) { - // @ts-ignore - if (name in p) { - throw new Error(`Unable to store ${nodeProperty} ${name} on array as name conflicts.`); - } - } - // @ts-ignore - p[name] = item; - return p; - }, Object.assign([], { $: this })); - } -} - -export class EzGraph { - /** @type { app } */ - app; - - /** - * @param { app } app - */ - constructor(app) { - this.app = app; - } - - get nodes() { - return this.app.graph._nodes.map((n) => new EzNode(this.app, n)); - } - - clear() { - this.app.graph.clear(); - } - - arrange() { - this.app.graph.arrange(); - } - - stringify() { - return JSON.stringify(this.app.graph.serialize(), undefined); - } - - /** - * @param { number | LGNode | EzNode } obj - * @returns { EzNode } - */ - find(obj) { - let match; - let id; - if (typeof obj === "number") { - id = obj; - } else { - id = obj.id; - } - - match = this.app.graph.getNodeById(id); - - if (!match) { - throw new Error(`Unable to find node with ID ${id}.`); - } - - return new EzNode(this.app, match); - } - - /** - * @returns { Promise } - */ - reload() { - const graph = JSON.parse(JSON.stringify(this.app.graph.serialize())); - return new Promise((r) => { - this.app.graph.clear(); - setTimeout(async () => { - await this.app.loadGraphData(graph); - r(); - }, 10); - }); - } - - /** - * @returns { Promise<{ - * workflow: {}, - * output: Record - * }>}> } - */ - toPrompt() { - // @ts-ignore - return this.app.graphToPrompt(); - } -} - -export const Ez = { - /** - * Quickly build and interact with a ComfyUI graph - * @example - * const { ez, graph } = Ez.graph(app); - * graph.clear(); - * const [model, clip, vae] = ez.CheckpointLoaderSimple().outputs; - * const [pos] = ez.CLIPTextEncode(clip, { text: "positive" }).outputs; - * const [neg] = ez.CLIPTextEncode(clip, { text: "negative" }).outputs; - * const [latent] = ez.KSampler(model, pos, neg, ...ez.EmptyLatentImage().outputs).outputs; - * const [image] = ez.VAEDecode(latent, vae).outputs; - * const saveNode = ez.SaveImage(image); - * console.log(saveNode); - * graph.arrange(); - * @param { app } app - * @param { LG["LiteGraph"] } LiteGraph - * @param { LG["LGraphCanvas"] } LGraphCanvas - * @param { boolean } clearGraph - * @returns { { graph: EzGraph, ez: Record } } - */ - graph(app, LiteGraph = window["LiteGraph"], LGraphCanvas = window["LGraphCanvas"], clearGraph = true) { - // Always set the active canvas so things work - LGraphCanvas.active_canvas = app.canvas; - - if (clearGraph) { - app.graph.clear(); - } - - // @ts-ignore : this proxy handles utility methods & node creation - const factory = new Proxy( - {}, - { - get(_, p) { - if (typeof p !== "string") throw new Error("Invalid node"); - const node = LiteGraph.createNode(p); - if (!node) throw new Error(`Unknown node "${p}"`); - app.graph.add(node); - - /** - * @param {Parameters} args - */ - return function (...args) { - const ezNode = new EzNode(app, node); - const inputs = ezNode.inputs; - - let slot = 0; - for (const arg of args) { - if (arg instanceof EzOutput) { - arg.connectTo(inputs[slot++]); - } else { - for (const k in arg) { - ezNode.widgets[k].value = arg[k]; - } - } - } - - return ezNode; - }; - }, - } - ); - - return { graph: new EzGraph(app), ez: factory }; - }, -}; diff --git a/tests-ui/utils/index.js b/tests-ui/utils/index.js deleted file mode 100644 index 74b6cf93d..000000000 --- a/tests-ui/utils/index.js +++ /dev/null @@ -1,129 +0,0 @@ -const { mockApi } = require("./setup"); -const { Ez } = require("./ezgraph"); -const lg = require("./litegraph"); -const fs = require("fs"); -const path = require("path"); - -const html = fs.readFileSync(path.resolve(__dirname, "../../web/index.html")) - -/** - * - * @param { Parameters[0] & { - * resetEnv?: boolean, - * preSetup?(app): Promise, - * localStorage?: Record - * } } config - * @returns - */ -export async function start(config = {}) { - if(config.resetEnv) { - jest.resetModules(); - jest.resetAllMocks(); - lg.setup(global); - localStorage.clear(); - sessionStorage.clear(); - } - - Object.assign(localStorage, config.localStorage ?? {}); - document.body.innerHTML = html; - - mockApi(config); - const { app } = require("../../web/scripts/app"); - config.preSetup?.(app); - await app.setup(); - - return { ...Ez.graph(app, global["LiteGraph"], global["LGraphCanvas"]), app }; -} - -/** - * @param { ReturnType["graph"] } graph - * @param { (hasReloaded: boolean) => (Promise | void) } cb - */ -export async function checkBeforeAndAfterReload(graph, cb) { - await cb(false); - await graph.reload(); - await cb(true); -} - -/** - * @param { string } name - * @param { Record } input - * @param { (string | string[])[] | Record } output - * @returns { Record } - */ -export function makeNodeDef(name, input, output = {}) { - const nodeDef = { - name, - category: "test", - output: [], - output_name: [], - output_is_list: [], - input: { - required: {}, - }, - }; - for (const k in input) { - nodeDef.input.required[k] = typeof input[k] === "string" ? [input[k], {}] : [...input[k]]; - } - if (output instanceof Array) { - output = output.reduce((p, c) => { - p[c] = c; - return p; - }, {}); - } - for (const k in output) { - nodeDef.output.push(output[k]); - nodeDef.output_name.push(k); - nodeDef.output_is_list.push(false); - } - - return { [name]: nodeDef }; -} - -/** -/** - * @template { any } T - * @param { T } x - * @returns { x is Exclude } - */ -export function assertNotNullOrUndefined(x) { - expect(x).not.toEqual(null); - expect(x).not.toEqual(undefined); - return true; -} - -/** - * - * @param { ReturnType["ez"] } ez - * @param { ReturnType["graph"] } graph - */ -export function createDefaultWorkflow(ez, graph) { - graph.clear(); - const ckpt = ez.CheckpointLoaderSimple(); - - const pos = ez.CLIPTextEncode(ckpt.outputs.CLIP, { text: "positive" }); - const neg = ez.CLIPTextEncode(ckpt.outputs.CLIP, { text: "negative" }); - - const empty = ez.EmptyLatentImage(); - const sampler = ez.KSampler( - ckpt.outputs.MODEL, - pos.outputs.CONDITIONING, - neg.outputs.CONDITIONING, - empty.outputs.LATENT - ); - - const decode = ez.VAEDecode(sampler.outputs.LATENT, ckpt.outputs.VAE); - const save = ez.SaveImage(decode.outputs.IMAGE); - graph.arrange(); - - return { ckpt, pos, neg, empty, sampler, decode, save }; -} - -export async function getNodeDefs() { - const { api } = require("../../web/scripts/api"); - return api.getNodeDefs(); -} - -export async function getNodeDef(nodeId) { - return (await getNodeDefs())[nodeId]; -} \ No newline at end of file diff --git a/tests-ui/utils/litegraph.js b/tests-ui/utils/litegraph.js deleted file mode 100644 index 777f8c3ba..000000000 --- a/tests-ui/utils/litegraph.js +++ /dev/null @@ -1,36 +0,0 @@ -const fs = require("fs"); -const path = require("path"); -const { nop } = require("../utils/nopProxy"); - -function forEachKey(cb) { - for (const k of [ - "LiteGraph", - "LGraph", - "LLink", - "LGraphNode", - "LGraphGroup", - "DragAndScale", - "LGraphCanvas", - "ContextMenu", - ]) { - cb(k); - } -} - -export function setup(ctx) { - const lg = fs.readFileSync(path.resolve("../web/lib/litegraph.core.js"), "utf-8"); - const globalTemp = {}; - (function (console) { - eval(lg); - }).call(globalTemp, nop); - - forEachKey((k) => (ctx[k] = globalTemp[k])); - require(path.resolve("../web/lib/litegraph.extensions.js")); -} - -export function teardown(ctx) { - forEachKey((k) => delete ctx[k]); - - // Clear document after each run - document.getElementsByTagName("html")[0].innerHTML = ""; -} diff --git a/tests-ui/utils/nopProxy.js b/tests-ui/utils/nopProxy.js deleted file mode 100644 index 2502d9d03..000000000 --- a/tests-ui/utils/nopProxy.js +++ /dev/null @@ -1,6 +0,0 @@ -export const nop = new Proxy(function () {}, { - get: () => nop, - set: () => true, - apply: () => nop, - construct: () => nop, -}); diff --git a/tests-ui/utils/setup.js b/tests-ui/utils/setup.js deleted file mode 100644 index 3a6d69b72..000000000 --- a/tests-ui/utils/setup.js +++ /dev/null @@ -1,82 +0,0 @@ -require("../../web/scripts/api"); - -const fs = require("fs"); -const path = require("path"); -function* walkSync(dir) { - const files = fs.readdirSync(dir, { withFileTypes: true }); - for (const file of files) { - if (file.isDirectory()) { - yield* walkSync(path.join(dir, file.name)); - } else { - yield path.join(dir, file.name); - } - } -} - -/** - * @typedef { import("../../web/types/comfy").ComfyObjectInfo } ComfyObjectInfo - */ - -/** - * @param {{ - * mockExtensions?: string[], - * mockNodeDefs?: Record, -* settings?: Record -* userConfig?: {storage: "server" | "browser", users?: Record, migrated?: boolean }, -* userData?: Record - * }} config - */ -export function mockApi(config = {}) { - let { mockExtensions, mockNodeDefs, userConfig, settings, userData } = { - userConfig, - settings: {}, - userData: {}, - ...config, - }; - if (!mockExtensions) { - mockExtensions = Array.from(walkSync(path.resolve("../web/extensions/core"))) - .filter((x) => x.endsWith(".js")) - .map((x) => path.relative(path.resolve("../web"), x)); - } - if (!mockNodeDefs) { - mockNodeDefs = JSON.parse(fs.readFileSync(path.resolve("./data/object_info.json"))); - } - - const events = new EventTarget(); - const mockApi = { - addEventListener: events.addEventListener.bind(events), - removeEventListener: events.removeEventListener.bind(events), - dispatchEvent: events.dispatchEvent.bind(events), - getSystemStats: jest.fn(), - getExtensions: jest.fn(() => mockExtensions), - getNodeDefs: jest.fn(() => mockNodeDefs), - init: jest.fn(), - apiURL: jest.fn((x) => "../../web/" + x), - createUser: jest.fn((username) => { - if(username in userConfig.users) { - return { status: 400, json: () => "Duplicate" } - } - userConfig.users[username + "!"] = username; - return { status: 200, json: () => username + "!" } - }), - getUserConfig: jest.fn(() => userConfig ?? { storage: "browser", migrated: false }), - getSettings: jest.fn(() => settings), - storeSettings: jest.fn((v) => Object.assign(settings, v)), - getUserData: jest.fn((f) => { - if (f in userData) { - return { status: 200, json: () => userData[f] }; - } else { - return { status: 404 }; - } - }), - storeUserData: jest.fn((file, data) => { - userData[file] = data; - }), - listUserData: jest.fn(() => []) - }; - jest.mock("../../web/scripts/api", () => ({ - get api() { - return mockApi; - }, - })); -} diff --git a/tests-unit/prompt_server_test/__init__.py b/tests-unit/prompt_server_test/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests-unit/prompt_server_test/download_models_test.py b/tests-unit/prompt_server_test/download_models_test.py new file mode 100644 index 000000000..66150a468 --- /dev/null +++ b/tests-unit/prompt_server_test/download_models_test.py @@ -0,0 +1,321 @@ +import pytest +import aiohttp +from aiohttp import ClientResponse +import itertools +import os +from unittest.mock import AsyncMock, patch, MagicMock +from model_filemanager import download_model, validate_model_subdirectory, track_download_progress, create_model_path, check_file_exists, DownloadStatusType, DownloadModelStatus, validate_filename + +class AsyncIteratorMock: + """ + A mock class that simulates an asynchronous iterator. + This is used to mimic the behavior of aiohttp's content iterator. + """ + def __init__(self, seq): + # Convert the input sequence into an iterator + self.iter = iter(seq) + + def __aiter__(self): + # This method is called when 'async for' is used + return self + + async def __anext__(self): + # This method is called for each iteration in an 'async for' loop + try: + return next(self.iter) + except StopIteration: + # This is the asynchronous equivalent of StopIteration + raise StopAsyncIteration + +class ContentMock: + """ + A mock class that simulates the content attribute of an aiohttp ClientResponse. + This class provides the iter_chunked method which returns an async iterator of chunks. + """ + def __init__(self, chunks): + # Store the chunks that will be returned by the iterator + self.chunks = chunks + + def iter_chunked(self, chunk_size): + # This method mimics aiohttp's content.iter_chunked() + # For simplicity in testing, we ignore chunk_size and just return our predefined chunks + return AsyncIteratorMock(self.chunks) + +@pytest.mark.asyncio +async def test_download_model_success(): + mock_response = AsyncMock(spec=aiohttp.ClientResponse) + mock_response.status = 200 + mock_response.headers = {'Content-Length': '1000'} + # Create a mock for content that returns an async iterator directly + chunks = [b'a' * 500, b'b' * 300, b'c' * 200] + mock_response.content = ContentMock(chunks) + + mock_make_request = AsyncMock(return_value=mock_response) + mock_progress_callback = AsyncMock() + + # Mock file operations + mock_open = MagicMock() + mock_file = MagicMock() + mock_open.return_value.__enter__.return_value = mock_file + time_values = itertools.count(0, 0.1) + + with patch('model_filemanager.create_model_path', return_value=('models/checkpoints/model.sft', 'checkpoints/model.sft')), \ + patch('model_filemanager.check_file_exists', return_value=None), \ + patch('builtins.open', mock_open), \ + patch('time.time', side_effect=time_values): # Simulate time passing + + result = await download_model( + mock_make_request, + 'model.sft', + 'http://example.com/model.sft', + 'checkpoints', + mock_progress_callback + ) + + # Assert the result + assert isinstance(result, DownloadModelStatus) + assert result.message == 'Successfully downloaded model.sft' + assert result.status == 'completed' + assert result.already_existed is False + + # Check progress callback calls + assert mock_progress_callback.call_count >= 3 # At least start, one progress update, and completion + + # Check initial call + mock_progress_callback.assert_any_call( + 'checkpoints/model.sft', + DownloadModelStatus(DownloadStatusType.PENDING, 0, "Starting download of model.sft", False) + ) + + # Check final call + mock_progress_callback.assert_any_call( + 'checkpoints/model.sft', + DownloadModelStatus(DownloadStatusType.COMPLETED, 100, "Successfully downloaded model.sft", False) + ) + + # Verify file writing + mock_file.write.assert_any_call(b'a' * 500) + mock_file.write.assert_any_call(b'b' * 300) + mock_file.write.assert_any_call(b'c' * 200) + + # Verify request was made + mock_make_request.assert_called_once_with('http://example.com/model.sft') + +@pytest.mark.asyncio +async def test_download_model_url_request_failure(): + # Mock dependencies + mock_response = AsyncMock(spec=ClientResponse) + mock_response.status = 404 # Simulate a "Not Found" error + mock_get = AsyncMock(return_value=mock_response) + mock_progress_callback = AsyncMock() + + # Mock the create_model_path function + with patch('model_filemanager.create_model_path', return_value=('/mock/path/model.safetensors', 'mock/path/model.safetensors')): + # Mock the check_file_exists function to return None (file doesn't exist) + with patch('model_filemanager.check_file_exists', return_value=None): + # Call the function + result = await download_model( + mock_get, + 'model.safetensors', + 'http://example.com/model.safetensors', + 'mock_directory', + mock_progress_callback + ) + + # Assert the expected behavior + assert isinstance(result, DownloadModelStatus) + assert result.status == 'error' + assert result.message == 'Failed to download model.safetensors. Status code: 404' + assert result.already_existed is False + + # Check that progress_callback was called with the correct arguments + mock_progress_callback.assert_any_call( + 'mock_directory/model.safetensors', + DownloadModelStatus( + status=DownloadStatusType.PENDING, + progress_percentage=0, + message='Starting download of model.safetensors', + already_existed=False + ) + ) + mock_progress_callback.assert_called_with( + 'mock_directory/model.safetensors', + DownloadModelStatus( + status=DownloadStatusType.ERROR, + progress_percentage=0, + message='Failed to download model.safetensors. Status code: 404', + already_existed=False + ) + ) + + # Verify that the get method was called with the correct URL + mock_get.assert_called_once_with('http://example.com/model.safetensors') + +@pytest.mark.asyncio +async def test_download_model_invalid_model_subdirectory(): + + mock_make_request = AsyncMock() + mock_progress_callback = AsyncMock() + + + result = await download_model( + mock_make_request, + 'model.sft', + 'http://example.com/model.sft', + '../bad_path', + mock_progress_callback + ) + + # Assert the result + assert isinstance(result, DownloadModelStatus) + assert result.message == 'Invalid model subdirectory' + assert result.status == 'error' + assert result.already_existed is False + + +# For create_model_path function +def test_create_model_path(tmp_path, monkeypatch): + mock_models_dir = tmp_path / "models" + monkeypatch.setattr('folder_paths.models_dir', str(mock_models_dir)) + + model_name = "test_model.sft" + model_directory = "test_dir" + + file_path, relative_path = create_model_path(model_name, model_directory, mock_models_dir) + + assert file_path == str(mock_models_dir / model_directory / model_name) + assert relative_path == f"{model_directory}/{model_name}" + assert os.path.exists(os.path.dirname(file_path)) + + +@pytest.mark.asyncio +async def test_check_file_exists_when_file_exists(tmp_path): + file_path = tmp_path / "existing_model.sft" + file_path.touch() # Create an empty file + + mock_callback = AsyncMock() + + result = await check_file_exists(str(file_path), "existing_model.sft", mock_callback, "test/existing_model.sft") + + assert result is not None + assert result.status == "completed" + assert result.message == "existing_model.sft already exists" + assert result.already_existed is True + + mock_callback.assert_called_once_with( + "test/existing_model.sft", + DownloadModelStatus(DownloadStatusType.COMPLETED, 100, "existing_model.sft already exists", already_existed=True) + ) + +@pytest.mark.asyncio +async def test_check_file_exists_when_file_does_not_exist(tmp_path): + file_path = tmp_path / "non_existing_model.sft" + + mock_callback = AsyncMock() + + result = await check_file_exists(str(file_path), "non_existing_model.sft", mock_callback, "test/non_existing_model.sft") + + assert result is None + mock_callback.assert_not_called() + +@pytest.mark.asyncio +async def test_track_download_progress_no_content_length(): + mock_response = AsyncMock(spec=aiohttp.ClientResponse) + mock_response.headers = {} # No Content-Length header + mock_response.content.iter_chunked.return_value = AsyncIteratorMock([b'a' * 500, b'b' * 500]) + + mock_callback = AsyncMock() + mock_open = MagicMock(return_value=MagicMock()) + + with patch('builtins.open', mock_open): + result = await track_download_progress( + mock_response, '/mock/path/model.sft', 'model.sft', + mock_callback, 'models/model.sft', interval=0.1 + ) + + assert result.status == "completed" + # Check that progress was reported even without knowing the total size + mock_callback.assert_any_call( + 'models/model.sft', + DownloadModelStatus(DownloadStatusType.IN_PROGRESS, 0, "Downloading model.sft", already_existed=False) + ) + +@pytest.mark.asyncio +async def test_track_download_progress_interval(): + mock_response = AsyncMock(spec=aiohttp.ClientResponse) + mock_response.headers = {'Content-Length': '1000'} + mock_response.content.iter_chunked.return_value = AsyncIteratorMock([b'a' * 100] * 10) + + mock_callback = AsyncMock() + mock_open = MagicMock(return_value=MagicMock()) + + # Create a mock time function that returns incremental float values + mock_time = MagicMock() + mock_time.side_effect = [i * 0.5 for i in range(30)] # This should be enough for 10 chunks + + with patch('builtins.open', mock_open), \ + patch('time.time', mock_time): + await track_download_progress( + mock_response, '/mock/path/model.sft', 'model.sft', + mock_callback, 'models/model.sft', interval=1.0 + ) + + # Print out the actual call count and the arguments of each call for debugging + print(f"mock_callback was called {mock_callback.call_count} times") + for i, call in enumerate(mock_callback.call_args_list): + args, kwargs = call + print(f"Call {i + 1}: {args[1].status}, Progress: {args[1].progress_percentage:.2f}%") + + # Assert that progress was updated at least 3 times (start, at least one interval, and end) + assert mock_callback.call_count >= 3, f"Expected at least 3 calls, but got {mock_callback.call_count}" + + # Verify the first and last calls + first_call = mock_callback.call_args_list[0] + assert first_call[0][1].status == "in_progress" + # Allow for some initial progress, but it should be less than 50% + assert 0 <= first_call[0][1].progress_percentage < 50, f"First call progress was {first_call[0][1].progress_percentage}%" + + last_call = mock_callback.call_args_list[-1] + assert last_call[0][1].status == "completed" + assert last_call[0][1].progress_percentage == 100 + +def test_valid_subdirectory(): + assert validate_model_subdirectory("valid-model123") is True + +def test_subdirectory_too_long(): + assert validate_model_subdirectory("a" * 51) is False + +def test_subdirectory_with_double_dots(): + assert validate_model_subdirectory("model/../unsafe") is False + +def test_subdirectory_with_slash(): + assert validate_model_subdirectory("model/unsafe") is False + +def test_subdirectory_with_special_characters(): + assert validate_model_subdirectory("model@unsafe") is False + +def test_subdirectory_with_underscore_and_dash(): + assert validate_model_subdirectory("valid_model-name") is True + +def test_empty_subdirectory(): + assert validate_model_subdirectory("") is False + +@pytest.mark.parametrize("filename, expected", [ + ("valid_model.safetensors", True), + ("valid_model.sft", True), + ("valid model.safetensors", True), # Test with space + ("UPPERCASE_MODEL.SAFETENSORS", True), + ("model_with.multiple.dots.pt", False), + ("", False), # Empty string + ("../../../etc/passwd", False), # Path traversal attempt + ("/etc/passwd", False), # Absolute path + ("\\windows\\system32\\config\\sam", False), # Windows path + (".hidden_file.pt", False), # Hidden file + ("invalid.ckpt", False), # Invalid character + ("invalid?.ckpt", False), # Another invalid character + ("very" * 100 + ".safetensors", False), # Too long filename + ("\nmodel_with_newline.pt", False), # Newline character + ("model_with_emoji😊.pt", False), # Emoji in filename +]) +def test_validate_filename(filename, expected): + assert validate_filename(filename) == expected diff --git a/tests-unit/requirements.txt b/tests-unit/requirements.txt index 0587502f8..d70d00f4b 100644 --- a/tests-unit/requirements.txt +++ b/tests-unit/requirements.txt @@ -1 +1,3 @@ pytest>=7.8.0 +pytest-aiohttp +pytest-asyncio diff --git a/tests/inference/extra_model_paths.yaml b/tests/inference/extra_model_paths.yaml new file mode 100644 index 000000000..75b2e1ae4 --- /dev/null +++ b/tests/inference/extra_model_paths.yaml @@ -0,0 +1,4 @@ +# Config for testing nodes +testing: + custom_nodes: tests/inference/testing_nodes + diff --git a/tests/inference/test_execution.py b/tests/inference/test_execution.py new file mode 100644 index 000000000..9df1d7df8 --- /dev/null +++ b/tests/inference/test_execution.py @@ -0,0 +1,461 @@ +from io import BytesIO +import numpy +from PIL import Image +import pytest +from pytest import fixture +import time +import torch +from typing import Union, Dict +import json +import subprocess +import websocket #NOTE: websocket-client (https://github.com/websocket-client/websocket-client) +import uuid +import urllib.request +import urllib.parse +import urllib.error +from comfy_execution.graph_utils import GraphBuilder, Node + +class RunResult: + def __init__(self, prompt_id: str): + self.outputs: Dict[str,Dict] = {} + self.runs: Dict[str,bool] = {} + self.prompt_id: str = prompt_id + + def get_output(self, node: Node): + return self.outputs.get(node.id, None) + + def did_run(self, node: Node): + return self.runs.get(node.id, False) + + def get_images(self, node: Node): + output = self.get_output(node) + if output is None: + return [] + return output.get('image_objects', []) + + def get_prompt_id(self): + return self.prompt_id + +class ComfyClient: + def __init__(self): + self.test_name = "" + + def connect(self, + listen:str = '127.0.0.1', + port:Union[str,int] = 8188, + client_id: str = str(uuid.uuid4()) + ): + self.client_id = client_id + self.server_address = f"{listen}:{port}" + ws = websocket.WebSocket() + ws.connect("ws://{}/ws?clientId={}".format(self.server_address, self.client_id)) + self.ws = ws + + def queue_prompt(self, prompt): + p = {"prompt": prompt, "client_id": self.client_id} + data = json.dumps(p).encode('utf-8') + req = urllib.request.Request("http://{}/prompt".format(self.server_address), data=data) + return json.loads(urllib.request.urlopen(req).read()) + + def get_image(self, filename, subfolder, folder_type): + data = {"filename": filename, "subfolder": subfolder, "type": folder_type} + url_values = urllib.parse.urlencode(data) + with urllib.request.urlopen("http://{}/view?{}".format(self.server_address, url_values)) as response: + return response.read() + + def get_history(self, prompt_id): + with urllib.request.urlopen("http://{}/history/{}".format(self.server_address, prompt_id)) as response: + return json.loads(response.read()) + + def set_test_name(self, name): + self.test_name = name + + def run(self, graph): + prompt = graph.finalize() + for node in graph.nodes.values(): + if node.class_type == 'SaveImage': + node.inputs['filename_prefix'] = self.test_name + + prompt_id = self.queue_prompt(prompt)['prompt_id'] + result = RunResult(prompt_id) + while True: + out = self.ws.recv() + if isinstance(out, str): + message = json.loads(out) + if message['type'] == 'executing': + data = message['data'] + if data['prompt_id'] != prompt_id: + continue + if data['node'] is None: + break + result.runs[data['node']] = True + elif message['type'] == 'execution_error': + raise Exception(message['data']) + elif message['type'] == 'execution_cached': + pass # Probably want to store this off for testing + + history = self.get_history(prompt_id)[prompt_id] + for o in history['outputs']: + for node_id in history['outputs']: + node_output = history['outputs'][node_id] + result.outputs[node_id] = node_output + if 'images' in node_output: + images_output = [] + for image in node_output['images']: + image_data = self.get_image(image['filename'], image['subfolder'], image['type']) + image_obj = Image.open(BytesIO(image_data)) + images_output.append(image_obj) + node_output['image_objects'] = images_output + + return result + +# +# Loop through these variables +# +@pytest.mark.execution +class TestExecution: + # + # Initialize server and client + # + @fixture(scope="class", autouse=True, params=[ + # (use_lru, lru_size) + (False, 0), + (True, 0), + (True, 100), + ]) + def _server(self, args_pytest, request): + # Start server + pargs = [ + 'python','main.py', + '--output-directory', args_pytest["output_dir"], + '--listen', args_pytest["listen"], + '--port', str(args_pytest["port"]), + '--extra-model-paths-config', 'tests/inference/extra_model_paths.yaml', + ] + use_lru, lru_size = request.param + if use_lru: + pargs += ['--cache-lru', str(lru_size)] + print("Running server with args:", pargs) + p = subprocess.Popen(pargs) + yield + p.kill() + torch.cuda.empty_cache() + + def start_client(self, listen:str, port:int): + # Start client + comfy_client = ComfyClient() + # Connect to server (with retries) + n_tries = 5 + for i in range(n_tries): + time.sleep(4) + try: + comfy_client.connect(listen=listen, port=port) + except ConnectionRefusedError as e: + print(e) + print(f"({i+1}/{n_tries}) Retrying...") + else: + break + return comfy_client + + @fixture(scope="class", autouse=True) + def shared_client(self, args_pytest, _server): + client = self.start_client(args_pytest["listen"], args_pytest["port"]) + yield client + del client + torch.cuda.empty_cache() + + @fixture + def client(self, shared_client, request): + shared_client.set_test_name(f"execution[{request.node.name}]") + yield shared_client + + @fixture + def builder(self, request): + yield GraphBuilder(prefix=request.node.name) + + def test_lazy_input(self, client: ComfyClient, builder: GraphBuilder): + g = builder + input1 = g.node("StubImage", content="BLACK", height=512, width=512, batch_size=1) + input2 = g.node("StubImage", content="WHITE", height=512, width=512, batch_size=1) + mask = g.node("StubMask", value=0.0, height=512, width=512, batch_size=1) + + lazy_mix = g.node("TestLazyMixImages", image1=input1.out(0), image2=input2.out(0), mask=mask.out(0)) + output = g.node("SaveImage", images=lazy_mix.out(0)) + result = client.run(g) + + result_image = result.get_images(output)[0] + assert numpy.array(result_image).any() == 0, "Image should be black" + assert result.did_run(input1) + assert not result.did_run(input2) + assert result.did_run(mask) + assert result.did_run(lazy_mix) + + def test_full_cache(self, client: ComfyClient, builder: GraphBuilder): + g = builder + input1 = g.node("StubImage", content="BLACK", height=512, width=512, batch_size=1) + input2 = g.node("StubImage", content="NOISE", height=512, width=512, batch_size=1) + mask = g.node("StubMask", value=0.5, height=512, width=512, batch_size=1) + + lazy_mix = g.node("TestLazyMixImages", image1=input1.out(0), image2=input2.out(0), mask=mask.out(0)) + g.node("SaveImage", images=lazy_mix.out(0)) + + client.run(g) + result2 = client.run(g) + for node_id, node in g.nodes.items(): + assert not result2.did_run(node), f"Node {node_id} ran, but should have been cached" + + def test_partial_cache(self, client: ComfyClient, builder: GraphBuilder): + g = builder + input1 = g.node("StubImage", content="BLACK", height=512, width=512, batch_size=1) + input2 = g.node("StubImage", content="NOISE", height=512, width=512, batch_size=1) + mask = g.node("StubMask", value=0.5, height=512, width=512, batch_size=1) + + lazy_mix = g.node("TestLazyMixImages", image1=input1.out(0), image2=input2.out(0), mask=mask.out(0)) + g.node("SaveImage", images=lazy_mix.out(0)) + + client.run(g) + mask.inputs['value'] = 0.4 + result2 = client.run(g) + assert not result2.did_run(input1), "Input1 should have been cached" + assert not result2.did_run(input2), "Input2 should have been cached" + + def test_error(self, client: ComfyClient, builder: GraphBuilder): + g = builder + input1 = g.node("StubImage", content="BLACK", height=512, width=512, batch_size=1) + # Different size of the two images + input2 = g.node("StubImage", content="NOISE", height=256, width=256, batch_size=1) + mask = g.node("StubMask", value=0.5, height=512, width=512, batch_size=1) + + lazy_mix = g.node("TestLazyMixImages", image1=input1.out(0), image2=input2.out(0), mask=mask.out(0)) + g.node("SaveImage", images=lazy_mix.out(0)) + + try: + client.run(g) + assert False, "Should have raised an error" + except Exception as e: + assert 'prompt_id' in e.args[0], f"Did not get back a proper error message: {e}" + + @pytest.mark.parametrize("test_value, expect_error", [ + (5, True), + ("foo", True), + (5.0, False), + ]) + def test_validation_error_literal(self, test_value, expect_error, client: ComfyClient, builder: GraphBuilder): + g = builder + validation1 = g.node("TestCustomValidation1", input1=test_value, input2=3.0) + g.node("SaveImage", images=validation1.out(0)) + + if expect_error: + with pytest.raises(urllib.error.HTTPError): + client.run(g) + else: + client.run(g) + + @pytest.mark.parametrize("test_type, test_value", [ + ("StubInt", 5), + ("StubFloat", 5.0) + ]) + def test_validation_error_edge1(self, test_type, test_value, client: ComfyClient, builder: GraphBuilder): + g = builder + stub = g.node(test_type, value=test_value) + validation1 = g.node("TestCustomValidation1", input1=stub.out(0), input2=3.0) + g.node("SaveImage", images=validation1.out(0)) + + with pytest.raises(urllib.error.HTTPError): + client.run(g) + + @pytest.mark.parametrize("test_type, test_value, expect_error", [ + ("StubInt", 5, True), + ("StubFloat", 5.0, False) + ]) + def test_validation_error_edge2(self, test_type, test_value, expect_error, client: ComfyClient, builder: GraphBuilder): + g = builder + stub = g.node(test_type, value=test_value) + validation2 = g.node("TestCustomValidation2", input1=stub.out(0), input2=3.0) + g.node("SaveImage", images=validation2.out(0)) + + if expect_error: + with pytest.raises(urllib.error.HTTPError): + client.run(g) + else: + client.run(g) + + @pytest.mark.parametrize("test_type, test_value, expect_error", [ + ("StubInt", 5, True), + ("StubFloat", 5.0, False) + ]) + def test_validation_error_edge3(self, test_type, test_value, expect_error, client: ComfyClient, builder: GraphBuilder): + g = builder + stub = g.node(test_type, value=test_value) + validation3 = g.node("TestCustomValidation3", input1=stub.out(0), input2=3.0) + g.node("SaveImage", images=validation3.out(0)) + + if expect_error: + with pytest.raises(urllib.error.HTTPError): + client.run(g) + else: + client.run(g) + + @pytest.mark.parametrize("test_type, test_value, expect_error", [ + ("StubInt", 5, True), + ("StubFloat", 5.0, False) + ]) + def test_validation_error_edge4(self, test_type, test_value, expect_error, client: ComfyClient, builder: GraphBuilder): + g = builder + stub = g.node(test_type, value=test_value) + validation4 = g.node("TestCustomValidation4", input1=stub.out(0), input2=3.0) + g.node("SaveImage", images=validation4.out(0)) + + if expect_error: + with pytest.raises(urllib.error.HTTPError): + client.run(g) + else: + client.run(g) + + @pytest.mark.parametrize("test_value1, test_value2, expect_error", [ + (0.0, 0.5, False), + (0.0, 5.0, False), + (0.0, 7.0, True) + ]) + def test_validation_error_kwargs(self, test_value1, test_value2, expect_error, client: ComfyClient, builder: GraphBuilder): + g = builder + validation5 = g.node("TestCustomValidation5", input1=test_value1, input2=test_value2) + g.node("SaveImage", images=validation5.out(0)) + + if expect_error: + with pytest.raises(urllib.error.HTTPError): + client.run(g) + else: + client.run(g) + + def test_cycle_error(self, client: ComfyClient, builder: GraphBuilder): + g = builder + input1 = g.node("StubImage", content="BLACK", height=512, width=512, batch_size=1) + input2 = g.node("StubImage", content="WHITE", height=512, width=512, batch_size=1) + mask = g.node("StubMask", value=0.5, height=512, width=512, batch_size=1) + + lazy_mix1 = g.node("TestLazyMixImages", image1=input1.out(0), mask=mask.out(0)) + lazy_mix2 = g.node("TestLazyMixImages", image1=lazy_mix1.out(0), image2=input2.out(0), mask=mask.out(0)) + g.node("SaveImage", images=lazy_mix2.out(0)) + + # When the cycle exists on initial submission, it should raise a validation error + with pytest.raises(urllib.error.HTTPError): + client.run(g) + + def test_dynamic_cycle_error(self, client: ComfyClient, builder: GraphBuilder): + g = builder + input1 = g.node("StubImage", content="BLACK", height=512, width=512, batch_size=1) + input2 = g.node("StubImage", content="WHITE", height=512, width=512, batch_size=1) + generator = g.node("TestDynamicDependencyCycle", input1=input1.out(0), input2=input2.out(0)) + g.node("SaveImage", images=generator.out(0)) + + # When the cycle is in a graph that is generated dynamically, it should raise a runtime error + try: + client.run(g) + assert False, "Should have raised an error" + except Exception as e: + assert 'prompt_id' in e.args[0], f"Did not get back a proper error message: {e}" + assert e.args[0]['node_id'] == generator.id, "Error should have been on the generator node" + + def test_custom_is_changed(self, client: ComfyClient, builder: GraphBuilder): + g = builder + # Creating the nodes in this specific order previously caused a bug + save = g.node("SaveImage") + is_changed = g.node("TestCustomIsChanged", should_change=False) + input1 = g.node("StubImage", content="BLACK", height=512, width=512, batch_size=1) + + save.set_input('images', is_changed.out(0)) + is_changed.set_input('image', input1.out(0)) + + result1 = client.run(g) + result2 = client.run(g) + is_changed.set_input('should_change', True) + result3 = client.run(g) + result4 = client.run(g) + assert result1.did_run(is_changed), "is_changed should have been run" + assert not result2.did_run(is_changed), "is_changed should have been cached" + assert result3.did_run(is_changed), "is_changed should have been re-run" + assert result4.did_run(is_changed), "is_changed should not have been cached" + + def test_undeclared_inputs(self, client: ComfyClient, builder: GraphBuilder): + g = builder + input1 = g.node("StubImage", content="BLACK", height=512, width=512, batch_size=1) + input2 = g.node("StubImage", content="WHITE", height=512, width=512, batch_size=1) + input3 = g.node("StubImage", content="BLACK", height=512, width=512, batch_size=1) + input4 = g.node("StubImage", content="BLACK", height=512, width=512, batch_size=1) + average = g.node("TestVariadicAverage", input1=input1.out(0), input2=input2.out(0), input3=input3.out(0), input4=input4.out(0)) + output = g.node("SaveImage", images=average.out(0)) + + result = client.run(g) + result_image = result.get_images(output)[0] + expected = 255 // 4 + assert numpy.array(result_image).min() == expected and numpy.array(result_image).max() == expected, "Image should be grey" + + def test_for_loop(self, client: ComfyClient, builder: GraphBuilder): + g = builder + iterations = 4 + input1 = g.node("StubImage", content="BLACK", height=512, width=512, batch_size=1) + input2 = g.node("StubImage", content="WHITE", height=512, width=512, batch_size=1) + is_changed = g.node("TestCustomIsChanged", should_change=True, image=input2.out(0)) + for_open = g.node("TestForLoopOpen", remaining=iterations, initial_value1=is_changed.out(0)) + average = g.node("TestVariadicAverage", input1=input1.out(0), input2=for_open.out(2)) + for_close = g.node("TestForLoopClose", flow_control=for_open.out(0), initial_value1=average.out(0)) + output = g.node("SaveImage", images=for_close.out(0)) + + for iterations in range(1, 5): + for_open.set_input('remaining', iterations) + result = client.run(g) + result_image = result.get_images(output)[0] + expected = 255 // (2 ** iterations) + assert numpy.array(result_image).min() == expected and numpy.array(result_image).max() == expected, "Image should be grey" + assert result.did_run(is_changed) + + def test_mixed_expansion_returns(self, client: ComfyClient, builder: GraphBuilder): + g = builder + val_list = g.node("TestMakeListNode", value1=0.1, value2=0.2, value3=0.3) + mixed = g.node("TestMixedExpansionReturns", input1=val_list.out(0)) + output_dynamic = g.node("SaveImage", images=mixed.out(0)) + output_literal = g.node("SaveImage", images=mixed.out(1)) + + result = client.run(g) + images_dynamic = result.get_images(output_dynamic) + assert len(images_dynamic) == 3, "Should have 2 images" + assert numpy.array(images_dynamic[0]).min() == 25 and numpy.array(images_dynamic[0]).max() == 25, "First image should be 0.1" + assert numpy.array(images_dynamic[1]).min() == 51 and numpy.array(images_dynamic[1]).max() == 51, "Second image should be 0.2" + assert numpy.array(images_dynamic[2]).min() == 76 and numpy.array(images_dynamic[2]).max() == 76, "Third image should be 0.3" + + images_literal = result.get_images(output_literal) + assert len(images_literal) == 3, "Should have 2 images" + for i in range(3): + assert numpy.array(images_literal[i]).min() == 255 and numpy.array(images_literal[i]).max() == 255, "All images should be white" + + def test_mixed_lazy_results(self, client: ComfyClient, builder: GraphBuilder): + g = builder + val_list = g.node("TestMakeListNode", value1=0.0, value2=0.5, value3=1.0) + mask = g.node("StubMask", value=val_list.out(0), height=512, width=512, batch_size=1) + input1 = g.node("StubImage", content="BLACK", height=512, width=512, batch_size=1) + input2 = g.node("StubImage", content="WHITE", height=512, width=512, batch_size=1) + mix = g.node("TestLazyMixImages", image1=input1.out(0), image2=input2.out(0), mask=mask.out(0)) + rebatch = g.node("RebatchImages", images=mix.out(0), batch_size=3) + output = g.node("SaveImage", images=rebatch.out(0)) + + result = client.run(g) + images = result.get_images(output) + assert len(images) == 3, "Should have 3 image" + assert numpy.array(images[0]).min() == 0 and numpy.array(images[0]).max() == 0, "First image should be 0.0" + assert numpy.array(images[1]).min() == 127 and numpy.array(images[1]).max() == 127, "Second image should be 0.5" + assert numpy.array(images[2]).min() == 255 and numpy.array(images[2]).max() == 255, "Third image should be 1.0" + + def test_output_reuse(self, client: ComfyClient, builder: GraphBuilder): + g = builder + input1 = g.node("StubImage", content="BLACK", height=512, width=512, batch_size=1) + + output1 = g.node("PreviewImage", images=input1.out(0)) + output2 = g.node("PreviewImage", images=input1.out(0)) + + result = client.run(g) + images1 = result.get_images(output1) + images2 = result.get_images(output2) + assert len(images1) == 1, "Should have 1 image" + assert len(images2) == 1, "Should have 1 image" + diff --git a/tests/inference/testing_nodes/testing-pack/__init__.py b/tests/inference/testing_nodes/testing-pack/__init__.py new file mode 100644 index 000000000..dcc71659a --- /dev/null +++ b/tests/inference/testing_nodes/testing-pack/__init__.py @@ -0,0 +1,23 @@ +from .specific_tests import TEST_NODE_CLASS_MAPPINGS, TEST_NODE_DISPLAY_NAME_MAPPINGS +from .flow_control import FLOW_CONTROL_NODE_CLASS_MAPPINGS, FLOW_CONTROL_NODE_DISPLAY_NAME_MAPPINGS +from .util import UTILITY_NODE_CLASS_MAPPINGS, UTILITY_NODE_DISPLAY_NAME_MAPPINGS +from .conditions import CONDITION_NODE_CLASS_MAPPINGS, CONDITION_NODE_DISPLAY_NAME_MAPPINGS +from .stubs import TEST_STUB_NODE_CLASS_MAPPINGS, TEST_STUB_NODE_DISPLAY_NAME_MAPPINGS + +# NODE_CLASS_MAPPINGS = GENERAL_NODE_CLASS_MAPPINGS.update(COMPONENT_NODE_CLASS_MAPPINGS) +# NODE_DISPLAY_NAME_MAPPINGS = GENERAL_NODE_DISPLAY_NAME_MAPPINGS.update(COMPONENT_NODE_DISPLAY_NAME_MAPPINGS) + +NODE_CLASS_MAPPINGS = {} +NODE_CLASS_MAPPINGS.update(TEST_NODE_CLASS_MAPPINGS) +NODE_CLASS_MAPPINGS.update(FLOW_CONTROL_NODE_CLASS_MAPPINGS) +NODE_CLASS_MAPPINGS.update(UTILITY_NODE_CLASS_MAPPINGS) +NODE_CLASS_MAPPINGS.update(CONDITION_NODE_CLASS_MAPPINGS) +NODE_CLASS_MAPPINGS.update(TEST_STUB_NODE_CLASS_MAPPINGS) + +NODE_DISPLAY_NAME_MAPPINGS = {} +NODE_DISPLAY_NAME_MAPPINGS.update(TEST_NODE_DISPLAY_NAME_MAPPINGS) +NODE_DISPLAY_NAME_MAPPINGS.update(FLOW_CONTROL_NODE_DISPLAY_NAME_MAPPINGS) +NODE_DISPLAY_NAME_MAPPINGS.update(UTILITY_NODE_DISPLAY_NAME_MAPPINGS) +NODE_DISPLAY_NAME_MAPPINGS.update(CONDITION_NODE_DISPLAY_NAME_MAPPINGS) +NODE_DISPLAY_NAME_MAPPINGS.update(TEST_STUB_NODE_DISPLAY_NAME_MAPPINGS) + diff --git a/tests/inference/testing_nodes/testing-pack/conditions.py b/tests/inference/testing_nodes/testing-pack/conditions.py new file mode 100644 index 000000000..0c200ee28 --- /dev/null +++ b/tests/inference/testing_nodes/testing-pack/conditions.py @@ -0,0 +1,194 @@ +import re +import torch + +class TestIntConditions: + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "a": ("INT", {"default": 0, "min": -0xffffffffffffffff, "max": 0xffffffffffffffff, "step": 1}), + "b": ("INT", {"default": 0, "min": -0xffffffffffffffff, "max": 0xffffffffffffffff, "step": 1}), + "operation": (["==", "!=", "<", ">", "<=", ">="],), + }, + } + + RETURN_TYPES = ("BOOLEAN",) + FUNCTION = "int_condition" + + CATEGORY = "Testing/Logic" + + def int_condition(self, a, b, operation): + if operation == "==": + return (a == b,) + elif operation == "!=": + return (a != b,) + elif operation == "<": + return (a < b,) + elif operation == ">": + return (a > b,) + elif operation == "<=": + return (a <= b,) + elif operation == ">=": + return (a >= b,) + + +class TestFloatConditions: + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "a": ("FLOAT", {"default": 0, "min": -999999999999.0, "max": 999999999999.0, "step": 1}), + "b": ("FLOAT", {"default": 0, "min": -999999999999.0, "max": 999999999999.0, "step": 1}), + "operation": (["==", "!=", "<", ">", "<=", ">="],), + }, + } + + RETURN_TYPES = ("BOOLEAN",) + FUNCTION = "float_condition" + + CATEGORY = "Testing/Logic" + + def float_condition(self, a, b, operation): + if operation == "==": + return (a == b,) + elif operation == "!=": + return (a != b,) + elif operation == "<": + return (a < b,) + elif operation == ">": + return (a > b,) + elif operation == "<=": + return (a <= b,) + elif operation == ">=": + return (a >= b,) + +class TestStringConditions: + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "a": ("STRING", {"multiline": False}), + "b": ("STRING", {"multiline": False}), + "operation": (["a == b", "a != b", "a IN b", "a MATCH REGEX(b)", "a BEGINSWITH b", "a ENDSWITH b"],), + "case_sensitive": ("BOOLEAN", {"default": True}), + }, + } + + RETURN_TYPES = ("BOOLEAN",) + FUNCTION = "string_condition" + + CATEGORY = "Testing/Logic" + + def string_condition(self, a, b, operation, case_sensitive): + if not case_sensitive: + a = a.lower() + b = b.lower() + + if operation == "a == b": + return (a == b,) + elif operation == "a != b": + return (a != b,) + elif operation == "a IN b": + return (a in b,) + elif operation == "a MATCH REGEX(b)": + try: + return (re.match(b, a) is not None,) + except: + return (False,) + elif operation == "a BEGINSWITH b": + return (a.startswith(b),) + elif operation == "a ENDSWITH b": + return (a.endswith(b),) + +class TestToBoolNode: + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "value": ("*",), + }, + "optional": { + "invert": ("BOOLEAN", {"default": False}), + }, + } + + RETURN_TYPES = ("BOOLEAN",) + FUNCTION = "to_bool" + + CATEGORY = "Testing/Logic" + + def to_bool(self, value, invert = False): + if isinstance(value, torch.Tensor): + if value.max().item() == 0 and value.min().item() == 0: + result = False + else: + result = True + else: + try: + result = bool(value) + except: + # Can't convert it? Well then it's something or other. I dunno, I'm not a Python programmer. + result = True + + if invert: + result = not result + + return (result,) + +class TestBoolOperationNode: + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "a": ("BOOLEAN",), + "b": ("BOOLEAN",), + "op": (["a AND b", "a OR b", "a XOR b", "NOT a"],), + }, + } + + RETURN_TYPES = ("BOOLEAN",) + FUNCTION = "bool_operation" + + CATEGORY = "Testing/Logic" + + def bool_operation(self, a, b, op): + if op == "a AND b": + return (a and b,) + elif op == "a OR b": + return (a or b,) + elif op == "a XOR b": + return (a ^ b,) + elif op == "NOT a": + return (not a,) + + +CONDITION_NODE_CLASS_MAPPINGS = { + "TestIntConditions": TestIntConditions, + "TestFloatConditions": TestFloatConditions, + "TestStringConditions": TestStringConditions, + "TestToBoolNode": TestToBoolNode, + "TestBoolOperationNode": TestBoolOperationNode, +} + +CONDITION_NODE_DISPLAY_NAME_MAPPINGS = { + "TestIntConditions": "Int Condition", + "TestFloatConditions": "Float Condition", + "TestStringConditions": "String Condition", + "TestToBoolNode": "To Bool", + "TestBoolOperationNode": "Bool Operation", +} diff --git a/tests/inference/testing_nodes/testing-pack/flow_control.py b/tests/inference/testing_nodes/testing-pack/flow_control.py new file mode 100644 index 000000000..ba943be60 --- /dev/null +++ b/tests/inference/testing_nodes/testing-pack/flow_control.py @@ -0,0 +1,173 @@ +from comfy_execution.graph_utils import GraphBuilder, is_link +from comfy_execution.graph import ExecutionBlocker +from .tools import VariantSupport + +NUM_FLOW_SOCKETS = 5 +@VariantSupport() +class TestWhileLoopOpen: + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(cls): + inputs = { + "required": { + "condition": ("BOOLEAN", {"default": True}), + }, + "optional": { + }, + } + for i in range(NUM_FLOW_SOCKETS): + inputs["optional"][f"initial_value{i}"] = ("*",) + return inputs + + RETURN_TYPES = tuple(["FLOW_CONTROL"] + ["*"] * NUM_FLOW_SOCKETS) + RETURN_NAMES = tuple(["FLOW_CONTROL"] + [f"value{i}" for i in range(NUM_FLOW_SOCKETS)]) + FUNCTION = "while_loop_open" + + CATEGORY = "Testing/Flow" + + def while_loop_open(self, condition, **kwargs): + values = [] + for i in range(NUM_FLOW_SOCKETS): + values.append(kwargs.get(f"initial_value{i}", None)) + return tuple(["stub"] + values) + +@VariantSupport() +class TestWhileLoopClose: + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(cls): + inputs = { + "required": { + "flow_control": ("FLOW_CONTROL", {"rawLink": True}), + "condition": ("BOOLEAN", {"forceInput": True}), + }, + "optional": { + }, + "hidden": { + "dynprompt": "DYNPROMPT", + "unique_id": "UNIQUE_ID", + } + } + for i in range(NUM_FLOW_SOCKETS): + inputs["optional"][f"initial_value{i}"] = ("*",) + return inputs + + RETURN_TYPES = tuple(["*"] * NUM_FLOW_SOCKETS) + RETURN_NAMES = tuple([f"value{i}" for i in range(NUM_FLOW_SOCKETS)]) + FUNCTION = "while_loop_close" + + CATEGORY = "Testing/Flow" + + def explore_dependencies(self, node_id, dynprompt, upstream): + node_info = dynprompt.get_node(node_id) + if "inputs" not in node_info: + return + for k, v in node_info["inputs"].items(): + if is_link(v): + parent_id = v[0] + if parent_id not in upstream: + upstream[parent_id] = [] + self.explore_dependencies(parent_id, dynprompt, upstream) + upstream[parent_id].append(node_id) + + def collect_contained(self, node_id, upstream, contained): + if node_id not in upstream: + return + for child_id in upstream[node_id]: + if child_id not in contained: + contained[child_id] = True + self.collect_contained(child_id, upstream, contained) + + + def while_loop_close(self, flow_control, condition, dynprompt=None, unique_id=None, **kwargs): + assert dynprompt is not None + if not condition: + # We're done with the loop + values = [] + for i in range(NUM_FLOW_SOCKETS): + values.append(kwargs.get(f"initial_value{i}", None)) + return tuple(values) + + # We want to loop + upstream = {} + # Get the list of all nodes between the open and close nodes + self.explore_dependencies(unique_id, dynprompt, upstream) + + contained = {} + open_node = flow_control[0] + self.collect_contained(open_node, upstream, contained) + contained[unique_id] = True + contained[open_node] = True + + # We'll use the default prefix, but to avoid having node names grow exponentially in size, + # we'll use "Recurse" for the name of the recursively-generated copy of this node. + graph = GraphBuilder() + for node_id in contained: + original_node = dynprompt.get_node(node_id) + node = graph.node(original_node["class_type"], "Recurse" if node_id == unique_id else node_id) + node.set_override_display_id(node_id) + for node_id in contained: + original_node = dynprompt.get_node(node_id) + node = graph.lookup_node("Recurse" if node_id == unique_id else node_id) + assert node is not None + for k, v in original_node["inputs"].items(): + if is_link(v) and v[0] in contained: + parent = graph.lookup_node(v[0]) + assert parent is not None + node.set_input(k, parent.out(v[1])) + else: + node.set_input(k, v) + new_open = graph.lookup_node(open_node) + assert new_open is not None + for i in range(NUM_FLOW_SOCKETS): + key = f"initial_value{i}" + new_open.set_input(key, kwargs.get(key, None)) + my_clone = graph.lookup_node("Recurse") + assert my_clone is not None + result = map(lambda x: my_clone.out(x), range(NUM_FLOW_SOCKETS)) + return { + "result": tuple(result), + "expand": graph.finalize(), + } + +@VariantSupport() +class TestExecutionBlockerNode: + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(cls): + inputs = { + "required": { + "input": ("*",), + "block": ("BOOLEAN",), + "verbose": ("BOOLEAN", {"default": False}), + }, + } + return inputs + + RETURN_TYPES = ("*",) + RETURN_NAMES = ("output",) + FUNCTION = "execution_blocker" + + CATEGORY = "Testing/Flow" + + def execution_blocker(self, input, block, verbose): + if block: + return (ExecutionBlocker("Blocked Execution" if verbose else None),) + return (input,) + +FLOW_CONTROL_NODE_CLASS_MAPPINGS = { + "TestWhileLoopOpen": TestWhileLoopOpen, + "TestWhileLoopClose": TestWhileLoopClose, + "TestExecutionBlocker": TestExecutionBlockerNode, +} +FLOW_CONTROL_NODE_DISPLAY_NAME_MAPPINGS = { + "TestWhileLoopOpen": "While Loop Open", + "TestWhileLoopClose": "While Loop Close", + "TestExecutionBlocker": "Execution Blocker", +} diff --git a/tests/inference/testing_nodes/testing-pack/specific_tests.py b/tests/inference/testing_nodes/testing-pack/specific_tests.py new file mode 100644 index 000000000..b961d1b63 --- /dev/null +++ b/tests/inference/testing_nodes/testing-pack/specific_tests.py @@ -0,0 +1,335 @@ +import torch +from .tools import VariantSupport +from comfy_execution.graph_utils import GraphBuilder + +class TestLazyMixImages: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "image1": ("IMAGE",{"lazy": True}), + "image2": ("IMAGE",{"lazy": True}), + "mask": ("MASK",), + }, + } + + RETURN_TYPES = ("IMAGE",) + FUNCTION = "mix" + + CATEGORY = "Testing/Nodes" + + def check_lazy_status(self, mask, image1, image2): + mask_min = mask.min() + mask_max = mask.max() + needed = [] + if image1 is None and (mask_min != 1.0 or mask_max != 1.0): + needed.append("image1") + if image2 is None and (mask_min != 0.0 or mask_max != 0.0): + needed.append("image2") + return needed + + # Not trying to handle different batch sizes here just to keep the demo simple + def mix(self, mask, image1, image2): + mask_min = mask.min() + mask_max = mask.max() + if mask_min == 0.0 and mask_max == 0.0: + return (image1,) + elif mask_min == 1.0 and mask_max == 1.0: + return (image2,) + + if len(mask.shape) == 2: + mask = mask.unsqueeze(0) + if len(mask.shape) == 3: + mask = mask.unsqueeze(3) + if mask.shape[3] < image1.shape[3]: + mask = mask.repeat(1, 1, 1, image1.shape[3]) + + result = image1 * (1. - mask) + image2 * mask, + return (result[0],) + +class TestVariadicAverage: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "input1": ("IMAGE",), + }, + } + + RETURN_TYPES = ("IMAGE",) + FUNCTION = "variadic_average" + + CATEGORY = "Testing/Nodes" + + def variadic_average(self, input1, **kwargs): + inputs = [input1] + while 'input' + str(len(inputs) + 1) in kwargs: + inputs.append(kwargs['input' + str(len(inputs) + 1)]) + return (torch.stack(inputs).mean(dim=0),) + + +class TestCustomIsChanged: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "image": ("IMAGE",), + }, + "optional": { + "should_change": ("BOOL", {"default": False}), + }, + } + + RETURN_TYPES = ("IMAGE",) + FUNCTION = "custom_is_changed" + + CATEGORY = "Testing/Nodes" + + def custom_is_changed(self, image, should_change=False): + return (image,) + + @classmethod + def IS_CHANGED(cls, should_change=False, *args, **kwargs): + if should_change: + return float("NaN") + else: + return False + +class TestCustomValidation1: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "input1": ("IMAGE,FLOAT",), + "input2": ("IMAGE,FLOAT",), + }, + } + + RETURN_TYPES = ("IMAGE",) + FUNCTION = "custom_validation1" + + CATEGORY = "Testing/Nodes" + + def custom_validation1(self, input1, input2): + if isinstance(input1, float) and isinstance(input2, float): + result = torch.ones([1, 512, 512, 3]) * input1 * input2 + else: + result = input1 * input2 + return (result,) + + @classmethod + def VALIDATE_INPUTS(cls, input1=None, input2=None): + if input1 is not None: + if not isinstance(input1, (torch.Tensor, float)): + return f"Invalid type of input1: {type(input1)}" + if input2 is not None: + if not isinstance(input2, (torch.Tensor, float)): + return f"Invalid type of input2: {type(input2)}" + + return True + +class TestCustomValidation2: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "input1": ("IMAGE,FLOAT",), + "input2": ("IMAGE,FLOAT",), + }, + } + + RETURN_TYPES = ("IMAGE",) + FUNCTION = "custom_validation2" + + CATEGORY = "Testing/Nodes" + + def custom_validation2(self, input1, input2): + if isinstance(input1, float) and isinstance(input2, float): + result = torch.ones([1, 512, 512, 3]) * input1 * input2 + else: + result = input1 * input2 + return (result,) + + @classmethod + def VALIDATE_INPUTS(cls, input_types, input1=None, input2=None): + if input1 is not None: + if not isinstance(input1, (torch.Tensor, float)): + return f"Invalid type of input1: {type(input1)}" + if input2 is not None: + if not isinstance(input2, (torch.Tensor, float)): + return f"Invalid type of input2: {type(input2)}" + + if 'input1' in input_types: + if input_types['input1'] not in ["IMAGE", "FLOAT"]: + return f"Invalid type of input1: {input_types['input1']}" + if 'input2' in input_types: + if input_types['input2'] not in ["IMAGE", "FLOAT"]: + return f"Invalid type of input2: {input_types['input2']}" + + return True + +@VariantSupport() +class TestCustomValidation3: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "input1": ("IMAGE,FLOAT",), + "input2": ("IMAGE,FLOAT",), + }, + } + + RETURN_TYPES = ("IMAGE",) + FUNCTION = "custom_validation3" + + CATEGORY = "Testing/Nodes" + + def custom_validation3(self, input1, input2): + if isinstance(input1, float) and isinstance(input2, float): + result = torch.ones([1, 512, 512, 3]) * input1 * input2 + else: + result = input1 * input2 + return (result,) + +class TestCustomValidation4: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "input1": ("FLOAT",), + "input2": ("FLOAT",), + }, + } + + RETURN_TYPES = ("IMAGE",) + FUNCTION = "custom_validation4" + + CATEGORY = "Testing/Nodes" + + def custom_validation4(self, input1, input2): + result = torch.ones([1, 512, 512, 3]) * input1 * input2 + return (result,) + + @classmethod + def VALIDATE_INPUTS(cls, input1, input2): + if input1 is not None: + if not isinstance(input1, float): + return f"Invalid type of input1: {type(input1)}" + if input2 is not None: + if not isinstance(input2, float): + return f"Invalid type of input2: {type(input2)}" + + return True + +class TestCustomValidation5: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "input1": ("FLOAT", {"min": 0.0, "max": 1.0}), + "input2": ("FLOAT", {"min": 0.0, "max": 1.0}), + }, + } + + RETURN_TYPES = ("IMAGE",) + FUNCTION = "custom_validation5" + + CATEGORY = "Testing/Nodes" + + def custom_validation5(self, input1, input2): + value = input1 * input2 + return (torch.ones([1, 512, 512, 3]) * value,) + + @classmethod + def VALIDATE_INPUTS(cls, **kwargs): + if kwargs['input2'] == 7.0: + return "7s are not allowed. I've never liked 7s." + return True + +class TestDynamicDependencyCycle: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "input1": ("IMAGE",), + "input2": ("IMAGE",), + }, + } + + RETURN_TYPES = ("IMAGE",) + FUNCTION = "dynamic_dependency_cycle" + + CATEGORY = "Testing/Nodes" + + def dynamic_dependency_cycle(self, input1, input2): + g = GraphBuilder() + mask = g.node("StubMask", value=0.5, height=512, width=512, batch_size=1) + mix1 = g.node("TestLazyMixImages", image1=input1, mask=mask.out(0)) + mix2 = g.node("TestLazyMixImages", image1=mix1.out(0), image2=input2, mask=mask.out(0)) + + # Create the cyle + mix1.set_input("image2", mix2.out(0)) + + return { + "result": (mix2.out(0),), + "expand": g.finalize(), + } + +class TestMixedExpansionReturns: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "input1": ("FLOAT",), + }, + } + + RETURN_TYPES = ("IMAGE","IMAGE") + FUNCTION = "mixed_expansion_returns" + + CATEGORY = "Testing/Nodes" + + def mixed_expansion_returns(self, input1): + white_image = torch.ones([1, 512, 512, 3]) + if input1 <= 0.1: + return (torch.ones([1, 512, 512, 3]) * 0.1, white_image) + elif input1 <= 0.2: + return { + "result": (torch.ones([1, 512, 512, 3]) * 0.2, white_image), + } + else: + g = GraphBuilder() + mask = g.node("StubMask", value=0.3, height=512, width=512, batch_size=1) + black = g.node("StubImage", content="BLACK", height=512, width=512, batch_size=1) + white = g.node("StubImage", content="WHITE", height=512, width=512, batch_size=1) + mix = g.node("TestLazyMixImages", image1=black.out(0), image2=white.out(0), mask=mask.out(0)) + return { + "result": (mix.out(0), white_image), + "expand": g.finalize(), + } + +TEST_NODE_CLASS_MAPPINGS = { + "TestLazyMixImages": TestLazyMixImages, + "TestVariadicAverage": TestVariadicAverage, + "TestCustomIsChanged": TestCustomIsChanged, + "TestCustomValidation1": TestCustomValidation1, + "TestCustomValidation2": TestCustomValidation2, + "TestCustomValidation3": TestCustomValidation3, + "TestCustomValidation4": TestCustomValidation4, + "TestCustomValidation5": TestCustomValidation5, + "TestDynamicDependencyCycle": TestDynamicDependencyCycle, + "TestMixedExpansionReturns": TestMixedExpansionReturns, +} + +TEST_NODE_DISPLAY_NAME_MAPPINGS = { + "TestLazyMixImages": "Lazy Mix Images", + "TestVariadicAverage": "Variadic Average", + "TestCustomIsChanged": "Custom IsChanged", + "TestCustomValidation1": "Custom Validation 1", + "TestCustomValidation2": "Custom Validation 2", + "TestCustomValidation3": "Custom Validation 3", + "TestCustomValidation4": "Custom Validation 4", + "TestCustomValidation5": "Custom Validation 5", + "TestDynamicDependencyCycle": "Dynamic Dependency Cycle", + "TestMixedExpansionReturns": "Mixed Expansion Returns", +} diff --git a/tests/inference/testing_nodes/testing-pack/stubs.py b/tests/inference/testing_nodes/testing-pack/stubs.py new file mode 100644 index 000000000..9be6eac9d --- /dev/null +++ b/tests/inference/testing_nodes/testing-pack/stubs.py @@ -0,0 +1,105 @@ +import torch + +class StubImage: + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "content": (['WHITE', 'BLACK', 'NOISE'],), + "height": ("INT", {"default": 512, "min": 1, "max": 1024 ** 3, "step": 1}), + "width": ("INT", {"default": 512, "min": 1, "max": 4096 ** 3, "step": 1}), + "batch_size": ("INT", {"default": 1, "min": 1, "max": 1024 ** 3, "step": 1}), + }, + } + + RETURN_TYPES = ("IMAGE",) + FUNCTION = "stub_image" + + CATEGORY = "Testing/Stub Nodes" + + def stub_image(self, content, height, width, batch_size): + if content == "WHITE": + return (torch.ones(batch_size, height, width, 3),) + elif content == "BLACK": + return (torch.zeros(batch_size, height, width, 3),) + elif content == "NOISE": + return (torch.rand(batch_size, height, width, 3),) + +class StubMask: + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "value": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.01}), + "height": ("INT", {"default": 512, "min": 1, "max": 1024 ** 3, "step": 1}), + "width": ("INT", {"default": 512, "min": 1, "max": 4096 ** 3, "step": 1}), + "batch_size": ("INT", {"default": 1, "min": 1, "max": 1024 ** 3, "step": 1}), + }, + } + + RETURN_TYPES = ("MASK",) + FUNCTION = "stub_mask" + + CATEGORY = "Testing/Stub Nodes" + + def stub_mask(self, value, height, width, batch_size): + return (torch.ones(batch_size, height, width) * value,) + +class StubInt: + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "value": ("INT", {"default": 0, "min": -0xffffffff, "max": 0xffffffff, "step": 1}), + }, + } + + RETURN_TYPES = ("INT",) + FUNCTION = "stub_int" + + CATEGORY = "Testing/Stub Nodes" + + def stub_int(self, value): + return (value,) + +class StubFloat: + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "value": ("FLOAT", {"default": 0.0, "min": -1.0e38, "max": 1.0e38, "step": 0.01}), + }, + } + + RETURN_TYPES = ("FLOAT",) + FUNCTION = "stub_float" + + CATEGORY = "Testing/Stub Nodes" + + def stub_float(self, value): + return (value,) + +TEST_STUB_NODE_CLASS_MAPPINGS = { + "StubImage": StubImage, + "StubMask": StubMask, + "StubInt": StubInt, + "StubFloat": StubFloat, +} +TEST_STUB_NODE_DISPLAY_NAME_MAPPINGS = { + "StubImage": "Stub Image", + "StubMask": "Stub Mask", + "StubInt": "Stub Int", + "StubFloat": "Stub Float", +} diff --git a/tests/inference/testing_nodes/testing-pack/tools.py b/tests/inference/testing_nodes/testing-pack/tools.py new file mode 100644 index 000000000..34b28c0eb --- /dev/null +++ b/tests/inference/testing_nodes/testing-pack/tools.py @@ -0,0 +1,53 @@ + +def MakeSmartType(t): + if isinstance(t, str): + return SmartType(t) + return t + +class SmartType(str): + def __ne__(self, other): + if self == "*" or other == "*": + return False + selfset = set(self.split(',')) + otherset = set(other.split(',')) + return not selfset.issubset(otherset) + +def VariantSupport(): + def decorator(cls): + if hasattr(cls, "INPUT_TYPES"): + old_input_types = getattr(cls, "INPUT_TYPES") + def new_input_types(*args, **kwargs): + types = old_input_types(*args, **kwargs) + for category in ["required", "optional"]: + if category not in types: + continue + for key, value in types[category].items(): + if isinstance(value, tuple): + types[category][key] = (MakeSmartType(value[0]),) + value[1:] + return types + setattr(cls, "INPUT_TYPES", new_input_types) + if hasattr(cls, "RETURN_TYPES"): + old_return_types = cls.RETURN_TYPES + setattr(cls, "RETURN_TYPES", tuple(MakeSmartType(x) for x in old_return_types)) + if hasattr(cls, "VALIDATE_INPUTS"): + # Reflection is used to determine what the function signature is, so we can't just change the function signature + raise NotImplementedError("VariantSupport does not support VALIDATE_INPUTS yet") + else: + def validate_inputs(input_types): + inputs = cls.INPUT_TYPES() + for key, value in input_types.items(): + if isinstance(value, SmartType): + continue + if "required" in inputs and key in inputs["required"]: + expected_type = inputs["required"][key][0] + elif "optional" in inputs and key in inputs["optional"]: + expected_type = inputs["optional"][key][0] + else: + expected_type = None + if expected_type is not None and MakeSmartType(value) != expected_type: + return f"Invalid type of {key}: {value} (expected {expected_type})" + return True + setattr(cls, "VALIDATE_INPUTS", validate_inputs) + return cls + return decorator + diff --git a/tests/inference/testing_nodes/testing-pack/util.py b/tests/inference/testing_nodes/testing-pack/util.py new file mode 100644 index 000000000..ca116c16e --- /dev/null +++ b/tests/inference/testing_nodes/testing-pack/util.py @@ -0,0 +1,364 @@ +from comfy_execution.graph_utils import GraphBuilder +from .tools import VariantSupport + +@VariantSupport() +class TestAccumulateNode: + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "to_add": ("*",), + }, + "optional": { + "accumulation": ("ACCUMULATION",), + }, + } + + RETURN_TYPES = ("ACCUMULATION",) + FUNCTION = "accumulate" + + CATEGORY = "Testing/Lists" + + def accumulate(self, to_add, accumulation = None): + if accumulation is None: + value = [to_add] + else: + value = accumulation["accum"] + [to_add] + return ({"accum": value},) + +@VariantSupport() +class TestAccumulationHeadNode: + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "accumulation": ("ACCUMULATION",), + }, + } + + RETURN_TYPES = ("ACCUMULATION", "*",) + FUNCTION = "accumulation_head" + + CATEGORY = "Testing/Lists" + + def accumulation_head(self, accumulation): + accum = accumulation["accum"] + if len(accum) == 0: + return (accumulation, None) + else: + return ({"accum": accum[1:]}, accum[0]) + +class TestAccumulationTailNode: + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "accumulation": ("ACCUMULATION",), + }, + } + + RETURN_TYPES = ("ACCUMULATION", "*",) + FUNCTION = "accumulation_tail" + + CATEGORY = "Testing/Lists" + + def accumulation_tail(self, accumulation): + accum = accumulation["accum"] + if len(accum) == 0: + return (None, accumulation) + else: + return ({"accum": accum[:-1]}, accum[-1]) + +@VariantSupport() +class TestAccumulationToListNode: + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "accumulation": ("ACCUMULATION",), + }, + } + + RETURN_TYPES = ("*",) + OUTPUT_IS_LIST = (True,) + + FUNCTION = "accumulation_to_list" + + CATEGORY = "Testing/Lists" + + def accumulation_to_list(self, accumulation): + return (accumulation["accum"],) + +@VariantSupport() +class TestListToAccumulationNode: + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "list": ("*",), + }, + } + + RETURN_TYPES = ("ACCUMULATION",) + INPUT_IS_LIST = (True,) + + FUNCTION = "list_to_accumulation" + + CATEGORY = "Testing/Lists" + + def list_to_accumulation(self, list): + return ({"accum": list},) + +@VariantSupport() +class TestAccumulationGetLengthNode: + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "accumulation": ("ACCUMULATION",), + }, + } + + RETURN_TYPES = ("INT",) + + FUNCTION = "accumlength" + + CATEGORY = "Testing/Lists" + + def accumlength(self, accumulation): + return (len(accumulation['accum']),) + +@VariantSupport() +class TestAccumulationGetItemNode: + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "accumulation": ("ACCUMULATION",), + "index": ("INT", {"default":0, "step":1}) + }, + } + + RETURN_TYPES = ("*",) + + FUNCTION = "get_item" + + CATEGORY = "Testing/Lists" + + def get_item(self, accumulation, index): + return (accumulation['accum'][index],) + +@VariantSupport() +class TestAccumulationSetItemNode: + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "accumulation": ("ACCUMULATION",), + "index": ("INT", {"default":0, "step":1}), + "value": ("*",), + }, + } + + RETURN_TYPES = ("ACCUMULATION",) + + FUNCTION = "set_item" + + CATEGORY = "Testing/Lists" + + def set_item(self, accumulation, index, value): + new_accum = accumulation['accum'][:] + new_accum[index] = value + return ({"accum": new_accum},) + +class TestIntMathOperation: + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "a": ("INT", {"default": 0, "min": -0xffffffffffffffff, "max": 0xffffffffffffffff, "step": 1}), + "b": ("INT", {"default": 0, "min": -0xffffffffffffffff, "max": 0xffffffffffffffff, "step": 1}), + "operation": (["add", "subtract", "multiply", "divide", "modulo", "power"],), + }, + } + + RETURN_TYPES = ("INT",) + FUNCTION = "int_math_operation" + + CATEGORY = "Testing/Logic" + + def int_math_operation(self, a, b, operation): + if operation == "add": + return (a + b,) + elif operation == "subtract": + return (a - b,) + elif operation == "multiply": + return (a * b,) + elif operation == "divide": + return (a // b,) + elif operation == "modulo": + return (a % b,) + elif operation == "power": + return (a ** b,) + + +from .flow_control import NUM_FLOW_SOCKETS +@VariantSupport() +class TestForLoopOpen: + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "remaining": ("INT", {"default": 1, "min": 0, "max": 100000, "step": 1}), + }, + "optional": { + f"initial_value{i}": ("*",) for i in range(1, NUM_FLOW_SOCKETS) + }, + "hidden": { + "initial_value0": ("*",) + } + } + + RETURN_TYPES = tuple(["FLOW_CONTROL", "INT",] + ["*"] * (NUM_FLOW_SOCKETS-1)) + RETURN_NAMES = tuple(["flow_control", "remaining"] + [f"value{i}" for i in range(1, NUM_FLOW_SOCKETS)]) + FUNCTION = "for_loop_open" + + CATEGORY = "Testing/Flow" + + def for_loop_open(self, remaining, **kwargs): + graph = GraphBuilder() + if "initial_value0" in kwargs: + remaining = kwargs["initial_value0"] + while_open = graph.node("TestWhileLoopOpen", condition=remaining, initial_value0=remaining, **{(f"initial_value{i}"): kwargs.get(f"initial_value{i}", None) for i in range(1, NUM_FLOW_SOCKETS)}) + outputs = [kwargs.get(f"initial_value{i}", None) for i in range(1, NUM_FLOW_SOCKETS)] + return { + "result": tuple(["stub", remaining] + outputs), + "expand": graph.finalize(), + } + +@VariantSupport() +class TestForLoopClose: + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "flow_control": ("FLOW_CONTROL", {"rawLink": True}), + }, + "optional": { + f"initial_value{i}": ("*",{"rawLink": True}) for i in range(1, NUM_FLOW_SOCKETS) + }, + } + + RETURN_TYPES = tuple(["*"] * (NUM_FLOW_SOCKETS-1)) + RETURN_NAMES = tuple([f"value{i}" for i in range(1, NUM_FLOW_SOCKETS)]) + FUNCTION = "for_loop_close" + + CATEGORY = "Testing/Flow" + + def for_loop_close(self, flow_control, **kwargs): + graph = GraphBuilder() + while_open = flow_control[0] + sub = graph.node("TestIntMathOperation", operation="subtract", a=[while_open,1], b=1) + cond = graph.node("TestToBoolNode", value=sub.out(0)) + input_values = {f"initial_value{i}": kwargs.get(f"initial_value{i}", None) for i in range(1, NUM_FLOW_SOCKETS)} + while_close = graph.node("TestWhileLoopClose", + flow_control=flow_control, + condition=cond.out(0), + initial_value0=sub.out(0), + **input_values) + return { + "result": tuple([while_close.out(i) for i in range(1, NUM_FLOW_SOCKETS)]), + "expand": graph.finalize(), + } + +NUM_LIST_SOCKETS = 10 +@VariantSupport() +class TestMakeListNode: + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "value1": ("*",), + }, + "optional": { + f"value{i}": ("*",) for i in range(1, NUM_LIST_SOCKETS) + }, + } + + RETURN_TYPES = ("*",) + FUNCTION = "make_list" + OUTPUT_IS_LIST = (True,) + + CATEGORY = "Testing/Lists" + + def make_list(self, **kwargs): + result = [] + for i in range(NUM_LIST_SOCKETS): + if f"value{i}" in kwargs: + result.append(kwargs[f"value{i}"]) + return (result,) + +UTILITY_NODE_CLASS_MAPPINGS = { + "TestAccumulateNode": TestAccumulateNode, + "TestAccumulationHeadNode": TestAccumulationHeadNode, + "TestAccumulationTailNode": TestAccumulationTailNode, + "TestAccumulationToListNode": TestAccumulationToListNode, + "TestListToAccumulationNode": TestListToAccumulationNode, + "TestAccumulationGetLengthNode": TestAccumulationGetLengthNode, + "TestAccumulationGetItemNode": TestAccumulationGetItemNode, + "TestAccumulationSetItemNode": TestAccumulationSetItemNode, + "TestForLoopOpen": TestForLoopOpen, + "TestForLoopClose": TestForLoopClose, + "TestIntMathOperation": TestIntMathOperation, + "TestMakeListNode": TestMakeListNode, +} +UTILITY_NODE_DISPLAY_NAME_MAPPINGS = { + "TestAccumulateNode": "Accumulate", + "TestAccumulationHeadNode": "Accumulation Head", + "TestAccumulationTailNode": "Accumulation Tail", + "TestAccumulationToListNode": "Accumulation to List", + "TestListToAccumulationNode": "List to Accumulation", + "TestAccumulationGetLengthNode": "Accumulation Get Length", + "TestAccumulationGetItemNode": "Accumulation Get Item", + "TestAccumulationSetItemNode": "Accumulation Set Item", + "TestForLoopOpen": "For Loop Open", + "TestForLoopClose": "For Loop Close", + "TestIntMathOperation": "Int Math Operation", + "TestMakeListNode": "Make List", +} diff --git a/web/assets/index-CwWW6Xjy.css b/web/assets/index-CwWW6Xjy.css new file mode 100644 index 000000000..24e7e4abe --- /dev/null +++ b/web/assets/index-CwWW6Xjy.css @@ -0,0 +1,4025 @@ +@font-face { + font-family: 'primeicons'; + font-display: block; + src: url('/assets/primeicons-DMOk5skT.eot'); + src: url('/assets/primeicons-DMOk5skT.eot?#iefix') format('embedded-opentype'), url('/assets/primeicons-C6QP2o4f.woff2') format('woff2'), url('/assets/primeicons-WjwUDZjB.woff') format('woff'), url('/assets/primeicons-MpK4pl85.ttf') format('truetype'), url('/assets/primeicons-Dr5RGzOO.svg?#primeicons') format('svg'); + font-weight: normal; + font-style: normal; +} + +.pi { + font-family: 'primeicons'; + speak: none; + font-style: normal; + font-weight: normal; + font-variant: normal; + text-transform: none; + line-height: 1; + display: inline-block; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; +} + +.pi:before { + --webkit-backface-visibility:hidden; + backface-visibility: hidden; +} + +.pi-fw { + width: 1.28571429em; + text-align: center; +} + +.pi-spin { + animation: fa-spin 2s infinite linear; +} + +@media (prefers-reduced-motion: reduce) { + .pi-spin { + animation-delay: -1ms; + animation-duration: 1ms; + animation-iteration-count: 1; + transition-delay: 0s; + transition-duration: 0s; + } +} + +@keyframes fa-spin { + 0% { + transform: rotate(0deg); + } + 100% { + transform: rotate(359deg); + } +} + +.pi-folder-plus:before { + content: "\ea05"; +} + +.pi-receipt:before { + content: "\ea06"; +} + +.pi-asterisk:before { + content: "\ea07"; +} + +.pi-face-smile:before { + content: "\ea08"; +} + +.pi-pinterest:before { + content: "\ea09"; +} + +.pi-expand:before { + content: "\ea0a"; +} + +.pi-pen-to-square:before { + content: "\ea0b"; +} + +.pi-wave-pulse:before { + content: "\ea0c"; +} + +.pi-turkish-lira:before { + content: "\ea0d"; +} + +.pi-spinner-dotted:before { + content: "\ea0e"; +} + +.pi-crown:before { + content: "\ea0f"; +} + +.pi-pause-circle:before { + content: "\ea10"; +} + +.pi-warehouse:before { + content: "\ea11"; +} + +.pi-objects-column:before { + content: "\ea12"; +} + +.pi-clipboard:before { + content: "\ea13"; +} + +.pi-play-circle:before { + content: "\ea14"; +} + +.pi-venus:before { + content: "\ea15"; +} + +.pi-cart-minus:before { + content: "\ea16"; +} + +.pi-file-plus:before { + content: "\ea17"; +} + +.pi-microchip:before { + content: "\ea18"; +} + +.pi-twitch:before { + content: "\ea19"; +} + +.pi-building-columns:before { + content: "\ea1a"; +} + +.pi-file-check:before { + content: "\ea1b"; +} + +.pi-microchip-ai:before { + content: "\ea1c"; +} + +.pi-trophy:before { + content: "\ea1d"; +} + +.pi-barcode:before { + content: "\ea1e"; +} + +.pi-file-arrow-up:before { + content: "\ea1f"; +} + +.pi-mars:before { + content: "\ea20"; +} + +.pi-tiktok:before { + content: "\ea21"; +} + +.pi-arrow-up-right-and-arrow-down-left-from-center:before { + content: "\ea22"; +} + +.pi-ethereum:before { + content: "\ea23"; +} + +.pi-list-check:before { + content: "\ea24"; +} + +.pi-thumbtack:before { + content: "\ea25"; +} + +.pi-arrow-down-left-and-arrow-up-right-to-center:before { + content: "\ea26"; +} + +.pi-equals:before { + content: "\ea27"; +} + +.pi-lightbulb:before { + content: "\ea28"; +} + +.pi-star-half:before { + content: "\ea29"; +} + +.pi-address-book:before { + content: "\ea2a"; +} + +.pi-chart-scatter:before { + content: "\ea2b"; +} + +.pi-indian-rupee:before { + content: "\ea2c"; +} + +.pi-star-half-fill:before { + content: "\ea2d"; +} + +.pi-cart-arrow-down:before { + content: "\ea2e"; +} + +.pi-calendar-clock:before { + content: "\ea2f"; +} + +.pi-sort-up-fill:before { + content: "\ea30"; +} + +.pi-sparkles:before { + content: "\ea31"; +} + +.pi-bullseye:before { + content: "\ea32"; +} + +.pi-sort-down-fill:before { + content: "\ea33"; +} + +.pi-graduation-cap:before { + content: "\ea34"; +} + +.pi-hammer:before { + content: "\ea35"; +} + +.pi-bell-slash:before { + content: "\ea36"; +} + +.pi-gauge:before { + content: "\ea37"; +} + +.pi-shop:before { + content: "\ea38"; +} + +.pi-headphones:before { + content: "\ea39"; +} + +.pi-eraser:before { + content: "\ea04"; +} + +.pi-stopwatch:before { + content: "\ea01"; +} + +.pi-verified:before { + content: "\ea02"; +} + +.pi-delete-left:before { + content: "\ea03"; +} + +.pi-hourglass:before { + content: "\e9fe"; +} + +.pi-truck:before { + content: "\ea00"; +} + +.pi-wrench:before { + content: "\e9ff"; +} + +.pi-microphone:before { + content: "\e9fa"; +} + +.pi-megaphone:before { + content: "\e9fb"; +} + +.pi-arrow-right-arrow-left:before { + content: "\e9fc"; +} + +.pi-bitcoin:before { + content: "\e9fd"; +} + +.pi-file-edit:before { + content: "\e9f6"; +} + +.pi-language:before { + content: "\e9f7"; +} + +.pi-file-export:before { + content: "\e9f8"; +} + +.pi-file-import:before { + content: "\e9f9"; +} + +.pi-file-word:before { + content: "\e9f1"; +} + +.pi-gift:before { + content: "\e9f2"; +} + +.pi-cart-plus:before { + content: "\e9f3"; +} + +.pi-thumbs-down-fill:before { + content: "\e9f4"; +} + +.pi-thumbs-up-fill:before { + content: "\e9f5"; +} + +.pi-arrows-alt:before { + content: "\e9f0"; +} + +.pi-calculator:before { + content: "\e9ef"; +} + +.pi-sort-alt-slash:before { + content: "\e9ee"; +} + +.pi-arrows-h:before { + content: "\e9ec"; +} + +.pi-arrows-v:before { + content: "\e9ed"; +} + +.pi-pound:before { + content: "\e9eb"; +} + +.pi-prime:before { + content: "\e9ea"; +} + +.pi-chart-pie:before { + content: "\e9e9"; +} + +.pi-reddit:before { + content: "\e9e8"; +} + +.pi-code:before { + content: "\e9e7"; +} + +.pi-sync:before { + content: "\e9e6"; +} + +.pi-shopping-bag:before { + content: "\e9e5"; +} + +.pi-server:before { + content: "\e9e4"; +} + +.pi-database:before { + content: "\e9e3"; +} + +.pi-hashtag:before { + content: "\e9e2"; +} + +.pi-bookmark-fill:before { + content: "\e9df"; +} + +.pi-filter-fill:before { + content: "\e9e0"; +} + +.pi-heart-fill:before { + content: "\e9e1"; +} + +.pi-flag-fill:before { + content: "\e9de"; +} + +.pi-circle:before { + content: "\e9dc"; +} + +.pi-circle-fill:before { + content: "\e9dd"; +} + +.pi-bolt:before { + content: "\e9db"; +} + +.pi-history:before { + content: "\e9da"; +} + +.pi-box:before { + content: "\e9d9"; +} + +.pi-at:before { + content: "\e9d8"; +} + +.pi-arrow-up-right:before { + content: "\e9d4"; +} + +.pi-arrow-up-left:before { + content: "\e9d5"; +} + +.pi-arrow-down-left:before { + content: "\e9d6"; +} + +.pi-arrow-down-right:before { + content: "\e9d7"; +} + +.pi-telegram:before { + content: "\e9d3"; +} + +.pi-stop-circle:before { + content: "\e9d2"; +} + +.pi-stop:before { + content: "\e9d1"; +} + +.pi-whatsapp:before { + content: "\e9d0"; +} + +.pi-building:before { + content: "\e9cf"; +} + +.pi-qrcode:before { + content: "\e9ce"; +} + +.pi-car:before { + content: "\e9cd"; +} + +.pi-instagram:before { + content: "\e9cc"; +} + +.pi-linkedin:before { + content: "\e9cb"; +} + +.pi-send:before { + content: "\e9ca"; +} + +.pi-slack:before { + content: "\e9c9"; +} + +.pi-sun:before { + content: "\e9c8"; +} + +.pi-moon:before { + content: "\e9c7"; +} + +.pi-vimeo:before { + content: "\e9c6"; +} + +.pi-youtube:before { + content: "\e9c5"; +} + +.pi-flag:before { + content: "\e9c4"; +} + +.pi-wallet:before { + content: "\e9c3"; +} + +.pi-map:before { + content: "\e9c2"; +} + +.pi-link:before { + content: "\e9c1"; +} + +.pi-credit-card:before { + content: "\e9bf"; +} + +.pi-discord:before { + content: "\e9c0"; +} + +.pi-percentage:before { + content: "\e9be"; +} + +.pi-euro:before { + content: "\e9bd"; +} + +.pi-book:before { + content: "\e9ba"; +} + +.pi-shield:before { + content: "\e9b9"; +} + +.pi-paypal:before { + content: "\e9bb"; +} + +.pi-amazon:before { + content: "\e9bc"; +} + +.pi-phone:before { + content: "\e9b8"; +} + +.pi-filter-slash:before { + content: "\e9b7"; +} + +.pi-facebook:before { + content: "\e9b4"; +} + +.pi-github:before { + content: "\e9b5"; +} + +.pi-twitter:before { + content: "\e9b6"; +} + +.pi-step-backward-alt:before { + content: "\e9ac"; +} + +.pi-step-forward-alt:before { + content: "\e9ad"; +} + +.pi-forward:before { + content: "\e9ae"; +} + +.pi-backward:before { + content: "\e9af"; +} + +.pi-fast-backward:before { + content: "\e9b0"; +} + +.pi-fast-forward:before { + content: "\e9b1"; +} + +.pi-pause:before { + content: "\e9b2"; +} + +.pi-play:before { + content: "\e9b3"; +} + +.pi-compass:before { + content: "\e9ab"; +} + +.pi-id-card:before { + content: "\e9aa"; +} + +.pi-ticket:before { + content: "\e9a9"; +} + +.pi-file-o:before { + content: "\e9a8"; +} + +.pi-reply:before { + content: "\e9a7"; +} + +.pi-directions-alt:before { + content: "\e9a5"; +} + +.pi-directions:before { + content: "\e9a6"; +} + +.pi-thumbs-up:before { + content: "\e9a3"; +} + +.pi-thumbs-down:before { + content: "\e9a4"; +} + +.pi-sort-numeric-down-alt:before { + content: "\e996"; +} + +.pi-sort-numeric-up-alt:before { + content: "\e997"; +} + +.pi-sort-alpha-down-alt:before { + content: "\e998"; +} + +.pi-sort-alpha-up-alt:before { + content: "\e999"; +} + +.pi-sort-numeric-down:before { + content: "\e99a"; +} + +.pi-sort-numeric-up:before { + content: "\e99b"; +} + +.pi-sort-alpha-down:before { + content: "\e99c"; +} + +.pi-sort-alpha-up:before { + content: "\e99d"; +} + +.pi-sort-alt:before { + content: "\e99e"; +} + +.pi-sort-amount-up:before { + content: "\e99f"; +} + +.pi-sort-amount-down:before { + content: "\e9a0"; +} + +.pi-sort-amount-down-alt:before { + content: "\e9a1"; +} + +.pi-sort-amount-up-alt:before { + content: "\e9a2"; +} + +.pi-palette:before { + content: "\e995"; +} + +.pi-undo:before { + content: "\e994"; +} + +.pi-desktop:before { + content: "\e993"; +} + +.pi-sliders-v:before { + content: "\e991"; +} + +.pi-sliders-h:before { + content: "\e992"; +} + +.pi-search-plus:before { + content: "\e98f"; +} + +.pi-search-minus:before { + content: "\e990"; +} + +.pi-file-excel:before { + content: "\e98e"; +} + +.pi-file-pdf:before { + content: "\e98d"; +} + +.pi-check-square:before { + content: "\e98c"; +} + +.pi-chart-line:before { + content: "\e98b"; +} + +.pi-user-edit:before { + content: "\e98a"; +} + +.pi-exclamation-circle:before { + content: "\e989"; +} + +.pi-android:before { + content: "\e985"; +} + +.pi-google:before { + content: "\e986"; +} + +.pi-apple:before { + content: "\e987"; +} + +.pi-microsoft:before { + content: "\e988"; +} + +.pi-heart:before { + content: "\e984"; +} + +.pi-mobile:before { + content: "\e982"; +} + +.pi-tablet:before { + content: "\e983"; +} + +.pi-key:before { + content: "\e981"; +} + +.pi-shopping-cart:before { + content: "\e980"; +} + +.pi-comments:before { + content: "\e97e"; +} + +.pi-comment:before { + content: "\e97f"; +} + +.pi-briefcase:before { + content: "\e97d"; +} + +.pi-bell:before { + content: "\e97c"; +} + +.pi-paperclip:before { + content: "\e97b"; +} + +.pi-share-alt:before { + content: "\e97a"; +} + +.pi-envelope:before { + content: "\e979"; +} + +.pi-volume-down:before { + content: "\e976"; +} + +.pi-volume-up:before { + content: "\e977"; +} + +.pi-volume-off:before { + content: "\e978"; +} + +.pi-eject:before { + content: "\e975"; +} + +.pi-money-bill:before { + content: "\e974"; +} + +.pi-images:before { + content: "\e973"; +} + +.pi-image:before { + content: "\e972"; +} + +.pi-sign-in:before { + content: "\e970"; +} + +.pi-sign-out:before { + content: "\e971"; +} + +.pi-wifi:before { + content: "\e96f"; +} + +.pi-sitemap:before { + content: "\e96e"; +} + +.pi-chart-bar:before { + content: "\e96d"; +} + +.pi-camera:before { + content: "\e96c"; +} + +.pi-dollar:before { + content: "\e96b"; +} + +.pi-lock-open:before { + content: "\e96a"; +} + +.pi-table:before { + content: "\e969"; +} + +.pi-map-marker:before { + content: "\e968"; +} + +.pi-list:before { + content: "\e967"; +} + +.pi-eye-slash:before { + content: "\e965"; +} + +.pi-eye:before { + content: "\e966"; +} + +.pi-folder-open:before { + content: "\e964"; +} + +.pi-folder:before { + content: "\e963"; +} + +.pi-video:before { + content: "\e962"; +} + +.pi-inbox:before { + content: "\e961"; +} + +.pi-lock:before { + content: "\e95f"; +} + +.pi-unlock:before { + content: "\e960"; +} + +.pi-tags:before { + content: "\e95d"; +} + +.pi-tag:before { + content: "\e95e"; +} + +.pi-power-off:before { + content: "\e95c"; +} + +.pi-save:before { + content: "\e95b"; +} + +.pi-question-circle:before { + content: "\e959"; +} + +.pi-question:before { + content: "\e95a"; +} + +.pi-copy:before { + content: "\e957"; +} + +.pi-file:before { + content: "\e958"; +} + +.pi-clone:before { + content: "\e955"; +} + +.pi-calendar-times:before { + content: "\e952"; +} + +.pi-calendar-minus:before { + content: "\e953"; +} + +.pi-calendar-plus:before { + content: "\e954"; +} + +.pi-ellipsis-v:before { + content: "\e950"; +} + +.pi-ellipsis-h:before { + content: "\e951"; +} + +.pi-bookmark:before { + content: "\e94e"; +} + +.pi-globe:before { + content: "\e94f"; +} + +.pi-replay:before { + content: "\e94d"; +} + +.pi-filter:before { + content: "\e94c"; +} + +.pi-print:before { + content: "\e94b"; +} + +.pi-align-right:before { + content: "\e946"; +} + +.pi-align-left:before { + content: "\e947"; +} + +.pi-align-center:before { + content: "\e948"; +} + +.pi-align-justify:before { + content: "\e949"; +} + +.pi-cog:before { + content: "\e94a"; +} + +.pi-cloud-download:before { + content: "\e943"; +} + +.pi-cloud-upload:before { + content: "\e944"; +} + +.pi-cloud:before { + content: "\e945"; +} + +.pi-pencil:before { + content: "\e942"; +} + +.pi-users:before { + content: "\e941"; +} + +.pi-clock:before { + content: "\e940"; +} + +.pi-user-minus:before { + content: "\e93e"; +} + +.pi-user-plus:before { + content: "\e93f"; +} + +.pi-trash:before { + content: "\e93d"; +} + +.pi-external-link:before { + content: "\e93c"; +} + +.pi-window-maximize:before { + content: "\e93b"; +} + +.pi-window-minimize:before { + content: "\e93a"; +} + +.pi-refresh:before { + content: "\e938"; +} + +.pi-user:before { + content: "\e939"; +} + +.pi-exclamation-triangle:before { + content: "\e922"; +} + +.pi-calendar:before { + content: "\e927"; +} + +.pi-chevron-circle-left:before { + content: "\e928"; +} + +.pi-chevron-circle-down:before { + content: "\e929"; +} + +.pi-chevron-circle-right:before { + content: "\e92a"; +} + +.pi-chevron-circle-up:before { + content: "\e92b"; +} + +.pi-angle-double-down:before { + content: "\e92c"; +} + +.pi-angle-double-left:before { + content: "\e92d"; +} + +.pi-angle-double-right:before { + content: "\e92e"; +} + +.pi-angle-double-up:before { + content: "\e92f"; +} + +.pi-angle-down:before { + content: "\e930"; +} + +.pi-angle-left:before { + content: "\e931"; +} + +.pi-angle-right:before { + content: "\e932"; +} + +.pi-angle-up:before { + content: "\e933"; +} + +.pi-upload:before { + content: "\e934"; +} + +.pi-download:before { + content: "\e956"; +} + +.pi-ban:before { + content: "\e935"; +} + +.pi-star-fill:before { + content: "\e936"; +} + +.pi-star:before { + content: "\e937"; +} + +.pi-chevron-left:before { + content: "\e900"; +} + +.pi-chevron-right:before { + content: "\e901"; +} + +.pi-chevron-down:before { + content: "\e902"; +} + +.pi-chevron-up:before { + content: "\e903"; +} + +.pi-caret-left:before { + content: "\e904"; +} + +.pi-caret-right:before { + content: "\e905"; +} + +.pi-caret-down:before { + content: "\e906"; +} + +.pi-caret-up:before { + content: "\e907"; +} + +.pi-search:before { + content: "\e908"; +} + +.pi-check:before { + content: "\e909"; +} + +.pi-check-circle:before { + content: "\e90a"; +} + +.pi-times:before { + content: "\e90b"; +} + +.pi-times-circle:before { + content: "\e90c"; +} + +.pi-plus:before { + content: "\e90d"; +} + +.pi-plus-circle:before { + content: "\e90e"; +} + +.pi-minus:before { + content: "\e90f"; +} + +.pi-minus-circle:before { + content: "\e910"; +} + +.pi-circle-on:before { + content: "\e911"; +} + +.pi-circle-off:before { + content: "\e912"; +} + +.pi-sort-down:before { + content: "\e913"; +} + +.pi-sort-up:before { + content: "\e914"; +} + +.pi-sort:before { + content: "\e915"; +} + +.pi-step-backward:before { + content: "\e916"; +} + +.pi-step-forward:before { + content: "\e917"; +} + +.pi-th-large:before { + content: "\e918"; +} + +.pi-arrow-down:before { + content: "\e919"; +} + +.pi-arrow-left:before { + content: "\e91a"; +} + +.pi-arrow-right:before { + content: "\e91b"; +} + +.pi-arrow-up:before { + content: "\e91c"; +} + +.pi-bars:before { + content: "\e91d"; +} + +.pi-arrow-circle-down:before { + content: "\e91e"; +} + +.pi-arrow-circle-left:before { + content: "\e91f"; +} + +.pi-arrow-circle-right:before { + content: "\e920"; +} + +.pi-arrow-circle-up:before { + content: "\e921"; +} + +.pi-info:before { + content: "\e923"; +} + +.pi-info-circle:before { + content: "\e924"; +} + +.pi-home:before { + content: "\e925"; +} + +.pi-spinner:before { + content: "\e926"; +} + +.side-bar-button-icon { + font-size: var(--sidebar-icon-size) !important; +} +.side-bar-button-selected .side-bar-button-icon { + font-size: var(--sidebar-icon-size) !important; + font-weight: bold; +} + +.side-bar-button[data-v-7a0b94a3] { + width: var(--sidebar-width); + height: var(--sidebar-width); + border-radius: 0; +} +.comfyui-body-left .side-bar-button.side-bar-button-selected[data-v-7a0b94a3], +.comfyui-body-left .side-bar-button.side-bar-button-selected[data-v-7a0b94a3]:hover { + border-left: 4px solid var(--p-button-text-primary-color); +} +.comfyui-body-right .side-bar-button.side-bar-button-selected[data-v-7a0b94a3], +.comfyui-body-right .side-bar-button.side-bar-button-selected[data-v-7a0b94a3]:hover { + border-right: 4px solid var(--p-button-text-primary-color); +} +.lds-ring { + display: inline-block; + position: relative; + width: 1em; + height: 1em; +} +.lds-ring div { + box-sizing: border-box; + display: block; + position: absolute; + width: 100%; + height: 100%; + border: 0.15em solid #fff; + border-radius: 50%; + animation: lds-ring 1.2s cubic-bezier(0.5, 0, 0.5, 1) infinite; + border-color: #fff transparent transparent transparent; +} +.lds-ring div:nth-child(1) { + animation-delay: -0.45s; +} +.lds-ring div:nth-child(2) { + animation-delay: -0.3s; +} +.lds-ring div:nth-child(3) { + animation-delay: -0.15s; +} +@keyframes lds-ring { + 0% { + transform: rotate(0deg); + } + 100% { + transform: rotate(360deg); + } +} +.relative { + position: relative; +} +.hidden { + display: none !important; +} +.mdi.rotate270::before { + transform: rotate(270deg); +} + +/* Generic */ +.comfyui-button { + display: flex; + align-items: center; + gap: 0.5em; + cursor: pointer; + border: none; + border-radius: 4px; + padding: 4px 8px; + box-sizing: border-box; + margin: 0; + transition: box-shadow 0.1s; +} + +.comfyui-button:active { + box-shadow: inset 1px 1px 10px rgba(0, 0, 0, 0.5); +} + +.comfyui-button:disabled { + opacity: 0.5; + cursor: not-allowed; +} +.primary .comfyui-button, +.primary.comfyui-button { + background-color: var(--primary-bg) !important; + color: var(--primary-fg) !important; +} + +.primary .comfyui-button:not(:disabled):hover, +.primary.comfyui-button:not(:disabled):hover { + background-color: var(--primary-hover-bg) !important; + color: var(--primary-hover-fg) !important; +} + +/* Popup */ +.comfyui-popup { + position: absolute; + left: var(--left); + right: var(--right); + top: var(--top); + bottom: var(--bottom); + z-index: 2000; + max-height: calc(100vh - var(--limit) - 10px); + box-shadow: 3px 3px 5px 0px rgba(0, 0, 0, 0.3); +} + +.comfyui-popup:not(.open) { + display: none; +} + +.comfyui-popup.right.open { + border-top-left-radius: 4px; + border-bottom-right-radius: 4px; + border-bottom-left-radius: 4px; + overflow: hidden; +} +/* Split button */ +.comfyui-split-button { + position: relative; + display: flex; +} + +.comfyui-split-primary { + flex: auto; +} + +.comfyui-split-primary .comfyui-button { + border-top-right-radius: 0; + border-bottom-right-radius: 0; + border-right: 1px solid var(--comfy-menu-bg); + width: 100%; +} + +.comfyui-split-arrow .comfyui-button { + border-top-left-radius: 0; + border-bottom-left-radius: 0; + padding-left: 2px; + padding-right: 2px; +} + +.comfyui-split-button-popup { + white-space: nowrap; + background-color: var(--content-bg); + color: var(--content-fg); + display: flex; + flex-direction: column; + overflow: auto; +} + +.comfyui-split-button-popup.hover { + z-index: 2001; +} +.comfyui-split-button-popup > .comfyui-button { + border: none; + background-color: transparent; + color: var(--fg-color); + padding: 8px 12px 8px 8px; +} + +.comfyui-split-button-popup > .comfyui-button:not(:disabled):hover { + background-color: var(--comfy-input-bg); +} + +/* Button group */ +.comfyui-button-group { + display: flex; + border-radius: 4px; + overflow: hidden; +} + +.comfyui-button-group > .comfyui-button, +.comfyui-button-group > .comfyui-button-wrapper > .comfyui-button { + padding: 4px 10px; + border-radius: 0; +} + +/* Menu */ +.comfyui-menu { + width: 100vw; + background: var(--comfy-menu-bg); + color: var(--fg-color); + font-family: Arial, Helvetica, sans-serif; + font-size: 0.8em; + display: flex; + padding: 4px 8px; + align-items: center; + gap: 8px; + box-sizing: border-box; + z-index: 1000; + order: 0; + grid-column: 1/-1; + overflow: auto; + max-height: 90vh; +} + +.comfyui-menu>* { + flex-shrink: 0; +} +.comfyui-menu .mdi::before { + font-size: 18px; +} + +.comfyui-menu .comfyui-button { + background: var(--comfy-input-bg); + color: var(--fg-color); + white-space: nowrap; +} + +.comfyui-menu .comfyui-button:not(:disabled):hover { + background: var(--border-color); + color: var(--content-fg); +} + +.comfyui-menu .comfyui-split-button-popup > .comfyui-button { + border-radius: 0; + background-color: transparent; +} + +.comfyui-menu .comfyui-split-button-popup > .comfyui-button:not(:disabled):hover { + background-color: var(--comfy-input-bg); +} + +.comfyui-menu .comfyui-split-button-popup.left { + border-top-right-radius: 4px; + border-bottom-left-radius: 4px; + border-bottom-right-radius: 4px; +} + +.comfyui-menu .comfyui-button.popup-open { + background-color: var(--content-bg); + color: var(--content-fg); +} + +.comfyui-menu-push { + margin-left: -0.8em; + flex: auto; +} + +.comfyui-logo { + font-size: 1.2em; + margin: 0; + -webkit-user-select: none; + -moz-user-select: none; + user-select: none; + cursor: default; +} + +/* Workflows */ +.comfyui-workflows-button { + flex-direction: row-reverse; + max-width: 200px; + position: relative; + z-index: 0; +} + +.comfyui-workflows-button.popup-open { + border-bottom-left-radius: 0; + border-bottom-right-radius: 0; +} +.comfyui-workflows-button.unsaved { + font-style: italic; +} +.comfyui-workflows-button-progress { + position: absolute; + top: 0; + left: 0; + background-color: green; + height: 100%; + border-radius: 4px; + z-index: -1; +} + +.comfyui-workflows-button > span { + flex: auto; + text-align: left; + overflow: hidden; +} +.comfyui-workflows-button-inner { + display: flex; + align-items: center; + gap: 7px; + width: 150px; +} +.comfyui-workflows-label { + overflow: hidden; + text-overflow: ellipsis; + direction: rtl; + flex: auto; + position: relative; +} + +.comfyui-workflows-button.unsaved .comfyui-workflows-label { + padding-left: 8px; +} + +.comfyui-workflows-button.unsaved .comfyui-workflows-label:after { + content: "*"; + position: absolute; + top: 0; + left: 0; +} +.comfyui-workflows-button-inner .mdi-graph::before { + transform: rotate(-90deg); +} + +.comfyui-workflows-popup { + font-family: Arial, Helvetica, sans-serif; + font-size: 0.8em; + padding: 10px; + overflow: auto; + background-color: var(--content-bg); + color: var(--content-fg); + border-top-right-radius: 4px; + border-bottom-right-radius: 4px; + border-bottom-left-radius: 4px; + z-index: 1001; +} + +.comfyui-workflows-panel { + min-height: 150px; +} + +.comfyui-workflows-panel .lds-ring { + transform: translate(-50%); + position: absolute; + left: 50%; + top: 75px; +} + +.comfyui-workflows-panel h3 { + margin: 10px 0 10px 0; + font-size: 11px; + opacity: 0.8; +} + +.comfyui-workflows-panel section header { + display: flex; + justify-content: space-between; + align-items: center; +} +.comfy-ui-workflows-search .mdi { + position: relative; + top: 2px; + pointer-events: none; +} +.comfy-ui-workflows-search input { + background-color: var(--comfy-input-bg); + color: var(--input-text); + border: none; + border-radius: 4px; + padding: 4px 10px; + margin-left: -24px; + text-indent: 18px; +} +.comfy-ui-workflows-search input:-moz-placeholder-shown { + width: 10px; +} +.comfy-ui-workflows-search input:placeholder-shown { + width: 10px; +} +.comfy-ui-workflows-search input:-moz-placeholder-shown:focus { + width: auto; +} +.comfy-ui-workflows-search input:placeholder-shown:focus { + width: auto; +} +.comfyui-workflows-actions { + display: flex; + gap: 10px; + margin-bottom: 10px; +} + +.comfyui-workflows-actions .comfyui-button { + background: var(--comfy-input-bg); + color: var(--input-text); +} + +.comfyui-workflows-actions .comfyui-button:not(:disabled):hover { + background: var(--primary-bg); + color: var(--primary-fg); +} + +.comfyui-workflows-favorites, +.comfyui-workflows-open { + border-bottom: 1px solid var(--comfy-input-bg); + padding-bottom: 5px; + margin-bottom: 5px; +} + +.comfyui-workflows-open .active { + font-weight: bold; + color: var(--primary-fg); +} + +.comfyui-workflows-favorites:empty { + display: none; +} + +.comfyui-workflows-tree { + padding: 0; + margin: 0; +} + +.comfyui-workflows-tree:empty::after { + content: "No saved workflows"; + display: block; + text-align: center; +} +.comfyui-workflows-tree > ul { + padding: 0; +} + +.comfyui-workflows-tree > ul ul { + margin: 0; + padding: 0 0 0 25px; +} + +.comfyui-workflows-tree:not(.filtered) .closed > ul { + display: none; +} + +.comfyui-workflows-tree li, +.comfyui-workflows-tree-file { + --item-height: 32px; + list-style-type: none; + height: var(--item-height); + display: flex; + align-items: center; + gap: 5px; + cursor: pointer; + -webkit-user-select: none; + -moz-user-select: none; + user-select: none; +} + +.comfyui-workflows-tree-file.active::before, +.comfyui-workflows-tree li:hover::before, +.comfyui-workflows-tree-file:hover::before { + content: ""; + position: absolute; + width: 100%; + left: 0; + height: var(--item-height); + background-color: var(--content-hover-bg); + color: var(--content-hover-fg); + z-index: -1; +} + +.comfyui-workflows-tree-file.active::before { + background-color: var(--primary-bg); + color: var(--primary-fg); +} + +.comfyui-workflows-tree-file.running:not(:hover)::before { + content: ""; + position: absolute; + width: var(--progress, 0); + left: 0; + height: var(--item-height); + background-color: green; + z-index: -1; +} + +.comfyui-workflows-tree-file.unsaved span { + font-style: italic; +} + +.comfyui-workflows-tree-file span { + flex: auto; +} + +.comfyui-workflows-tree-file span + .comfyui-workflows-file-action { + margin-left: 10px; +} + +.comfyui-workflows-tree-file .comfyui-workflows-file-action { + background-color: transparent; + color: var(--fg-color); + padding: 2px 4px; +} + +.comfyui-workflows-tree-file.active .comfyui-workflows-file-action { + color: var(--primary-fg); +} + +.lg ~ .comfyui-workflows-popup .comfyui-workflows-tree-file:not(:hover) .comfyui-workflows-file-action { + opacity: 0; +} + +.comfyui-workflows-tree-file .comfyui-workflows-file-action:hover { + background-color: var(--primary-bg); + color: var(--primary-fg); +} + +.comfyui-workflows-tree-file .comfyui-workflows-file-action-primary { + background-color: transparent; + color: var(--fg-color); + padding: 2px 4px; + margin: 0 -4px; +} + +.comfyui-workflows-file-action-favorite .mdi-star { + color: orange; +} + +/* View List */ +.comfyui-view-list-popup { + padding: 10px; + background-color: var(--content-bg); + color: var(--content-fg); + min-width: 170px; + min-height: 435px; + display: flex; + flex-direction: column; + align-items: center; + box-sizing: border-box; +} +.comfyui-view-list-popup h3 { + margin: 0 0 5px 0; +} +.comfyui-view-list-items { + width: 100%; + background: var(--comfy-menu-bg); + border-radius: 5px; + display: flex; + justify-content: center; + flex: auto; + align-items: center; + flex-direction: column; +} +.comfyui-view-list-items section { + max-height: 400px; + overflow: auto; + width: 100%; + display: grid; + grid-template-columns: auto auto auto; + align-items: center; + justify-content: center; + gap: 5px; + padding: 5px 0; +} +.comfyui-view-list-items section + section { + border-top: 1px solid var(--border-color); + margin-top: 10px; + padding-top: 5px; +} +.comfyui-view-list-items section h5 { + grid-column: 1 / 4; + text-align: center; + margin: 5px; +} +.comfyui-view-list-items span { + text-align: center; + padding: 0 2px; +} +.comfyui-view-list-popup header { + margin-bottom: 10px; + display: flex; + gap: 5px; +} +.comfyui-view-list-popup header .comfyui-button { + border: 1px solid transparent; +} +.comfyui-view-list-popup header .comfyui-button:not(:disabled):hover { + border: 1px solid var(--comfy-menu-bg); +} +/* Queue button */ +.comfyui-queue-button .comfyui-split-primary .comfyui-button { + padding-right: 12px; +} +.comfyui-queue-count { + margin-left: 5px; + border-radius: 10px; + background-color: rgb(8, 80, 153); + padding: 2px 4px; + font-size: 10px; + min-width: 1em; + display: inline-block; +} +/* Queue options*/ +.comfyui-queue-options { + padding: 10px; + font-family: Arial, Helvetica, sans-serif; + font-size: 12px; + display: flex; + gap: 10px; +} + +.comfyui-queue-batch { + display: flex; + flex-direction: column; + border-right: 1px solid var(--comfy-menu-bg); + padding-right: 10px; + gap: 5px; +} + +.comfyui-queue-batch input { + width: 145px; +} + +.comfyui-queue-batch .comfyui-queue-batch-value { + width: 70px; +} + +.comfyui-queue-mode { + display: flex; + flex-direction: column; +} + +.comfyui-queue-mode span { + font-weight: bold; + margin-bottom: 2px; +} + +.comfyui-queue-mode label { + display: flex; + flex-direction: row-reverse; + justify-content: start; + gap: 5px; + padding: 2px 0; +} + +.comfyui-queue-mode label input { + padding: 0; + margin: 0; +} + +/** Send to workflow widget selection dialog */ +.comfy-widget-selection-dialog { + border: none; +} + +.comfy-widget-selection-dialog div { + color: var(--fg-color); + font-family: Arial, Helvetica, sans-serif; +} + +.comfy-widget-selection-dialog h2 { + margin-top: 0; +} + +.comfy-widget-selection-dialog section { + width: -moz-fit-content; + width: fit-content; + display: flex; + flex-direction: column; +} + +.comfy-widget-selection-item { + display: flex; + gap: 10px; + align-items: center; +} + +.comfy-widget-selection-item span { + margin-right: auto; +} + +.comfy-widget-selection-item span::before { + content: '#' attr(data-id); + opacity: 0.5; + margin-right: 5px; +} + +.comfy-modal .comfy-widget-selection-item button { + font-size: 1em; +} + +/***** Responsive *****/ +.lg.comfyui-menu .lt-lg-show { + display: none !important; +} +.comfyui-menu:not(.lg) .nlg-hide { + display: none !important; +} +/** Large screen */ +.lg.comfyui-menu>.comfyui-menu-mobile-collapse .comfyui-button span, +.lg.comfyui-menu>.comfyui-menu-mobile-collapse.comfyui-button span { + display: none; +} +.lg.comfyui-menu>.comfyui-menu-mobile-collapse .comfyui-popup .comfyui-button span { + display: unset; +} + +/** Non large screen */ +.lt-lg.comfyui-menu { + flex-wrap: wrap; +} + +.lt-lg.comfyui-menu > *:not(.comfyui-menu-mobile-collapse) { + order: 1; +} + +.lt-lg.comfyui-menu > .comfyui-menu-mobile-collapse { + order: 9999; + width: 100%; +} + +.comfyui-body-bottom .lt-lg.comfyui-menu > .comfyui-menu-mobile-collapse { + order: -1; +} + +.comfyui-body-bottom .lt-lg.comfyui-menu > .comfyui-menu-button { + top: unset; + bottom: 4px; +} + +.lt-lg.comfyui-menu > .comfyui-menu-mobile-collapse.comfyui-button-group { + flex-wrap: wrap; +} + +.lt-lg.comfyui-menu > .comfyui-menu-mobile-collapse .comfyui-button, +.lt-lg.comfyui-menu > .comfyui-menu-mobile-collapse.comfyui-button { + padding: 10px; +} +.lt-lg.comfyui-menu > .comfyui-menu-mobile-collapse .comfyui-button, +.lt-lg.comfyui-menu > .comfyui-menu-mobile-collapse .comfyui-button-wrapper { + width: 100%; +} + +.lt-lg.comfyui-menu > .comfyui-menu-mobile-collapse .comfyui-popup { + position: static; + background-color: var(--comfy-input-bg); + max-width: unset; + max-height: 50vh; + overflow: auto; +} + +.lt-lg.comfyui-menu:not(.expanded) > .comfyui-menu-mobile-collapse { + display: none; +} + +.lt-lg .comfyui-queue-button { + margin-right: 44px; +} + +.lt-lg .comfyui-menu-button { + position: absolute; + top: 4px; + right: 8px; +} + +.lt-lg.comfyui-menu > .comfyui-menu-mobile-collapse .comfyui-view-list-popup { + border-radius: 0; +} + +.lt-lg.comfyui-menu .comfyui-workflows-popup { + width: 100vw; +} + +/** Small */ +.lt-md .comfyui-workflows-button-inner { + width: unset !important; +} +.lt-md .comfyui-workflows-label { + display: none; +} + +/** Extra small */ +.lt-sm .comfyui-queue-button { + margin-right: 0; + width: 100%; +} +.lt-sm .comfyui-queue-button .comfyui-button { + justify-content: center; +} +.lt-sm .comfyui-interrupt-button { + margin-right: 45px; +} +.comfyui-body-bottom .lt-sm.comfyui-menu > .comfyui-menu-button{ + bottom: 41px; +}/* this CSS contains only the basic CSS needed to run the app and use it */ + +.lgraphcanvas { + /*cursor: crosshair;*/ + user-select: none; + -moz-user-select: none; + -webkit-user-select: none; + outline: none; + font-family: Tahoma, sans-serif; +} + +.lgraphcanvas * { + box-sizing: border-box; +} + +.litegraph.litecontextmenu { + font-family: Tahoma, sans-serif; + position: fixed; + top: 100px; + left: 100px; + min-width: 100px; + color: #aaf; + padding: 0; + box-shadow: 0 0 10px black !important; + background-color: #2e2e2e !important; + z-index: 10; +} + +.litegraph.litecontextmenu.dark { + background-color: #000 !important; +} + +.litegraph.litecontextmenu .litemenu-title img { + margin-top: 2px; + margin-left: 2px; + margin-right: 4px; +} + +.litegraph.litecontextmenu .litemenu-entry { + margin: 2px; + padding: 2px; +} + +.litegraph.litecontextmenu .litemenu-entry.submenu { + background-color: #2e2e2e !important; +} + +.litegraph.litecontextmenu.dark .litemenu-entry.submenu { + background-color: #000 !important; +} + +.litegraph .litemenubar ul { + font-family: Tahoma, sans-serif; + margin: 0; + padding: 0; +} + +.litegraph .litemenubar li { + font-size: 14px; + color: #999; + display: inline-block; + min-width: 50px; + padding-left: 10px; + padding-right: 10px; + user-select: none; + -moz-user-select: none; + -webkit-user-select: none; + cursor: pointer; +} + +.litegraph .litemenubar li:hover { + background-color: #777; + color: #eee; +} + +.litegraph .litegraph .litemenubar-panel { + position: absolute; + top: 5px; + left: 5px; + min-width: 100px; + background-color: #444; + box-shadow: 0 0 3px black; + padding: 4px; + border-bottom: 2px solid #aaf; + z-index: 10; +} + +.litegraph .litemenu-entry, +.litemenu-title { + font-size: 12px; + color: #aaa; + padding: 0 0 0 4px; + margin: 2px; + padding-left: 2px; + -moz-user-select: none; + -webkit-user-select: none; + user-select: none; + cursor: pointer; +} + +.litegraph .litemenu-entry .icon { + display: inline-block; + width: 12px; + height: 12px; + margin: 2px; + vertical-align: top; +} + +.litegraph .litemenu-entry.checked .icon { + background-color: #aaf; +} + +.litegraph .litemenu-entry .more { + float: right; + padding-right: 5px; +} + +.litegraph .litemenu-entry.disabled { + opacity: 0.5; + cursor: default; +} + +.litegraph .litemenu-entry.separator { + display: block; + border-top: 1px solid #333; + border-bottom: 1px solid #666; + width: 100%; + height: 0px; + margin: 3px 0 2px 0; + background-color: transparent; + padding: 0 !important; + cursor: default !important; +} + +.litegraph .litemenu-entry.has_submenu { + border-right: 2px solid cyan; +} + +.litegraph .litemenu-title { + color: #dde; + background-color: #111; + margin: 0; + padding: 2px; + cursor: default; +} + +.litegraph .litemenu-entry:hover:not(.disabled):not(.separator) { + background-color: #444 !important; + color: #eee; + transition: all 0.2s; +} + +.litegraph .litemenu-entry .property_name { + display: inline-block; + text-align: left; + min-width: 80px; + min-height: 1.2em; +} + +.litegraph .litemenu-entry .property_value { + display: inline-block; + background-color: rgba(0, 0, 0, 0.5); + text-align: right; + min-width: 80px; + min-height: 1.2em; + vertical-align: middle; + padding-right: 10px; +} + +.litegraph.litesearchbox { + font-family: Tahoma, sans-serif; + position: absolute; + background-color: rgba(0, 0, 0, 0.5); + padding-top: 4px; +} + +.litegraph.litesearchbox input, +.litegraph.litesearchbox select { + margin-top: 3px; + min-width: 60px; + min-height: 1.5em; + background-color: black; + border: 0; + color: white; + padding-left: 10px; + margin-right: 5px; + max-width: 300px; +} + +.litegraph.litesearchbox .name { + display: inline-block; + min-width: 60px; + min-height: 1.5em; + padding-left: 10px; +} + +.litegraph.litesearchbox .helper { + overflow: auto; + max-height: 200px; + margin-top: 2px; +} + +.litegraph.lite-search-item { + font-family: Tahoma, sans-serif; + background-color: rgba(0, 0, 0, 0.5); + color: white; + padding-top: 2px; +} + +.litegraph.lite-search-item.not_in_filter{ + /*background-color: rgba(50, 50, 50, 0.5);*/ + /*color: #999;*/ + color: #B99; + font-style: italic; +} + +.litegraph.lite-search-item.generic_type{ + /*background-color: rgba(50, 50, 50, 0.5);*/ + /*color: #DD9;*/ + color: #999; + font-style: italic; +} + +.litegraph.lite-search-item:hover, +.litegraph.lite-search-item.selected { + cursor: pointer; + background-color: white; + color: black; +} + +.litegraph.lite-search-item-type { + display: inline-block; + background: rgba(0,0,0,0.2); + margin-left: 5px; + font-size: 14px; + padding: 2px 5px; + position: relative; + top: -2px; + opacity: 0.8; + border-radius: 4px; + } + +/* DIALOGs ******/ + +.litegraph .dialog { + position: absolute; + top: 50%; + left: 50%; + margin-top: -150px; + margin-left: -200px; + + background-color: #2A2A2A; + + min-width: 400px; + min-height: 200px; + box-shadow: 0 0 4px #111; + border-radius: 6px; +} + +.litegraph .dialog.settings { + left: 10px; + top: 10px; + height: calc( 100% - 20px ); + margin: auto; + max-width: 50%; +} + +.litegraph .dialog.centered { + top: 50px; + left: 50%; + position: absolute; + transform: translateX(-50%); + min-width: 600px; + min-height: 300px; + height: calc( 100% - 100px ); + margin: auto; +} + +.litegraph .dialog .close { + float: right; + margin: 4px; + margin-right: 10px; + cursor: pointer; + font-size: 1.4em; +} + +.litegraph .dialog .close:hover { + color: white; +} + +.litegraph .dialog .dialog-header { + color: #AAA; + border-bottom: 1px solid #161616; height: 40px; +} +.litegraph .dialog .dialog-footer { height: 50px; padding: 10px; border-top: 1px solid #1a1a1a;} + +.litegraph .dialog .dialog-header .dialog-title { + font: 20px "Arial"; + margin: 4px; + padding: 4px 10px; + display: inline-block; +} + +.litegraph .dialog .dialog-content, .litegraph .dialog .dialog-alt-content { + height: calc(100% - 90px); + width: 100%; + min-height: 100px; + display: inline-block; + color: #AAA; + /*background-color: black;*/ + overflow: auto; +} + +.litegraph .dialog .dialog-content h3 { + margin: 10px; +} + +.litegraph .dialog .dialog-content .connections { + flex-direction: row; +} + +.litegraph .dialog .dialog-content .connections .connections_side { + width: calc(50% - 5px); + min-height: 100px; + background-color: black; + display: flex; +} + +.litegraph .dialog .node_type { + font-size: 1.2em; + display: block; + margin: 10px; +} + +.litegraph .dialog .node_desc { + opacity: 0.5; + display: block; + margin: 10px; +} + +.litegraph .dialog .separator { + display: block; + width: calc( 100% - 4px ); + height: 1px; + border-top: 1px solid #000; + border-bottom: 1px solid #333; + margin: 10px 2px; + padding: 0; +} + +.litegraph .dialog .property { + margin-bottom: 2px; + padding: 4px; +} + +.litegraph .dialog .property:hover { + background: #545454; +} + +.litegraph .dialog .property_name { + color: #737373; + display: inline-block; + text-align: left; + vertical-align: top; + width: 160px; + padding-left: 4px; + overflow: hidden; + margin-right: 6px; +} + +.litegraph .dialog .property:hover .property_name { + color: white; +} + +.litegraph .dialog .property_value { + display: inline-block; + text-align: right; + color: #AAA; + background-color: #1A1A1A; + /*width: calc( 100% - 122px );*/ + max-width: calc( 100% - 162px ); + min-width: 200px; + max-height: 300px; + min-height: 20px; + padding: 4px; + padding-right: 12px; + overflow: hidden; + cursor: pointer; + border-radius: 3px; +} + +.litegraph .dialog .property_value:hover { + color: white; +} + +.litegraph .dialog .property.boolean .property_value { + padding-right: 30px; + color: #A88; + /*width: auto; + float: right;*/ +} + +.litegraph .dialog .property.boolean.bool-on .property_name{ + color: #8A8; +} +.litegraph .dialog .property.boolean.bool-on .property_value{ + color: #8A8; +} + +.litegraph .dialog .btn { + border: 0; + border-radius: 4px; + padding: 4px 20px; + margin-left: 0px; + background-color: #060606; + color: #8e8e8e; +} + +.litegraph .dialog .btn:hover { + background-color: #111; + color: #FFF; +} + +.litegraph .dialog .btn.delete:hover { + background-color: #F33; + color: black; +} + +.litegraph .subgraph_property { + padding: 4px; +} + +.litegraph .subgraph_property:hover { + background-color: #333; +} + +.litegraph .subgraph_property.extra { + margin-top: 8px; +} + +.litegraph .subgraph_property span.name { + font-size: 1.3em; + padding-left: 4px; +} + +.litegraph .subgraph_property span.type { + opacity: 0.5; + margin-right: 20px; + padding-left: 4px; +} + +.litegraph .subgraph_property span.label { + display: inline-block; + width: 60px; + padding: 0px 10px; +} + +.litegraph .subgraph_property input { + width: 140px; + color: #999; + background-color: #1A1A1A; + border-radius: 4px; + border: 0; + margin-right: 10px; + padding: 4px; + padding-left: 10px; +} + +.litegraph .subgraph_property button { + background-color: #1c1c1c; + color: #aaa; + border: 0; + border-radius: 2px; + padding: 4px 10px; + cursor: pointer; +} + +.litegraph .subgraph_property.extra { + color: #ccc; +} + +.litegraph .subgraph_property.extra input { + background-color: #111; +} + +.litegraph .bullet_icon { + margin-left: 10px; + border-radius: 10px; + width: 12px; + height: 12px; + background-color: #666; + display: inline-block; + margin-top: 2px; + margin-right: 4px; + transition: background-color 0.1s ease 0s; + -moz-transition: background-color 0.1s ease 0s; +} + +.litegraph .bullet_icon:hover { + background-color: #698; + cursor: pointer; +} + +/* OLD */ + +.graphcontextmenu { + padding: 4px; + min-width: 100px; +} + +.graphcontextmenu-title { + color: #dde; + background-color: #222; + margin: 0; + padding: 2px; + cursor: default; +} + +.graphmenu-entry { + box-sizing: border-box; + margin: 2px; + padding-left: 20px; + user-select: none; + -moz-user-select: none; + -webkit-user-select: none; + transition: all linear 0.3s; +} + +.graphmenu-entry.event, +.litemenu-entry.event { + border-left: 8px solid orange; + padding-left: 12px; +} + +.graphmenu-entry.disabled { + opacity: 0.3; +} + +.graphmenu-entry.submenu { + border-right: 2px solid #eee; +} + +.graphmenu-entry:hover { + background-color: #555; +} + +.graphmenu-entry.separator { + background-color: #111; + border-bottom: 1px solid #666; + height: 1px; + width: calc(100% - 20px); + -moz-width: calc(100% - 20px); + -webkit-width: calc(100% - 20px); +} + +.graphmenu-entry .property_name { + display: inline-block; + text-align: left; + min-width: 80px; + min-height: 1.2em; +} + +.graphmenu-entry .property_value, +.litemenu-entry .property_value { + display: inline-block; + background-color: rgba(0, 0, 0, 0.5); + text-align: right; + min-width: 80px; + min-height: 1.2em; + vertical-align: middle; + padding-right: 10px; +} + +.graphdialog { + position: absolute; + top: 10px; + left: 10px; + min-height: 2em; + background-color: #333; + font-size: 1.2em; + box-shadow: 0 0 10px black !important; + z-index: 10; +} + +.graphdialog.rounded { + border-radius: 12px; + padding-right: 2px; +} + +.graphdialog .name { + display: inline-block; + min-width: 60px; + min-height: 1.5em; + padding-left: 10px; +} + +.graphdialog input, +.graphdialog textarea, +.graphdialog select { + margin: 3px; + min-width: 60px; + min-height: 1.5em; + background-color: black; + border: 0; + color: white; + padding-left: 10px; + outline: none; +} + +.graphdialog textarea { + min-height: 150px; +} + +.graphdialog button { + margin-top: 3px; + vertical-align: top; + background-color: #999; + border: 0; +} + +.graphdialog button.rounded, +.graphdialog input.rounded { + border-radius: 0 12px 12px 0; +} + +.graphdialog .helper { + overflow: auto; + max-height: 200px; +} + +.graphdialog .help-item { + padding-left: 10px; +} + +.graphdialog .help-item:hover, +.graphdialog .help-item.selected { + cursor: pointer; + background-color: white; + color: black; +} + +.litegraph .dialog { + min-height: 0; +} +.litegraph .dialog .dialog-content { +display: block; +} +.litegraph .dialog .dialog-content .subgraph_property { +padding: 5px; +} +.litegraph .dialog .dialog-footer { +margin: 0; +} +.litegraph .dialog .dialog-footer .subgraph_property { +margin-top: 0; +display: flex; +align-items: center; +padding: 5px; +} +.litegraph .dialog .dialog-footer .subgraph_property .name { +flex: 1; +} +.litegraph .graphdialog { +display: flex; +align-items: center; +border-radius: 20px; +padding: 4px 10px; +position: fixed; +} +.litegraph .graphdialog .name { +padding: 0; +min-height: 0; +font-size: 16px; +vertical-align: middle; +} +.litegraph .graphdialog .value { +font-size: 16px; +min-height: 0; +margin: 0 10px; +padding: 2px 5px; +} +.litegraph .graphdialog input[type="checkbox"] { +width: 16px; +height: 16px; +} +.litegraph .graphdialog button { +padding: 4px 18px; +border-radius: 20px; +cursor: pointer; +} + +:root { + --fg-color: #000; + --bg-color: #fff; + --comfy-menu-bg: #353535; + --comfy-input-bg: #222; + --input-text: #ddd; + --descrip-text: #999; + --drag-text: #ccc; + --error-text: #ff4444; + --border-color: #4e4e4e; + --tr-even-bg-color: #222; + --tr-odd-bg-color: #353535; + --primary-bg: #236692; + --primary-fg: #ffffff; + --primary-hover-bg: #3485bb; + --primary-hover-fg: #ffffff; + --content-bg: #e0e0e0; + --content-fg: #000; + --content-hover-bg: #adadad; + --content-hover-fg: #000; +} + +@media (prefers-color-scheme: dark) { + :root { + --fg-color: #fff; + --bg-color: #202020; + --content-bg: #4e4e4e; + --content-fg: #fff; + --content-hover-bg: #222; + --content-hover-fg: #fff; + } +} + +body { + width: 100vw; + height: 100vh; + margin: 0; + overflow: hidden; + grid-template-columns: auto 1fr auto; + grid-template-rows: auto 1fr auto; + background-color: var(--bg-color); + color: var(--fg-color); + min-height: -webkit-fill-available; + max-height: -webkit-fill-available; + min-width: -webkit-fill-available; + max-width: -webkit-fill-available; + font-family: Arial, sans-serif; +} + +/** + +------------------+------------------+------------------+ + | | + | .comfyui-body- | + | top | + | (spans all cols) | + | | + +------------------+------------------+------------------+ + | | | | + | .comfyui-body- | #graph-canvas | .comfyui-body- | + | left | | right | + | | | | + | | | | + +------------------+------------------+------------------+ + | | + | .comfyui-body- | + | bottom | + | (spans all cols) | + | | + +------------------+------------------+------------------+ +*/ + +.comfyui-body-top { + order: -5; + /* Span across all columns */ + grid-column: 1/-1; + /* Position at the first row */ + grid-row: 1; + z-index: 10; + display: flex; + flex-direction: column; +} + +.comfyui-body-left { + order: -4; + /* Position in the first column */ + grid-column: 1; + /* Position below the top element */ + grid-row: 2; + z-index: 10; + display: flex; +} + +.graph-canvas-container { + width: 100%; + height: 100%; + order: -3; + grid-column: 2; + grid-row: 2; + position: relative; + overflow: hidden; +} + +#graph-canvas { + width: 100%; + height: 100%; +} + +.comfyui-body-right { + order: -2; + z-index: 10; + grid-column: 3; + grid-row: 2; +} + +.comfyui-body-bottom { + order: 4; + /* Span across all columns */ + grid-column: 1/-1; + grid-row: 3; + z-index: 10; + display: flex; + flex-direction: column; +} + +.comfy-multiline-input { + background-color: var(--comfy-input-bg); + color: var(--input-text); + overflow: hidden; + overflow-y: auto; + padding: 2px; + resize: none; + border: none; + box-sizing: border-box; + font-size: 10px; +} + +.comfy-modal { + display: none; /* Hidden by default */ + position: fixed; /* Stay in place */ + z-index: 100; /* Sit on top */ + padding: 30px 30px 10px 30px; + background-color: var(--comfy-menu-bg); /* Modal background */ + color: var(--error-text); + box-shadow: 0 0 20px #888888; + border-radius: 10px; + top: 50%; + left: 50%; + max-width: 80vw; + max-height: 80vh; + transform: translate(-50%, -50%); + overflow: hidden; + justify-content: center; + font-family: monospace; + font-size: 15px; +} + +.comfy-modal-content { + display: flex; + flex-direction: column; +} + +.comfy-modal p { + overflow: auto; + white-space: pre-line; /* This will respect line breaks */ + margin-bottom: 20px; /* Add some margin between the text and the close button*/ +} + +.comfy-modal select, +.comfy-modal input[type=button], +.comfy-modal input[type=checkbox] { + margin: 3px 3px 3px 4px; +} + +.comfy-menu-hamburger { + position: fixed; + top: 10px; + z-index: 9999; + right: 10px; + width: 30px; + display: none; + gap: 8px; + flex-direction: column; + cursor: pointer; +} + +.comfy-menu-hamburger div { + height: 3px; + width: 100%; + border-radius: 20px; + background-color: white; +} + +.comfy-menu { + font-size: 15px; + position: absolute; + top: 50%; + right: 0; + text-align: center; + z-index: 999; + width: 190px; + display: flex; + flex-direction: column; + align-items: center; + color: var(--descrip-text); + background-color: var(--comfy-menu-bg); + font-family: sans-serif; + padding: 10px; + border-radius: 0 8px 8px 8px; + box-shadow: 3px 3px 8px rgba(0, 0, 0, 0.4); +} + +.comfy-menu-header { + display: flex; +} + +.comfy-menu-actions { + display: flex; + gap: 3px; + align-items: center; + height: 20px; + position: relative; + top: -1px; + font-size: 22px; +} + +.comfy-menu .comfy-menu-actions button { + background-color: rgba(0, 0, 0, 0); + padding: 0; + border: none; + cursor: pointer; + font-size: inherit; +} + +.comfy-menu .comfy-menu-actions .comfy-settings-btn { + font-size: 0.6em; +} + +button.comfy-close-menu-btn { + font-size: 1em; + line-height: 12px; + color: #ccc; + position: relative; + top: -1px; +} + +.comfy-menu-queue-size { + flex: auto; +} + +.comfy-menu button, +.comfy-modal button { + font-size: 20px; +} + +.comfy-menu-btns { + margin-bottom: 10px; + width: 100%; +} + +.comfy-menu-btns button { + font-size: 10px; + width: 50%; + color: var(--descrip-text) !important; +} + +.comfy-menu > button { + width: 100%; +} + +.comfy-btn, +.comfy-menu > button, +.comfy-menu-btns button, +.comfy-menu .comfy-list button, +.comfy-modal button { + color: var(--input-text); + background-color: var(--comfy-input-bg); + border-radius: 8px; + border-color: var(--border-color); + border-style: solid; + margin-top: 2px; +} + +.comfy-btn:hover:not(:disabled), +.comfy-menu > button:hover, +.comfy-menu-btns button:hover, +.comfy-menu .comfy-list button:hover, +.comfy-modal button:hover, +.comfy-menu-actions button:hover { + filter: brightness(1.2); + will-change: transform; + cursor: pointer; +} + +span.drag-handle { + width: 10px; + height: 20px; + display: inline-block; + overflow: hidden; + line-height: 5px; + padding: 3px 4px; + cursor: move; + vertical-align: middle; + margin-top: -.4em; + margin-left: -.2em; + font-size: 12px; + font-family: sans-serif; + letter-spacing: 2px; + color: var(--drag-text); + text-shadow: 1px 0 1px black; +} + +span.drag-handle::after { + content: '.. .. ..'; +} + +.comfy-queue-btn { + width: 100%; +} + +.comfy-list { + color: var(--descrip-text); + background-color: var(--comfy-menu-bg); + margin-bottom: 10px; + border-color: var(--border-color); + border-style: solid; +} + +.comfy-list-items { + overflow-y: scroll; + max-height: 100px; + min-height: 25px; + background-color: var(--comfy-input-bg); + padding: 5px; +} + +.comfy-list h4 { + min-width: 160px; + margin: 0; + padding: 3px; + font-weight: normal; +} + +.comfy-list-items button { + font-size: 10px; +} + +.comfy-list-actions { + margin: 5px; + display: flex; + gap: 5px; + justify-content: center; +} + +.comfy-list-actions button { + font-size: 12px; +} + +button.comfy-queue-btn { + margin: 6px 0 !important; +} + +.comfy-modal.comfy-settings, +.comfy-modal.comfy-manage-templates { + text-align: center; + font-family: sans-serif; + color: var(--descrip-text); + z-index: 99; +} + +.comfy-modal.comfy-settings input[type="range"] { + vertical-align: middle; +} + +.comfy-modal.comfy-settings input[type="range"] + input[type="number"] { + width: 3.5em; +} + +.comfy-modal input, +.comfy-modal select { + color: var(--input-text); + background-color: var(--comfy-input-bg); + border-radius: 8px; + border-color: var(--border-color); + border-style: solid; + font-size: inherit; +} + +.comfy-tooltip-indicator { + text-decoration: underline; + text-decoration-style: dashed; +} + +@media only screen and (max-height: 850px) { + .comfy-menu { + top: 0 !important; + bottom: 0 !important; + left: auto !important; + right: 0 !important; + border-radius: 0; + } + + .comfy-menu span.drag-handle { + display: none; + } + + .comfy-menu-queue-size { + flex: unset; + } + + .comfy-menu-header { + justify-content: space-between; + } + .comfy-menu-actions { + gap: 10px; + font-size: 28px; + } +} + +/* Input popup */ + +.graphdialog { + min-height: 1em; + background-color: var(--comfy-menu-bg); +} + +.graphdialog .name { + font-size: 14px; + font-family: sans-serif; + color: var(--descrip-text); +} + +.graphdialog button { + margin-top: unset; + vertical-align: unset; + height: 1.6em; + padding-right: 8px; +} + +.graphdialog input, .graphdialog textarea, .graphdialog select { + background-color: var(--comfy-input-bg); + border: 2px solid; + border-color: var(--border-color); + color: var(--input-text); + border-radius: 12px 0 0 12px; +} + +/* Dialogs */ + +dialog { + box-shadow: 0 0 20px #888888; +} + +dialog::backdrop { + background: rgba(0, 0, 0, 0.5); +} + +.comfy-dialog.comfyui-dialog.comfy-modal { + top: 0; + left: 0; + right: 0; + bottom: 0; + transform: none; +} + +.comfy-dialog.comfy-modal { + font-family: Arial, sans-serif; + border-color: var(--bg-color); + box-shadow: none; + border: 2px solid var(--border-color); +} + +.comfy-dialog .comfy-modal-content { + flex-direction: row; + flex-wrap: wrap; + gap: 10px; + color: var(--fg-color); +} + +.comfy-dialog .comfy-modal-content h3 { + margin-top: 0; +} + +.comfy-dialog .comfy-modal-content > p { + width: 100%; +} + +.comfy-dialog .comfy-modal-content > .comfyui-button { + flex: 1; + justify-content: center; +} + +#comfy-settings-dialog { + padding: 0; + width: 41rem; +} + +#comfy-settings-dialog tr > td:first-child { + text-align: right; +} + +#comfy-settings-dialog tbody button, #comfy-settings-dialog table > button { + background-color: var(--bg-color); + border: 1px var(--border-color) solid; + border-radius: 0; + color: var(--input-text); + font-size: 1rem; + padding: 0.5rem; +} + +#comfy-settings-dialog button:hover { + background-color: var(--tr-odd-bg-color); +} + +/* General CSS for tables */ + +.comfy-table { + border-collapse: collapse; + color: var(--input-text); + font-family: Arial, sans-serif; + width: 100%; +} + +.comfy-table caption { + position: sticky; + top: 0; + background-color: var(--bg-color); + color: var(--input-text); + font-size: 1rem; + font-weight: bold; + padding: 8px; + text-align: center; + border-bottom: 1px solid var(--border-color); +} + +.comfy-table caption .comfy-btn { + position: absolute; + top: -2px; + right: 0; + bottom: 0; + cursor: pointer; + border: none; + height: 100%; + border-radius: 0; + aspect-ratio: 1/1; + -webkit-user-select: none; + -moz-user-select: none; + user-select: none; + font-size: 20px; +} + +.comfy-table caption .comfy-btn:focus { + outline: none; +} + +.comfy-table tr:nth-child(even) { + background-color: var(--tr-even-bg-color); +} + +.comfy-table tr:nth-child(odd) { + background-color: var(--tr-odd-bg-color); +} + +.comfy-table td, +.comfy-table th { + border: 1px solid var(--border-color); + padding: 8px; +} + +/* Context menu */ + +.litegraph .dialog { + z-index: 1; + font-family: Arial, sans-serif; +} + +.litegraph .litemenu-entry.has_submenu { + position: relative; + padding-right: 20px; +} + +.litemenu-entry.has_submenu::after { + content: ">"; + position: absolute; + top: 0; + right: 2px; +} + +.litegraph.litecontextmenu, +.litegraph.litecontextmenu.dark { + z-index: 9999 !important; + background-color: var(--comfy-menu-bg) !important; + filter: brightness(95%); + will-change: transform; +} + +.litegraph.litecontextmenu .litemenu-entry:hover:not(.disabled):not(.separator) { + background-color: var(--comfy-menu-bg) !important; + filter: brightness(155%); + will-change: transform; + color: var(--input-text); +} + +.litegraph.litecontextmenu .litemenu-entry.submenu, +.litegraph.litecontextmenu.dark .litemenu-entry.submenu { + background-color: var(--comfy-menu-bg) !important; + color: var(--input-text); +} + +.litegraph.litecontextmenu input { + background-color: var(--comfy-input-bg) !important; + color: var(--input-text) !important; +} + +.comfy-context-menu-filter { + box-sizing: border-box; + border: 1px solid #999; + margin: 0 0 5px 5px; + width: calc(100% - 10px); +} + +.comfy-img-preview { + pointer-events: none; + overflow: hidden; + display: flex; + flex-wrap: wrap; + align-content: flex-start; + justify-content: center; +} + +.comfy-img-preview img { + -o-object-fit: contain; + object-fit: contain; + width: var(--comfy-img-preview-width); + height: var(--comfy-img-preview-height); +} + +.comfy-missing-nodes li button { + font-size: 12px; + margin-left: 5px; +} + +/* Search box */ + +.litegraph.litesearchbox { + z-index: 9999 !important; + background-color: var(--comfy-menu-bg) !important; + overflow: hidden; + display: block; +} + +.litegraph.litesearchbox input, +.litegraph.litesearchbox select { + background-color: var(--comfy-input-bg) !important; + color: var(--input-text); +} + +.litegraph.lite-search-item { + color: var(--input-text); + background-color: var(--comfy-input-bg); + filter: brightness(80%); + will-change: transform; + padding-left: 0.2em; +} + +.litegraph.lite-search-item.generic_type { + color: var(--input-text); + filter: brightness(50%); + will-change: transform; +} + +@media only screen and (max-width: 450px) { + #comfy-settings-dialog .comfy-table tbody { + display: grid; + } + #comfy-settings-dialog .comfy-table tr { + display: grid; + } + #comfy-settings-dialog tr > td:first-child { + text-align: center; + border-bottom: none; + padding-bottom: 0; + } + #comfy-settings-dialog tr > td:not(:first-child) { + text-align: center; + border-top: none; + } +} + +audio.comfy-audio.empty-audio-widget { + display: none; +} + +#vue-app { + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; + pointer-events: none; +} + +/* Set auto complete panel's width as it is not accessible within vue-root */ +.p-autocomplete-overlay { + max-width: 25vw; +} + +:root { + --red-600: #dc3545; +} + +.comfy-missing-nodes[data-v-286402f2] { + font-family: monospace; + color: var(--red-600); + padding: 1.5rem; + background-color: var(--surface-ground); + border-radius: var(--border-radius); + box-shadow: var(--card-shadow); +} +.warning-title[data-v-286402f2] { + margin-top: 0; + margin-bottom: 1rem; +} +.warning-description[data-v-286402f2] { + margin-bottom: 1rem; +} +.missing-nodes-list[data-v-286402f2] { + max-height: 300px; + overflow-y: auto; +} +.missing-nodes-list.maximized[data-v-286402f2] { + max-height: unset; +} +.missing-node-item[data-v-286402f2] { + display: flex; + align-items: center; + padding: 0.5rem; +} +.node-type[data-v-286402f2] { + font-weight: 600; + color: var(--text-color); +} +.node-hint[data-v-286402f2] { + margin-left: 0.5rem; + font-style: italic; + color: var(--text-color-secondary); +} +[data-v-286402f2] .p-button { + margin-left: auto; +} +.added-nodes-warning[data-v-286402f2] { + margin-top: 1rem; + font-style: italic; +} + +.input-slider[data-v-fbaf7a8c] { + display: flex; + align-items: center; + gap: 1rem; +} +.slider-part[data-v-fbaf7a8c] { + flex-grow: 1; +} +.input-part[data-v-fbaf7a8c] { + width: 5rem !important; +} + +.info-chip[data-v-4feeb3d2] { + background: transparent; +} +.setting-item[data-v-4feeb3d2] { + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: 1rem; +} +.setting-label[data-v-4feeb3d2] { + display: flex; + align-items: center; + flex: 1; +} +.setting-input[data-v-4feeb3d2] { + flex: 1; + display: flex; + justify-content: flex-end; + margin-left: 1rem; +} + +/* Ensure PrimeVue components take full width of their container */ +.setting-input[data-v-4feeb3d2] .p-inputtext, +.setting-input[data-v-4feeb3d2] .input-slider, +.setting-input[data-v-4feeb3d2] .p-select, +.setting-input[data-v-4feeb3d2] .p-togglebutton { + width: 100%; + max-width: 200px; +} +.setting-input[data-v-4feeb3d2] .p-inputtext { + max-width: unset; +} + +/* Special case for ToggleSwitch to align it to the right */ +.setting-input[data-v-4feeb3d2] .p-toggleswitch { + margin-left: auto; +} + +.search-box-input[data-v-3bbe5335] { + width: 100%; +} + +.no-results-placeholder[data-v-5a7d148a] { + display: flex; + justify-content: center; + align-items: center; + height: 100%; + padding: 2rem; +} +.no-results-placeholder[data-v-5a7d148a] .p-card { + background-color: var(--surface-ground); + text-align: center; +} +.no-results-placeholder h3[data-v-5a7d148a] { + color: var(--text-color); + margin-bottom: 0.5rem; +} +.no-results-placeholder p[data-v-5a7d148a] { + color: var(--text-color-secondary); + margin-bottom: 1rem; +} + +/* Remove after we have tailwind setup */ +.border-none { + border: none !important; +} +.settings-tab-panels { + padding-top: 0px !important; +} + +.settings-container[data-v-833dbfbb] { + display: flex; + height: 70vh; + width: 60vw; + max-width: 1000px; + overflow: hidden; + /* Prevents container from scrolling */ +} +.settings-sidebar[data-v-833dbfbb] { + width: 250px; + flex-shrink: 0; + /* Prevents sidebar from shrinking */ + overflow-y: auto; + padding: 10px; +} +.settings-search-box[data-v-833dbfbb] { + width: 100%; + margin-bottom: 10px; +} +.settings-content[data-v-833dbfbb] { + flex-grow: 1; + overflow-y: auto; + /* Allows vertical scrolling */ +} + +/* Ensure the Listbox takes full width of the sidebar */ +.settings-sidebar[data-v-833dbfbb] .p-listbox { + width: 100%; +} + +/* Optional: Style scrollbars for webkit browsers */ +.settings-sidebar[data-v-833dbfbb]::-webkit-scrollbar, +.settings-content[data-v-833dbfbb]::-webkit-scrollbar { + width: 1px; +} +.settings-sidebar[data-v-833dbfbb]::-webkit-scrollbar-thumb, +.settings-content[data-v-833dbfbb]::-webkit-scrollbar-thumb { + background-color: transparent; +} + +.pi-cog[data-v-969a1066] { + font-size: 1.25rem; + margin-right: 0.5rem; +} +.version-tag[data-v-969a1066] { + margin-left: 0.5rem; +} + +:root { + --sidebar-width: 64px; + --sidebar-icon-size: 1.5rem; +} +:root .small-sidebar { + --sidebar-width: 40px; + --sidebar-icon-size: 1rem; +} + +.side-tool-bar-container[data-v-f54e0ebc] { + display: flex; + flex-direction: column; + align-items: center; + + pointer-events: auto; + + width: var(--sidebar-width); + height: 100%; + + background-color: var(--comfy-menu-bg); + color: var(--fg-color); +} +.side-tool-bar-end[data-v-f54e0ebc] { + align-self: flex-end; + margin-top: auto; +} +.sidebar-content-container[data-v-f54e0ebc] { + height: 100%; + overflow-y: auto; +} + +.p-splitter-gutter { + pointer-events: auto; +} +.gutter-hidden { + display: none !important; +} + +.side-bar-panel[data-v-1c49e664] { + background-color: var(--bg-color); + pointer-events: auto; +} +.splitter-overlay[data-v-1c49e664] { + width: 100%; + height: 100%; + position: absolute; + top: 0; + left: 0; + background-color: transparent; + pointer-events: none; + /* Set it the same as the ComfyUI menu */ + /* Note: Lite-graph DOM widgets have the same z-index as the node id, so + 999 should be sufficient to make sure splitter overlays on node's DOM + widgets */ + z-index: 999; + border: none; +} + +._filter-button[data-v-071f55e3] { + z-index: 10; +} +._dialog[data-v-071f55e3] { + min-width: 24rem; +} +._dialog-body[data-v-071f55e3] { + display: flex; + flex-direction: column; +} +._dialog-body[data-v-071f55e3] > :not([hidden]) ~ :not([hidden]) { + --tw-space-y-reverse: 0; + margin-top: calc(0.5rem * calc(1 - var(--tw-space-y-reverse))); + margin-bottom: calc(0.5rem * var(--tw-space-y-reverse)); +} + +.comfy-core[data-v-1d7c94e5], +.comfy-custom-nodes[data-v-1d7c94e5], +.comfy-unknown[data-v-1d7c94e5] { + font-size: small; + font-weight: lighter; +} + +.slot_row[data-v-d926c92a] { + padding: 2px; +} + +/* Original N-Sidebar styles */ +._sb_dot[data-v-d926c92a] { + width: 8px; + height: 8px; + border-radius: 50%; + background-color: grey; +} +.node_header[data-v-d926c92a] { + line-height: 1; + padding: 8px 13px 7px; + background: var(--comfy-input-bg); + margin-bottom: 5px; + font-size: 15px; + text-wrap: nowrap; + overflow: hidden; + display: flex; + align-items: center; +} +.headdot[data-v-d926c92a] { + width: 10px; + height: 10px; + float: inline-start; + margin-right: 8px; +} +.IMAGE[data-v-d926c92a] { + background-color: #64b5f6; +} +.VAE[data-v-d926c92a] { + background-color: #ff6e6e; +} +.LATENT[data-v-d926c92a] { + background-color: #ff9cf9; +} +.MASK[data-v-d926c92a] { + background-color: #81c784; +} +.CONDITIONING[data-v-d926c92a] { + background-color: #ffa931; +} +.CLIP[data-v-d926c92a] { + background-color: #ffd500; +} +.MODEL[data-v-d926c92a] { + background-color: #b39ddb; +} +.CONTROL_NET[data-v-d926c92a] { + background-color: #a5d6a7; +} +._sb_node_preview[data-v-d926c92a] { + background-color: var(--comfy-menu-bg); + font-family: 'Open Sans', sans-serif; + font-size: small; + color: var(--descrip-text); + border: 1px solid var(--descrip-text); + min-width: 300px; + width: -moz-min-content; + width: min-content; + height: -moz-fit-content; + height: fit-content; + z-index: 9999; + border-radius: 12px; + overflow: hidden; + font-size: 12px; + padding-bottom: 10px; +} +._sb_node_preview ._sb_description[data-v-d926c92a] { + margin: 10px; + padding: 6px; + background: var(--border-color); + border-radius: 5px; + font-style: italic; + font-weight: 500; + font-size: 0.9rem; + word-break: break-word; +} +._sb_table[data-v-d926c92a] { + display: grid; + + grid-column-gap: 10px; + /* Spazio tra le colonne */ + width: 100%; + /* Imposta la larghezza della tabella al 100% del contenitore */ +} +._sb_row[data-v-d926c92a] { + display: grid; + grid-template-columns: 10px 1fr 1fr 1fr 10px; + grid-column-gap: 10px; + align-items: center; + padding-left: 9px; + padding-right: 9px; +} +._sb_row_string[data-v-d926c92a] { + grid-template-columns: 10px 1fr 1fr 10fr 1fr; +} +._sb_col[data-v-d926c92a] { + border: 0px solid #000; + display: flex; + align-items: flex-end; + flex-direction: row-reverse; + flex-wrap: nowrap; + align-content: flex-start; + justify-content: flex-end; +} +._sb_inherit[data-v-d926c92a] { + display: inherit; +} +._long_field[data-v-d926c92a] { + background: var(--bg-color); + border: 2px solid var(--border-color); + margin: 5px 5px 0 5px; + border-radius: 10px; + line-height: 1.7; + text-wrap: nowrap; +} +._sb_arrow[data-v-d926c92a] { + color: var(--fg-color); +} +._sb_preview_badge[data-v-d926c92a] { + text-align: center; + background: var(--comfy-input-bg); + font-weight: bold; + color: var(--error-text); +} + +.comfy-vue-node-search-container[data-v-9b4aa1b3] { + display: flex; + width: 100%; + min-width: 24rem; + align-items: center; + justify-content: center; +} +.comfy-vue-node-search-container[data-v-9b4aa1b3] * { + pointer-events: auto; +} +.comfy-vue-node-preview-container[data-v-9b4aa1b3] { + position: absolute; + left: -350px; + top: 50px; +} +.comfy-vue-node-search-box[data-v-9b4aa1b3] { + z-index: 10; + flex-grow: 1; +} +.option-container[data-v-9b4aa1b3] { + display: flex; + width: 100%; + cursor: pointer; + flex-direction: column; + overflow: hidden; + padding-left: 1rem; + padding-right: 1rem; + padding-top: 0.5rem; + padding-bottom: 0.5rem; +} +.option-display-name[data-v-9b4aa1b3] { + font-weight: 600; +} +.option-category[data-v-9b4aa1b3] { + overflow: hidden; + text-overflow: ellipsis; + font-size: 0.875rem; + line-height: 1.25rem; + --tw-text-opacity: 1; + color: rgb(156 163 175 / var(--tw-text-opacity)); + /* Keeps the text on a single line by default */ + white-space: nowrap; +} +.i-badge[data-v-9b4aa1b3] { + --tw-bg-opacity: 1; + background-color: rgb(34 197 94 / var(--tw-bg-opacity)); + --tw-text-opacity: 1; + color: rgb(255 255 255 / var(--tw-text-opacity)); +} +.o-badge[data-v-9b4aa1b3] { + --tw-bg-opacity: 1; + background-color: rgb(239 68 68 / var(--tw-bg-opacity)); + --tw-text-opacity: 1; + color: rgb(255 255 255 / var(--tw-text-opacity)); +} +.c-badge[data-v-9b4aa1b3] { + --tw-bg-opacity: 1; + background-color: rgb(59 130 246 / var(--tw-bg-opacity)); + --tw-text-opacity: 1; + color: rgb(255 255 255 / var(--tw-text-opacity)); +} +.s-badge[data-v-9b4aa1b3] { + --tw-bg-opacity: 1; + background-color: rgb(234 179 8 / var(--tw-bg-opacity)); +} +[data-v-9b4aa1b3] .highlight { + background-color: var(--p-primary-color); + color: var(--p-primary-contrast-color); + font-weight: bold; + border-radius: 0.25rem; + padding: 0.125rem 0.25rem; + margin: -0.125rem 0.125rem; +} + +.invisible-dialog-root { + width: 30%; + min-width: 24rem; + max-width: 48rem; + border: 0 !important; + background-color: transparent !important; + margin-top: 25vh; +} +.node-search-box-dialog-mask { + align-items: flex-start !important; +} + +.node-tooltip[data-v-d6edb6a0] { + background: var(--comfy-input-bg); + border-radius: 5px; + box-shadow: 0 0 5px rgba(0, 0, 0, 0.4); + color: var(--input-text); + font-family: sans-serif; + left: 0; + max-width: 30vw; + padding: 4px 8px; + position: absolute; + top: 0; + transform: translate(5px, calc(-100% - 5px)); + white-space: pre-wrap; + z-index: 99999; +} + +.queue-tool-header-cell { + display: flex; + justify-content: flex-end; +} +.queue-tool-body-cell { + display: table-cell; + text-align: right !important; +} + +.queue-time-cell-content[data-v-89313500] { + width: -moz-fit-content; + width: fit-content; +} + +.comfy-vue-side-bar-container[data-v-68eb78dd] { + display: flex; + flex-direction: column; + height: 100%; + overflow: hidden; +} +.comfy-vue-side-bar-header[data-v-68eb78dd] { + flex-shrink: 0; + border-left: none; + border-right: none; + border-top: none; + border-radius: 0; + padding: 0.25rem 1rem; +} +.comfy-vue-side-bar-header-span[data-v-68eb78dd] { + font-size: small; +} +.comfy-vue-side-bar-body[data-v-68eb78dd] { + flex-grow: 1; + overflow: auto; + scrollbar-width: thin; + scrollbar-color: transparent transparent; +} +.comfy-vue-side-bar-body[data-v-68eb78dd]::-webkit-scrollbar { + width: 1px; +} +.comfy-vue-side-bar-body[data-v-68eb78dd]::-webkit-scrollbar-thumb { + background-color: transparent; +} + +.spinner[data-v-2a1001f4] { + position: absolute; + inset: 0px; + display: flex; + height: 100vh; + align-items: center; + justify-content: center +} diff --git a/web/assets/index-DIiqwEjy.js b/web/assets/index-DIiqwEjy.js new file mode 100644 index 000000000..f32745b54 --- /dev/null +++ b/web/assets/index-DIiqwEjy.js @@ -0,0 +1,88595 @@ +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-DJRcbqp_.js","assets/index-DjWyclij.css","assets/userSelection-BifVfRyx.js","assets/userSelection-BGzn1LuN.css"])))=>i.map(i=>d[i]); +var __defProp2 = Object.defineProperty; +var __defProps2 = Object.defineProperties; +var __getOwnPropDescs2 = Object.getOwnPropertyDescriptors; +var __getOwnPropSymbols2 = Object.getOwnPropertySymbols; +var __hasOwnProp2 = Object.prototype.hasOwnProperty; +var __propIsEnum2 = Object.prototype.propertyIsEnumerable; +var __typeError = (msg) => { + throw TypeError(msg); +}; +var __defNormalProp2 = (obj, key, value3) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value: value3 }) : obj[key] = value3; +var __spreadValues2 = (a, b) => { + for (var prop2 in b || (b = {})) + if (__hasOwnProp2.call(b, prop2)) + __defNormalProp2(a, prop2, b[prop2]); + if (__getOwnPropSymbols2) + for (var prop2 of __getOwnPropSymbols2(b)) { + if (__propIsEnum2.call(b, prop2)) + __defNormalProp2(a, prop2, b[prop2]); + } + return a; +}; +var __spreadProps2 = (a, b) => __defProps2(a, __getOwnPropDescs2(b)); +var __objRest2 = (source, exclude) => { + var target = {}; + for (var prop2 in source) + if (__hasOwnProp2.call(source, prop2) && exclude.indexOf(prop2) < 0) + target[prop2] = source[prop2]; + if (source != null && __getOwnPropSymbols2) + for (var prop2 of __getOwnPropSymbols2(source)) { + if (exclude.indexOf(prop2) < 0 && __propIsEnum2.call(source, prop2)) + target[prop2] = source[prop2]; + } + return target; +}; +var __publicField2 = (obj, key, value3) => __defNormalProp2(obj, typeof key !== "symbol" ? key + "" : key, value3); +var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg); +var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)); +var __privateAdd = (obj, member, value3) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value3); +var __privateSet = (obj, member, value3, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value3) : member.set(obj, value3), value3); +var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method); +var __privateWrapper = (obj, member, setter, getter) => ({ + set _(value3) { + __privateSet(obj, member, value3, setter); + }, + get _() { + return __privateGet(obj, member, getter); + } +}); +var __async = (__this, __arguments, generator) => { + return new Promise((resolve8, reject2) => { + var fulfilled = (value3) => { + try { + step(generator.next(value3)); + } catch (e) { + reject2(e); + } + }; + var rejected = (value3) => { + try { + step(generator.throw(value3)); + } catch (e) { + reject2(e); + } + }; + var step = (x2) => x2.done ? resolve8(x2.value) : Promise.resolve(x2.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +var _registered, _ComfyApi_instances, pollQueue_fn, createSocket_fn, postItem_fn, _buttons, _a, _ComfySettingsDialog_instances, dispatchChange_fn, _type, _text, _reverse, _enabled, _console, _over, _popupOpen, _ComfyPopup_instances, hide_fn, show_fn, _escHandler, _clickHandler, _internalQueueSize, _app, _ChangeTracker_instances, setApp_fn, _resolve, _activePromptId, _unsavedCount, _activeWorkflow, _ComfyWorkflowManager_instances, bindExecutionEvents_fn, _name, _path, _pathParts, _isFavorite, _ComfyWorkflow_instances, updatePath_fn, save_fn, _first, _updateProgress, _updateActive, _ComfyWorkflowsMenu_instances, bindEvents_fn, getMenuOptions_fn, getFavoriteMenuOptions_fn, _ComfyWorkflowsContent_instances, expandNode_fn, updateActive_fn, removeActive_fn, getFavoriteIcon_fn, getFavoriteOverIcon_fn, getFavoriteTooltip_fn, getFavoriteButton_fn, getDeleteButton_fn, getInsertButton_fn, getRenameButton_fn, getWorkflowElement_fn, createLeafNode_fn, createNode_fn, _options, _sizeBreak, _lastSizeBreaks, _sizeBreaks, _cachedInnerSize, _cacheTimeout, _queueItems, _processingQueue, _ComfyApp_instances, invokeExtensions_fn, invokeExtensionsAsync_fn, addRestoreWorkflowView_fn, addNodeContextMenuHandler_fn, addNodeKeyHandler_fn, addDrawBackgroundHandler_fn, addDropHandler_fn, addPasteHandler_fn, addCopyHandler_fn, addProcessMouseHandler_fn, addProcessKeyHandler_fn, addDrawGroupsHandler_fn, addDrawNodeHandler_fn, addApiUpdateHandlers_fn, addKeyboardHandler_fn, addConfigureHandler_fn, addAfterConfigureHandler_fn, loadExtensions_fn, migrateSettings_fn, setUser_fn, formatPromptError_fn, formatExecutionError_fn; +(function polyfill() { + const relList = document.createElement("link").relList; + if (relList && relList.supports && relList.supports("modulepreload")) { + return; + } + for (const link of document.querySelectorAll('link[rel="modulepreload"]')) { + processPreload(link); + } + new MutationObserver((mutations) => { + for (const mutation of mutations) { + if (mutation.type !== "childList") { + continue; + } + for (const node3 of mutation.addedNodes) { + if (node3.tagName === "LINK" && node3.rel === "modulepreload") + processPreload(node3); + } + } + }).observe(document, { childList: true, subtree: true }); + function getFetchOpts(link) { + const fetchOpts = {}; + if (link.integrity) fetchOpts.integrity = link.integrity; + if (link.referrerPolicy) fetchOpts.referrerPolicy = link.referrerPolicy; + if (link.crossOrigin === "use-credentials") + fetchOpts.credentials = "include"; + else if (link.crossOrigin === "anonymous") fetchOpts.credentials = "omit"; + else fetchOpts.credentials = "same-origin"; + return fetchOpts; + } + function processPreload(link) { + if (link.ep) + return; + link.ep = true; + const fetchOpts = getFetchOpts(link); + fetch(link.href, fetchOpts); + } +})(); +var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {}; +function getDefaultExportFromCjs(x2) { + return x2 && x2.__esModule && Object.prototype.hasOwnProperty.call(x2, "default") ? x2["default"] : x2; +} +function getDefaultExportFromNamespaceIfPresent(n) { + return n && Object.prototype.hasOwnProperty.call(n, "default") ? n["default"] : n; +} +function getDefaultExportFromNamespaceIfNotNamed(n) { + return n && Object.prototype.hasOwnProperty.call(n, "default") && Object.keys(n).length === 1 ? n["default"] : n; +} +function getAugmentedNamespace(n) { + if (n.__esModule) return n; + var f = n.default; + if (typeof f == "function") { + var a = function a2() { + if (this instanceof a2) { + return Reflect.construct(f, arguments, this.constructor); + } + return f.apply(this, arguments); + }; + a.prototype = f.prototype; + } else a = {}; + Object.defineProperty(a, "__esModule", { value: true }); + Object.keys(n).forEach(function(k) { + var d = Object.getOwnPropertyDescriptor(n, k); + Object.defineProperty(a, k, d.get ? d : { + enumerable: true, + get: function() { + return n[k]; + } + }); + }); + return a; +} +var _Reflect = {}; +/*! ***************************************************************************** +Copyright (C) Microsoft. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +var Reflect$1; +(function(Reflect2) { + (function(factory) { + var root27 = typeof globalThis === "object" ? globalThis : typeof commonjsGlobal === "object" ? commonjsGlobal : typeof self === "object" ? self : typeof this === "object" ? this : sloppyModeThis(); + var exporter = makeExporter(Reflect2); + if (typeof root27.Reflect !== "undefined") { + exporter = makeExporter(root27.Reflect, exporter); + } + factory(exporter, root27); + if (typeof root27.Reflect === "undefined") { + root27.Reflect = Reflect2; + } + function makeExporter(target, previous) { + return function(key, value3) { + Object.defineProperty(target, key, { configurable: true, writable: true, value: value3 }); + if (previous) + previous(key, value3); + }; + } + function functionThis() { + try { + return Function("return this;")(); + } catch (_2) { + } + } + function indirectEvalThis() { + try { + return (void 0, eval)("(function() { return this; })()"); + } catch (_2) { + } + } + function sloppyModeThis() { + return functionThis() || indirectEvalThis(); + } + })(function(exporter, root27) { + var hasOwn2 = Object.prototype.hasOwnProperty; + var supportsSymbol = typeof Symbol === "function"; + var toPrimitiveSymbol = supportsSymbol && typeof Symbol.toPrimitive !== "undefined" ? Symbol.toPrimitive : "@@toPrimitive"; + var iteratorSymbol = supportsSymbol && typeof Symbol.iterator !== "undefined" ? Symbol.iterator : "@@iterator"; + var supportsCreate = typeof Object.create === "function"; + var supportsProto = { __proto__: [] } instanceof Array; + var downLevel = !supportsCreate && !supportsProto; + var HashMap = { + // create an object in dictionary mode (a.k.a. "slow" mode in v8) + create: supportsCreate ? function() { + return MakeDictionary(/* @__PURE__ */ Object.create(null)); + } : supportsProto ? function() { + return MakeDictionary({ __proto__: null }); + } : function() { + return MakeDictionary({}); + }, + has: downLevel ? function(map2, key) { + return hasOwn2.call(map2, key); + } : function(map2, key) { + return key in map2; + }, + get: downLevel ? function(map2, key) { + return hasOwn2.call(map2, key) ? map2[key] : void 0; + } : function(map2, key) { + return map2[key]; + } + }; + var functionPrototype = Object.getPrototypeOf(Function); + var _Map = typeof Map === "function" && typeof Map.prototype.entries === "function" ? Map : CreateMapPolyfill(); + var _Set = typeof Set === "function" && typeof Set.prototype.entries === "function" ? Set : CreateSetPolyfill(); + var _WeakMap = typeof WeakMap === "function" ? WeakMap : CreateWeakMapPolyfill(); + var registrySymbol = supportsSymbol ? Symbol.for("@reflect-metadata:registry") : void 0; + var metadataRegistry = GetOrCreateMetadataRegistry(); + var metadataProvider = CreateMetadataProvider(metadataRegistry); + function decorate(decorators, target, propertyKey, attributes) { + if (!IsUndefined(propertyKey)) { + if (!IsArray(decorators)) + throw new TypeError(); + if (!IsObject(target)) + throw new TypeError(); + if (!IsObject(attributes) && !IsUndefined(attributes) && !IsNull(attributes)) + throw new TypeError(); + if (IsNull(attributes)) + attributes = void 0; + propertyKey = ToPropertyKey(propertyKey); + return DecorateProperty(decorators, target, propertyKey, attributes); + } else { + if (!IsArray(decorators)) + throw new TypeError(); + if (!IsConstructor(target)) + throw new TypeError(); + return DecorateConstructor(decorators, target); + } + } + exporter("decorate", decorate); + function metadata(metadataKey, metadataValue) { + function decorator(target, propertyKey) { + if (!IsObject(target)) + throw new TypeError(); + if (!IsUndefined(propertyKey) && !IsPropertyKey(propertyKey)) + throw new TypeError(); + OrdinaryDefineOwnMetadata(metadataKey, metadataValue, target, propertyKey); + } + return decorator; + } + exporter("metadata", metadata); + function defineMetadata(metadataKey, metadataValue, target, propertyKey) { + if (!IsObject(target)) + throw new TypeError(); + if (!IsUndefined(propertyKey)) + propertyKey = ToPropertyKey(propertyKey); + return OrdinaryDefineOwnMetadata(metadataKey, metadataValue, target, propertyKey); + } + exporter("defineMetadata", defineMetadata); + function hasMetadata(metadataKey, target, propertyKey) { + if (!IsObject(target)) + throw new TypeError(); + if (!IsUndefined(propertyKey)) + propertyKey = ToPropertyKey(propertyKey); + return OrdinaryHasMetadata(metadataKey, target, propertyKey); + } + exporter("hasMetadata", hasMetadata); + function hasOwnMetadata(metadataKey, target, propertyKey) { + if (!IsObject(target)) + throw new TypeError(); + if (!IsUndefined(propertyKey)) + propertyKey = ToPropertyKey(propertyKey); + return OrdinaryHasOwnMetadata(metadataKey, target, propertyKey); + } + exporter("hasOwnMetadata", hasOwnMetadata); + function getMetadata(metadataKey, target, propertyKey) { + if (!IsObject(target)) + throw new TypeError(); + if (!IsUndefined(propertyKey)) + propertyKey = ToPropertyKey(propertyKey); + return OrdinaryGetMetadata(metadataKey, target, propertyKey); + } + exporter("getMetadata", getMetadata); + function getOwnMetadata(metadataKey, target, propertyKey) { + if (!IsObject(target)) + throw new TypeError(); + if (!IsUndefined(propertyKey)) + propertyKey = ToPropertyKey(propertyKey); + return OrdinaryGetOwnMetadata(metadataKey, target, propertyKey); + } + exporter("getOwnMetadata", getOwnMetadata); + function getMetadataKeys(target, propertyKey) { + if (!IsObject(target)) + throw new TypeError(); + if (!IsUndefined(propertyKey)) + propertyKey = ToPropertyKey(propertyKey); + return OrdinaryMetadataKeys(target, propertyKey); + } + exporter("getMetadataKeys", getMetadataKeys); + function getOwnMetadataKeys(target, propertyKey) { + if (!IsObject(target)) + throw new TypeError(); + if (!IsUndefined(propertyKey)) + propertyKey = ToPropertyKey(propertyKey); + return OrdinaryOwnMetadataKeys(target, propertyKey); + } + exporter("getOwnMetadataKeys", getOwnMetadataKeys); + function deleteMetadata(metadataKey, target, propertyKey) { + if (!IsObject(target)) + throw new TypeError(); + if (!IsUndefined(propertyKey)) + propertyKey = ToPropertyKey(propertyKey); + if (!IsObject(target)) + throw new TypeError(); + if (!IsUndefined(propertyKey)) + propertyKey = ToPropertyKey(propertyKey); + var provider = GetMetadataProvider( + target, + propertyKey, + /*Create*/ + false + ); + if (IsUndefined(provider)) + return false; + return provider.OrdinaryDeleteMetadata(metadataKey, target, propertyKey); + } + exporter("deleteMetadata", deleteMetadata); + function DecorateConstructor(decorators, target) { + for (var i2 = decorators.length - 1; i2 >= 0; --i2) { + var decorator = decorators[i2]; + var decorated = decorator(target); + if (!IsUndefined(decorated) && !IsNull(decorated)) { + if (!IsConstructor(decorated)) + throw new TypeError(); + target = decorated; + } + } + return target; + } + function DecorateProperty(decorators, target, propertyKey, descriptor) { + for (var i2 = decorators.length - 1; i2 >= 0; --i2) { + var decorator = decorators[i2]; + var decorated = decorator(target, propertyKey, descriptor); + if (!IsUndefined(decorated) && !IsNull(decorated)) { + if (!IsObject(decorated)) + throw new TypeError(); + descriptor = decorated; + } + } + return descriptor; + } + function OrdinaryHasMetadata(MetadataKey, O, P) { + var hasOwn3 = OrdinaryHasOwnMetadata(MetadataKey, O, P); + if (hasOwn3) + return true; + var parent = OrdinaryGetPrototypeOf(O); + if (!IsNull(parent)) + return OrdinaryHasMetadata(MetadataKey, parent, P); + return false; + } + function OrdinaryHasOwnMetadata(MetadataKey, O, P) { + var provider = GetMetadataProvider( + O, + P, + /*Create*/ + false + ); + if (IsUndefined(provider)) + return false; + return ToBoolean(provider.OrdinaryHasOwnMetadata(MetadataKey, O, P)); + } + function OrdinaryGetMetadata(MetadataKey, O, P) { + var hasOwn3 = OrdinaryHasOwnMetadata(MetadataKey, O, P); + if (hasOwn3) + return OrdinaryGetOwnMetadata(MetadataKey, O, P); + var parent = OrdinaryGetPrototypeOf(O); + if (!IsNull(parent)) + return OrdinaryGetMetadata(MetadataKey, parent, P); + return void 0; + } + function OrdinaryGetOwnMetadata(MetadataKey, O, P) { + var provider = GetMetadataProvider( + O, + P, + /*Create*/ + false + ); + if (IsUndefined(provider)) + return; + return provider.OrdinaryGetOwnMetadata(MetadataKey, O, P); + } + function OrdinaryDefineOwnMetadata(MetadataKey, MetadataValue, O, P) { + var provider = GetMetadataProvider( + O, + P, + /*Create*/ + true + ); + provider.OrdinaryDefineOwnMetadata(MetadataKey, MetadataValue, O, P); + } + function OrdinaryMetadataKeys(O, P) { + var ownKeys2 = OrdinaryOwnMetadataKeys(O, P); + var parent = OrdinaryGetPrototypeOf(O); + if (parent === null) + return ownKeys2; + var parentKeys = OrdinaryMetadataKeys(parent, P); + if (parentKeys.length <= 0) + return ownKeys2; + if (ownKeys2.length <= 0) + return parentKeys; + var set2 = new _Set(); + var keys = []; + for (var _i = 0, ownKeys_1 = ownKeys2; _i < ownKeys_1.length; _i++) { + var key = ownKeys_1[_i]; + var hasKey = set2.has(key); + if (!hasKey) { + set2.add(key); + keys.push(key); + } + } + for (var _a2 = 0, parentKeys_1 = parentKeys; _a2 < parentKeys_1.length; _a2++) { + var key = parentKeys_1[_a2]; + var hasKey = set2.has(key); + if (!hasKey) { + set2.add(key); + keys.push(key); + } + } + return keys; + } + function OrdinaryOwnMetadataKeys(O, P) { + var provider = GetMetadataProvider( + O, + P, + /*create*/ + false + ); + if (!provider) { + return []; + } + return provider.OrdinaryOwnMetadataKeys(O, P); + } + function Type2(x2) { + if (x2 === null) + return 1; + switch (typeof x2) { + case "undefined": + return 0; + case "boolean": + return 2; + case "string": + return 3; + case "symbol": + return 4; + case "number": + return 5; + case "object": + return x2 === null ? 1 : 6; + default: + return 6; + } + } + function IsUndefined(x2) { + return x2 === void 0; + } + function IsNull(x2) { + return x2 === null; + } + function IsSymbol(x2) { + return typeof x2 === "symbol"; + } + function IsObject(x2) { + return typeof x2 === "object" ? x2 !== null : typeof x2 === "function"; + } + function ToPrimitive(input, PreferredType) { + switch (Type2(input)) { + case 0: + return input; + case 1: + return input; + case 2: + return input; + case 3: + return input; + case 4: + return input; + case 5: + return input; + } + var hint = PreferredType === 3 ? "string" : PreferredType === 5 ? "number" : "default"; + var exoticToPrim = GetMethod(input, toPrimitiveSymbol); + if (exoticToPrim !== void 0) { + var result = exoticToPrim.call(input, hint); + if (IsObject(result)) + throw new TypeError(); + return result; + } + return OrdinaryToPrimitive(input, hint === "default" ? "number" : hint); + } + function OrdinaryToPrimitive(O, hint) { + if (hint === "string") { + var toString_1 = O.toString; + if (IsCallable(toString_1)) { + var result = toString_1.call(O); + if (!IsObject(result)) + return result; + } + var valueOf = O.valueOf; + if (IsCallable(valueOf)) { + var result = valueOf.call(O); + if (!IsObject(result)) + return result; + } + } else { + var valueOf = O.valueOf; + if (IsCallable(valueOf)) { + var result = valueOf.call(O); + if (!IsObject(result)) + return result; + } + var toString_2 = O.toString; + if (IsCallable(toString_2)) { + var result = toString_2.call(O); + if (!IsObject(result)) + return result; + } + } + throw new TypeError(); + } + function ToBoolean(argument) { + return !!argument; + } + function ToString(argument) { + return "" + argument; + } + function ToPropertyKey(argument) { + var key = ToPrimitive( + argument, + 3 + /* String */ + ); + if (IsSymbol(key)) + return key; + return ToString(key); + } + function IsArray(argument) { + return Array.isArray ? Array.isArray(argument) : argument instanceof Object ? argument instanceof Array : Object.prototype.toString.call(argument) === "[object Array]"; + } + function IsCallable(argument) { + return typeof argument === "function"; + } + function IsConstructor(argument) { + return typeof argument === "function"; + } + function IsPropertyKey(argument) { + switch (Type2(argument)) { + case 3: + return true; + case 4: + return true; + default: + return false; + } + } + function SameValueZero(x2, y2) { + return x2 === y2 || x2 !== x2 && y2 !== y2; + } + function GetMethod(V, P) { + var func = V[P]; + if (func === void 0 || func === null) + return void 0; + if (!IsCallable(func)) + throw new TypeError(); + return func; + } + function GetIterator(obj) { + var method = GetMethod(obj, iteratorSymbol); + if (!IsCallable(method)) + throw new TypeError(); + var iterator = method.call(obj); + if (!IsObject(iterator)) + throw new TypeError(); + return iterator; + } + function IteratorValue(iterResult) { + return iterResult.value; + } + function IteratorStep(iterator) { + var result = iterator.next(); + return result.done ? false : result; + } + function IteratorClose(iterator) { + var f = iterator["return"]; + if (f) + f.call(iterator); + } + function OrdinaryGetPrototypeOf(O) { + var proto = Object.getPrototypeOf(O); + if (typeof O !== "function" || O === functionPrototype) + return proto; + if (proto !== functionPrototype) + return proto; + var prototype = O.prototype; + var prototypeProto = prototype && Object.getPrototypeOf(prototype); + if (prototypeProto == null || prototypeProto === Object.prototype) + return proto; + var constructor = prototypeProto.constructor; + if (typeof constructor !== "function") + return proto; + if (constructor === O) + return proto; + return constructor; + } + function CreateMetadataRegistry() { + var fallback; + if (!IsUndefined(registrySymbol) && typeof root27.Reflect !== "undefined" && !(registrySymbol in root27.Reflect) && typeof root27.Reflect.defineMetadata === "function") { + fallback = CreateFallbackProvider(root27.Reflect); + } + var first4; + var second; + var rest; + var targetProviderMap = new _WeakMap(); + var registry = { + registerProvider, + getProvider, + setProvider + }; + return registry; + function registerProvider(provider) { + if (!Object.isExtensible(registry)) { + throw new Error("Cannot add provider to a frozen registry."); + } + switch (true) { + case fallback === provider: + break; + case IsUndefined(first4): + first4 = provider; + break; + case first4 === provider: + break; + case IsUndefined(second): + second = provider; + break; + case second === provider: + break; + default: + if (rest === void 0) + rest = new _Set(); + rest.add(provider); + break; + } + } + function getProviderNoCache(O, P) { + if (!IsUndefined(first4)) { + if (first4.isProviderFor(O, P)) + return first4; + if (!IsUndefined(second)) { + if (second.isProviderFor(O, P)) + return first4; + if (!IsUndefined(rest)) { + var iterator = GetIterator(rest); + while (true) { + var next2 = IteratorStep(iterator); + if (!next2) { + return void 0; + } + var provider = IteratorValue(next2); + if (provider.isProviderFor(O, P)) { + IteratorClose(iterator); + return provider; + } + } + } + } + } + if (!IsUndefined(fallback) && fallback.isProviderFor(O, P)) { + return fallback; + } + return void 0; + } + function getProvider(O, P) { + var providerMap = targetProviderMap.get(O); + var provider; + if (!IsUndefined(providerMap)) { + provider = providerMap.get(P); + } + if (!IsUndefined(provider)) { + return provider; + } + provider = getProviderNoCache(O, P); + if (!IsUndefined(provider)) { + if (IsUndefined(providerMap)) { + providerMap = new _Map(); + targetProviderMap.set(O, providerMap); + } + providerMap.set(P, provider); + } + return provider; + } + function hasProvider(provider) { + if (IsUndefined(provider)) + throw new TypeError(); + return first4 === provider || second === provider || !IsUndefined(rest) && rest.has(provider); + } + function setProvider(O, P, provider) { + if (!hasProvider(provider)) { + throw new Error("Metadata provider not registered."); + } + var existingProvider = getProvider(O, P); + if (existingProvider !== provider) { + if (!IsUndefined(existingProvider)) { + return false; + } + var providerMap = targetProviderMap.get(O); + if (IsUndefined(providerMap)) { + providerMap = new _Map(); + targetProviderMap.set(O, providerMap); + } + providerMap.set(P, provider); + } + return true; + } + } + function GetOrCreateMetadataRegistry() { + var metadataRegistry2; + if (!IsUndefined(registrySymbol) && IsObject(root27.Reflect) && Object.isExtensible(root27.Reflect)) { + metadataRegistry2 = root27.Reflect[registrySymbol]; + } + if (IsUndefined(metadataRegistry2)) { + metadataRegistry2 = CreateMetadataRegistry(); + } + if (!IsUndefined(registrySymbol) && IsObject(root27.Reflect) && Object.isExtensible(root27.Reflect)) { + Object.defineProperty(root27.Reflect, registrySymbol, { + enumerable: false, + configurable: false, + writable: false, + value: metadataRegistry2 + }); + } + return metadataRegistry2; + } + function CreateMetadataProvider(registry) { + var metadata2 = new _WeakMap(); + var provider = { + isProviderFor: function(O, P) { + var targetMetadata = metadata2.get(O); + if (IsUndefined(targetMetadata)) + return false; + return targetMetadata.has(P); + }, + OrdinaryDefineOwnMetadata: OrdinaryDefineOwnMetadata2, + OrdinaryHasOwnMetadata: OrdinaryHasOwnMetadata2, + OrdinaryGetOwnMetadata: OrdinaryGetOwnMetadata2, + OrdinaryOwnMetadataKeys: OrdinaryOwnMetadataKeys2, + OrdinaryDeleteMetadata + }; + metadataRegistry.registerProvider(provider); + return provider; + function GetOrCreateMetadataMap(O, P, Create) { + var targetMetadata = metadata2.get(O); + var createdTargetMetadata = false; + if (IsUndefined(targetMetadata)) { + if (!Create) + return void 0; + targetMetadata = new _Map(); + metadata2.set(O, targetMetadata); + createdTargetMetadata = true; + } + var metadataMap = targetMetadata.get(P); + if (IsUndefined(metadataMap)) { + if (!Create) + return void 0; + metadataMap = new _Map(); + targetMetadata.set(P, metadataMap); + if (!registry.setProvider(O, P, provider)) { + targetMetadata.delete(P); + if (createdTargetMetadata) { + metadata2.delete(O); + } + throw new Error("Wrong provider for target."); + } + } + return metadataMap; + } + function OrdinaryHasOwnMetadata2(MetadataKey, O, P) { + var metadataMap = GetOrCreateMetadataMap( + O, + P, + /*Create*/ + false + ); + if (IsUndefined(metadataMap)) + return false; + return ToBoolean(metadataMap.has(MetadataKey)); + } + function OrdinaryGetOwnMetadata2(MetadataKey, O, P) { + var metadataMap = GetOrCreateMetadataMap( + O, + P, + /*Create*/ + false + ); + if (IsUndefined(metadataMap)) + return void 0; + return metadataMap.get(MetadataKey); + } + function OrdinaryDefineOwnMetadata2(MetadataKey, MetadataValue, O, P) { + var metadataMap = GetOrCreateMetadataMap( + O, + P, + /*Create*/ + true + ); + metadataMap.set(MetadataKey, MetadataValue); + } + function OrdinaryOwnMetadataKeys2(O, P) { + var keys = []; + var metadataMap = GetOrCreateMetadataMap( + O, + P, + /*Create*/ + false + ); + if (IsUndefined(metadataMap)) + return keys; + var keysObj = metadataMap.keys(); + var iterator = GetIterator(keysObj); + var k = 0; + while (true) { + var next2 = IteratorStep(iterator); + if (!next2) { + keys.length = k; + return keys; + } + var nextValue = IteratorValue(next2); + try { + keys[k] = nextValue; + } catch (e) { + try { + IteratorClose(iterator); + } finally { + throw e; + } + } + k++; + } + } + function OrdinaryDeleteMetadata(MetadataKey, O, P) { + var metadataMap = GetOrCreateMetadataMap( + O, + P, + /*Create*/ + false + ); + if (IsUndefined(metadataMap)) + return false; + if (!metadataMap.delete(MetadataKey)) + return false; + if (metadataMap.size === 0) { + var targetMetadata = metadata2.get(O); + if (!IsUndefined(targetMetadata)) { + targetMetadata.delete(P); + if (targetMetadata.size === 0) { + metadata2.delete(targetMetadata); + } + } + } + return true; + } + } + function CreateFallbackProvider(reflect) { + var defineMetadata2 = reflect.defineMetadata, hasOwnMetadata2 = reflect.hasOwnMetadata, getOwnMetadata2 = reflect.getOwnMetadata, getOwnMetadataKeys2 = reflect.getOwnMetadataKeys, deleteMetadata2 = reflect.deleteMetadata; + var metadataOwner = new _WeakMap(); + var provider = { + isProviderFor: function(O, P) { + var metadataPropertySet = metadataOwner.get(O); + if (!IsUndefined(metadataPropertySet) && metadataPropertySet.has(P)) { + return true; + } + if (getOwnMetadataKeys2(O, P).length) { + if (IsUndefined(metadataPropertySet)) { + metadataPropertySet = new _Set(); + metadataOwner.set(O, metadataPropertySet); + } + metadataPropertySet.add(P); + return true; + } + return false; + }, + OrdinaryDefineOwnMetadata: defineMetadata2, + OrdinaryHasOwnMetadata: hasOwnMetadata2, + OrdinaryGetOwnMetadata: getOwnMetadata2, + OrdinaryOwnMetadataKeys: getOwnMetadataKeys2, + OrdinaryDeleteMetadata: deleteMetadata2 + }; + return provider; + } + function GetMetadataProvider(O, P, Create) { + var registeredProvider = metadataRegistry.getProvider(O, P); + if (!IsUndefined(registeredProvider)) { + return registeredProvider; + } + if (Create) { + if (metadataRegistry.setProvider(O, P, metadataProvider)) { + return metadataProvider; + } + throw new Error("Illegal state."); + } + return void 0; + } + function CreateMapPolyfill() { + var cacheSentinel = {}; + var arraySentinel = []; + var MapIterator = ( + /** @class */ + function() { + function MapIterator2(keys, values2, selector) { + this._index = 0; + this._keys = keys; + this._values = values2; + this._selector = selector; + } + MapIterator2.prototype["@@iterator"] = function() { + return this; + }; + MapIterator2.prototype[iteratorSymbol] = function() { + return this; + }; + MapIterator2.prototype.next = function() { + var index2 = this._index; + if (index2 >= 0 && index2 < this._keys.length) { + var result = this._selector(this._keys[index2], this._values[index2]); + if (index2 + 1 >= this._keys.length) { + this._index = -1; + this._keys = arraySentinel; + this._values = arraySentinel; + } else { + this._index++; + } + return { value: result, done: false }; + } + return { value: void 0, done: true }; + }; + MapIterator2.prototype.throw = function(error) { + if (this._index >= 0) { + this._index = -1; + this._keys = arraySentinel; + this._values = arraySentinel; + } + throw error; + }; + MapIterator2.prototype.return = function(value3) { + if (this._index >= 0) { + this._index = -1; + this._keys = arraySentinel; + this._values = arraySentinel; + } + return { value: value3, done: true }; + }; + return MapIterator2; + }() + ); + var Map2 = ( + /** @class */ + function() { + function Map3() { + this._keys = []; + this._values = []; + this._cacheKey = cacheSentinel; + this._cacheIndex = -2; + } + Object.defineProperty(Map3.prototype, "size", { + get: function() { + return this._keys.length; + }, + enumerable: true, + configurable: true + }); + Map3.prototype.has = function(key) { + return this._find( + key, + /*insert*/ + false + ) >= 0; + }; + Map3.prototype.get = function(key) { + var index2 = this._find( + key, + /*insert*/ + false + ); + return index2 >= 0 ? this._values[index2] : void 0; + }; + Map3.prototype.set = function(key, value3) { + var index2 = this._find( + key, + /*insert*/ + true + ); + this._values[index2] = value3; + return this; + }; + Map3.prototype.delete = function(key) { + var index2 = this._find( + key, + /*insert*/ + false + ); + if (index2 >= 0) { + var size2 = this._keys.length; + for (var i2 = index2 + 1; i2 < size2; i2++) { + this._keys[i2 - 1] = this._keys[i2]; + this._values[i2 - 1] = this._values[i2]; + } + this._keys.length--; + this._values.length--; + if (SameValueZero(key, this._cacheKey)) { + this._cacheKey = cacheSentinel; + this._cacheIndex = -2; + } + return true; + } + return false; + }; + Map3.prototype.clear = function() { + this._keys.length = 0; + this._values.length = 0; + this._cacheKey = cacheSentinel; + this._cacheIndex = -2; + }; + Map3.prototype.keys = function() { + return new MapIterator(this._keys, this._values, getKey); + }; + Map3.prototype.values = function() { + return new MapIterator(this._keys, this._values, getValue2); + }; + Map3.prototype.entries = function() { + return new MapIterator(this._keys, this._values, getEntry); + }; + Map3.prototype["@@iterator"] = function() { + return this.entries(); + }; + Map3.prototype[iteratorSymbol] = function() { + return this.entries(); + }; + Map3.prototype._find = function(key, insert2) { + if (!SameValueZero(this._cacheKey, key)) { + this._cacheIndex = -1; + for (var i2 = 0; i2 < this._keys.length; i2++) { + if (SameValueZero(this._keys[i2], key)) { + this._cacheIndex = i2; + break; + } + } + } + if (this._cacheIndex < 0 && insert2) { + this._cacheIndex = this._keys.length; + this._keys.push(key); + this._values.push(void 0); + } + return this._cacheIndex; + }; + return Map3; + }() + ); + return Map2; + function getKey(key, _2) { + return key; + } + function getValue2(_2, value3) { + return value3; + } + function getEntry(key, value3) { + return [key, value3]; + } + } + function CreateSetPolyfill() { + var Set2 = ( + /** @class */ + function() { + function Set3() { + this._map = new _Map(); + } + Object.defineProperty(Set3.prototype, "size", { + get: function() { + return this._map.size; + }, + enumerable: true, + configurable: true + }); + Set3.prototype.has = function(value3) { + return this._map.has(value3); + }; + Set3.prototype.add = function(value3) { + return this._map.set(value3, value3), this; + }; + Set3.prototype.delete = function(value3) { + return this._map.delete(value3); + }; + Set3.prototype.clear = function() { + this._map.clear(); + }; + Set3.prototype.keys = function() { + return this._map.keys(); + }; + Set3.prototype.values = function() { + return this._map.keys(); + }; + Set3.prototype.entries = function() { + return this._map.entries(); + }; + Set3.prototype["@@iterator"] = function() { + return this.keys(); + }; + Set3.prototype[iteratorSymbol] = function() { + return this.keys(); + }; + return Set3; + }() + ); + return Set2; + } + function CreateWeakMapPolyfill() { + var UUID_SIZE = 16; + var keys = HashMap.create(); + var rootKey = CreateUniqueKey(); + return ( + /** @class */ + function() { + function WeakMap2() { + this._key = CreateUniqueKey(); + } + WeakMap2.prototype.has = function(target) { + var table2 = GetOrCreateWeakMapTable( + target, + /*create*/ + false + ); + return table2 !== void 0 ? HashMap.has(table2, this._key) : false; + }; + WeakMap2.prototype.get = function(target) { + var table2 = GetOrCreateWeakMapTable( + target, + /*create*/ + false + ); + return table2 !== void 0 ? HashMap.get(table2, this._key) : void 0; + }; + WeakMap2.prototype.set = function(target, value3) { + var table2 = GetOrCreateWeakMapTable( + target, + /*create*/ + true + ); + table2[this._key] = value3; + return this; + }; + WeakMap2.prototype.delete = function(target) { + var table2 = GetOrCreateWeakMapTable( + target, + /*create*/ + false + ); + return table2 !== void 0 ? delete table2[this._key] : false; + }; + WeakMap2.prototype.clear = function() { + this._key = CreateUniqueKey(); + }; + return WeakMap2; + }() + ); + function CreateUniqueKey() { + var key; + do + key = "@@WeakMap@@" + CreateUUID(); + while (HashMap.has(keys, key)); + keys[key] = true; + return key; + } + function GetOrCreateWeakMapTable(target, create2) { + if (!hasOwn2.call(target, rootKey)) { + if (!create2) + return void 0; + Object.defineProperty(target, rootKey, { value: HashMap.create() }); + } + return target[rootKey]; + } + function FillRandomBytes(buffer2, size2) { + for (var i2 = 0; i2 < size2; ++i2) + buffer2[i2] = Math.random() * 255 | 0; + return buffer2; + } + function GenRandomBytes(size2) { + if (typeof Uint8Array === "function") { + var array = new Uint8Array(size2); + if (typeof crypto !== "undefined") { + crypto.getRandomValues(array); + } else if (typeof msCrypto !== "undefined") { + msCrypto.getRandomValues(array); + } else { + FillRandomBytes(array, size2); + } + return array; + } + return FillRandomBytes(new Array(size2), size2); + } + function CreateUUID() { + var data28 = GenRandomBytes(UUID_SIZE); + data28[6] = data28[6] & 79 | 64; + data28[8] = data28[8] & 191 | 128; + var result = ""; + for (var offset = 0; offset < UUID_SIZE; ++offset) { + var byte = data28[offset]; + if (offset === 4 || offset === 6 || offset === 8) + result += "-"; + if (byte < 16) + result += "0"; + result += byte.toString(16).toLowerCase(); + } + return result; + } + } + function MakeDictionary(obj) { + obj.__ = void 0; + delete obj.__; + return obj; + } + }); +})(Reflect$1 || (Reflect$1 = {})); +window["__COMFYUI_FRONTEND_VERSION__"] = "1.2.23"; +console.log("ComfyUI Front-end version:", "1.2.23"); +/** +* @vue/shared v3.4.31 +* (c) 2018-present Yuxi (Evan) You and Vue contributors +* @license MIT +**/ +/*! #__NO_SIDE_EFFECTS__ */ +// @__NO_SIDE_EFFECTS__ +function makeMap(str, expectsLowerCase) { + const set2 = new Set(str.split(",")); + return expectsLowerCase ? (val) => set2.has(val.toLowerCase()) : (val) => set2.has(val); +} +const EMPTY_OBJ = false ? Object.freeze({}) : {}; +const EMPTY_ARR = false ? Object.freeze([]) : []; +const NOOP = () => { +}; +const NO = () => false; +const isOn = (key) => key.charCodeAt(0) === 111 && key.charCodeAt(1) === 110 && // uppercase letter +(key.charCodeAt(2) > 122 || key.charCodeAt(2) < 97); +const isModelListener = (key) => key.startsWith("onUpdate:"); +const extend = Object.assign; +const remove$1 = (arr, el) => { + const i2 = arr.indexOf(el); + if (i2 > -1) { + arr.splice(i2, 1); + } +}; +const hasOwnProperty$2 = Object.prototype.hasOwnProperty; +const hasOwn$2 = (val, key) => hasOwnProperty$2.call(val, key); +const isArray$3 = Array.isArray; +const isMap = (val) => toTypeString$1(val) === "[object Map]"; +const isSet = (val) => toTypeString$1(val) === "[object Set]"; +const isDate$2 = (val) => toTypeString$1(val) === "[object Date]"; +const isRegExp$1 = (val) => toTypeString$1(val) === "[object RegExp]"; +const isFunction$3 = (val) => typeof val === "function"; +const isString$4 = (val) => typeof val === "string"; +const isSymbol$1 = (val) => typeof val === "symbol"; +const isObject$4 = (val) => val !== null && typeof val === "object"; +const isPromise$2 = (val) => { + return (isObject$4(val) || isFunction$3(val)) && isFunction$3(val.then) && isFunction$3(val.catch); +}; +const objectToString$1 = Object.prototype.toString; +const toTypeString$1 = (value3) => objectToString$1.call(value3); +const toRawType = (value3) => { + return toTypeString$1(value3).slice(8, -1); +}; +const isPlainObject$2 = (val) => toTypeString$1(val) === "[object Object]"; +const isIntegerKey = (key) => isString$4(key) && key !== "NaN" && key[0] !== "-" && "" + parseInt(key, 10) === key; +const isReservedProp = /* @__PURE__ */ makeMap( + // the leading comma is intentional so empty string "" is also included + ",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted" +); +const isBuiltInDirective = /* @__PURE__ */ makeMap( + "bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text,memo" +); +const cacheStringFunction = (fn) => { + const cache2 = /* @__PURE__ */ Object.create(null); + return (str) => { + const hit = cache2[str]; + return hit || (cache2[str] = fn(str)); + }; +}; +const camelizeRE = /-(\w)/g; +const camelize = cacheStringFunction((str) => { + return str.replace(camelizeRE, (_2, c) => c ? c.toUpperCase() : ""); +}); +const hyphenateRE = /\B([A-Z])/g; +const hyphenate = cacheStringFunction( + (str) => str.replace(hyphenateRE, "-$1").toLowerCase() +); +const capitalize$1 = cacheStringFunction((str) => { + return str.charAt(0).toUpperCase() + str.slice(1); +}); +const toHandlerKey = cacheStringFunction((str) => { + const s = str ? `on${capitalize$1(str)}` : ``; + return s; +}); +const hasChanged = (value3, oldValue) => !Object.is(value3, oldValue); +const invokeArrayFns = (fns, ...arg) => { + for (let i2 = 0; i2 < fns.length; i2++) { + fns[i2](...arg); + } +}; +const def = (obj, key, value3, writable = false) => { + Object.defineProperty(obj, key, { + configurable: true, + enumerable: false, + writable, + value: value3 + }); +}; +const looseToNumber = (val) => { + const n = parseFloat(val); + return isNaN(n) ? val : n; +}; +const toNumber = (val) => { + const n = isString$4(val) ? Number(val) : NaN; + return isNaN(n) ? val : n; +}; +let _globalThis$1; +const getGlobalThis$1 = () => { + return _globalThis$1 || (_globalThis$1 = typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {}); +}; +const identRE = /^[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*$/; +function genPropsAccessExp(name) { + return identRE.test(name) ? `__props.${name}` : `__props[${JSON.stringify(name)}]`; +} +const PatchFlags = { + "TEXT": 1, + "1": "TEXT", + "CLASS": 2, + "2": "CLASS", + "STYLE": 4, + "4": "STYLE", + "PROPS": 8, + "8": "PROPS", + "FULL_PROPS": 16, + "16": "FULL_PROPS", + "NEED_HYDRATION": 32, + "32": "NEED_HYDRATION", + "STABLE_FRAGMENT": 64, + "64": "STABLE_FRAGMENT", + "KEYED_FRAGMENT": 128, + "128": "KEYED_FRAGMENT", + "UNKEYED_FRAGMENT": 256, + "256": "UNKEYED_FRAGMENT", + "NEED_PATCH": 512, + "512": "NEED_PATCH", + "DYNAMIC_SLOTS": 1024, + "1024": "DYNAMIC_SLOTS", + "DEV_ROOT_FRAGMENT": 2048, + "2048": "DEV_ROOT_FRAGMENT", + "HOISTED": -1, + "-1": "HOISTED", + "BAIL": -2, + "-2": "BAIL" +}; +const PatchFlagNames = { + [1]: `TEXT`, + [2]: `CLASS`, + [4]: `STYLE`, + [8]: `PROPS`, + [16]: `FULL_PROPS`, + [32]: `NEED_HYDRATION`, + [64]: `STABLE_FRAGMENT`, + [128]: `KEYED_FRAGMENT`, + [256]: `UNKEYED_FRAGMENT`, + [512]: `NEED_PATCH`, + [1024]: `DYNAMIC_SLOTS`, + [2048]: `DEV_ROOT_FRAGMENT`, + [-1]: `HOISTED`, + [-2]: `BAIL` +}; +const ShapeFlags = { + "ELEMENT": 1, + "1": "ELEMENT", + "FUNCTIONAL_COMPONENT": 2, + "2": "FUNCTIONAL_COMPONENT", + "STATEFUL_COMPONENT": 4, + "4": "STATEFUL_COMPONENT", + "TEXT_CHILDREN": 8, + "8": "TEXT_CHILDREN", + "ARRAY_CHILDREN": 16, + "16": "ARRAY_CHILDREN", + "SLOTS_CHILDREN": 32, + "32": "SLOTS_CHILDREN", + "TELEPORT": 64, + "64": "TELEPORT", + "SUSPENSE": 128, + "128": "SUSPENSE", + "COMPONENT_SHOULD_KEEP_ALIVE": 256, + "256": "COMPONENT_SHOULD_KEEP_ALIVE", + "COMPONENT_KEPT_ALIVE": 512, + "512": "COMPONENT_KEPT_ALIVE", + "COMPONENT": 6, + "6": "COMPONENT" +}; +const SlotFlags = { + "STABLE": 1, + "1": "STABLE", + "DYNAMIC": 2, + "2": "DYNAMIC", + "FORWARDED": 3, + "3": "FORWARDED" +}; +const slotFlagsText = { + [1]: "STABLE", + [2]: "DYNAMIC", + [3]: "FORWARDED" +}; +const GLOBALS_ALLOWED = "Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt,console,Error"; +const isGloballyAllowed = /* @__PURE__ */ makeMap(GLOBALS_ALLOWED); +const isGloballyWhitelisted = isGloballyAllowed; +const range = 2; +function generateCodeFrame$1(source, start2 = 0, end = source.length) { + start2 = Math.max(0, Math.min(start2, source.length)); + end = Math.max(0, Math.min(end, source.length)); + if (start2 > end) return ""; + let lines = source.split(/(\r?\n)/); + const newlineSequences = lines.filter((_2, idx) => idx % 2 === 1); + lines = lines.filter((_2, idx) => idx % 2 === 0); + let count = 0; + const res = []; + for (let i2 = 0; i2 < lines.length; i2++) { + count += lines[i2].length + (newlineSequences[i2] && newlineSequences[i2].length || 0); + if (count >= start2) { + for (let j = i2 - range; j <= i2 + range || end > count; j++) { + if (j < 0 || j >= lines.length) continue; + const line = j + 1; + res.push( + `${line}${" ".repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}` + ); + const lineLength = lines[j].length; + const newLineSeqLength = newlineSequences[j] && newlineSequences[j].length || 0; + if (j === i2) { + const pad = start2 - (count - (lineLength + newLineSeqLength)); + const length = Math.max( + 1, + end > count ? lineLength - pad : end - start2 + ); + res.push(` | ` + " ".repeat(pad) + "^".repeat(length)); + } else if (j > i2) { + if (end > count) { + const length = Math.max(Math.min(end - count, lineLength), 1); + res.push(` | ` + "^".repeat(length)); + } + count += lineLength + newLineSeqLength; + } + } + break; + } + } + return res.join("\n"); +} +function normalizeStyle(value3) { + if (isArray$3(value3)) { + const res = {}; + for (let i2 = 0; i2 < value3.length; i2++) { + const item = value3[i2]; + const normalized = isString$4(item) ? parseStringStyle(item) : normalizeStyle(item); + if (normalized) { + for (const key in normalized) { + res[key] = normalized[key]; + } + } + } + return res; + } else if (isString$4(value3) || isObject$4(value3)) { + return value3; + } +} +const listDelimiterRE = /;(?![^(]*\))/g; +const propertyDelimiterRE = /:([^]+)/; +const styleCommentRE = /\/\*[^]*?\*\//g; +function parseStringStyle(cssText) { + const ret = {}; + cssText.replace(styleCommentRE, "").split(listDelimiterRE).forEach((item) => { + if (item) { + const tmp = item.split(propertyDelimiterRE); + tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim()); + } + }); + return ret; +} +function stringifyStyle(styles) { + let ret = ""; + if (!styles || isString$4(styles)) { + return ret; + } + for (const key in styles) { + const value3 = styles[key]; + if (isString$4(value3) || typeof value3 === "number") { + const normalizedKey = key.startsWith(`--`) ? key : hyphenate(key); + ret += `${normalizedKey}:${value3};`; + } + } + return ret; +} +function normalizeClass(value3) { + let res = ""; + if (isString$4(value3)) { + res = value3; + } else if (isArray$3(value3)) { + for (let i2 = 0; i2 < value3.length; i2++) { + const normalized = normalizeClass(value3[i2]); + if (normalized) { + res += normalized + " "; + } + } + } else if (isObject$4(value3)) { + for (const name in value3) { + if (value3[name]) { + res += name + " "; + } + } + } + return res.trim(); +} +function normalizeProps(props) { + if (!props) return null; + let { class: klass, style } = props; + if (klass && !isString$4(klass)) { + props.class = normalizeClass(klass); + } + if (style) { + props.style = normalizeStyle(style); + } + return props; +} +const HTML_TAGS = "html,body,base,head,link,meta,style,title,address,article,aside,footer,header,hgroup,h1,h2,h3,h4,h5,h6,nav,section,div,dd,dl,dt,figcaption,figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,ruby,s,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,output,progress,select,textarea,details,dialog,menu,summary,template,blockquote,iframe,tfoot"; +const SVG_TAGS = "svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,feDistantLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,text,textPath,title,tspan,unknown,use,view"; +const MATH_TAGS = "annotation,annotation-xml,maction,maligngroup,malignmark,math,menclose,merror,mfenced,mfrac,mfraction,mglyph,mi,mlabeledtr,mlongdiv,mmultiscripts,mn,mo,mover,mpadded,mphantom,mprescripts,mroot,mrow,ms,mscarries,mscarry,msgroup,msline,mspace,msqrt,msrow,mstack,mstyle,msub,msubsup,msup,mtable,mtd,mtext,mtr,munder,munderover,none,semantics"; +const VOID_TAGS = "area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr"; +const isHTMLTag = /* @__PURE__ */ makeMap(HTML_TAGS); +const isSVGTag = /* @__PURE__ */ makeMap(SVG_TAGS); +const isMathMLTag = /* @__PURE__ */ makeMap(MATH_TAGS); +const isVoidTag = /* @__PURE__ */ makeMap(VOID_TAGS); +const specialBooleanAttrs = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`; +const isSpecialBooleanAttr = /* @__PURE__ */ makeMap(specialBooleanAttrs); +const isBooleanAttr = /* @__PURE__ */ makeMap( + specialBooleanAttrs + `,async,autofocus,autoplay,controls,default,defer,disabled,hidden,inert,loop,open,required,reversed,scoped,seamless,checked,muted,multiple,selected` +); +function includeBooleanAttr(value3) { + return !!value3 || value3 === ""; +} +const unsafeAttrCharRE = /[>/="'\u0009\u000a\u000c\u0020]/; +const attrValidationCache = {}; +function isSSRSafeAttrName(name) { + if (attrValidationCache.hasOwnProperty(name)) { + return attrValidationCache[name]; + } + const isUnsafe = unsafeAttrCharRE.test(name); + if (isUnsafe) { + console.error(`unsafe attribute name: ${name}`); + } + return attrValidationCache[name] = !isUnsafe; +} +const propsToAttrMap = { + acceptCharset: "accept-charset", + className: "class", + htmlFor: "for", + httpEquiv: "http-equiv" +}; +const isKnownHtmlAttr = /* @__PURE__ */ makeMap( + `accept,accept-charset,accesskey,action,align,allow,alt,async,autocapitalize,autocomplete,autofocus,autoplay,background,bgcolor,border,buffered,capture,challenge,charset,checked,cite,class,code,codebase,color,cols,colspan,content,contenteditable,contextmenu,controls,coords,crossorigin,csp,data,datetime,decoding,default,defer,dir,dirname,disabled,download,draggable,dropzone,enctype,enterkeyhint,for,form,formaction,formenctype,formmethod,formnovalidate,formtarget,headers,height,hidden,high,href,hreflang,http-equiv,icon,id,importance,inert,integrity,ismap,itemprop,keytype,kind,label,lang,language,loading,list,loop,low,manifest,max,maxlength,minlength,media,min,multiple,muted,name,novalidate,open,optimum,pattern,ping,placeholder,poster,preload,radiogroup,readonly,referrerpolicy,rel,required,reversed,rows,rowspan,sandbox,scope,scoped,selected,shape,size,sizes,slot,span,spellcheck,src,srcdoc,srclang,srcset,start,step,style,summary,tabindex,target,title,translate,type,usemap,value,width,wrap` +); +const isKnownSvgAttr = /* @__PURE__ */ makeMap( + `xmlns,accent-height,accumulate,additive,alignment-baseline,alphabetic,amplitude,arabic-form,ascent,attributeName,attributeType,azimuth,baseFrequency,baseline-shift,baseProfile,bbox,begin,bias,by,calcMode,cap-height,class,clip,clipPathUnits,clip-path,clip-rule,color,color-interpolation,color-interpolation-filters,color-profile,color-rendering,contentScriptType,contentStyleType,crossorigin,cursor,cx,cy,d,decelerate,descent,diffuseConstant,direction,display,divisor,dominant-baseline,dur,dx,dy,edgeMode,elevation,enable-background,end,exponent,fill,fill-opacity,fill-rule,filter,filterRes,filterUnits,flood-color,flood-opacity,font-family,font-size,font-size-adjust,font-stretch,font-style,font-variant,font-weight,format,from,fr,fx,fy,g1,g2,glyph-name,glyph-orientation-horizontal,glyph-orientation-vertical,glyphRef,gradientTransform,gradientUnits,hanging,height,href,hreflang,horiz-adv-x,horiz-origin-x,id,ideographic,image-rendering,in,in2,intercept,k,k1,k2,k3,k4,kernelMatrix,kernelUnitLength,kerning,keyPoints,keySplines,keyTimes,lang,lengthAdjust,letter-spacing,lighting-color,limitingConeAngle,local,marker-end,marker-mid,marker-start,markerHeight,markerUnits,markerWidth,mask,maskContentUnits,maskUnits,mathematical,max,media,method,min,mode,name,numOctaves,offset,opacity,operator,order,orient,orientation,origin,overflow,overline-position,overline-thickness,panose-1,paint-order,path,pathLength,patternContentUnits,patternTransform,patternUnits,ping,pointer-events,points,pointsAtX,pointsAtY,pointsAtZ,preserveAlpha,preserveAspectRatio,primitiveUnits,r,radius,referrerPolicy,refX,refY,rel,rendering-intent,repeatCount,repeatDur,requiredExtensions,requiredFeatures,restart,result,rotate,rx,ry,scale,seed,shape-rendering,slope,spacing,specularConstant,specularExponent,speed,spreadMethod,startOffset,stdDeviation,stemh,stemv,stitchTiles,stop-color,stop-opacity,strikethrough-position,strikethrough-thickness,string,stroke,stroke-dasharray,stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,stroke-opacity,stroke-width,style,surfaceScale,systemLanguage,tabindex,tableValues,target,targetX,targetY,text-anchor,text-decoration,text-rendering,textLength,to,transform,transform-origin,type,u1,u2,underline-position,underline-thickness,unicode,unicode-bidi,unicode-range,units-per-em,v-alphabetic,v-hanging,v-ideographic,v-mathematical,values,vector-effect,version,vert-adv-y,vert-origin-x,vert-origin-y,viewBox,viewTarget,visibility,width,widths,word-spacing,writing-mode,x,x-height,x1,x2,xChannelSelector,xlink:actuate,xlink:arcrole,xlink:href,xlink:role,xlink:show,xlink:title,xlink:type,xmlns:xlink,xml:base,xml:lang,xml:space,y,y1,y2,yChannelSelector,z,zoomAndPan` +); +function isRenderableAttrValue(value3) { + if (value3 == null) { + return false; + } + const type = typeof value3; + return type === "string" || type === "number" || type === "boolean"; +} +const escapeRE = /["'&<>]/; +function escapeHtml$1(string) { + const str = "" + string; + const match = escapeRE.exec(str); + if (!match) { + return str; + } + let html = ""; + let escaped; + let index2; + let lastIndex = 0; + for (index2 = match.index; index2 < str.length; index2++) { + switch (str.charCodeAt(index2)) { + case 34: + escaped = """; + break; + case 38: + escaped = "&"; + break; + case 39: + escaped = "'"; + break; + case 60: + escaped = "<"; + break; + case 62: + escaped = ">"; + break; + default: + continue; + } + if (lastIndex !== index2) { + html += str.slice(lastIndex, index2); + } + lastIndex = index2 + 1; + html += escaped; + } + return lastIndex !== index2 ? html + str.slice(lastIndex, index2) : html; +} +const commentStripRE = /^-?>||--!>| looseEqual(item, val)); +} +const isRef$1 = (val) => { + return !!(val && val.__v_isRef === true); +}; +const toDisplayString$1 = (val) => { + return isString$4(val) ? val : val == null ? "" : isArray$3(val) || isObject$4(val) && (val.toString === objectToString$1 || !isFunction$3(val.toString)) ? isRef$1(val) ? toDisplayString$1(val.value) : JSON.stringify(val, replacer, 2) : String(val); +}; +const replacer = (_key, val) => { + if (isRef$1(val)) { + return replacer(_key, val.value); + } else if (isMap(val)) { + return { + [`Map(${val.size})`]: [...val.entries()].reduce( + (entries, [key, val2], i2) => { + entries[stringifySymbol(key, i2) + " =>"] = val2; + return entries; + }, + {} + ) + }; + } else if (isSet(val)) { + return { + [`Set(${val.size})`]: [...val.values()].map((v2) => stringifySymbol(v2)) + }; + } else if (isSymbol$1(val)) { + return stringifySymbol(val); + } else if (isObject$4(val) && !isArray$3(val) && !isPlainObject$2(val)) { + return String(val); + } + return val; +}; +const stringifySymbol = (v2, i2 = "") => { + var _a2; + return ( + // Symbol.description in es2019+ so we need to cast here to pass + // the lib: es2016 check + isSymbol$1(v2) ? `Symbol(${(_a2 = v2.description) != null ? _a2 : i2})` : v2 + ); +}; +/** +* @vue/reactivity v3.4.31 +* (c) 2018-present Yuxi (Evan) You and Vue contributors +* @license MIT +**/ +function warn$3(msg, ...args) { + console.warn(`[Vue warn] ${msg}`, ...args); +} +let activeEffectScope; +class EffectScope { + constructor(detached = false) { + this.detached = detached; + this._active = true; + this.effects = []; + this.cleanups = []; + this.parent = activeEffectScope; + if (!detached && activeEffectScope) { + this.index = (activeEffectScope.scopes || (activeEffectScope.scopes = [])).push( + this + ) - 1; + } + } + get active() { + return this._active; + } + run(fn) { + if (this._active) { + const currentEffectScope = activeEffectScope; + try { + activeEffectScope = this; + return fn(); + } finally { + activeEffectScope = currentEffectScope; + } + } else if (false) { + warn$3(`cannot run an inactive effect scope.`); + } + } + /** + * This should only be called on non-detached scopes + * @internal + */ + on() { + activeEffectScope = this; + } + /** + * This should only be called on non-detached scopes + * @internal + */ + off() { + activeEffectScope = this.parent; + } + stop(fromParent) { + if (this._active) { + let i2, l; + for (i2 = 0, l = this.effects.length; i2 < l; i2++) { + this.effects[i2].stop(); + } + for (i2 = 0, l = this.cleanups.length; i2 < l; i2++) { + this.cleanups[i2](); + } + if (this.scopes) { + for (i2 = 0, l = this.scopes.length; i2 < l; i2++) { + this.scopes[i2].stop(true); + } + } + if (!this.detached && this.parent && !fromParent) { + const last2 = this.parent.scopes.pop(); + if (last2 && last2 !== this) { + this.parent.scopes[this.index] = last2; + last2.index = this.index; + } + } + this.parent = void 0; + this._active = false; + } + } +} +function effectScope(detached) { + return new EffectScope(detached); +} +function recordEffectScope(effect2, scope = activeEffectScope) { + if (scope && scope.active) { + scope.effects.push(effect2); + } +} +function getCurrentScope() { + return activeEffectScope; +} +function onScopeDispose(fn) { + if (activeEffectScope) { + activeEffectScope.cleanups.push(fn); + } else if (false) { + warn$3( + `onScopeDispose() is called when there is no active effect scope to be associated with.` + ); + } +} +let activeEffect; +class ReactiveEffect { + constructor(fn, trigger2, scheduler, scope) { + this.fn = fn; + this.trigger = trigger2; + this.scheduler = scheduler; + this.active = true; + this.deps = []; + this._dirtyLevel = 4; + this._trackId = 0; + this._runnings = 0; + this._shouldSchedule = false; + this._depsLength = 0; + recordEffectScope(this, scope); + } + get dirty() { + if (this._dirtyLevel === 2 || this._dirtyLevel === 3) { + this._dirtyLevel = 1; + pauseTracking(); + for (let i2 = 0; i2 < this._depsLength; i2++) { + const dep = this.deps[i2]; + if (dep.computed) { + triggerComputed(dep.computed); + if (this._dirtyLevel >= 4) { + break; + } + } + } + if (this._dirtyLevel === 1) { + this._dirtyLevel = 0; + } + resetTracking(); + } + return this._dirtyLevel >= 4; + } + set dirty(v2) { + this._dirtyLevel = v2 ? 4 : 0; + } + run() { + this._dirtyLevel = 0; + if (!this.active) { + return this.fn(); + } + let lastShouldTrack = shouldTrack; + let lastEffect = activeEffect; + try { + shouldTrack = true; + activeEffect = this; + this._runnings++; + preCleanupEffect(this); + return this.fn(); + } finally { + postCleanupEffect(this); + this._runnings--; + activeEffect = lastEffect; + shouldTrack = lastShouldTrack; + } + } + stop() { + if (this.active) { + preCleanupEffect(this); + postCleanupEffect(this); + this.onStop && this.onStop(); + this.active = false; + } + } +} +function triggerComputed(computed2) { + return computed2.value; +} +function preCleanupEffect(effect2) { + effect2._trackId++; + effect2._depsLength = 0; +} +function postCleanupEffect(effect2) { + if (effect2.deps.length > effect2._depsLength) { + for (let i2 = effect2._depsLength; i2 < effect2.deps.length; i2++) { + cleanupDepEffect(effect2.deps[i2], effect2); + } + effect2.deps.length = effect2._depsLength; + } +} +function cleanupDepEffect(dep, effect2) { + const trackId = dep.get(effect2); + if (trackId !== void 0 && effect2._trackId !== trackId) { + dep.delete(effect2); + if (dep.size === 0) { + dep.cleanup(); + } + } +} +function effect(fn, options3) { + if (fn.effect instanceof ReactiveEffect) { + fn = fn.effect.fn; + } + const _effect = new ReactiveEffect(fn, NOOP, () => { + if (_effect.dirty) { + _effect.run(); + } + }); + if (options3) { + extend(_effect, options3); + if (options3.scope) recordEffectScope(_effect, options3.scope); + } + if (!options3 || !options3.lazy) { + _effect.run(); + } + const runner = _effect.run.bind(_effect); + runner.effect = _effect; + return runner; +} +function stop(runner) { + runner.effect.stop(); +} +let shouldTrack = true; +let pauseScheduleStack = 0; +const trackStack = []; +function pauseTracking() { + trackStack.push(shouldTrack); + shouldTrack = false; +} +function enableTracking() { + trackStack.push(shouldTrack); + shouldTrack = true; +} +function resetTracking() { + const last2 = trackStack.pop(); + shouldTrack = last2 === void 0 ? true : last2; +} +function pauseScheduling() { + pauseScheduleStack++; +} +function resetScheduling() { + pauseScheduleStack--; + while (!pauseScheduleStack && queueEffectSchedulers.length) { + queueEffectSchedulers.shift()(); + } +} +function trackEffect(effect2, dep, debuggerEventExtraInfo) { + var _a2; + if (dep.get(effect2) !== effect2._trackId) { + dep.set(effect2, effect2._trackId); + const oldDep = effect2.deps[effect2._depsLength]; + if (oldDep !== dep) { + if (oldDep) { + cleanupDepEffect(oldDep, effect2); + } + effect2.deps[effect2._depsLength++] = dep; + } else { + effect2._depsLength++; + } + if (false) { + (_a2 = effect2.onTrack) == null ? void 0 : _a2.call(effect2, extend({ effect: effect2 }, debuggerEventExtraInfo)); + } + } +} +const queueEffectSchedulers = []; +function triggerEffects(dep, dirtyLevel, debuggerEventExtraInfo) { + var _a2; + pauseScheduling(); + for (const effect2 of dep.keys()) { + let tracking; + if (effect2._dirtyLevel < dirtyLevel && (tracking != null ? tracking : tracking = dep.get(effect2) === effect2._trackId)) { + effect2._shouldSchedule || (effect2._shouldSchedule = effect2._dirtyLevel === 0); + effect2._dirtyLevel = dirtyLevel; + } + if (effect2._shouldSchedule && (tracking != null ? tracking : tracking = dep.get(effect2) === effect2._trackId)) { + if (false) { + (_a2 = effect2.onTrigger) == null ? void 0 : _a2.call(effect2, extend({ effect: effect2 }, debuggerEventExtraInfo)); + } + effect2.trigger(); + if ((!effect2._runnings || effect2.allowRecurse) && effect2._dirtyLevel !== 2) { + effect2._shouldSchedule = false; + if (effect2.scheduler) { + queueEffectSchedulers.push(effect2.scheduler); + } + } + } + } + resetScheduling(); +} +const createDep = (cleanup, computed2) => { + const dep = /* @__PURE__ */ new Map(); + dep.cleanup = cleanup; + dep.computed = computed2; + return dep; +}; +const targetMap = /* @__PURE__ */ new WeakMap(); +const ITERATE_KEY = Symbol(false ? "iterate" : ""); +const MAP_KEY_ITERATE_KEY = Symbol(false ? "Map key iterate" : ""); +function track(target, type, key) { + if (shouldTrack && activeEffect) { + let depsMap = targetMap.get(target); + if (!depsMap) { + targetMap.set(target, depsMap = /* @__PURE__ */ new Map()); + } + let dep = depsMap.get(key); + if (!dep) { + depsMap.set(key, dep = createDep(() => depsMap.delete(key))); + } + trackEffect( + activeEffect, + dep, + false ? { + target, + type, + key + } : void 0 + ); + } +} +function trigger(target, type, key, newValue, oldValue, oldTarget) { + const depsMap = targetMap.get(target); + if (!depsMap) { + return; + } + let deps = []; + if (type === "clear") { + deps = [...depsMap.values()]; + } else if (key === "length" && isArray$3(target)) { + const newLength = Number(newValue); + depsMap.forEach((dep, key2) => { + if (key2 === "length" || !isSymbol$1(key2) && key2 >= newLength) { + deps.push(dep); + } + }); + } else { + if (key !== void 0) { + deps.push(depsMap.get(key)); + } + switch (type) { + case "add": + if (!isArray$3(target)) { + deps.push(depsMap.get(ITERATE_KEY)); + if (isMap(target)) { + deps.push(depsMap.get(MAP_KEY_ITERATE_KEY)); + } + } else if (isIntegerKey(key)) { + deps.push(depsMap.get("length")); + } + break; + case "delete": + if (!isArray$3(target)) { + deps.push(depsMap.get(ITERATE_KEY)); + if (isMap(target)) { + deps.push(depsMap.get(MAP_KEY_ITERATE_KEY)); + } + } + break; + case "set": + if (isMap(target)) { + deps.push(depsMap.get(ITERATE_KEY)); + } + break; + } + } + pauseScheduling(); + for (const dep of deps) { + if (dep) { + triggerEffects( + dep, + 4, + false ? { + target, + type, + key, + newValue, + oldValue, + oldTarget + } : void 0 + ); + } + } + resetScheduling(); +} +function getDepFromReactive(object, key) { + const depsMap = targetMap.get(object); + return depsMap && depsMap.get(key); +} +const isNonTrackableKeys = /* @__PURE__ */ makeMap(`__proto__,__v_isRef,__isVue`); +const builtInSymbols = new Set( + /* @__PURE__ */ Object.getOwnPropertyNames(Symbol).filter((key) => key !== "arguments" && key !== "caller").map((key) => Symbol[key]).filter(isSymbol$1) +); +const arrayInstrumentations = /* @__PURE__ */ createArrayInstrumentations(); +function createArrayInstrumentations() { + const instrumentations = {}; + ["includes", "indexOf", "lastIndexOf"].forEach((key) => { + instrumentations[key] = function(...args) { + const arr = toRaw(this); + for (let i2 = 0, l = this.length; i2 < l; i2++) { + track(arr, "get", i2 + ""); + } + const res = arr[key](...args); + if (res === -1 || res === false) { + return arr[key](...args.map(toRaw)); + } else { + return res; + } + }; + }); + ["push", "pop", "shift", "unshift", "splice"].forEach((key) => { + instrumentations[key] = function(...args) { + pauseTracking(); + pauseScheduling(); + const res = toRaw(this)[key].apply(this, args); + resetScheduling(); + resetTracking(); + return res; + }; + }); + return instrumentations; +} +function hasOwnProperty$1(key) { + if (!isSymbol$1(key)) key = String(key); + const obj = toRaw(this); + track(obj, "has", key); + return obj.hasOwnProperty(key); +} +class BaseReactiveHandler { + constructor(_isReadonly = false, _isShallow = false) { + this._isReadonly = _isReadonly; + this._isShallow = _isShallow; + } + get(target, key, receiver) { + const isReadonly2 = this._isReadonly, isShallow2 = this._isShallow; + if (key === "__v_isReactive") { + return !isReadonly2; + } else if (key === "__v_isReadonly") { + return isReadonly2; + } else if (key === "__v_isShallow") { + return isShallow2; + } else if (key === "__v_raw") { + if (receiver === (isReadonly2 ? isShallow2 ? shallowReadonlyMap : readonlyMap : isShallow2 ? shallowReactiveMap : reactiveMap).get(target) || // receiver is not the reactive proxy, but has the same prototype + // this means the reciever is a user proxy of the reactive proxy + Object.getPrototypeOf(target) === Object.getPrototypeOf(receiver)) { + return target; + } + return; + } + const targetIsArray = isArray$3(target); + if (!isReadonly2) { + if (targetIsArray && hasOwn$2(arrayInstrumentations, key)) { + return Reflect.get(arrayInstrumentations, key, receiver); + } + if (key === "hasOwnProperty") { + return hasOwnProperty$1; + } + } + const res = Reflect.get(target, key, receiver); + if (isSymbol$1(key) ? builtInSymbols.has(key) : isNonTrackableKeys(key)) { + return res; + } + if (!isReadonly2) { + track(target, "get", key); + } + if (isShallow2) { + return res; + } + if (isRef(res)) { + return targetIsArray && isIntegerKey(key) ? res : res.value; + } + if (isObject$4(res)) { + return isReadonly2 ? readonly(res) : reactive(res); + } + return res; + } +} +class MutableReactiveHandler extends BaseReactiveHandler { + constructor(isShallow2 = false) { + super(false, isShallow2); + } + set(target, key, value3, receiver) { + let oldValue = target[key]; + if (!this._isShallow) { + const isOldValueReadonly = isReadonly(oldValue); + if (!isShallow(value3) && !isReadonly(value3)) { + oldValue = toRaw(oldValue); + value3 = toRaw(value3); + } + if (!isArray$3(target) && isRef(oldValue) && !isRef(value3)) { + if (isOldValueReadonly) { + return false; + } else { + oldValue.value = value3; + return true; + } + } + } + const hadKey = isArray$3(target) && isIntegerKey(key) ? Number(key) < target.length : hasOwn$2(target, key); + const result = Reflect.set(target, key, value3, receiver); + if (target === toRaw(receiver)) { + if (!hadKey) { + trigger(target, "add", key, value3); + } else if (hasChanged(value3, oldValue)) { + trigger(target, "set", key, value3, oldValue); + } + } + return result; + } + deleteProperty(target, key) { + const hadKey = hasOwn$2(target, key); + const oldValue = target[key]; + const result = Reflect.deleteProperty(target, key); + if (result && hadKey) { + trigger(target, "delete", key, void 0, oldValue); + } + return result; + } + has(target, key) { + const result = Reflect.has(target, key); + if (!isSymbol$1(key) || !builtInSymbols.has(key)) { + track(target, "has", key); + } + return result; + } + ownKeys(target) { + track( + target, + "iterate", + isArray$3(target) ? "length" : ITERATE_KEY + ); + return Reflect.ownKeys(target); + } +} +class ReadonlyReactiveHandler extends BaseReactiveHandler { + constructor(isShallow2 = false) { + super(true, isShallow2); + } + set(target, key) { + if (false) { + warn$3( + `Set operation on key "${String(key)}" failed: target is readonly.`, + target + ); + } + return true; + } + deleteProperty(target, key) { + if (false) { + warn$3( + `Delete operation on key "${String(key)}" failed: target is readonly.`, + target + ); + } + return true; + } +} +const mutableHandlers = /* @__PURE__ */ new MutableReactiveHandler(); +const readonlyHandlers = /* @__PURE__ */ new ReadonlyReactiveHandler(); +const shallowReactiveHandlers = /* @__PURE__ */ new MutableReactiveHandler( + true +); +const shallowReadonlyHandlers = /* @__PURE__ */ new ReadonlyReactiveHandler(true); +const toShallow = (value3) => value3; +const getProto = (v2) => Reflect.getPrototypeOf(v2); +function get$1(target, key, isReadonly2 = false, isShallow2 = false) { + target = target["__v_raw"]; + const rawTarget = toRaw(target); + const rawKey = toRaw(key); + if (!isReadonly2) { + if (hasChanged(key, rawKey)) { + track(rawTarget, "get", key); + } + track(rawTarget, "get", rawKey); + } + const { has: has2 } = getProto(rawTarget); + const wrap = isShallow2 ? toShallow : isReadonly2 ? toReadonly : toReactive; + if (has2.call(rawTarget, key)) { + return wrap(target.get(key)); + } else if (has2.call(rawTarget, rawKey)) { + return wrap(target.get(rawKey)); + } else if (target !== rawTarget) { + target.get(key); + } +} +function has(key, isReadonly2 = false) { + const target = this["__v_raw"]; + const rawTarget = toRaw(target); + const rawKey = toRaw(key); + if (!isReadonly2) { + if (hasChanged(key, rawKey)) { + track(rawTarget, "has", key); + } + track(rawTarget, "has", rawKey); + } + return key === rawKey ? target.has(key) : target.has(key) || target.has(rawKey); +} +function size(target, isReadonly2 = false) { + target = target["__v_raw"]; + !isReadonly2 && track(toRaw(target), "iterate", ITERATE_KEY); + return Reflect.get(target, "size", target); +} +function add(value3) { + value3 = toRaw(value3); + const target = toRaw(this); + const proto = getProto(target); + const hadKey = proto.has.call(target, value3); + if (!hadKey) { + target.add(value3); + trigger(target, "add", value3, value3); + } + return this; +} +function set$1(key, value3) { + value3 = toRaw(value3); + const target = toRaw(this); + const { has: has2, get: get2 } = getProto(target); + let hadKey = has2.call(target, key); + if (!hadKey) { + key = toRaw(key); + hadKey = has2.call(target, key); + } else if (false) { + checkIdentityKeys(target, has2, key); + } + const oldValue = get2.call(target, key); + target.set(key, value3); + if (!hadKey) { + trigger(target, "add", key, value3); + } else if (hasChanged(value3, oldValue)) { + trigger(target, "set", key, value3, oldValue); + } + return this; +} +function deleteEntry(key) { + const target = toRaw(this); + const { has: has2, get: get2 } = getProto(target); + let hadKey = has2.call(target, key); + if (!hadKey) { + key = toRaw(key); + hadKey = has2.call(target, key); + } else if (false) { + checkIdentityKeys(target, has2, key); + } + const oldValue = get2 ? get2.call(target, key) : void 0; + const result = target.delete(key); + if (hadKey) { + trigger(target, "delete", key, void 0, oldValue); + } + return result; +} +function clear() { + const target = toRaw(this); + const hadItems = target.size !== 0; + const oldTarget = false ? isMap(target) ? new Map(target) : new Set(target) : void 0; + const result = target.clear(); + if (hadItems) { + trigger(target, "clear", void 0, void 0, oldTarget); + } + return result; +} +function createForEach(isReadonly2, isShallow2) { + return function forEach(callback, thisArg) { + const observed = this; + const target = observed["__v_raw"]; + const rawTarget = toRaw(target); + const wrap = isShallow2 ? toShallow : isReadonly2 ? toReadonly : toReactive; + !isReadonly2 && track(rawTarget, "iterate", ITERATE_KEY); + return target.forEach((value3, key) => { + return callback.call(thisArg, wrap(value3), wrap(key), observed); + }); + }; +} +function createIterableMethod(method, isReadonly2, isShallow2) { + return function(...args) { + const target = this["__v_raw"]; + const rawTarget = toRaw(target); + const targetIsMap = isMap(rawTarget); + const isPair = method === "entries" || method === Symbol.iterator && targetIsMap; + const isKeyOnly = method === "keys" && targetIsMap; + const innerIterator = target[method](...args); + const wrap = isShallow2 ? toShallow : isReadonly2 ? toReadonly : toReactive; + !isReadonly2 && track( + rawTarget, + "iterate", + isKeyOnly ? MAP_KEY_ITERATE_KEY : ITERATE_KEY + ); + return { + // iterator protocol + next() { + const { value: value3, done } = innerIterator.next(); + return done ? { value: value3, done } : { + value: isPair ? [wrap(value3[0]), wrap(value3[1])] : wrap(value3), + done + }; + }, + // iterable protocol + [Symbol.iterator]() { + return this; + } + }; + }; +} +function createReadonlyMethod(type) { + return function(...args) { + if (false) { + const key = args[0] ? `on key "${args[0]}" ` : ``; + warn$3( + `${capitalize$1(type)} operation ${key}failed: target is readonly.`, + toRaw(this) + ); + } + return type === "delete" ? false : type === "clear" ? void 0 : this; + }; +} +function createInstrumentations() { + const mutableInstrumentations2 = { + get(key) { + return get$1(this, key); + }, + get size() { + return size(this); + }, + has, + add, + set: set$1, + delete: deleteEntry, + clear, + forEach: createForEach(false, false) + }; + const shallowInstrumentations2 = { + get(key) { + return get$1(this, key, false, true); + }, + get size() { + return size(this); + }, + has, + add, + set: set$1, + delete: deleteEntry, + clear, + forEach: createForEach(false, true) + }; + const readonlyInstrumentations2 = { + get(key) { + return get$1(this, key, true); + }, + get size() { + return size(this, true); + }, + has(key) { + return has.call(this, key, true); + }, + add: createReadonlyMethod("add"), + set: createReadonlyMethod("set"), + delete: createReadonlyMethod("delete"), + clear: createReadonlyMethod("clear"), + forEach: createForEach(true, false) + }; + const shallowReadonlyInstrumentations2 = { + get(key) { + return get$1(this, key, true, true); + }, + get size() { + return size(this, true); + }, + has(key) { + return has.call(this, key, true); + }, + add: createReadonlyMethod("add"), + set: createReadonlyMethod("set"), + delete: createReadonlyMethod("delete"), + clear: createReadonlyMethod("clear"), + forEach: createForEach(true, true) + }; + const iteratorMethods = [ + "keys", + "values", + "entries", + Symbol.iterator + ]; + iteratorMethods.forEach((method) => { + mutableInstrumentations2[method] = createIterableMethod(method, false, false); + readonlyInstrumentations2[method] = createIterableMethod(method, true, false); + shallowInstrumentations2[method] = createIterableMethod(method, false, true); + shallowReadonlyInstrumentations2[method] = createIterableMethod( + method, + true, + true + ); + }); + return [ + mutableInstrumentations2, + readonlyInstrumentations2, + shallowInstrumentations2, + shallowReadonlyInstrumentations2 + ]; +} +const [ + mutableInstrumentations, + readonlyInstrumentations, + shallowInstrumentations, + shallowReadonlyInstrumentations +] = /* @__PURE__ */ createInstrumentations(); +function createInstrumentationGetter(isReadonly2, shallow) { + const instrumentations = shallow ? isReadonly2 ? shallowReadonlyInstrumentations : shallowInstrumentations : isReadonly2 ? readonlyInstrumentations : mutableInstrumentations; + return (target, key, receiver) => { + if (key === "__v_isReactive") { + return !isReadonly2; + } else if (key === "__v_isReadonly") { + return isReadonly2; + } else if (key === "__v_raw") { + return target; + } + return Reflect.get( + hasOwn$2(instrumentations, key) && key in target ? instrumentations : target, + key, + receiver + ); + }; +} +const mutableCollectionHandlers = { + get: /* @__PURE__ */ createInstrumentationGetter(false, false) +}; +const shallowCollectionHandlers = { + get: /* @__PURE__ */ createInstrumentationGetter(false, true) +}; +const readonlyCollectionHandlers = { + get: /* @__PURE__ */ createInstrumentationGetter(true, false) +}; +const shallowReadonlyCollectionHandlers = { + get: /* @__PURE__ */ createInstrumentationGetter(true, true) +}; +function checkIdentityKeys(target, has2, key) { + const rawKey = toRaw(key); + if (rawKey !== key && has2.call(target, rawKey)) { + const type = toRawType(target); + warn$3( + `Reactive ${type} contains both the raw and reactive versions of the same object${type === `Map` ? ` as keys` : ``}, which can lead to inconsistencies. Avoid differentiating between the raw and reactive versions of an object and only use the reactive version if possible.` + ); + } +} +const reactiveMap = /* @__PURE__ */ new WeakMap(); +const shallowReactiveMap = /* @__PURE__ */ new WeakMap(); +const readonlyMap = /* @__PURE__ */ new WeakMap(); +const shallowReadonlyMap = /* @__PURE__ */ new WeakMap(); +function targetTypeMap(rawType) { + switch (rawType) { + case "Object": + case "Array": + return 1; + case "Map": + case "Set": + case "WeakMap": + case "WeakSet": + return 2; + default: + return 0; + } +} +function getTargetType(value3) { + return value3["__v_skip"] || !Object.isExtensible(value3) ? 0 : targetTypeMap(toRawType(value3)); +} +function reactive(target) { + if (isReadonly(target)) { + return target; + } + return createReactiveObject( + target, + false, + mutableHandlers, + mutableCollectionHandlers, + reactiveMap + ); +} +function shallowReactive(target) { + return createReactiveObject( + target, + false, + shallowReactiveHandlers, + shallowCollectionHandlers, + shallowReactiveMap + ); +} +function readonly(target) { + return createReactiveObject( + target, + true, + readonlyHandlers, + readonlyCollectionHandlers, + readonlyMap + ); +} +function shallowReadonly(target) { + return createReactiveObject( + target, + true, + shallowReadonlyHandlers, + shallowReadonlyCollectionHandlers, + shallowReadonlyMap + ); +} +function createReactiveObject(target, isReadonly2, baseHandlers, collectionHandlers, proxyMap) { + if (!isObject$4(target)) { + if (false) { + warn$3( + `value cannot be made ${isReadonly2 ? "readonly" : "reactive"}: ${String( + target + )}` + ); + } + return target; + } + if (target["__v_raw"] && !(isReadonly2 && target["__v_isReactive"])) { + return target; + } + const existingProxy = proxyMap.get(target); + if (existingProxy) { + return existingProxy; + } + const targetType = getTargetType(target); + if (targetType === 0) { + return target; + } + const proxy = new Proxy( + target, + targetType === 2 ? collectionHandlers : baseHandlers + ); + proxyMap.set(target, proxy); + return proxy; +} +function isReactive(value3) { + if (isReadonly(value3)) { + return isReactive(value3["__v_raw"]); + } + return !!(value3 && value3["__v_isReactive"]); +} +function isReadonly(value3) { + return !!(value3 && value3["__v_isReadonly"]); +} +function isShallow(value3) { + return !!(value3 && value3["__v_isShallow"]); +} +function isProxy(value3) { + return value3 ? !!value3["__v_raw"] : false; +} +function toRaw(observed) { + const raw = observed && observed["__v_raw"]; + return raw ? toRaw(raw) : observed; +} +function markRaw(value3) { + if (Object.isExtensible(value3)) { + def(value3, "__v_skip", true); + } + return value3; +} +const toReactive = (value3) => isObject$4(value3) ? reactive(value3) : value3; +const toReadonly = (value3) => isObject$4(value3) ? readonly(value3) : value3; +const COMPUTED_SIDE_EFFECT_WARN = `Computed is still dirty after getter evaluation, likely because a computed is mutating its own dependency in its getter. State mutations in computed getters should be avoided. Check the docs for more details: https://vuejs.org/guide/essentials/computed.html#getters-should-be-side-effect-free`; +class ComputedRefImpl { + constructor(getter, _setter, isReadonly2, isSSR) { + this.getter = getter; + this._setter = _setter; + this.dep = void 0; + this.__v_isRef = true; + this["__v_isReadonly"] = false; + this.effect = new ReactiveEffect( + () => getter(this._value), + () => triggerRefValue( + this, + this.effect._dirtyLevel === 2 ? 2 : 3 + ) + ); + this.effect.computed = this; + this.effect.active = this._cacheable = !isSSR; + this["__v_isReadonly"] = isReadonly2; + } + get value() { + const self2 = toRaw(this); + if ((!self2._cacheable || self2.effect.dirty) && hasChanged(self2._value, self2._value = self2.effect.run())) { + triggerRefValue(self2, 4); + } + trackRefValue(self2); + if (self2.effect._dirtyLevel >= 2) { + if (false) { + warn$3(COMPUTED_SIDE_EFFECT_WARN, ` + +getter: `, this.getter); + } + triggerRefValue(self2, 2); + } + return self2._value; + } + set value(newValue) { + this._setter(newValue); + } + // #region polyfill _dirty for backward compatibility third party code for Vue <= 3.3.x + get _dirty() { + return this.effect.dirty; + } + set _dirty(v2) { + this.effect.dirty = v2; + } + // #endregion +} +function computed$1(getterOrOptions, debugOptions, isSSR = false) { + let getter; + let setter; + const onlyGetter = isFunction$3(getterOrOptions); + if (onlyGetter) { + getter = getterOrOptions; + setter = false ? () => { + warn$3("Write operation failed: computed value is readonly"); + } : NOOP; + } else { + getter = getterOrOptions.get; + setter = getterOrOptions.set; + } + const cRef = new ComputedRefImpl(getter, setter, onlyGetter || !setter, isSSR); + if (false) { + cRef.effect.onTrack = debugOptions.onTrack; + cRef.effect.onTrigger = debugOptions.onTrigger; + } + return cRef; +} +function trackRefValue(ref2) { + var _a2; + if (shouldTrack && activeEffect) { + ref2 = toRaw(ref2); + trackEffect( + activeEffect, + (_a2 = ref2.dep) != null ? _a2 : ref2.dep = createDep( + () => ref2.dep = void 0, + ref2 instanceof ComputedRefImpl ? ref2 : void 0 + ), + false ? { + target: ref2, + type: "get", + key: "value" + } : void 0 + ); + } +} +function triggerRefValue(ref2, dirtyLevel = 4, newVal, oldVal) { + ref2 = toRaw(ref2); + const dep = ref2.dep; + if (dep) { + triggerEffects( + dep, + dirtyLevel, + false ? { + target: ref2, + type: "set", + key: "value", + newValue: newVal, + oldValue: oldVal + } : void 0 + ); + } +} +function isRef(r) { + return !!(r && r.__v_isRef === true); +} +function ref(value3) { + return createRef(value3, false); +} +function shallowRef(value3) { + return createRef(value3, true); +} +function createRef(rawValue, shallow) { + if (isRef(rawValue)) { + return rawValue; + } + return new RefImpl(rawValue, shallow); +} +class RefImpl { + constructor(value3, __v_isShallow) { + this.__v_isShallow = __v_isShallow; + this.dep = void 0; + this.__v_isRef = true; + this._rawValue = __v_isShallow ? value3 : toRaw(value3); + this._value = __v_isShallow ? value3 : toReactive(value3); + } + get value() { + trackRefValue(this); + return this._value; + } + set value(newVal) { + const useDirectValue = this.__v_isShallow || isShallow(newVal) || isReadonly(newVal); + newVal = useDirectValue ? newVal : toRaw(newVal); + if (hasChanged(newVal, this._rawValue)) { + const oldVal = this._rawValue; + this._rawValue = newVal; + this._value = useDirectValue ? newVal : toReactive(newVal); + triggerRefValue(this, 4, newVal, oldVal); + } + } +} +function triggerRef(ref2) { + triggerRefValue(ref2, 4, false ? ref2.value : void 0); +} +function unref(ref2) { + return isRef(ref2) ? ref2.value : ref2; +} +function toValue$1(source) { + return isFunction$3(source) ? source() : unref(source); +} +const shallowUnwrapHandlers = { + get: (target, key, receiver) => unref(Reflect.get(target, key, receiver)), + set: (target, key, value3, receiver) => { + const oldValue = target[key]; + if (isRef(oldValue) && !isRef(value3)) { + oldValue.value = value3; + return true; + } else { + return Reflect.set(target, key, value3, receiver); + } + } +}; +function proxyRefs(objectWithRefs) { + return isReactive(objectWithRefs) ? objectWithRefs : new Proxy(objectWithRefs, shallowUnwrapHandlers); +} +class CustomRefImpl { + constructor(factory) { + this.dep = void 0; + this.__v_isRef = true; + const { get: get2, set: set2 } = factory( + () => trackRefValue(this), + () => triggerRefValue(this) + ); + this._get = get2; + this._set = set2; + } + get value() { + return this._get(); + } + set value(newVal) { + this._set(newVal); + } +} +function customRef(factory) { + return new CustomRefImpl(factory); +} +function toRefs(object) { + if (false) { + warn$3(`toRefs() expects a reactive object but received a plain one.`); + } + const ret = isArray$3(object) ? new Array(object.length) : {}; + for (const key in object) { + ret[key] = propertyToRef(object, key); + } + return ret; +} +class ObjectRefImpl { + constructor(_object, _key, _defaultValue) { + this._object = _object; + this._key = _key; + this._defaultValue = _defaultValue; + this.__v_isRef = true; + } + get value() { + const val = this._object[this._key]; + return val === void 0 ? this._defaultValue : val; + } + set value(newVal) { + this._object[this._key] = newVal; + } + get dep() { + return getDepFromReactive(toRaw(this._object), this._key); + } +} +class GetterRefImpl { + constructor(_getter) { + this._getter = _getter; + this.__v_isRef = true; + this.__v_isReadonly = true; + } + get value() { + return this._getter(); + } +} +function toRef(source, key, defaultValue) { + if (isRef(source)) { + return source; + } else if (isFunction$3(source)) { + return new GetterRefImpl(source); + } else if (isObject$4(source) && arguments.length > 1) { + return propertyToRef(source, key, defaultValue); + } else { + return ref(source); + } +} +function propertyToRef(source, key, defaultValue) { + const val = source[key]; + return isRef(val) ? val : new ObjectRefImpl(source, key, defaultValue); +} +const deferredComputed = computed$1; +const TrackOpTypes = { + "GET": "get", + "HAS": "has", + "ITERATE": "iterate" +}; +const TriggerOpTypes = { + "SET": "set", + "ADD": "add", + "DELETE": "delete", + "CLEAR": "clear" +}; +const ReactiveFlags = { + "SKIP": "__v_skip", + "IS_REACTIVE": "__v_isReactive", + "IS_READONLY": "__v_isReadonly", + "IS_SHALLOW": "__v_isShallow", + "RAW": "__v_raw" +}; +/** +* @vue/runtime-core v3.4.31 +* (c) 2018-present Yuxi (Evan) You and Vue contributors +* @license MIT +**/ +const stack = []; +function pushWarningContext(vnode) { + stack.push(vnode); +} +function popWarningContext() { + stack.pop(); +} +function warn$1(msg, ...args) { + pauseTracking(); + const instance = stack.length ? stack[stack.length - 1].component : null; + const appWarnHandler = instance && instance.appContext.config.warnHandler; + const trace = getComponentTrace(); + if (appWarnHandler) { + callWithErrorHandling( + appWarnHandler, + instance, + 11, + [ + // eslint-disable-next-line no-restricted-syntax + msg + args.map((a) => { + var _a2, _b; + return (_b = (_a2 = a.toString) == null ? void 0 : _a2.call(a)) != null ? _b : JSON.stringify(a); + }).join(""), + instance && instance.proxy, + trace.map( + ({ vnode }) => `at <${formatComponentName(instance, vnode.type)}>` + ).join("\n"), + trace + ] + ); + } else { + const warnArgs = [`[Vue warn]: ${msg}`, ...args]; + if (trace.length && // avoid spamming console during tests + true) { + warnArgs.push(` +`, ...formatTrace(trace)); + } + console.warn(...warnArgs); + } + resetTracking(); +} +function getComponentTrace() { + let currentVNode = stack[stack.length - 1]; + if (!currentVNode) { + return []; + } + const normalizedStack = []; + while (currentVNode) { + const last2 = normalizedStack[0]; + if (last2 && last2.vnode === currentVNode) { + last2.recurseCount++; + } else { + normalizedStack.push({ + vnode: currentVNode, + recurseCount: 0 + }); + } + const parentInstance = currentVNode.component && currentVNode.component.parent; + currentVNode = parentInstance && parentInstance.vnode; + } + return normalizedStack; +} +function formatTrace(trace) { + const logs = []; + trace.forEach((entry, i2) => { + logs.push(...i2 === 0 ? [] : [` +`], ...formatTraceEntry(entry)); + }); + return logs; +} +function formatTraceEntry({ vnode, recurseCount }) { + const postfix = recurseCount > 0 ? `... (${recurseCount} recursive calls)` : ``; + const isRoot = vnode.component ? vnode.component.parent == null : false; + const open2 = ` at <${formatComponentName( + vnode.component, + vnode.type, + isRoot + )}`; + const close4 = `>` + postfix; + return vnode.props ? [open2, ...formatProps(vnode.props), close4] : [open2 + close4]; +} +function formatProps(props) { + const res = []; + const keys = Object.keys(props); + keys.slice(0, 3).forEach((key) => { + res.push(...formatProp(key, props[key])); + }); + if (keys.length > 3) { + res.push(` ...`); + } + return res; +} +function formatProp(key, value3, raw) { + if (isString$4(value3)) { + value3 = JSON.stringify(value3); + return raw ? value3 : [`${key}=${value3}`]; + } else if (typeof value3 === "number" || typeof value3 === "boolean" || value3 == null) { + return raw ? value3 : [`${key}=${value3}`]; + } else if (isRef(value3)) { + value3 = formatProp(key, toRaw(value3.value), true); + return raw ? value3 : [`${key}=Ref<`, value3, `>`]; + } else if (isFunction$3(value3)) { + return [`${key}=fn${value3.name ? `<${value3.name}>` : ``}`]; + } else { + value3 = toRaw(value3); + return raw ? value3 : [`${key}=`, value3]; + } +} +function assertNumber(val, type) { + if (true) return; + if (val === void 0) { + return; + } else if (typeof val !== "number") { + warn$1(`${type} is not a valid number - got ${JSON.stringify(val)}.`); + } else if (isNaN(val)) { + warn$1(`${type} is NaN - the duration expression might be incorrect.`); + } +} +const ErrorCodes = { + "SETUP_FUNCTION": 0, + "0": "SETUP_FUNCTION", + "RENDER_FUNCTION": 1, + "1": "RENDER_FUNCTION", + "WATCH_GETTER": 2, + "2": "WATCH_GETTER", + "WATCH_CALLBACK": 3, + "3": "WATCH_CALLBACK", + "WATCH_CLEANUP": 4, + "4": "WATCH_CLEANUP", + "NATIVE_EVENT_HANDLER": 5, + "5": "NATIVE_EVENT_HANDLER", + "COMPONENT_EVENT_HANDLER": 6, + "6": "COMPONENT_EVENT_HANDLER", + "VNODE_HOOK": 7, + "7": "VNODE_HOOK", + "DIRECTIVE_HOOK": 8, + "8": "DIRECTIVE_HOOK", + "TRANSITION_HOOK": 9, + "9": "TRANSITION_HOOK", + "APP_ERROR_HANDLER": 10, + "10": "APP_ERROR_HANDLER", + "APP_WARN_HANDLER": 11, + "11": "APP_WARN_HANDLER", + "FUNCTION_REF": 12, + "12": "FUNCTION_REF", + "ASYNC_COMPONENT_LOADER": 13, + "13": "ASYNC_COMPONENT_LOADER", + "SCHEDULER": 14, + "14": "SCHEDULER" +}; +const ErrorTypeStrings$1 = { + ["sp"]: "serverPrefetch hook", + ["bc"]: "beforeCreate hook", + ["c"]: "created hook", + ["bm"]: "beforeMount hook", + ["m"]: "mounted hook", + ["bu"]: "beforeUpdate hook", + ["u"]: "updated", + ["bum"]: "beforeUnmount hook", + ["um"]: "unmounted hook", + ["a"]: "activated hook", + ["da"]: "deactivated hook", + ["ec"]: "errorCaptured hook", + ["rtc"]: "renderTracked hook", + ["rtg"]: "renderTriggered hook", + [0]: "setup function", + [1]: "render function", + [2]: "watcher getter", + [3]: "watcher callback", + [4]: "watcher cleanup function", + [5]: "native event handler", + [6]: "component event handler", + [7]: "vnode hook", + [8]: "directive hook", + [9]: "transition hook", + [10]: "app errorHandler", + [11]: "app warnHandler", + [12]: "ref function", + [13]: "async component loader", + [14]: "scheduler flush. This is likely a Vue internals bug. Please open an issue at https://github.com/vuejs/core ." +}; +function callWithErrorHandling(fn, instance, type, args) { + try { + return args ? fn(...args) : fn(); + } catch (err) { + handleError(err, instance, type); + } +} +function callWithAsyncErrorHandling(fn, instance, type, args) { + if (isFunction$3(fn)) { + const res = callWithErrorHandling(fn, instance, type, args); + if (res && isPromise$2(res)) { + res.catch((err) => { + handleError(err, instance, type); + }); + } + return res; + } + if (isArray$3(fn)) { + const values2 = []; + for (let i2 = 0; i2 < fn.length; i2++) { + values2.push(callWithAsyncErrorHandling(fn[i2], instance, type, args)); + } + return values2; + } else if (false) { + warn$1( + `Invalid value type passed to callWithAsyncErrorHandling(): ${typeof fn}` + ); + } +} +function handleError(err, instance, type, throwInDev = true) { + const contextVNode = instance ? instance.vnode : null; + if (instance) { + let cur = instance.parent; + const exposedInstance = instance.proxy; + const errorInfo = false ? ErrorTypeStrings$1[type] : `https://vuejs.org/error-reference/#runtime-${type}`; + while (cur) { + const errorCapturedHooks = cur.ec; + if (errorCapturedHooks) { + for (let i2 = 0; i2 < errorCapturedHooks.length; i2++) { + if (errorCapturedHooks[i2](err, exposedInstance, errorInfo) === false) { + return; + } + } + } + cur = cur.parent; + } + const appErrorHandler = instance.appContext.config.errorHandler; + if (appErrorHandler) { + pauseTracking(); + callWithErrorHandling( + appErrorHandler, + null, + 10, + [err, exposedInstance, errorInfo] + ); + resetTracking(); + return; + } + } + logError(err, type, contextVNode, throwInDev); +} +function logError(err, type, contextVNode, throwInDev = true) { + if (false) { + const info = ErrorTypeStrings$1[type]; + if (contextVNode) { + pushWarningContext(contextVNode); + } + warn$1(`Unhandled error${info ? ` during execution of ${info}` : ``}`); + if (contextVNode) { + popWarningContext(); + } + if (throwInDev) { + throw err; + } else { + console.error(err); + } + } else { + console.error(err); + } +} +let isFlushing = false; +let isFlushPending = false; +const queue = []; +let flushIndex = 0; +const pendingPostFlushCbs = []; +let activePostFlushCbs = null; +let postFlushIndex = 0; +const resolvedPromise = /* @__PURE__ */ Promise.resolve(); +let currentFlushPromise = null; +const RECURSION_LIMIT = 100; +function nextTick(fn) { + const p2 = currentFlushPromise || resolvedPromise; + return fn ? p2.then(this ? fn.bind(this) : fn) : p2; +} +function findInsertionIndex(id2) { + let start2 = flushIndex + 1; + let end = queue.length; + while (start2 < end) { + const middle = start2 + end >>> 1; + const middleJob = queue[middle]; + const middleJobId = getId(middleJob); + if (middleJobId < id2 || middleJobId === id2 && middleJob.pre) { + start2 = middle + 1; + } else { + end = middle; + } + } + return start2; +} +function queueJob(job) { + if (!queue.length || !queue.includes( + job, + isFlushing && job.allowRecurse ? flushIndex + 1 : flushIndex + )) { + if (job.id == null) { + queue.push(job); + } else { + queue.splice(findInsertionIndex(job.id), 0, job); + } + queueFlush(); + } +} +function queueFlush() { + if (!isFlushing && !isFlushPending) { + isFlushPending = true; + currentFlushPromise = resolvedPromise.then(flushJobs); + } +} +function invalidateJob(job) { + const i2 = queue.indexOf(job); + if (i2 > flushIndex) { + queue.splice(i2, 1); + } +} +function queuePostFlushCb(cb) { + if (!isArray$3(cb)) { + if (!activePostFlushCbs || !activePostFlushCbs.includes( + cb, + cb.allowRecurse ? postFlushIndex + 1 : postFlushIndex + )) { + pendingPostFlushCbs.push(cb); + } + } else { + pendingPostFlushCbs.push(...cb); + } + queueFlush(); +} +function flushPreFlushCbs(instance, seen2, i2 = isFlushing ? flushIndex + 1 : 0) { + if (false) { + seen2 = seen2 || /* @__PURE__ */ new Map(); + } + for (; i2 < queue.length; i2++) { + const cb = queue[i2]; + if (cb && cb.pre) { + if (instance && cb.id !== instance.uid) { + continue; + } + if (false) { + continue; + } + queue.splice(i2, 1); + i2--; + cb(); + } + } +} +function flushPostFlushCbs(seen2) { + if (pendingPostFlushCbs.length) { + const deduped = [...new Set(pendingPostFlushCbs)].sort( + (a, b) => getId(a) - getId(b) + ); + pendingPostFlushCbs.length = 0; + if (activePostFlushCbs) { + activePostFlushCbs.push(...deduped); + return; + } + activePostFlushCbs = deduped; + if (false) { + seen2 = seen2 || /* @__PURE__ */ new Map(); + } + for (postFlushIndex = 0; postFlushIndex < activePostFlushCbs.length; postFlushIndex++) { + const cb = activePostFlushCbs[postFlushIndex]; + if (false) { + continue; + } + if (cb.active !== false) cb(); + } + activePostFlushCbs = null; + postFlushIndex = 0; + } +} +const getId = (job) => job.id == null ? Infinity : job.id; +const comparator = (a, b) => { + const diff = getId(a) - getId(b); + if (diff === 0) { + if (a.pre && !b.pre) return -1; + if (b.pre && !a.pre) return 1; + } + return diff; +}; +function flushJobs(seen2) { + isFlushPending = false; + isFlushing = true; + if (false) { + seen2 = seen2 || /* @__PURE__ */ new Map(); + } + queue.sort(comparator); + const check = false ? (job) => checkRecursiveUpdates(seen2, job) : NOOP; + try { + for (flushIndex = 0; flushIndex < queue.length; flushIndex++) { + const job = queue[flushIndex]; + if (job && job.active !== false) { + if (false) { + continue; + } + callWithErrorHandling(job, null, 14); + } + } + } finally { + flushIndex = 0; + queue.length = 0; + flushPostFlushCbs(seen2); + isFlushing = false; + currentFlushPromise = null; + if (queue.length || pendingPostFlushCbs.length) { + flushJobs(seen2); + } + } +} +function checkRecursiveUpdates(seen2, fn) { + if (!seen2.has(fn)) { + seen2.set(fn, 1); + } else { + const count = seen2.get(fn); + if (count > RECURSION_LIMIT) { + const instance = fn.ownerInstance; + const componentName = instance && getComponentName(instance.type); + handleError( + `Maximum recursive updates exceeded${componentName ? ` in component <${componentName}>` : ``}. This means you have a reactive effect that is mutating its own dependencies and thus recursively triggering itself. Possible sources include component template, render function, updated hook or watcher source function.`, + null, + 10 + ); + return true; + } else { + seen2.set(fn, count + 1); + } + } +} +let isHmrUpdating = false; +const hmrDirtyComponents = /* @__PURE__ */ new Set(); +if (false) { + getGlobalThis$1().__VUE_HMR_RUNTIME__ = { + createRecord: tryWrap(createRecord), + rerender: tryWrap(rerender), + reload: tryWrap(reload) + }; +} +const map = /* @__PURE__ */ new Map(); +function registerHMR(instance) { + const id2 = instance.type.__hmrId; + let record = map.get(id2); + if (!record) { + createRecord(id2, instance.type); + record = map.get(id2); + } + record.instances.add(instance); +} +function unregisterHMR(instance) { + map.get(instance.type.__hmrId).instances.delete(instance); +} +function createRecord(id2, initialDef) { + if (map.has(id2)) { + return false; + } + map.set(id2, { + initialDef: normalizeClassComponent(initialDef), + instances: /* @__PURE__ */ new Set() + }); + return true; +} +function normalizeClassComponent(component) { + return isClassComponent(component) ? component.__vccOpts : component; +} +function rerender(id2, newRender) { + const record = map.get(id2); + if (!record) { + return; + } + record.initialDef.render = newRender; + [...record.instances].forEach((instance) => { + if (newRender) { + instance.render = newRender; + normalizeClassComponent(instance.type).render = newRender; + } + instance.renderCache = []; + isHmrUpdating = true; + instance.effect.dirty = true; + instance.update(); + isHmrUpdating = false; + }); +} +function reload(id2, newComp) { + const record = map.get(id2); + if (!record) return; + newComp = normalizeClassComponent(newComp); + updateComponentDef(record.initialDef, newComp); + const instances = [...record.instances]; + for (const instance of instances) { + const oldComp = normalizeClassComponent(instance.type); + if (!hmrDirtyComponents.has(oldComp)) { + if (oldComp !== record.initialDef) { + updateComponentDef(oldComp, newComp); + } + hmrDirtyComponents.add(oldComp); + } + instance.appContext.propsCache.delete(instance.type); + instance.appContext.emitsCache.delete(instance.type); + instance.appContext.optionsCache.delete(instance.type); + if (instance.ceReload) { + hmrDirtyComponents.add(oldComp); + instance.ceReload(newComp.styles); + hmrDirtyComponents.delete(oldComp); + } else if (instance.parent) { + instance.parent.effect.dirty = true; + queueJob(() => { + instance.parent.update(); + hmrDirtyComponents.delete(oldComp); + }); + } else if (instance.appContext.reload) { + instance.appContext.reload(); + } else if (typeof window !== "undefined") { + window.location.reload(); + } else { + console.warn( + "[HMR] Root or manually mounted instance modified. Full reload required." + ); + } + } + queuePostFlushCb(() => { + for (const instance of instances) { + hmrDirtyComponents.delete( + normalizeClassComponent(instance.type) + ); + } + }); +} +function updateComponentDef(oldComp, newComp) { + extend(oldComp, newComp); + for (const key in oldComp) { + if (key !== "__file" && !(key in newComp)) { + delete oldComp[key]; + } + } +} +function tryWrap(fn) { + return (id2, arg) => { + try { + return fn(id2, arg); + } catch (e) { + console.error(e); + console.warn( + `[HMR] Something went wrong during Vue component hot-reload. Full reload required.` + ); + } + }; +} +let devtools$1; +let buffer = []; +let devtoolsNotInstalled = false; +function emit$1(event2, ...args) { + if (devtools$1) { + devtools$1.emit(event2, ...args); + } else if (!devtoolsNotInstalled) { + buffer.push({ event: event2, args }); + } +} +function setDevtoolsHook$1(hook, target) { + var _a2, _b; + devtools$1 = hook; + if (devtools$1) { + devtools$1.enabled = true; + buffer.forEach(({ event: event2, args }) => devtools$1.emit(event2, ...args)); + buffer = []; + } else if ( + // handle late devtools injection - only do this if we are in an actual + // browser environment to avoid the timer handle stalling test runner exit + // (#4815) + typeof window !== "undefined" && // some envs mock window but not fully + window.HTMLElement && // also exclude jsdom + // eslint-disable-next-line no-restricted-syntax + !((_b = (_a2 = window.navigator) == null ? void 0 : _a2.userAgent) == null ? void 0 : _b.includes("jsdom")) + ) { + const replay = target.__VUE_DEVTOOLS_HOOK_REPLAY__ = target.__VUE_DEVTOOLS_HOOK_REPLAY__ || []; + replay.push((newHook) => { + setDevtoolsHook$1(newHook, target); + }); + setTimeout(() => { + if (!devtools$1) { + target.__VUE_DEVTOOLS_HOOK_REPLAY__ = null; + devtoolsNotInstalled = true; + buffer = []; + } + }, 3e3); + } else { + devtoolsNotInstalled = true; + buffer = []; + } +} +function devtoolsInitApp(app2, version2) { + emit$1("app:init", app2, version2, { + Fragment, + Text, + Comment, + Static + }); +} +function devtoolsUnmountApp(app2) { + emit$1("app:unmount", app2); +} +const devtoolsComponentAdded = /* @__PURE__ */ createDevtoolsComponentHook( + "component:added" + /* COMPONENT_ADDED */ +); +const devtoolsComponentUpdated = /* @__PURE__ */ createDevtoolsComponentHook( + "component:updated" + /* COMPONENT_UPDATED */ +); +const _devtoolsComponentRemoved = /* @__PURE__ */ createDevtoolsComponentHook( + "component:removed" + /* COMPONENT_REMOVED */ +); +const devtoolsComponentRemoved = (component) => { + if (devtools$1 && typeof devtools$1.cleanupBuffer === "function" && // remove the component if it wasn't buffered + !devtools$1.cleanupBuffer(component)) { + _devtoolsComponentRemoved(component); + } +}; +/*! #__NO_SIDE_EFFECTS__ */ +// @__NO_SIDE_EFFECTS__ +function createDevtoolsComponentHook(hook) { + return (component) => { + emit$1( + hook, + component.appContext.app, + component.uid, + component.parent ? component.parent.uid : void 0, + component + ); + }; +} +const devtoolsPerfStart = /* @__PURE__ */ createDevtoolsPerformanceHook( + "perf:start" + /* PERFORMANCE_START */ +); +const devtoolsPerfEnd = /* @__PURE__ */ createDevtoolsPerformanceHook( + "perf:end" + /* PERFORMANCE_END */ +); +function createDevtoolsPerformanceHook(hook) { + return (component, type, time) => { + emit$1(hook, component.appContext.app, component.uid, component, type, time); + }; +} +function devtoolsComponentEmit(component, event2, params) { + emit$1( + "component:emit", + component.appContext.app, + component, + event2, + params + ); +} +function emit(instance, event2, ...rawArgs) { + if (instance.isUnmounted) return; + const props = instance.vnode.props || EMPTY_OBJ; + if (false) { + const { + emitsOptions, + propsOptions: [propsOptions] + } = instance; + if (emitsOptions) { + if (!(event2 in emitsOptions) && true) { + if (!propsOptions || !(toHandlerKey(event2) in propsOptions)) { + warn$1( + `Component emitted event "${event2}" but it is neither declared in the emits option nor as an "${toHandlerKey(event2)}" prop.` + ); + } + } else { + const validator2 = emitsOptions[event2]; + if (isFunction$3(validator2)) { + const isValid2 = validator2(...rawArgs); + if (!isValid2) { + warn$1( + `Invalid event arguments: event validation failed for event "${event2}".` + ); + } + } + } + } + } + let args = rawArgs; + const isModelListener2 = event2.startsWith("update:"); + const modelArg = isModelListener2 && event2.slice(7); + if (modelArg && modelArg in props) { + const modifiersKey = `${modelArg === "modelValue" ? "model" : modelArg}Modifiers`; + const { number: number2, trim } = props[modifiersKey] || EMPTY_OBJ; + if (trim) { + args = rawArgs.map((a) => isString$4(a) ? a.trim() : a); + } + if (number2) { + args = rawArgs.map(looseToNumber); + } + } + if (false) { + devtoolsComponentEmit(instance, event2, args); + } + if (false) { + const lowerCaseEvent = event2.toLowerCase(); + if (lowerCaseEvent !== event2 && props[toHandlerKey(lowerCaseEvent)]) { + warn$1( + `Event "${lowerCaseEvent}" is emitted in component ${formatComponentName( + instance, + instance.type + )} but the handler is registered for "${event2}". Note that HTML attributes are case-insensitive and you cannot use v-on to listen to camelCase events when using in-DOM templates. You should probably use "${hyphenate( + event2 + )}" instead of "${event2}".` + ); + } + } + let handlerName; + let handler8 = props[handlerName = toHandlerKey(event2)] || // also try camelCase event handler (#2249) + props[handlerName = toHandlerKey(camelize(event2))]; + if (!handler8 && isModelListener2) { + handler8 = props[handlerName = toHandlerKey(hyphenate(event2))]; + } + if (handler8) { + callWithAsyncErrorHandling( + handler8, + instance, + 6, + args + ); + } + const onceHandler = props[handlerName + `Once`]; + if (onceHandler) { + if (!instance.emitted) { + instance.emitted = {}; + } else if (instance.emitted[handlerName]) { + return; + } + instance.emitted[handlerName] = true; + callWithAsyncErrorHandling( + onceHandler, + instance, + 6, + args + ); + } +} +function normalizeEmitsOptions(comp, appContext, asMixin = false) { + const cache2 = appContext.emitsCache; + const cached = cache2.get(comp); + if (cached !== void 0) { + return cached; + } + const raw = comp.emits; + let normalized = {}; + let hasExtends = false; + if (!isFunction$3(comp)) { + const extendEmits = (raw2) => { + const normalizedFromExtend = normalizeEmitsOptions(raw2, appContext, true); + if (normalizedFromExtend) { + hasExtends = true; + extend(normalized, normalizedFromExtend); + } + }; + if (!asMixin && appContext.mixins.length) { + appContext.mixins.forEach(extendEmits); + } + if (comp.extends) { + extendEmits(comp.extends); + } + if (comp.mixins) { + comp.mixins.forEach(extendEmits); + } + } + if (!raw && !hasExtends) { + if (isObject$4(comp)) { + cache2.set(comp, null); + } + return null; + } + if (isArray$3(raw)) { + raw.forEach((key) => normalized[key] = null); + } else { + extend(normalized, raw); + } + if (isObject$4(comp)) { + cache2.set(comp, normalized); + } + return normalized; +} +function isEmitListener(options3, key) { + if (!options3 || !isOn(key)) { + return false; + } + key = key.slice(2).replace(/Once$/, ""); + return hasOwn$2(options3, key[0].toLowerCase() + key.slice(1)) || hasOwn$2(options3, hyphenate(key)) || hasOwn$2(options3, key); +} +let currentRenderingInstance = null; +let currentScopeId = null; +function setCurrentRenderingInstance(instance) { + const prev2 = currentRenderingInstance; + currentRenderingInstance = instance; + currentScopeId = instance && instance.type.__scopeId || null; + return prev2; +} +function pushScopeId(id2) { + currentScopeId = id2; +} +function popScopeId() { + currentScopeId = null; +} +const withScopeId = (_id2) => withCtx; +function withCtx(fn, ctx = currentRenderingInstance, isNonScopedSlot) { + if (!ctx) return fn; + if (fn._n) { + return fn; + } + const renderFnWithContext = (...args) => { + if (renderFnWithContext._d) { + setBlockTracking(-1); + } + const prevInstance = setCurrentRenderingInstance(ctx); + let res; + try { + res = fn(...args); + } finally { + setCurrentRenderingInstance(prevInstance); + if (renderFnWithContext._d) { + setBlockTracking(1); + } + } + if (false) { + devtoolsComponentUpdated(ctx); + } + return res; + }; + renderFnWithContext._n = true; + renderFnWithContext._c = true; + renderFnWithContext._d = true; + return renderFnWithContext; +} +let accessedAttrs = false; +function markAttrsAccessed() { + accessedAttrs = true; +} +function renderComponentRoot(instance) { + const { + type: Component, + vnode, + proxy, + withProxy, + propsOptions: [propsOptions], + slots, + attrs: attrs3, + emit: emit2, + render: render3, + renderCache, + props, + data: data28, + setupState, + ctx, + inheritAttrs + } = instance; + const prev2 = setCurrentRenderingInstance(instance); + let result; + let fallthroughAttrs; + if (false) { + accessedAttrs = false; + } + try { + if (vnode.shapeFlag & 4) { + const proxyToUse = withProxy || proxy; + const thisProxy = false ? new Proxy(proxyToUse, { + get(target, key, receiver) { + warn$1( + `Property '${String( + key + )}' was accessed via 'this'. Avoid using 'this' in templates.` + ); + return Reflect.get(target, key, receiver); + } + }) : proxyToUse; + result = normalizeVNode( + render3.call( + thisProxy, + proxyToUse, + renderCache, + false ? shallowReadonly(props) : props, + setupState, + data28, + ctx + ) + ); + fallthroughAttrs = attrs3; + } else { + const render22 = Component; + if (false) { + markAttrsAccessed(); + } + result = normalizeVNode( + render22.length > 1 ? render22( + false ? shallowReadonly(props) : props, + false ? { + get attrs() { + markAttrsAccessed(); + return shallowReadonly(attrs3); + }, + slots, + emit: emit2 + } : { attrs: attrs3, slots, emit: emit2 } + ) : render22( + false ? shallowReadonly(props) : props, + null + ) + ); + fallthroughAttrs = Component.props ? attrs3 : getFunctionalFallthrough(attrs3); + } + } catch (err) { + blockStack.length = 0; + handleError(err, instance, 1); + result = createVNode(Comment); + } + let root27 = result; + let setRoot = void 0; + if (false) { + [root27, setRoot] = getChildRoot(result); + } + if (fallthroughAttrs && inheritAttrs !== false) { + const keys = Object.keys(fallthroughAttrs); + const { shapeFlag } = root27; + if (keys.length) { + if (shapeFlag & (1 | 6)) { + if (propsOptions && keys.some(isModelListener)) { + fallthroughAttrs = filterModelListeners( + fallthroughAttrs, + propsOptions + ); + } + root27 = cloneVNode(root27, fallthroughAttrs, false, true); + } else if (false) { + const allAttrs = Object.keys(attrs3); + const eventAttrs = []; + const extraAttrs = []; + for (let i2 = 0, l = allAttrs.length; i2 < l; i2++) { + const key = allAttrs[i2]; + if (isOn(key)) { + if (!isModelListener(key)) { + eventAttrs.push(key[2].toLowerCase() + key.slice(3)); + } + } else { + extraAttrs.push(key); + } + } + if (extraAttrs.length) { + warn$1( + `Extraneous non-props attributes (${extraAttrs.join(", ")}) were passed to component but could not be automatically inherited because component renders fragment or text root nodes.` + ); + } + if (eventAttrs.length) { + warn$1( + `Extraneous non-emits event listeners (${eventAttrs.join(", ")}) were passed to component but could not be automatically inherited because component renders fragment or text root nodes. If the listener is intended to be a component custom event listener only, declare it using the "emits" option.` + ); + } + } + } + } + if (vnode.dirs) { + if (false) { + warn$1( + `Runtime directive used on component with non-element root node. The directives will not function as intended.` + ); + } + root27 = cloneVNode(root27, null, false, true); + root27.dirs = root27.dirs ? root27.dirs.concat(vnode.dirs) : vnode.dirs; + } + if (vnode.transition) { + if (false) { + warn$1( + `Component inside renders non-element root node that cannot be animated.` + ); + } + root27.transition = vnode.transition; + } + if (false) { + setRoot(root27); + } else { + result = root27; + } + setCurrentRenderingInstance(prev2); + return result; +} +const getChildRoot = (vnode) => { + const rawChildren = vnode.children; + const dynamicChildren = vnode.dynamicChildren; + const childRoot = filterSingleRoot(rawChildren, false); + if (!childRoot) { + return [vnode, void 0]; + } else if (false) { + return getChildRoot(childRoot); + } + const index2 = rawChildren.indexOf(childRoot); + const dynamicIndex = dynamicChildren ? dynamicChildren.indexOf(childRoot) : -1; + const setRoot = (updatedRoot) => { + rawChildren[index2] = updatedRoot; + if (dynamicChildren) { + if (dynamicIndex > -1) { + dynamicChildren[dynamicIndex] = updatedRoot; + } else if (updatedRoot.patchFlag > 0) { + vnode.dynamicChildren = [...dynamicChildren, updatedRoot]; + } + } + }; + return [normalizeVNode(childRoot), setRoot]; +}; +function filterSingleRoot(children, recurse = true) { + let singleRoot; + for (let i2 = 0; i2 < children.length; i2++) { + const child = children[i2]; + if (isVNode$1(child)) { + if (child.type !== Comment || child.children === "v-if") { + if (singleRoot) { + return; + } else { + singleRoot = child; + if (false) { + return filterSingleRoot(singleRoot.children); + } + } + } + } else { + return; + } + } + return singleRoot; +} +const getFunctionalFallthrough = (attrs3) => { + let res; + for (const key in attrs3) { + if (key === "class" || key === "style" || isOn(key)) { + (res || (res = {}))[key] = attrs3[key]; + } + } + return res; +}; +const filterModelListeners = (attrs3, props) => { + const res = {}; + for (const key in attrs3) { + if (!isModelListener(key) || !(key.slice(9) in props)) { + res[key] = attrs3[key]; + } + } + return res; +}; +const isElementRoot = (vnode) => { + return vnode.shapeFlag & (6 | 1) || vnode.type === Comment; +}; +function shouldUpdateComponent(prevVNode, nextVNode, optimized) { + const { props: prevProps, children: prevChildren, component } = prevVNode; + const { props: nextProps, children: nextChildren, patchFlag } = nextVNode; + const emits = component.emitsOptions; + if (false) { + return true; + } + if (nextVNode.dirs || nextVNode.transition) { + return true; + } + if (optimized && patchFlag >= 0) { + if (patchFlag & 1024) { + return true; + } + if (patchFlag & 16) { + if (!prevProps) { + return !!nextProps; + } + return hasPropsChanged(prevProps, nextProps, emits); + } else if (patchFlag & 8) { + const dynamicProps = nextVNode.dynamicProps; + for (let i2 = 0; i2 < dynamicProps.length; i2++) { + const key = dynamicProps[i2]; + if (nextProps[key] !== prevProps[key] && !isEmitListener(emits, key)) { + return true; + } + } + } + } else { + if (prevChildren || nextChildren) { + if (!nextChildren || !nextChildren.$stable) { + return true; + } + } + if (prevProps === nextProps) { + return false; + } + if (!prevProps) { + return !!nextProps; + } + if (!nextProps) { + return true; + } + return hasPropsChanged(prevProps, nextProps, emits); + } + return false; +} +function hasPropsChanged(prevProps, nextProps, emitsOptions) { + const nextKeys = Object.keys(nextProps); + if (nextKeys.length !== Object.keys(prevProps).length) { + return true; + } + for (let i2 = 0; i2 < nextKeys.length; i2++) { + const key = nextKeys[i2]; + if (nextProps[key] !== prevProps[key] && !isEmitListener(emitsOptions, key)) { + return true; + } + } + return false; +} +function updateHOCHostEl({ vnode, parent }, el) { + while (parent) { + const root27 = parent.subTree; + if (root27.suspense && root27.suspense.activeBranch === vnode) { + root27.el = vnode.el; + } + if (root27 === vnode) { + (vnode = parent.vnode).el = el; + parent = parent.parent; + } else { + break; + } + } +} +const COMPONENTS = "components"; +const DIRECTIVES = "directives"; +function resolveComponent(name, maybeSelfReference) { + return resolveAsset(COMPONENTS, name, true, maybeSelfReference) || name; +} +const NULL_DYNAMIC_COMPONENT = Symbol.for("v-ndc"); +function resolveDynamicComponent(component) { + if (isString$4(component)) { + return resolveAsset(COMPONENTS, component, false) || component; + } else { + return component || NULL_DYNAMIC_COMPONENT; + } +} +function resolveDirective(name) { + return resolveAsset(DIRECTIVES, name); +} +function resolveAsset(type, name, warnMissing = true, maybeSelfReference = false) { + const instance = currentRenderingInstance || currentInstance; + if (instance) { + const Component = instance.type; + if (type === COMPONENTS) { + const selfName = getComponentName( + Component, + false + ); + if (selfName && (selfName === name || selfName === camelize(name) || selfName === capitalize$1(camelize(name)))) { + return Component; + } + } + const res = ( + // local registration + // check instance[type] first which is resolved for options API + resolve$1(instance[type] || Component[type], name) || // global registration + resolve$1(instance.appContext[type], name) + ); + if (!res && maybeSelfReference) { + return Component; + } + if (false) { + const extra = type === COMPONENTS ? ` +If this is a native custom element, make sure to exclude it from component resolution via compilerOptions.isCustomElement.` : ``; + warn$1(`Failed to resolve ${type.slice(0, -1)}: ${name}${extra}`); + } + return res; + } else if (false) { + warn$1( + `resolve${capitalize$1(type.slice(0, -1))} can only be used in render() or setup().` + ); + } +} +function resolve$1(registry, name) { + return registry && (registry[name] || registry[camelize(name)] || registry[capitalize$1(camelize(name))]); +} +const isSuspense = (type) => type.__isSuspense; +let suspenseId = 0; +const SuspenseImpl = { + name: "Suspense", + // In order to make Suspense tree-shakable, we need to avoid importing it + // directly in the renderer. The renderer checks for the __isSuspense flag + // on a vnode's type and calls the `process` method, passing in renderer + // internals. + __isSuspense: true, + process(n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, rendererInternals) { + if (n1 == null) { + mountSuspense( + n2, + container, + anchor, + parentComponent, + parentSuspense, + namespace, + slotScopeIds, + optimized, + rendererInternals + ); + } else { + if (parentSuspense && parentSuspense.deps > 0 && !n1.suspense.isInFallback) { + n2.suspense = n1.suspense; + n2.suspense.vnode = n2; + n2.el = n1.el; + return; + } + patchSuspense( + n1, + n2, + container, + anchor, + parentComponent, + namespace, + slotScopeIds, + optimized, + rendererInternals + ); + } + }, + hydrate: hydrateSuspense, + normalize: normalizeSuspenseChildren +}; +const Suspense = SuspenseImpl; +function triggerEvent(vnode, name) { + const eventListener = vnode.props && vnode.props[name]; + if (isFunction$3(eventListener)) { + eventListener(); + } +} +function mountSuspense(vnode, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, rendererInternals) { + const { + p: patch, + o: { createElement: createElement2 } + } = rendererInternals; + const hiddenContainer = createElement2("div"); + const suspense = vnode.suspense = createSuspenseBoundary( + vnode, + parentSuspense, + parentComponent, + container, + hiddenContainer, + anchor, + namespace, + slotScopeIds, + optimized, + rendererInternals + ); + patch( + null, + suspense.pendingBranch = vnode.ssContent, + hiddenContainer, + null, + parentComponent, + suspense, + namespace, + slotScopeIds + ); + if (suspense.deps > 0) { + triggerEvent(vnode, "onPending"); + triggerEvent(vnode, "onFallback"); + patch( + null, + vnode.ssFallback, + container, + anchor, + parentComponent, + null, + // fallback tree will not have suspense context + namespace, + slotScopeIds + ); + setActiveBranch(suspense, vnode.ssFallback); + } else { + suspense.resolve(false, true); + } +} +function patchSuspense(n1, n2, container, anchor, parentComponent, namespace, slotScopeIds, optimized, { p: patch, um: unmount, o: { createElement: createElement2 } }) { + const suspense = n2.suspense = n1.suspense; + suspense.vnode = n2; + n2.el = n1.el; + const newBranch = n2.ssContent; + const newFallback = n2.ssFallback; + const { activeBranch, pendingBranch, isInFallback, isHydrating } = suspense; + if (pendingBranch) { + suspense.pendingBranch = newBranch; + if (isSameVNodeType(newBranch, pendingBranch)) { + patch( + pendingBranch, + newBranch, + suspense.hiddenContainer, + null, + parentComponent, + suspense, + namespace, + slotScopeIds, + optimized + ); + if (suspense.deps <= 0) { + suspense.resolve(); + } else if (isInFallback) { + if (!isHydrating) { + patch( + activeBranch, + newFallback, + container, + anchor, + parentComponent, + null, + // fallback tree will not have suspense context + namespace, + slotScopeIds, + optimized + ); + setActiveBranch(suspense, newFallback); + } + } + } else { + suspense.pendingId = suspenseId++; + if (isHydrating) { + suspense.isHydrating = false; + suspense.activeBranch = pendingBranch; + } else { + unmount(pendingBranch, parentComponent, suspense); + } + suspense.deps = 0; + suspense.effects.length = 0; + suspense.hiddenContainer = createElement2("div"); + if (isInFallback) { + patch( + null, + newBranch, + suspense.hiddenContainer, + null, + parentComponent, + suspense, + namespace, + slotScopeIds, + optimized + ); + if (suspense.deps <= 0) { + suspense.resolve(); + } else { + patch( + activeBranch, + newFallback, + container, + anchor, + parentComponent, + null, + // fallback tree will not have suspense context + namespace, + slotScopeIds, + optimized + ); + setActiveBranch(suspense, newFallback); + } + } else if (activeBranch && isSameVNodeType(newBranch, activeBranch)) { + patch( + activeBranch, + newBranch, + container, + anchor, + parentComponent, + suspense, + namespace, + slotScopeIds, + optimized + ); + suspense.resolve(true); + } else { + patch( + null, + newBranch, + suspense.hiddenContainer, + null, + parentComponent, + suspense, + namespace, + slotScopeIds, + optimized + ); + if (suspense.deps <= 0) { + suspense.resolve(); + } + } + } + } else { + if (activeBranch && isSameVNodeType(newBranch, activeBranch)) { + patch( + activeBranch, + newBranch, + container, + anchor, + parentComponent, + suspense, + namespace, + slotScopeIds, + optimized + ); + setActiveBranch(suspense, newBranch); + } else { + triggerEvent(n2, "onPending"); + suspense.pendingBranch = newBranch; + if (newBranch.shapeFlag & 512) { + suspense.pendingId = newBranch.component.suspenseId; + } else { + suspense.pendingId = suspenseId++; + } + patch( + null, + newBranch, + suspense.hiddenContainer, + null, + parentComponent, + suspense, + namespace, + slotScopeIds, + optimized + ); + if (suspense.deps <= 0) { + suspense.resolve(); + } else { + const { timeout, pendingId } = suspense; + if (timeout > 0) { + setTimeout(() => { + if (suspense.pendingId === pendingId) { + suspense.fallback(newFallback); + } + }, timeout); + } else if (timeout === 0) { + suspense.fallback(newFallback); + } + } + } + } +} +let hasWarned$1 = false; +function createSuspenseBoundary(vnode, parentSuspense, parentComponent, container, hiddenContainer, anchor, namespace, slotScopeIds, optimized, rendererInternals, isHydrating = false) { + if (false) { + hasWarned$1 = true; + console[console.info ? "info" : "log"]( + ` is an experimental feature and its API will likely change.` + ); + } + const { + p: patch, + m: move, + um: unmount, + n: next2, + o: { parentNode, remove: remove22 } + } = rendererInternals; + let parentSuspenseId; + const isSuspensible = isVNodeSuspensible(vnode); + if (isSuspensible) { + if (parentSuspense && parentSuspense.pendingBranch) { + parentSuspenseId = parentSuspense.pendingId; + parentSuspense.deps++; + } + } + const timeout = vnode.props ? toNumber(vnode.props.timeout) : void 0; + if (false) { + assertNumber(timeout, `Suspense timeout`); + } + const initialAnchor = anchor; + const suspense = { + vnode, + parent: parentSuspense, + parentComponent, + namespace, + container, + hiddenContainer, + deps: 0, + pendingId: suspenseId++, + timeout: typeof timeout === "number" ? timeout : -1, + activeBranch: null, + pendingBranch: null, + isInFallback: !isHydrating, + isHydrating, + isUnmounted: false, + effects: [], + resolve(resume = false, sync = false) { + if (false) { + if (!resume && !suspense.pendingBranch) { + throw new Error( + `suspense.resolve() is called without a pending branch.` + ); + } + if (suspense.isUnmounted) { + throw new Error( + `suspense.resolve() is called on an already unmounted suspense boundary.` + ); + } + } + const { + vnode: vnode2, + activeBranch, + pendingBranch, + pendingId, + effects, + parentComponent: parentComponent2, + container: container2 + } = suspense; + let delayEnter = false; + if (suspense.isHydrating) { + suspense.isHydrating = false; + } else if (!resume) { + delayEnter = activeBranch && pendingBranch.transition && pendingBranch.transition.mode === "out-in"; + if (delayEnter) { + activeBranch.transition.afterLeave = () => { + if (pendingId === suspense.pendingId) { + move( + pendingBranch, + container2, + anchor === initialAnchor ? next2(activeBranch) : anchor, + 0 + ); + queuePostFlushCb(effects); + } + }; + } + if (activeBranch) { + if (parentNode(activeBranch.el) !== suspense.hiddenContainer) { + anchor = next2(activeBranch); + } + unmount(activeBranch, parentComponent2, suspense, true); + } + if (!delayEnter) { + move(pendingBranch, container2, anchor, 0); + } + } + setActiveBranch(suspense, pendingBranch); + suspense.pendingBranch = null; + suspense.isInFallback = false; + let parent = suspense.parent; + let hasUnresolvedAncestor = false; + while (parent) { + if (parent.pendingBranch) { + parent.effects.push(...effects); + hasUnresolvedAncestor = true; + break; + } + parent = parent.parent; + } + if (!hasUnresolvedAncestor && !delayEnter) { + queuePostFlushCb(effects); + } + suspense.effects = []; + if (isSuspensible) { + if (parentSuspense && parentSuspense.pendingBranch && parentSuspenseId === parentSuspense.pendingId) { + parentSuspense.deps--; + if (parentSuspense.deps === 0 && !sync) { + parentSuspense.resolve(); + } + } + } + triggerEvent(vnode2, "onResolve"); + }, + fallback(fallbackVNode) { + if (!suspense.pendingBranch) { + return; + } + const { vnode: vnode2, activeBranch, parentComponent: parentComponent2, container: container2, namespace: namespace2 } = suspense; + triggerEvent(vnode2, "onFallback"); + const anchor2 = next2(activeBranch); + const mountFallback = () => { + if (!suspense.isInFallback) { + return; + } + patch( + null, + fallbackVNode, + container2, + anchor2, + parentComponent2, + null, + // fallback tree will not have suspense context + namespace2, + slotScopeIds, + optimized + ); + setActiveBranch(suspense, fallbackVNode); + }; + const delayEnter = fallbackVNode.transition && fallbackVNode.transition.mode === "out-in"; + if (delayEnter) { + activeBranch.transition.afterLeave = mountFallback; + } + suspense.isInFallback = true; + unmount( + activeBranch, + parentComponent2, + null, + // no suspense so unmount hooks fire now + true + // shouldRemove + ); + if (!delayEnter) { + mountFallback(); + } + }, + move(container2, anchor2, type) { + suspense.activeBranch && move(suspense.activeBranch, container2, anchor2, type); + suspense.container = container2; + }, + next() { + return suspense.activeBranch && next2(suspense.activeBranch); + }, + registerDep(instance, setupRenderEffect, optimized2) { + const isInPendingSuspense = !!suspense.pendingBranch; + if (isInPendingSuspense) { + suspense.deps++; + } + const hydratedEl = instance.vnode.el; + instance.asyncDep.catch((err) => { + handleError(err, instance, 0); + }).then((asyncSetupResult) => { + if (instance.isUnmounted || suspense.isUnmounted || suspense.pendingId !== instance.suspenseId) { + return; + } + instance.asyncResolved = true; + const { vnode: vnode2 } = instance; + if (false) { + pushWarningContext(vnode2); + } + handleSetupResult(instance, asyncSetupResult, false); + if (hydratedEl) { + vnode2.el = hydratedEl; + } + const placeholder = !hydratedEl && instance.subTree.el; + setupRenderEffect( + instance, + vnode2, + // component may have been moved before resolve. + // if this is not a hydration, instance.subTree will be the comment + // placeholder. + parentNode(hydratedEl || instance.subTree.el), + // anchor will not be used if this is hydration, so only need to + // consider the comment placeholder case. + hydratedEl ? null : next2(instance.subTree), + suspense, + namespace, + optimized2 + ); + if (placeholder) { + remove22(placeholder); + } + updateHOCHostEl(instance, vnode2.el); + if (false) { + popWarningContext(); + } + if (isInPendingSuspense && --suspense.deps === 0) { + suspense.resolve(); + } + }); + }, + unmount(parentSuspense2, doRemove) { + suspense.isUnmounted = true; + if (suspense.activeBranch) { + unmount( + suspense.activeBranch, + parentComponent, + parentSuspense2, + doRemove + ); + } + if (suspense.pendingBranch) { + unmount( + suspense.pendingBranch, + parentComponent, + parentSuspense2, + doRemove + ); + } + } + }; + return suspense; +} +function hydrateSuspense(node3, vnode, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, rendererInternals, hydrateNode) { + const suspense = vnode.suspense = createSuspenseBoundary( + vnode, + parentSuspense, + parentComponent, + node3.parentNode, + // eslint-disable-next-line no-restricted-globals + document.createElement("div"), + null, + namespace, + slotScopeIds, + optimized, + rendererInternals, + true + ); + const result = hydrateNode( + node3, + suspense.pendingBranch = vnode.ssContent, + parentComponent, + suspense, + slotScopeIds, + optimized + ); + if (suspense.deps === 0) { + suspense.resolve(false, true); + } + return result; +} +function normalizeSuspenseChildren(vnode) { + const { shapeFlag, children } = vnode; + const isSlotChildren = shapeFlag & 32; + vnode.ssContent = normalizeSuspenseSlot( + isSlotChildren ? children.default : children + ); + vnode.ssFallback = isSlotChildren ? normalizeSuspenseSlot(children.fallback) : createVNode(Comment); +} +function normalizeSuspenseSlot(s) { + let block2; + if (isFunction$3(s)) { + const trackBlock = isBlockTreeEnabled && s._c; + if (trackBlock) { + s._d = false; + openBlock(); + } + s = s(); + if (trackBlock) { + s._d = true; + block2 = currentBlock; + closeBlock(); + } + } + if (isArray$3(s)) { + const singleChild = filterSingleRoot(s); + if (false) { + warn$1(` slots expect a single root node.`); + } + s = singleChild; + } + s = normalizeVNode(s); + if (block2 && !s.dynamicChildren) { + s.dynamicChildren = block2.filter((c) => c !== s); + } + return s; +} +function queueEffectWithSuspense(fn, suspense) { + if (suspense && suspense.pendingBranch) { + if (isArray$3(fn)) { + suspense.effects.push(...fn); + } else { + suspense.effects.push(fn); + } + } else { + queuePostFlushCb(fn); + } +} +function setActiveBranch(suspense, branch) { + suspense.activeBranch = branch; + const { vnode, parentComponent } = suspense; + let el = branch.el; + while (!el && branch.component) { + branch = branch.component.subTree; + el = branch.el; + } + vnode.el = el; + if (parentComponent && parentComponent.subTree === vnode) { + parentComponent.vnode.el = el; + updateHOCHostEl(parentComponent, el); + } +} +function isVNodeSuspensible(vnode) { + const suspensible = vnode.props && vnode.props.suspensible; + return suspensible != null && suspensible !== false; +} +function injectHook(type, hook, target = currentInstance, prepend = false) { + if (target) { + const hooks = target[type] || (target[type] = []); + const wrappedHook = hook.__weh || (hook.__weh = (...args) => { + pauseTracking(); + const reset = setCurrentInstance(target); + const res = callWithAsyncErrorHandling(hook, target, type, args); + reset(); + resetTracking(); + return res; + }); + if (prepend) { + hooks.unshift(wrappedHook); + } else { + hooks.push(wrappedHook); + } + return wrappedHook; + } else if (false) { + const apiName = toHandlerKey(ErrorTypeStrings$1[type].replace(/ hook$/, "")); + warn$1( + `${apiName} is called when there is no active component instance to be associated with. Lifecycle injection APIs can only be used during execution of setup(). If you are using async setup(), make sure to register lifecycle hooks before the first await statement.` + ); + } +} +const createHook = (lifecycle2) => (hook, target = currentInstance) => { + if (!isInSSRComponentSetup || lifecycle2 === "sp") { + injectHook(lifecycle2, (...args) => hook(...args), target); + } +}; +const onBeforeMount = createHook("bm"); +const onMounted = createHook("m"); +const onBeforeUpdate = createHook("bu"); +const onUpdated = createHook("u"); +const onBeforeUnmount = createHook("bum"); +const onUnmounted = createHook("um"); +const onServerPrefetch = createHook("sp"); +const onRenderTriggered = createHook( + "rtg" +); +const onRenderTracked = createHook( + "rtc" +); +function onErrorCaptured(hook, target = currentInstance) { + injectHook("ec", hook, target); +} +function validateDirectiveName(name) { + if (isBuiltInDirective(name)) { + warn$1("Do not use built-in directive ids as custom directive id: " + name); + } +} +function withDirectives(vnode, directives) { + if (currentRenderingInstance === null) { + return vnode; + } + const instance = getComponentPublicInstance(currentRenderingInstance); + const bindings = vnode.dirs || (vnode.dirs = []); + for (let i2 = 0; i2 < directives.length; i2++) { + let [dir, value3, arg, modifiers = EMPTY_OBJ] = directives[i2]; + if (dir) { + if (isFunction$3(dir)) { + dir = { + mounted: dir, + updated: dir + }; + } + if (dir.deep) { + traverse(value3); + } + bindings.push({ + dir, + instance, + value: value3, + oldValue: void 0, + arg, + modifiers + }); + } + } + return vnode; +} +function invokeDirectiveHook(vnode, prevVNode, instance, name) { + const bindings = vnode.dirs; + const oldBindings = prevVNode && prevVNode.dirs; + for (let i2 = 0; i2 < bindings.length; i2++) { + const binding = bindings[i2]; + if (oldBindings) { + binding.oldValue = oldBindings[i2].value; + } + let hook = binding.dir[name]; + if (hook) { + pauseTracking(); + callWithAsyncErrorHandling(hook, instance, 8, [ + vnode.el, + binding, + vnode, + prevVNode + ]); + resetTracking(); + } + } +} +function renderList(source, renderItem, cache2, index2) { + let ret; + const cached = cache2 && cache2[index2]; + if (isArray$3(source) || isString$4(source)) { + ret = new Array(source.length); + for (let i2 = 0, l = source.length; i2 < l; i2++) { + ret[i2] = renderItem(source[i2], i2, void 0, cached && cached[i2]); + } + } else if (typeof source === "number") { + if (false) { + warn$1(`The v-for range expect an integer value but got ${source}.`); + } + ret = new Array(source); + for (let i2 = 0; i2 < source; i2++) { + ret[i2] = renderItem(i2 + 1, i2, void 0, cached && cached[i2]); + } + } else if (isObject$4(source)) { + if (source[Symbol.iterator]) { + ret = Array.from( + source, + (item, i2) => renderItem(item, i2, void 0, cached && cached[i2]) + ); + } else { + const keys = Object.keys(source); + ret = new Array(keys.length); + for (let i2 = 0, l = keys.length; i2 < l; i2++) { + const key = keys[i2]; + ret[i2] = renderItem(source[key], key, i2, cached && cached[i2]); + } + } + } else { + ret = []; + } + if (cache2) { + cache2[index2] = ret; + } + return ret; +} +function createSlots(slots, dynamicSlots) { + for (let i2 = 0; i2 < dynamicSlots.length; i2++) { + const slot = dynamicSlots[i2]; + if (isArray$3(slot)) { + for (let j = 0; j < slot.length; j++) { + slots[slot[j].name] = slot[j].fn; + } + } else if (slot) { + slots[slot.name] = slot.key ? (...args) => { + const res = slot.fn(...args); + if (res) res.key = slot.key; + return res; + } : slot.fn; + } + } + return slots; +} +/*! #__NO_SIDE_EFFECTS__ */ +// @__NO_SIDE_EFFECTS__ +function defineComponent(options3, extraOptions) { + return isFunction$3(options3) ? ( + // #8326: extend call and options.name access are considered side-effects + // by Rollup, so we have to wrap it in a pure-annotated IIFE. + /* @__PURE__ */ (() => extend({ name: options3.name }, extraOptions, { setup: options3 }))() + ) : options3; +} +const isAsyncWrapper = (i2) => !!i2.type.__asyncLoader; +/*! #__NO_SIDE_EFFECTS__ */ +// @__NO_SIDE_EFFECTS__ +function defineAsyncComponent(source) { + if (isFunction$3(source)) { + source = { loader: source }; + } + const { + loader, + loadingComponent, + errorComponent, + delay = 200, + timeout, + // undefined = never times out + suspensible = true, + onError: userOnError + } = source; + let pendingRequest = null; + let resolvedComp; + let retries = 0; + const retry = () => { + retries++; + pendingRequest = null; + return load2(); + }; + const load2 = () => { + let thisRequest; + return pendingRequest || (thisRequest = pendingRequest = loader().catch((err) => { + err = err instanceof Error ? err : new Error(String(err)); + if (userOnError) { + return new Promise((resolve22, reject2) => { + const userRetry = () => resolve22(retry()); + const userFail = () => reject2(err); + userOnError(err, userRetry, userFail, retries + 1); + }); + } else { + throw err; + } + }).then((comp) => { + if (thisRequest !== pendingRequest && pendingRequest) { + return pendingRequest; + } + if (false) { + warn$1( + `Async component loader resolved to undefined. If you are using retry(), make sure to return its return value.` + ); + } + if (comp && (comp.__esModule || comp[Symbol.toStringTag] === "Module")) { + comp = comp.default; + } + if (false) { + throw new Error(`Invalid async component load result: ${comp}`); + } + resolvedComp = comp; + return comp; + })); + }; + return /* @__PURE__ */ defineComponent({ + name: "AsyncComponentWrapper", + __asyncLoader: load2, + get __asyncResolved() { + return resolvedComp; + }, + setup() { + const instance = currentInstance; + if (resolvedComp) { + return () => createInnerComp(resolvedComp, instance); + } + const onError = (err) => { + pendingRequest = null; + handleError( + err, + instance, + 13, + !errorComponent + ); + }; + if (suspensible && instance.suspense || isInSSRComponentSetup) { + return load2().then((comp) => { + return () => createInnerComp(comp, instance); + }).catch((err) => { + onError(err); + return () => errorComponent ? createVNode(errorComponent, { + error: err + }) : null; + }); + } + const loaded = ref(false); + const error = ref(); + const delayed = ref(!!delay); + if (delay) { + setTimeout(() => { + delayed.value = false; + }, delay); + } + if (timeout != null) { + setTimeout(() => { + if (!loaded.value && !error.value) { + const err = new Error( + `Async component timed out after ${timeout}ms.` + ); + onError(err); + error.value = err; + } + }, timeout); + } + load2().then(() => { + loaded.value = true; + if (instance.parent && isKeepAlive(instance.parent.vnode)) { + instance.parent.effect.dirty = true; + queueJob(instance.parent.update); + } + }).catch((err) => { + onError(err); + error.value = err; + }); + return () => { + if (loaded.value && resolvedComp) { + return createInnerComp(resolvedComp, instance); + } else if (error.value && errorComponent) { + return createVNode(errorComponent, { + error: error.value + }); + } else if (loadingComponent && !delayed.value) { + return createVNode(loadingComponent); + } + }; + } + }); +} +function createInnerComp(comp, parent) { + const { ref: ref22, props, children, ce } = parent.vnode; + const vnode = createVNode(comp, props, children); + vnode.ref = ref22; + vnode.ce = ce; + delete parent.vnode.ce; + return vnode; +} +function renderSlot(slots, name, props = {}, fallback, noSlotted) { + if (currentRenderingInstance.isCE || currentRenderingInstance.parent && isAsyncWrapper(currentRenderingInstance.parent) && currentRenderingInstance.parent.isCE) { + if (name !== "default") props.name = name; + return createVNode("slot", props, fallback && fallback()); + } + let slot = slots[name]; + if (false) { + warn$1( + `SSR-optimized slot function detected in a non-SSR-optimized render function. You need to mark this component with $dynamic-slots in the parent template.` + ); + slot = () => []; + } + if (slot && slot._c) { + slot._d = false; + } + openBlock(); + const validSlotContent = slot && ensureValidVNode(slot(props)); + const rendered = createBlock( + Fragment, + { + key: props.key || // slot content array of a dynamic conditional slot may have a branch + // key attached in the `createSlots` helper, respect that + validSlotContent && validSlotContent.key || `_${name}` + }, + validSlotContent || (fallback ? fallback() : []), + validSlotContent && slots._ === 1 ? 64 : -2 + ); + if (!noSlotted && rendered.scopeId) { + rendered.slotScopeIds = [rendered.scopeId + "-s"]; + } + if (slot && slot._c) { + slot._d = true; + } + return rendered; +} +function ensureValidVNode(vnodes) { + return vnodes.some((child) => { + if (!isVNode$1(child)) return true; + if (child.type === Comment) return false; + if (child.type === Fragment && !ensureValidVNode(child.children)) + return false; + return true; + }) ? vnodes : null; +} +function toHandlers(obj, preserveCaseIfNecessary) { + const ret = {}; + if (false) { + warn$1(`v-on with no argument expects an object value.`); + return ret; + } + for (const key in obj) { + ret[preserveCaseIfNecessary && /[A-Z]/.test(key) ? `on:${key}` : toHandlerKey(key)] = obj[key]; + } + return ret; +} +const getPublicInstance = (i2) => { + if (!i2) return null; + if (isStatefulComponent(i2)) return getComponentPublicInstance(i2); + return getPublicInstance(i2.parent); +}; +const publicPropertiesMap = ( + // Move PURE marker to new line to workaround compiler discarding it + // due to type annotation + /* @__PURE__ */ extend(/* @__PURE__ */ Object.create(null), { + $: (i2) => i2, + $el: (i2) => i2.vnode.el, + $data: (i2) => i2.data, + $props: (i2) => false ? shallowReadonly(i2.props) : i2.props, + $attrs: (i2) => false ? shallowReadonly(i2.attrs) : i2.attrs, + $slots: (i2) => false ? shallowReadonly(i2.slots) : i2.slots, + $refs: (i2) => false ? shallowReadonly(i2.refs) : i2.refs, + $parent: (i2) => getPublicInstance(i2.parent), + $root: (i2) => getPublicInstance(i2.root), + $emit: (i2) => i2.emit, + $options: (i2) => true ? resolveMergedOptions(i2) : i2.type, + $forceUpdate: (i2) => i2.f || (i2.f = () => { + i2.effect.dirty = true; + queueJob(i2.update); + }), + $nextTick: (i2) => i2.n || (i2.n = nextTick.bind(i2.proxy)), + $watch: (i2) => true ? instanceWatch.bind(i2) : NOOP + }) +); +const isReservedPrefix = (key) => key === "_" || key === "$"; +const hasSetupBinding = (state, key) => state !== EMPTY_OBJ && !state.__isScriptSetup && hasOwn$2(state, key); +const PublicInstanceProxyHandlers = { + get({ _: instance }, key) { + if (key === "__v_skip") { + return true; + } + const { ctx, setupState, data: data28, props, accessCache, type, appContext } = instance; + if (false) { + return true; + } + let normalizedProps; + if (key[0] !== "$") { + const n = accessCache[key]; + if (n !== void 0) { + switch (n) { + case 1: + return setupState[key]; + case 2: + return data28[key]; + case 4: + return ctx[key]; + case 3: + return props[key]; + } + } else if (hasSetupBinding(setupState, key)) { + accessCache[key] = 1; + return setupState[key]; + } else if (data28 !== EMPTY_OBJ && hasOwn$2(data28, key)) { + accessCache[key] = 2; + return data28[key]; + } else if ( + // only cache other properties when instance has declared (thus stable) + // props + (normalizedProps = instance.propsOptions[0]) && hasOwn$2(normalizedProps, key) + ) { + accessCache[key] = 3; + return props[key]; + } else if (ctx !== EMPTY_OBJ && hasOwn$2(ctx, key)) { + accessCache[key] = 4; + return ctx[key]; + } else if (shouldCacheAccess) { + accessCache[key] = 0; + } + } + const publicGetter = publicPropertiesMap[key]; + let cssModule, globalProperties; + if (publicGetter) { + if (key === "$attrs") { + track(instance.attrs, "get", ""); + } else if (false) { + track(instance, "get", key); + } + return publicGetter(instance); + } else if ( + // css module (injected by vue-loader) + (cssModule = type.__cssModules) && (cssModule = cssModule[key]) + ) { + return cssModule; + } else if (ctx !== EMPTY_OBJ && hasOwn$2(ctx, key)) { + accessCache[key] = 4; + return ctx[key]; + } else if ( + // global properties + globalProperties = appContext.config.globalProperties, hasOwn$2(globalProperties, key) + ) { + { + return globalProperties[key]; + } + } else if (false) { + if (data28 !== EMPTY_OBJ && isReservedPrefix(key[0]) && hasOwn$2(data28, key)) { + warn$1( + `Property ${JSON.stringify( + key + )} must be accessed via $data because it starts with a reserved character ("$" or "_") and is not proxied on the render context.` + ); + } else if (instance === currentRenderingInstance) { + warn$1( + `Property ${JSON.stringify(key)} was accessed during render but is not defined on instance.` + ); + } + } + }, + set({ _: instance }, key, value3) { + const { data: data28, setupState, ctx } = instance; + if (hasSetupBinding(setupState, key)) { + setupState[key] = value3; + return true; + } else if (false) { + warn$1(`Cannot mutate \r\n\r\n\r\n\r\n\r\n","var util;\n(function (util) {\n util.assertEqual = (val) => val;\n function assertIs(_arg) { }\n util.assertIs = assertIs;\n function assertNever(_x) {\n throw new Error();\n }\n util.assertNever = assertNever;\n util.arrayToEnum = (items) => {\n const obj = {};\n for (const item of items) {\n obj[item] = item;\n }\n return obj;\n };\n util.getValidEnumValues = (obj) => {\n const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== \"number\");\n const filtered = {};\n for (const k of validKeys) {\n filtered[k] = obj[k];\n }\n return util.objectValues(filtered);\n };\n util.objectValues = (obj) => {\n return util.objectKeys(obj).map(function (e) {\n return obj[e];\n });\n };\n util.objectKeys = typeof Object.keys === \"function\" // eslint-disable-line ban/ban\n ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban\n : (object) => {\n const keys = [];\n for (const key in object) {\n if (Object.prototype.hasOwnProperty.call(object, key)) {\n keys.push(key);\n }\n }\n return keys;\n };\n util.find = (arr, checker) => {\n for (const item of arr) {\n if (checker(item))\n return item;\n }\n return undefined;\n };\n util.isInteger = typeof Number.isInteger === \"function\"\n ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban\n : (val) => typeof val === \"number\" && isFinite(val) && Math.floor(val) === val;\n function joinValues(array, separator = \" | \") {\n return array\n .map((val) => (typeof val === \"string\" ? `'${val}'` : val))\n .join(separator);\n }\n util.joinValues = joinValues;\n util.jsonStringifyReplacer = (_, value) => {\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n return value;\n };\n})(util || (util = {}));\nvar objectUtil;\n(function (objectUtil) {\n objectUtil.mergeShapes = (first, second) => {\n return {\n ...first,\n ...second, // second overwrites first\n };\n };\n})(objectUtil || (objectUtil = {}));\nconst ZodParsedType = util.arrayToEnum([\n \"string\",\n \"nan\",\n \"number\",\n \"integer\",\n \"float\",\n \"boolean\",\n \"date\",\n \"bigint\",\n \"symbol\",\n \"function\",\n \"undefined\",\n \"null\",\n \"array\",\n \"object\",\n \"unknown\",\n \"promise\",\n \"void\",\n \"never\",\n \"map\",\n \"set\",\n]);\nconst getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return ZodParsedType.undefined;\n case \"string\":\n return ZodParsedType.string;\n case \"number\":\n return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;\n case \"boolean\":\n return ZodParsedType.boolean;\n case \"function\":\n return ZodParsedType.function;\n case \"bigint\":\n return ZodParsedType.bigint;\n case \"symbol\":\n return ZodParsedType.symbol;\n case \"object\":\n if (Array.isArray(data)) {\n return ZodParsedType.array;\n }\n if (data === null) {\n return ZodParsedType.null;\n }\n if (data.then &&\n typeof data.then === \"function\" &&\n data.catch &&\n typeof data.catch === \"function\") {\n return ZodParsedType.promise;\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return ZodParsedType.map;\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return ZodParsedType.set;\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return ZodParsedType.date;\n }\n return ZodParsedType.object;\n default:\n return ZodParsedType.unknown;\n }\n};\n\nconst ZodIssueCode = util.arrayToEnum([\n \"invalid_type\",\n \"invalid_literal\",\n \"custom\",\n \"invalid_union\",\n \"invalid_union_discriminator\",\n \"invalid_enum_value\",\n \"unrecognized_keys\",\n \"invalid_arguments\",\n \"invalid_return_type\",\n \"invalid_date\",\n \"invalid_string\",\n \"too_small\",\n \"too_big\",\n \"invalid_intersection_types\",\n \"not_multiple_of\",\n \"not_finite\",\n]);\nconst quotelessJson = (obj) => {\n const json = JSON.stringify(obj, null, 2);\n return json.replace(/\"([^\"]+)\":/g, \"$1:\");\n};\nclass ZodError extends Error {\n constructor(issues) {\n super();\n this.issues = [];\n this.addIssue = (sub) => {\n this.issues = [...this.issues, sub];\n };\n this.addIssues = (subs = []) => {\n this.issues = [...this.issues, ...subs];\n };\n const actualProto = new.target.prototype;\n if (Object.setPrototypeOf) {\n // eslint-disable-next-line ban/ban\n Object.setPrototypeOf(this, actualProto);\n }\n else {\n this.__proto__ = actualProto;\n }\n this.name = \"ZodError\";\n this.issues = issues;\n }\n get errors() {\n return this.issues;\n }\n format(_mapper) {\n const mapper = _mapper ||\n function (issue) {\n return issue.message;\n };\n const fieldErrors = { _errors: [] };\n const processError = (error) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\") {\n issue.unionErrors.map(processError);\n }\n else if (issue.code === \"invalid_return_type\") {\n processError(issue.returnTypeError);\n }\n else if (issue.code === \"invalid_arguments\") {\n processError(issue.argumentsError);\n }\n else if (issue.path.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < issue.path.length) {\n const el = issue.path[i];\n const terminal = i === issue.path.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n // if (typeof el === \"string\") {\n // curr[el] = curr[el] || { _errors: [] };\n // } else if (typeof el === \"number\") {\n // const errorArray: any = [];\n // errorArray._errors = [];\n // curr[el] = curr[el] || errorArray;\n // }\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n };\n processError(this);\n return fieldErrors;\n }\n static assert(value) {\n if (!(value instanceof ZodError)) {\n throw new Error(`Not a ZodError: ${value}`);\n }\n }\n toString() {\n return this.message;\n }\n get message() {\n return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);\n }\n get isEmpty() {\n return this.issues.length === 0;\n }\n flatten(mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of this.issues) {\n if (sub.path.length > 0) {\n fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];\n fieldErrors[sub.path[0]].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n }\n get formErrors() {\n return this.flatten();\n }\n}\nZodError.create = (issues) => {\n const error = new ZodError(issues);\n return error;\n};\n\nconst errorMap = (issue, _ctx) => {\n let message;\n switch (issue.code) {\n case ZodIssueCode.invalid_type:\n if (issue.received === ZodParsedType.undefined) {\n message = \"Required\";\n }\n else {\n message = `Expected ${issue.expected}, received ${issue.received}`;\n }\n break;\n case ZodIssueCode.invalid_literal:\n message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;\n break;\n case ZodIssueCode.unrecognized_keys:\n message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, \", \")}`;\n break;\n case ZodIssueCode.invalid_union:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_union_discriminator:\n message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;\n break;\n case ZodIssueCode.invalid_enum_value:\n message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;\n break;\n case ZodIssueCode.invalid_arguments:\n message = `Invalid function arguments`;\n break;\n case ZodIssueCode.invalid_return_type:\n message = `Invalid function return type`;\n break;\n case ZodIssueCode.invalid_date:\n message = `Invalid date`;\n break;\n case ZodIssueCode.invalid_string:\n if (typeof issue.validation === \"object\") {\n if (\"includes\" in issue.validation) {\n message = `Invalid input: must include \"${issue.validation.includes}\"`;\n if (typeof issue.validation.position === \"number\") {\n message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;\n }\n }\n else if (\"startsWith\" in issue.validation) {\n message = `Invalid input: must start with \"${issue.validation.startsWith}\"`;\n }\n else if (\"endsWith\" in issue.validation) {\n message = `Invalid input: must end with \"${issue.validation.endsWith}\"`;\n }\n else {\n util.assertNever(issue.validation);\n }\n }\n else if (issue.validation !== \"regex\") {\n message = `Invalid ${issue.validation}`;\n }\n else {\n message = \"Invalid\";\n }\n break;\n case ZodIssueCode.too_small:\n if (issue.type === \"array\")\n message = `Array must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;\n else if (issue.type === \"string\")\n message = `String must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;\n else if (issue.type === \"number\")\n message = `Number must be ${issue.exact\n ? `exactly equal to `\n : issue.inclusive\n ? `greater than or equal to `\n : `greater than `}${issue.minimum}`;\n else if (issue.type === \"date\")\n message = `Date must be ${issue.exact\n ? `exactly equal to `\n : issue.inclusive\n ? `greater than or equal to `\n : `greater than `}${new Date(Number(issue.minimum))}`;\n else\n message = \"Invalid input\";\n break;\n case ZodIssueCode.too_big:\n if (issue.type === \"array\")\n message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;\n else if (issue.type === \"string\")\n message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;\n else if (issue.type === \"number\")\n message = `Number must be ${issue.exact\n ? `exactly`\n : issue.inclusive\n ? `less than or equal to`\n : `less than`} ${issue.maximum}`;\n else if (issue.type === \"bigint\")\n message = `BigInt must be ${issue.exact\n ? `exactly`\n : issue.inclusive\n ? `less than or equal to`\n : `less than`} ${issue.maximum}`;\n else if (issue.type === \"date\")\n message = `Date must be ${issue.exact\n ? `exactly`\n : issue.inclusive\n ? `smaller than or equal to`\n : `smaller than`} ${new Date(Number(issue.maximum))}`;\n else\n message = \"Invalid input\";\n break;\n case ZodIssueCode.custom:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_intersection_types:\n message = `Intersection results could not be merged`;\n break;\n case ZodIssueCode.not_multiple_of:\n message = `Number must be a multiple of ${issue.multipleOf}`;\n break;\n case ZodIssueCode.not_finite:\n message = \"Number must be finite\";\n break;\n default:\n message = _ctx.defaultError;\n util.assertNever(issue);\n }\n return { message };\n};\n\nlet overrideErrorMap = errorMap;\nfunction setErrorMap(map) {\n overrideErrorMap = map;\n}\nfunction getErrorMap() {\n return overrideErrorMap;\n}\n\nconst makeIssue = (params) => {\n const { data, path, errorMaps, issueData } = params;\n const fullPath = [...path, ...(issueData.path || [])];\n const fullIssue = {\n ...issueData,\n path: fullPath,\n };\n if (issueData.message !== undefined) {\n return {\n ...issueData,\n path: fullPath,\n message: issueData.message,\n };\n }\n let errorMessage = \"\";\n const maps = errorMaps\n .filter((m) => !!m)\n .slice()\n .reverse();\n for (const map of maps) {\n errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;\n }\n return {\n ...issueData,\n path: fullPath,\n message: errorMessage,\n };\n};\nconst EMPTY_PATH = [];\nfunction addIssueToContext(ctx, issueData) {\n const overrideMap = getErrorMap();\n const issue = makeIssue({\n issueData: issueData,\n data: ctx.data,\n path: ctx.path,\n errorMaps: [\n ctx.common.contextualErrorMap,\n ctx.schemaErrorMap,\n overrideMap,\n overrideMap === errorMap ? undefined : errorMap, // then global default map\n ].filter((x) => !!x),\n });\n ctx.common.issues.push(issue);\n}\nclass ParseStatus {\n constructor() {\n this.value = \"valid\";\n }\n dirty() {\n if (this.value === \"valid\")\n this.value = \"dirty\";\n }\n abort() {\n if (this.value !== \"aborted\")\n this.value = \"aborted\";\n }\n static mergeArray(status, results) {\n const arrayValue = [];\n for (const s of results) {\n if (s.status === \"aborted\")\n return INVALID;\n if (s.status === \"dirty\")\n status.dirty();\n arrayValue.push(s.value);\n }\n return { status: status.value, value: arrayValue };\n }\n static async mergeObjectAsync(status, pairs) {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n });\n }\n return ParseStatus.mergeObjectSync(status, syncPairs);\n }\n static mergeObjectSync(status, pairs) {\n const finalObject = {};\n for (const pair of pairs) {\n const { key, value } = pair;\n if (key.status === \"aborted\")\n return INVALID;\n if (value.status === \"aborted\")\n return INVALID;\n if (key.status === \"dirty\")\n status.dirty();\n if (value.status === \"dirty\")\n status.dirty();\n if (key.value !== \"__proto__\" &&\n (typeof value.value !== \"undefined\" || pair.alwaysSet)) {\n finalObject[key.value] = value.value;\n }\n }\n return { status: status.value, value: finalObject };\n }\n}\nconst INVALID = Object.freeze({\n status: \"aborted\",\n});\nconst DIRTY = (value) => ({ status: \"dirty\", value });\nconst OK = (value) => ({ status: \"valid\", value });\nconst isAborted = (x) => x.status === \"aborted\";\nconst isDirty = (x) => x.status === \"dirty\";\nconst isValid = (x) => x.status === \"valid\";\nconst isAsync = (x) => typeof Promise !== \"undefined\" && x instanceof Promise;\n\n/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n\r\nfunction __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nfunction __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\ntypeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\n\nvar errorUtil;\n(function (errorUtil) {\n errorUtil.errToObj = (message) => typeof message === \"string\" ? { message } : message || {};\n errorUtil.toString = (message) => typeof message === \"string\" ? message : message === null || message === void 0 ? void 0 : message.message;\n})(errorUtil || (errorUtil = {}));\n\nvar _ZodEnum_cache, _ZodNativeEnum_cache;\nclass ParseInputLazyPath {\n constructor(parent, value, path, key) {\n this._cachedPath = [];\n this.parent = parent;\n this.data = value;\n this._path = path;\n this._key = key;\n }\n get path() {\n if (!this._cachedPath.length) {\n if (this._key instanceof Array) {\n this._cachedPath.push(...this._path, ...this._key);\n }\n else {\n this._cachedPath.push(...this._path, this._key);\n }\n }\n return this._cachedPath;\n }\n}\nconst handleResult = (ctx, result) => {\n if (isValid(result)) {\n return { success: true, data: result.value };\n }\n else {\n if (!ctx.common.issues.length) {\n throw new Error(\"Validation failed but no issues detected.\");\n }\n return {\n success: false,\n get error() {\n if (this._error)\n return this._error;\n const error = new ZodError(ctx.common.issues);\n this._error = error;\n return this._error;\n },\n };\n }\n};\nfunction processCreateParams(params) {\n if (!params)\n return {};\n const { errorMap, invalid_type_error, required_error, description } = params;\n if (errorMap && (invalid_type_error || required_error)) {\n throw new Error(`Can't use \"invalid_type_error\" or \"required_error\" in conjunction with custom error map.`);\n }\n if (errorMap)\n return { errorMap: errorMap, description };\n const customMap = (iss, ctx) => {\n var _a, _b;\n const { message } = params;\n if (iss.code === \"invalid_enum_value\") {\n return { message: message !== null && message !== void 0 ? message : ctx.defaultError };\n }\n if (typeof ctx.data === \"undefined\") {\n return { message: (_a = message !== null && message !== void 0 ? message : required_error) !== null && _a !== void 0 ? _a : ctx.defaultError };\n }\n if (iss.code !== \"invalid_type\")\n return { message: ctx.defaultError };\n return { message: (_b = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError };\n };\n return { errorMap: customMap, description };\n}\nclass ZodType {\n constructor(def) {\n /** Alias of safeParseAsync */\n this.spa = this.safeParseAsync;\n this._def = def;\n this.parse = this.parse.bind(this);\n this.safeParse = this.safeParse.bind(this);\n this.parseAsync = this.parseAsync.bind(this);\n this.safeParseAsync = this.safeParseAsync.bind(this);\n this.spa = this.spa.bind(this);\n this.refine = this.refine.bind(this);\n this.refinement = this.refinement.bind(this);\n this.superRefine = this.superRefine.bind(this);\n this.optional = this.optional.bind(this);\n this.nullable = this.nullable.bind(this);\n this.nullish = this.nullish.bind(this);\n this.array = this.array.bind(this);\n this.promise = this.promise.bind(this);\n this.or = this.or.bind(this);\n this.and = this.and.bind(this);\n this.transform = this.transform.bind(this);\n this.brand = this.brand.bind(this);\n this.default = this.default.bind(this);\n this.catch = this.catch.bind(this);\n this.describe = this.describe.bind(this);\n this.pipe = this.pipe.bind(this);\n this.readonly = this.readonly.bind(this);\n this.isNullable = this.isNullable.bind(this);\n this.isOptional = this.isOptional.bind(this);\n }\n get description() {\n return this._def.description;\n }\n _getType(input) {\n return getParsedType(input.data);\n }\n _getOrReturnCtx(input, ctx) {\n return (ctx || {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n });\n }\n _processInputParams(input) {\n return {\n status: new ParseStatus(),\n ctx: {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n },\n };\n }\n _parseSync(input) {\n const result = this._parse(input);\n if (isAsync(result)) {\n throw new Error(\"Synchronous parse encountered promise.\");\n }\n return result;\n }\n _parseAsync(input) {\n const result = this._parse(input);\n return Promise.resolve(result);\n }\n parse(data, params) {\n const result = this.safeParse(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n safeParse(data, params) {\n var _a;\n const ctx = {\n common: {\n issues: [],\n async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false,\n contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,\n },\n path: (params === null || params === void 0 ? void 0 : params.path) || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const result = this._parseSync({ data, path: ctx.path, parent: ctx });\n return handleResult(ctx, result);\n }\n async parseAsync(data, params) {\n const result = await this.safeParseAsync(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n async safeParseAsync(data, params) {\n const ctx = {\n common: {\n issues: [],\n contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,\n async: true,\n },\n path: (params === null || params === void 0 ? void 0 : params.path) || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });\n const result = await (isAsync(maybeAsyncResult)\n ? maybeAsyncResult\n : Promise.resolve(maybeAsyncResult));\n return handleResult(ctx, result);\n }\n refine(check, message) {\n const getIssueProperties = (val) => {\n if (typeof message === \"string\" || typeof message === \"undefined\") {\n return { message };\n }\n else if (typeof message === \"function\") {\n return message(val);\n }\n else {\n return message;\n }\n };\n return this._refinement((val, ctx) => {\n const result = check(val);\n const setError = () => ctx.addIssue({\n code: ZodIssueCode.custom,\n ...getIssueProperties(val),\n });\n if (typeof Promise !== \"undefined\" && result instanceof Promise) {\n return result.then((data) => {\n if (!data) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n if (!result) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n refinement(check, refinementData) {\n return this._refinement((val, ctx) => {\n if (!check(val)) {\n ctx.addIssue(typeof refinementData === \"function\"\n ? refinementData(val, ctx)\n : refinementData);\n return false;\n }\n else {\n return true;\n }\n });\n }\n _refinement(refinement) {\n return new ZodEffects({\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"refinement\", refinement },\n });\n }\n superRefine(refinement) {\n return this._refinement(refinement);\n }\n optional() {\n return ZodOptional.create(this, this._def);\n }\n nullable() {\n return ZodNullable.create(this, this._def);\n }\n nullish() {\n return this.nullable().optional();\n }\n array() {\n return ZodArray.create(this, this._def);\n }\n promise() {\n return ZodPromise.create(this, this._def);\n }\n or(option) {\n return ZodUnion.create([this, option], this._def);\n }\n and(incoming) {\n return ZodIntersection.create(this, incoming, this._def);\n }\n transform(transform) {\n return new ZodEffects({\n ...processCreateParams(this._def),\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"transform\", transform },\n });\n }\n default(def) {\n const defaultValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodDefault({\n ...processCreateParams(this._def),\n innerType: this,\n defaultValue: defaultValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n });\n }\n brand() {\n return new ZodBranded({\n typeName: ZodFirstPartyTypeKind.ZodBranded,\n type: this,\n ...processCreateParams(this._def),\n });\n }\n catch(def) {\n const catchValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodCatch({\n ...processCreateParams(this._def),\n innerType: this,\n catchValue: catchValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n });\n }\n describe(description) {\n const This = this.constructor;\n return new This({\n ...this._def,\n description,\n });\n }\n pipe(target) {\n return ZodPipeline.create(this, target);\n }\n readonly() {\n return ZodReadonly.create(this);\n }\n isOptional() {\n return this.safeParse(undefined).success;\n }\n isNullable() {\n return this.safeParse(null).success;\n }\n}\nconst cuidRegex = /^c[^\\s-]{8,}$/i;\nconst cuid2Regex = /^[0-9a-z]+$/;\nconst ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/;\n// const uuidRegex =\n// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;\nconst uuidRegex = /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/i;\nconst nanoidRegex = /^[a-z0-9_-]{21}$/i;\nconst durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n// from https://stackoverflow.com/a/46181/1550155\n// old version: too slow, didn't support unicode\n// const emailRegex = /^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))$/i;\n//old email regex\n// const emailRegex = /^(([^<>()[\\].,;:\\s@\"]+(\\.[^<>()[\\].,;:\\s@\"]+)*)|(\".+\"))@((?!-)([^<>()[\\].,;:\\s@\"]+\\.)+[^<>()[\\].,;:\\s@\"]{1,})[^-<>()[\\].,;:\\s@\"]$/i;\n// eslint-disable-next-line\n// const emailRegex =\n// /^(([^<>()[\\]\\\\.,;:\\s@\\\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\\\"]+)*)|(\\\".+\\\"))@((\\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\])|(\\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\\.[A-Za-z]{2,})+))$/;\n// const emailRegex =\n// /^[a-zA-Z0-9\\.\\!\\#\\$\\%\\&\\'\\*\\+\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~\\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// const emailRegex =\n// /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])$/i;\nconst emailRegex = /^(?!\\.)(?!.*\\.\\.)([A-Z0-9_'+\\-\\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\\-]*\\.)+[A-Z]{2,}$/i;\n// const emailRegex =\n// /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\\.[a-z0-9\\-]+)*$/i;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\nconst _emojiRegex = `^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$`;\nlet emojiRegex;\n// faster, simpler, safer\nconst ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;\nconst ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nconst base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;\n// simple\n// const dateRegexSource = `\\\\d{4}-\\\\d{2}-\\\\d{2}`;\n// no leap year validation\n// const dateRegexSource = `\\\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\\\d|2\\\\d))`;\n// with leap year validation\nconst dateRegexSource = `((\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\\\d|30)|(02)-(0[1-9]|1\\\\d|2[0-8])))`;\nconst dateRegex = new RegExp(`^${dateRegexSource}$`);\nfunction timeRegexSource(args) {\n // let regex = `\\\\d{2}:\\\\d{2}:\\\\d{2}`;\n let regex = `([01]\\\\d|2[0-3]):[0-5]\\\\d:[0-5]\\\\d`;\n if (args.precision) {\n regex = `${regex}\\\\.\\\\d{${args.precision}}`;\n }\n else if (args.precision == null) {\n regex = `${regex}(\\\\.\\\\d+)?`;\n }\n return regex;\n}\nfunction timeRegex(args) {\n return new RegExp(`^${timeRegexSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nfunction datetimeRegex(args) {\n let regex = `${dateRegexSource}T${timeRegexSource(args)}`;\n const opts = [];\n opts.push(args.local ? `Z?` : `Z`);\n if (args.offset)\n opts.push(`([+-]\\\\d{2}:?\\\\d{2})`);\n regex = `${regex}(${opts.join(\"|\")})`;\n return new RegExp(`^${regex}$`);\n}\nfunction isValidIP(ip, version) {\n if ((version === \"v4\" || !version) && ipv4Regex.test(ip)) {\n return true;\n }\n if ((version === \"v6\" || !version) && ipv6Regex.test(ip)) {\n return true;\n }\n return false;\n}\nclass ZodString extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = String(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.string) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.string,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.length < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.length > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"length\") {\n const tooBig = input.data.length > check.value;\n const tooSmall = input.data.length < check.value;\n if (tooBig || tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n if (tooBig) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n else if (tooSmall) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n status.dirty();\n }\n }\n else if (check.kind === \"email\") {\n if (!emailRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"email\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"emoji\") {\n if (!emojiRegex) {\n emojiRegex = new RegExp(_emojiRegex, \"u\");\n }\n if (!emojiRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"emoji\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"uuid\") {\n if (!uuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"uuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"nanoid\") {\n if (!nanoidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"nanoid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid\") {\n if (!cuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid2\") {\n if (!cuid2Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid2\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ulid\") {\n if (!ulidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ulid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"url\") {\n try {\n new URL(input.data);\n }\n catch (_a) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"url\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"regex\") {\n check.regex.lastIndex = 0;\n const testResult = check.regex.test(input.data);\n if (!testResult) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"regex\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"trim\") {\n input.data = input.data.trim();\n }\n else if (check.kind === \"includes\") {\n if (!input.data.includes(check.value, check.position)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { includes: check.value, position: check.position },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"toLowerCase\") {\n input.data = input.data.toLowerCase();\n }\n else if (check.kind === \"toUpperCase\") {\n input.data = input.data.toUpperCase();\n }\n else if (check.kind === \"startsWith\") {\n if (!input.data.startsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { startsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"endsWith\") {\n if (!input.data.endsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { endsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"datetime\") {\n const regex = datetimeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"datetime\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"date\") {\n const regex = dateRegex;\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"date\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"time\") {\n const regex = timeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"time\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"duration\") {\n if (!durationRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"duration\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ip\") {\n if (!isValidIP(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ip\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"base64\") {\n if (!base64Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"base64\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _regex(regex, validation, message) {\n return this.refinement((data) => regex.test(data), {\n validation,\n code: ZodIssueCode.invalid_string,\n ...errorUtil.errToObj(message),\n });\n }\n _addCheck(check) {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n email(message) {\n return this._addCheck({ kind: \"email\", ...errorUtil.errToObj(message) });\n }\n url(message) {\n return this._addCheck({ kind: \"url\", ...errorUtil.errToObj(message) });\n }\n emoji(message) {\n return this._addCheck({ kind: \"emoji\", ...errorUtil.errToObj(message) });\n }\n uuid(message) {\n return this._addCheck({ kind: \"uuid\", ...errorUtil.errToObj(message) });\n }\n nanoid(message) {\n return this._addCheck({ kind: \"nanoid\", ...errorUtil.errToObj(message) });\n }\n cuid(message) {\n return this._addCheck({ kind: \"cuid\", ...errorUtil.errToObj(message) });\n }\n cuid2(message) {\n return this._addCheck({ kind: \"cuid2\", ...errorUtil.errToObj(message) });\n }\n ulid(message) {\n return this._addCheck({ kind: \"ulid\", ...errorUtil.errToObj(message) });\n }\n base64(message) {\n return this._addCheck({ kind: \"base64\", ...errorUtil.errToObj(message) });\n }\n ip(options) {\n return this._addCheck({ kind: \"ip\", ...errorUtil.errToObj(options) });\n }\n datetime(options) {\n var _a, _b;\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"datetime\",\n precision: null,\n offset: false,\n local: false,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"datetime\",\n precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === \"undefined\" ? null : options === null || options === void 0 ? void 0 : options.precision,\n offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false,\n local: (_b = options === null || options === void 0 ? void 0 : options.local) !== null && _b !== void 0 ? _b : false,\n ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),\n });\n }\n date(message) {\n return this._addCheck({ kind: \"date\", message });\n }\n time(options) {\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"time\",\n precision: null,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"time\",\n precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === \"undefined\" ? null : options === null || options === void 0 ? void 0 : options.precision,\n ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),\n });\n }\n duration(message) {\n return this._addCheck({ kind: \"duration\", ...errorUtil.errToObj(message) });\n }\n regex(regex, message) {\n return this._addCheck({\n kind: \"regex\",\n regex: regex,\n ...errorUtil.errToObj(message),\n });\n }\n includes(value, options) {\n return this._addCheck({\n kind: \"includes\",\n value: value,\n position: options === null || options === void 0 ? void 0 : options.position,\n ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),\n });\n }\n startsWith(value, message) {\n return this._addCheck({\n kind: \"startsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n endsWith(value, message) {\n return this._addCheck({\n kind: \"endsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n min(minLength, message) {\n return this._addCheck({\n kind: \"min\",\n value: minLength,\n ...errorUtil.errToObj(message),\n });\n }\n max(maxLength, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxLength,\n ...errorUtil.errToObj(message),\n });\n }\n length(len, message) {\n return this._addCheck({\n kind: \"length\",\n value: len,\n ...errorUtil.errToObj(message),\n });\n }\n /**\n * @deprecated Use z.string().min(1) instead.\n * @see {@link ZodString.min}\n */\n nonempty(message) {\n return this.min(1, errorUtil.errToObj(message));\n }\n trim() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"trim\" }],\n });\n }\n toLowerCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toLowerCase\" }],\n });\n }\n toUpperCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toUpperCase\" }],\n });\n }\n get isDatetime() {\n return !!this._def.checks.find((ch) => ch.kind === \"datetime\");\n }\n get isDate() {\n return !!this._def.checks.find((ch) => ch.kind === \"date\");\n }\n get isTime() {\n return !!this._def.checks.find((ch) => ch.kind === \"time\");\n }\n get isDuration() {\n return !!this._def.checks.find((ch) => ch.kind === \"duration\");\n }\n get isEmail() {\n return !!this._def.checks.find((ch) => ch.kind === \"email\");\n }\n get isURL() {\n return !!this._def.checks.find((ch) => ch.kind === \"url\");\n }\n get isEmoji() {\n return !!this._def.checks.find((ch) => ch.kind === \"emoji\");\n }\n get isUUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"uuid\");\n }\n get isNANOID() {\n return !!this._def.checks.find((ch) => ch.kind === \"nanoid\");\n }\n get isCUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid\");\n }\n get isCUID2() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid2\");\n }\n get isULID() {\n return !!this._def.checks.find((ch) => ch.kind === \"ulid\");\n }\n get isIP() {\n return !!this._def.checks.find((ch) => ch.kind === \"ip\");\n }\n get isBase64() {\n return !!this._def.checks.find((ch) => ch.kind === \"base64\");\n }\n get minLength() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxLength() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodString.create = (params) => {\n var _a;\n return new ZodString({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodString,\n coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,\n ...processCreateParams(params),\n });\n};\n// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034\nfunction floatSafeRemainder(val, step) {\n const valDecCount = (val.toString().split(\".\")[1] || \"\").length;\n const stepDecCount = (step.toString().split(\".\")[1] || \"\").length;\n const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n const valInt = parseInt(val.toFixed(decCount).replace(\".\", \"\"));\n const stepInt = parseInt(step.toFixed(decCount).replace(\".\", \"\"));\n return (valInt % stepInt) / Math.pow(10, decCount);\n}\nclass ZodNumber extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n this.step = this.multipleOf;\n }\n _parse(input) {\n if (this._def.coerce) {\n input.data = Number(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.number) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.number,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"int\") {\n if (!util.isInteger(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: \"integer\",\n received: \"float\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"min\") {\n const tooSmall = check.inclusive\n ? input.data < check.value\n : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive\n ? input.data > check.value\n : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (floatSafeRemainder(input.data, check.value) !== 0) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"finite\") {\n if (!Number.isFinite(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_finite,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodNumber({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodNumber({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n int(message) {\n return this._addCheck({\n kind: \"int\",\n message: errorUtil.toString(message),\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value: value,\n message: errorUtil.toString(message),\n });\n }\n finite(message) {\n return this._addCheck({\n kind: \"finite\",\n message: errorUtil.toString(message),\n });\n }\n safe(message) {\n return this._addCheck({\n kind: \"min\",\n inclusive: true,\n value: Number.MIN_SAFE_INTEGER,\n message: errorUtil.toString(message),\n })._addCheck({\n kind: \"max\",\n inclusive: true,\n value: Number.MAX_SAFE_INTEGER,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n get isInt() {\n return !!this._def.checks.find((ch) => ch.kind === \"int\" ||\n (ch.kind === \"multipleOf\" && util.isInteger(ch.value)));\n }\n get isFinite() {\n let max = null, min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"finite\" ||\n ch.kind === \"int\" ||\n ch.kind === \"multipleOf\") {\n return true;\n }\n else if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n else if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return Number.isFinite(min) && Number.isFinite(max);\n }\n}\nZodNumber.create = (params) => {\n return new ZodNumber({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodNumber,\n coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,\n ...processCreateParams(params),\n });\n};\nclass ZodBigInt extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n }\n _parse(input) {\n if (this._def.coerce) {\n input.data = BigInt(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.bigint) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.bigint,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n const tooSmall = check.inclusive\n ? input.data < check.value\n : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n type: \"bigint\",\n minimum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive\n ? input.data > check.value\n : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n type: \"bigint\",\n maximum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (input.data % check.value !== BigInt(0)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodBigInt({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodBigInt({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodBigInt.create = (params) => {\n var _a;\n return new ZodBigInt({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodBigInt,\n coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,\n ...processCreateParams(params),\n });\n};\nclass ZodBoolean extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = Boolean(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.boolean) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.boolean,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodBoolean.create = (params) => {\n return new ZodBoolean({\n typeName: ZodFirstPartyTypeKind.ZodBoolean,\n coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,\n ...processCreateParams(params),\n });\n};\nclass ZodDate extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = new Date(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.date) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.date,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (isNaN(input.data.getTime())) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_date,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.getTime() < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n message: check.message,\n inclusive: true,\n exact: false,\n minimum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.getTime() > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n message: check.message,\n inclusive: true,\n exact: false,\n maximum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return {\n status: status.value,\n value: new Date(input.data.getTime()),\n };\n }\n _addCheck(check) {\n return new ZodDate({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n min(minDate, message) {\n return this._addCheck({\n kind: \"min\",\n value: minDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n max(maxDate, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n get minDate() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min != null ? new Date(min) : null;\n }\n get maxDate() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max != null ? new Date(max) : null;\n }\n}\nZodDate.create = (params) => {\n return new ZodDate({\n checks: [],\n coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,\n typeName: ZodFirstPartyTypeKind.ZodDate,\n ...processCreateParams(params),\n });\n};\nclass ZodSymbol extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.symbol) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.symbol,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodSymbol.create = (params) => {\n return new ZodSymbol({\n typeName: ZodFirstPartyTypeKind.ZodSymbol,\n ...processCreateParams(params),\n });\n};\nclass ZodUndefined extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.undefined,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodUndefined.create = (params) => {\n return new ZodUndefined({\n typeName: ZodFirstPartyTypeKind.ZodUndefined,\n ...processCreateParams(params),\n });\n};\nclass ZodNull extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.null) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.null,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodNull.create = (params) => {\n return new ZodNull({\n typeName: ZodFirstPartyTypeKind.ZodNull,\n ...processCreateParams(params),\n });\n};\nclass ZodAny extends ZodType {\n constructor() {\n super(...arguments);\n // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.\n this._any = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodAny.create = (params) => {\n return new ZodAny({\n typeName: ZodFirstPartyTypeKind.ZodAny,\n ...processCreateParams(params),\n });\n};\nclass ZodUnknown extends ZodType {\n constructor() {\n super(...arguments);\n // required\n this._unknown = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodUnknown.create = (params) => {\n return new ZodUnknown({\n typeName: ZodFirstPartyTypeKind.ZodUnknown,\n ...processCreateParams(params),\n });\n};\nclass ZodNever extends ZodType {\n _parse(input) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.never,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n}\nZodNever.create = (params) => {\n return new ZodNever({\n typeName: ZodFirstPartyTypeKind.ZodNever,\n ...processCreateParams(params),\n });\n};\nclass ZodVoid extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.void,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodVoid.create = (params) => {\n return new ZodVoid({\n typeName: ZodFirstPartyTypeKind.ZodVoid,\n ...processCreateParams(params),\n });\n};\nclass ZodArray extends ZodType {\n _parse(input) {\n const { ctx, status } = this._processInputParams(input);\n const def = this._def;\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (def.exactLength !== null) {\n const tooBig = ctx.data.length > def.exactLength.value;\n const tooSmall = ctx.data.length < def.exactLength.value;\n if (tooBig || tooSmall) {\n addIssueToContext(ctx, {\n code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,\n minimum: (tooSmall ? def.exactLength.value : undefined),\n maximum: (tooBig ? def.exactLength.value : undefined),\n type: \"array\",\n inclusive: true,\n exact: true,\n message: def.exactLength.message,\n });\n status.dirty();\n }\n }\n if (def.minLength !== null) {\n if (ctx.data.length < def.minLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.minLength.message,\n });\n status.dirty();\n }\n }\n if (def.maxLength !== null) {\n if (ctx.data.length > def.maxLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.maxLength.message,\n });\n status.dirty();\n }\n }\n if (ctx.common.async) {\n return Promise.all([...ctx.data].map((item, i) => {\n return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n })).then((result) => {\n return ParseStatus.mergeArray(status, result);\n });\n }\n const result = [...ctx.data].map((item, i) => {\n return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n });\n return ParseStatus.mergeArray(status, result);\n }\n get element() {\n return this._def.type;\n }\n min(minLength, message) {\n return new ZodArray({\n ...this._def,\n minLength: { value: minLength, message: errorUtil.toString(message) },\n });\n }\n max(maxLength, message) {\n return new ZodArray({\n ...this._def,\n maxLength: { value: maxLength, message: errorUtil.toString(message) },\n });\n }\n length(len, message) {\n return new ZodArray({\n ...this._def,\n exactLength: { value: len, message: errorUtil.toString(message) },\n });\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodArray.create = (schema, params) => {\n return new ZodArray({\n type: schema,\n minLength: null,\n maxLength: null,\n exactLength: null,\n typeName: ZodFirstPartyTypeKind.ZodArray,\n ...processCreateParams(params),\n });\n};\nfunction deepPartialify(schema) {\n if (schema instanceof ZodObject) {\n const newShape = {};\n for (const key in schema.shape) {\n const fieldSchema = schema.shape[key];\n newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));\n }\n return new ZodObject({\n ...schema._def,\n shape: () => newShape,\n });\n }\n else if (schema instanceof ZodArray) {\n return new ZodArray({\n ...schema._def,\n type: deepPartialify(schema.element),\n });\n }\n else if (schema instanceof ZodOptional) {\n return ZodOptional.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodNullable) {\n return ZodNullable.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodTuple) {\n return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));\n }\n else {\n return schema;\n }\n}\nclass ZodObject extends ZodType {\n constructor() {\n super(...arguments);\n this._cached = null;\n /**\n * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.\n * If you want to pass through unknown properties, use `.passthrough()` instead.\n */\n this.nonstrict = this.passthrough;\n // extend<\n // Augmentation extends ZodRawShape,\n // NewOutput extends util.flatten<{\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // }>,\n // NewInput extends util.flatten<{\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }>\n // >(\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape,\n // UnknownKeys,\n // Catchall,\n // NewOutput,\n // NewInput\n // > {\n // return new ZodObject({\n // ...this._def,\n // shape: () => ({\n // ...this._def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // }\n /**\n * @deprecated Use `.extend` instead\n * */\n this.augment = this.extend;\n }\n _getCached() {\n if (this._cached !== null)\n return this._cached;\n const shape = this._def.shape();\n const keys = util.objectKeys(shape);\n return (this._cached = { shape, keys });\n }\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.object) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const { status, ctx } = this._processInputParams(input);\n const { shape, keys: shapeKeys } = this._getCached();\n const extraKeys = [];\n if (!(this._def.catchall instanceof ZodNever &&\n this._def.unknownKeys === \"strip\")) {\n for (const key in ctx.data) {\n if (!shapeKeys.includes(key)) {\n extraKeys.push(key);\n }\n }\n }\n const pairs = [];\n for (const key of shapeKeys) {\n const keyValidator = shape[key];\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (this._def.catchall instanceof ZodNever) {\n const unknownKeys = this._def.unknownKeys;\n if (unknownKeys === \"passthrough\") {\n for (const key of extraKeys) {\n pairs.push({\n key: { status: \"valid\", value: key },\n value: { status: \"valid\", value: ctx.data[key] },\n });\n }\n }\n else if (unknownKeys === \"strict\") {\n if (extraKeys.length > 0) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.unrecognized_keys,\n keys: extraKeys,\n });\n status.dirty();\n }\n }\n else if (unknownKeys === \"strip\") ;\n else {\n throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);\n }\n }\n else {\n // run catchall validation\n const catchall = this._def.catchall;\n for (const key of extraKeys) {\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)\n ),\n alwaysSet: key in ctx.data,\n });\n }\n }\n if (ctx.common.async) {\n return Promise.resolve()\n .then(async () => {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n alwaysSet: pair.alwaysSet,\n });\n }\n return syncPairs;\n })\n .then((syncPairs) => {\n return ParseStatus.mergeObjectSync(status, syncPairs);\n });\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get shape() {\n return this._def.shape();\n }\n strict(message) {\n errorUtil.errToObj;\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strict\",\n ...(message !== undefined\n ? {\n errorMap: (issue, ctx) => {\n var _a, _b, _c, _d;\n const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError;\n if (issue.code === \"unrecognized_keys\")\n return {\n message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError,\n };\n return {\n message: defaultError,\n };\n },\n }\n : {}),\n });\n }\n strip() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strip\",\n });\n }\n passthrough() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"passthrough\",\n });\n }\n // const AugmentFactory =\n // (def: Def) =>\n // (\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape, Augmentation>,\n // Def[\"unknownKeys\"],\n // Def[\"catchall\"]\n // > => {\n // return new ZodObject({\n // ...def,\n // shape: () => ({\n // ...def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // };\n extend(augmentation) {\n return new ZodObject({\n ...this._def,\n shape: () => ({\n ...this._def.shape(),\n ...augmentation,\n }),\n });\n }\n /**\n * Prior to zod@1.0.12 there was a bug in the\n * inferred type of merged objects. Please\n * upgrade if you are experiencing issues.\n */\n merge(merging) {\n const merged = new ZodObject({\n unknownKeys: merging._def.unknownKeys,\n catchall: merging._def.catchall,\n shape: () => ({\n ...this._def.shape(),\n ...merging._def.shape(),\n }),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n });\n return merged;\n }\n // merge<\n // Incoming extends AnyZodObject,\n // Augmentation extends Incoming[\"shape\"],\n // NewOutput extends {\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // },\n // NewInput extends {\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }\n // >(\n // merging: Incoming\n // ): ZodObject<\n // extendShape>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"],\n // NewOutput,\n // NewInput\n // > {\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n setKey(key, schema) {\n return this.augment({ [key]: schema });\n }\n // merge(\n // merging: Incoming\n // ): //ZodObject = (merging) => {\n // ZodObject<\n // extendShape>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"]\n // > {\n // // const mergedShape = objectUtil.mergeShapes(\n // // this._def.shape(),\n // // merging._def.shape()\n // // );\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n catchall(index) {\n return new ZodObject({\n ...this._def,\n catchall: index,\n });\n }\n pick(mask) {\n const shape = {};\n util.objectKeys(mask).forEach((key) => {\n if (mask[key] && this.shape[key]) {\n shape[key] = this.shape[key];\n }\n });\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n omit(mask) {\n const shape = {};\n util.objectKeys(this.shape).forEach((key) => {\n if (!mask[key]) {\n shape[key] = this.shape[key];\n }\n });\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n /**\n * @deprecated\n */\n deepPartial() {\n return deepPartialify(this);\n }\n partial(mask) {\n const newShape = {};\n util.objectKeys(this.shape).forEach((key) => {\n const fieldSchema = this.shape[key];\n if (mask && !mask[key]) {\n newShape[key] = fieldSchema;\n }\n else {\n newShape[key] = fieldSchema.optional();\n }\n });\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n required(mask) {\n const newShape = {};\n util.objectKeys(this.shape).forEach((key) => {\n if (mask && !mask[key]) {\n newShape[key] = this.shape[key];\n }\n else {\n const fieldSchema = this.shape[key];\n let newField = fieldSchema;\n while (newField instanceof ZodOptional) {\n newField = newField._def.innerType;\n }\n newShape[key] = newField;\n }\n });\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n keyof() {\n return createZodEnum(util.objectKeys(this.shape));\n }\n}\nZodObject.create = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.strictCreate = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strict\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.lazycreate = (shape, params) => {\n return new ZodObject({\n shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nclass ZodUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const options = this._def.options;\n function handleResults(results) {\n // return first issue-free validation if it exists\n for (const result of results) {\n if (result.result.status === \"valid\") {\n return result.result;\n }\n }\n for (const result of results) {\n if (result.result.status === \"dirty\") {\n // add issues from dirty option\n ctx.common.issues.push(...result.ctx.common.issues);\n return result.result;\n }\n }\n // return invalid\n const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return Promise.all(options.map(async (option) => {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n return {\n result: await option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n }),\n ctx: childCtx,\n };\n })).then(handleResults);\n }\n else {\n let dirty = undefined;\n const issues = [];\n for (const option of options) {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n const result = option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n });\n if (result.status === \"valid\") {\n return result;\n }\n else if (result.status === \"dirty\" && !dirty) {\n dirty = { result, ctx: childCtx };\n }\n if (childCtx.common.issues.length) {\n issues.push(childCtx.common.issues);\n }\n }\n if (dirty) {\n ctx.common.issues.push(...dirty.ctx.common.issues);\n return dirty.result;\n }\n const unionErrors = issues.map((issues) => new ZodError(issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n }\n get options() {\n return this._def.options;\n }\n}\nZodUnion.create = (types, params) => {\n return new ZodUnion({\n options: types,\n typeName: ZodFirstPartyTypeKind.ZodUnion,\n ...processCreateParams(params),\n });\n};\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\n////////// //////////\n////////// ZodDiscriminatedUnion //////////\n////////// //////////\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\nconst getDiscriminator = (type) => {\n if (type instanceof ZodLazy) {\n return getDiscriminator(type.schema);\n }\n else if (type instanceof ZodEffects) {\n return getDiscriminator(type.innerType());\n }\n else if (type instanceof ZodLiteral) {\n return [type.value];\n }\n else if (type instanceof ZodEnum) {\n return type.options;\n }\n else if (type instanceof ZodNativeEnum) {\n // eslint-disable-next-line ban/ban\n return util.objectValues(type.enum);\n }\n else if (type instanceof ZodDefault) {\n return getDiscriminator(type._def.innerType);\n }\n else if (type instanceof ZodUndefined) {\n return [undefined];\n }\n else if (type instanceof ZodNull) {\n return [null];\n }\n else if (type instanceof ZodOptional) {\n return [undefined, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodNullable) {\n return [null, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodBranded) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodReadonly) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodCatch) {\n return getDiscriminator(type._def.innerType);\n }\n else {\n return [];\n }\n};\nclass ZodDiscriminatedUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const discriminator = this.discriminator;\n const discriminatorValue = ctx.data[discriminator];\n const option = this.optionsMap.get(discriminatorValue);\n if (!option) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union_discriminator,\n options: Array.from(this.optionsMap.keys()),\n path: [discriminator],\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n else {\n return option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n get discriminator() {\n return this._def.discriminator;\n }\n get options() {\n return this._def.options;\n }\n get optionsMap() {\n return this._def.optionsMap;\n }\n /**\n * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.\n * However, it only allows a union of objects, all of which need to share a discriminator property. This property must\n * have a different value for each object in the union.\n * @param discriminator the name of the discriminator property\n * @param types an array of object schemas\n * @param params\n */\n static create(discriminator, options, params) {\n // Get all the valid discriminator values\n const optionsMap = new Map();\n // try {\n for (const type of options) {\n const discriminatorValues = getDiscriminator(type.shape[discriminator]);\n if (!discriminatorValues.length) {\n throw new Error(`A discriminator value for key \\`${discriminator}\\` could not be extracted from all schema options`);\n }\n for (const value of discriminatorValues) {\n if (optionsMap.has(value)) {\n throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);\n }\n optionsMap.set(value, type);\n }\n }\n return new ZodDiscriminatedUnion({\n typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,\n discriminator,\n options,\n optionsMap,\n ...processCreateParams(params),\n });\n }\n}\nfunction mergeValues(a, b) {\n const aType = getParsedType(a);\n const bType = getParsedType(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {\n const bKeys = util.objectKeys(b);\n const sharedKeys = util\n .objectKeys(a)\n .filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n for (const key of sharedKeys) {\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {\n if (a.length !== b.length) {\n return { valid: false };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n else if (aType === ZodParsedType.date &&\n bType === ZodParsedType.date &&\n +a === +b) {\n return { valid: true, data: a };\n }\n else {\n return { valid: false };\n }\n}\nclass ZodIntersection extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const handleParsed = (parsedLeft, parsedRight) => {\n if (isAborted(parsedLeft) || isAborted(parsedRight)) {\n return INVALID;\n }\n const merged = mergeValues(parsedLeft.value, parsedRight.value);\n if (!merged.valid) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_intersection_types,\n });\n return INVALID;\n }\n if (isDirty(parsedLeft) || isDirty(parsedRight)) {\n status.dirty();\n }\n return { status: status.value, value: merged.data };\n };\n if (ctx.common.async) {\n return Promise.all([\n this._def.left._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n this._def.right._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n ]).then(([left, right]) => handleParsed(left, right));\n }\n else {\n return handleParsed(this._def.left._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }), this._def.right._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }));\n }\n }\n}\nZodIntersection.create = (left, right, params) => {\n return new ZodIntersection({\n left: left,\n right: right,\n typeName: ZodFirstPartyTypeKind.ZodIntersection,\n ...processCreateParams(params),\n });\n};\nclass ZodTuple extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (ctx.data.length < this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n return INVALID;\n }\n const rest = this._def.rest;\n if (!rest && ctx.data.length > this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n status.dirty();\n }\n const items = [...ctx.data]\n .map((item, itemIndex) => {\n const schema = this._def.items[itemIndex] || this._def.rest;\n if (!schema)\n return null;\n return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));\n })\n .filter((x) => !!x); // filter nulls\n if (ctx.common.async) {\n return Promise.all(items).then((results) => {\n return ParseStatus.mergeArray(status, results);\n });\n }\n else {\n return ParseStatus.mergeArray(status, items);\n }\n }\n get items() {\n return this._def.items;\n }\n rest(rest) {\n return new ZodTuple({\n ...this._def,\n rest,\n });\n }\n}\nZodTuple.create = (schemas, params) => {\n if (!Array.isArray(schemas)) {\n throw new Error(\"You must pass an array of schemas to z.tuple([ ... ])\");\n }\n return new ZodTuple({\n items: schemas,\n typeName: ZodFirstPartyTypeKind.ZodTuple,\n rest: null,\n ...processCreateParams(params),\n });\n};\nclass ZodRecord extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const pairs = [];\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n for (const key in ctx.data) {\n pairs.push({\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),\n value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (ctx.common.async) {\n return ParseStatus.mergeObjectAsync(status, pairs);\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get element() {\n return this._def.valueType;\n }\n static create(first, second, third) {\n if (second instanceof ZodType) {\n return new ZodRecord({\n keyType: first,\n valueType: second,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(third),\n });\n }\n return new ZodRecord({\n keyType: ZodString.create(),\n valueType: first,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(second),\n });\n }\n}\nclass ZodMap extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.map) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.map,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n const pairs = [...ctx.data.entries()].map(([key, value], index) => {\n return {\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, \"key\"])),\n value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, \"value\"])),\n };\n });\n if (ctx.common.async) {\n const finalMap = new Map();\n return Promise.resolve().then(async () => {\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n });\n }\n else {\n const finalMap = new Map();\n for (const pair of pairs) {\n const key = pair.key;\n const value = pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n }\n }\n}\nZodMap.create = (keyType, valueType, params) => {\n return new ZodMap({\n valueType,\n keyType,\n typeName: ZodFirstPartyTypeKind.ZodMap,\n ...processCreateParams(params),\n });\n};\nclass ZodSet extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.set) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.set,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const def = this._def;\n if (def.minSize !== null) {\n if (ctx.data.size < def.minSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.minSize.message,\n });\n status.dirty();\n }\n }\n if (def.maxSize !== null) {\n if (ctx.data.size > def.maxSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.maxSize.message,\n });\n status.dirty();\n }\n }\n const valueType = this._def.valueType;\n function finalizeSet(elements) {\n const parsedSet = new Set();\n for (const element of elements) {\n if (element.status === \"aborted\")\n return INVALID;\n if (element.status === \"dirty\")\n status.dirty();\n parsedSet.add(element.value);\n }\n return { status: status.value, value: parsedSet };\n }\n const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));\n if (ctx.common.async) {\n return Promise.all(elements).then((elements) => finalizeSet(elements));\n }\n else {\n return finalizeSet(elements);\n }\n }\n min(minSize, message) {\n return new ZodSet({\n ...this._def,\n minSize: { value: minSize, message: errorUtil.toString(message) },\n });\n }\n max(maxSize, message) {\n return new ZodSet({\n ...this._def,\n maxSize: { value: maxSize, message: errorUtil.toString(message) },\n });\n }\n size(size, message) {\n return this.min(size, message).max(size, message);\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodSet.create = (valueType, params) => {\n return new ZodSet({\n valueType,\n minSize: null,\n maxSize: null,\n typeName: ZodFirstPartyTypeKind.ZodSet,\n ...processCreateParams(params),\n });\n};\nclass ZodFunction extends ZodType {\n constructor() {\n super(...arguments);\n this.validate = this.implement;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.function) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.function,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n function makeArgsIssue(args, error) {\n return makeIssue({\n data: args,\n path: ctx.path,\n errorMaps: [\n ctx.common.contextualErrorMap,\n ctx.schemaErrorMap,\n getErrorMap(),\n errorMap,\n ].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_arguments,\n argumentsError: error,\n },\n });\n }\n function makeReturnsIssue(returns, error) {\n return makeIssue({\n data: returns,\n path: ctx.path,\n errorMaps: [\n ctx.common.contextualErrorMap,\n ctx.schemaErrorMap,\n getErrorMap(),\n errorMap,\n ].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_return_type,\n returnTypeError: error,\n },\n });\n }\n const params = { errorMap: ctx.common.contextualErrorMap };\n const fn = ctx.data;\n if (this._def.returns instanceof ZodPromise) {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(async function (...args) {\n const error = new ZodError([]);\n const parsedArgs = await me._def.args\n .parseAsync(args, params)\n .catch((e) => {\n error.addIssue(makeArgsIssue(args, e));\n throw error;\n });\n const result = await Reflect.apply(fn, this, parsedArgs);\n const parsedReturns = await me._def.returns._def.type\n .parseAsync(result, params)\n .catch((e) => {\n error.addIssue(makeReturnsIssue(result, e));\n throw error;\n });\n return parsedReturns;\n });\n }\n else {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(function (...args) {\n const parsedArgs = me._def.args.safeParse(args, params);\n if (!parsedArgs.success) {\n throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);\n }\n const result = Reflect.apply(fn, this, parsedArgs.data);\n const parsedReturns = me._def.returns.safeParse(result, params);\n if (!parsedReturns.success) {\n throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);\n }\n return parsedReturns.data;\n });\n }\n }\n parameters() {\n return this._def.args;\n }\n returnType() {\n return this._def.returns;\n }\n args(...items) {\n return new ZodFunction({\n ...this._def,\n args: ZodTuple.create(items).rest(ZodUnknown.create()),\n });\n }\n returns(returnType) {\n return new ZodFunction({\n ...this._def,\n returns: returnType,\n });\n }\n implement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n strictImplement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n static create(args, returns, params) {\n return new ZodFunction({\n args: (args\n ? args\n : ZodTuple.create([]).rest(ZodUnknown.create())),\n returns: returns || ZodUnknown.create(),\n typeName: ZodFirstPartyTypeKind.ZodFunction,\n ...processCreateParams(params),\n });\n }\n}\nclass ZodLazy extends ZodType {\n get schema() {\n return this._def.getter();\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const lazySchema = this._def.getter();\n return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });\n }\n}\nZodLazy.create = (getter, params) => {\n return new ZodLazy({\n getter: getter,\n typeName: ZodFirstPartyTypeKind.ZodLazy,\n ...processCreateParams(params),\n });\n};\nclass ZodLiteral extends ZodType {\n _parse(input) {\n if (input.data !== this._def.value) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_literal,\n expected: this._def.value,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n get value() {\n return this._def.value;\n }\n}\nZodLiteral.create = (value, params) => {\n return new ZodLiteral({\n value: value,\n typeName: ZodFirstPartyTypeKind.ZodLiteral,\n ...processCreateParams(params),\n });\n};\nfunction createZodEnum(values, params) {\n return new ZodEnum({\n values,\n typeName: ZodFirstPartyTypeKind.ZodEnum,\n ...processCreateParams(params),\n });\n}\nclass ZodEnum extends ZodType {\n constructor() {\n super(...arguments);\n _ZodEnum_cache.set(this, void 0);\n }\n _parse(input) {\n if (typeof input.data !== \"string\") {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!__classPrivateFieldGet(this, _ZodEnum_cache, \"f\")) {\n __classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values), \"f\");\n }\n if (!__classPrivateFieldGet(this, _ZodEnum_cache, \"f\").has(input.data)) {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get options() {\n return this._def.values;\n }\n get enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Values() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n extract(values, newDef = this._def) {\n return ZodEnum.create(values, {\n ...this._def,\n ...newDef,\n });\n }\n exclude(values, newDef = this._def) {\n return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {\n ...this._def,\n ...newDef,\n });\n }\n}\n_ZodEnum_cache = new WeakMap();\nZodEnum.create = createZodEnum;\nclass ZodNativeEnum extends ZodType {\n constructor() {\n super(...arguments);\n _ZodNativeEnum_cache.set(this, void 0);\n }\n _parse(input) {\n const nativeEnumValues = util.getValidEnumValues(this._def.values);\n const ctx = this._getOrReturnCtx(input);\n if (ctx.parsedType !== ZodParsedType.string &&\n ctx.parsedType !== ZodParsedType.number) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, \"f\")) {\n __classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util.getValidEnumValues(this._def.values)), \"f\");\n }\n if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, \"f\").has(input.data)) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get enum() {\n return this._def.values;\n }\n}\n_ZodNativeEnum_cache = new WeakMap();\nZodNativeEnum.create = (values, params) => {\n return new ZodNativeEnum({\n values: values,\n typeName: ZodFirstPartyTypeKind.ZodNativeEnum,\n ...processCreateParams(params),\n });\n};\nclass ZodPromise extends ZodType {\n unwrap() {\n return this._def.type;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.promise &&\n ctx.common.async === false) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.promise,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const promisified = ctx.parsedType === ZodParsedType.promise\n ? ctx.data\n : Promise.resolve(ctx.data);\n return OK(promisified.then((data) => {\n return this._def.type.parseAsync(data, {\n path: ctx.path,\n errorMap: ctx.common.contextualErrorMap,\n });\n }));\n }\n}\nZodPromise.create = (schema, params) => {\n return new ZodPromise({\n type: schema,\n typeName: ZodFirstPartyTypeKind.ZodPromise,\n ...processCreateParams(params),\n });\n};\nclass ZodEffects extends ZodType {\n innerType() {\n return this._def.schema;\n }\n sourceType() {\n return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects\n ? this._def.schema.sourceType()\n : this._def.schema;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const effect = this._def.effect || null;\n const checkCtx = {\n addIssue: (arg) => {\n addIssueToContext(ctx, arg);\n if (arg.fatal) {\n status.abort();\n }\n else {\n status.dirty();\n }\n },\n get path() {\n return ctx.path;\n },\n };\n checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);\n if (effect.type === \"preprocess\") {\n const processed = effect.transform(ctx.data, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(processed).then(async (processed) => {\n if (status.value === \"aborted\")\n return INVALID;\n const result = await this._def.schema._parseAsync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return INVALID;\n if (result.status === \"dirty\")\n return DIRTY(result.value);\n if (status.value === \"dirty\")\n return DIRTY(result.value);\n return result;\n });\n }\n else {\n if (status.value === \"aborted\")\n return INVALID;\n const result = this._def.schema._parseSync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return INVALID;\n if (result.status === \"dirty\")\n return DIRTY(result.value);\n if (status.value === \"dirty\")\n return DIRTY(result.value);\n return result;\n }\n }\n if (effect.type === \"refinement\") {\n const executeRefinement = (acc) => {\n const result = effect.refinement(acc, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(result);\n }\n if (result instanceof Promise) {\n throw new Error(\"Async refinement encountered during synchronous parse operation. Use .parseAsync instead.\");\n }\n return acc;\n };\n if (ctx.common.async === false) {\n const inner = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n // return value is ignored\n executeRefinement(inner.value);\n return { status: status.value, value: inner.value };\n }\n else {\n return this._def.schema\n ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })\n .then((inner) => {\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n return executeRefinement(inner.value).then(() => {\n return { status: status.value, value: inner.value };\n });\n });\n }\n }\n if (effect.type === \"transform\") {\n if (ctx.common.async === false) {\n const base = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (!isValid(base))\n return base;\n const result = effect.transform(base.value, checkCtx);\n if (result instanceof Promise) {\n throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);\n }\n return { status: status.value, value: result };\n }\n else {\n return this._def.schema\n ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })\n .then((base) => {\n if (!isValid(base))\n return base;\n return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result }));\n });\n }\n }\n util.assertNever(effect);\n }\n}\nZodEffects.create = (schema, effect, params) => {\n return new ZodEffects({\n schema,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect,\n ...processCreateParams(params),\n });\n};\nZodEffects.createWithPreprocess = (preprocess, schema, params) => {\n return new ZodEffects({\n schema,\n effect: { type: \"preprocess\", transform: preprocess },\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n ...processCreateParams(params),\n });\n};\nclass ZodOptional extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.undefined) {\n return OK(undefined);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodOptional.create = (type, params) => {\n return new ZodOptional({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodOptional,\n ...processCreateParams(params),\n });\n};\nclass ZodNullable extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.null) {\n return OK(null);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodNullable.create = (type, params) => {\n return new ZodNullable({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodNullable,\n ...processCreateParams(params),\n });\n};\nclass ZodDefault extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n let data = ctx.data;\n if (ctx.parsedType === ZodParsedType.undefined) {\n data = this._def.defaultValue();\n }\n return this._def.innerType._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n removeDefault() {\n return this._def.innerType;\n }\n}\nZodDefault.create = (type, params) => {\n return new ZodDefault({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n defaultValue: typeof params.default === \"function\"\n ? params.default\n : () => params.default,\n ...processCreateParams(params),\n });\n};\nclass ZodCatch extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n // newCtx is used to not collect issues from inner types in ctx\n const newCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n };\n const result = this._def.innerType._parse({\n data: newCtx.data,\n path: newCtx.path,\n parent: {\n ...newCtx,\n },\n });\n if (isAsync(result)) {\n return result.then((result) => {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n });\n }\n else {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n }\n }\n removeCatch() {\n return this._def.innerType;\n }\n}\nZodCatch.create = (type, params) => {\n return new ZodCatch({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n catchValue: typeof params.catch === \"function\" ? params.catch : () => params.catch,\n ...processCreateParams(params),\n });\n};\nclass ZodNaN extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.nan) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.nan,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n}\nZodNaN.create = (params) => {\n return new ZodNaN({\n typeName: ZodFirstPartyTypeKind.ZodNaN,\n ...processCreateParams(params),\n });\n};\nconst BRAND = Symbol(\"zod_brand\");\nclass ZodBranded extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const data = ctx.data;\n return this._def.type._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n unwrap() {\n return this._def.type;\n }\n}\nclass ZodPipeline extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.common.async) {\n const handleAsync = async () => {\n const inResult = await this._def.in._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return DIRTY(inResult.value);\n }\n else {\n return this._def.out._parseAsync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n };\n return handleAsync();\n }\n else {\n const inResult = this._def.in._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return {\n status: \"dirty\",\n value: inResult.value,\n };\n }\n else {\n return this._def.out._parseSync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n }\n static create(a, b) {\n return new ZodPipeline({\n in: a,\n out: b,\n typeName: ZodFirstPartyTypeKind.ZodPipeline,\n });\n }\n}\nclass ZodReadonly extends ZodType {\n _parse(input) {\n const result = this._def.innerType._parse(input);\n const freeze = (data) => {\n if (isValid(data)) {\n data.value = Object.freeze(data.value);\n }\n return data;\n };\n return isAsync(result)\n ? result.then((data) => freeze(data))\n : freeze(result);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodReadonly.create = (type, params) => {\n return new ZodReadonly({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodReadonly,\n ...processCreateParams(params),\n });\n};\nfunction custom(check, params = {}, \n/**\n * @deprecated\n *\n * Pass `fatal` into the params object instead:\n *\n * ```ts\n * z.string().custom((val) => val.length > 5, { fatal: false })\n * ```\n *\n */\nfatal) {\n if (check)\n return ZodAny.create().superRefine((data, ctx) => {\n var _a, _b;\n if (!check(data)) {\n const p = typeof params === \"function\"\n ? params(data)\n : typeof params === \"string\"\n ? { message: params }\n : params;\n const _fatal = (_b = (_a = p.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true;\n const p2 = typeof p === \"string\" ? { message: p } : p;\n ctx.addIssue({ code: \"custom\", ...p2, fatal: _fatal });\n }\n });\n return ZodAny.create();\n}\nconst late = {\n object: ZodObject.lazycreate,\n};\nvar ZodFirstPartyTypeKind;\n(function (ZodFirstPartyTypeKind) {\n ZodFirstPartyTypeKind[\"ZodString\"] = \"ZodString\";\n ZodFirstPartyTypeKind[\"ZodNumber\"] = \"ZodNumber\";\n ZodFirstPartyTypeKind[\"ZodNaN\"] = \"ZodNaN\";\n ZodFirstPartyTypeKind[\"ZodBigInt\"] = \"ZodBigInt\";\n ZodFirstPartyTypeKind[\"ZodBoolean\"] = \"ZodBoolean\";\n ZodFirstPartyTypeKind[\"ZodDate\"] = \"ZodDate\";\n ZodFirstPartyTypeKind[\"ZodSymbol\"] = \"ZodSymbol\";\n ZodFirstPartyTypeKind[\"ZodUndefined\"] = \"ZodUndefined\";\n ZodFirstPartyTypeKind[\"ZodNull\"] = \"ZodNull\";\n ZodFirstPartyTypeKind[\"ZodAny\"] = \"ZodAny\";\n ZodFirstPartyTypeKind[\"ZodUnknown\"] = \"ZodUnknown\";\n ZodFirstPartyTypeKind[\"ZodNever\"] = \"ZodNever\";\n ZodFirstPartyTypeKind[\"ZodVoid\"] = \"ZodVoid\";\n ZodFirstPartyTypeKind[\"ZodArray\"] = \"ZodArray\";\n ZodFirstPartyTypeKind[\"ZodObject\"] = \"ZodObject\";\n ZodFirstPartyTypeKind[\"ZodUnion\"] = \"ZodUnion\";\n ZodFirstPartyTypeKind[\"ZodDiscriminatedUnion\"] = \"ZodDiscriminatedUnion\";\n ZodFirstPartyTypeKind[\"ZodIntersection\"] = \"ZodIntersection\";\n ZodFirstPartyTypeKind[\"ZodTuple\"] = \"ZodTuple\";\n ZodFirstPartyTypeKind[\"ZodRecord\"] = \"ZodRecord\";\n ZodFirstPartyTypeKind[\"ZodMap\"] = \"ZodMap\";\n ZodFirstPartyTypeKind[\"ZodSet\"] = \"ZodSet\";\n ZodFirstPartyTypeKind[\"ZodFunction\"] = \"ZodFunction\";\n ZodFirstPartyTypeKind[\"ZodLazy\"] = \"ZodLazy\";\n ZodFirstPartyTypeKind[\"ZodLiteral\"] = \"ZodLiteral\";\n ZodFirstPartyTypeKind[\"ZodEnum\"] = \"ZodEnum\";\n ZodFirstPartyTypeKind[\"ZodEffects\"] = \"ZodEffects\";\n ZodFirstPartyTypeKind[\"ZodNativeEnum\"] = \"ZodNativeEnum\";\n ZodFirstPartyTypeKind[\"ZodOptional\"] = \"ZodOptional\";\n ZodFirstPartyTypeKind[\"ZodNullable\"] = \"ZodNullable\";\n ZodFirstPartyTypeKind[\"ZodDefault\"] = \"ZodDefault\";\n ZodFirstPartyTypeKind[\"ZodCatch\"] = \"ZodCatch\";\n ZodFirstPartyTypeKind[\"ZodPromise\"] = \"ZodPromise\";\n ZodFirstPartyTypeKind[\"ZodBranded\"] = \"ZodBranded\";\n ZodFirstPartyTypeKind[\"ZodPipeline\"] = \"ZodPipeline\";\n ZodFirstPartyTypeKind[\"ZodReadonly\"] = \"ZodReadonly\";\n})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));\nconst instanceOfType = (\n// const instanceOfType = any>(\ncls, params = {\n message: `Input not instance of ${cls.name}`,\n}) => custom((data) => data instanceof cls, params);\nconst stringType = ZodString.create;\nconst numberType = ZodNumber.create;\nconst nanType = ZodNaN.create;\nconst bigIntType = ZodBigInt.create;\nconst booleanType = ZodBoolean.create;\nconst dateType = ZodDate.create;\nconst symbolType = ZodSymbol.create;\nconst undefinedType = ZodUndefined.create;\nconst nullType = ZodNull.create;\nconst anyType = ZodAny.create;\nconst unknownType = ZodUnknown.create;\nconst neverType = ZodNever.create;\nconst voidType = ZodVoid.create;\nconst arrayType = ZodArray.create;\nconst objectType = ZodObject.create;\nconst strictObjectType = ZodObject.strictCreate;\nconst unionType = ZodUnion.create;\nconst discriminatedUnionType = ZodDiscriminatedUnion.create;\nconst intersectionType = ZodIntersection.create;\nconst tupleType = ZodTuple.create;\nconst recordType = ZodRecord.create;\nconst mapType = ZodMap.create;\nconst setType = ZodSet.create;\nconst functionType = ZodFunction.create;\nconst lazyType = ZodLazy.create;\nconst literalType = ZodLiteral.create;\nconst enumType = ZodEnum.create;\nconst nativeEnumType = ZodNativeEnum.create;\nconst promiseType = ZodPromise.create;\nconst effectsType = ZodEffects.create;\nconst optionalType = ZodOptional.create;\nconst nullableType = ZodNullable.create;\nconst preprocessType = ZodEffects.createWithPreprocess;\nconst pipelineType = ZodPipeline.create;\nconst ostring = () => stringType().optional();\nconst onumber = () => numberType().optional();\nconst oboolean = () => booleanType().optional();\nconst coerce = {\n string: ((arg) => ZodString.create({ ...arg, coerce: true })),\n number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),\n boolean: ((arg) => ZodBoolean.create({\n ...arg,\n coerce: true,\n })),\n bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),\n date: ((arg) => ZodDate.create({ ...arg, coerce: true })),\n};\nconst NEVER = INVALID;\n\nvar z = /*#__PURE__*/Object.freeze({\n __proto__: null,\n defaultErrorMap: errorMap,\n setErrorMap: setErrorMap,\n getErrorMap: getErrorMap,\n makeIssue: makeIssue,\n EMPTY_PATH: EMPTY_PATH,\n addIssueToContext: addIssueToContext,\n ParseStatus: ParseStatus,\n INVALID: INVALID,\n DIRTY: DIRTY,\n OK: OK,\n isAborted: isAborted,\n isDirty: isDirty,\n isValid: isValid,\n isAsync: isAsync,\n get util () { return util; },\n get objectUtil () { return objectUtil; },\n ZodParsedType: ZodParsedType,\n getParsedType: getParsedType,\n ZodType: ZodType,\n datetimeRegex: datetimeRegex,\n ZodString: ZodString,\n ZodNumber: ZodNumber,\n ZodBigInt: ZodBigInt,\n ZodBoolean: ZodBoolean,\n ZodDate: ZodDate,\n ZodSymbol: ZodSymbol,\n ZodUndefined: ZodUndefined,\n ZodNull: ZodNull,\n ZodAny: ZodAny,\n ZodUnknown: ZodUnknown,\n ZodNever: ZodNever,\n ZodVoid: ZodVoid,\n ZodArray: ZodArray,\n ZodObject: ZodObject,\n ZodUnion: ZodUnion,\n ZodDiscriminatedUnion: ZodDiscriminatedUnion,\n ZodIntersection: ZodIntersection,\n ZodTuple: ZodTuple,\n ZodRecord: ZodRecord,\n ZodMap: ZodMap,\n ZodSet: ZodSet,\n ZodFunction: ZodFunction,\n ZodLazy: ZodLazy,\n ZodLiteral: ZodLiteral,\n ZodEnum: ZodEnum,\n ZodNativeEnum: ZodNativeEnum,\n ZodPromise: ZodPromise,\n ZodEffects: ZodEffects,\n ZodTransformer: ZodEffects,\n ZodOptional: ZodOptional,\n ZodNullable: ZodNullable,\n ZodDefault: ZodDefault,\n ZodCatch: ZodCatch,\n ZodNaN: ZodNaN,\n BRAND: BRAND,\n ZodBranded: ZodBranded,\n ZodPipeline: ZodPipeline,\n ZodReadonly: ZodReadonly,\n custom: custom,\n Schema: ZodType,\n ZodSchema: ZodType,\n late: late,\n get ZodFirstPartyTypeKind () { return ZodFirstPartyTypeKind; },\n coerce: coerce,\n any: anyType,\n array: arrayType,\n bigint: bigIntType,\n boolean: booleanType,\n date: dateType,\n discriminatedUnion: discriminatedUnionType,\n effect: effectsType,\n 'enum': enumType,\n 'function': functionType,\n 'instanceof': instanceOfType,\n intersection: intersectionType,\n lazy: lazyType,\n literal: literalType,\n map: mapType,\n nan: nanType,\n nativeEnum: nativeEnumType,\n never: neverType,\n 'null': nullType,\n nullable: nullableType,\n number: numberType,\n object: objectType,\n oboolean: oboolean,\n onumber: onumber,\n optional: optionalType,\n ostring: ostring,\n pipeline: pipelineType,\n preprocess: preprocessType,\n promise: promiseType,\n record: recordType,\n set: setType,\n strictObject: strictObjectType,\n string: stringType,\n symbol: symbolType,\n transformer: effectsType,\n tuple: tupleType,\n 'undefined': undefinedType,\n union: unionType,\n unknown: unknownType,\n 'void': voidType,\n NEVER: NEVER,\n ZodIssueCode: ZodIssueCode,\n quotelessJson: quotelessJson,\n ZodError: ZodError\n});\n\nexport { BRAND, DIRTY, EMPTY_PATH, INVALID, NEVER, OK, ParseStatus, ZodType as Schema, ZodAny, ZodArray, ZodBigInt, ZodBoolean, ZodBranded, ZodCatch, ZodDate, ZodDefault, ZodDiscriminatedUnion, ZodEffects, ZodEnum, ZodError, ZodFirstPartyTypeKind, ZodFunction, ZodIntersection, ZodIssueCode, ZodLazy, ZodLiteral, ZodMap, ZodNaN, ZodNativeEnum, ZodNever, ZodNull, ZodNullable, ZodNumber, ZodObject, ZodOptional, ZodParsedType, ZodPipeline, ZodPromise, ZodReadonly, ZodRecord, ZodType as ZodSchema, ZodSet, ZodString, ZodSymbol, ZodEffects as ZodTransformer, ZodTuple, ZodType, ZodUndefined, ZodUnion, ZodUnknown, ZodVoid, addIssueToContext, anyType as any, arrayType as array, bigIntType as bigint, booleanType as boolean, coerce, custom, dateType as date, datetimeRegex, z as default, errorMap as defaultErrorMap, discriminatedUnionType as discriminatedUnion, effectsType as effect, enumType as enum, functionType as function, getErrorMap, getParsedType, instanceOfType as instanceof, intersectionType as intersection, isAborted, isAsync, isDirty, isValid, late, lazyType as lazy, literalType as literal, makeIssue, mapType as map, nanType as nan, nativeEnumType as nativeEnum, neverType as never, nullType as null, nullableType as nullable, numberType as number, objectType as object, objectUtil, oboolean, onumber, optionalType as optional, ostring, pipelineType as pipeline, preprocessType as preprocess, promiseType as promise, quotelessJson, recordType as record, setType as set, setErrorMap, strictObjectType as strictObject, stringType as string, symbolType as symbol, effectsType as transformer, tupleType as tuple, undefinedType as undefined, unionType as union, unknownType as unknown, util, voidType as void, z };\n","// lib/isZodErrorLike.ts\nfunction isZodErrorLike(err) {\n return err instanceof Error && err.name === \"ZodError\" && \"issues\" in err && Array.isArray(err.issues);\n}\n\n// lib/ValidationError.ts\nvar ValidationError = class extends Error {\n name;\n details;\n constructor(message, options) {\n super(message, options);\n this.name = \"ZodValidationError\";\n this.details = getIssuesFromErrorOptions(options);\n }\n toString() {\n return this.message;\n }\n};\nfunction getIssuesFromErrorOptions(options) {\n if (options) {\n const cause = options.cause;\n if (isZodErrorLike(cause)) {\n return cause.issues;\n }\n }\n return [];\n}\n\n// lib/isValidationError.ts\nfunction isValidationError(err) {\n return err instanceof ValidationError;\n}\n\n// lib/isValidationErrorLike.ts\nfunction isValidationErrorLike(err) {\n return err instanceof Error && err.name === \"ZodValidationError\";\n}\n\n// lib/fromZodIssue.ts\nimport * as zod from \"zod\";\n\n// lib/config.ts\nvar ISSUE_SEPARATOR = \"; \";\nvar MAX_ISSUES_IN_MESSAGE = 99;\nvar PREFIX = \"Validation error\";\nvar PREFIX_SEPARATOR = \": \";\nvar UNION_SEPARATOR = \", or \";\n\n// lib/prefixMessage.ts\nfunction prefixMessage(message, prefix, prefixSeparator) {\n if (prefix !== null) {\n if (message.length > 0) {\n return [prefix, message].join(prefixSeparator);\n }\n return prefix;\n }\n if (message.length > 0) {\n return message;\n }\n return PREFIX;\n}\n\n// lib/utils/joinPath.ts\nvar identifierRegex = /[$_\\p{ID_Start}][$\\u200c\\u200d\\p{ID_Continue}]*/u;\nfunction joinPath(path) {\n if (path.length === 1) {\n return path[0].toString();\n }\n return path.reduce((acc, item) => {\n if (typeof item === \"number\") {\n return acc + \"[\" + item.toString() + \"]\";\n }\n if (item.includes('\"')) {\n return acc + '[\"' + escapeQuotes(item) + '\"]';\n }\n if (!identifierRegex.test(item)) {\n return acc + '[\"' + item + '\"]';\n }\n const separator = acc.length === 0 ? \"\" : \".\";\n return acc + separator + item;\n }, \"\");\n}\nfunction escapeQuotes(str) {\n return str.replace(/\"/g, '\\\\\"');\n}\n\n// lib/utils/NonEmptyArray.ts\nfunction isNonEmptyArray(value) {\n return value.length !== 0;\n}\n\n// lib/fromZodIssue.ts\nfunction getMessageFromZodIssue(props) {\n const { issue, issueSeparator, unionSeparator, includePath } = props;\n if (issue.code === \"invalid_union\") {\n return issue.unionErrors.reduce((acc, zodError) => {\n const newIssues = zodError.issues.map(\n (issue2) => getMessageFromZodIssue({\n issue: issue2,\n issueSeparator,\n unionSeparator,\n includePath\n })\n ).join(issueSeparator);\n if (!acc.includes(newIssues)) {\n acc.push(newIssues);\n }\n return acc;\n }, []).join(unionSeparator);\n }\n if (issue.code === \"invalid_arguments\") {\n return [\n issue.message,\n ...issue.argumentsError.issues.map(\n (issue2) => getMessageFromZodIssue({\n issue: issue2,\n issueSeparator,\n unionSeparator,\n includePath\n })\n )\n ].join(issueSeparator);\n }\n if (issue.code === \"invalid_return_type\") {\n return [\n issue.message,\n ...issue.returnTypeError.issues.map(\n (issue2) => getMessageFromZodIssue({\n issue: issue2,\n issueSeparator,\n unionSeparator,\n includePath\n })\n )\n ].join(issueSeparator);\n }\n if (includePath && isNonEmptyArray(issue.path)) {\n if (issue.path.length === 1) {\n const identifier = issue.path[0];\n if (typeof identifier === \"number\") {\n return `${issue.message} at index ${identifier}`;\n }\n }\n return `${issue.message} at \"${joinPath(issue.path)}\"`;\n }\n return issue.message;\n}\nfunction fromZodIssue(issue, options = {}) {\n const {\n issueSeparator = ISSUE_SEPARATOR,\n unionSeparator = UNION_SEPARATOR,\n prefixSeparator = PREFIX_SEPARATOR,\n prefix = PREFIX,\n includePath = true\n } = options;\n const reason = getMessageFromZodIssue({\n issue,\n issueSeparator,\n unionSeparator,\n includePath\n });\n const message = prefixMessage(reason, prefix, prefixSeparator);\n return new ValidationError(message, { cause: new zod.ZodError([issue]) });\n}\n\n// lib/errorMap.ts\nvar errorMap = (issue, ctx) => {\n const error = fromZodIssue({\n ...issue,\n // fallback to the default error message\n // when issue does not have a message\n message: issue.message ?? ctx.defaultError\n });\n return {\n message: error.message\n };\n};\n\n// lib/fromZodError.ts\nfunction fromZodError(zodError, options = {}) {\n if (!isZodErrorLike(zodError)) {\n throw new TypeError(\n `Invalid zodError param; expected instance of ZodError. Did you mean to use the \"${fromError.name}\" method instead?`\n );\n }\n return fromZodErrorWithoutRuntimeCheck(zodError, options);\n}\nfunction fromZodErrorWithoutRuntimeCheck(zodError, options = {}) {\n const {\n maxIssuesInMessage = MAX_ISSUES_IN_MESSAGE,\n issueSeparator = ISSUE_SEPARATOR,\n unionSeparator = UNION_SEPARATOR,\n prefixSeparator = PREFIX_SEPARATOR,\n prefix = PREFIX,\n includePath = true\n } = options;\n const zodIssues = zodError.errors;\n const reason = zodIssues.length === 0 ? zodError.message : zodIssues.slice(0, maxIssuesInMessage).map(\n (issue) => getMessageFromZodIssue({\n issue,\n issueSeparator,\n unionSeparator,\n includePath\n })\n ).join(issueSeparator);\n const message = prefixMessage(reason, prefix, prefixSeparator);\n return new ValidationError(message, { cause: zodError });\n}\n\n// lib/toValidationError.ts\nvar toValidationError = (options = {}) => (err) => {\n if (isZodErrorLike(err)) {\n return fromZodErrorWithoutRuntimeCheck(err, options);\n }\n if (err instanceof Error) {\n return new ValidationError(err.message, { cause: err });\n }\n return new ValidationError(\"Unknown error\");\n};\n\n// lib/fromError.ts\nfunction fromError(err, options = {}) {\n return toValidationError(options)(err);\n}\nexport {\n ValidationError,\n errorMap,\n fromError,\n fromZodError,\n fromZodIssue,\n isValidationError,\n isValidationErrorLike,\n isZodErrorLike,\n toValidationError\n};\n//# sourceMappingURL=index.mjs.map","import { z } from 'zod'\r\nimport { fromZodError } from 'zod-validation-error'\r\n\r\n// GroupNode is hacking node id to be a string, so we need to allow that.\r\n// innerNode.id = `${this.node.id}:${i}`\r\n// Remove it after GroupNode is redesigned.\r\nexport const zNodeId = z.union([z.number().int(), z.string()])\r\nexport const zSlotIndex = z.union([\r\n z.number().int(),\r\n z\r\n .string()\r\n .transform((val) => parseInt(val))\r\n .refine((val) => !isNaN(val), {\r\n message: 'Invalid number'\r\n })\r\n])\r\n\r\n// TODO: Investigate usage of array and number as data type usage in custom nodes.\r\n// Known usage:\r\n// - https://github.com/rgthree/rgthree-comfy Context Big node is using array as type.\r\nexport const zDataType = z.union([z.string(), z.array(z.string()), z.number()])\r\n\r\n// Definition of an AI model file used in the workflow.\r\nconst zModelFile = z.object({\r\n name: z.string(),\r\n url: z.string().url(),\r\n hash: z.string(),\r\n hash_type: z.string(),\r\n directory: z.string()\r\n})\r\n\r\nconst zComfyLink = z.tuple([\r\n z.number(), // Link id\r\n zNodeId, // Node id of source node\r\n zSlotIndex, // Output slot# of source node\r\n zNodeId, // Node id of destination node\r\n zSlotIndex, // Input slot# of destination node\r\n zDataType // Data type\r\n])\r\n\r\nconst zNodeOutput = z\r\n .object({\r\n name: z.string(),\r\n type: zDataType,\r\n links: z.array(z.number()).nullable().optional(),\r\n slot_index: zSlotIndex.optional()\r\n })\r\n .passthrough()\r\n\r\nconst zNodeInput = z\r\n .object({\r\n name: z.string(),\r\n type: zDataType,\r\n link: z.number().nullable().optional(),\r\n slot_index: zSlotIndex.optional()\r\n })\r\n .passthrough()\r\n\r\nconst zFlags = z\r\n .object({\r\n collapsed: z.boolean().optional(),\r\n pinned: z.boolean().optional(),\r\n allow_interaction: z.boolean().optional(),\r\n horizontal: z.boolean().optional(),\r\n skip_repeated_outputs: z.boolean().optional()\r\n })\r\n .passthrough()\r\n\r\nconst zProperties = z\r\n .object({\r\n ['Node name for S&R']: z.string().optional()\r\n })\r\n .passthrough()\r\n\r\nconst zVector2 = z.union([\r\n z.object({ 0: z.number(), 1: z.number() }).transform((v) => [v[0], v[1]]),\r\n z.tuple([z.number(), z.number()])\r\n])\r\n\r\nconst zWidgetValues = z.union([z.array(z.any()), z.record(z.any())])\r\n\r\nconst zComfyNode = z\r\n .object({\r\n id: zNodeId,\r\n type: z.string(),\r\n pos: zVector2,\r\n size: zVector2,\r\n flags: zFlags,\r\n order: z.number(),\r\n mode: z.number(),\r\n inputs: z.array(zNodeInput).optional(),\r\n outputs: z.array(zNodeOutput).optional(),\r\n properties: zProperties,\r\n widgets_values: zWidgetValues.optional(),\r\n color: z.string().optional(),\r\n bgcolor: z.string().optional()\r\n })\r\n .passthrough()\r\n\r\nconst zGroup = z\r\n .object({\r\n title: z.string(),\r\n bounding: z.tuple([z.number(), z.number(), z.number(), z.number()]),\r\n color: z.string().optional(),\r\n font_size: z.number().optional(),\r\n locked: z.boolean().optional()\r\n })\r\n .passthrough()\r\n\r\nconst zInfo = z\r\n .object({\r\n name: z.string(),\r\n author: z.string(),\r\n description: z.string(),\r\n version: z.string(),\r\n created: z.string(),\r\n modified: z.string(),\r\n software: z.string()\r\n })\r\n .passthrough()\r\n\r\nconst zDS = z\r\n .object({\r\n scale: z.number(),\r\n offset: zVector2\r\n })\r\n .passthrough()\r\n\r\nconst zConfig = z\r\n .object({\r\n links_ontop: z.boolean().optional(),\r\n align_to_grid: z.boolean().optional()\r\n })\r\n .passthrough()\r\n\r\nconst zExtra = z\r\n .object({\r\n ds: zDS.optional(),\r\n info: zInfo.optional()\r\n })\r\n .passthrough()\r\n\r\nexport const zComfyWorkflow = z\r\n .object({\r\n last_node_id: zNodeId,\r\n last_link_id: z.number(),\r\n nodes: z.array(zComfyNode),\r\n links: z.array(zComfyLink),\r\n groups: z.array(zGroup).optional(),\r\n config: zConfig.optional().nullable(),\r\n extra: zExtra.optional().nullable(),\r\n version: z.number(),\r\n models: z.array(zModelFile).optional()\r\n })\r\n .passthrough()\r\n\r\nexport type NodeInput = z.infer\r\nexport type NodeOutput = z.infer\r\nexport type ComfyLink = z.infer\r\nexport type ComfyNode = z.infer\r\nexport type ComfyWorkflowJSON = z.infer\r\n\r\nexport async function validateComfyWorkflow(\r\n data: any,\r\n onError: (error: string) => void = console.warn\r\n): Promise {\r\n const result = await zComfyWorkflow.safeParseAsync(data)\r\n if (!result.success) {\r\n const error = fromZodError(result.error)\r\n onError(`Invalid workflow against zod schema:\\n${error}`)\r\n return null\r\n }\r\n return result.data\r\n}\r\n","import { ZodType, z } from 'zod'\r\nimport { zComfyWorkflow, zNodeId } from './comfyWorkflow'\r\nimport { fromZodError } from 'zod-validation-error'\r\n\r\nconst zNodeType = z.string()\r\nconst zQueueIndex = z.number()\r\nconst zPromptId = z.string()\r\nconst zImageResult = z.object({\r\n filename: z.string(),\r\n subfolder: z.string().optional(),\r\n type: z.string()\r\n})\r\n\r\n// WS messages\r\nconst zStatusWsMessageStatus = z.object({\r\n exec_info: z.object({\r\n queue_remaining: z.number().int()\r\n })\r\n})\r\n\r\nconst zStatusWsMessage = z.object({\r\n status: zStatusWsMessageStatus.nullable().optional()\r\n})\r\n\r\nconst zProgressWsMessage = z.object({\r\n value: z.number().int(),\r\n max: z.number().int(),\r\n prompt_id: zPromptId,\r\n node: zNodeId\r\n})\r\n\r\nconst zExecutingWsMessage = z.object({\r\n node: zNodeId,\r\n display_node: zNodeId,\r\n prompt_id: zPromptId\r\n})\r\n\r\nconst zExecutedWsMessage = zExecutingWsMessage.extend({\r\n outputs: z\r\n .object({\r\n images: z.array(zImageResult)\r\n })\r\n .passthrough()\r\n})\r\n\r\nconst zExecutionWsMessageBase = z.object({\r\n prompt_id: zPromptId,\r\n timestamp: z.number().int()\r\n})\r\n\r\nconst zExecutionStartWsMessage = zExecutionWsMessageBase\r\nconst zExecutionSuccessWsMessage = zExecutionWsMessageBase\r\nconst zExecutionCachedWsMessage = zExecutionWsMessageBase.extend({\r\n nodes: z.array(zNodeId)\r\n})\r\nconst zExecutionInterruptedWsMessage = zExecutionWsMessageBase.extend({\r\n node_id: zNodeId,\r\n node_type: zNodeType,\r\n executed: z.array(zNodeId)\r\n})\r\nconst zExecutionErrorWsMessage = zExecutionWsMessageBase.extend({\r\n node_id: zNodeId,\r\n node_type: zNodeType,\r\n executed: z.array(zNodeId),\r\n exception_message: z.string(),\r\n exception_type: z.string(),\r\n traceback: z.string(),\r\n current_inputs: z.any(),\r\n current_outputs: z.any()\r\n})\r\n\r\nexport type StatusWsMessageStatus = z.infer\r\nexport type StatusWsMessage = z.infer\r\nexport type ProgressWsMessage = z.infer\r\nexport type ExecutingWsMessage = z.infer\r\nexport type ExecutedWsMessage = z.infer\r\nexport type ExecutionStartWsMessage = z.infer\r\nexport type ExecutionSuccessWsMessage = z.infer<\r\n typeof zExecutionSuccessWsMessage\r\n>\r\nexport type ExecutionCachedWsMessage = z.infer\r\nexport type ExecutionInterruptedWsMessage = z.infer<\r\n typeof zExecutionInterruptedWsMessage\r\n>\r\nexport type ExecutionErrorWsMessage = z.infer\r\n// End of ws messages\r\n\r\nconst zPromptInputItem = z.object({\r\n inputs: z.record(z.string(), z.any()),\r\n class_type: zNodeType\r\n})\r\n\r\nconst zPromptInputs = z.record(zPromptInputItem)\r\n\r\nconst zExtraPngInfo = z\r\n .object({\r\n workflow: zComfyWorkflow\r\n })\r\n .passthrough()\r\n\r\nconst zExtraData = z.object({\r\n extra_pnginfo: zExtraPngInfo,\r\n client_id: z.string()\r\n})\r\nconst zOutputsToExecute = z.array(zNodeId)\r\n\r\nconst zExecutionStartMessage = z.tuple([\r\n z.literal('execution_start'),\r\n zExecutionStartWsMessage\r\n])\r\n\r\nconst zExecutionSuccessMessage = z.tuple([\r\n z.literal('execution_success'),\r\n zExecutionSuccessWsMessage\r\n])\r\n\r\nconst zExecutionCachedMessage = z.tuple([\r\n z.literal('execution_cached'),\r\n zExecutionCachedWsMessage\r\n])\r\n\r\nconst zExecutionInterruptedMessage = z.tuple([\r\n z.literal('execution_interrupted'),\r\n zExecutionInterruptedWsMessage\r\n])\r\n\r\nconst zExecutionErrorMessage = z.tuple([\r\n z.literal('execution_error'),\r\n zExecutionErrorWsMessage\r\n])\r\n\r\nconst zStatusMessage = z.union([\r\n zExecutionStartMessage,\r\n zExecutionSuccessMessage,\r\n zExecutionCachedMessage,\r\n zExecutionInterruptedMessage,\r\n zExecutionErrorMessage\r\n])\r\n\r\nconst zStatus = z.object({\r\n status_str: z.enum(['success', 'error']),\r\n completed: z.boolean(),\r\n messages: z.array(zStatusMessage)\r\n})\r\n\r\n// TODO: this is a placeholder\r\nconst zOutput = z.any()\r\n\r\nconst zTaskPrompt = z.tuple([\r\n zQueueIndex,\r\n zPromptId,\r\n zPromptInputs,\r\n zExtraData,\r\n zOutputsToExecute\r\n])\r\n\r\nconst zRunningTaskItem = z.object({\r\n taskType: z.literal('Running'),\r\n prompt: zTaskPrompt,\r\n // @Deprecated\r\n remove: z.object({\r\n name: z.literal('Cancel'),\r\n cb: z.function()\r\n })\r\n})\r\n\r\nconst zPendingTaskItem = z.object({\r\n taskType: z.literal('Pending'),\r\n prompt: zTaskPrompt\r\n})\r\n\r\nconst zTaskOutput = z.record(zNodeId, zOutput)\r\n\r\nconst zHistoryTaskItem = z.object({\r\n taskType: z.literal('History'),\r\n prompt: zTaskPrompt,\r\n status: zStatus.optional(),\r\n outputs: zTaskOutput\r\n})\r\n\r\nconst zTaskItem = z.union([\r\n zRunningTaskItem,\r\n zPendingTaskItem,\r\n zHistoryTaskItem\r\n])\r\n\r\nconst zTaskType = z.union([\r\n z.literal('Running'),\r\n z.literal('Pending'),\r\n z.literal('History')\r\n])\r\n\r\nexport type TaskType = z.infer\r\nexport type TaskPrompt = z.infer\r\nexport type TaskStatus = z.infer\r\nexport type TaskOutput = z.infer\r\n\r\n// `/queue`\r\nexport type RunningTaskItem = z.infer\r\nexport type PendingTaskItem = z.infer\r\n// `/history`\r\nexport type HistoryTaskItem = z.infer\r\nexport type TaskItem = z.infer\r\n\r\nexport function validateTaskItem(taskItem: unknown) {\r\n const result = zTaskItem.safeParse(taskItem)\r\n if (!result.success) {\r\n const zodError = fromZodError(result.error)\r\n // TODO accept a callback to report error.\r\n console.warn(\r\n `Invalid TaskItem: ${JSON.stringify(taskItem)}\\n${zodError.message}`\r\n )\r\n }\r\n return result\r\n}\r\n\r\nfunction inputSpec(\r\n spec: [ZodType, ZodType],\r\n allowUpcast: boolean = true\r\n): ZodType {\r\n const [inputType, inputSpec] = spec\r\n // e.g. \"INT\" => [\"INT\", {}]\r\n const upcastTypes: ZodType[] = allowUpcast\r\n ? [inputType.transform((type) => [type, {}])]\r\n : []\r\n\r\n return z.union([\r\n z.tuple([inputType, inputSpec]),\r\n z.tuple([inputType]).transform(([type]) => [type, {}]),\r\n ...upcastTypes\r\n ])\r\n}\r\n\r\nconst zBaseInputSpecValue = z\r\n .object({\r\n default: z.any().optional(),\r\n forceInput: z.boolean().optional()\r\n })\r\n .passthrough()\r\n\r\nconst zIntInputSpec = inputSpec([\r\n z.literal('INT'),\r\n zBaseInputSpecValue.extend({\r\n min: z.number().optional(),\r\n max: z.number().optional(),\r\n step: z.number().optional(),\r\n // Note: Many node authors are using INT to pass list of INT.\r\n // TODO: Add list of ints type.\r\n default: z.union([z.number(), z.array(z.number())]).optional()\r\n })\r\n])\r\n\r\nconst zFloatInputSpec = inputSpec([\r\n z.literal('FLOAT'),\r\n zBaseInputSpecValue.extend({\r\n min: z.number().optional(),\r\n max: z.number().optional(),\r\n step: z.number().optional(),\r\n round: z.union([z.number(), z.literal(false)]).optional(),\r\n // Note: Many node authors are using FLOAT to pass list of FLOAT.\r\n // TODO: Add list of floats type.\r\n default: z.union([z.number(), z.array(z.number())]).optional()\r\n })\r\n])\r\n\r\nconst zBooleanInputSpec = inputSpec([\r\n z.literal('BOOLEAN'),\r\n zBaseInputSpecValue.extend({\r\n label_on: z.string().optional(),\r\n label_off: z.string().optional(),\r\n default: z.boolean().optional()\r\n })\r\n])\r\n\r\nconst zStringInputSpec = inputSpec([\r\n z.literal('STRING'),\r\n zBaseInputSpecValue.extend({\r\n default: z.string().optional(),\r\n multiline: z.boolean().optional(),\r\n dynamicPrompts: z.boolean().optional()\r\n })\r\n])\r\n\r\n// Dropdown Selection.\r\nconst zComboInputSpec = inputSpec(\r\n [\r\n z.array(z.any()),\r\n zBaseInputSpecValue.extend({\r\n control_after_generate: z.boolean().optional(),\r\n image_upload: z.boolean().optional()\r\n })\r\n ],\r\n /* allowUpcast=*/ false\r\n)\r\n\r\nconst excludedLiterals = new Set(['INT', 'FLOAT', 'BOOLEAN', 'STRING', 'COMBO'])\r\n\r\nconst zCustomInputSpec = inputSpec([\r\n z.string().refine((value) => !excludedLiterals.has(value)),\r\n zBaseInputSpecValue\r\n])\r\n\r\nconst zInputSpec = z.union([\r\n zIntInputSpec,\r\n zFloatInputSpec,\r\n zBooleanInputSpec,\r\n zStringInputSpec,\r\n zComboInputSpec,\r\n zCustomInputSpec\r\n])\r\n\r\nconst zComfyInputsSpec = z.object({\r\n required: z.record(zInputSpec).optional(),\r\n optional: z.record(zInputSpec).optional(),\r\n // Frontend repo is not using it, but some custom nodes are using the\r\n // hidden field to pass various values.\r\n hidden: z.record(z.any()).optional()\r\n})\r\n\r\nconst zComfyNodeDataType = z.string()\r\nconst zComfyComboOutput = z.array(z.any())\r\nconst zComfyOutputTypesSpec = z.array(\r\n z.union([zComfyNodeDataType, zComfyComboOutput])\r\n)\r\n\r\nconst zComfyNodeDef = z.object({\r\n input: zComfyInputsSpec,\r\n output: zComfyOutputTypesSpec,\r\n output_is_list: z.array(z.boolean()),\r\n output_name: z.array(z.string()),\r\n output_tooltips: z.array(z.string()).optional(),\r\n name: z.string(),\r\n display_name: z.string(),\r\n description: z.string(),\r\n category: z.string(),\r\n output_node: z.boolean(),\r\n python_module: z.string()\r\n})\r\n\r\n// `/object_info`\r\nexport type ComfyInputsSpec = z.infer\r\nexport type ComfyOutputTypesSpec = z.infer\r\nexport type ComfyNodeDef = z.infer\r\n\r\nexport function validateComfyNodeDef(\r\n data: any,\r\n onError: (error: string) => void = console.warn\r\n): ComfyNodeDef | null {\r\n const result = zComfyNodeDef.safeParse(data)\r\n if (!result.success) {\r\n const zodError = fromZodError(result.error)\r\n onError(\r\n `Invalid ComfyNodeDef: ${JSON.stringify(data)}\\n${zodError.message}`\r\n )\r\n return null\r\n }\r\n return result.data\r\n}\r\n","import { ComfyWorkflowJSON } from '@/types/comfyWorkflow'\r\nimport {\r\n HistoryTaskItem,\r\n PendingTaskItem,\r\n RunningTaskItem,\r\n ComfyNodeDef,\r\n validateComfyNodeDef\r\n} from '@/types/apiTypes'\r\n\r\ninterface QueuePromptRequestBody {\r\n client_id: string\r\n // Mapping from node id to node info + input values\r\n // TODO: Type this.\r\n prompt: Record\r\n extra_data: {\r\n extra_pnginfo: {\r\n workflow: ComfyWorkflowJSON\r\n }\r\n }\r\n front?: boolean\r\n number?: number\r\n}\r\n\r\nclass ComfyApi extends EventTarget {\r\n #registered = new Set()\r\n api_host: string\r\n api_base: string\r\n initialClientId: string\r\n user: string\r\n socket?: WebSocket\r\n clientId?: string\r\n\r\n reportedUnknownMessageTypes = new Set()\r\n\r\n constructor() {\r\n super()\r\n this.api_host = location.host\r\n this.api_base = location.pathname.split('/').slice(0, -1).join('/')\r\n this.initialClientId = sessionStorage.getItem('clientId')\r\n }\r\n\r\n apiURL(route: string): string {\r\n return this.api_base + '/api' + route\r\n }\r\n\r\n fileURL(route: string): string {\r\n return this.api_base + route\r\n }\r\n\r\n fetchApi(route, options?) {\r\n if (!options) {\r\n options = {}\r\n }\r\n if (!options.headers) {\r\n options.headers = {}\r\n }\r\n if (!options.cache) {\r\n options.cache = 'no-cache'\r\n }\r\n options.headers['Comfy-User'] = this.user\r\n return fetch(this.apiURL(route), options)\r\n }\r\n\r\n addEventListener(type, callback, options?) {\r\n super.addEventListener(type, callback, options)\r\n this.#registered.add(type)\r\n }\r\n\r\n /**\r\n * Poll status for colab and other things that don't support websockets.\r\n */\r\n #pollQueue() {\r\n setInterval(async () => {\r\n try {\r\n const resp = await this.fetchApi('/prompt')\r\n const status = await resp.json()\r\n this.dispatchEvent(new CustomEvent('status', { detail: status }))\r\n } catch (error) {\r\n this.dispatchEvent(new CustomEvent('status', { detail: null }))\r\n }\r\n }, 1000)\r\n }\r\n\r\n /**\r\n * Creates and connects a WebSocket for realtime updates\r\n * @param {boolean} isReconnect If the socket is connection is a reconnect attempt\r\n */\r\n #createSocket(isReconnect?) {\r\n if (this.socket) {\r\n return\r\n }\r\n\r\n let opened = false\r\n let existingSession = window.name\r\n if (existingSession) {\r\n existingSession = '?clientId=' + existingSession\r\n }\r\n this.socket = new WebSocket(\r\n `ws${window.location.protocol === 'https:' ? 's' : ''}://${this.api_host}${this.api_base}/ws${existingSession}`\r\n )\r\n this.socket.binaryType = 'arraybuffer'\r\n\r\n this.socket.addEventListener('open', () => {\r\n opened = true\r\n if (isReconnect) {\r\n this.dispatchEvent(new CustomEvent('reconnected'))\r\n }\r\n })\r\n\r\n this.socket.addEventListener('error', () => {\r\n if (this.socket) this.socket.close()\r\n if (!isReconnect && !opened) {\r\n this.#pollQueue()\r\n }\r\n })\r\n\r\n this.socket.addEventListener('close', () => {\r\n setTimeout(() => {\r\n this.socket = null\r\n this.#createSocket(true)\r\n }, 300)\r\n if (opened) {\r\n this.dispatchEvent(new CustomEvent('status', { detail: null }))\r\n this.dispatchEvent(new CustomEvent('reconnecting'))\r\n }\r\n })\r\n\r\n this.socket.addEventListener('message', (event) => {\r\n try {\r\n if (event.data instanceof ArrayBuffer) {\r\n const view = new DataView(event.data)\r\n const eventType = view.getUint32(0)\r\n const buffer = event.data.slice(4)\r\n switch (eventType) {\r\n case 1:\r\n const view2 = new DataView(event.data)\r\n const imageType = view2.getUint32(0)\r\n let imageMime\r\n switch (imageType) {\r\n case 1:\r\n default:\r\n imageMime = 'image/jpeg'\r\n break\r\n case 2:\r\n imageMime = 'image/png'\r\n }\r\n const imageBlob = new Blob([buffer.slice(4)], {\r\n type: imageMime\r\n })\r\n this.dispatchEvent(\r\n new CustomEvent('b_preview', { detail: imageBlob })\r\n )\r\n break\r\n default:\r\n throw new Error(\r\n `Unknown binary websocket message of type ${eventType}`\r\n )\r\n }\r\n } else {\r\n const msg = JSON.parse(event.data)\r\n switch (msg.type) {\r\n case 'status':\r\n if (msg.data.sid) {\r\n this.clientId = msg.data.sid\r\n window.name = this.clientId // use window name so it isnt reused when duplicating tabs\r\n sessionStorage.setItem('clientId', this.clientId) // store in session storage so duplicate tab can load correct workflow\r\n }\r\n this.dispatchEvent(\r\n new CustomEvent('status', { detail: msg.data.status })\r\n )\r\n break\r\n case 'progress':\r\n this.dispatchEvent(\r\n new CustomEvent('progress', { detail: msg.data })\r\n )\r\n break\r\n case 'executing':\r\n this.dispatchEvent(\r\n new CustomEvent('executing', {\r\n detail: msg.data.display_node || msg.data.node\r\n })\r\n )\r\n break\r\n case 'executed':\r\n this.dispatchEvent(\r\n new CustomEvent('executed', { detail: msg.data })\r\n )\r\n break\r\n case 'execution_start':\r\n this.dispatchEvent(\r\n new CustomEvent('execution_start', { detail: msg.data })\r\n )\r\n break\r\n case 'execution_success':\r\n this.dispatchEvent(\r\n new CustomEvent('execution_success', { detail: msg.data })\r\n )\r\n break\r\n case 'execution_error':\r\n this.dispatchEvent(\r\n new CustomEvent('execution_error', { detail: msg.data })\r\n )\r\n break\r\n case 'execution_cached':\r\n this.dispatchEvent(\r\n new CustomEvent('execution_cached', { detail: msg.data })\r\n )\r\n break\r\n default:\r\n if (this.#registered.has(msg.type)) {\r\n this.dispatchEvent(\r\n new CustomEvent(msg.type, { detail: msg.data })\r\n )\r\n } else if (!this.reportedUnknownMessageTypes.has(msg.type)) {\r\n this.reportedUnknownMessageTypes.add(msg.type)\r\n throw new Error(`Unknown message type ${msg.type}`)\r\n }\r\n }\r\n }\r\n } catch (error) {\r\n console.warn('Unhandled message:', event.data, error)\r\n }\r\n })\r\n }\r\n\r\n /**\r\n * Initialises sockets and realtime updates\r\n */\r\n init() {\r\n this.#createSocket()\r\n }\r\n\r\n /**\r\n * Gets a list of extension urls\r\n * @returns An array of script urls to import\r\n */\r\n async getExtensions() {\r\n const resp = await this.fetchApi('/extensions', { cache: 'no-store' })\r\n return await resp.json()\r\n }\r\n\r\n /**\r\n * Gets a list of embedding names\r\n * @returns An array of script urls to import\r\n */\r\n async getEmbeddings() {\r\n const resp = await this.fetchApi('/embeddings', { cache: 'no-store' })\r\n return await resp.json()\r\n }\r\n\r\n /**\r\n * Loads node object definitions for the graph\r\n * @returns The node definitions\r\n */\r\n async getNodeDefs(): Promise> {\r\n const resp = await this.fetchApi('/object_info', { cache: 'no-store' })\r\n const objectInfoUnsafe = await resp.json()\r\n const objectInfo: Record = {}\r\n for (const key in objectInfoUnsafe) {\r\n const validatedDef = validateComfyNodeDef(\r\n objectInfoUnsafe[key],\r\n /* onError=*/ (errorMessage: string) => {\r\n console.warn(\r\n `Skipping invalid node definition: ${key}. See debug log for more information.`\r\n )\r\n console.debug(errorMessage)\r\n }\r\n )\r\n if (validatedDef !== null) {\r\n objectInfo[key] = validatedDef\r\n }\r\n }\r\n return objectInfo\r\n }\r\n\r\n /**\r\n *\r\n * @param {number} number The index at which to queue the prompt, passing -1 will insert the prompt at the front of the queue\r\n * @param {object} prompt The prompt data to queue\r\n */\r\n async queuePrompt(number: number, { output, workflow }) {\r\n const body: QueuePromptRequestBody = {\r\n client_id: this.clientId,\r\n prompt: output,\r\n extra_data: { extra_pnginfo: { workflow } }\r\n }\r\n\r\n if (number === -1) {\r\n body.front = true\r\n } else if (number != 0) {\r\n body.number = number\r\n }\r\n\r\n const res = await this.fetchApi('/prompt', {\r\n method: 'POST',\r\n headers: {\r\n 'Content-Type': 'application/json'\r\n },\r\n body: JSON.stringify(body)\r\n })\r\n\r\n if (res.status !== 200) {\r\n throw {\r\n response: await res.json()\r\n }\r\n }\r\n\r\n return await res.json()\r\n }\r\n\r\n /**\r\n * Loads a list of items (queue or history)\r\n * @param {string} type The type of items to load, queue or history\r\n * @returns The items of the specified type grouped by their status\r\n */\r\n async getItems(type) {\r\n if (type === 'queue') {\r\n return this.getQueue()\r\n }\r\n return this.getHistory()\r\n }\r\n\r\n /**\r\n * Gets the current state of the queue\r\n * @returns The currently running and queued items\r\n */\r\n async getQueue(): Promise<{\r\n Running: RunningTaskItem[]\r\n Pending: PendingTaskItem[]\r\n }> {\r\n try {\r\n const res = await this.fetchApi('/queue')\r\n const data = await res.json()\r\n return {\r\n // Running action uses a different endpoint for cancelling\r\n Running: data.queue_running.map((prompt) => ({\r\n taskType: 'Running',\r\n prompt,\r\n remove: { name: 'Cancel', cb: () => api.interrupt() }\r\n })),\r\n Pending: data.queue_pending.map((prompt) => ({\r\n taskType: 'Pending',\r\n prompt\r\n }))\r\n }\r\n } catch (error) {\r\n console.error(error)\r\n return { Running: [], Pending: [] }\r\n }\r\n }\r\n\r\n /**\r\n * Gets the prompt execution history\r\n * @returns Prompt history including node outputs\r\n */\r\n async getHistory(\r\n max_items: number = 200\r\n ): Promise<{ History: HistoryTaskItem[] }> {\r\n try {\r\n const res = await this.fetchApi(`/history?max_items=${max_items}`)\r\n return {\r\n History: Object.values(await res.json()).map(\r\n (item: HistoryTaskItem) => ({ ...item, taskType: 'History' })\r\n )\r\n }\r\n } catch (error) {\r\n console.error(error)\r\n return { History: [] }\r\n }\r\n }\r\n\r\n /**\r\n * Gets system & device stats\r\n * @returns System stats such as python version, OS, per device info\r\n */\r\n async getSystemStats() {\r\n const res = await this.fetchApi('/system_stats')\r\n return await res.json()\r\n }\r\n\r\n /**\r\n * Sends a POST request to the API\r\n * @param {*} type The endpoint to post to\r\n * @param {*} body Optional POST data\r\n */\r\n async #postItem(type, body) {\r\n try {\r\n await this.fetchApi('/' + type, {\r\n method: 'POST',\r\n headers: {\r\n 'Content-Type': 'application/json'\r\n },\r\n body: body ? JSON.stringify(body) : undefined\r\n })\r\n } catch (error) {\r\n console.error(error)\r\n }\r\n }\r\n\r\n /**\r\n * Deletes an item from the specified list\r\n * @param {string} type The type of item to delete, queue or history\r\n * @param {number} id The id of the item to delete\r\n */\r\n async deleteItem(type, id) {\r\n await this.#postItem(type, { delete: [id] })\r\n }\r\n\r\n /**\r\n * Clears the specified list\r\n * @param {string} type The type of list to clear, queue or history\r\n */\r\n async clearItems(type) {\r\n await this.#postItem(type, { clear: true })\r\n }\r\n\r\n /**\r\n * Interrupts the execution of the running prompt\r\n */\r\n async interrupt() {\r\n await this.#postItem('interrupt', null)\r\n }\r\n\r\n /**\r\n * Gets user configuration data and where data should be stored\r\n * @returns { Promise<{ storage: \"server\" | \"browser\", users?: Promise, migrated?: boolean }> }\r\n */\r\n async getUserConfig() {\r\n return (await this.fetchApi('/users')).json()\r\n }\r\n\r\n /**\r\n * Creates a new user\r\n * @param { string } username\r\n * @returns The fetch response\r\n */\r\n createUser(username) {\r\n return this.fetchApi('/users', {\r\n method: 'POST',\r\n headers: {\r\n 'Content-Type': 'application/json'\r\n },\r\n body: JSON.stringify({ username })\r\n })\r\n }\r\n\r\n /**\r\n * Gets all setting values for the current user\r\n * @returns { Promise } A dictionary of id -> value\r\n */\r\n async getSettings() {\r\n return (await this.fetchApi('/settings')).json()\r\n }\r\n\r\n /**\r\n * Gets a setting for the current user\r\n * @param { string } id The id of the setting to fetch\r\n * @returns { Promise } The setting value\r\n */\r\n async getSetting(id) {\r\n return (await this.fetchApi(`/settings/${encodeURIComponent(id)}`)).json()\r\n }\r\n\r\n /**\r\n * Stores a dictionary of settings for the current user\r\n * @param { Record } settings Dictionary of setting id -> value to save\r\n * @returns { Promise }\r\n */\r\n async storeSettings(settings) {\r\n return this.fetchApi(`/settings`, {\r\n method: 'POST',\r\n body: JSON.stringify(settings)\r\n })\r\n }\r\n\r\n /**\r\n * Stores a setting for the current user\r\n * @param { string } id The id of the setting to update\r\n * @param { unknown } value The value of the setting\r\n * @returns { Promise }\r\n */\r\n async storeSetting(id, value) {\r\n return this.fetchApi(`/settings/${encodeURIComponent(id)}`, {\r\n method: 'POST',\r\n body: JSON.stringify(value)\r\n })\r\n }\r\n\r\n /**\r\n * Gets a user data file for the current user\r\n * @param { string } file The name of the userdata file to load\r\n * @param { RequestInit } [options]\r\n * @returns { Promise } The fetch response object\r\n */\r\n async getUserData(file, options?) {\r\n return this.fetchApi(`/userdata/${encodeURIComponent(file)}`, options)\r\n }\r\n\r\n /**\r\n * Stores a user data file for the current user\r\n * @param { string } file The name of the userdata file to save\r\n * @param { unknown } data The data to save to the file\r\n * @param { RequestInit & { stringify?: boolean, throwOnError?: boolean } } [options]\r\n * @returns { Promise }\r\n */\r\n async storeUserData(\r\n file: string,\r\n data: unknown,\r\n options: RequestInit & {\r\n overwrite?: boolean\r\n stringify?: boolean\r\n throwOnError?: boolean\r\n } = { overwrite: true, stringify: true, throwOnError: true }\r\n ): Promise {\r\n const resp = await this.fetchApi(\r\n `/userdata/${encodeURIComponent(file)}?overwrite=${options.overwrite}`,\r\n {\r\n method: 'POST',\r\n body: options?.stringify ? JSON.stringify(data) : data,\r\n ...options\r\n }\r\n )\r\n if (resp.status !== 200 && options.throwOnError !== false) {\r\n throw new Error(\r\n `Error storing user data file '${file}': ${resp.status} ${(await resp).statusText}`\r\n )\r\n }\r\n\r\n return resp\r\n }\r\n\r\n /**\r\n * Deletes a user data file for the current user\r\n * @param { string } file The name of the userdata file to delete\r\n */\r\n async deleteUserData(file) {\r\n const resp = await this.fetchApi(`/userdata/${encodeURIComponent(file)}`, {\r\n method: 'DELETE'\r\n })\r\n if (resp.status !== 204) {\r\n throw new Error(\r\n `Error removing user data file '${file}': ${resp.status} ${resp.statusText}`\r\n )\r\n }\r\n }\r\n\r\n /**\r\n * Move a user data file for the current user\r\n * @param { string } source The userdata file to move\r\n * @param { string } dest The destination for the file\r\n */\r\n async moveUserData(source, dest, options = { overwrite: false }) {\r\n const resp = await this.fetchApi(\r\n `/userdata/${encodeURIComponent(source)}/move/${encodeURIComponent(dest)}?overwrite=${options?.overwrite}`,\r\n {\r\n method: 'POST'\r\n }\r\n )\r\n return resp\r\n }\r\n\r\n /**\r\n * @overload\r\n * Lists user data files for the current user\r\n * @param { string } dir The directory in which to list files\r\n * @param { boolean } [recurse] If the listing should be recursive\r\n * @param { true } [split] If the paths should be split based on the os path separator\r\n * @returns { Promise> } The list of split file paths in the format [fullPath, ...splitPath]\r\n */\r\n /**\r\n * @overload\r\n * Lists user data files for the current user\r\n * @param { string } dir The directory in which to list files\r\n * @param { boolean } [recurse] If the listing should be recursive\r\n * @param { false | undefined } [split] If the paths should be split based on the os path separator\r\n * @returns { Promise } The list of files\r\n */\r\n async listUserData(dir, recurse, split) {\r\n const resp = await this.fetchApi(\r\n `/userdata?${new URLSearchParams({\r\n recurse,\r\n dir,\r\n split\r\n })}`\r\n )\r\n if (resp.status === 404) return []\r\n if (resp.status !== 200) {\r\n throw new Error(\r\n `Error getting user data list '${dir}': ${resp.status} ${resp.statusText}`\r\n )\r\n }\r\n return resp.json()\r\n }\r\n}\r\n\r\nexport const api = new ComfyApi()\r\n","import { useDialogStore } from '@/stores/dialogStore'\r\nimport { $el } from '../ui'\r\n\r\nexport class ComfyDialog<\r\n T extends HTMLElement = HTMLElement\r\n> extends EventTarget {\r\n element: T\r\n textElement: HTMLElement\r\n #buttons: HTMLButtonElement[] | null\r\n\r\n constructor(type = 'div', buttons = null) {\r\n super()\r\n this.#buttons = buttons\r\n this.element = $el(type + '.comfy-modal', { parent: document.body }, [\r\n $el('div.comfy-modal-content', [\r\n $el('p', { $: (p) => (this.textElement = p) }),\r\n ...this.createButtons()\r\n ])\r\n ]) as T\r\n }\r\n\r\n createButtons() {\r\n return (\r\n this.#buttons ?? [\r\n $el('button', {\r\n type: 'button',\r\n textContent: 'Close',\r\n onclick: () => this.close()\r\n })\r\n ]\r\n )\r\n }\r\n\r\n close() {\r\n this.element.style.display = 'none'\r\n }\r\n\r\n show(html) {\r\n if (typeof html === 'string') {\r\n this.textElement.innerHTML = html\r\n } else {\r\n this.textElement.replaceChildren(\r\n ...(html instanceof Array ? html : [html])\r\n )\r\n }\r\n this.element.style.display = 'flex'\r\n }\r\n}\r\n","import { $el } from '../ui'\r\n\r\n/**\r\n * @typedef { { text: string, value?: string, tooltip?: string } } ToggleSwitchItem\r\n */\r\n/**\r\n * Creates a toggle switch element\r\n * @param { string } name\r\n * @param { Array | ToggleSwitchItem } items\r\n * @param { Object } [opts]\r\n * @param { (e: { item: ToggleSwitchItem, prev?: ToggleSwitchItem }) => void } [opts.onChange]\r\n */\r\nexport function toggleSwitch(name, items, e?) {\r\n const onChange = e?.onChange\r\n\r\n let selectedIndex\r\n let elements\r\n\r\n function updateSelected(index) {\r\n if (selectedIndex != null) {\r\n elements[selectedIndex].classList.remove('comfy-toggle-selected')\r\n }\r\n onChange?.({\r\n item: items[index],\r\n prev: selectedIndex == null ? undefined : items[selectedIndex]\r\n })\r\n selectedIndex = index\r\n elements[selectedIndex].classList.add('comfy-toggle-selected')\r\n }\r\n\r\n elements = items.map((item, i) => {\r\n if (typeof item === 'string') item = { text: item }\r\n if (!item.value) item.value = item.text\r\n\r\n const toggle = $el(\r\n 'label',\r\n {\r\n textContent: item.text,\r\n title: item.tooltip ?? ''\r\n },\r\n $el('input', {\r\n name,\r\n type: 'radio',\r\n value: item.value ?? item.text,\r\n checked: item.selected,\r\n onchange: () => {\r\n updateSelected(i)\r\n }\r\n })\r\n )\r\n if (item.selected) {\r\n updateSelected(i)\r\n }\r\n return toggle\r\n })\r\n\r\n const container = $el('div.comfy-toggle-switch', elements)\r\n\r\n if (selectedIndex == null) {\r\n elements[0].children[0].checked = true\r\n updateSelected(0)\r\n }\r\n\r\n return container\r\n}\r\n","import { $el } from '../ui'\r\nimport { api } from '../api'\r\nimport { ComfyDialog } from './dialog'\r\nimport type { ComfyApp } from '../app'\r\nimport type { Setting, SettingParams } from '@/types/settingTypes'\r\nimport { useSettingStore } from '@/stores/settingStore'\r\n\r\nexport class ComfySettingsDialog extends ComfyDialog {\r\n app: ComfyApp\r\n settingsValues: any\r\n settingsLookup: Record\r\n settingsParamLookup: Record\r\n\r\n constructor(app: ComfyApp) {\r\n super()\r\n const frontendVersion = window['__COMFYUI_FRONTEND_VERSION__']\r\n this.app = app\r\n this.settingsValues = {}\r\n this.settingsLookup = {}\r\n this.settingsParamLookup = {}\r\n this.element = $el(\r\n 'dialog',\r\n {\r\n id: 'comfy-settings-dialog',\r\n parent: document.body\r\n },\r\n [\r\n $el('table.comfy-modal-content.comfy-table', [\r\n $el(\r\n 'caption',\r\n { textContent: `Settings (v${frontendVersion})` },\r\n $el('button.comfy-btn', {\r\n type: 'button',\r\n textContent: '\\u00d7',\r\n onclick: () => {\r\n this.element.close()\r\n }\r\n })\r\n ),\r\n $el('tbody', { $: (tbody) => (this.textElement = tbody) }),\r\n $el('button', {\r\n type: 'button',\r\n textContent: 'Close',\r\n style: {\r\n cursor: 'pointer'\r\n },\r\n onclick: () => {\r\n this.element.close()\r\n }\r\n })\r\n ])\r\n ]\r\n ) as HTMLDialogElement\r\n }\r\n\r\n get settings() {\r\n return Object.values(this.settingsLookup)\r\n }\r\n\r\n #dispatchChange(id: string, value: T, oldValue?: T) {\r\n // Keep the settingStore updated. Not using `store.set` as it would trigger\r\n // setSettingValue again.\r\n // `load` re-dispatch the change for any settings added before load so\r\n // settingStore is always up to date.\r\n if (this.app.vueAppReady) {\r\n useSettingStore().settingValues[id] = value\r\n }\r\n\r\n this.dispatchEvent(\r\n new CustomEvent(id + '.change', {\r\n detail: {\r\n value,\r\n oldValue\r\n }\r\n })\r\n )\r\n }\r\n\r\n async load() {\r\n if (this.app.storageLocation === 'browser') {\r\n this.settingsValues = localStorage\r\n } else {\r\n this.settingsValues = await api.getSettings()\r\n }\r\n\r\n // Trigger onChange for any settings added before load\r\n for (const id in this.settingsLookup) {\r\n const value = this.settingsValues[this.getId(id)]\r\n this.settingsLookup[id].onChange?.(value)\r\n this.#dispatchChange(id, value)\r\n }\r\n }\r\n\r\n getId(id: string) {\r\n if (this.app.storageLocation === 'browser') {\r\n id = 'Comfy.Settings.' + id\r\n }\r\n return id\r\n }\r\n\r\n getSettingValue(id: string, defaultValue?: T): T {\r\n let value = this.settingsValues[this.getId(id)]\r\n if (value != null) {\r\n if (this.app.storageLocation === 'browser') {\r\n try {\r\n value = JSON.parse(value) as T\r\n } catch (error) {}\r\n }\r\n }\r\n return value ?? defaultValue\r\n }\r\n\r\n getSettingDefaultValue(id: string) {\r\n const param = this.settingsParamLookup[id]\r\n return param?.defaultValue\r\n }\r\n\r\n async setSettingValueAsync(id: string, value: any) {\r\n const json = JSON.stringify(value)\r\n localStorage['Comfy.Settings.' + id] = json // backwards compatibility for extensions keep setting in storage\r\n\r\n let oldValue = this.getSettingValue(id, undefined)\r\n this.settingsValues[this.getId(id)] = value\r\n\r\n if (id in this.settingsLookup) {\r\n this.settingsLookup[id].onChange?.(value, oldValue)\r\n }\r\n this.#dispatchChange(id, value, oldValue)\r\n\r\n await api.storeSetting(id, value)\r\n }\r\n\r\n setSettingValue(id: string, value: any) {\r\n this.setSettingValueAsync(id, value).catch((err) => {\r\n alert(`Error saving setting '${id}'`)\r\n console.error(err)\r\n })\r\n }\r\n\r\n refreshSetting(id: string) {\r\n const value = this.getSettingValue(id)\r\n this.settingsLookup[id].onChange?.(value)\r\n this.#dispatchChange(id, value)\r\n }\r\n\r\n addSetting(params: SettingParams) {\r\n const {\r\n id,\r\n name,\r\n type,\r\n defaultValue,\r\n onChange,\r\n attrs = {},\r\n tooltip = '',\r\n options = undefined\r\n } = params\r\n if (!id) {\r\n throw new Error('Settings must have an ID')\r\n }\r\n\r\n if (id in this.settingsLookup) {\r\n throw new Error(`Setting ${id} of type ${type} must have a unique ID.`)\r\n }\r\n\r\n let skipOnChange = false\r\n let value = this.getSettingValue(id)\r\n if (value == null) {\r\n if (this.app.isNewUserSession) {\r\n // Check if we have a localStorage value but not a setting value and we are a new user\r\n const localValue = localStorage['Comfy.Settings.' + id]\r\n if (localValue) {\r\n value = JSON.parse(localValue)\r\n this.setSettingValue(id, value) // Store on the server\r\n }\r\n }\r\n if (value == null) {\r\n value = defaultValue\r\n }\r\n }\r\n\r\n // Trigger initial setting of value\r\n if (!skipOnChange) {\r\n onChange?.(value, undefined)\r\n this.#dispatchChange(id, value)\r\n }\r\n\r\n this.settingsParamLookup[id] = params\r\n if (this.app.vueAppReady) {\r\n useSettingStore().settings[id] = params\r\n }\r\n this.settingsLookup[id] = {\r\n id,\r\n onChange,\r\n name,\r\n render: () => {\r\n if (type === 'hidden') return\r\n\r\n const setter = (v) => {\r\n if (onChange) {\r\n onChange(v, value)\r\n }\r\n\r\n this.setSettingValue(id, v)\r\n value = v\r\n }\r\n value = this.getSettingValue(id, defaultValue)\r\n\r\n let element\r\n const htmlID = id.replaceAll('.', '-')\r\n\r\n const labelCell = $el('td', [\r\n $el('label', {\r\n for: htmlID,\r\n classList: [tooltip !== '' ? 'comfy-tooltip-indicator' : ''],\r\n textContent: name\r\n })\r\n ])\r\n\r\n if (typeof type === 'function') {\r\n element = type(name, setter, value, attrs)\r\n } else {\r\n switch (type) {\r\n case 'boolean':\r\n element = $el('tr', [\r\n labelCell,\r\n $el('td', [\r\n $el('input', {\r\n id: htmlID,\r\n type: 'checkbox',\r\n checked: value,\r\n onchange: (event) => {\r\n const isChecked = event.target.checked\r\n if (onChange !== undefined) {\r\n onChange(isChecked)\r\n }\r\n this.setSettingValue(id, isChecked)\r\n }\r\n })\r\n ])\r\n ])\r\n break\r\n case 'number':\r\n element = $el('tr', [\r\n labelCell,\r\n $el('td', [\r\n $el('input', {\r\n type,\r\n value,\r\n id: htmlID,\r\n oninput: (e) => {\r\n setter(e.target.value)\r\n },\r\n ...attrs\r\n })\r\n ])\r\n ])\r\n break\r\n case 'slider':\r\n element = $el('tr', [\r\n labelCell,\r\n $el('td', [\r\n $el(\r\n 'div',\r\n {\r\n style: {\r\n display: 'grid',\r\n gridAutoFlow: 'column'\r\n }\r\n },\r\n [\r\n $el('input', {\r\n ...attrs,\r\n value,\r\n type: 'range',\r\n oninput: (e) => {\r\n setter(e.target.value)\r\n e.target.nextElementSibling.value = e.target.value\r\n }\r\n }),\r\n $el('input', {\r\n ...attrs,\r\n value,\r\n id: htmlID,\r\n type: 'number',\r\n style: { maxWidth: '4rem' },\r\n oninput: (e) => {\r\n setter(e.target.value)\r\n e.target.previousElementSibling.value = e.target.value\r\n }\r\n })\r\n ]\r\n )\r\n ])\r\n ])\r\n break\r\n case 'combo':\r\n element = $el('tr', [\r\n labelCell,\r\n $el('td', [\r\n $el(\r\n 'select',\r\n {\r\n oninput: (e) => {\r\n setter(e.target.value)\r\n }\r\n },\r\n (typeof options === 'function'\r\n ? options(value)\r\n : options || []\r\n ).map((opt) => {\r\n if (typeof opt === 'string') {\r\n opt = { text: opt }\r\n }\r\n const v = opt.value ?? opt.text\r\n return $el('option', {\r\n value: v,\r\n textContent: opt.text,\r\n selected: value + '' === v + ''\r\n })\r\n })\r\n )\r\n ])\r\n ])\r\n break\r\n case 'text':\r\n default:\r\n if (type !== 'text') {\r\n console.warn(\r\n `Unsupported setting type '${type}, defaulting to text`\r\n )\r\n }\r\n\r\n element = $el('tr', [\r\n labelCell,\r\n $el('td', [\r\n $el('input', {\r\n value,\r\n id: htmlID,\r\n oninput: (e) => {\r\n setter(e.target.value)\r\n },\r\n ...attrs\r\n })\r\n ])\r\n ])\r\n break\r\n }\r\n }\r\n if (tooltip) {\r\n element.title = tooltip\r\n }\r\n\r\n return element\r\n }\r\n } as Setting\r\n\r\n const self = this\r\n return {\r\n get value() {\r\n return self.getSettingValue(id, defaultValue)\r\n },\r\n set value(v) {\r\n self.setSettingValue(id, v)\r\n }\r\n }\r\n }\r\n\r\n show() {\r\n this.textElement.replaceChildren(\r\n $el(\r\n 'tr',\r\n {\r\n style: { display: 'none' }\r\n },\r\n [$el('th'), $el('th', { style: { width: '33%' } })]\r\n ),\r\n ...this.settings\r\n .sort((a, b) => a.name.localeCompare(b.name))\r\n .map((s) => s.render())\r\n .filter(Boolean)\r\n )\r\n this.element.showModal()\r\n }\r\n}\r\n","import { api } from './api'\r\nimport { ComfyDialog as _ComfyDialog } from './ui/dialog'\r\nimport { toggleSwitch } from './ui/toggleSwitch'\r\nimport { ComfySettingsDialog } from './ui/settings'\r\nimport { ComfyApp, app } from './app'\r\nimport { StatusWsMessageStatus, TaskItem } from '@/types/apiTypes'\r\n\r\nexport const ComfyDialog = _ComfyDialog\r\n\r\ntype Position2D = {\r\n x: number\r\n y: number\r\n}\r\n\r\ntype Props = {\r\n parent?: HTMLElement\r\n $?: (el: HTMLElement) => void\r\n dataset?: DOMStringMap\r\n style?: Partial\r\n for?: string\r\n textContent?: string\r\n [key: string]: any\r\n}\r\n\r\ntype Children = Element[] | Element | string | string[]\r\n\r\ntype ElementType = K extends keyof HTMLElementTagNameMap\r\n ? HTMLElementTagNameMap[K]\r\n : HTMLElement\r\n\r\nexport function $el(\r\n tag: TTag,\r\n propsOrChildren?: Children | Props,\r\n children?: Children\r\n): ElementType {\r\n const split = tag.split('.')\r\n const element = document.createElement(split.shift() as string)\r\n if (split.length > 0) {\r\n element.classList.add(...split)\r\n }\r\n\r\n if (propsOrChildren) {\r\n if (typeof propsOrChildren === 'string') {\r\n propsOrChildren = { textContent: propsOrChildren }\r\n } else if (propsOrChildren instanceof Element) {\r\n propsOrChildren = [propsOrChildren]\r\n }\r\n if (Array.isArray(propsOrChildren)) {\r\n element.append(...propsOrChildren)\r\n } else {\r\n const {\r\n parent,\r\n $: cb,\r\n dataset,\r\n style,\r\n ...rest\r\n } = propsOrChildren as Props\r\n\r\n if (rest.for) {\r\n element.setAttribute('for', rest.for)\r\n }\r\n\r\n if (style) {\r\n Object.assign(element.style, style)\r\n }\r\n\r\n if (dataset) {\r\n Object.assign(element.dataset, dataset)\r\n }\r\n\r\n Object.assign(element, rest)\r\n if (children) {\r\n element.append(...(Array.isArray(children) ? children : [children]))\r\n }\r\n\r\n if (parent) {\r\n parent.append(element)\r\n }\r\n\r\n if (cb) {\r\n cb(element)\r\n }\r\n }\r\n }\r\n return element as ElementType\r\n}\r\n\r\nfunction dragElement(dragEl, settings): () => void {\r\n var posDiffX = 0,\r\n posDiffY = 0,\r\n posStartX = 0,\r\n posStartY = 0,\r\n newPosX = 0,\r\n newPosY = 0\r\n if (dragEl.getElementsByClassName('drag-handle')[0]) {\r\n // if present, the handle is where you move the DIV from:\r\n dragEl.getElementsByClassName('drag-handle')[0].onmousedown = dragMouseDown\r\n } else {\r\n // otherwise, move the DIV from anywhere inside the DIV:\r\n dragEl.onmousedown = dragMouseDown\r\n }\r\n\r\n // When the element resizes (e.g. view queue) ensure it is still in the windows bounds\r\n const resizeObserver = new ResizeObserver(() => {\r\n ensureInBounds()\r\n }).observe(dragEl)\r\n\r\n function ensureInBounds() {\r\n try {\r\n newPosX = Math.min(\r\n document.body.clientWidth - dragEl.clientWidth,\r\n Math.max(0, dragEl.offsetLeft)\r\n )\r\n newPosY = Math.min(\r\n document.body.clientHeight - dragEl.clientHeight,\r\n Math.max(0, dragEl.offsetTop)\r\n )\r\n\r\n positionElement()\r\n } catch (exception) {\r\n // robust\r\n }\r\n }\r\n\r\n function positionElement() {\r\n if (dragEl.style.display === 'none') return\r\n\r\n const halfWidth = document.body.clientWidth / 2\r\n const anchorRight = newPosX + dragEl.clientWidth / 2 > halfWidth\r\n\r\n // set the element's new position:\r\n if (anchorRight) {\r\n dragEl.style.left = 'unset'\r\n dragEl.style.right =\r\n document.body.clientWidth - newPosX - dragEl.clientWidth + 'px'\r\n } else {\r\n dragEl.style.left = newPosX + 'px'\r\n dragEl.style.right = 'unset'\r\n }\r\n\r\n dragEl.style.top = newPosY + 'px'\r\n dragEl.style.bottom = 'unset'\r\n\r\n if (savePos) {\r\n localStorage.setItem(\r\n 'Comfy.MenuPosition',\r\n JSON.stringify({\r\n x: dragEl.offsetLeft,\r\n y: dragEl.offsetTop\r\n })\r\n )\r\n }\r\n }\r\n\r\n function restorePos() {\r\n let posString = localStorage.getItem('Comfy.MenuPosition')\r\n if (posString) {\r\n const pos = JSON.parse(posString) as Position2D\r\n newPosX = pos.x\r\n newPosY = pos.y\r\n positionElement()\r\n ensureInBounds()\r\n }\r\n }\r\n\r\n let savePos = undefined\r\n settings.addSetting({\r\n id: 'Comfy.MenuPosition',\r\n name: 'Save menu position',\r\n type: 'boolean',\r\n defaultValue: savePos,\r\n onChange(value) {\r\n if (savePos === undefined && value) {\r\n restorePos()\r\n }\r\n savePos = value\r\n }\r\n })\r\n\r\n function dragMouseDown(e) {\r\n e = e || window.event\r\n e.preventDefault()\r\n // get the mouse cursor position at startup:\r\n posStartX = e.clientX\r\n posStartY = e.clientY\r\n document.onmouseup = closeDragElement\r\n // call a function whenever the cursor moves:\r\n document.onmousemove = elementDrag\r\n }\r\n\r\n function elementDrag(e) {\r\n e = e || window.event\r\n e.preventDefault()\r\n\r\n dragEl.classList.add('comfy-menu-manual-pos')\r\n\r\n // calculate the new cursor position:\r\n posDiffX = e.clientX - posStartX\r\n posDiffY = e.clientY - posStartY\r\n posStartX = e.clientX\r\n posStartY = e.clientY\r\n\r\n newPosX = Math.min(\r\n document.body.clientWidth - dragEl.clientWidth,\r\n Math.max(0, dragEl.offsetLeft + posDiffX)\r\n )\r\n newPosY = Math.min(\r\n document.body.clientHeight - dragEl.clientHeight,\r\n Math.max(0, dragEl.offsetTop + posDiffY)\r\n )\r\n\r\n positionElement()\r\n }\r\n\r\n window.addEventListener('resize', () => {\r\n ensureInBounds()\r\n })\r\n\r\n function closeDragElement() {\r\n // stop moving when mouse button is released:\r\n document.onmouseup = null\r\n document.onmousemove = null\r\n }\r\n\r\n return restorePos\r\n}\r\n\r\nclass ComfyList {\r\n #type\r\n #text\r\n #reverse\r\n element: HTMLDivElement\r\n button?: HTMLButtonElement\r\n\r\n constructor(text, type?, reverse?) {\r\n this.#text = text\r\n this.#type = type || text.toLowerCase()\r\n this.#reverse = reverse || false\r\n this.element = $el('div.comfy-list') as HTMLDivElement\r\n this.element.style.display = 'none'\r\n }\r\n\r\n get visible() {\r\n return this.element.style.display !== 'none'\r\n }\r\n\r\n async load() {\r\n const items = await api.getItems(this.#type)\r\n this.element.replaceChildren(\r\n ...Object.keys(items).flatMap((section) => [\r\n $el('h4', {\r\n textContent: section\r\n }),\r\n $el('div.comfy-list-items', [\r\n ...(this.#reverse ? items[section].reverse() : items[section]).map(\r\n (item: TaskItem) => {\r\n // Allow items to specify a custom remove action (e.g. for interrupt current prompt)\r\n const removeAction =\r\n 'remove' in item\r\n ? item.remove\r\n : {\r\n name: 'Delete',\r\n cb: () => api.deleteItem(this.#type, item.prompt[1])\r\n }\r\n return $el('div', { textContent: item.prompt[0] + ': ' }, [\r\n $el('button', {\r\n textContent: 'Load',\r\n onclick: async () => {\r\n await app.loadGraphData(\r\n item.prompt[3].extra_pnginfo.workflow,\r\n true,\r\n false\r\n )\r\n if ('outputs' in item) {\r\n app.nodeOutputs = {}\r\n for (const [key, value] of Object.entries(item.outputs)) {\r\n const realKey = item['meta']?.[key]?.display_node ?? key\r\n app.nodeOutputs[realKey] = value\r\n }\r\n }\r\n }\r\n }),\r\n $el('button', {\r\n textContent: removeAction.name,\r\n onclick: async () => {\r\n await removeAction.cb()\r\n await this.update()\r\n }\r\n })\r\n ])\r\n }\r\n )\r\n ])\r\n ]),\r\n $el('div.comfy-list-actions', [\r\n $el('button', {\r\n textContent: 'Clear ' + this.#text,\r\n onclick: async () => {\r\n await api.clearItems(this.#type)\r\n await this.load()\r\n }\r\n }),\r\n $el('button', { textContent: 'Refresh', onclick: () => this.load() })\r\n ])\r\n )\r\n }\r\n\r\n async update() {\r\n if (this.visible) {\r\n await this.load()\r\n }\r\n }\r\n\r\n async show() {\r\n this.element.style.display = 'block'\r\n this.button.textContent = 'Close'\r\n\r\n await this.load()\r\n }\r\n\r\n hide() {\r\n this.element.style.display = 'none'\r\n this.button.textContent = 'View ' + this.#text\r\n }\r\n\r\n toggle() {\r\n if (this.visible) {\r\n this.hide()\r\n return false\r\n } else {\r\n this.show()\r\n return true\r\n }\r\n }\r\n}\r\n\r\nexport class ComfyUI {\r\n app: ComfyApp\r\n dialog: _ComfyDialog\r\n settings: ComfySettingsDialog\r\n batchCount: number\r\n lastQueueSize: number\r\n queue: ComfyList\r\n history: ComfyList\r\n autoQueueMode: string\r\n graphHasChanged: boolean\r\n autoQueueEnabled: boolean\r\n menuHamburger: HTMLDivElement\r\n menuContainer: HTMLDivElement\r\n queueSize: Element\r\n restoreMenuPosition: () => void\r\n loadFile: () => void\r\n\r\n constructor(app) {\r\n this.app = app\r\n this.dialog = new ComfyDialog()\r\n this.settings = new ComfySettingsDialog(app)\r\n\r\n this.batchCount = 1\r\n this.lastQueueSize = 0\r\n this.queue = new ComfyList('Queue')\r\n this.history = new ComfyList('History', 'history', true)\r\n\r\n api.addEventListener('status', () => {\r\n this.queue.update()\r\n this.history.update()\r\n })\r\n\r\n const confirmClear = this.settings.addSetting({\r\n id: 'Comfy.ConfirmClear',\r\n name: 'Require confirmation when clearing workflow',\r\n type: 'boolean',\r\n defaultValue: true\r\n })\r\n\r\n const promptFilename = this.settings.addSetting({\r\n id: 'Comfy.PromptFilename',\r\n name: 'Prompt for filename when saving workflow',\r\n type: 'boolean',\r\n defaultValue: true\r\n })\r\n\r\n /**\r\n * file format for preview\r\n *\r\n * format;quality\r\n *\r\n * ex)\r\n * webp;50 -> webp, quality 50\r\n * jpeg;80 -> rgb, jpeg, quality 80\r\n *\r\n * @type {string}\r\n */\r\n const previewImage = this.settings.addSetting({\r\n id: 'Comfy.PreviewFormat',\r\n name: 'When displaying a preview in the image widget, convert it to a lightweight image, e.g. webp, jpeg, webp;50, etc.',\r\n type: 'text',\r\n defaultValue: ''\r\n })\r\n\r\n this.settings.addSetting({\r\n id: 'Comfy.DisableSliders',\r\n name: 'Disable sliders.',\r\n type: 'boolean',\r\n defaultValue: false\r\n })\r\n\r\n this.settings.addSetting({\r\n id: 'Comfy.DisableFloatRounding',\r\n name: 'Disable rounding floats (requires page reload).',\r\n type: 'boolean',\r\n defaultValue: false\r\n })\r\n\r\n this.settings.addSetting({\r\n id: 'Comfy.FloatRoundingPrecision',\r\n name: 'Decimal places [0 = auto] (requires page reload).',\r\n type: 'slider',\r\n attrs: {\r\n min: 0,\r\n max: 6,\r\n step: 1\r\n },\r\n defaultValue: 0\r\n })\r\n\r\n this.settings.addSetting({\r\n id: 'Comfy.EnableTooltips',\r\n name: 'Enable Tooltips',\r\n type: 'boolean',\r\n defaultValue: true\r\n })\r\n\r\n const fileInput = $el('input', {\r\n id: 'comfy-file-input',\r\n type: 'file',\r\n accept: '.json,image/png,.latent,.safetensors,image/webp,audio/flac',\r\n style: { display: 'none' },\r\n parent: document.body,\r\n onchange: () => {\r\n app.handleFile(fileInput.files[0])\r\n }\r\n })\r\n\r\n this.loadFile = () => fileInput.click()\r\n\r\n const autoQueueModeEl = toggleSwitch(\r\n 'autoQueueMode',\r\n [\r\n {\r\n text: 'instant',\r\n tooltip: 'A new prompt will be queued as soon as the queue reaches 0'\r\n },\r\n {\r\n text: 'change',\r\n tooltip:\r\n 'A new prompt will be queued when the queue is at 0 and the graph is/has changed'\r\n }\r\n ],\r\n {\r\n onChange: (value) => {\r\n this.autoQueueMode = value.item.value\r\n }\r\n }\r\n )\r\n autoQueueModeEl.style.display = 'none'\r\n\r\n api.addEventListener('graphChanged', () => {\r\n if (this.autoQueueMode === 'change' && this.autoQueueEnabled === true) {\r\n if (this.lastQueueSize === 0) {\r\n this.graphHasChanged = false\r\n app.queuePrompt(0, this.batchCount)\r\n } else {\r\n this.graphHasChanged = true\r\n }\r\n }\r\n })\r\n\r\n this.menuHamburger = $el(\r\n 'div.comfy-menu-hamburger',\r\n {\r\n parent: document.body,\r\n onclick: () => {\r\n this.menuContainer.style.display = 'block'\r\n this.menuHamburger.style.display = 'none'\r\n }\r\n },\r\n [$el('div'), $el('div'), $el('div')]\r\n ) as HTMLDivElement\r\n\r\n this.menuContainer = $el('div.comfy-menu', { parent: document.body }, [\r\n $el(\r\n 'div.drag-handle.comfy-menu-header',\r\n {\r\n style: {\r\n overflow: 'hidden',\r\n position: 'relative',\r\n width: '100%',\r\n cursor: 'default'\r\n }\r\n },\r\n [\r\n $el('span.drag-handle'),\r\n $el('span.comfy-menu-queue-size', { $: (q) => (this.queueSize = q) }),\r\n $el('div.comfy-menu-actions', [\r\n $el('button.comfy-settings-btn', {\r\n textContent: '⚙️',\r\n onclick: () => this.settings.show()\r\n }),\r\n $el('button.comfy-close-menu-btn', {\r\n textContent: '\\u00d7',\r\n onclick: () => {\r\n this.menuContainer.style.display = 'none'\r\n this.menuHamburger.style.display = 'flex'\r\n }\r\n })\r\n ])\r\n ]\r\n ),\r\n $el('button.comfy-queue-btn', {\r\n id: 'queue-button',\r\n textContent: 'Queue Prompt',\r\n onclick: () => app.queuePrompt(0, this.batchCount)\r\n }),\r\n $el('div', {}, [\r\n $el('label', { innerHTML: 'Extra options' }, [\r\n $el('input', {\r\n type: 'checkbox',\r\n onchange: (i) => {\r\n document.getElementById('extraOptions').style.display = i\r\n .srcElement.checked\r\n ? 'block'\r\n : 'none'\r\n this.batchCount = i.srcElement.checked\r\n ? Number.parseInt(\r\n (\r\n document.getElementById(\r\n 'batchCountInputRange'\r\n ) as HTMLInputElement\r\n ).value\r\n )\r\n : 1\r\n ;(\r\n document.getElementById('autoQueueCheckbox') as HTMLInputElement\r\n ).checked = false\r\n this.autoQueueEnabled = false\r\n }\r\n })\r\n ])\r\n ]),\r\n $el(\r\n 'div',\r\n { id: 'extraOptions', style: { width: '100%', display: 'none' } },\r\n [\r\n $el('div', [\r\n $el('label', { innerHTML: 'Batch count' }),\r\n $el('input', {\r\n id: 'batchCountInputNumber',\r\n type: 'number',\r\n value: this.batchCount,\r\n min: '1',\r\n style: { width: '35%', marginLeft: '0.4em' },\r\n oninput: (i) => {\r\n this.batchCount = i.target.value\r\n /* Even though an element with a type of range logically represents a number (since\r\n it's used for numeric input), the value it holds is still treated as a string in HTML and\r\n JavaScript. This behavior is consistent across all elements regardless of their type\r\n (like text, number, or range), where the .value property is always a string. */\r\n ;(\r\n document.getElementById(\r\n 'batchCountInputRange'\r\n ) as HTMLInputElement\r\n ).value = this.batchCount.toString()\r\n }\r\n }),\r\n $el('input', {\r\n id: 'batchCountInputRange',\r\n type: 'range',\r\n min: '1',\r\n max: '100',\r\n value: this.batchCount,\r\n oninput: (i) => {\r\n this.batchCount = i.srcElement.value\r\n // Note\r\n ;(\r\n document.getElementById(\r\n 'batchCountInputNumber'\r\n ) as HTMLInputElement\r\n ).value = i.srcElement.value\r\n }\r\n })\r\n ]),\r\n $el('div', [\r\n $el('label', {\r\n for: 'autoQueueCheckbox',\r\n innerHTML: 'Auto Queue'\r\n }),\r\n $el('input', {\r\n id: 'autoQueueCheckbox',\r\n type: 'checkbox',\r\n checked: false,\r\n title: 'Automatically queue prompt when the queue size hits 0',\r\n onchange: (e) => {\r\n this.autoQueueEnabled = e.target.checked\r\n autoQueueModeEl.style.display = this.autoQueueEnabled\r\n ? ''\r\n : 'none'\r\n }\r\n }),\r\n autoQueueModeEl\r\n ])\r\n ]\r\n ),\r\n $el('div.comfy-menu-btns', [\r\n $el('button', {\r\n id: 'queue-front-button',\r\n textContent: 'Queue Front',\r\n onclick: () => app.queuePrompt(-1, this.batchCount)\r\n }),\r\n $el('button', {\r\n $: (b) => (this.queue.button = b as HTMLButtonElement),\r\n id: 'comfy-view-queue-button',\r\n textContent: 'View Queue',\r\n onclick: () => {\r\n this.history.hide()\r\n this.queue.toggle()\r\n }\r\n }),\r\n $el('button', {\r\n $: (b) => (this.history.button = b as HTMLButtonElement),\r\n id: 'comfy-view-history-button',\r\n textContent: 'View History',\r\n onclick: () => {\r\n this.queue.hide()\r\n this.history.toggle()\r\n }\r\n })\r\n ]),\r\n this.queue.element,\r\n this.history.element,\r\n $el('button', {\r\n id: 'comfy-save-button',\r\n textContent: 'Save',\r\n onclick: () => {\r\n let filename = 'workflow.json'\r\n if (promptFilename.value) {\r\n filename = prompt('Save workflow as:', filename)\r\n if (!filename) return\r\n if (!filename.toLowerCase().endsWith('.json')) {\r\n filename += '.json'\r\n }\r\n }\r\n app.graphToPrompt().then((p) => {\r\n const json = JSON.stringify(p.workflow, null, 2) // convert the data to a JSON string\r\n const blob = new Blob([json], { type: 'application/json' })\r\n const url = URL.createObjectURL(blob)\r\n const a = $el('a', {\r\n href: url,\r\n download: filename,\r\n style: { display: 'none' },\r\n parent: document.body\r\n })\r\n a.click()\r\n setTimeout(function () {\r\n a.remove()\r\n window.URL.revokeObjectURL(url)\r\n }, 0)\r\n })\r\n }\r\n }),\r\n $el('button', {\r\n id: 'comfy-dev-save-api-button',\r\n textContent: 'Save (API Format)',\r\n style: { width: '100%', display: 'none' },\r\n onclick: () => {\r\n let filename = 'workflow_api.json'\r\n if (promptFilename.value) {\r\n filename = prompt('Save workflow (API) as:', filename)\r\n if (!filename) return\r\n if (!filename.toLowerCase().endsWith('.json')) {\r\n filename += '.json'\r\n }\r\n }\r\n app.graphToPrompt().then((p) => {\r\n const json = JSON.stringify(p.output, null, 2) // convert the data to a JSON string\r\n const blob = new Blob([json], { type: 'application/json' })\r\n const url = URL.createObjectURL(blob)\r\n const a = $el('a', {\r\n href: url,\r\n download: filename,\r\n style: { display: 'none' },\r\n parent: document.body\r\n })\r\n a.click()\r\n setTimeout(function () {\r\n a.remove()\r\n window.URL.revokeObjectURL(url)\r\n }, 0)\r\n })\r\n }\r\n }),\r\n $el('button', {\r\n id: 'comfy-load-button',\r\n textContent: 'Load',\r\n onclick: () => fileInput.click()\r\n }),\r\n $el('button', {\r\n id: 'comfy-refresh-button',\r\n textContent: 'Refresh',\r\n onclick: () => app.refreshComboInNodes()\r\n }),\r\n $el('button', {\r\n id: 'comfy-clipspace-button',\r\n textContent: 'Clipspace',\r\n onclick: () => app.openClipspace()\r\n }),\r\n $el('button', {\r\n id: 'comfy-clear-button',\r\n textContent: 'Clear',\r\n onclick: () => {\r\n if (!confirmClear.value || confirm('Clear workflow?')) {\r\n app.clean()\r\n app.graph.clear()\r\n app.resetView()\r\n api.dispatchEvent(new CustomEvent('graphCleared'))\r\n }\r\n }\r\n }),\r\n $el('button', {\r\n id: 'comfy-load-default-button',\r\n textContent: 'Load Default',\r\n onclick: async () => {\r\n if (!confirmClear.value || confirm('Load default workflow?')) {\r\n app.resetView()\r\n await app.loadGraphData()\r\n }\r\n }\r\n }),\r\n $el('button', {\r\n id: 'comfy-reset-view-button',\r\n textContent: 'Reset View',\r\n onclick: async () => {\r\n app.resetView()\r\n }\r\n })\r\n ]) as HTMLDivElement\r\n\r\n const devMode = this.settings.addSetting({\r\n id: 'Comfy.DevMode',\r\n name: 'Enable Dev mode Options',\r\n type: 'boolean',\r\n defaultValue: false,\r\n onChange: function (value) {\r\n document.getElementById('comfy-dev-save-api-button').style.display =\r\n value ? 'flex' : 'none'\r\n }\r\n })\r\n\r\n this.restoreMenuPosition = dragElement(this.menuContainer, this.settings)\r\n\r\n this.setStatus({ exec_info: { queue_remaining: 'X' } })\r\n }\r\n\r\n setStatus(status) {\r\n this.queueSize.textContent =\r\n 'Queue size: ' + (status ? status.exec_info.queue_remaining : 'ERR')\r\n if (status) {\r\n if (\r\n this.lastQueueSize != 0 &&\r\n status.exec_info.queue_remaining == 0 &&\r\n this.autoQueueEnabled &&\r\n (this.autoQueueMode === 'instant' || this.graphHasChanged) &&\r\n !app.lastExecutionError\r\n ) {\r\n app.queuePrompt(0, this.batchCount)\r\n status.exec_info.queue_remaining += this.batchCount\r\n this.graphHasChanged = false\r\n }\r\n this.lastQueueSize = status.exec_info.queue_remaining\r\n }\r\n }\r\n}\r\n","import { $el, ComfyDialog } from './ui'\r\nimport { api } from './api'\r\nimport type { ComfyApp } from './app'\r\n\r\n$el('style', {\r\n textContent: `\r\n .comfy-logging-logs {\r\n display: grid;\r\n color: var(--fg-color);\r\n white-space: pre-wrap;\r\n }\r\n .comfy-logging-log {\r\n display: contents;\r\n }\r\n .comfy-logging-title {\r\n background: var(--tr-even-bg-color);\r\n font-weight: bold;\r\n margin-bottom: 5px;\r\n text-align: center;\r\n }\r\n .comfy-logging-log div {\r\n background: var(--row-bg);\r\n padding: 5px;\r\n }\r\n `,\r\n parent: document.body\r\n})\r\n\r\n// Stringify function supporting max depth and removal of circular references\r\n// https://stackoverflow.com/a/57193345\r\nfunction stringify(val, depth, replacer, space, onGetObjID?) {\r\n depth = isNaN(+depth) ? 1 : depth\r\n var recursMap = new WeakMap()\r\n function _build(val, depth, o?, a?, r?) {\r\n // (JSON.stringify() has it's own rules, which we respect here by using it for property iteration)\r\n return !val || typeof val != 'object'\r\n ? val\r\n : ((r = recursMap.has(val)),\r\n recursMap.set(val, true),\r\n (a = Array.isArray(val)),\r\n r\r\n ? (o = (onGetObjID && onGetObjID(val)) || null)\r\n : JSON.stringify(val, function (k, v) {\r\n if (a || depth > 0) {\r\n if (replacer) v = replacer(k, v)\r\n if (!k) return (a = Array.isArray(v)), (val = v)\r\n !o && (o = a ? [] : {})\r\n o[k] = _build(v, a ? depth : depth - 1)\r\n }\r\n }),\r\n o === void 0 ? (a ? [] : {}) : o)\r\n }\r\n return JSON.stringify(_build(val, depth), null, space)\r\n}\r\n\r\nconst jsonReplacer = (k, v, ui) => {\r\n if (v instanceof Array && v.length === 1) {\r\n v = v[0]\r\n }\r\n if (v instanceof Date) {\r\n v = v.toISOString()\r\n if (ui) {\r\n v = v.split('T')[1]\r\n }\r\n }\r\n if (v instanceof Error) {\r\n let err = ''\r\n if (v.name) err += v.name + '\\n'\r\n if (v.message) err += v.message + '\\n'\r\n if (v.stack) err += v.stack + '\\n'\r\n if (!err) {\r\n err = v.toString()\r\n }\r\n v = err\r\n }\r\n return v\r\n}\r\n\r\nconst fileInput: HTMLInputElement = $el('input', {\r\n type: 'file',\r\n accept: '.json',\r\n style: { display: 'none' },\r\n parent: document.body\r\n}) as HTMLInputElement\r\n\r\nclass ComfyLoggingDialog extends ComfyDialog {\r\n logging: any\r\n\r\n constructor(logging) {\r\n super()\r\n this.logging = logging\r\n }\r\n\r\n clear() {\r\n this.logging.clear()\r\n this.show()\r\n }\r\n\r\n export() {\r\n const blob = new Blob(\r\n [stringify([...this.logging.entries], 20, jsonReplacer, '\\t')],\r\n {\r\n type: 'application/json'\r\n }\r\n )\r\n const url = URL.createObjectURL(blob)\r\n const a = $el('a', {\r\n href: url,\r\n download: `comfyui-logs-${Date.now()}.json`,\r\n style: { display: 'none' },\r\n parent: document.body\r\n })\r\n a.click()\r\n setTimeout(function () {\r\n a.remove()\r\n window.URL.revokeObjectURL(url)\r\n }, 0)\r\n }\r\n\r\n import() {\r\n fileInput.onchange = () => {\r\n const reader = new FileReader()\r\n reader.onload = () => {\r\n fileInput.remove()\r\n try {\r\n const obj = JSON.parse(reader.result as string)\r\n if (obj instanceof Array) {\r\n this.show(obj)\r\n } else {\r\n throw new Error('Invalid file selected.')\r\n }\r\n } catch (error) {\r\n alert('Unable to load logs: ' + error.message)\r\n }\r\n }\r\n reader.readAsText(fileInput.files[0])\r\n }\r\n fileInput.click()\r\n }\r\n\r\n createButtons() {\r\n return [\r\n $el('button', {\r\n type: 'button',\r\n textContent: 'Clear',\r\n onclick: () => this.clear()\r\n }),\r\n $el('button', {\r\n type: 'button',\r\n textContent: 'Export logs...',\r\n onclick: () => this.export()\r\n }),\r\n $el('button', {\r\n type: 'button',\r\n textContent: 'View exported logs...',\r\n onclick: () => this.import()\r\n }),\r\n ...super.createButtons()\r\n ]\r\n }\r\n\r\n getTypeColor(type) {\r\n switch (type) {\r\n case 'error':\r\n return 'red'\r\n case 'warn':\r\n return 'orange'\r\n case 'debug':\r\n return 'dodgerblue'\r\n }\r\n }\r\n\r\n show(entries?: any[]) {\r\n if (!entries) entries = this.logging.entries\r\n this.element.style.width = '100%'\r\n const cols = {\r\n source: 'Source',\r\n type: 'Type',\r\n timestamp: 'Timestamp',\r\n message: 'Message'\r\n }\r\n const keys = Object.keys(cols)\r\n const headers = Object.values(cols).map((title) =>\r\n $el('div.comfy-logging-title', {\r\n textContent: title\r\n })\r\n )\r\n const rows = entries.map((entry, i) => {\r\n return $el(\r\n 'div.comfy-logging-log',\r\n {\r\n $: (el) =>\r\n el.style.setProperty(\r\n '--row-bg',\r\n `var(--tr-${i % 2 ? 'even' : 'odd'}-bg-color)`\r\n )\r\n },\r\n keys.map((key) => {\r\n let v = entry[key]\r\n let color\r\n if (key === 'type') {\r\n color = this.getTypeColor(v)\r\n } else {\r\n v = jsonReplacer(key, v, true)\r\n\r\n if (typeof v === 'object') {\r\n v = stringify(v, 5, jsonReplacer, ' ')\r\n }\r\n }\r\n\r\n return $el('div', {\r\n style: {\r\n color\r\n },\r\n textContent: v\r\n })\r\n })\r\n )\r\n })\r\n\r\n const grid = $el(\r\n 'div.comfy-logging-logs',\r\n {\r\n style: {\r\n gridTemplateColumns: `repeat(${headers.length}, 1fr)`\r\n }\r\n },\r\n [...headers, ...rows]\r\n )\r\n const els = [grid]\r\n if (!this.logging.enabled) {\r\n els.unshift(\r\n $el('h3', {\r\n style: { textAlign: 'center' },\r\n textContent: 'Logging is disabled'\r\n })\r\n )\r\n }\r\n super.show($el('div', els))\r\n }\r\n}\r\n\r\nexport class ComfyLogging {\r\n /**\r\n * @type Array<{ source: string, type: string, timestamp: Date, message: any }>\r\n */\r\n entries = []\r\n\r\n #enabled\r\n #console = {}\r\n\r\n app: ComfyApp\r\n dialog: ComfyLoggingDialog\r\n\r\n get enabled() {\r\n return this.#enabled\r\n }\r\n\r\n set enabled(value) {\r\n if (value === this.#enabled) return\r\n if (value) {\r\n this.patchConsole()\r\n } else {\r\n this.unpatchConsole()\r\n }\r\n this.#enabled = value\r\n }\r\n\r\n constructor(app) {\r\n this.app = app\r\n\r\n this.dialog = new ComfyLoggingDialog(this)\r\n this.addSetting()\r\n this.catchUnhandled()\r\n this.addInitData()\r\n }\r\n\r\n addSetting() {\r\n const settingId: string = 'Comfy.Logging.Enabled'\r\n const htmlSettingId = settingId.replaceAll('.', '-')\r\n const setting = this.app.ui.settings.addSetting({\r\n id: settingId,\r\n name: settingId,\r\n defaultValue: true,\r\n onChange: (value) => {\r\n this.enabled = value\r\n },\r\n type: (name, setter, value) => {\r\n return $el('tr', [\r\n $el('td', [\r\n $el('label', {\r\n textContent: 'Logging',\r\n for: htmlSettingId\r\n })\r\n ]),\r\n $el('td', [\r\n $el('input', {\r\n id: htmlSettingId,\r\n type: 'checkbox',\r\n checked: value,\r\n onchange: (event) => {\r\n setter(event.target.checked)\r\n }\r\n }),\r\n $el('button', {\r\n textContent: 'View Logs',\r\n onclick: () => {\r\n this.app.ui.settings.element.close()\r\n this.dialog.show()\r\n },\r\n style: {\r\n fontSize: '14px',\r\n display: 'block',\r\n marginTop: '5px'\r\n }\r\n })\r\n ])\r\n ])\r\n }\r\n })\r\n this.enabled = setting.value\r\n }\r\n\r\n patchConsole() {\r\n // Capture common console outputs\r\n const self = this\r\n for (const type of ['log', 'warn', 'error', 'debug']) {\r\n const orig = console[type]\r\n this.#console[type] = orig\r\n console[type] = function () {\r\n orig.apply(console, arguments)\r\n self.addEntry('console', type, ...arguments)\r\n }\r\n }\r\n }\r\n\r\n unpatchConsole() {\r\n // Restore original console functions\r\n for (const type of Object.keys(this.#console)) {\r\n console[type] = this.#console[type]\r\n }\r\n this.#console = {}\r\n }\r\n\r\n catchUnhandled() {\r\n // Capture uncaught errors\r\n window.addEventListener('error', (e) => {\r\n this.addEntry('window', 'error', e.error ?? 'Unknown error')\r\n return false\r\n })\r\n\r\n window.addEventListener('unhandledrejection', (e) => {\r\n this.addEntry('unhandledrejection', 'error', e.reason ?? 'Unknown error')\r\n })\r\n }\r\n\r\n clear() {\r\n this.entries = []\r\n }\r\n\r\n addEntry(source, type, ...args) {\r\n if (this.enabled) {\r\n this.entries.push({\r\n source,\r\n type,\r\n timestamp: new Date(),\r\n message: args\r\n })\r\n }\r\n }\r\n\r\n log(source, ...args) {\r\n this.addEntry(source, 'log', ...args)\r\n }\r\n\r\n async addInitData() {\r\n if (!this.enabled) return\r\n const source = 'ComfyUI.Logging'\r\n this.addEntry(source, 'debug', { UserAgent: navigator.userAgent })\r\n const systemStats = await api.getSystemStats()\r\n this.addEntry(source, 'debug', systemStats)\r\n }\r\n}\r\n","var __defProp = Object.defineProperty;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== \"symbol\" ? key + \"\" : key, value);\nconst globalExport = {};\n(function(globalThis) {\n var LiteGraph = globalThis.LiteGraph = {\n VERSION: 0.4,\n CANVAS_GRID_SIZE: 10,\n NODE_TITLE_HEIGHT: 30,\n NODE_TITLE_TEXT_Y: 20,\n NODE_SLOT_HEIGHT: 20,\n NODE_WIDGET_HEIGHT: 20,\n NODE_WIDTH: 140,\n NODE_MIN_WIDTH: 50,\n NODE_COLLAPSED_RADIUS: 10,\n NODE_COLLAPSED_WIDTH: 80,\n NODE_TITLE_COLOR: \"#999\",\n NODE_SELECTED_TITLE_COLOR: \"#FFF\",\n NODE_TEXT_SIZE: 14,\n NODE_TEXT_COLOR: \"#AAA\",\n NODE_SUBTEXT_SIZE: 12,\n NODE_DEFAULT_COLOR: \"#333\",\n NODE_DEFAULT_BGCOLOR: \"#353535\",\n NODE_DEFAULT_BOXCOLOR: \"#666\",\n NODE_DEFAULT_SHAPE: \"box\",\n NODE_BOX_OUTLINE_COLOR: \"#FFF\",\n DEFAULT_SHADOW_COLOR: \"rgba(0,0,0,0.5)\",\n DEFAULT_GROUP_FONT: 24,\n WIDGET_BGCOLOR: \"#222\",\n WIDGET_OUTLINE_COLOR: \"#666\",\n WIDGET_TEXT_COLOR: \"#DDD\",\n WIDGET_SECONDARY_TEXT_COLOR: \"#999\",\n LINK_COLOR: \"#9A9\",\n EVENT_LINK_COLOR: \"#A86\",\n CONNECTING_LINK_COLOR: \"#AFA\",\n MAX_NUMBER_OF_NODES: 1e4,\n //avoid infinite loops\n DEFAULT_POSITION: [100, 100],\n //default node position\n VALID_SHAPES: [\"default\", \"box\", \"round\", \"card\"],\n //,\"circle\"\n //shapes are used for nodes but also for slots\n BOX_SHAPE: 1,\n ROUND_SHAPE: 2,\n CIRCLE_SHAPE: 3,\n CARD_SHAPE: 4,\n ARROW_SHAPE: 5,\n GRID_SHAPE: 6,\n // intended for slot arrays\n //enums\n INPUT: 1,\n OUTPUT: 2,\n EVENT: -1,\n //for outputs\n ACTION: -1,\n //for inputs\n NODE_MODES: [\"Always\", \"On Event\", \"Never\", \"On Trigger\"],\n // helper, will add \"On Request\" and more in the future\n NODE_MODES_COLORS: [\"#666\", \"#422\", \"#333\", \"#224\", \"#626\"],\n // use with node_box_coloured_by_mode\n ALWAYS: 0,\n ON_EVENT: 1,\n NEVER: 2,\n ON_TRIGGER: 3,\n UP: 1,\n DOWN: 2,\n LEFT: 3,\n RIGHT: 4,\n CENTER: 5,\n LINK_RENDER_MODES: [\"Straight\", \"Linear\", \"Spline\"],\n // helper\n STRAIGHT_LINK: 0,\n LINEAR_LINK: 1,\n SPLINE_LINK: 2,\n NORMAL_TITLE: 0,\n NO_TITLE: 1,\n TRANSPARENT_TITLE: 2,\n AUTOHIDE_TITLE: 3,\n VERTICAL_LAYOUT: \"vertical\",\n // arrange nodes vertically\n proxy: null,\n //used to redirect calls\n node_images_path: \"\",\n debug: false,\n catch_exceptions: true,\n throw_errors: true,\n allow_scripts: false,\n //if set to true some nodes like Formula would be allowed to evaluate code that comes from unsafe sources (like node configuration), which could lead to exploits\n registered_node_types: {},\n //nodetypes by string\n node_types_by_file_extension: {},\n //used for dropping files in the canvas\n Nodes: {},\n //node types by classname\n Globals: {},\n //used to store vars between graphs\n searchbox_extras: {},\n //used to add extra features to the search box\n auto_sort_node_types: false,\n // [true!] If set to true, will automatically sort node types / categories in the context menus\n node_box_coloured_when_on: false,\n // [true!] this make the nodes box (top left circle) coloured when triggered (execute/action), visual feedback\n node_box_coloured_by_mode: false,\n // [true!] nodebox based on node mode, visual feedback\n dialog_close_on_mouse_leave: false,\n // [false on mobile] better true if not touch device, TODO add an helper/listener to close if false\n dialog_close_on_mouse_leave_delay: 500,\n shift_click_do_break_link_from: false,\n // [false!] prefer false if results too easy to break links - implement with ALT or TODO custom keys\n click_do_break_link_to: false,\n // [false!]prefer false, way too easy to break links\n ctrl_alt_click_do_break_link: true,\n // [true!] who accidentally ctrl-alt-clicks on an in/output? nobody! that's who!\n search_hide_on_mouse_leave: true,\n // [false on mobile] better true if not touch device, TODO add an helper/listener to close if false\n search_filter_enabled: false,\n // [true!] enable filtering slots type in the search widget, !requires auto_load_slot_types or manual set registered_slot_[in/out]_types and slot_types_[in/out]\n search_show_all_on_open: true,\n // [true!] opens the results list when opening the search widget\n auto_load_slot_types: false,\n // [if want false, use true, run, get vars values to be statically set, than disable] nodes types and nodeclass association with node types need to be calculated, if dont want this, calculate once and set registered_slot_[in/out]_types and slot_types_[in/out]\n // set these values if not using auto_load_slot_types\n registered_slot_in_types: {},\n // slot types for nodeclass\n registered_slot_out_types: {},\n // slot types for nodeclass\n slot_types_in: [],\n // slot types IN\n slot_types_out: [],\n // slot types OUT\n slot_types_default_in: [],\n // specify for each IN slot type a(/many) default node(s), use single string, array, or object (with node, title, parameters, ..) like for search\n slot_types_default_out: [],\n // specify for each OUT slot type a(/many) default node(s), use single string, array, or object (with node, title, parameters, ..) like for search\n alt_drag_do_clone_nodes: false,\n // [true!] very handy, ALT click to clone and drag the new node\n do_add_triggers_slots: false,\n // [true!] will create and connect event slots when using action/events connections, !WILL CHANGE node mode when using onTrigger (enable mode colors), onExecuted does not need this\n allow_multi_output_for_events: true,\n // [false!] being events, it is strongly reccomended to use them sequentially, one by one\n middle_click_slot_add_default_node: false,\n //[true!] allows to create and connect a ndoe clicking with the third button (wheel)\n release_link_on_empty_shows_menu: false,\n //[true!] dragging a link to empty space will open a menu, add from list, search or defaults\n pointerevents_method: \"pointer\",\n // \"mouse\"|\"pointer\" use mouse for retrocompatibility issues? (none found @ now)\n // TODO implement pointercancel, gotpointercapture, lostpointercapture, (pointerover, pointerout if necessary)\n ctrl_shift_v_paste_connect_unselected_outputs: true,\n //[true!] allows ctrl + shift + v to paste nodes with the outputs of the unselected nodes connected with the inputs of the newly pasted nodes\n // if true, all newly created nodes/links will use string UUIDs for their id fields instead of integers.\n // use this if you must have node IDs that are unique across all graphs and subgraphs.\n use_uuids: false,\n /**\n * Register a node class so it can be listed when the user wants to create a new one\n * @method registerNodeType\n * @param {String} type name of the node and path\n * @param {Class} base_class class containing the structure of a node\n */\n registerNodeType: function(type, base_class) {\n if (!base_class.prototype) {\n throw \"Cannot register a simple object, it must be a class with a prototype\";\n }\n base_class.type = type;\n if (LiteGraph.debug) {\n console.log(\"Node registered: \" + type);\n }\n const classname = base_class.name;\n const pos2 = type.lastIndexOf(\"/\");\n base_class.category = type.substring(0, pos2);\n if (!base_class.title) {\n base_class.title = classname;\n }\n for (var i2 in LGraphNode.prototype) {\n if (!base_class.prototype[i2]) {\n base_class.prototype[i2] = LGraphNode.prototype[i2];\n }\n }\n const prev = this.registered_node_types[type];\n if (prev) {\n console.log(\"replacing node type: \" + type);\n }\n if (!Object.prototype.hasOwnProperty.call(base_class.prototype, \"shape\")) {\n Object.defineProperty(base_class.prototype, \"shape\", {\n set: function(v2) {\n switch (v2) {\n case \"default\":\n delete this._shape;\n break;\n case \"box\":\n this._shape = LiteGraph.BOX_SHAPE;\n break;\n case \"round\":\n this._shape = LiteGraph.ROUND_SHAPE;\n break;\n case \"circle\":\n this._shape = LiteGraph.CIRCLE_SHAPE;\n break;\n case \"card\":\n this._shape = LiteGraph.CARD_SHAPE;\n break;\n default:\n this._shape = v2;\n }\n },\n get: function() {\n return this._shape;\n },\n enumerable: true,\n configurable: true\n });\n if (base_class.supported_extensions) {\n for (let i3 in base_class.supported_extensions) {\n const ext = base_class.supported_extensions[i3];\n if (ext && ext.constructor === String) {\n this.node_types_by_file_extension[ext.toLowerCase()] = base_class;\n }\n }\n }\n }\n this.registered_node_types[type] = base_class;\n if (base_class.constructor.name) {\n this.Nodes[classname] = base_class;\n }\n if (LiteGraph.onNodeTypeRegistered) {\n LiteGraph.onNodeTypeRegistered(type, base_class);\n }\n if (prev && LiteGraph.onNodeTypeReplaced) {\n LiteGraph.onNodeTypeReplaced(type, base_class, prev);\n }\n if (base_class.prototype.onPropertyChange) {\n console.warn(\n \"LiteGraph node class \" + type + \" has onPropertyChange method, it must be called onPropertyChanged with d at the end\"\n );\n }\n if (this.auto_load_slot_types) {\n new base_class(base_class.title || \"tmpnode\");\n }\n },\n /**\n * removes a node type from the system\n * @method unregisterNodeType\n * @param {String|Object} type name of the node or the node constructor itself\n */\n unregisterNodeType: function(type) {\n const base_class = type.constructor === String ? this.registered_node_types[type] : type;\n if (!base_class) {\n throw \"node type not found: \" + type;\n }\n delete this.registered_node_types[base_class.type];\n if (base_class.constructor.name) {\n delete this.Nodes[base_class.constructor.name];\n }\n },\n /**\n * Save a slot type and his node\n * @method registerSlotType\n * @param {String|Object} type name of the node or the node constructor itself\n * @param {String} slot_type name of the slot type (variable type), eg. string, number, array, boolean, ..\n */\n registerNodeAndSlotType: function(type, slot_type, out) {\n out = out || false;\n const base_class = type.constructor === String && this.registered_node_types[type] !== \"anonymous\" ? this.registered_node_types[type] : type;\n const class_type = base_class.constructor.type;\n let allTypes = [];\n if (typeof slot_type === \"string\") {\n allTypes = slot_type.split(\",\");\n } else if (slot_type == this.EVENT || slot_type == this.ACTION) {\n allTypes = [\"_event_\"];\n } else {\n allTypes = [\"*\"];\n }\n for (let i2 = 0; i2 < allTypes.length; ++i2) {\n let slotType = allTypes[i2];\n if (slotType === \"\") {\n slotType = \"*\";\n }\n const registerTo = out ? \"registered_slot_out_types\" : \"registered_slot_in_types\";\n if (this[registerTo][slotType] === void 0) {\n this[registerTo][slotType] = { nodes: [] };\n }\n if (!this[registerTo][slotType].nodes.includes(class_type)) {\n this[registerTo][slotType].nodes.push(class_type);\n }\n if (!out) {\n if (!this.slot_types_in.includes(slotType.toLowerCase())) {\n this.slot_types_in.push(slotType.toLowerCase());\n this.slot_types_in.sort();\n }\n } else {\n if (!this.slot_types_out.includes(slotType.toLowerCase())) {\n this.slot_types_out.push(slotType.toLowerCase());\n this.slot_types_out.sort();\n }\n }\n }\n },\n /**\n * Create a new nodetype by passing a function, it wraps it with a proper class and generates inputs according to the parameters of the function.\n * Useful to wrap simple methods that do not require properties, and that only process some input to generate an output.\n * @method wrapFunctionAsNode\n * @param {String} name node name with namespace (p.e.: 'math/sum')\n * @param {Function} func\n * @param {Array} param_types [optional] an array containing the type of every parameter, otherwise parameters will accept any type\n * @param {String} return_type [optional] string with the return type, otherwise it will be generic\n * @param {Object} properties [optional] properties to be configurable\n */\n wrapFunctionAsNode: function(name, func, param_types, return_type, properties) {\n var params = Array(func.length);\n var code = \"\";\n var names = LiteGraph.getParameterNames(func);\n for (var i2 = 0; i2 < names.length; ++i2) {\n code += \"this.addInput('\" + names[i2] + \"',\" + (param_types && param_types[i2] ? \"'\" + param_types[i2] + \"'\" : \"0\") + \");\\n\";\n }\n code += \"this.addOutput('out',\" + (return_type ? \"'\" + return_type + \"'\" : 0) + \");\\n\";\n if (properties) {\n code += \"this.properties = \" + JSON.stringify(properties) + \";\\n\";\n }\n var classobj = Function(code);\n classobj.title = name.split(\"/\").pop();\n classobj.desc = \"Generated from \" + func.name;\n classobj.prototype.onExecute = function onExecute() {\n for (var i3 = 0; i3 < params.length; ++i3) {\n params[i3] = this.getInputData(i3);\n }\n var r = func.apply(this, params);\n this.setOutputData(0, r);\n };\n this.registerNodeType(name, classobj);\n },\n /**\n * Removes all previously registered node's types\n */\n clearRegisteredTypes: function() {\n this.registered_node_types = {};\n this.node_types_by_file_extension = {};\n this.Nodes = {};\n this.searchbox_extras = {};\n },\n /**\n * Adds this method to all nodetypes, existing and to be created\n * (You can add it to LGraphNode.prototype but then existing node types wont have it)\n * @method addNodeMethod\n * @param {Function} func\n */\n addNodeMethod: function(name, func) {\n LGraphNode.prototype[name] = func;\n for (var i2 in this.registered_node_types) {\n var type = this.registered_node_types[i2];\n if (type.prototype[name]) {\n type.prototype[\"_\" + name] = type.prototype[name];\n }\n type.prototype[name] = func;\n }\n },\n /**\n * Create a node of a given type with a name. The node is not attached to any graph yet.\n * @method createNode\n * @param {String} type full name of the node class. p.e. \"math/sin\"\n * @param {String} name a name to distinguish from other nodes\n * @param {Object} options to set options\n */\n createNode: function(type, title, options) {\n var base_class = this.registered_node_types[type];\n if (!base_class) {\n if (LiteGraph.debug) {\n console.log(\n 'GraphNode type \"' + type + '\" not registered.'\n );\n }\n return null;\n }\n base_class.prototype || base_class;\n title = title || base_class.title || type;\n var node2 = null;\n if (LiteGraph.catch_exceptions) {\n try {\n node2 = new base_class(title);\n } catch (err) {\n console.error(err);\n return null;\n }\n } else {\n node2 = new base_class(title);\n }\n node2.type = type;\n if (!node2.title && title) {\n node2.title = title;\n }\n if (!node2.properties) {\n node2.properties = {};\n }\n if (!node2.properties_info) {\n node2.properties_info = [];\n }\n if (!node2.flags) {\n node2.flags = {};\n }\n if (!node2.size) {\n node2.size = node2.computeSize();\n }\n if (!node2.pos) {\n node2.pos = LiteGraph.DEFAULT_POSITION.concat();\n }\n if (!node2.mode) {\n node2.mode = LiteGraph.ALWAYS;\n }\n if (options) {\n for (var i2 in options) {\n node2[i2] = options[i2];\n }\n }\n if (node2.onNodeCreated) {\n node2.onNodeCreated();\n }\n return node2;\n },\n /**\n * Returns a registered node type with a given name\n * @method getNodeType\n * @param {String} type full name of the node class. p.e. \"math/sin\"\n * @return {Class} the node class\n */\n getNodeType: function(type) {\n return this.registered_node_types[type];\n },\n /**\n * Returns a list of node types matching one category\n * @method getNodeType\n * @param {String} category category name\n * @return {Array} array with all the node classes\n */\n getNodeTypesInCategory: function(category, filter) {\n var r = [];\n for (var i2 in this.registered_node_types) {\n var type = this.registered_node_types[i2];\n if (type.filter != filter) {\n continue;\n }\n if (category == \"\") {\n if (type.category == null) {\n r.push(type);\n }\n } else if (type.category == category) {\n r.push(type);\n }\n }\n if (this.auto_sort_node_types) {\n r.sort(function(a, b) {\n return a.title.localeCompare(b.title);\n });\n }\n return r;\n },\n /**\n * Returns a list with all the node type categories\n * @method getNodeTypesCategories\n * @param {String} filter only nodes with ctor.filter equal can be shown\n * @return {Array} array with all the names of the categories\n */\n getNodeTypesCategories: function(filter) {\n var categories = { \"\": 1 };\n for (var i2 in this.registered_node_types) {\n var type = this.registered_node_types[i2];\n if (type.category && !type.skip_list) {\n if (type.filter != filter)\n continue;\n categories[type.category] = 1;\n }\n }\n var result = [];\n for (var i2 in categories) {\n result.push(i2);\n }\n return this.auto_sort_node_types ? result.sort() : result;\n },\n //debug purposes: reloads all the js scripts that matches a wildcard\n reloadNodes: function(folder_wildcard) {\n var tmp = document.getElementsByTagName(\"script\");\n var script_files = [];\n for (var i2 = 0; i2 < tmp.length; i2++) {\n script_files.push(tmp[i2]);\n }\n var docHeadObj = document.getElementsByTagName(\"head\")[0];\n folder_wildcard = document.location.href + folder_wildcard;\n for (var i2 = 0; i2 < script_files.length; i2++) {\n var src = script_files[i2].src;\n if (!src || src.substr(0, folder_wildcard.length) != folder_wildcard) {\n continue;\n }\n try {\n if (LiteGraph.debug) {\n console.log(\"Reloading: \" + src);\n }\n var dynamicScript = document.createElement(\"script\");\n dynamicScript.type = \"text/javascript\";\n dynamicScript.src = src;\n docHeadObj.appendChild(dynamicScript);\n docHeadObj.removeChild(script_files[i2]);\n } catch (err) {\n if (LiteGraph.throw_errors) {\n throw err;\n }\n if (LiteGraph.debug) {\n console.log(\"Error while reloading \" + src);\n }\n }\n }\n if (LiteGraph.debug) {\n console.log(\"Nodes reloaded\");\n }\n },\n //separated just to improve if it doesn't work\n cloneObject: function(obj, target) {\n if (obj == null) {\n return null;\n }\n var r = JSON.parse(JSON.stringify(obj));\n if (!target) {\n return r;\n }\n for (var i2 in r) {\n target[i2] = r[i2];\n }\n return target;\n },\n /*\n * https://gist.github.com/jed/982883?permalink_comment_id=852670#gistcomment-852670\n */\n uuidv4: function() {\n return (\"10000000-1000-4000-8000\" + -1e11).replace(/[018]/g, (a) => (a ^ Math.random() * 16 >> a / 4).toString(16));\n },\n /**\n * Returns if the types of two slots are compatible (taking into account wildcards, etc)\n * @method isValidConnection\n * @param {String} type_a\n * @param {String} type_b\n * @return {Boolean} true if they can be connected\n */\n isValidConnection: function(type_a, type_b) {\n if (type_a == \"\" || type_a === \"*\") type_a = 0;\n if (type_b == \"\" || type_b === \"*\") type_b = 0;\n if (!type_a || !type_b || type_a == type_b || type_a == LiteGraph.EVENT && type_b == LiteGraph.ACTION) {\n return true;\n }\n type_a = String(type_a);\n type_b = String(type_b);\n type_a = type_a.toLowerCase();\n type_b = type_b.toLowerCase();\n if (type_a.indexOf(\",\") == -1 && type_b.indexOf(\",\") == -1) {\n return type_a == type_b;\n }\n var supported_types_a = type_a.split(\",\");\n var supported_types_b = type_b.split(\",\");\n for (var i2 = 0; i2 < supported_types_a.length; ++i2) {\n for (var j = 0; j < supported_types_b.length; ++j) {\n if (this.isValidConnection(supported_types_a[i2], supported_types_b[j])) {\n return true;\n }\n }\n }\n return false;\n },\n /**\n * Register a string in the search box so when the user types it it will recommend this node\n * @method registerSearchboxExtra\n * @param {String} node_type the node recommended\n * @param {String} description text to show next to it\n * @param {Object} data it could contain info of how the node should be configured\n * @return {Boolean} true if they can be connected\n */\n registerSearchboxExtra: function(node_type, description, data) {\n this.searchbox_extras[description.toLowerCase()] = {\n type: node_type,\n desc: description,\n data\n };\n },\n /**\n * Wrapper to load files (from url using fetch or from file using FileReader)\n * @method fetchFile\n * @param {String|File|Blob} url the url of the file (or the file itself)\n * @param {String} type an string to know how to fetch it: \"text\",\"arraybuffer\",\"json\",\"blob\"\n * @param {Function} on_complete callback(data)\n * @param {Function} on_error in case of an error\n * @return {FileReader|Promise} returns the object used to \n */\n fetchFile: function(url, type, on_complete, on_error) {\n if (!url)\n return null;\n type = type || \"text\";\n if (url.constructor === String) {\n if (url.substr(0, 4) == \"http\" && LiteGraph.proxy) {\n url = LiteGraph.proxy + url.substr(url.indexOf(\":\") + 3);\n }\n return fetch(url).then(function(response) {\n if (!response.ok)\n throw new Error(\"File not found\");\n if (type == \"arraybuffer\")\n return response.arrayBuffer();\n else if (type == \"text\" || type == \"string\")\n return response.text();\n else if (type == \"json\")\n return response.json();\n else if (type == \"blob\")\n return response.blob();\n }).then(function(data) {\n if (on_complete)\n on_complete(data);\n }).catch(function(error) {\n console.error(\"error fetching file:\", url);\n if (on_error)\n on_error(error);\n });\n } else if (url.constructor === File || url.constructor === Blob) {\n var reader = new FileReader();\n reader.onload = function(e) {\n var v2 = e.target.result;\n if (type == \"json\")\n v2 = JSON.parse(v2);\n if (on_complete)\n on_complete(v2);\n };\n if (type == \"arraybuffer\")\n return reader.readAsArrayBuffer(url);\n else if (type == \"text\" || type == \"json\")\n return reader.readAsText(url);\n else if (type == \"blob\")\n return reader.readAsBinaryString(url);\n }\n return null;\n }\n };\n if (typeof performance != \"undefined\") {\n LiteGraph.getTime = performance.now.bind(performance);\n } else if (typeof Date != \"undefined\" && Date.now) {\n LiteGraph.getTime = Date.now.bind(Date);\n } else if (typeof process != \"undefined\") {\n LiteGraph.getTime = function() {\n var t = process.hrtime();\n return t[0] * 1e-3 + t[1] * 1e-6;\n };\n } else {\n LiteGraph.getTime = function getTime() {\n return (/* @__PURE__ */ new Date()).getTime();\n };\n }\n const _LGraph = class _LGraph {\n constructor(o) {\n if (LiteGraph.debug) {\n console.log(\"Graph created\");\n }\n this.list_of_graphcanvas = null;\n this.clear();\n if (o) {\n this.configure(o);\n }\n }\n //used to know which types of connections support this graph (some graphs do not allow certain types)\n getSupportedTypes() {\n return this.supported_types || _LGraph.supported_types;\n }\n /**\n * Removes all nodes from this graph\n * @method clear\n */\n clear() {\n this.stop();\n this.status = _LGraph.STATUS_STOPPED;\n this.last_node_id = 0;\n this.last_link_id = 0;\n this._version = -1;\n if (this._nodes) {\n for (var i2 = 0; i2 < this._nodes.length; ++i2) {\n var node2 = this._nodes[i2];\n if (node2.onRemoved) {\n node2.onRemoved();\n }\n }\n }\n this._nodes = [];\n this._nodes_by_id = {};\n this._nodes_in_order = [];\n this._nodes_executable = null;\n this._groups = [];\n this.links = {};\n this.iteration = 0;\n this.config = {};\n this.vars = {};\n this.extra = {};\n this.globaltime = 0;\n this.runningtime = 0;\n this.fixedtime = 0;\n this.fixedtime_lapse = 0.01;\n this.elapsed_time = 0.01;\n this.last_update_time = 0;\n this.starttime = 0;\n this.catch_errors = true;\n this.nodes_executing = [];\n this.nodes_actioning = [];\n this.nodes_executedAction = [];\n this.inputs = {};\n this.outputs = {};\n this.change();\n this.sendActionToCanvas(\"clear\");\n }\n /**\n * Attach Canvas to this graph\n * @method attachCanvas\n * @param {GraphCanvas} graph_canvas\n */\n attachCanvas(graphcanvas) {\n if (graphcanvas.constructor != LGraphCanvas) {\n throw \"attachCanvas expects a LGraphCanvas instance\";\n }\n if (graphcanvas.graph && graphcanvas.graph != this) {\n graphcanvas.graph.detachCanvas(graphcanvas);\n }\n graphcanvas.graph = this;\n if (!this.list_of_graphcanvas) {\n this.list_of_graphcanvas = [];\n }\n this.list_of_graphcanvas.push(graphcanvas);\n }\n /**\n * Detach Canvas from this graph\n * @method detachCanvas\n * @param {GraphCanvas} graph_canvas\n */\n detachCanvas(graphcanvas) {\n if (!this.list_of_graphcanvas) {\n return;\n }\n var pos2 = this.list_of_graphcanvas.indexOf(graphcanvas);\n if (pos2 == -1) {\n return;\n }\n graphcanvas.graph = null;\n this.list_of_graphcanvas.splice(pos2, 1);\n }\n /**\n * Starts running this graph every interval milliseconds.\n * @method start\n * @param {number} interval amount of milliseconds between executions, if 0 then it renders to the monitor refresh rate\n */\n start(interval) {\n if (this.status == _LGraph.STATUS_RUNNING) {\n return;\n }\n this.status = _LGraph.STATUS_RUNNING;\n if (this.onPlayEvent) {\n this.onPlayEvent();\n }\n this.sendEventToAllNodes(\"onStart\");\n this.starttime = LiteGraph.getTime();\n this.last_update_time = this.starttime;\n interval = interval || 0;\n var that2 = this;\n if (interval == 0 && typeof window != \"undefined\" && window.requestAnimationFrame) {\n let on_frame = function() {\n if (that2.execution_timer_id != -1) {\n return;\n }\n window.requestAnimationFrame(on_frame);\n if (that2.onBeforeStep)\n that2.onBeforeStep();\n that2.runStep(1, !that2.catch_errors);\n if (that2.onAfterStep)\n that2.onAfterStep();\n };\n this.execution_timer_id = -1;\n on_frame();\n } else {\n this.execution_timer_id = setInterval(function() {\n if (that2.onBeforeStep)\n that2.onBeforeStep();\n that2.runStep(1, !that2.catch_errors);\n if (that2.onAfterStep)\n that2.onAfterStep();\n }, interval);\n }\n }\n /**\n * Stops the execution loop of the graph\n * @method stop execution\n */\n stop() {\n if (this.status == _LGraph.STATUS_STOPPED) {\n return;\n }\n this.status = _LGraph.STATUS_STOPPED;\n if (this.onStopEvent) {\n this.onStopEvent();\n }\n if (this.execution_timer_id != null) {\n if (this.execution_timer_id != -1) {\n clearInterval(this.execution_timer_id);\n }\n this.execution_timer_id = null;\n }\n this.sendEventToAllNodes(\"onStop\");\n }\n /**\n * Run N steps (cycles) of the graph\n * @method runStep\n * @param {number} num number of steps to run, default is 1\n * @param {Boolean} do_not_catch_errors [optional] if you want to try/catch errors\n * @param {number} limit max number of nodes to execute (used to execute from start to a node)\n */\n runStep(num, do_not_catch_errors, limit) {\n num = num || 1;\n var start = LiteGraph.getTime();\n this.globaltime = 1e-3 * (start - this.starttime);\n var nodes = this._nodes_executable ? this._nodes_executable : this._nodes;\n if (!nodes) {\n return;\n }\n limit = limit || nodes.length;\n if (do_not_catch_errors) {\n for (var i2 = 0; i2 < num; i2++) {\n for (var j = 0; j < limit; ++j) {\n var node2 = nodes[j];\n if (node2.mode == LiteGraph.ALWAYS && node2.onExecute) {\n node2.doExecute();\n }\n }\n this.fixedtime += this.fixedtime_lapse;\n if (this.onExecuteStep) {\n this.onExecuteStep();\n }\n }\n if (this.onAfterExecute) {\n this.onAfterExecute();\n }\n } else {\n try {\n for (var i2 = 0; i2 < num; i2++) {\n for (var j = 0; j < limit; ++j) {\n var node2 = nodes[j];\n if (node2.mode == LiteGraph.ALWAYS && node2.onExecute) {\n node2.onExecute();\n }\n }\n this.fixedtime += this.fixedtime_lapse;\n if (this.onExecuteStep) {\n this.onExecuteStep();\n }\n }\n if (this.onAfterExecute) {\n this.onAfterExecute();\n }\n this.errors_in_execution = false;\n } catch (err) {\n this.errors_in_execution = true;\n if (LiteGraph.throw_errors) {\n throw err;\n }\n if (LiteGraph.debug) {\n console.log(\"Error during execution: \" + err);\n }\n this.stop();\n }\n }\n var now = LiteGraph.getTime();\n var elapsed = now - start;\n if (elapsed == 0) {\n elapsed = 1;\n }\n this.execution_time = 1e-3 * elapsed;\n this.globaltime += 1e-3 * elapsed;\n this.iteration += 1;\n this.elapsed_time = (now - this.last_update_time) * 1e-3;\n this.last_update_time = now;\n this.nodes_executing = [];\n this.nodes_actioning = [];\n this.nodes_executedAction = [];\n }\n /**\n * Updates the graph execution order according to relevance of the nodes (nodes with only outputs have more relevance than\n * nodes with only inputs.\n * @method updateExecutionOrder\n */\n updateExecutionOrder() {\n this._nodes_in_order = this.computeExecutionOrder(false);\n this._nodes_executable = [];\n for (var i2 = 0; i2 < this._nodes_in_order.length; ++i2) {\n if (this._nodes_in_order[i2].onExecute) {\n this._nodes_executable.push(this._nodes_in_order[i2]);\n }\n }\n }\n //This is more internal, it computes the executable nodes in order and returns it\n computeExecutionOrder(only_onExecute, set_level) {\n var L = [];\n var S = [];\n var M = {};\n var visited_links = {};\n var remaining_links = {};\n for (var i2 = 0, l = this._nodes.length; i2 < l; ++i2) {\n var node2 = this._nodes[i2];\n if (only_onExecute && !node2.onExecute) {\n continue;\n }\n M[node2.id] = node2;\n var num = 0;\n if (node2.inputs) {\n for (var j = 0, l2 = node2.inputs.length; j < l2; j++) {\n if (node2.inputs[j] && node2.inputs[j].link != null) {\n num += 1;\n }\n }\n }\n if (num == 0) {\n S.push(node2);\n if (set_level) {\n node2._level = 1;\n }\n } else {\n if (set_level) {\n node2._level = 0;\n }\n remaining_links[node2.id] = num;\n }\n }\n while (true) {\n if (S.length == 0) {\n break;\n }\n var node2 = S.shift();\n L.push(node2);\n delete M[node2.id];\n if (!node2.outputs) {\n continue;\n }\n for (var i2 = 0; i2 < node2.outputs.length; i2++) {\n var output = node2.outputs[i2];\n if (output == null || output.links == null || output.links.length == 0) {\n continue;\n }\n for (var j = 0; j < output.links.length; j++) {\n var link_id = output.links[j];\n var link = this.links[link_id];\n if (!link) {\n continue;\n }\n if (visited_links[link.id]) {\n continue;\n }\n var target_node = this.getNodeById(link.target_id);\n if (target_node == null) {\n visited_links[link.id] = true;\n continue;\n }\n if (set_level && (!target_node._level || target_node._level <= node2._level)) {\n target_node._level = node2._level + 1;\n }\n visited_links[link.id] = true;\n remaining_links[target_node.id] -= 1;\n if (remaining_links[target_node.id] == 0) {\n S.push(target_node);\n }\n }\n }\n }\n for (var i2 in M) {\n L.push(M[i2]);\n }\n if (L.length != this._nodes.length && LiteGraph.debug) {\n console.warn(\"something went wrong, nodes missing\");\n }\n var l = L.length;\n for (var i2 = 0; i2 < l; ++i2) {\n L[i2].order = i2;\n }\n L = L.sort(function(A, B) {\n var Ap = A.constructor.priority || A.priority || 0;\n var Bp = B.constructor.priority || B.priority || 0;\n if (Ap == Bp) {\n return A.order - B.order;\n }\n return Ap - Bp;\n });\n for (var i2 = 0; i2 < l; ++i2) {\n L[i2].order = i2;\n }\n return L;\n }\n /**\n * Returns all the nodes that could affect this one (ancestors) by crawling all the inputs recursively.\n * It doesn't include the node itself\n * @method getAncestors\n * @return {Array} an array with all the LGraphNodes that affect this node, in order of execution\n */\n getAncestors(node2) {\n var ancestors = [];\n var pending = [node2];\n var visited = {};\n while (pending.length) {\n var current = pending.shift();\n if (!current.inputs) {\n continue;\n }\n if (!visited[current.id] && current != node2) {\n visited[current.id] = true;\n ancestors.push(current);\n }\n for (var i2 = 0; i2 < current.inputs.length; ++i2) {\n var input = current.getInputNode(i2);\n if (input && ancestors.indexOf(input) == -1) {\n pending.push(input);\n }\n }\n }\n ancestors.sort(function(a, b) {\n return a.order - b.order;\n });\n return ancestors;\n }\n /**\n * Positions every node in a more readable manner\n * @method arrange\n */\n arrange(margin, layout) {\n margin = margin || 100;\n const nodes = this.computeExecutionOrder(false, true);\n const columns = [];\n for (let i2 = 0; i2 < nodes.length; ++i2) {\n const node2 = nodes[i2];\n const col = node2._level || 1;\n if (!columns[col]) {\n columns[col] = [];\n }\n columns[col].push(node2);\n }\n let x2 = margin;\n for (let i2 = 0; i2 < columns.length; ++i2) {\n const column = columns[i2];\n if (!column) {\n continue;\n }\n let max_size = 100;\n let y2 = margin + LiteGraph.NODE_TITLE_HEIGHT;\n for (let j = 0; j < column.length; ++j) {\n const node2 = column[j];\n node2.pos[0] = layout == LiteGraph.VERTICAL_LAYOUT ? y2 : x2;\n node2.pos[1] = layout == LiteGraph.VERTICAL_LAYOUT ? x2 : y2;\n const max_size_index = layout == LiteGraph.VERTICAL_LAYOUT ? 1 : 0;\n if (node2.size[max_size_index] > max_size) {\n max_size = node2.size[max_size_index];\n }\n const node_size_index = layout == LiteGraph.VERTICAL_LAYOUT ? 0 : 1;\n y2 += node2.size[node_size_index] + margin + LiteGraph.NODE_TITLE_HEIGHT;\n }\n x2 += max_size + margin;\n }\n this.setDirtyCanvas(true, true);\n }\n /**\n * Returns the amount of time the graph has been running in milliseconds\n * @method getTime\n * @return {number} number of milliseconds the graph has been running\n */\n getTime() {\n return this.globaltime;\n }\n /**\n * Returns the amount of time accumulated using the fixedtime_lapse var. This is used in context where the time increments should be constant\n * @method getFixedTime\n * @return {number} number of milliseconds the graph has been running\n */\n getFixedTime() {\n return this.fixedtime;\n }\n /**\n * Returns the amount of time it took to compute the latest iteration. Take into account that this number could be not correct\n * if the nodes are using graphical actions\n * @method getElapsedTime\n * @return {number} number of milliseconds it took the last cycle\n */\n getElapsedTime() {\n return this.elapsed_time;\n }\n /**\n * Sends an event to all the nodes, useful to trigger stuff\n * @method sendEventToAllNodes\n * @param {String} eventname the name of the event (function to be called)\n * @param {Array} params parameters in array format\n */\n sendEventToAllNodes(eventname, params, mode) {\n mode = mode || LiteGraph.ALWAYS;\n var nodes = this._nodes_in_order ? this._nodes_in_order : this._nodes;\n if (!nodes) {\n return;\n }\n for (var j = 0, l = nodes.length; j < l; ++j) {\n var node2 = nodes[j];\n if (node2.constructor === LiteGraph.Subgraph && eventname != \"onExecute\") {\n if (node2.mode == mode) {\n node2.sendEventToAllNodes(eventname, params, mode);\n }\n continue;\n }\n if (!node2[eventname] || node2.mode != mode) {\n continue;\n }\n if (params === void 0) {\n node2[eventname]();\n } else if (params && params.constructor === Array) {\n node2[eventname].apply(node2, params);\n } else {\n node2[eventname](params);\n }\n }\n }\n sendActionToCanvas(action, params) {\n if (!this.list_of_graphcanvas) {\n return;\n }\n for (var i2 = 0; i2 < this.list_of_graphcanvas.length; ++i2) {\n var c = this.list_of_graphcanvas[i2];\n if (c[action]) {\n c[action].apply(c, params);\n }\n }\n }\n /**\n * Adds a new node instance to this graph\n * @method add\n * @param {LGraphNode} node the instance of the node\n */\n add(node2, skip_compute_order) {\n if (!node2) {\n return;\n }\n if (node2.constructor === LGraphGroup) {\n this._groups.push(node2);\n this.setDirtyCanvas(true);\n this.change();\n node2.graph = this;\n this._version++;\n return;\n }\n if (node2.id != -1 && this._nodes_by_id[node2.id] != null) {\n console.warn(\n \"LiteGraph: there is already a node with this ID, changing it\"\n );\n if (LiteGraph.use_uuids) {\n node2.id = LiteGraph.uuidv4();\n } else {\n node2.id = ++this.last_node_id;\n }\n }\n if (this._nodes.length >= LiteGraph.MAX_NUMBER_OF_NODES) {\n throw \"LiteGraph: max number of nodes in a graph reached\";\n }\n if (LiteGraph.use_uuids) {\n if (node2.id == null || node2.id == -1)\n node2.id = LiteGraph.uuidv4();\n } else {\n if (node2.id == null || node2.id == -1) {\n node2.id = ++this.last_node_id;\n } else if (this.last_node_id < node2.id) {\n this.last_node_id = node2.id;\n }\n }\n node2.graph = this;\n this._version++;\n this._nodes.push(node2);\n this._nodes_by_id[node2.id] = node2;\n if (node2.onAdded) {\n node2.onAdded(this);\n }\n if (this.config.align_to_grid) {\n node2.alignToGrid();\n }\n if (!skip_compute_order) {\n this.updateExecutionOrder();\n }\n if (this.onNodeAdded) {\n this.onNodeAdded(node2);\n }\n this.setDirtyCanvas(true);\n this.change();\n return node2;\n }\n /**\n * Removes a node from the graph\n * @method remove\n * @param {LGraphNode} node the instance of the node\n */\n remove(node2) {\n if (node2.constructor === LiteGraph.LGraphGroup) {\n var index2 = this._groups.indexOf(node2);\n if (index2 != -1) {\n this._groups.splice(index2, 1);\n }\n node2.graph = null;\n this._version++;\n this.setDirtyCanvas(true, true);\n this.change();\n return;\n }\n if (this._nodes_by_id[node2.id] == null) {\n return;\n }\n if (node2.ignore_remove) {\n return;\n }\n this.beforeChange();\n if (node2.inputs) {\n for (var i2 = 0; i2 < node2.inputs.length; i2++) {\n var slot = node2.inputs[i2];\n if (slot.link != null) {\n node2.disconnectInput(i2);\n }\n }\n }\n if (node2.outputs) {\n for (var i2 = 0; i2 < node2.outputs.length; i2++) {\n var slot = node2.outputs[i2];\n if (slot.links != null && slot.links.length) {\n node2.disconnectOutput(i2);\n }\n }\n }\n if (node2.onRemoved) {\n node2.onRemoved();\n }\n node2.graph = null;\n this._version++;\n if (this.list_of_graphcanvas) {\n for (var i2 = 0; i2 < this.list_of_graphcanvas.length; ++i2) {\n var canvas = this.list_of_graphcanvas[i2];\n if (canvas.selected_nodes[node2.id]) {\n delete canvas.selected_nodes[node2.id];\n }\n if (canvas.node_dragged == node2) {\n canvas.node_dragged = null;\n }\n }\n }\n var pos2 = this._nodes.indexOf(node2);\n if (pos2 != -1) {\n this._nodes.splice(pos2, 1);\n }\n delete this._nodes_by_id[node2.id];\n if (this.onNodeRemoved) {\n this.onNodeRemoved(node2);\n }\n this.sendActionToCanvas(\"checkPanels\");\n this.setDirtyCanvas(true, true);\n this.afterChange();\n this.change();\n this.updateExecutionOrder();\n }\n /**\n * Returns a node by its id.\n * @method getNodeById\n * @param {Number} id\n */\n getNodeById(id) {\n if (id == null) {\n return null;\n }\n return this._nodes_by_id[id];\n }\n /**\n * Returns a list of nodes that matches a class\n * @method findNodesByClass\n * @param {Class} classObject the class itself (not an string)\n * @return {Array} a list with all the nodes of this type\n */\n findNodesByClass(classObject, result) {\n result = result || [];\n result.length = 0;\n for (var i2 = 0, l = this._nodes.length; i2 < l; ++i2) {\n if (this._nodes[i2].constructor === classObject) {\n result.push(this._nodes[i2]);\n }\n }\n return result;\n }\n /**\n * Returns a list of nodes that matches a type\n * @method findNodesByType\n * @param {String} type the name of the node type\n * @return {Array} a list with all the nodes of this type\n */\n findNodesByType(type, result) {\n var type = type.toLowerCase();\n result = result || [];\n result.length = 0;\n for (var i2 = 0, l = this._nodes.length; i2 < l; ++i2) {\n if (this._nodes[i2].type.toLowerCase() == type) {\n result.push(this._nodes[i2]);\n }\n }\n return result;\n }\n /**\n * Returns the first node that matches a name in its title\n * @method findNodeByTitle\n * @param {String} name the name of the node to search\n * @return {Node} the node or null\n */\n findNodeByTitle(title) {\n for (var i2 = 0, l = this._nodes.length; i2 < l; ++i2) {\n if (this._nodes[i2].title == title) {\n return this._nodes[i2];\n }\n }\n return null;\n }\n /**\n * Returns a list of nodes that matches a name\n * @method findNodesByTitle\n * @param {String} name the name of the node to search\n * @return {Array} a list with all the nodes with this name\n */\n findNodesByTitle(title) {\n var result = [];\n for (var i2 = 0, l = this._nodes.length; i2 < l; ++i2) {\n if (this._nodes[i2].title == title) {\n result.push(this._nodes[i2]);\n }\n }\n return result;\n }\n /**\n * Returns the top-most node in this position of the canvas\n * @method getNodeOnPos\n * @param {number} x the x coordinate in canvas space\n * @param {number} y the y coordinate in canvas space\n * @param {Array} nodes_list a list with all the nodes to search from, by default is all the nodes in the graph\n * @return {LGraphNode} the node at this position or null\n */\n getNodeOnPos(x2, y2, nodes_list, margin) {\n nodes_list = nodes_list || this._nodes;\n var nRet = null;\n for (var i2 = nodes_list.length - 1; i2 >= 0; i2--) {\n var n = nodes_list[i2];\n var skip_title = n.constructor.title_mode == LiteGraph.NO_TITLE;\n if (n.isPointInside(x2, y2, margin, skip_title)) {\n return n;\n }\n }\n return nRet;\n }\n /**\n * Returns the top-most group in that position\n * @method getGroupOnPos\n * @param {number} x the x coordinate in canvas space\n * @param {number} y the y coordinate in canvas space\n * @return {LGraphGroup} the group or null\n */\n getGroupOnPos(x2, y2) {\n for (var i2 = this._groups.length - 1; i2 >= 0; i2--) {\n var g = this._groups[i2];\n if (g.isPointInside(x2, y2, 2, true)) {\n return g;\n }\n }\n return null;\n }\n /**\n * Checks that the node type matches the node type registered, used when replacing a nodetype by a newer version during execution\n * this replaces the ones using the old version with the new version\n * @method checkNodeTypes\n */\n checkNodeTypes() {\n for (var i2 = 0; i2 < this._nodes.length; i2++) {\n var node2 = this._nodes[i2];\n var ctor = LiteGraph.registered_node_types[node2.type];\n if (node2.constructor == ctor) {\n continue;\n }\n console.log(\"node being replaced by newer version: \" + node2.type);\n var newnode = LiteGraph.createNode(node2.type);\n this._nodes[i2] = newnode;\n newnode.configure(node2.serialize());\n newnode.graph = this;\n this._nodes_by_id[newnode.id] = newnode;\n if (node2.inputs) {\n newnode.inputs = node2.inputs.concat();\n }\n if (node2.outputs) {\n newnode.outputs = node2.outputs.concat();\n }\n }\n this.updateExecutionOrder();\n }\n // ********** GLOBALS *****************\n onAction(action, param, options) {\n this._input_nodes = this.findNodesByClass(\n LiteGraph.GraphInput,\n this._input_nodes\n );\n for (var i2 = 0; i2 < this._input_nodes.length; ++i2) {\n var node2 = this._input_nodes[i2];\n if (node2.properties.name != action) {\n continue;\n }\n node2.actionDo(action, param, options);\n break;\n }\n }\n trigger(action, param) {\n if (this.onTrigger) {\n this.onTrigger(action, param);\n }\n }\n /**\n * Tell this graph it has a global graph input of this type\n * @method addGlobalInput\n * @param {String} name\n * @param {String} type\n * @param {*} value [optional]\n */\n addInput(name, type, value) {\n var input = this.inputs[name];\n if (input) {\n return;\n }\n this.beforeChange();\n this.inputs[name] = { name, type, value };\n this._version++;\n this.afterChange();\n if (this.onInputAdded) {\n this.onInputAdded(name, type);\n }\n if (this.onInputsOutputsChange) {\n this.onInputsOutputsChange();\n }\n }\n /**\n * Assign a data to the global graph input\n * @method setGlobalInputData\n * @param {String} name\n * @param {*} data\n */\n setInputData(name, data) {\n var input = this.inputs[name];\n if (!input) {\n return;\n }\n input.value = data;\n }\n /**\n * Returns the current value of a global graph input\n * @method getInputData\n * @param {String} name\n * @return {*} the data\n */\n getInputData(name) {\n var input = this.inputs[name];\n if (!input) {\n return null;\n }\n return input.value;\n }\n /**\n * Changes the name of a global graph input\n * @method renameInput\n * @param {String} old_name\n * @param {String} new_name\n */\n renameInput(old_name, name) {\n if (name == old_name) {\n return;\n }\n if (!this.inputs[old_name]) {\n return false;\n }\n if (this.inputs[name]) {\n console.error(\"there is already one input with that name\");\n return false;\n }\n this.inputs[name] = this.inputs[old_name];\n delete this.inputs[old_name];\n this._version++;\n if (this.onInputRenamed) {\n this.onInputRenamed(old_name, name);\n }\n if (this.onInputsOutputsChange) {\n this.onInputsOutputsChange();\n }\n }\n /**\n * Changes the type of a global graph input\n * @method changeInputType\n * @param {String} name\n * @param {String} type\n */\n changeInputType(name, type) {\n if (!this.inputs[name]) {\n return false;\n }\n if (this.inputs[name].type && String(this.inputs[name].type).toLowerCase() == String(type).toLowerCase()) {\n return;\n }\n this.inputs[name].type = type;\n this._version++;\n if (this.onInputTypeChanged) {\n this.onInputTypeChanged(name, type);\n }\n }\n /**\n * Removes a global graph input\n * @method removeInput\n * @param {String} name\n * @param {String} type\n */\n removeInput(name) {\n if (!this.inputs[name]) {\n return false;\n }\n delete this.inputs[name];\n this._version++;\n if (this.onInputRemoved) {\n this.onInputRemoved(name);\n }\n if (this.onInputsOutputsChange) {\n this.onInputsOutputsChange();\n }\n return true;\n }\n /**\n * Creates a global graph output\n * @method addOutput\n * @param {String} name\n * @param {String} type\n * @param {*} value\n */\n addOutput(name, type, value) {\n this.outputs[name] = { name, type, value };\n this._version++;\n if (this.onOutputAdded) {\n this.onOutputAdded(name, type);\n }\n if (this.onInputsOutputsChange) {\n this.onInputsOutputsChange();\n }\n }\n /**\n * Assign a data to the global output\n * @method setOutputData\n * @param {String} name\n * @param {String} value\n */\n setOutputData(name, value) {\n var output = this.outputs[name];\n if (!output) {\n return;\n }\n output.value = value;\n }\n /**\n * Returns the current value of a global graph output\n * @method getOutputData\n * @param {String} name\n * @return {*} the data\n */\n getOutputData(name) {\n var output = this.outputs[name];\n if (!output) {\n return null;\n }\n return output.value;\n }\n /**\n * Renames a global graph output\n * @method renameOutput\n * @param {String} old_name\n * @param {String} new_name\n */\n renameOutput(old_name, name) {\n if (!this.outputs[old_name]) {\n return false;\n }\n if (this.outputs[name]) {\n console.error(\"there is already one output with that name\");\n return false;\n }\n this.outputs[name] = this.outputs[old_name];\n delete this.outputs[old_name];\n this._version++;\n if (this.onOutputRenamed) {\n this.onOutputRenamed(old_name, name);\n }\n if (this.onInputsOutputsChange) {\n this.onInputsOutputsChange();\n }\n }\n /**\n * Changes the type of a global graph output\n * @method changeOutputType\n * @param {String} name\n * @param {String} type\n */\n changeOutputType(name, type) {\n if (!this.outputs[name]) {\n return false;\n }\n if (this.outputs[name].type && String(this.outputs[name].type).toLowerCase() == String(type).toLowerCase()) {\n return;\n }\n this.outputs[name].type = type;\n this._version++;\n if (this.onOutputTypeChanged) {\n this.onOutputTypeChanged(name, type);\n }\n }\n /**\n * Removes a global graph output\n * @method removeOutput\n * @param {String} name\n */\n removeOutput(name) {\n if (!this.outputs[name]) {\n return false;\n }\n delete this.outputs[name];\n this._version++;\n if (this.onOutputRemoved) {\n this.onOutputRemoved(name);\n }\n if (this.onInputsOutputsChange) {\n this.onInputsOutputsChange();\n }\n return true;\n }\n triggerInput(name, value) {\n var nodes = this.findNodesByTitle(name);\n for (var i2 = 0; i2 < nodes.length; ++i2) {\n nodes[i2].onTrigger(value);\n }\n }\n setCallback(name, func) {\n var nodes = this.findNodesByTitle(name);\n for (var i2 = 0; i2 < nodes.length; ++i2) {\n nodes[i2].setTrigger(func);\n }\n }\n //used for undo, called before any change is made to the graph\n beforeChange(info) {\n if (this.onBeforeChange) {\n this.onBeforeChange(this, info);\n }\n this.sendActionToCanvas(\"onBeforeChange\", this);\n }\n //used to resend actions, called after any change is made to the graph\n afterChange(info) {\n if (this.onAfterChange) {\n this.onAfterChange(this, info);\n }\n this.sendActionToCanvas(\"onAfterChange\", this);\n }\n connectionChange(node2, link_info) {\n this.updateExecutionOrder();\n if (this.onConnectionChange) {\n this.onConnectionChange(node2);\n }\n this._version++;\n this.sendActionToCanvas(\"onConnectionChange\");\n }\n /**\n * returns if the graph is in live mode\n * @method isLive\n */\n isLive() {\n if (!this.list_of_graphcanvas) {\n return false;\n }\n for (var i2 = 0; i2 < this.list_of_graphcanvas.length; ++i2) {\n var c = this.list_of_graphcanvas[i2];\n if (c.live_mode) {\n return true;\n }\n }\n return false;\n }\n /**\n * clears the triggered slot animation in all links (stop visual animation)\n * @method clearTriggeredSlots\n */\n clearTriggeredSlots() {\n for (var i2 in this.links) {\n var link_info = this.links[i2];\n if (!link_info) {\n continue;\n }\n if (link_info._last_time) {\n link_info._last_time = 0;\n }\n }\n }\n /* Called when something visually changed (not the graph!) */\n change() {\n if (LiteGraph.debug) {\n console.log(\"Graph changed\");\n }\n this.sendActionToCanvas(\"setDirty\", [true, true]);\n if (this.on_change) {\n this.on_change(this);\n }\n }\n setDirtyCanvas(fg, bg) {\n this.sendActionToCanvas(\"setDirty\", [fg, bg]);\n }\n /**\n * Destroys a link\n * @method removeLink\n * @param {Number} link_id\n */\n removeLink(link_id) {\n var link = this.links[link_id];\n if (!link) {\n return;\n }\n var node2 = this.getNodeById(link.target_id);\n if (node2) {\n node2.disconnectInput(link.target_slot);\n }\n }\n //save and recover app state ***************************************\n /**\n * Creates a Object containing all the info about this graph, it can be serialized\n * @method serialize\n * @return {Object} value of the node\n */\n serialize() {\n var nodes_info = [];\n nodes_info = this._nodes.sort((a, b) => a.id - b.id).map((node2) => node2.serialize());\n var links = [];\n for (var i2 in this.links) {\n var link = this.links[i2];\n if (!link.serialize) {\n console.warn(\n \"weird LLink bug, link info is not a LLink but a regular object\"\n );\n var link2 = new LLink();\n for (var j in link) {\n link2[j] = link[j];\n }\n this.links[i2] = link2;\n link = link2;\n }\n links.push(link.serialize());\n }\n var groups_info = [];\n for (var i2 = 0; i2 < this._groups.length; ++i2) {\n groups_info.push(this._groups[i2].serialize());\n }\n var data = {\n last_node_id: this.last_node_id,\n last_link_id: this.last_link_id,\n nodes: nodes_info,\n links,\n groups: groups_info,\n config: this.config,\n extra: this.extra,\n version: LiteGraph.VERSION\n };\n if (this.onSerialize)\n this.onSerialize(data);\n return data;\n }\n /**\n * Configure a graph from a JSON string\n * @method configure\n * @param {String} str configure a graph from a JSON string\n * @param {Boolean} returns if there was any error parsing\n */\n configure(data, keep_old) {\n if (!data) {\n return;\n }\n if (!keep_old) {\n this.clear();\n }\n var nodes = data.nodes;\n if (data.links && data.links.constructor === Array) {\n var links = [];\n for (var i2 = 0; i2 < data.links.length; ++i2) {\n var link_data = data.links[i2];\n if (!link_data) {\n console.warn(\"serialized graph link data contains errors, skipping.\");\n continue;\n }\n var link = new LLink();\n link.configure(link_data);\n links[link.id] = link;\n }\n data.links = links;\n }\n for (var i2 in data) {\n if (i2 == \"nodes\" || i2 == \"groups\")\n continue;\n this[i2] = data[i2];\n }\n var error = false;\n this._nodes = [];\n if (nodes) {\n for (var i2 = 0, l = nodes.length; i2 < l; ++i2) {\n var n_info = nodes[i2];\n var node2 = LiteGraph.createNode(n_info.type, n_info.title);\n if (!node2) {\n if (LiteGraph.debug) {\n console.log(\n \"Node not found or has errors: \" + n_info.type\n );\n }\n node2 = new LGraphNode();\n node2.last_serialization = n_info;\n node2.has_errors = true;\n error = true;\n }\n node2.id = n_info.id;\n this.add(node2, true);\n }\n for (var i2 = 0, l = nodes.length; i2 < l; ++i2) {\n var n_info = nodes[i2];\n var node2 = this.getNodeById(n_info.id);\n if (node2) {\n node2.configure(n_info);\n }\n }\n }\n this._groups.length = 0;\n if (data.groups) {\n for (var i2 = 0; i2 < data.groups.length; ++i2) {\n var group = new LiteGraph.LGraphGroup();\n group.configure(data.groups[i2]);\n this.add(group);\n }\n }\n this.updateExecutionOrder();\n this.extra = data.extra || {};\n if (this.onConfigure)\n this.onConfigure(data);\n this._version++;\n this.setDirtyCanvas(true, true);\n return error;\n }\n load(url, callback) {\n var that2 = this;\n if (url.constructor === File || url.constructor === Blob) {\n var reader = new FileReader();\n reader.addEventListener(\"load\", function(event2) {\n var data = JSON.parse(event2.target.result);\n that2.configure(data);\n if (callback)\n callback();\n });\n reader.readAsText(url);\n return;\n }\n var req = new XMLHttpRequest();\n req.open(\"GET\", url, true);\n req.send(null);\n req.onload = function(oEvent) {\n if (req.status !== 200) {\n console.error(\"Error loading graph:\", req.status, req.response);\n return;\n }\n var data = JSON.parse(req.response);\n that2.configure(data);\n if (callback)\n callback();\n };\n req.onerror = function(err) {\n console.error(\"Error loading graph:\", err);\n };\n }\n onNodeTrace(node2, msg, color) {\n }\n };\n //default supported types\n __publicField(_LGraph, \"supported_types\", [\"number\", \"string\", \"boolean\"]);\n __publicField(_LGraph, \"STATUS_STOPPED\", 1);\n __publicField(_LGraph, \"STATUS_RUNNING\", 2);\n let LGraph = _LGraph;\n function LegacyLGraph(...args) {\n return new LGraph(...args);\n }\n LegacyLGraph.prototype = LGraph.prototype;\n globalThis.LGraph = LGraph;\n globalThis.LegacyLGraph = LiteGraph.LGraph = LegacyLGraph;\n function LLink(id, type, origin_id, origin_slot, target_id, target_slot) {\n this.id = id;\n this.type = type;\n this.origin_id = origin_id;\n this.origin_slot = origin_slot;\n this.target_id = target_id;\n this.target_slot = target_slot;\n this._data = null;\n this._pos = new Float32Array(2);\n }\n LLink.prototype.configure = function(o) {\n if (o.constructor === Array) {\n this.id = o[0];\n this.origin_id = o[1];\n this.origin_slot = o[2];\n this.target_id = o[3];\n this.target_slot = o[4];\n this.type = o[5];\n } else {\n this.id = o.id;\n this.type = o.type;\n this.origin_id = o.origin_id;\n this.origin_slot = o.origin_slot;\n this.target_id = o.target_id;\n this.target_slot = o.target_slot;\n }\n };\n LLink.prototype.serialize = function() {\n return [\n this.id,\n this.origin_id,\n this.origin_slot,\n this.target_id,\n this.target_slot,\n this.type\n ];\n };\n LiteGraph.LLink = LLink;\n function LGraphNode(title) {\n this._ctor(title);\n }\n globalThis.LGraphNode = LiteGraph.LGraphNode = LGraphNode;\n LGraphNode.prototype._ctor = function(title) {\n this.title = title || \"Unnamed\";\n this.size = [LiteGraph.NODE_WIDTH, 60];\n this.graph = null;\n this._pos = new Float32Array(10, 10);\n Object.defineProperty(this, \"pos\", {\n set: function(v2) {\n if (!v2 || v2.length < 2) {\n return;\n }\n this._pos[0] = v2[0];\n this._pos[1] = v2[1];\n },\n get: function() {\n return this._pos;\n },\n enumerable: true\n });\n if (LiteGraph.use_uuids) {\n this.id = LiteGraph.uuidv4();\n } else {\n this.id = -1;\n }\n this.type = null;\n this.inputs = [];\n this.outputs = [];\n this.connections = [];\n this.properties = {};\n this.properties_info = [];\n this.flags = {};\n };\n LGraphNode.prototype.configure = function(info) {\n if (this.graph) {\n this.graph._version++;\n }\n for (var j in info) {\n if (j == \"properties\") {\n for (var k in info.properties) {\n this.properties[k] = info.properties[k];\n if (this.onPropertyChanged) {\n this.onPropertyChanged(k, info.properties[k]);\n }\n }\n continue;\n }\n if (info[j] == null) {\n continue;\n } else if (typeof info[j] == \"object\") {\n if (this[j] && this[j].configure) {\n this[j].configure(info[j]);\n } else {\n this[j] = LiteGraph.cloneObject(info[j], this[j]);\n }\n } else {\n this[j] = info[j];\n }\n }\n if (!info.title) {\n this.title = this.constructor.title;\n }\n if (this.inputs) {\n for (var i2 = 0; i2 < this.inputs.length; ++i2) {\n var input = this.inputs[i2];\n var link_info = this.graph ? this.graph.links[input.link] : null;\n if (this.onConnectionsChange)\n this.onConnectionsChange(LiteGraph.INPUT, i2, true, link_info, input);\n if (this.onInputAdded)\n this.onInputAdded(input);\n }\n }\n if (this.outputs) {\n for (var i2 = 0; i2 < this.outputs.length; ++i2) {\n var output = this.outputs[i2];\n if (!output.links) {\n continue;\n }\n for (var j = 0; j < output.links.length; ++j) {\n var link_info = this.graph ? this.graph.links[output.links[j]] : null;\n if (this.onConnectionsChange)\n this.onConnectionsChange(LiteGraph.OUTPUT, i2, true, link_info, output);\n }\n if (this.onOutputAdded)\n this.onOutputAdded(output);\n }\n }\n if (this.widgets) {\n for (var i2 = 0; i2 < this.widgets.length; ++i2) {\n var w2 = this.widgets[i2];\n if (!w2)\n continue;\n if (w2.options && w2.options.property && this.properties[w2.options.property] != void 0)\n w2.value = JSON.parse(JSON.stringify(this.properties[w2.options.property]));\n }\n if (info.widgets_values) {\n for (var i2 = 0; i2 < info.widgets_values.length; ++i2) {\n if (this.widgets[i2]) {\n this.widgets[i2].value = info.widgets_values[i2];\n }\n }\n }\n }\n if (this.onConfigure) {\n this.onConfigure(info);\n }\n };\n LGraphNode.prototype.serialize = function() {\n var o = {\n id: this.id,\n type: this.type,\n pos: this.pos,\n size: this.size,\n flags: LiteGraph.cloneObject(this.flags),\n order: this.order,\n mode: this.mode\n };\n if (this.constructor === LGraphNode && this.last_serialization) {\n return this.last_serialization;\n }\n if (this.inputs) {\n o.inputs = this.inputs;\n }\n if (this.outputs) {\n for (var i2 = 0; i2 < this.outputs.length; i2++) {\n delete this.outputs[i2]._data;\n }\n o.outputs = this.outputs;\n }\n if (this.title && this.title != this.constructor.title) {\n o.title = this.title;\n }\n if (this.properties) {\n o.properties = LiteGraph.cloneObject(this.properties);\n }\n if (this.widgets && this.serialize_widgets) {\n o.widgets_values = [];\n for (var i2 = 0; i2 < this.widgets.length; ++i2) {\n if (this.widgets[i2])\n o.widgets_values[i2] = this.widgets[i2].value;\n else\n o.widgets_values[i2] = null;\n }\n }\n if (!o.type) {\n o.type = this.constructor.type;\n }\n if (this.color) {\n o.color = this.color;\n }\n if (this.bgcolor) {\n o.bgcolor = this.bgcolor;\n }\n if (this.boxcolor) {\n o.boxcolor = this.boxcolor;\n }\n if (this.shape) {\n o.shape = this.shape;\n }\n if (this.onSerialize) {\n if (this.onSerialize(o)) {\n console.warn(\n \"node onSerialize shouldnt return anything, data should be stored in the object pass in the first parameter\"\n );\n }\n }\n return o;\n };\n LGraphNode.prototype.clone = function() {\n var node2 = LiteGraph.createNode(this.type);\n if (!node2) {\n return null;\n }\n var data = LiteGraph.cloneObject(this.serialize());\n if (data.inputs) {\n for (var i2 = 0; i2 < data.inputs.length; ++i2) {\n data.inputs[i2].link = null;\n }\n }\n if (data.outputs) {\n for (var i2 = 0; i2 < data.outputs.length; ++i2) {\n if (data.outputs[i2].links) {\n data.outputs[i2].links.length = 0;\n }\n }\n }\n delete data[\"id\"];\n if (LiteGraph.use_uuids) {\n data[\"id\"] = LiteGraph.uuidv4();\n }\n node2.configure(data);\n return node2;\n };\n LGraphNode.prototype.toString = function() {\n return JSON.stringify(this.serialize());\n };\n LGraphNode.prototype.getTitle = function() {\n return this.title || this.constructor.title;\n };\n LGraphNode.prototype.setProperty = function(name, value) {\n if (!this.properties) {\n this.properties = {};\n }\n if (value === this.properties[name])\n return;\n var prev_value = this.properties[name];\n this.properties[name] = value;\n if (this.onPropertyChanged) {\n if (this.onPropertyChanged(name, value, prev_value) === false)\n this.properties[name] = prev_value;\n }\n if (this.widgets)\n for (var i2 = 0; i2 < this.widgets.length; ++i2) {\n var w2 = this.widgets[i2];\n if (!w2)\n continue;\n if (w2.options.property == name) {\n w2.value = value;\n break;\n }\n }\n };\n LGraphNode.prototype.setOutputData = function(slot, data) {\n if (!this.outputs) {\n return;\n }\n if (slot == -1 || slot >= this.outputs.length) {\n return;\n }\n var output_info = this.outputs[slot];\n if (!output_info) {\n return;\n }\n output_info._data = data;\n if (this.outputs[slot].links) {\n for (var i2 = 0; i2 < this.outputs[slot].links.length; i2++) {\n var link_id = this.outputs[slot].links[i2];\n var link = this.graph.links[link_id];\n if (link)\n link.data = data;\n }\n }\n };\n LGraphNode.prototype.setOutputDataType = function(slot, type) {\n if (!this.outputs) {\n return;\n }\n if (slot == -1 || slot >= this.outputs.length) {\n return;\n }\n var output_info = this.outputs[slot];\n if (!output_info) {\n return;\n }\n output_info.type = type;\n if (this.outputs[slot].links) {\n for (var i2 = 0; i2 < this.outputs[slot].links.length; i2++) {\n var link_id = this.outputs[slot].links[i2];\n this.graph.links[link_id].type = type;\n }\n }\n };\n LGraphNode.prototype.getInputData = function(slot, force_update) {\n if (!this.inputs) {\n return;\n }\n if (slot >= this.inputs.length || this.inputs[slot].link == null) {\n return;\n }\n var link_id = this.inputs[slot].link;\n var link = this.graph.links[link_id];\n if (!link) {\n return null;\n }\n if (!force_update) {\n return link.data;\n }\n var node2 = this.graph.getNodeById(link.origin_id);\n if (!node2) {\n return link.data;\n }\n if (node2.updateOutputData) {\n node2.updateOutputData(link.origin_slot);\n } else if (node2.onExecute) {\n node2.onExecute();\n }\n return link.data;\n };\n LGraphNode.prototype.getInputDataType = function(slot) {\n if (!this.inputs) {\n return null;\n }\n if (slot >= this.inputs.length || this.inputs[slot].link == null) {\n return null;\n }\n var link_id = this.inputs[slot].link;\n var link = this.graph.links[link_id];\n if (!link) {\n return null;\n }\n var node2 = this.graph.getNodeById(link.origin_id);\n if (!node2) {\n return link.type;\n }\n var output_info = node2.outputs[link.origin_slot];\n if (output_info) {\n return output_info.type;\n }\n return null;\n };\n LGraphNode.prototype.getInputDataByName = function(slot_name, force_update) {\n var slot = this.findInputSlot(slot_name);\n if (slot == -1) {\n return null;\n }\n return this.getInputData(slot, force_update);\n };\n LGraphNode.prototype.isInputConnected = function(slot) {\n if (!this.inputs) {\n return false;\n }\n return slot < this.inputs.length && this.inputs[slot].link != null;\n };\n LGraphNode.prototype.getInputInfo = function(slot) {\n if (!this.inputs) {\n return null;\n }\n if (slot < this.inputs.length) {\n return this.inputs[slot];\n }\n return null;\n };\n LGraphNode.prototype.getInputLink = function(slot) {\n if (!this.inputs) {\n return null;\n }\n if (slot < this.inputs.length) {\n var slot_info = this.inputs[slot];\n return this.graph.links[slot_info.link];\n }\n return null;\n };\n LGraphNode.prototype.getInputNode = function(slot) {\n if (!this.inputs) {\n return null;\n }\n if (slot >= this.inputs.length) {\n return null;\n }\n var input = this.inputs[slot];\n if (!input || input.link === null) {\n return null;\n }\n var link_info = this.graph.links[input.link];\n if (!link_info) {\n return null;\n }\n return this.graph.getNodeById(link_info.origin_id);\n };\n LGraphNode.prototype.getInputOrProperty = function(name) {\n if (!this.inputs || !this.inputs.length) {\n return this.properties ? this.properties[name] : null;\n }\n for (var i2 = 0, l = this.inputs.length; i2 < l; ++i2) {\n var input_info = this.inputs[i2];\n if (name == input_info.name && input_info.link != null) {\n var link = this.graph.links[input_info.link];\n if (link) {\n return link.data;\n }\n }\n }\n return this.properties[name];\n };\n LGraphNode.prototype.getOutputData = function(slot) {\n if (!this.outputs) {\n return null;\n }\n if (slot >= this.outputs.length) {\n return null;\n }\n var info = this.outputs[slot];\n return info._data;\n };\n LGraphNode.prototype.getOutputInfo = function(slot) {\n if (!this.outputs) {\n return null;\n }\n if (slot < this.outputs.length) {\n return this.outputs[slot];\n }\n return null;\n };\n LGraphNode.prototype.isOutputConnected = function(slot) {\n if (!this.outputs) {\n return false;\n }\n return slot < this.outputs.length && this.outputs[slot].links && this.outputs[slot].links.length;\n };\n LGraphNode.prototype.isAnyOutputConnected = function() {\n if (!this.outputs) {\n return false;\n }\n for (var i2 = 0; i2 < this.outputs.length; ++i2) {\n if (this.outputs[i2].links && this.outputs[i2].links.length) {\n return true;\n }\n }\n return false;\n };\n LGraphNode.prototype.getOutputNodes = function(slot) {\n if (!this.outputs || this.outputs.length == 0) {\n return null;\n }\n if (slot >= this.outputs.length) {\n return null;\n }\n var output = this.outputs[slot];\n if (!output.links || output.links.length == 0) {\n return null;\n }\n var r = [];\n for (var i2 = 0; i2 < output.links.length; i2++) {\n var link_id = output.links[i2];\n var link = this.graph.links[link_id];\n if (link) {\n var target_node = this.graph.getNodeById(link.target_id);\n if (target_node) {\n r.push(target_node);\n }\n }\n }\n return r;\n };\n LGraphNode.prototype.addOnTriggerInput = function() {\n var trigS = this.findInputSlot(\"onTrigger\");\n if (trigS == -1) {\n //!trigS || \n this.addInput(\"onTrigger\", LiteGraph.EVENT, { optional: true, nameLocked: true });\n return this.findInputSlot(\"onTrigger\");\n }\n return trigS;\n };\n LGraphNode.prototype.addOnExecutedOutput = function() {\n var trigS = this.findOutputSlot(\"onExecuted\");\n if (trigS == -1) {\n //!trigS || \n this.addOutput(\"onExecuted\", LiteGraph.ACTION, { optional: true, nameLocked: true });\n return this.findOutputSlot(\"onExecuted\");\n }\n return trigS;\n };\n LGraphNode.prototype.onAfterExecuteNode = function(param, options) {\n var trigS = this.findOutputSlot(\"onExecuted\");\n if (trigS != -1) {\n this.triggerSlot(trigS, param, null, options);\n }\n };\n LGraphNode.prototype.changeMode = function(modeTo) {\n switch (modeTo) {\n case LiteGraph.ON_EVENT:\n break;\n case LiteGraph.ON_TRIGGER:\n this.addOnTriggerInput();\n this.addOnExecutedOutput();\n break;\n case LiteGraph.NEVER:\n break;\n case LiteGraph.ALWAYS:\n break;\n case LiteGraph.ON_REQUEST:\n break;\n default:\n return false;\n }\n this.mode = modeTo;\n return true;\n };\n LGraphNode.prototype.doExecute = function(param, options) {\n options = options || {};\n if (this.onExecute) {\n if (!options.action_call) options.action_call = this.id + \"_exec_\" + Math.floor(Math.random() * 9999);\n this.graph.nodes_executing[this.id] = true;\n this.onExecute(param, options);\n this.graph.nodes_executing[this.id] = false;\n this.exec_version = this.graph.iteration;\n if (options && options.action_call) {\n this.action_call = options.action_call;\n this.graph.nodes_executedAction[this.id] = options.action_call;\n }\n }\n this.execute_triggered = 2;\n if (this.onAfterExecuteNode) this.onAfterExecuteNode(param, options);\n };\n LGraphNode.prototype.actionDo = function(action, param, options) {\n options = options || {};\n if (this.onAction) {\n if (!options.action_call) options.action_call = this.id + \"_\" + (action ? action : \"action\") + \"_\" + Math.floor(Math.random() * 9999);\n this.graph.nodes_actioning[this.id] = action ? action : \"actioning\";\n this.onAction(action, param, options);\n this.graph.nodes_actioning[this.id] = false;\n if (options && options.action_call) {\n this.action_call = options.action_call;\n this.graph.nodes_executedAction[this.id] = options.action_call;\n }\n }\n this.action_triggered = 2;\n if (this.onAfterExecuteNode) this.onAfterExecuteNode(param, options);\n };\n LGraphNode.prototype.trigger = function(action, param, options) {\n if (!this.outputs || !this.outputs.length) {\n return;\n }\n if (this.graph)\n this.graph._last_trigger_time = LiteGraph.getTime();\n for (var i2 = 0; i2 < this.outputs.length; ++i2) {\n var output = this.outputs[i2];\n if (!output || output.type !== LiteGraph.EVENT || action && output.name != action)\n continue;\n this.triggerSlot(i2, param, null, options);\n }\n };\n LGraphNode.prototype.triggerSlot = function(slot, param, link_id, options) {\n options = options || {};\n if (!this.outputs) {\n return;\n }\n if (slot == null) {\n console.error(\"slot must be a number\");\n return;\n }\n if (slot.constructor !== Number)\n console.warn(\"slot must be a number, use node.trigger('name') if you want to use a string\");\n var output = this.outputs[slot];\n if (!output) {\n return;\n }\n var links = output.links;\n if (!links || !links.length) {\n return;\n }\n if (this.graph) {\n this.graph._last_trigger_time = LiteGraph.getTime();\n }\n for (var k = 0; k < links.length; ++k) {\n var id = links[k];\n if (link_id != null && link_id != id) {\n continue;\n }\n var link_info = this.graph.links[links[k]];\n if (!link_info) {\n continue;\n }\n link_info._last_time = LiteGraph.getTime();\n var node2 = this.graph.getNodeById(link_info.target_id);\n if (!node2) {\n continue;\n }\n var target_connection = node2.inputs[link_info.target_slot];\n if (node2.mode === LiteGraph.ON_TRIGGER) {\n if (!options.action_call) options.action_call = this.id + \"_trigg_\" + Math.floor(Math.random() * 9999);\n if (node2.onExecute) {\n node2.doExecute(param, options);\n }\n } else if (node2.onAction) {\n if (!options.action_call) options.action_call = this.id + \"_act_\" + Math.floor(Math.random() * 9999);\n var target_connection = node2.inputs[link_info.target_slot];\n node2.actionDo(target_connection.name, param, options);\n }\n }\n };\n LGraphNode.prototype.clearTriggeredSlot = function(slot, link_id) {\n if (!this.outputs) {\n return;\n }\n var output = this.outputs[slot];\n if (!output) {\n return;\n }\n var links = output.links;\n if (!links || !links.length) {\n return;\n }\n for (var k = 0; k < links.length; ++k) {\n var id = links[k];\n if (link_id != null && link_id != id) {\n continue;\n }\n var link_info = this.graph.links[links[k]];\n if (!link_info) {\n continue;\n }\n link_info._last_time = 0;\n }\n };\n LGraphNode.prototype.setSize = function(size) {\n this.size = size;\n if (this.onResize)\n this.onResize(this.size);\n };\n LGraphNode.prototype.addProperty = function(name, default_value, type, extra_info) {\n var o = { name, type, default_value };\n if (extra_info) {\n for (var i2 in extra_info) {\n o[i2] = extra_info[i2];\n }\n }\n if (!this.properties_info) {\n this.properties_info = [];\n }\n this.properties_info.push(o);\n if (!this.properties) {\n this.properties = {};\n }\n this.properties[name] = default_value;\n return o;\n };\n LGraphNode.prototype.addOutput = function(name, type, extra_info) {\n var output = { name, type, links: null };\n if (extra_info) {\n for (var i2 in extra_info) {\n output[i2] = extra_info[i2];\n }\n }\n if (!this.outputs) {\n this.outputs = [];\n }\n this.outputs.push(output);\n if (this.onOutputAdded) {\n this.onOutputAdded(output);\n }\n if (LiteGraph.auto_load_slot_types) LiteGraph.registerNodeAndSlotType(this, type, true);\n this.setSize(this.computeSize());\n this.setDirtyCanvas(true, true);\n return output;\n };\n LGraphNode.prototype.addOutputs = function(array) {\n for (var i2 = 0; i2 < array.length; ++i2) {\n var info = array[i2];\n var o = { name: info[0], type: info[1], link: null };\n if (array[2]) {\n for (var j in info[2]) {\n o[j] = info[2][j];\n }\n }\n if (!this.outputs) {\n this.outputs = [];\n }\n this.outputs.push(o);\n if (this.onOutputAdded) {\n this.onOutputAdded(o);\n }\n if (LiteGraph.auto_load_slot_types) LiteGraph.registerNodeAndSlotType(this, info[1], true);\n }\n this.setSize(this.computeSize());\n this.setDirtyCanvas(true, true);\n };\n LGraphNode.prototype.removeOutput = function(slot) {\n this.disconnectOutput(slot);\n this.outputs.splice(slot, 1);\n for (var i2 = slot; i2 < this.outputs.length; ++i2) {\n if (!this.outputs[i2] || !this.outputs[i2].links) {\n continue;\n }\n var links = this.outputs[i2].links;\n for (var j = 0; j < links.length; ++j) {\n var link = this.graph.links[links[j]];\n if (!link) {\n continue;\n }\n link.origin_slot -= 1;\n }\n }\n this.setSize(this.computeSize());\n if (this.onOutputRemoved) {\n this.onOutputRemoved(slot);\n }\n this.setDirtyCanvas(true, true);\n };\n LGraphNode.prototype.addInput = function(name, type, extra_info) {\n type = type || 0;\n var input = { name, type, link: null };\n if (extra_info) {\n for (var i2 in extra_info) {\n input[i2] = extra_info[i2];\n }\n }\n if (!this.inputs) {\n this.inputs = [];\n }\n this.inputs.push(input);\n this.setSize(this.computeSize());\n if (this.onInputAdded) {\n this.onInputAdded(input);\n }\n LiteGraph.registerNodeAndSlotType(this, type);\n this.setDirtyCanvas(true, true);\n return input;\n };\n LGraphNode.prototype.addInputs = function(array) {\n for (var i2 = 0; i2 < array.length; ++i2) {\n var info = array[i2];\n var o = { name: info[0], type: info[1], link: null };\n if (array[2]) {\n for (var j in info[2]) {\n o[j] = info[2][j];\n }\n }\n if (!this.inputs) {\n this.inputs = [];\n }\n this.inputs.push(o);\n if (this.onInputAdded) {\n this.onInputAdded(o);\n }\n LiteGraph.registerNodeAndSlotType(this, info[1]);\n }\n this.setSize(this.computeSize());\n this.setDirtyCanvas(true, true);\n };\n LGraphNode.prototype.removeInput = function(slot) {\n this.disconnectInput(slot);\n var slot_info = this.inputs.splice(slot, 1);\n for (var i2 = slot; i2 < this.inputs.length; ++i2) {\n if (!this.inputs[i2]) {\n continue;\n }\n var link = this.graph.links[this.inputs[i2].link];\n if (!link) {\n continue;\n }\n link.target_slot -= 1;\n }\n this.setSize(this.computeSize());\n if (this.onInputRemoved) {\n this.onInputRemoved(slot, slot_info[0]);\n }\n this.setDirtyCanvas(true, true);\n };\n LGraphNode.prototype.addConnection = function(name, type, pos2, direction) {\n var o = {\n name,\n type,\n pos: pos2,\n direction,\n links: null\n };\n this.connections.push(o);\n return o;\n };\n LGraphNode.prototype.computeSize = function(out) {\n if (this.constructor.size) {\n return this.constructor.size.concat();\n }\n var rows = Math.max(\n this.inputs ? this.inputs.length : 1,\n this.outputs ? this.outputs.length : 1\n );\n var size = out || new Float32Array([0, 0]);\n rows = Math.max(rows, 1);\n var font_size = LiteGraph.NODE_TEXT_SIZE;\n var title_width = compute_text_size(this.title);\n var input_width = 0;\n var output_width = 0;\n if (this.inputs) {\n for (var i2 = 0, l = this.inputs.length; i2 < l; ++i2) {\n var input = this.inputs[i2];\n var text = input.label || input.name || \"\";\n var text_width = compute_text_size(text);\n if (input_width < text_width) {\n input_width = text_width;\n }\n }\n }\n if (this.outputs) {\n for (var i2 = 0, l = this.outputs.length; i2 < l; ++i2) {\n var output = this.outputs[i2];\n var text = output.label || output.name || \"\";\n var text_width = compute_text_size(text);\n if (output_width < text_width) {\n output_width = text_width;\n }\n }\n }\n size[0] = Math.max(input_width + output_width + 10, title_width);\n size[0] = Math.max(size[0], LiteGraph.NODE_WIDTH);\n if (this.widgets && this.widgets.length) {\n size[0] = Math.max(size[0], LiteGraph.NODE_WIDTH * 1.5);\n }\n size[1] = (this.constructor.slot_start_y || 0) + rows * LiteGraph.NODE_SLOT_HEIGHT;\n var widgets_height = 0;\n if (this.widgets && this.widgets.length) {\n for (var i2 = 0, l = this.widgets.length; i2 < l; ++i2) {\n if (this.widgets[i2].computeSize)\n widgets_height += this.widgets[i2].computeSize(size[0])[1] + 4;\n else\n widgets_height += LiteGraph.NODE_WIDGET_HEIGHT + 4;\n }\n widgets_height += 8;\n }\n if (this.widgets_up)\n size[1] = Math.max(size[1], widgets_height);\n else if (this.widgets_start_y != null)\n size[1] = Math.max(size[1], widgets_height + this.widgets_start_y);\n else\n size[1] += widgets_height;\n function compute_text_size(text2) {\n if (!text2) {\n return 0;\n }\n return font_size * text2.length * 0.6;\n }\n if (this.constructor.min_height && size[1] < this.constructor.min_height) {\n size[1] = this.constructor.min_height;\n }\n size[1] += 6;\n return size;\n };\n LGraphNode.prototype.inResizeCorner = function(canvasX, canvasY) {\n var rows = this.outputs ? this.outputs.length : 1;\n var outputs_offset = (this.constructor.slot_start_y || 0) + rows * LiteGraph.NODE_SLOT_HEIGHT;\n return isInsideRectangle(\n canvasX,\n canvasY,\n this.pos[0] + this.size[0] - 15,\n this.pos[1] + Math.max(this.size[1] - 15, outputs_offset),\n 20,\n 20\n );\n };\n LGraphNode.prototype.getPropertyInfo = function(property) {\n var info = null;\n if (this.properties_info) {\n for (var i2 = 0; i2 < this.properties_info.length; ++i2) {\n if (this.properties_info[i2].name == property) {\n info = this.properties_info[i2];\n break;\n }\n }\n }\n if (this.constructor[\"@\" + property])\n info = this.constructor[\"@\" + property];\n if (this.constructor.widgets_info && this.constructor.widgets_info[property])\n info = this.constructor.widgets_info[property];\n if (!info && this.onGetPropertyInfo) {\n info = this.onGetPropertyInfo(property);\n }\n if (!info)\n info = {};\n if (!info.type)\n info.type = typeof this.properties[property];\n if (info.widget == \"combo\")\n info.type = \"enum\";\n return info;\n };\n LGraphNode.prototype.addWidget = function(type, name, value, callback, options) {\n if (!this.widgets) {\n this.widgets = [];\n }\n if (!options && callback && callback.constructor === Object) {\n options = callback;\n callback = null;\n }\n if (options && options.constructor === String)\n options = { property: options };\n if (callback && callback.constructor === String) {\n if (!options)\n options = {};\n options.property = callback;\n callback = null;\n }\n if (callback && callback.constructor !== Function) {\n console.warn(\"addWidget: callback must be a function\");\n callback = null;\n }\n var w2 = {\n type: type.toLowerCase(),\n name,\n value,\n callback,\n options: options || {}\n };\n if (w2.options.y !== void 0) {\n w2.y = w2.options.y;\n }\n if (!callback && !w2.options.callback && !w2.options.property) {\n console.warn(\"LiteGraph addWidget(...) without a callback or property assigned\");\n }\n if (type == \"combo\" && !w2.options.values) {\n throw \"LiteGraph addWidget('combo',...) requires to pass values in options: { values:['red','blue'] }\";\n }\n this.widgets.push(w2);\n this.setSize(this.computeSize());\n return w2;\n };\n LGraphNode.prototype.addCustomWidget = function(custom_widget) {\n if (!this.widgets) {\n this.widgets = [];\n }\n this.widgets.push(custom_widget);\n return custom_widget;\n };\n LGraphNode.prototype.getBounding = function(out, compute_outer) {\n out = out || new Float32Array(4);\n const nodePos = this.pos;\n const isCollapsed = this.flags.collapsed;\n const nodeSize = this.size;\n let left_offset = 0;\n let right_offset = 1;\n let top_offset = 0;\n let bottom_offset = 0;\n if (compute_outer) {\n left_offset = 4;\n right_offset = 6 + left_offset;\n top_offset = 4;\n bottom_offset = 5 + top_offset;\n }\n out[0] = nodePos[0] - left_offset;\n out[1] = nodePos[1] - LiteGraph.NODE_TITLE_HEIGHT - top_offset;\n out[2] = isCollapsed ? (this._collapsed_width || LiteGraph.NODE_COLLAPSED_WIDTH) + right_offset : nodeSize[0] + right_offset;\n out[3] = isCollapsed ? LiteGraph.NODE_TITLE_HEIGHT + bottom_offset : nodeSize[1] + LiteGraph.NODE_TITLE_HEIGHT + bottom_offset;\n if (this.onBounding) {\n this.onBounding(out);\n }\n return out;\n };\n LGraphNode.prototype.isPointInside = function(x2, y2, margin, skip_title) {\n margin = margin || 0;\n var margin_top = this.graph && this.graph.isLive() ? 0 : LiteGraph.NODE_TITLE_HEIGHT;\n if (skip_title) {\n margin_top = 0;\n }\n if (this.flags && this.flags.collapsed) {\n if (isInsideRectangle(\n x2,\n y2,\n this.pos[0] - margin,\n this.pos[1] - LiteGraph.NODE_TITLE_HEIGHT - margin,\n (this._collapsed_width || LiteGraph.NODE_COLLAPSED_WIDTH) + 2 * margin,\n LiteGraph.NODE_TITLE_HEIGHT + 2 * margin\n )) {\n return true;\n }\n } else if (this.pos[0] - 4 - margin < x2 && this.pos[0] + this.size[0] + 4 + margin > x2 && this.pos[1] - margin_top - margin < y2 && this.pos[1] + this.size[1] + margin > y2) {\n return true;\n }\n return false;\n };\n LGraphNode.prototype.getSlotInPosition = function(x2, y2) {\n var link_pos = new Float32Array(2);\n if (this.inputs) {\n for (var i2 = 0, l = this.inputs.length; i2 < l; ++i2) {\n var input = this.inputs[i2];\n this.getConnectionPos(true, i2, link_pos);\n if (isInsideRectangle(\n x2,\n y2,\n link_pos[0] - 10,\n link_pos[1] - 5,\n 20,\n 10\n )) {\n return { input, slot: i2, link_pos };\n }\n }\n }\n if (this.outputs) {\n for (var i2 = 0, l = this.outputs.length; i2 < l; ++i2) {\n var output = this.outputs[i2];\n this.getConnectionPos(false, i2, link_pos);\n if (isInsideRectangle(\n x2,\n y2,\n link_pos[0] - 10,\n link_pos[1] - 5,\n 20,\n 10\n )) {\n return { output, slot: i2, link_pos };\n }\n }\n }\n return null;\n };\n LGraphNode.prototype.findInputSlot = function(name, returnObj) {\n if (!this.inputs) {\n return -1;\n }\n for (var i2 = 0, l = this.inputs.length; i2 < l; ++i2) {\n if (name == this.inputs[i2].name) {\n return !returnObj ? i2 : this.inputs[i2];\n }\n }\n return -1;\n };\n LGraphNode.prototype.findOutputSlot = function(name, returnObj) {\n returnObj = returnObj || false;\n if (!this.outputs) {\n return -1;\n }\n for (var i2 = 0, l = this.outputs.length; i2 < l; ++i2) {\n if (name == this.outputs[i2].name) {\n return !returnObj ? i2 : this.outputs[i2];\n }\n }\n return -1;\n };\n LGraphNode.prototype.findInputSlotFree = function(optsIn) {\n var optsIn = optsIn || {};\n var optsDef = {\n returnObj: false,\n typesNotAccepted: []\n };\n var opts = Object.assign(optsDef, optsIn);\n if (!this.inputs) {\n return -1;\n }\n for (var i2 = 0, l = this.inputs.length; i2 < l; ++i2) {\n if (this.inputs[i2].link && this.inputs[i2].link != null) {\n continue;\n }\n if (opts.typesNotAccepted && opts.typesNotAccepted.includes && opts.typesNotAccepted.includes(this.inputs[i2].type)) {\n continue;\n }\n return !opts.returnObj ? i2 : this.inputs[i2];\n }\n return -1;\n };\n LGraphNode.prototype.findOutputSlotFree = function(optsIn) {\n var optsIn = optsIn || {};\n var optsDef = {\n returnObj: false,\n typesNotAccepted: []\n };\n var opts = Object.assign(optsDef, optsIn);\n if (!this.outputs) {\n return -1;\n }\n for (var i2 = 0, l = this.outputs.length; i2 < l; ++i2) {\n if (this.outputs[i2].links && this.outputs[i2].links != null) {\n continue;\n }\n if (opts.typesNotAccepted && opts.typesNotAccepted.includes && opts.typesNotAccepted.includes(this.outputs[i2].type)) {\n continue;\n }\n return !opts.returnObj ? i2 : this.outputs[i2];\n }\n return -1;\n };\n LGraphNode.prototype.findInputSlotByType = function(type, returnObj, preferFreeSlot, doNotUseOccupied) {\n return this.findSlotByType(true, type, returnObj, preferFreeSlot, doNotUseOccupied);\n };\n LGraphNode.prototype.findOutputSlotByType = function(type, returnObj, preferFreeSlot, doNotUseOccupied) {\n return this.findSlotByType(false, type, returnObj, preferFreeSlot, doNotUseOccupied);\n };\n LGraphNode.prototype.findSlotByType = function(input, type, returnObj, preferFreeSlot, doNotUseOccupied) {\n input = input || false;\n returnObj = returnObj || false;\n preferFreeSlot = preferFreeSlot || false;\n doNotUseOccupied = doNotUseOccupied || false;\n var aSlots = input ? this.inputs : this.outputs;\n if (!aSlots) {\n return -1;\n }\n if (type == \"\" || type == \"*\") type = 0;\n for (var i2 = 0, l = aSlots.length; i2 < l; ++i2) {\n var aSource = (type + \"\").toLowerCase().split(\",\");\n var aDest = aSlots[i2].type == \"0\" || aSlots[i2].type == \"*\" ? \"0\" : aSlots[i2].type;\n aDest = (aDest + \"\").toLowerCase().split(\",\");\n for (var sI = 0; sI < aSource.length; sI++) {\n for (var dI = 0; dI < aDest.length; dI++) {\n if (aSource[sI] == \"_event_\") aSource[sI] = LiteGraph.EVENT;\n if (aDest[sI] == \"_event_\") aDest[sI] = LiteGraph.EVENT;\n if (aSource[sI] == \"*\") aSource[sI] = 0;\n if (aDest[sI] == \"*\") aDest[sI] = 0;\n if (aSource[sI] == aDest[dI]) {\n if (preferFreeSlot && (aSlots[i2].links && aSlots[i2].links !== null) || aSlots[i2].link && aSlots[i2].link !== null) continue;\n return !returnObj ? i2 : aSlots[i2];\n }\n }\n }\n }\n if (preferFreeSlot && !doNotUseOccupied) {\n for (var i2 = 0, l = aSlots.length; i2 < l; ++i2) {\n var aSource = (type + \"\").toLowerCase().split(\",\");\n var aDest = aSlots[i2].type == \"0\" || aSlots[i2].type == \"*\" ? \"0\" : aSlots[i2].type;\n aDest = (aDest + \"\").toLowerCase().split(\",\");\n for (var sI = 0; sI < aSource.length; sI++) {\n for (var dI = 0; dI < aDest.length; dI++) {\n if (aSource[sI] == \"*\") aSource[sI] = 0;\n if (aDest[sI] == \"*\") aDest[sI] = 0;\n if (aSource[sI] == aDest[dI]) {\n return !returnObj ? i2 : aSlots[i2];\n }\n }\n }\n }\n }\n return -1;\n };\n LGraphNode.prototype.connectByType = function(slot, target_node, target_slotType, optsIn) {\n var optsIn = optsIn || {};\n var optsDef = {\n createEventInCase: true,\n firstFreeIfOutputGeneralInCase: true,\n generalTypeInCase: true\n };\n var opts = Object.assign(optsDef, optsIn);\n if (target_node && target_node.constructor === Number) {\n target_node = this.graph.getNodeById(target_node);\n }\n var target_slot = target_node.findInputSlotByType(target_slotType, false, true);\n if (target_slot >= 0 && target_slot !== null) {\n return this.connect(slot, target_node, target_slot);\n } else {\n if (opts.createEventInCase && target_slotType == LiteGraph.EVENT) {\n return this.connect(slot, target_node, -1);\n }\n if (opts.generalTypeInCase) {\n var target_slot = target_node.findInputSlotByType(0, false, true, true);\n if (target_slot >= 0) {\n return this.connect(slot, target_node, target_slot);\n }\n }\n if (opts.firstFreeIfOutputGeneralInCase && (target_slotType == 0 || target_slotType == \"*\" || target_slotType == \"\")) {\n var target_slot = target_node.findInputSlotFree({ typesNotAccepted: [LiteGraph.EVENT] });\n if (target_slot >= 0) {\n return this.connect(slot, target_node, target_slot);\n }\n }\n console.debug(\"no way to connect type: \", target_slotType, \" to targetNODE \", target_node);\n return null;\n }\n };\n LGraphNode.prototype.connectByTypeOutput = function(slot, source_node, source_slotType, optsIn) {\n var optsIn = optsIn || {};\n var optsDef = {\n createEventInCase: true,\n firstFreeIfInputGeneralInCase: true,\n generalTypeInCase: true\n };\n var opts = Object.assign(optsDef, optsIn);\n if (source_node && source_node.constructor === Number) {\n source_node = this.graph.getNodeById(source_node);\n }\n var source_slot = source_node.findOutputSlotByType(source_slotType, false, true);\n if (source_slot >= 0 && source_slot !== null) {\n return source_node.connect(source_slot, this, slot);\n } else {\n if (opts.generalTypeInCase) {\n var source_slot = source_node.findOutputSlotByType(0, false, true, true);\n if (source_slot >= 0) {\n return source_node.connect(source_slot, this, slot);\n }\n }\n if (opts.createEventInCase && source_slotType == LiteGraph.EVENT) {\n if (LiteGraph.do_add_triggers_slots) {\n var source_slot = source_node.addOnExecutedOutput();\n return source_node.connect(source_slot, this, slot);\n }\n }\n if (opts.firstFreeIfInputGeneralInCase && (source_slotType == 0 || source_slotType == \"*\" || source_slotType == \"\")) {\n var source_slot = source_node.findOutputSlotFree({ typesNotAccepted: [LiteGraph.EVENT] });\n if (source_slot >= 0) {\n return source_node.connect(source_slot, this, slot);\n }\n }\n console.debug(\"no way to connect byOUT type: \", source_slotType, \" to sourceNODE \", source_node);\n return null;\n }\n };\n LGraphNode.prototype.connect = function(slot, target_node, target_slot) {\n target_slot = target_slot || 0;\n if (!this.graph) {\n console.log(\n \"Connect: Error, node doesn't belong to any graph. Nodes must be added first to a graph before connecting them.\"\n );\n return null;\n }\n if (slot.constructor === String) {\n slot = this.findOutputSlot(slot);\n if (slot == -1) {\n if (LiteGraph.debug) {\n console.log(\"Connect: Error, no slot of name \" + slot);\n }\n return null;\n }\n } else if (!this.outputs || slot >= this.outputs.length) {\n if (LiteGraph.debug) {\n console.log(\"Connect: Error, slot number not found\");\n }\n return null;\n }\n if (target_node && target_node.constructor === Number) {\n target_node = this.graph.getNodeById(target_node);\n }\n if (!target_node) {\n throw \"target node is null\";\n }\n if (target_node == this) {\n return null;\n }\n if (target_slot.constructor === String) {\n target_slot = target_node.findInputSlot(target_slot);\n if (target_slot == -1) {\n if (LiteGraph.debug) {\n console.log(\n \"Connect: Error, no slot of name \" + target_slot\n );\n }\n return null;\n }\n } else if (target_slot === LiteGraph.EVENT) {\n if (LiteGraph.do_add_triggers_slots) {\n target_node.changeMode(LiteGraph.ON_TRIGGER);\n target_slot = target_node.findInputSlot(\"onTrigger\");\n } else {\n return null;\n }\n } else if (!target_node.inputs || target_slot >= target_node.inputs.length) {\n if (LiteGraph.debug) {\n console.log(\"Connect: Error, slot number not found\");\n }\n return null;\n }\n var changed = false;\n var input = target_node.inputs[target_slot];\n var link_info = null;\n var output = this.outputs[slot];\n if (!this.outputs[slot]) {\n return null;\n }\n if (target_node.onBeforeConnectInput) {\n target_slot = target_node.onBeforeConnectInput(target_slot);\n }\n if (target_slot === false || target_slot === null || !LiteGraph.isValidConnection(output.type, input.type)) {\n this.setDirtyCanvas(false, true);\n if (changed)\n this.graph.connectionChange(this, link_info);\n return null;\n }\n if (target_node.onConnectInput) {\n if (target_node.onConnectInput(target_slot, output.type, output, this, slot) === false) {\n return null;\n }\n }\n if (this.onConnectOutput) {\n if (this.onConnectOutput(slot, input.type, input, target_node, target_slot) === false) {\n return null;\n }\n }\n if (target_node.inputs[target_slot] && target_node.inputs[target_slot].link != null) {\n this.graph.beforeChange();\n target_node.disconnectInput(target_slot, { doProcessChange: false });\n changed = true;\n }\n if (output.links !== null && output.links.length) {\n switch (output.type) {\n case LiteGraph.EVENT:\n if (!LiteGraph.allow_multi_output_for_events) {\n this.graph.beforeChange();\n this.disconnectOutput(slot, false, { doProcessChange: false });\n changed = true;\n }\n break;\n }\n }\n var nextId;\n if (LiteGraph.use_uuids)\n nextId = LiteGraph.uuidv4();\n else\n nextId = ++this.graph.last_link_id;\n link_info = new LLink(\n nextId,\n input.type || output.type,\n this.id,\n slot,\n target_node.id,\n target_slot\n );\n this.graph.links[link_info.id] = link_info;\n if (output.links == null) {\n output.links = [];\n }\n output.links.push(link_info.id);\n target_node.inputs[target_slot].link = link_info.id;\n if (this.graph) {\n this.graph._version++;\n }\n if (this.onConnectionsChange) {\n this.onConnectionsChange(\n LiteGraph.OUTPUT,\n slot,\n true,\n link_info,\n output\n );\n }\n if (target_node.onConnectionsChange) {\n target_node.onConnectionsChange(\n LiteGraph.INPUT,\n target_slot,\n true,\n link_info,\n input\n );\n }\n if (this.graph && this.graph.onNodeConnectionChange) {\n this.graph.onNodeConnectionChange(\n LiteGraph.INPUT,\n target_node,\n target_slot,\n this,\n slot\n );\n this.graph.onNodeConnectionChange(\n LiteGraph.OUTPUT,\n this,\n slot,\n target_node,\n target_slot\n );\n }\n this.setDirtyCanvas(false, true);\n this.graph.afterChange();\n this.graph.connectionChange(this, link_info);\n return link_info;\n };\n LGraphNode.prototype.disconnectOutput = function(slot, target_node) {\n if (slot.constructor === String) {\n slot = this.findOutputSlot(slot);\n if (slot == -1) {\n if (LiteGraph.debug) {\n console.log(\"Connect: Error, no slot of name \" + slot);\n }\n return false;\n }\n } else if (!this.outputs || slot >= this.outputs.length) {\n if (LiteGraph.debug) {\n console.log(\"Connect: Error, slot number not found\");\n }\n return false;\n }\n var output = this.outputs[slot];\n if (!output || !output.links || output.links.length == 0) {\n return false;\n }\n if (target_node) {\n if (target_node.constructor === Number) {\n target_node = this.graph.getNodeById(target_node);\n }\n if (!target_node) {\n throw \"Target Node not found\";\n }\n for (var i2 = 0, l = output.links.length; i2 < l; i2++) {\n var link_id = output.links[i2];\n var link_info = this.graph.links[link_id];\n if (link_info.target_id == target_node.id) {\n output.links.splice(i2, 1);\n var input = target_node.inputs[link_info.target_slot];\n input.link = null;\n delete this.graph.links[link_id];\n if (this.graph) {\n this.graph._version++;\n }\n if (target_node.onConnectionsChange) {\n target_node.onConnectionsChange(\n LiteGraph.INPUT,\n link_info.target_slot,\n false,\n link_info,\n input\n );\n }\n if (this.onConnectionsChange) {\n this.onConnectionsChange(\n LiteGraph.OUTPUT,\n slot,\n false,\n link_info,\n output\n );\n }\n if (this.graph && this.graph.onNodeConnectionChange) {\n this.graph.onNodeConnectionChange(\n LiteGraph.OUTPUT,\n this,\n slot\n );\n }\n if (this.graph && this.graph.onNodeConnectionChange) {\n this.graph.onNodeConnectionChange(\n LiteGraph.OUTPUT,\n this,\n slot\n );\n this.graph.onNodeConnectionChange(\n LiteGraph.INPUT,\n target_node,\n link_info.target_slot\n );\n }\n break;\n }\n }\n } else {\n for (var i2 = 0, l = output.links.length; i2 < l; i2++) {\n var link_id = output.links[i2];\n var link_info = this.graph.links[link_id];\n if (!link_info) {\n continue;\n }\n var target_node = this.graph.getNodeById(link_info.target_id);\n var input = null;\n if (this.graph) {\n this.graph._version++;\n }\n if (target_node) {\n input = target_node.inputs[link_info.target_slot];\n input.link = null;\n if (target_node.onConnectionsChange) {\n target_node.onConnectionsChange(\n LiteGraph.INPUT,\n link_info.target_slot,\n false,\n link_info,\n input\n );\n }\n if (this.graph && this.graph.onNodeConnectionChange) {\n this.graph.onNodeConnectionChange(\n LiteGraph.INPUT,\n target_node,\n link_info.target_slot\n );\n }\n }\n delete this.graph.links[link_id];\n if (this.onConnectionsChange) {\n this.onConnectionsChange(\n LiteGraph.OUTPUT,\n slot,\n false,\n link_info,\n output\n );\n }\n if (this.graph && this.graph.onNodeConnectionChange) {\n this.graph.onNodeConnectionChange(\n LiteGraph.OUTPUT,\n this,\n slot\n );\n this.graph.onNodeConnectionChange(\n LiteGraph.INPUT,\n target_node,\n link_info.target_slot\n );\n }\n }\n output.links = null;\n }\n this.setDirtyCanvas(false, true);\n this.graph.connectionChange(this);\n return true;\n };\n LGraphNode.prototype.disconnectInput = function(slot) {\n if (slot.constructor === String) {\n slot = this.findInputSlot(slot);\n if (slot == -1) {\n if (LiteGraph.debug) {\n console.log(\"Connect: Error, no slot of name \" + slot);\n }\n return false;\n }\n } else if (!this.inputs || slot >= this.inputs.length) {\n if (LiteGraph.debug) {\n console.log(\"Connect: Error, slot number not found\");\n }\n return false;\n }\n var input = this.inputs[slot];\n if (!input) {\n return false;\n }\n var link_id = this.inputs[slot].link;\n if (link_id != null) {\n this.inputs[slot].link = null;\n var link_info = this.graph.links[link_id];\n if (link_info) {\n var target_node = this.graph.getNodeById(link_info.origin_id);\n if (!target_node) {\n return false;\n }\n var output = target_node.outputs[link_info.origin_slot];\n if (!output || !output.links || output.links.length == 0) {\n return false;\n }\n for (var i2 = 0, l = output.links.length; i2 < l; i2++) {\n if (output.links[i2] == link_id) {\n output.links.splice(i2, 1);\n break;\n }\n }\n delete this.graph.links[link_id];\n if (this.graph) {\n this.graph._version++;\n }\n if (this.onConnectionsChange) {\n this.onConnectionsChange(\n LiteGraph.INPUT,\n slot,\n false,\n link_info,\n input\n );\n }\n if (target_node.onConnectionsChange) {\n target_node.onConnectionsChange(\n LiteGraph.OUTPUT,\n i2,\n false,\n link_info,\n output\n );\n }\n if (this.graph && this.graph.onNodeConnectionChange) {\n this.graph.onNodeConnectionChange(\n LiteGraph.OUTPUT,\n target_node,\n i2\n );\n this.graph.onNodeConnectionChange(LiteGraph.INPUT, this, slot);\n }\n }\n }\n this.setDirtyCanvas(false, true);\n if (this.graph)\n this.graph.connectionChange(this);\n return true;\n };\n LGraphNode.prototype.getConnectionPos = function(is_input, slot_number, out) {\n out = out || new Float32Array(2);\n var num_slots = 0;\n if (is_input && this.inputs) {\n num_slots = this.inputs.length;\n }\n if (!is_input && this.outputs) {\n num_slots = this.outputs.length;\n }\n var offset = LiteGraph.NODE_SLOT_HEIGHT * 0.5;\n if (this.flags.collapsed) {\n var w2 = this._collapsed_width || LiteGraph.NODE_COLLAPSED_WIDTH;\n if (this.horizontal) {\n out[0] = this.pos[0] + w2 * 0.5;\n if (is_input) {\n out[1] = this.pos[1] - LiteGraph.NODE_TITLE_HEIGHT;\n } else {\n out[1] = this.pos[1];\n }\n } else {\n if (is_input) {\n out[0] = this.pos[0];\n } else {\n out[0] = this.pos[0] + w2;\n }\n out[1] = this.pos[1] - LiteGraph.NODE_TITLE_HEIGHT * 0.5;\n }\n return out;\n }\n if (is_input && slot_number == -1) {\n out[0] = this.pos[0] + LiteGraph.NODE_TITLE_HEIGHT * 0.5;\n out[1] = this.pos[1] + LiteGraph.NODE_TITLE_HEIGHT * 0.5;\n return out;\n }\n if (is_input && num_slots > slot_number && this.inputs[slot_number].pos) {\n out[0] = this.pos[0] + this.inputs[slot_number].pos[0];\n out[1] = this.pos[1] + this.inputs[slot_number].pos[1];\n return out;\n } else if (!is_input && num_slots > slot_number && this.outputs[slot_number].pos) {\n out[0] = this.pos[0] + this.outputs[slot_number].pos[0];\n out[1] = this.pos[1] + this.outputs[slot_number].pos[1];\n return out;\n }\n if (this.horizontal) {\n out[0] = this.pos[0] + (slot_number + 0.5) * (this.size[0] / num_slots);\n if (is_input) {\n out[1] = this.pos[1] - LiteGraph.NODE_TITLE_HEIGHT;\n } else {\n out[1] = this.pos[1] + this.size[1];\n }\n return out;\n }\n if (is_input) {\n out[0] = this.pos[0] + offset;\n } else {\n out[0] = this.pos[0] + this.size[0] + 1 - offset;\n }\n out[1] = this.pos[1] + (slot_number + 0.7) * LiteGraph.NODE_SLOT_HEIGHT + (this.constructor.slot_start_y || 0);\n return out;\n };\n LGraphNode.prototype.alignToGrid = function() {\n this.pos[0] = LiteGraph.CANVAS_GRID_SIZE * Math.round(this.pos[0] / LiteGraph.CANVAS_GRID_SIZE);\n this.pos[1] = LiteGraph.CANVAS_GRID_SIZE * Math.round(this.pos[1] / LiteGraph.CANVAS_GRID_SIZE);\n };\n LGraphNode.prototype.trace = function(msg) {\n if (!this.console) {\n this.console = [];\n }\n this.console.push(msg);\n if (this.console.length > LGraphNode.MAX_CONSOLE) {\n this.console.shift();\n }\n if (this.graph.onNodeTrace)\n this.graph.onNodeTrace(this, msg);\n };\n LGraphNode.prototype.setDirtyCanvas = function(dirty_foreground, dirty_background) {\n if (!this.graph) {\n return;\n }\n this.graph.sendActionToCanvas(\"setDirty\", [\n dirty_foreground,\n dirty_background\n ]);\n };\n LGraphNode.prototype.loadImage = function(url) {\n var img = new Image();\n img.src = LiteGraph.node_images_path + url;\n img.ready = false;\n var that2 = this;\n img.onload = function() {\n this.ready = true;\n that2.setDirtyCanvas(true);\n };\n return img;\n };\n LGraphNode.prototype.captureInput = function(v2) {\n if (!this.graph || !this.graph.list_of_graphcanvas) {\n return;\n }\n var list = this.graph.list_of_graphcanvas;\n for (var i2 = 0; i2 < list.length; ++i2) {\n var c = list[i2];\n if (!v2 && c.node_capturing_input != this) {\n continue;\n }\n c.node_capturing_input = v2 ? this : null;\n }\n };\n LGraphNode.prototype.collapse = function(force) {\n this.graph._version++;\n if (this.constructor.collapsable === false && !force) {\n return;\n }\n if (!this.flags.collapsed) {\n this.flags.collapsed = true;\n } else {\n this.flags.collapsed = false;\n }\n this.setDirtyCanvas(true, true);\n };\n LGraphNode.prototype.pin = function(v2) {\n this.graph._version++;\n if (v2 === void 0) {\n this.flags.pinned = !this.flags.pinned;\n } else {\n this.flags.pinned = v2;\n }\n };\n LGraphNode.prototype.localToScreen = function(x2, y2, graphcanvas) {\n return [\n (x2 + this.pos[0]) * graphcanvas.scale + graphcanvas.offset[0],\n (y2 + this.pos[1]) * graphcanvas.scale + graphcanvas.offset[1]\n ];\n };\n function LGraphGroup(title) {\n this._ctor(title);\n }\n globalThis.LGraphGroup = LiteGraph.LGraphGroup = LGraphGroup;\n LGraphGroup.prototype._ctor = function(title) {\n this.title = title || \"Group\";\n this.font_size = LiteGraph.DEFAULT_GROUP_FONT || 24;\n this.color = LGraphCanvas.node_colors.pale_blue ? LGraphCanvas.node_colors.pale_blue.groupcolor : \"#AAA\";\n this._bounding = new Float32Array([10, 10, 140, 80]);\n this._pos = this._bounding.subarray(0, 2);\n this._size = this._bounding.subarray(2, 4);\n this._nodes = [];\n this.graph = null;\n Object.defineProperty(this, \"pos\", {\n set: function(v2) {\n if (!v2 || v2.length < 2) {\n return;\n }\n this._pos[0] = v2[0];\n this._pos[1] = v2[1];\n },\n get: function() {\n return this._pos;\n },\n enumerable: true\n });\n Object.defineProperty(this, \"size\", {\n set: function(v2) {\n if (!v2 || v2.length < 2) {\n return;\n }\n this._size[0] = Math.max(140, v2[0]);\n this._size[1] = Math.max(80, v2[1]);\n },\n get: function() {\n return this._size;\n },\n enumerable: true\n });\n };\n LGraphGroup.prototype.configure = function(o) {\n this.title = o.title;\n this._bounding.set(o.bounding);\n this.color = o.color;\n if (o.font_size) {\n this.font_size = o.font_size;\n }\n };\n LGraphGroup.prototype.serialize = function() {\n var b = this._bounding;\n return {\n title: this.title,\n bounding: [\n Math.round(b[0]),\n Math.round(b[1]),\n Math.round(b[2]),\n Math.round(b[3])\n ],\n color: this.color,\n font_size: this.font_size\n };\n };\n LGraphGroup.prototype.move = function(deltax, deltay, ignore_nodes) {\n this._pos[0] += deltax;\n this._pos[1] += deltay;\n if (ignore_nodes) {\n return;\n }\n for (var i2 = 0; i2 < this._nodes.length; ++i2) {\n var node2 = this._nodes[i2];\n node2.pos[0] += deltax;\n node2.pos[1] += deltay;\n }\n };\n LGraphGroup.prototype.recomputeInsideNodes = function() {\n this._nodes.length = 0;\n var nodes = this.graph._nodes;\n var node_bounding = new Float32Array(4);\n for (var i2 = 0; i2 < nodes.length; ++i2) {\n var node2 = nodes[i2];\n node2.getBounding(node_bounding);\n if (!overlapBounding(this._bounding, node_bounding)) {\n continue;\n }\n this._nodes.push(node2);\n }\n };\n LGraphGroup.prototype.isPointInside = LGraphNode.prototype.isPointInside;\n LGraphGroup.prototype.setDirtyCanvas = LGraphNode.prototype.setDirtyCanvas;\n function DragAndScale(element, skip_events) {\n this.offset = new Float32Array([0, 0]);\n this.scale = 1;\n this.max_scale = 10;\n this.min_scale = 0.1;\n this.onredraw = null;\n this.enabled = true;\n this.last_mouse = [0, 0];\n this.element = null;\n this.visible_area = new Float32Array(4);\n if (element) {\n this.element = element;\n if (!skip_events) {\n this.bindEvents(element);\n }\n }\n }\n LiteGraph.DragAndScale = DragAndScale;\n DragAndScale.prototype.bindEvents = function(element) {\n this.last_mouse = new Float32Array(2);\n this._binded_mouse_callback = this.onMouse.bind(this);\n LiteGraph.pointerListenerAdd(element, \"down\", this._binded_mouse_callback);\n LiteGraph.pointerListenerAdd(element, \"move\", this._binded_mouse_callback);\n LiteGraph.pointerListenerAdd(element, \"up\", this._binded_mouse_callback);\n element.addEventListener(\n \"mousewheel\",\n this._binded_mouse_callback,\n false\n );\n element.addEventListener(\"wheel\", this._binded_mouse_callback, false);\n };\n DragAndScale.prototype.computeVisibleArea = function(viewport) {\n if (!this.element) {\n this.visible_area[0] = this.visible_area[1] = this.visible_area[2] = this.visible_area[3] = 0;\n return;\n }\n var width2 = this.element.width;\n var height = this.element.height;\n var startx = -this.offset[0];\n var starty = -this.offset[1];\n if (viewport) {\n startx += viewport[0] / this.scale;\n starty += viewport[1] / this.scale;\n width2 = viewport[2];\n height = viewport[3];\n }\n var endx = startx + width2 / this.scale;\n var endy = starty + height / this.scale;\n this.visible_area[0] = startx;\n this.visible_area[1] = starty;\n this.visible_area[2] = endx - startx;\n this.visible_area[3] = endy - starty;\n };\n DragAndScale.prototype.onMouse = function(e) {\n if (!this.enabled) {\n return;\n }\n var canvas = this.element;\n var rect = canvas.getBoundingClientRect();\n var x2 = e.clientX - rect.left;\n var y2 = e.clientY - rect.top;\n e.canvasx = x2;\n e.canvasy = y2;\n e.dragging = this.dragging;\n var is_inside = !this.viewport || this.viewport && x2 >= this.viewport[0] && x2 < this.viewport[0] + this.viewport[2] && y2 >= this.viewport[1] && y2 < this.viewport[1] + this.viewport[3];\n var ignore = false;\n if (this.onmouse) {\n ignore = this.onmouse(e);\n }\n if (e.type == LiteGraph.pointerevents_method + \"down\" && is_inside) {\n this.dragging = true;\n LiteGraph.pointerListenerRemove(canvas, \"move\", this._binded_mouse_callback);\n LiteGraph.pointerListenerAdd(document, \"move\", this._binded_mouse_callback);\n LiteGraph.pointerListenerAdd(document, \"up\", this._binded_mouse_callback);\n } else if (e.type == LiteGraph.pointerevents_method + \"move\") {\n if (!ignore) {\n var deltax = x2 - this.last_mouse[0];\n var deltay = y2 - this.last_mouse[1];\n if (this.dragging) {\n this.mouseDrag(deltax, deltay);\n }\n }\n } else if (e.type == LiteGraph.pointerevents_method + \"up\") {\n this.dragging = false;\n LiteGraph.pointerListenerRemove(document, \"move\", this._binded_mouse_callback);\n LiteGraph.pointerListenerRemove(document, \"up\", this._binded_mouse_callback);\n LiteGraph.pointerListenerAdd(canvas, \"move\", this._binded_mouse_callback);\n } else if (is_inside && (e.type == \"mousewheel\" || e.type == \"wheel\" || e.type == \"DOMMouseScroll\")) {\n e.eventType = \"mousewheel\";\n if (e.type == \"wheel\") {\n e.wheel = -e.deltaY;\n } else {\n e.wheel = e.wheelDeltaY != null ? e.wheelDeltaY : e.detail * -60;\n }\n e.delta = e.wheelDelta ? e.wheelDelta / 40 : e.deltaY ? -e.deltaY / 3 : 0;\n this.changeDeltaScale(1 + e.delta * 0.05);\n }\n this.last_mouse[0] = x2;\n this.last_mouse[1] = y2;\n if (is_inside) {\n e.preventDefault();\n e.stopPropagation();\n return false;\n }\n };\n DragAndScale.prototype.toCanvasContext = function(ctx) {\n ctx.scale(this.scale, this.scale);\n ctx.translate(this.offset[0], this.offset[1]);\n };\n DragAndScale.prototype.convertOffsetToCanvas = function(pos2) {\n return [\n (pos2[0] + this.offset[0]) * this.scale,\n (pos2[1] + this.offset[1]) * this.scale\n ];\n };\n DragAndScale.prototype.convertCanvasToOffset = function(pos2, out) {\n out = out || [0, 0];\n out[0] = pos2[0] / this.scale - this.offset[0];\n out[1] = pos2[1] / this.scale - this.offset[1];\n return out;\n };\n DragAndScale.prototype.mouseDrag = function(x2, y2) {\n this.offset[0] += x2 / this.scale;\n this.offset[1] += y2 / this.scale;\n if (this.onredraw) {\n this.onredraw(this);\n }\n };\n DragAndScale.prototype.changeScale = function(value, zooming_center) {\n if (value < this.min_scale) {\n value = this.min_scale;\n } else if (value > this.max_scale) {\n value = this.max_scale;\n }\n if (value == this.scale) {\n return;\n }\n if (!this.element) {\n return;\n }\n var rect = this.element.getBoundingClientRect();\n if (!rect) {\n return;\n }\n zooming_center = zooming_center || [\n rect.width * 0.5,\n rect.height * 0.5\n ];\n var center = this.convertCanvasToOffset(zooming_center);\n this.scale = value;\n if (Math.abs(this.scale - 1) < 0.01) {\n this.scale = 1;\n }\n var new_center = this.convertCanvasToOffset(zooming_center);\n var delta_offset = [\n new_center[0] - center[0],\n new_center[1] - center[1]\n ];\n this.offset[0] += delta_offset[0];\n this.offset[1] += delta_offset[1];\n if (this.onredraw) {\n this.onredraw(this);\n }\n };\n DragAndScale.prototype.changeDeltaScale = function(value, zooming_center) {\n this.changeScale(this.scale * value, zooming_center);\n };\n DragAndScale.prototype.reset = function() {\n this.scale = 1;\n this.offset[0] = 0;\n this.offset[1] = 0;\n };\n function LGraphCanvas(canvas, graph, options) {\n this.options = options = options || {};\n this.background_image = LGraphCanvas.DEFAULT_BACKGROUND_IMAGE;\n if (canvas && canvas.constructor === String) {\n canvas = document.querySelector(canvas);\n }\n this.ds = new DragAndScale();\n this.zoom_modify_alpha = true;\n this.title_text_font = \"\" + LiteGraph.NODE_TEXT_SIZE + \"px Arial\";\n this.inner_text_font = \"normal \" + LiteGraph.NODE_SUBTEXT_SIZE + \"px Arial\";\n this.node_title_color = LiteGraph.NODE_TITLE_COLOR;\n this.default_link_color = LiteGraph.LINK_COLOR;\n this.default_connection_color = {\n input_off: \"#778\",\n input_on: \"#7F7\",\n //\"#BBD\"\n output_off: \"#778\",\n output_on: \"#7F7\"\n //\"#BBD\"\n };\n this.default_connection_color_byType = {\n /*number: \"#7F7\",\n string: \"#77F\",\n boolean: \"#F77\",*/\n };\n this.default_connection_color_byTypeOff = {\n /*number: \"#474\",\n string: \"#447\",\n boolean: \"#744\",*/\n };\n this.highquality_render = true;\n this.use_gradients = false;\n this.editor_alpha = 1;\n this.pause_rendering = false;\n this.clear_background = true;\n this.clear_background_color = \"#222\";\n this.read_only = false;\n this.render_only_selected = true;\n this.live_mode = false;\n this.show_info = true;\n this.allow_dragcanvas = true;\n this.allow_dragnodes = true;\n this.allow_interaction = true;\n this.multi_select = false;\n this.allow_searchbox = true;\n this.allow_reconnect_links = true;\n this.align_to_grid = false;\n this.drag_mode = false;\n this.dragging_rectangle = null;\n this.filter = null;\n this.set_canvas_dirty_on_mouse_event = true;\n this.always_render_background = false;\n this.render_shadows = true;\n this.render_canvas_border = true;\n this.render_connections_shadows = false;\n this.render_connections_border = true;\n this.render_curved_connections = false;\n this.render_connection_arrows = false;\n this.render_collapsed_slots = true;\n this.render_execution_order = false;\n this.render_title_colored = true;\n this.render_link_tooltip = true;\n this.links_render_mode = LiteGraph.SPLINE_LINK;\n this.mouse = [0, 0];\n this.graph_mouse = [0, 0];\n this.canvas_mouse = this.graph_mouse;\n this.onSearchBox = null;\n this.onSearchBoxSelection = null;\n this.onMouse = null;\n this.onDrawBackground = null;\n this.onDrawForeground = null;\n this.onDrawOverlay = null;\n this.onDrawLinkTooltip = null;\n this.onNodeMoved = null;\n this.onSelectionChange = null;\n this.onConnectingChange = null;\n this.onBeforeChange = null;\n this.onAfterChange = null;\n this.connections_width = 3;\n this.round_radius = 8;\n this.current_node = null;\n this.node_widget = null;\n this.over_link_center = null;\n this.last_mouse_position = [0, 0];\n this.visible_area = this.ds.visible_area;\n this.visible_links = [];\n this.connecting_links = null;\n this.viewport = options.viewport || null;\n if (graph) {\n graph.attachCanvas(this);\n }\n this.setCanvas(canvas, options.skip_events);\n this.clear();\n if (!options.skip_render) {\n this.startRendering();\n }\n this.autoresize = options.autoresize;\n }\n globalThis.LGraphCanvas = LiteGraph.LGraphCanvas = LGraphCanvas;\n LGraphCanvas.DEFAULT_BACKGROUND_IMAGE = \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAQBJREFUeNrs1rEKwjAUhlETUkj3vP9rdmr1Ysammk2w5wdxuLgcMHyptfawuZX4pJSWZTnfnu/lnIe/jNNxHHGNn//HNbbv+4dr6V+11uF527arU7+u63qfa/bnmh8sWLBgwYJlqRf8MEptXPBXJXa37BSl3ixYsGDBMliwFLyCV/DeLIMFCxYsWLBMwSt4Be/NggXLYMGCBUvBK3iNruC9WbBgwYJlsGApeAWv4L1ZBgsWLFiwYJmCV/AK3psFC5bBggULloJX8BpdwXuzYMGCBctgwVLwCl7Be7MMFixYsGDBsu8FH1FaSmExVfAxBa/gvVmwYMGCZbBg/W4vAQYA5tRF9QYlv/QAAAAASUVORK5CYII=\";\n LGraphCanvas.link_type_colors = {\n \"-1\": LiteGraph.EVENT_LINK_COLOR,\n number: \"#AAA\",\n node: \"#DCA\"\n };\n LGraphCanvas.gradients = {};\n LGraphCanvas.prototype.clear = function() {\n this.frame = 0;\n this.last_draw_time = 0;\n this.render_time = 0;\n this.fps = 0;\n this.dragging_rectangle = null;\n this.selected_nodes = {};\n this.selected_group = null;\n this.visible_nodes = [];\n this.node_dragged = null;\n this.node_over = null;\n this.node_capturing_input = null;\n this.connecting_links = null;\n this.highlighted_links = {};\n this.dragging_canvas = false;\n this.dirty_canvas = true;\n this.dirty_bgcanvas = true;\n this.dirty_area = null;\n this.node_in_panel = null;\n this.node_widget = null;\n this.last_mouse = [0, 0];\n this.last_mouseclick = 0;\n this.pointer_is_down = false;\n this.pointer_is_double = false;\n this.visible_area.set([0, 0, 0, 0]);\n if (this.onClear) {\n this.onClear();\n }\n };\n LGraphCanvas.prototype.setGraph = function(graph, skip_clear) {\n if (this.graph == graph) {\n return;\n }\n if (!skip_clear) {\n this.clear();\n }\n if (!graph && this.graph) {\n this.graph.detachCanvas(this);\n return;\n }\n graph.attachCanvas(this);\n if (this._graph_stack)\n this._graph_stack = null;\n this.setDirty(true, true);\n };\n LGraphCanvas.prototype.getTopGraph = function() {\n if (this._graph_stack.length)\n return this._graph_stack[0];\n return this.graph;\n };\n LGraphCanvas.prototype.openSubgraph = function(graph) {\n if (!graph) {\n throw \"graph cannot be null\";\n }\n if (this.graph == graph) {\n throw \"graph cannot be the same\";\n }\n this.clear();\n if (this.graph) {\n if (!this._graph_stack) {\n this._graph_stack = [];\n }\n this._graph_stack.push(this.graph);\n }\n graph.attachCanvas(this);\n this.checkPanels();\n this.setDirty(true, true);\n };\n LGraphCanvas.prototype.closeSubgraph = function() {\n if (!this._graph_stack || this._graph_stack.length == 0) {\n return;\n }\n var subgraph_node = this.graph._subgraph_node;\n var graph = this._graph_stack.pop();\n this.selected_nodes = {};\n this.highlighted_links = {};\n graph.attachCanvas(this);\n this.setDirty(true, true);\n if (subgraph_node) {\n this.centerOnNode(subgraph_node);\n this.selectNodes([subgraph_node]);\n }\n this.ds.offset = [0, 0];\n this.ds.scale = 1;\n };\n LGraphCanvas.prototype.getCurrentGraph = function() {\n return this.graph;\n };\n LGraphCanvas.prototype.setCanvas = function(canvas, skip_events) {\n if (canvas) {\n if (canvas.constructor === String) {\n canvas = document.getElementById(canvas);\n if (!canvas) {\n throw \"Error creating LiteGraph canvas: Canvas not found\";\n }\n }\n }\n if (canvas === this.canvas) {\n return;\n }\n if (!canvas && this.canvas) {\n if (!skip_events) {\n this.unbindEvents();\n }\n }\n this.canvas = canvas;\n this.ds.element = canvas;\n if (!canvas) {\n return;\n }\n canvas.className += \" lgraphcanvas\";\n canvas.data = this;\n canvas.tabindex = \"1\";\n this.bgcanvas = null;\n if (!this.bgcanvas) {\n this.bgcanvas = document.createElement(\"canvas\");\n this.bgcanvas.width = this.canvas.width;\n this.bgcanvas.height = this.canvas.height;\n }\n if (canvas.getContext == null) {\n if (canvas.localName != \"canvas\") {\n throw \"Element supplied for LGraphCanvas must be a element, you passed a \" + canvas.localName;\n }\n throw \"This browser doesn't support Canvas\";\n }\n var ctx = this.ctx = canvas.getContext(\"2d\");\n if (ctx == null) {\n if (!canvas.webgl_enabled) {\n console.warn(\n \"This canvas seems to be WebGL, enabling WebGL renderer\"\n );\n }\n this.enableWebGL();\n }\n if (!skip_events) {\n this.bindEvents();\n }\n };\n LGraphCanvas.prototype._doNothing = function doNothing(e) {\n e.preventDefault();\n return false;\n };\n LGraphCanvas.prototype._doReturnTrue = function doNothing(e) {\n e.preventDefault();\n return true;\n };\n LGraphCanvas.prototype.bindEvents = function() {\n if (this._events_binded) {\n console.warn(\"LGraphCanvas: events already binded\");\n return;\n }\n var canvas = this.canvas;\n var ref_window2 = this.getCanvasWindow();\n var document2 = ref_window2.document;\n this._mousedown_callback = this.processMouseDown.bind(this);\n this._mousewheel_callback = this.processMouseWheel.bind(this);\n this._mousemove_callback = this.processMouseMove.bind(this);\n this._mouseup_callback = this.processMouseUp.bind(this);\n LiteGraph.pointerListenerAdd(canvas, \"down\", this._mousedown_callback, true);\n canvas.addEventListener(\"mousewheel\", this._mousewheel_callback, false);\n LiteGraph.pointerListenerAdd(canvas, \"up\", this._mouseup_callback, true);\n LiteGraph.pointerListenerAdd(canvas, \"move\", this._mousemove_callback);\n canvas.addEventListener(\"contextmenu\", this._doNothing);\n canvas.addEventListener(\n \"DOMMouseScroll\",\n this._mousewheel_callback,\n false\n );\n this._key_callback = this.processKey.bind(this);\n canvas.addEventListener(\"keydown\", this._key_callback, true);\n document2.addEventListener(\"keyup\", this._key_callback, true);\n this._ondrop_callback = this.processDrop.bind(this);\n canvas.addEventListener(\"dragover\", this._doNothing, false);\n canvas.addEventListener(\"dragend\", this._doNothing, false);\n canvas.addEventListener(\"drop\", this._ondrop_callback, false);\n canvas.addEventListener(\"dragenter\", this._doReturnTrue, false);\n this._events_binded = true;\n };\n LGraphCanvas.prototype.unbindEvents = function() {\n if (!this._events_binded) {\n console.warn(\"LGraphCanvas: no events binded\");\n return;\n }\n var ref_window2 = this.getCanvasWindow();\n var document2 = ref_window2.document;\n LiteGraph.pointerListenerRemove(this.canvas, \"move\", this._mousemove_callback);\n LiteGraph.pointerListenerRemove(this.canvas, \"up\", this._mouseup_callback);\n LiteGraph.pointerListenerRemove(this.canvas, \"down\", this._mousedown_callback);\n this.canvas.removeEventListener(\n \"mousewheel\",\n this._mousewheel_callback\n );\n this.canvas.removeEventListener(\n \"DOMMouseScroll\",\n this._mousewheel_callback\n );\n this.canvas.removeEventListener(\"keydown\", this._key_callback);\n document2.removeEventListener(\"keyup\", this._key_callback);\n this.canvas.removeEventListener(\"contextmenu\", this._doNothing);\n this.canvas.removeEventListener(\"drop\", this._ondrop_callback);\n this.canvas.removeEventListener(\"dragenter\", this._doReturnTrue);\n this._mousedown_callback = null;\n this._mousewheel_callback = null;\n this._key_callback = null;\n this._ondrop_callback = null;\n this._events_binded = false;\n };\n LGraphCanvas.getFileExtension = function(url) {\n var question = url.indexOf(\"?\");\n if (question != -1) {\n url = url.substr(0, question);\n }\n var point = url.lastIndexOf(\".\");\n if (point == -1) {\n return \"\";\n }\n return url.substr(point + 1).toLowerCase();\n };\n LGraphCanvas.prototype.enableWebGL = function() {\n if (typeof GL === \"undefined\") {\n throw \"litegl.js must be included to use a WebGL canvas\";\n }\n if (typeof enableWebGLCanvas === \"undefined\") {\n throw \"webglCanvas.js must be included to use this feature\";\n }\n this.gl = this.ctx = enableWebGLCanvas(this.canvas);\n this.ctx.webgl = true;\n this.bgcanvas = this.canvas;\n this.bgctx = this.gl;\n this.canvas.webgl_enabled = true;\n };\n LGraphCanvas.prototype.setDirty = function(fgcanvas, bgcanvas) {\n if (fgcanvas) {\n this.dirty_canvas = true;\n }\n if (bgcanvas) {\n this.dirty_bgcanvas = true;\n }\n };\n LGraphCanvas.prototype.getCanvasWindow = function() {\n if (!this.canvas) {\n return window;\n }\n var doc = this.canvas.ownerDocument;\n return doc.defaultView || doc.parentWindow;\n };\n LGraphCanvas.prototype.startRendering = function() {\n if (this.is_rendering) {\n return;\n }\n this.is_rendering = true;\n renderFrame.call(this);\n function renderFrame() {\n if (!this.pause_rendering) {\n this.draw();\n }\n var window2 = this.getCanvasWindow();\n if (this.is_rendering) {\n window2.requestAnimationFrame(renderFrame.bind(this));\n }\n }\n };\n LGraphCanvas.prototype.stopRendering = function() {\n this.is_rendering = false;\n };\n LGraphCanvas.prototype.blockClick = function() {\n this.block_click = true;\n this.last_mouseclick = 0;\n };\n LGraphCanvas.prototype.processMouseDown = function(e) {\n var _a;\n if (this.set_canvas_dirty_on_mouse_event)\n this.dirty_canvas = true;\n if (!this.graph) {\n return;\n }\n this.adjustMouseEvent(e);\n var ref_window2 = this.getCanvasWindow();\n ref_window2.document;\n LGraphCanvas.active_canvas = this;\n var that2 = this;\n var x2 = e.clientX;\n var y2 = e.clientY;\n this.ds.viewport = this.viewport;\n var is_inside = !this.viewport || this.viewport && x2 >= this.viewport[0] && x2 < this.viewport[0] + this.viewport[2] && y2 >= this.viewport[1] && y2 < this.viewport[1] + this.viewport[3];\n if (!this.options.skip_events) {\n LiteGraph.pointerListenerRemove(this.canvas, \"move\", this._mousemove_callback);\n LiteGraph.pointerListenerAdd(ref_window2.document, \"move\", this._mousemove_callback, true);\n LiteGraph.pointerListenerAdd(ref_window2.document, \"up\", this._mouseup_callback, true);\n }\n if (!is_inside) {\n return;\n }\n var node2 = this.graph.getNodeOnPos(e.canvasX, e.canvasY, this.visible_nodes, 5);\n var skip_action = false;\n var now = LiteGraph.getTime();\n var is_primary = e.isPrimary === void 0 || !e.isPrimary;\n var is_double_click = now - this.last_mouseclick < 300;\n this.mouse[0] = e.clientX;\n this.mouse[1] = e.clientY;\n this.graph_mouse[0] = e.canvasX;\n this.graph_mouse[1] = e.canvasY;\n this.last_click_position = [this.mouse[0], this.mouse[1]];\n if (this.pointer_is_down && is_primary) {\n this.pointer_is_double = true;\n } else {\n this.pointer_is_double = false;\n }\n this.pointer_is_down = true;\n this.canvas.focus();\n LiteGraph.closeAllContextMenus(ref_window2);\n if (this.onMouse) {\n if (this.onMouse(e) == true)\n return;\n }\n if (e.which == 1 && !this.pointer_is_double) {\n if (e.ctrlKey && !e.altKey) {\n this.dragging_rectangle = new Float32Array(4);\n this.dragging_rectangle[0] = e.canvasX;\n this.dragging_rectangle[1] = e.canvasY;\n this.dragging_rectangle[2] = 1;\n this.dragging_rectangle[3] = 1;\n skip_action = true;\n }\n if (LiteGraph.alt_drag_do_clone_nodes && e.altKey && !e.ctrlKey && node2 && this.allow_interaction && !skip_action && !this.read_only) {\n const cloned = node2.clone();\n if (cloned) {\n cloned.pos[0] += 5;\n cloned.pos[1] += 5;\n this.graph.add(cloned, false, { doCalcSize: false });\n node2 = cloned;\n skip_action = true;\n if (!block_drag_node) {\n if (this.allow_dragnodes) {\n this.graph.beforeChange();\n this.node_dragged = node2;\n }\n if (!this.selected_nodes[node2.id]) {\n this.processNodeSelected(node2, e);\n }\n }\n }\n }\n var clicking_canvas_bg = false;\n if (node2 && (this.allow_interaction || node2.flags.allow_interaction) && !skip_action && !this.read_only) {\n if (!this.live_mode && !node2.flags.pinned) {\n this.bringToFront(node2);\n }\n if (this.allow_interaction && !this.connecting_links && !node2.flags.collapsed && !this.live_mode) {\n if (!skip_action && node2.resizable !== false && node2.inResizeCorner(e.canvasX, e.canvasY)) {\n this.graph.beforeChange();\n this.resizing_node = node2;\n this.canvas.style.cursor = \"se-resize\";\n skip_action = true;\n } else {\n if (node2.outputs) {\n for (var i2 = 0, l = node2.outputs.length; i2 < l; ++i2) {\n var output = node2.outputs[i2];\n var link_pos = node2.getConnectionPos(false, i2);\n if (isInsideRectangle(\n e.canvasX,\n e.canvasY,\n link_pos[0] - 15,\n link_pos[1] - 10,\n 30,\n 20\n )) {\n if (e.shiftKey) {\n if (((_a = output.links) == null ? void 0 : _a.length) > 0) {\n this.connecting_links = [];\n for (const linkId of output.links) {\n const link2 = this.graph.links[linkId];\n const slot = link2.target_slot;\n const linked_node = this.graph._nodes_by_id[link2.target_id];\n const input2 = linked_node.inputs[slot];\n const pos3 = linked_node.getConnectionPos(true, slot);\n this.connecting_links.push({\n node: linked_node,\n slot,\n input: input2,\n output: null,\n pos: pos3\n });\n }\n skip_action = true;\n break;\n }\n }\n output.slot_index = i2;\n this.connecting_links = [\n {\n node: node2,\n slot: i2,\n input: null,\n output,\n pos: link_pos\n }\n ];\n if (LiteGraph.shift_click_do_break_link_from) {\n if (e.shiftKey) {\n node2.disconnectOutput(i2);\n }\n } else if (LiteGraph.ctrl_alt_click_do_break_link) {\n if (e.ctrlKey && e.altKey && !e.shiftKey) {\n node2.disconnectOutput(i2);\n }\n }\n if (is_double_click) {\n if (node2.onOutputDblClick) {\n node2.onOutputDblClick(i2, e);\n }\n } else {\n if (node2.onOutputClick) {\n node2.onOutputClick(i2, e);\n }\n }\n skip_action = true;\n break;\n }\n }\n }\n if (node2.inputs) {\n for (var i2 = 0, l = node2.inputs.length; i2 < l; ++i2) {\n var input = node2.inputs[i2];\n var link_pos = node2.getConnectionPos(true, i2);\n if (isInsideRectangle(\n e.canvasX,\n e.canvasY,\n link_pos[0] - 15,\n link_pos[1] - 10,\n 30,\n 20\n )) {\n if (is_double_click) {\n if (node2.onInputDblClick) {\n node2.onInputDblClick(i2, e);\n }\n } else {\n if (node2.onInputClick) {\n node2.onInputClick(i2, e);\n }\n }\n if (input.link !== null) {\n var link_info = this.graph.links[input.link];\n if (LiteGraph.click_do_break_link_to || LiteGraph.ctrl_alt_click_do_break_link && e.ctrlKey && e.altKey && !e.shiftKey) {\n node2.disconnectInput(i2);\n } else if (this.allow_reconnect_links || //this.move_destination_link_without_shift ||\n e.shiftKey) {\n if (!LiteGraph.click_do_break_link_to) {\n node2.disconnectInput(i2);\n }\n const linked_node = this.graph._nodes_by_id[link_info.origin_id];\n const slot = link_info.origin_slot;\n this.connecting_links = [\n {\n node: linked_node,\n slot,\n input: null,\n output: linked_node.outputs[slot],\n pos: linked_node.getConnectionPos(false, slot)\n }\n ];\n this.dirty_bgcanvas = true;\n skip_action = true;\n } else ;\n }\n if (!skip_action) {\n this.connecting_links = [\n {\n node: node2,\n slot: i2,\n input,\n output: null,\n pos: link_pos\n }\n ];\n this.dirty_bgcanvas = true;\n skip_action = true;\n }\n break;\n }\n }\n }\n }\n }\n if (!skip_action) {\n var block_drag_node = false;\n if (node2 && node2.flags && node2.flags.pinned) {\n block_drag_node = true;\n }\n var pos2 = [e.canvasX - node2.pos[0], e.canvasY - node2.pos[1]];\n var widget = this.processNodeWidgets(node2, this.graph_mouse, e);\n if (widget) {\n block_drag_node = true;\n this.node_widget = [node2, widget];\n }\n if (this.allow_interaction && is_double_click && this.selected_nodes[node2.id]) {\n if (node2.onDblClick) {\n node2.onDblClick(e, pos2, this);\n }\n this.processNodeDblClicked(node2);\n block_drag_node = true;\n }\n if (node2.onMouseDown && node2.onMouseDown(e, pos2, this)) {\n block_drag_node = true;\n } else {\n if (node2.subgraph && !node2.skip_subgraph_button) {\n if (!node2.flags.collapsed && pos2[0] > node2.size[0] - LiteGraph.NODE_TITLE_HEIGHT && pos2[1] < 0) {\n var that2 = this;\n setTimeout(function() {\n that2.openSubgraph(node2.subgraph);\n }, 10);\n }\n }\n if (this.live_mode) {\n clicking_canvas_bg = true;\n block_drag_node = true;\n }\n }\n if (!block_drag_node) {\n if (this.allow_dragnodes) {\n this.graph.beforeChange();\n this.node_dragged = node2;\n }\n if (!(e.shiftKey && !e.ctrlKey && !e.altKey) || !node2.is_selected) {\n this.processNodeSelected(node2, e);\n }\n } else {\n if (!node2.is_selected) this.processNodeSelected(node2, e);\n }\n this.dirty_canvas = true;\n }\n } else {\n if (!skip_action) {\n if (!this.read_only) {\n for (var i2 = 0; i2 < this.visible_links.length; ++i2) {\n var link = this.visible_links[i2];\n var center = link._pos;\n if (!center || e.canvasX < center[0] - 4 || e.canvasX > center[0] + 4 || e.canvasY < center[1] - 4 || e.canvasY > center[1] + 4) {\n continue;\n }\n this.showLinkMenu(link, e);\n this.over_link_center = null;\n break;\n }\n }\n this.selected_group = this.graph.getGroupOnPos(e.canvasX, e.canvasY);\n this.selected_group_resizing = false;\n if (this.selected_group && !this.read_only) {\n if (e.ctrlKey) {\n this.dragging_rectangle = null;\n }\n var dist = distance([e.canvasX, e.canvasY], [this.selected_group.pos[0] + this.selected_group.size[0], this.selected_group.pos[1] + this.selected_group.size[1]]);\n if (dist * this.ds.scale < 10) {\n this.selected_group_resizing = true;\n } else {\n this.selected_group.recomputeInsideNodes();\n }\n }\n if (is_double_click && !this.read_only) {\n if (this.allow_searchbox) {\n this.showSearchBox(e);\n e.preventDefault();\n e.stopPropagation();\n }\n this.canvas.dispatchEvent(new CustomEvent(\n \"litegraph:canvas\",\n {\n bubbles: true,\n detail: {\n subType: \"empty-double-click\",\n originalEvent: e\n }\n }\n ));\n }\n clicking_canvas_bg = true;\n }\n }\n if (!skip_action && clicking_canvas_bg && this.allow_dragcanvas) {\n this.dragging_canvas = true;\n }\n } else if (e.which == 2) {\n if (LiteGraph.middle_click_slot_add_default_node) {\n if (node2 && this.allow_interaction && !skip_action && !this.read_only) {\n if (!this.connecting_links && !node2.flags.collapsed && !this.live_mode) {\n var mClikSlot = false;\n var mClikSlot_index = false;\n var mClikSlot_isOut = false;\n if (node2.outputs) {\n for (var i2 = 0, l = node2.outputs.length; i2 < l; ++i2) {\n var output = node2.outputs[i2];\n var link_pos = node2.getConnectionPos(false, i2);\n if (isInsideRectangle(e.canvasX, e.canvasY, link_pos[0] - 15, link_pos[1] - 10, 30, 20)) {\n mClikSlot = output;\n mClikSlot_index = i2;\n mClikSlot_isOut = true;\n break;\n }\n }\n }\n if (node2.inputs) {\n for (var i2 = 0, l = node2.inputs.length; i2 < l; ++i2) {\n var input = node2.inputs[i2];\n var link_pos = node2.getConnectionPos(true, i2);\n if (isInsideRectangle(e.canvasX, e.canvasY, link_pos[0] - 15, link_pos[1] - 10, 30, 20)) {\n mClikSlot = input;\n mClikSlot_index = i2;\n mClikSlot_isOut = false;\n break;\n }\n }\n }\n if (mClikSlot && mClikSlot_index !== false) {\n var alphaPosY = 0.5 - (mClikSlot_index + 1) / (mClikSlot_isOut ? node2.outputs.length : node2.inputs.length);\n var node_bounding = node2.getBounding();\n var posRef = [\n !mClikSlot_isOut ? node_bounding[0] : node_bounding[0] + node_bounding[2],\n e.canvasY - 80\n // + node_bounding[0]/this.canvas.width*66 // vertical \"derive\"\n ];\n this.createDefaultNodeForSlot({\n nodeFrom: !mClikSlot_isOut ? null : node2,\n slotFrom: !mClikSlot_isOut ? null : mClikSlot_index,\n nodeTo: !mClikSlot_isOut ? node2 : null,\n slotTo: !mClikSlot_isOut ? mClikSlot_index : null,\n position: posRef,\n nodeType: \"AUTO\",\n posAdd: [!mClikSlot_isOut ? -30 : 30, -alphaPosY * 130],\n posSizeFix: [!mClikSlot_isOut ? -1 : 0, 0]\n //-alphaPosY*2*/\n });\n skip_action = true;\n }\n }\n }\n }\n if (!skip_action && this.allow_dragcanvas) {\n this.dragging_canvas = true;\n }\n } else if (e.which == 3 || this.pointer_is_double) {\n if (this.allow_interaction && !skip_action && !this.read_only) {\n if (node2) {\n if (Object.keys(this.selected_nodes).length && (this.selected_nodes[node2.id] || e.shiftKey || e.ctrlKey || e.metaKey)) {\n if (!this.selected_nodes[node2.id]) this.selectNodes([node2], true);\n } else {\n this.selectNodes([node2]);\n }\n }\n this.processContextMenu(node2, e);\n }\n }\n this.last_mouse[0] = e.clientX;\n this.last_mouse[1] = e.clientY;\n this.last_mouseclick = LiteGraph.getTime();\n this.last_mouse_dragging = true;\n this.graph.change();\n if (!ref_window2.document.activeElement || ref_window2.document.activeElement.nodeName.toLowerCase() != \"input\" && ref_window2.document.activeElement.nodeName.toLowerCase() != \"textarea\") {\n e.preventDefault();\n }\n e.stopPropagation();\n if (this.onMouseDown) {\n this.onMouseDown(e);\n }\n return false;\n };\n LGraphCanvas.prototype.processMouseMove = function(e) {\n if (this.autoresize) {\n this.resize();\n }\n if (this.set_canvas_dirty_on_mouse_event)\n this.dirty_canvas = true;\n if (!this.graph) {\n return;\n }\n LGraphCanvas.active_canvas = this;\n this.adjustMouseEvent(e);\n var mouse = [e.clientX, e.clientY];\n this.mouse[0] = mouse[0];\n this.mouse[1] = mouse[1];\n var delta2 = [\n mouse[0] - this.last_mouse[0],\n mouse[1] - this.last_mouse[1]\n ];\n this.last_mouse = mouse;\n this.graph_mouse[0] = e.canvasX;\n this.graph_mouse[1] = e.canvasY;\n if (this.block_click) {\n e.preventDefault();\n return false;\n }\n e.dragging = this.last_mouse_dragging;\n if (this.node_widget) {\n this.processNodeWidgets(\n this.node_widget[0],\n this.graph_mouse,\n e,\n this.node_widget[1]\n );\n this.dirty_canvas = true;\n }\n var node2 = this.graph.getNodeOnPos(e.canvasX, e.canvasY, this.visible_nodes);\n if (this.dragging_rectangle) {\n this.dragging_rectangle[2] = e.canvasX - this.dragging_rectangle[0];\n this.dragging_rectangle[3] = e.canvasY - this.dragging_rectangle[1];\n this.dirty_canvas = true;\n } else if (this.selected_group && !this.read_only) {\n if (this.selected_group_resizing) {\n this.selected_group.size = [\n e.canvasX - this.selected_group.pos[0],\n e.canvasY - this.selected_group.pos[1]\n ];\n } else {\n var deltax = delta2[0] / this.ds.scale;\n var deltay = delta2[1] / this.ds.scale;\n this.selected_group.move(deltax, deltay, e.ctrlKey);\n if (this.selected_group._nodes.length) {\n this.dirty_canvas = true;\n }\n }\n this.dirty_bgcanvas = true;\n } else if (this.dragging_canvas) {\n this.ds.offset[0] += delta2[0] / this.ds.scale;\n this.ds.offset[1] += delta2[1] / this.ds.scale;\n this.dirty_canvas = true;\n this.dirty_bgcanvas = true;\n } else if ((this.allow_interaction || node2 && node2.flags.allow_interaction) && !this.read_only) {\n if (this.connecting_links) {\n this.dirty_canvas = true;\n }\n for (var i2 = 0, l = this.graph._nodes.length; i2 < l; ++i2) {\n if (this.graph._nodes[i2].mouseOver && node2 != this.graph._nodes[i2]) {\n this.graph._nodes[i2].mouseOver = false;\n if (this.node_over && this.node_over.onMouseLeave) {\n this.node_over.onMouseLeave(e);\n }\n this.node_over = null;\n this.dirty_canvas = true;\n }\n }\n if (node2) {\n if (node2.redraw_on_mouse)\n this.dirty_canvas = true;\n if (!node2.mouseOver) {\n node2.mouseOver = true;\n this.node_over = node2;\n this.dirty_canvas = true;\n if (node2.onMouseEnter) {\n node2.onMouseEnter(e);\n }\n }\n if (node2.onMouseMove) {\n node2.onMouseMove(e, [e.canvasX - node2.pos[0], e.canvasY - node2.pos[1]], this);\n }\n if (this.connecting_links) {\n const firstLink = this.connecting_links[0];\n if (firstLink.output) {\n var pos2 = this._highlight_input || [0, 0];\n if (this.isOverNodeBox(node2, e.canvasX, e.canvasY)) ;\n else {\n var slot = this.isOverNodeInput(node2, e.canvasX, e.canvasY, pos2);\n if (slot != -1 && node2.inputs[slot] && LiteGraph.isValidConnection(firstLink.output.type, node2.inputs[slot].type)) {\n this._highlight_input = pos2;\n this._highlight_input_slot = node2.inputs[slot];\n } else {\n this._highlight_input = null;\n this._highlight_input_slot = null;\n }\n }\n } else if (firstLink.input) {\n var pos2 = this._highlight_output || [0, 0];\n if (this.isOverNodeBox(node2, e.canvasX, e.canvasY)) ;\n else {\n var slot = this.isOverNodeOutput(node2, e.canvasX, e.canvasY, pos2);\n if (slot != -1 && node2.outputs[slot] && LiteGraph.isValidConnection(firstLink.input.type, node2.outputs[slot].type)) {\n this._highlight_output = pos2;\n } else {\n this._highlight_output = null;\n }\n }\n }\n }\n if (this.canvas) {\n if (node2.inResizeCorner(e.canvasX, e.canvasY)) {\n this.canvas.style.cursor = \"se-resize\";\n } else {\n this.canvas.style.cursor = \"crosshair\";\n }\n }\n } else {\n var over_link = null;\n for (var i2 = 0; i2 < this.visible_links.length; ++i2) {\n var link = this.visible_links[i2];\n var center = link._pos;\n if (!center || e.canvasX < center[0] - 4 || e.canvasX > center[0] + 4 || e.canvasY < center[1] - 4 || e.canvasY > center[1] + 4) {\n continue;\n }\n over_link = link;\n break;\n }\n if (over_link != this.over_link_center) {\n this.over_link_center = over_link;\n this.dirty_canvas = true;\n }\n if (this.canvas) {\n this.canvas.style.cursor = \"\";\n }\n }\n if (this.node_capturing_input && this.node_capturing_input != node2 && this.node_capturing_input.onMouseMove) {\n this.node_capturing_input.onMouseMove(e, [e.canvasX - this.node_capturing_input.pos[0], e.canvasY - this.node_capturing_input.pos[1]], this);\n }\n if (this.node_dragged && !this.live_mode) {\n for (var i2 in this.selected_nodes) {\n var n = this.selected_nodes[i2];\n n.pos[0] += delta2[0] / this.ds.scale;\n n.pos[1] += delta2[1] / this.ds.scale;\n if (!n.is_selected) this.processNodeSelected(n, e);\n }\n this.dirty_canvas = true;\n this.dirty_bgcanvas = true;\n }\n if (this.resizing_node && !this.live_mode) {\n var desired_size = [e.canvasX - this.resizing_node.pos[0], e.canvasY - this.resizing_node.pos[1]];\n var min_size = this.resizing_node.computeSize();\n desired_size[0] = Math.max(min_size[0], desired_size[0]);\n desired_size[1] = Math.max(min_size[1], desired_size[1]);\n this.resizing_node.setSize(desired_size);\n this.canvas.style.cursor = \"se-resize\";\n this.dirty_canvas = true;\n this.dirty_bgcanvas = true;\n }\n }\n e.preventDefault();\n return false;\n };\n LGraphCanvas.prototype.processMouseUp = function(e) {\n var is_primary = e.isPrimary === void 0 || e.isPrimary;\n if (!is_primary) {\n return false;\n }\n if (!this.graph)\n return;\n var window2 = this.getCanvasWindow();\n var document2 = window2.document;\n LGraphCanvas.active_canvas = this;\n if (!this.options.skip_events) {\n LiteGraph.pointerListenerRemove(document2, \"move\", this._mousemove_callback, true);\n LiteGraph.pointerListenerAdd(this.canvas, \"move\", this._mousemove_callback, true);\n LiteGraph.pointerListenerRemove(document2, \"up\", this._mouseup_callback, true);\n }\n this.adjustMouseEvent(e);\n var now = LiteGraph.getTime();\n e.click_time = now - this.last_mouseclick;\n this.last_mouse_dragging = false;\n this.last_click_position = null;\n if (this.block_click) {\n this.block_click = false;\n }\n if (e.which == 1) {\n if (this.node_widget) {\n this.processNodeWidgets(this.node_widget[0], this.graph_mouse, e);\n }\n this.node_widget = null;\n if (this.selected_group) {\n var diffx = this.selected_group.pos[0] - Math.round(this.selected_group.pos[0]);\n var diffy = this.selected_group.pos[1] - Math.round(this.selected_group.pos[1]);\n this.selected_group.move(diffx, diffy, e.ctrlKey);\n this.selected_group.pos[0] = Math.round(\n this.selected_group.pos[0]\n );\n this.selected_group.pos[1] = Math.round(\n this.selected_group.pos[1]\n );\n if (this.selected_group._nodes.length) {\n this.dirty_canvas = true;\n }\n this.selected_group = null;\n }\n this.selected_group_resizing = false;\n var node2 = this.graph.getNodeOnPos(\n e.canvasX,\n e.canvasY,\n this.visible_nodes\n );\n if (this.dragging_rectangle) {\n if (this.graph) {\n var nodes = this.graph._nodes;\n var node_bounding = new Float32Array(4);\n var w2 = Math.abs(this.dragging_rectangle[2]);\n var h = Math.abs(this.dragging_rectangle[3]);\n var startx = this.dragging_rectangle[2] < 0 ? this.dragging_rectangle[0] - w2 : this.dragging_rectangle[0];\n var starty = this.dragging_rectangle[3] < 0 ? this.dragging_rectangle[1] - h : this.dragging_rectangle[1];\n this.dragging_rectangle[0] = startx;\n this.dragging_rectangle[1] = starty;\n this.dragging_rectangle[2] = w2;\n this.dragging_rectangle[3] = h;\n if (!node2 || w2 > 10 && h > 10) {\n var to_select = [];\n for (var i2 = 0; i2 < nodes.length; ++i2) {\n var nodeX = nodes[i2];\n nodeX.getBounding(node_bounding);\n if (!overlapBounding(\n this.dragging_rectangle,\n node_bounding\n )) {\n continue;\n }\n to_select.push(nodeX);\n }\n if (to_select.length) {\n this.selectNodes(to_select, e.shiftKey);\n }\n } else {\n this.selectNodes([node2], e.shiftKey || e.ctrlKey);\n }\n }\n this.dragging_rectangle = null;\n } else if (this.connecting_links) {\n if (node2) {\n for (const link of this.connecting_links) {\n this.dirty_canvas = true;\n this.dirty_bgcanvas = true;\n if (link.output) {\n var slot = this.isOverNodeInput(\n node2,\n e.canvasX,\n e.canvasY\n );\n if (slot != -1) {\n link.node.connect(link.slot, node2, slot);\n } else {\n link.node.connectByType(link.slot, node2, link.output.type);\n }\n } else if (link.input) {\n var slot = this.isOverNodeOutput(\n node2,\n e.canvasX,\n e.canvasY\n );\n if (slot != -1) {\n node2.connect(slot, link.node, link.slot);\n } else {\n link.node.connectByTypeOutput(link.slot, node2, link.input.type);\n }\n }\n }\n } else {\n const firstLink = this.connecting_links[0];\n const linkReleaseContext = firstLink.output ? {\n node_from: firstLink.node,\n slot_from: firstLink.output,\n type_filter_in: firstLink.output.type\n } : {\n node_to: firstLink.node,\n slot_from: firstLink.input,\n type_filter_out: firstLink.input.type\n };\n const linkReleaseContextExtended = {\n links: this.connecting_links\n };\n this.canvas.dispatchEvent(new CustomEvent(\n \"litegraph:canvas\",\n {\n bubbles: true,\n detail: {\n subType: \"empty-release\",\n originalEvent: e,\n linkReleaseContext: linkReleaseContextExtended\n }\n }\n ));\n if (LiteGraph.release_link_on_empty_shows_menu) {\n if (e.shiftKey) {\n if (this.allow_searchbox) {\n this.showSearchBox(e, linkReleaseContext);\n }\n } else {\n if (firstLink.output) {\n this.showConnectionMenu({ nodeFrom: firstLink.node, slotFrom: firstLink.output, e });\n } else if (firstLink.input) {\n this.showConnectionMenu({ nodeTo: firstLink.node, slotTo: firstLink.input, e });\n }\n }\n }\n }\n this.connecting_links = null;\n } else if (this.resizing_node) {\n this.dirty_canvas = true;\n this.dirty_bgcanvas = true;\n this.graph.afterChange(this.resizing_node);\n this.resizing_node = null;\n } else if (this.node_dragged) {\n var node2 = this.node_dragged;\n if (node2 && e.click_time < 300 && isInsideRectangle(e.canvasX, e.canvasY, node2.pos[0], node2.pos[1] - LiteGraph.NODE_TITLE_HEIGHT, LiteGraph.NODE_TITLE_HEIGHT, LiteGraph.NODE_TITLE_HEIGHT)) {\n node2.collapse();\n }\n this.dirty_canvas = true;\n this.dirty_bgcanvas = true;\n this.node_dragged.pos[0] = Math.round(this.node_dragged.pos[0]);\n this.node_dragged.pos[1] = Math.round(this.node_dragged.pos[1]);\n if (this.graph.config.align_to_grid || this.align_to_grid) {\n this.node_dragged.alignToGrid();\n }\n if (this.onNodeMoved)\n this.onNodeMoved(this.node_dragged);\n this.graph.afterChange(this.node_dragged);\n this.node_dragged = null;\n } else {\n var node2 = this.graph.getNodeOnPos(\n e.canvasX,\n e.canvasY,\n this.visible_nodes\n );\n if (!node2 && e.click_time < 300) {\n this.deselectAllNodes();\n }\n this.dirty_canvas = true;\n this.dragging_canvas = false;\n if (this.node_over && this.node_over.onMouseUp) {\n this.node_over.onMouseUp(e, [e.canvasX - this.node_over.pos[0], e.canvasY - this.node_over.pos[1]], this);\n }\n if (this.node_capturing_input && this.node_capturing_input.onMouseUp) {\n this.node_capturing_input.onMouseUp(e, [\n e.canvasX - this.node_capturing_input.pos[0],\n e.canvasY - this.node_capturing_input.pos[1]\n ]);\n }\n }\n } else if (e.which == 2) {\n this.dirty_canvas = true;\n this.dragging_canvas = false;\n } else if (e.which == 3) {\n this.dirty_canvas = true;\n this.dragging_canvas = false;\n }\n if (is_primary) {\n this.pointer_is_down = false;\n this.pointer_is_double = false;\n }\n this.graph.change();\n e.stopPropagation();\n e.preventDefault();\n return false;\n };\n LGraphCanvas.prototype.processMouseWheel = function(e) {\n if (!this.graph || !this.allow_dragcanvas) {\n return;\n }\n var delta2 = e.wheelDeltaY != null ? e.wheelDeltaY : e.detail * -60;\n this.adjustMouseEvent(e);\n var x2 = e.clientX;\n var y2 = e.clientY;\n var is_inside = !this.viewport || this.viewport && x2 >= this.viewport[0] && x2 < this.viewport[0] + this.viewport[2] && y2 >= this.viewport[1] && y2 < this.viewport[1] + this.viewport[3];\n if (!is_inside)\n return;\n var scale = this.ds.scale;\n if (delta2 > 0) {\n scale *= 1.1;\n } else if (delta2 < 0) {\n scale *= 1 / 1.1;\n }\n this.ds.changeScale(scale, [e.clientX, e.clientY]);\n this.graph.change();\n e.preventDefault();\n return false;\n };\n LGraphCanvas.prototype.isOverNodeBox = function(node2, canvasx, canvasy) {\n var title_height = LiteGraph.NODE_TITLE_HEIGHT;\n if (isInsideRectangle(\n canvasx,\n canvasy,\n node2.pos[0] + 2,\n node2.pos[1] + 2 - title_height,\n title_height - 4,\n title_height - 4\n )) {\n return true;\n }\n return false;\n };\n LGraphCanvas.prototype.isOverNodeInput = function(node2, canvasx, canvasy, slot_pos) {\n var _a, _b;\n if (node2.inputs) {\n for (var i2 = 0, l = node2.inputs.length; i2 < l; ++i2) {\n var input = node2.inputs[i2];\n var link_pos = node2.getConnectionPos(true, i2);\n var is_inside = false;\n if (node2.horizontal) {\n is_inside = isInsideRectangle(\n canvasx,\n canvasy,\n link_pos[0] - 5,\n link_pos[1] - 10,\n 10,\n 20\n );\n } else {\n const width2 = 20 + ((((_a = input.label) == null ? void 0 : _a.length) ?? ((_b = input.name) == null ? void 0 : _b.length)) || 3) * 7;\n is_inside = isInsideRectangle(\n canvasx,\n canvasy,\n link_pos[0] - 10,\n link_pos[1] - 10,\n width2,\n 20\n );\n }\n if (is_inside) {\n if (slot_pos) {\n slot_pos[0] = link_pos[0];\n slot_pos[1] = link_pos[1];\n }\n return i2;\n }\n }\n }\n return -1;\n };\n LGraphCanvas.prototype.isOverNodeOutput = function(node2, canvasx, canvasy, slot_pos) {\n if (node2.outputs) {\n for (var i2 = 0, l = node2.outputs.length; i2 < l; ++i2) {\n node2.outputs[i2];\n var link_pos = node2.getConnectionPos(false, i2);\n var is_inside = false;\n if (node2.horizontal) {\n is_inside = isInsideRectangle(\n canvasx,\n canvasy,\n link_pos[0] - 5,\n link_pos[1] - 10,\n 10,\n 20\n );\n } else {\n is_inside = isInsideRectangle(\n canvasx,\n canvasy,\n link_pos[0] - 10,\n link_pos[1] - 10,\n 40,\n 20\n );\n }\n if (is_inside) {\n if (slot_pos) {\n slot_pos[0] = link_pos[0];\n slot_pos[1] = link_pos[1];\n }\n return i2;\n }\n }\n }\n return -1;\n };\n LGraphCanvas.prototype.processKey = function(e) {\n if (!this.graph) {\n return;\n }\n var block_default = false;\n if (e.target.localName == \"input\") {\n return;\n }\n if (e.type == \"keydown\") {\n if (e.keyCode == 32) {\n this.dragging_canvas = true;\n block_default = true;\n }\n if (e.keyCode == 27) {\n if (this.node_panel) this.node_panel.close();\n if (this.options_panel) this.options_panel.close();\n block_default = true;\n }\n if (e.keyCode == 65 && e.ctrlKey) {\n this.selectNodes();\n block_default = true;\n }\n if (e.keyCode === 67 && (e.metaKey || e.ctrlKey) && !e.shiftKey) {\n if (this.selected_nodes) {\n this.copyToClipboard();\n block_default = true;\n }\n }\n if (e.keyCode === 86 && (e.metaKey || e.ctrlKey)) {\n this.pasteFromClipboard(e.shiftKey);\n }\n if (e.keyCode == 46 || e.keyCode == 8) {\n if (e.target.localName != \"input\" && e.target.localName != \"textarea\") {\n this.deleteSelectedNodes();\n block_default = true;\n }\n }\n if (this.selected_nodes) {\n for (var i2 in this.selected_nodes) {\n if (this.selected_nodes[i2].onKeyDown) {\n this.selected_nodes[i2].onKeyDown(e);\n }\n }\n }\n } else if (e.type == \"keyup\") {\n if (e.keyCode == 32) {\n this.dragging_canvas = false;\n }\n if (this.selected_nodes) {\n for (var i2 in this.selected_nodes) {\n if (this.selected_nodes[i2].onKeyUp) {\n this.selected_nodes[i2].onKeyUp(e);\n }\n }\n }\n }\n this.graph.change();\n if (block_default) {\n e.preventDefault();\n e.stopImmediatePropagation();\n return false;\n }\n };\n LGraphCanvas.prototype.copyToClipboard = function(nodes) {\n var clipboard_info = {\n nodes: [],\n links: []\n };\n var index2 = 0;\n var selected_nodes_array = [];\n if (!nodes) nodes = this.selected_nodes;\n for (var i2 in nodes) {\n var node2 = nodes[i2];\n if (node2.clonable === false)\n continue;\n node2._relative_id = index2;\n selected_nodes_array.push(node2);\n index2 += 1;\n }\n for (var i2 = 0; i2 < selected_nodes_array.length; ++i2) {\n var node2 = selected_nodes_array[i2];\n var cloned = node2.clone();\n if (!cloned) {\n console.warn(\"node type not found: \" + node2.type);\n continue;\n }\n clipboard_info.nodes.push(cloned.serialize());\n if (node2.inputs && node2.inputs.length) {\n for (var j = 0; j < node2.inputs.length; ++j) {\n var input = node2.inputs[j];\n if (!input || input.link == null) {\n continue;\n }\n var link_info = this.graph.links[input.link];\n if (!link_info) {\n continue;\n }\n var target_node = this.graph.getNodeById(\n link_info.origin_id\n );\n if (!target_node) {\n continue;\n }\n clipboard_info.links.push([\n target_node._relative_id,\n link_info.origin_slot,\n //j,\n node2._relative_id,\n link_info.target_slot,\n target_node.id\n ]);\n }\n }\n }\n localStorage.setItem(\n \"litegrapheditor_clipboard\",\n JSON.stringify(clipboard_info)\n );\n };\n LGraphCanvas.prototype.pasteFromClipboard = function(isConnectUnselected = false) {\n if (!LiteGraph.ctrl_shift_v_paste_connect_unselected_outputs && isConnectUnselected) {\n return;\n }\n var data = localStorage.getItem(\"litegrapheditor_clipboard\");\n if (!data) {\n return;\n }\n this.graph.beforeChange();\n var clipboard_info = JSON.parse(data);\n var posMin = false;\n var posMinIndexes = false;\n for (var i2 = 0; i2 < clipboard_info.nodes.length; ++i2) {\n if (posMin) {\n if (posMin[0] > clipboard_info.nodes[i2].pos[0]) {\n posMin[0] = clipboard_info.nodes[i2].pos[0];\n posMinIndexes[0] = i2;\n }\n if (posMin[1] > clipboard_info.nodes[i2].pos[1]) {\n posMin[1] = clipboard_info.nodes[i2].pos[1];\n posMinIndexes[1] = i2;\n }\n } else {\n posMin = [clipboard_info.nodes[i2].pos[0], clipboard_info.nodes[i2].pos[1]];\n posMinIndexes = [i2, i2];\n }\n }\n var nodes = [];\n for (var i2 = 0; i2 < clipboard_info.nodes.length; ++i2) {\n var node_data = clipboard_info.nodes[i2];\n var node2 = LiteGraph.createNode(node_data.type);\n if (node2) {\n node2.configure(node_data);\n node2.pos[0] += this.graph_mouse[0] - posMin[0];\n node2.pos[1] += this.graph_mouse[1] - posMin[1];\n this.graph.add(node2, { doProcessChange: false });\n nodes.push(node2);\n }\n }\n for (var i2 = 0; i2 < clipboard_info.links.length; ++i2) {\n var link_info = clipboard_info.links[i2];\n var origin_node = void 0;\n var origin_node_relative_id = link_info[0];\n if (origin_node_relative_id != null) {\n origin_node = nodes[origin_node_relative_id];\n } else if (LiteGraph.ctrl_shift_v_paste_connect_unselected_outputs && isConnectUnselected) {\n var origin_node_id = link_info[4];\n if (origin_node_id) {\n origin_node = this.graph.getNodeById(origin_node_id);\n }\n }\n var target_node = nodes[link_info[2]];\n if (origin_node && target_node)\n origin_node.connect(link_info[1], target_node, link_info[3]);\n else\n console.warn(\"Warning, nodes missing on pasting\");\n }\n this.selectNodes(nodes);\n this.graph.afterChange();\n };\n LGraphCanvas.prototype.processDrop = function(e) {\n e.preventDefault();\n this.adjustMouseEvent(e);\n var x2 = e.clientX;\n var y2 = e.clientY;\n var is_inside = !this.viewport || this.viewport && x2 >= this.viewport[0] && x2 < this.viewport[0] + this.viewport[2] && y2 >= this.viewport[1] && y2 < this.viewport[1] + this.viewport[3];\n if (!is_inside) {\n return;\n }\n var pos2 = [e.canvasX, e.canvasY];\n var node2 = this.graph ? this.graph.getNodeOnPos(pos2[0], pos2[1]) : null;\n if (!node2) {\n var r = null;\n if (this.onDropItem) {\n r = this.onDropItem(event);\n }\n if (!r) {\n this.checkDropItem(e);\n }\n return;\n }\n if (node2.onDropFile || node2.onDropData) {\n var files = e.dataTransfer.files;\n if (files && files.length) {\n for (var i2 = 0; i2 < files.length; i2++) {\n var file = e.dataTransfer.files[0];\n var filename = file.name;\n LGraphCanvas.getFileExtension(filename);\n if (node2.onDropFile) {\n node2.onDropFile(file);\n }\n if (node2.onDropData) {\n var reader = new FileReader();\n reader.onload = function(event2) {\n var data = event2.target.result;\n node2.onDropData(data, filename, file);\n };\n var type = file.type.split(\"/\")[0];\n if (type == \"text\" || type == \"\") {\n reader.readAsText(file);\n } else if (type == \"image\") {\n reader.readAsDataURL(file);\n } else {\n reader.readAsArrayBuffer(file);\n }\n }\n }\n }\n }\n if (node2.onDropItem) {\n if (node2.onDropItem(event)) {\n return true;\n }\n }\n if (this.onDropItem) {\n return this.onDropItem(event);\n }\n return false;\n };\n LGraphCanvas.prototype.checkDropItem = function(e) {\n if (e.dataTransfer.files.length) {\n var file = e.dataTransfer.files[0];\n var ext = LGraphCanvas.getFileExtension(file.name).toLowerCase();\n var nodetype = LiteGraph.node_types_by_file_extension[ext];\n if (nodetype) {\n this.graph.beforeChange();\n var node2 = LiteGraph.createNode(nodetype.type);\n node2.pos = [e.canvasX, e.canvasY];\n this.graph.add(node2);\n if (node2.onDropFile) {\n node2.onDropFile(file);\n }\n this.graph.afterChange();\n }\n }\n };\n LGraphCanvas.prototype.processNodeDblClicked = function(n) {\n if (this.onShowNodePanel) {\n this.onShowNodePanel(n);\n }\n if (this.onNodeDblClicked) {\n this.onNodeDblClicked(n);\n }\n this.setDirty(true);\n };\n LGraphCanvas.prototype.processNodeSelected = function(node2, e) {\n this.selectNode(node2, e && (e.shiftKey || e.ctrlKey || this.multi_select));\n if (this.onNodeSelected) {\n this.onNodeSelected(node2);\n }\n };\n LGraphCanvas.prototype.selectNode = function(node2, add_to_current_selection) {\n if (node2 == null) {\n this.deselectAllNodes();\n } else {\n this.selectNodes([node2], add_to_current_selection);\n }\n };\n LGraphCanvas.prototype.selectNodes = function(nodes, add_to_current_selection) {\n if (!add_to_current_selection) {\n this.deselectAllNodes();\n }\n nodes = nodes || this.graph._nodes;\n if (typeof nodes == \"string\") nodes = [nodes];\n for (var i2 in nodes) {\n var node2 = nodes[i2];\n if (node2.is_selected) {\n this.deselectNode(node2);\n continue;\n }\n if (!node2.is_selected && node2.onSelected) {\n node2.onSelected();\n }\n node2.is_selected = true;\n this.selected_nodes[node2.id] = node2;\n if (node2.inputs) {\n for (var j = 0; j < node2.inputs.length; ++j) {\n this.highlighted_links[node2.inputs[j].link] = true;\n }\n }\n if (node2.outputs) {\n for (var j = 0; j < node2.outputs.length; ++j) {\n var out = node2.outputs[j];\n if (out.links) {\n for (var k = 0; k < out.links.length; ++k) {\n this.highlighted_links[out.links[k]] = true;\n }\n }\n }\n }\n }\n if (this.onSelectionChange)\n this.onSelectionChange(this.selected_nodes);\n this.setDirty(true);\n };\n LGraphCanvas.prototype.deselectNode = function(node2) {\n if (!node2.is_selected) {\n return;\n }\n if (node2.onDeselected) {\n node2.onDeselected();\n }\n node2.is_selected = false;\n delete this.selected_nodes[node2.id];\n if (this.onNodeDeselected) {\n this.onNodeDeselected(node2);\n }\n if (node2.inputs) {\n for (var i2 = 0; i2 < node2.inputs.length; ++i2) {\n delete this.highlighted_links[node2.inputs[i2].link];\n }\n }\n if (node2.outputs) {\n for (var i2 = 0; i2 < node2.outputs.length; ++i2) {\n var out = node2.outputs[i2];\n if (out.links) {\n for (var j = 0; j < out.links.length; ++j) {\n delete this.highlighted_links[out.links[j]];\n }\n }\n }\n }\n };\n LGraphCanvas.prototype.deselectAllNodes = function() {\n if (!this.graph) {\n return;\n }\n var nodes = this.graph._nodes;\n for (var i2 = 0, l = nodes.length; i2 < l; ++i2) {\n var node2 = nodes[i2];\n if (!node2.is_selected) {\n continue;\n }\n if (node2.onDeselected) {\n node2.onDeselected();\n }\n node2.is_selected = false;\n if (this.onNodeDeselected) {\n this.onNodeDeselected(node2);\n }\n }\n this.selected_nodes = {};\n this.current_node = null;\n this.highlighted_links = {};\n if (this.onSelectionChange)\n this.onSelectionChange(this.selected_nodes);\n this.setDirty(true);\n };\n LGraphCanvas.prototype.deleteSelectedNodes = function() {\n this.graph.beforeChange();\n for (var i2 in this.selected_nodes) {\n var node2 = this.selected_nodes[i2];\n if (node2.block_delete)\n continue;\n if (node2.inputs && node2.inputs.length && node2.outputs && node2.outputs.length && LiteGraph.isValidConnection(node2.inputs[0].type, node2.outputs[0].type) && node2.inputs[0].link && node2.outputs[0].links && node2.outputs[0].links.length) {\n var input_link = node2.graph.links[node2.inputs[0].link];\n var output_link = node2.graph.links[node2.outputs[0].links[0]];\n var input_node = node2.getInputNode(0);\n var output_node = node2.getOutputNodes(0)[0];\n if (input_node && output_node)\n input_node.connect(input_link.origin_slot, output_node, output_link.target_slot);\n }\n this.graph.remove(node2);\n if (this.onNodeDeselected) {\n this.onNodeDeselected(node2);\n }\n }\n this.selected_nodes = {};\n this.current_node = null;\n this.highlighted_links = {};\n this.setDirty(true);\n this.graph.afterChange();\n };\n LGraphCanvas.prototype.centerOnNode = function(node2) {\n const dpi = (window == null ? void 0 : window.devicePixelRatio) || 1;\n this.ds.offset[0] = -node2.pos[0] - node2.size[0] * 0.5 + this.canvas.width * 0.5 / (this.ds.scale * dpi);\n this.ds.offset[1] = -node2.pos[1] - node2.size[1] * 0.5 + this.canvas.height * 0.5 / (this.ds.scale * dpi);\n this.setDirty(true, true);\n };\n LGraphCanvas.prototype.adjustMouseEvent = function(e) {\n var clientX_rel = 0;\n var clientY_rel = 0;\n if (this.canvas) {\n var b = this.canvas.getBoundingClientRect();\n clientX_rel = e.clientX - b.left;\n clientY_rel = e.clientY - b.top;\n } else {\n clientX_rel = e.clientX;\n clientY_rel = e.clientY;\n }\n if (e.deltaX === void 0)\n e.deltaX = clientX_rel - this.last_mouse_position[0];\n if (e.deltaY === void 0)\n e.deltaY = clientY_rel - this.last_mouse_position[1];\n this.last_mouse_position[0] = clientX_rel;\n this.last_mouse_position[1] = clientY_rel;\n e.canvasX = clientX_rel / this.ds.scale - this.ds.offset[0];\n e.canvasY = clientY_rel / this.ds.scale - this.ds.offset[1];\n };\n LGraphCanvas.prototype.setZoom = function(value, zooming_center) {\n this.ds.changeScale(value, zooming_center);\n this.dirty_canvas = true;\n this.dirty_bgcanvas = true;\n };\n LGraphCanvas.prototype.convertOffsetToCanvas = function(pos2, out) {\n return this.ds.convertOffsetToCanvas(pos2, out);\n };\n LGraphCanvas.prototype.convertCanvasToOffset = function(pos2, out) {\n return this.ds.convertCanvasToOffset(pos2, out);\n };\n LGraphCanvas.prototype.convertEventToCanvasOffset = function(e) {\n var rect = this.canvas.getBoundingClientRect();\n return this.convertCanvasToOffset([\n e.clientX - rect.left,\n e.clientY - rect.top\n ]);\n };\n LGraphCanvas.prototype.bringToFront = function(node2) {\n var i2 = this.graph._nodes.indexOf(node2);\n if (i2 == -1) {\n return;\n }\n this.graph._nodes.splice(i2, 1);\n this.graph._nodes.push(node2);\n };\n LGraphCanvas.prototype.sendToBack = function(node2) {\n var i2 = this.graph._nodes.indexOf(node2);\n if (i2 == -1) {\n return;\n }\n this.graph._nodes.splice(i2, 1);\n this.graph._nodes.unshift(node2);\n };\n var temp = new Float32Array(4);\n LGraphCanvas.prototype.computeVisibleNodes = function(nodes, out) {\n var visible_nodes = out || [];\n visible_nodes.length = 0;\n nodes = nodes || this.graph._nodes;\n for (var i2 = 0, l = nodes.length; i2 < l; ++i2) {\n var n = nodes[i2];\n if (this.live_mode && !n.onDrawBackground && !n.onDrawForeground) {\n continue;\n }\n if (!overlapBounding(this.visible_area, n.getBounding(temp, true))) {\n continue;\n }\n visible_nodes.push(n);\n }\n return visible_nodes;\n };\n LGraphCanvas.prototype.draw = function(force_canvas, force_bgcanvas) {\n if (!this.canvas || this.canvas.width == 0 || this.canvas.height == 0) {\n return;\n }\n var now = LiteGraph.getTime();\n this.render_time = (now - this.last_draw_time) * 1e-3;\n this.last_draw_time = now;\n if (this.graph) {\n this.ds.computeVisibleArea(this.viewport);\n }\n if (this.dirty_bgcanvas || force_bgcanvas || this.always_render_background || this.graph && this.graph._last_trigger_time && now - this.graph._last_trigger_time < 1e3) {\n this.drawBackCanvas();\n }\n if (this.dirty_canvas || force_canvas) {\n this.drawFrontCanvas();\n }\n this.fps = this.render_time ? 1 / this.render_time : 0;\n this.frame += 1;\n };\n LGraphCanvas.prototype.drawFrontCanvas = function() {\n this.dirty_canvas = false;\n if (!this.ctx) {\n this.ctx = this.bgcanvas.getContext(\"2d\");\n }\n var ctx = this.ctx;\n if (!ctx) {\n return;\n }\n var canvas = this.canvas;\n if (ctx.start2D && !this.viewport) {\n ctx.start2D();\n ctx.restore();\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n }\n var area = this.viewport || this.dirty_area;\n if (area) {\n ctx.save();\n ctx.beginPath();\n ctx.rect(area[0], area[1], area[2], area[3]);\n ctx.clip();\n }\n if (this.clear_background) {\n if (area)\n ctx.clearRect(area[0], area[1], area[2], area[3]);\n else\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n }\n if (this.bgcanvas == this.canvas) {\n this.drawBackCanvas();\n } else {\n ctx.drawImage(this.bgcanvas, 0, 0);\n }\n if (this.onRender) {\n this.onRender(canvas, ctx);\n }\n if (this.show_info) {\n this.renderInfo(ctx, area ? area[0] : 0, area ? area[1] : 0);\n }\n if (this.graph) {\n ctx.save();\n this.ds.toCanvasContext(ctx);\n var visible_nodes = this.computeVisibleNodes(\n null,\n this.visible_nodes\n );\n for (var i2 = 0; i2 < visible_nodes.length; ++i2) {\n var node2 = visible_nodes[i2];\n ctx.save();\n ctx.translate(node2.pos[0], node2.pos[1]);\n this.drawNode(node2, ctx);\n ctx.restore();\n }\n if (this.render_execution_order) {\n this.drawExecutionOrder(ctx);\n }\n if (this.graph.config.links_ontop) {\n if (!this.live_mode) {\n this.drawConnections(ctx);\n }\n }\n if (this.connecting_links) {\n for (const link of this.connecting_links) {\n ctx.lineWidth = this.connections_width;\n var link_color = null;\n var connInOrOut = link.output || link.input;\n var connType = connInOrOut.type;\n var connDir = connInOrOut.dir;\n if (connDir == null) {\n if (link.output)\n connDir = link.node.horizontal ? LiteGraph.DOWN : LiteGraph.RIGHT;\n else\n connDir = link.node.horizontal ? LiteGraph.UP : LiteGraph.LEFT;\n }\n var connShape = connInOrOut.shape;\n switch (connType) {\n case LiteGraph.EVENT:\n link_color = LiteGraph.EVENT_LINK_COLOR;\n break;\n default:\n link_color = LiteGraph.CONNECTING_LINK_COLOR;\n }\n this.renderLink(\n ctx,\n link.pos,\n [this.graph_mouse[0], this.graph_mouse[1]],\n null,\n false,\n null,\n link_color,\n connDir,\n LiteGraph.CENTER\n );\n ctx.beginPath();\n if (connType === LiteGraph.EVENT || connShape === LiteGraph.BOX_SHAPE) {\n ctx.rect(\n link.pos[0] - 6 + 0.5,\n link.pos[1] - 5 + 0.5,\n 14,\n 10\n );\n ctx.fill();\n ctx.beginPath();\n ctx.rect(\n this.graph_mouse[0] - 6 + 0.5,\n this.graph_mouse[1] - 5 + 0.5,\n 14,\n 10\n );\n } else if (connShape === LiteGraph.ARROW_SHAPE) {\n ctx.moveTo(link.pos[0] + 8, link.pos[1] + 0.5);\n ctx.lineTo(link.pos[0] - 4, link.pos[1] + 6 + 0.5);\n ctx.lineTo(link.pos[0] - 4, link.pos[1] - 6 + 0.5);\n ctx.closePath();\n } else {\n ctx.arc(\n link.pos[0],\n link.pos[1],\n 4,\n 0,\n Math.PI * 2\n );\n ctx.fill();\n ctx.beginPath();\n ctx.arc(\n this.graph_mouse[0],\n this.graph_mouse[1],\n 4,\n 0,\n Math.PI * 2\n );\n }\n ctx.fill();\n ctx.fillStyle = \"#ffcc00\";\n if (this._highlight_input) {\n ctx.beginPath();\n var shape = this._highlight_input_slot.shape;\n if (shape === LiteGraph.ARROW_SHAPE) {\n ctx.moveTo(this._highlight_input[0] + 8, this._highlight_input[1] + 0.5);\n ctx.lineTo(this._highlight_input[0] - 4, this._highlight_input[1] + 6 + 0.5);\n ctx.lineTo(this._highlight_input[0] - 4, this._highlight_input[1] - 6 + 0.5);\n ctx.closePath();\n } else {\n ctx.arc(\n this._highlight_input[0],\n this._highlight_input[1],\n 6,\n 0,\n Math.PI * 2\n );\n }\n ctx.fill();\n }\n if (this._highlight_output) {\n ctx.beginPath();\n if (shape === LiteGraph.ARROW_SHAPE) {\n ctx.moveTo(this._highlight_output[0] + 8, this._highlight_output[1] + 0.5);\n ctx.lineTo(this._highlight_output[0] - 4, this._highlight_output[1] + 6 + 0.5);\n ctx.lineTo(this._highlight_output[0] - 4, this._highlight_output[1] - 6 + 0.5);\n ctx.closePath();\n } else {\n ctx.arc(\n this._highlight_output[0],\n this._highlight_output[1],\n 6,\n 0,\n Math.PI * 2\n );\n }\n ctx.fill();\n }\n }\n }\n if (this.dragging_rectangle) {\n ctx.strokeStyle = \"#FFF\";\n ctx.strokeRect(\n this.dragging_rectangle[0],\n this.dragging_rectangle[1],\n this.dragging_rectangle[2],\n this.dragging_rectangle[3]\n );\n }\n if (this.over_link_center && this.render_link_tooltip)\n this.drawLinkTooltip(ctx, this.over_link_center);\n else if (this.onDrawLinkTooltip)\n this.onDrawLinkTooltip(ctx, null);\n if (this.onDrawForeground) {\n this.onDrawForeground(ctx, this.visible_rect);\n }\n ctx.restore();\n }\n if (this._graph_stack && this._graph_stack.length) {\n this.drawSubgraphPanel(ctx);\n }\n if (this.onDrawOverlay) {\n this.onDrawOverlay(ctx);\n }\n if (area) {\n ctx.restore();\n }\n if (ctx.finish2D) {\n ctx.finish2D();\n }\n };\n LGraphCanvas.prototype.drawSubgraphPanel = function(ctx) {\n var subgraph = this.graph;\n var subnode = subgraph._subgraph_node;\n if (!subnode) {\n console.warn(\"subgraph without subnode\");\n return;\n }\n this.drawSubgraphPanelLeft(subgraph, subnode, ctx);\n this.drawSubgraphPanelRight(subgraph, subnode, ctx);\n };\n LGraphCanvas.prototype.drawSubgraphPanelLeft = function(subgraph, subnode, ctx) {\n var num = subnode.inputs ? subnode.inputs.length : 0;\n var w2 = 200;\n var h = Math.floor(LiteGraph.NODE_SLOT_HEIGHT * 1.6);\n ctx.fillStyle = \"#111\";\n ctx.globalAlpha = 0.8;\n ctx.beginPath();\n ctx.roundRect(10, 10, w2, (num + 1) * h + 50, [8]);\n ctx.fill();\n ctx.globalAlpha = 1;\n ctx.fillStyle = \"#888\";\n ctx.font = \"14px Arial\";\n ctx.textAlign = \"left\";\n ctx.fillText(\"Graph Inputs\", 20, 34);\n if (this.drawButton(w2 - 20, 20, 20, 20, \"X\", \"#151515\")) {\n this.closeSubgraph();\n return;\n }\n var y2 = 50;\n ctx.font = \"14px Arial\";\n if (subnode.inputs)\n for (var i2 = 0; i2 < subnode.inputs.length; ++i2) {\n var input = subnode.inputs[i2];\n if (input.not_subgraph_input)\n continue;\n if (this.drawButton(20, y2 + 2, w2 - 20, h - 2)) {\n var type = subnode.constructor.input_node_type || \"graph/input\";\n this.graph.beforeChange();\n var newnode = LiteGraph.createNode(type);\n if (newnode) {\n subgraph.add(newnode);\n this.block_click = false;\n this.last_click_position = null;\n this.selectNodes([newnode]);\n this.node_dragged = newnode;\n this.dragging_canvas = false;\n newnode.setProperty(\"name\", input.name);\n newnode.setProperty(\"type\", input.type);\n this.node_dragged.pos[0] = this.graph_mouse[0] - 5;\n this.node_dragged.pos[1] = this.graph_mouse[1] - 5;\n this.graph.afterChange();\n } else\n console.error(\"graph input node not found:\", type);\n }\n ctx.fillStyle = \"#9C9\";\n ctx.beginPath();\n ctx.arc(w2 - 16, y2 + h * 0.5, 5, 0, 2 * Math.PI);\n ctx.fill();\n ctx.fillStyle = \"#AAA\";\n ctx.fillText(input.name, 30, y2 + h * 0.75);\n ctx.fillStyle = \"#777\";\n ctx.fillText(input.type, 130, y2 + h * 0.75);\n y2 += h;\n }\n if (this.drawButton(20, y2 + 2, w2 - 20, h - 2, \"+\", \"#151515\", \"#222\")) {\n this.showSubgraphPropertiesDialog(subnode);\n }\n };\n LGraphCanvas.prototype.drawSubgraphPanelRight = function(subgraph, subnode, ctx) {\n var num = subnode.outputs ? subnode.outputs.length : 0;\n var canvas_w = this.bgcanvas.width;\n var w2 = 200;\n var h = Math.floor(LiteGraph.NODE_SLOT_HEIGHT * 1.6);\n ctx.fillStyle = \"#111\";\n ctx.globalAlpha = 0.8;\n ctx.beginPath();\n ctx.roundRect(canvas_w - w2 - 10, 10, w2, (num + 1) * h + 50, [8]);\n ctx.fill();\n ctx.globalAlpha = 1;\n ctx.fillStyle = \"#888\";\n ctx.font = \"14px Arial\";\n ctx.textAlign = \"left\";\n var title_text = \"Graph Outputs\";\n var tw = ctx.measureText(title_text).width;\n ctx.fillText(title_text, canvas_w - tw - 20, 34);\n if (this.drawButton(canvas_w - w2, 20, 20, 20, \"X\", \"#151515\")) {\n this.closeSubgraph();\n return;\n }\n var y2 = 50;\n ctx.font = \"14px Arial\";\n if (subnode.outputs)\n for (var i2 = 0; i2 < subnode.outputs.length; ++i2) {\n var output = subnode.outputs[i2];\n if (output.not_subgraph_input)\n continue;\n if (this.drawButton(canvas_w - w2, y2 + 2, w2 - 20, h - 2)) {\n var type = subnode.constructor.output_node_type || \"graph/output\";\n this.graph.beforeChange();\n var newnode = LiteGraph.createNode(type);\n if (newnode) {\n subgraph.add(newnode);\n this.block_click = false;\n this.last_click_position = null;\n this.selectNodes([newnode]);\n this.node_dragged = newnode;\n this.dragging_canvas = false;\n newnode.setProperty(\"name\", output.name);\n newnode.setProperty(\"type\", output.type);\n this.node_dragged.pos[0] = this.graph_mouse[0] - 5;\n this.node_dragged.pos[1] = this.graph_mouse[1] - 5;\n this.graph.afterChange();\n } else\n console.error(\"graph input node not found:\", type);\n }\n ctx.fillStyle = \"#9C9\";\n ctx.beginPath();\n ctx.arc(canvas_w - w2 + 16, y2 + h * 0.5, 5, 0, 2 * Math.PI);\n ctx.fill();\n ctx.fillStyle = \"#AAA\";\n ctx.fillText(output.name, canvas_w - w2 + 30, y2 + h * 0.75);\n ctx.fillStyle = \"#777\";\n ctx.fillText(output.type, canvas_w - w2 + 130, y2 + h * 0.75);\n y2 += h;\n }\n if (this.drawButton(canvas_w - w2, y2 + 2, w2 - 20, h - 2, \"+\", \"#151515\", \"#222\")) {\n this.showSubgraphPropertiesDialogRight(subnode);\n }\n };\n LGraphCanvas.prototype.drawButton = function(x2, y2, w2, h, text, bgcolor, hovercolor, textcolor) {\n var ctx = this.ctx;\n bgcolor = bgcolor || LiteGraph.NODE_DEFAULT_COLOR;\n hovercolor = hovercolor || \"#555\";\n textcolor = textcolor || LiteGraph.NODE_TEXT_COLOR;\n var pos2 = this.ds.convertOffsetToCanvas(this.graph_mouse);\n var hover = LiteGraph.isInsideRectangle(pos2[0], pos2[1], x2, y2, w2, h);\n pos2 = this.last_click_position ? [this.last_click_position[0], this.last_click_position[1]] : null;\n if (pos2) {\n var rect = this.canvas.getBoundingClientRect();\n pos2[0] -= rect.left;\n pos2[1] -= rect.top;\n }\n var clicked = pos2 && LiteGraph.isInsideRectangle(pos2[0], pos2[1], x2, y2, w2, h);\n ctx.fillStyle = hover ? hovercolor : bgcolor;\n if (clicked)\n ctx.fillStyle = \"#AAA\";\n ctx.beginPath();\n ctx.roundRect(x2, y2, w2, h, [4]);\n ctx.fill();\n if (text != null) {\n if (text.constructor == String) {\n ctx.fillStyle = textcolor;\n ctx.textAlign = \"center\";\n ctx.font = (h * 0.65 | 0) + \"px Arial\";\n ctx.fillText(text, x2 + w2 * 0.5, y2 + h * 0.75);\n ctx.textAlign = \"left\";\n }\n }\n var was_clicked = clicked && !this.block_click;\n if (clicked)\n this.blockClick();\n return was_clicked;\n };\n LGraphCanvas.prototype.isAreaClicked = function(x2, y2, w2, h, hold_click) {\n var pos2 = this.mouse;\n LiteGraph.isInsideRectangle(pos2[0], pos2[1], x2, y2, w2, h);\n pos2 = this.last_click_position;\n var clicked = pos2 && LiteGraph.isInsideRectangle(pos2[0], pos2[1], x2, y2, w2, h);\n var was_clicked = clicked && !this.block_click;\n if (clicked && hold_click)\n this.blockClick();\n return was_clicked;\n };\n LGraphCanvas.prototype.renderInfo = function(ctx, x2, y2) {\n x2 = x2 || 10;\n y2 = y2 || this.canvas.offsetHeight - 80;\n ctx.save();\n ctx.translate(x2, y2);\n ctx.font = \"10px Arial\";\n ctx.fillStyle = \"#888\";\n ctx.textAlign = \"left\";\n if (this.graph) {\n ctx.fillText(\"T: \" + this.graph.globaltime.toFixed(2) + \"s\", 5, 13 * 1);\n ctx.fillText(\"I: \" + this.graph.iteration, 5, 13 * 2);\n ctx.fillText(\"N: \" + this.graph._nodes.length + \" [\" + this.visible_nodes.length + \"]\", 5, 13 * 3);\n ctx.fillText(\"V: \" + this.graph._version, 5, 13 * 4);\n ctx.fillText(\"FPS:\" + this.fps.toFixed(2), 5, 13 * 5);\n } else {\n ctx.fillText(\"No graph selected\", 5, 13 * 1);\n }\n ctx.restore();\n };\n LGraphCanvas.prototype.drawBackCanvas = function() {\n var canvas = this.bgcanvas;\n if (canvas.width != this.canvas.width || canvas.height != this.canvas.height) {\n canvas.width = this.canvas.width;\n canvas.height = this.canvas.height;\n }\n if (!this.bgctx) {\n this.bgctx = this.bgcanvas.getContext(\"2d\");\n }\n var ctx = this.bgctx;\n if (ctx.start) {\n ctx.start();\n }\n var viewport = this.viewport || [0, 0, ctx.canvas.width, ctx.canvas.height];\n if (this.clear_background) {\n ctx.clearRect(viewport[0], viewport[1], viewport[2], viewport[3]);\n }\n if (this._graph_stack && this._graph_stack.length) {\n ctx.save();\n this._graph_stack[this._graph_stack.length - 1];\n var subgraph_node = this.graph._subgraph_node;\n ctx.strokeStyle = subgraph_node.bgcolor;\n ctx.lineWidth = 10;\n ctx.strokeRect(1, 1, canvas.width - 2, canvas.height - 2);\n ctx.lineWidth = 1;\n ctx.font = \"40px Arial\";\n ctx.textAlign = \"center\";\n ctx.fillStyle = subgraph_node.bgcolor || \"#AAA\";\n var title = \"\";\n for (var i2 = 1; i2 < this._graph_stack.length; ++i2) {\n title += this._graph_stack[i2]._subgraph_node.getTitle() + \" >> \";\n }\n ctx.fillText(\n title + subgraph_node.getTitle(),\n canvas.width * 0.5,\n 40\n );\n ctx.restore();\n }\n var bg_already_painted = false;\n if (this.onRenderBackground) {\n bg_already_painted = this.onRenderBackground(canvas, ctx);\n }\n if (!this.viewport) {\n ctx.restore();\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n }\n this.visible_links.length = 0;\n if (this.graph) {\n ctx.save();\n this.ds.toCanvasContext(ctx);\n if (this.ds.scale < 1.5 && !bg_already_painted && this.clear_background_color) {\n ctx.fillStyle = this.clear_background_color;\n ctx.fillRect(\n this.visible_area[0],\n this.visible_area[1],\n this.visible_area[2],\n this.visible_area[3]\n );\n }\n if (this.background_image && this.ds.scale > 0.5 && !bg_already_painted) {\n if (this.zoom_modify_alpha) {\n ctx.globalAlpha = (1 - 0.5 / this.ds.scale) * this.editor_alpha;\n } else {\n ctx.globalAlpha = this.editor_alpha;\n }\n ctx.imageSmoothingEnabled = ctx.imageSmoothingEnabled = false;\n if (!this._bg_img || this._bg_img.name != this.background_image) {\n this._bg_img = new Image();\n this._bg_img.name = this.background_image;\n this._bg_img.src = this.background_image;\n var that2 = this;\n this._bg_img.onload = function() {\n that2.draw(true, true);\n };\n }\n var pattern = null;\n if (this._pattern == null && this._bg_img.width > 0) {\n pattern = ctx.createPattern(this._bg_img, \"repeat\");\n this._pattern_img = this._bg_img;\n this._pattern = pattern;\n } else {\n pattern = this._pattern;\n }\n if (pattern) {\n ctx.fillStyle = pattern;\n ctx.fillRect(\n this.visible_area[0],\n this.visible_area[1],\n this.visible_area[2],\n this.visible_area[3]\n );\n ctx.fillStyle = \"transparent\";\n }\n ctx.globalAlpha = 1;\n ctx.imageSmoothingEnabled = ctx.imageSmoothingEnabled = true;\n }\n if (this.graph._groups.length && !this.live_mode) {\n this.drawGroups(canvas, ctx);\n }\n if (this.onDrawBackground) {\n this.onDrawBackground(ctx, this.visible_area);\n }\n if (this.onBackgroundRender) {\n console.error(\n \"WARNING! onBackgroundRender deprecated, now is named onDrawBackground \"\n );\n this.onBackgroundRender = null;\n }\n if (this.render_canvas_border) {\n ctx.strokeStyle = \"#235\";\n ctx.strokeRect(0, 0, canvas.width, canvas.height);\n }\n if (this.render_connections_shadows) {\n ctx.shadowColor = \"#000\";\n ctx.shadowOffsetX = 0;\n ctx.shadowOffsetY = 0;\n ctx.shadowBlur = 6;\n } else {\n ctx.shadowColor = \"rgba(0,0,0,0)\";\n }\n if (!this.live_mode) {\n this.drawConnections(ctx);\n }\n ctx.shadowColor = \"rgba(0,0,0,0)\";\n ctx.restore();\n }\n if (ctx.finish) {\n ctx.finish();\n }\n this.dirty_bgcanvas = false;\n this.dirty_canvas = true;\n };\n var temp_vec2 = new Float32Array(2);\n LGraphCanvas.prototype.drawNode = function(node2, ctx) {\n this.current_node = node2;\n var color = node2.color || node2.constructor.color || LiteGraph.NODE_DEFAULT_COLOR;\n var bgcolor = node2.bgcolor || node2.constructor.bgcolor || LiteGraph.NODE_DEFAULT_BGCOLOR;\n if (node2.mouseOver) ;\n var low_quality = this.ds.scale < 0.6;\n if (this.live_mode) {\n if (!node2.flags.collapsed) {\n ctx.shadowColor = \"transparent\";\n if (node2.onDrawForeground) {\n node2.onDrawForeground(ctx, this, this.canvas);\n }\n }\n return;\n }\n var editor_alpha = this.editor_alpha;\n ctx.globalAlpha = editor_alpha;\n if (this.render_shadows && !low_quality) {\n ctx.shadowColor = LiteGraph.DEFAULT_SHADOW_COLOR;\n ctx.shadowOffsetX = 2 * this.ds.scale;\n ctx.shadowOffsetY = 2 * this.ds.scale;\n ctx.shadowBlur = 3 * this.ds.scale;\n } else {\n ctx.shadowColor = \"transparent\";\n }\n if (node2.flags.collapsed && node2.onDrawCollapsed && node2.onDrawCollapsed(ctx, this) == true) {\n return;\n }\n var shape = node2._shape || LiteGraph.BOX_SHAPE;\n var size = temp_vec2;\n temp_vec2.set(node2.size);\n var horizontal = node2.horizontal;\n if (node2.flags.collapsed) {\n ctx.font = this.inner_text_font;\n var title = node2.getTitle ? node2.getTitle() : node2.title;\n if (title != null) {\n node2._collapsed_width = Math.min(\n node2.size[0],\n ctx.measureText(title).width + LiteGraph.NODE_TITLE_HEIGHT * 2\n );\n size[0] = node2._collapsed_width;\n size[1] = 0;\n }\n }\n if (node2.clip_area) {\n ctx.save();\n ctx.beginPath();\n if (shape == LiteGraph.BOX_SHAPE) {\n ctx.rect(0, 0, size[0], size[1]);\n } else if (shape == LiteGraph.ROUND_SHAPE) {\n ctx.roundRect(0, 0, size[0], size[1], [10]);\n } else if (shape == LiteGraph.CIRCLE_SHAPE) {\n ctx.arc(\n size[0] * 0.5,\n size[1] * 0.5,\n size[0] * 0.5,\n 0,\n Math.PI * 2\n );\n }\n ctx.clip();\n }\n if (node2.has_errors) {\n bgcolor = \"red\";\n }\n this.drawNodeShape(\n node2,\n ctx,\n size,\n color,\n bgcolor,\n node2.is_selected,\n node2.mouseOver\n );\n ctx.shadowColor = \"transparent\";\n if (node2.onDrawForeground) {\n node2.onDrawForeground(ctx, this, this.canvas);\n }\n ctx.textAlign = horizontal ? \"center\" : \"left\";\n ctx.font = this.inner_text_font;\n var render_text = !low_quality;\n var out_slot = this.connecting_links ? this.connecting_links[0].output : null;\n var in_slot = this.connecting_links ? this.connecting_links[0].input : null;\n ctx.lineWidth = 1;\n var max_y = 0;\n var slot_pos = new Float32Array(2);\n if (!node2.flags.collapsed) {\n if (node2.inputs) {\n for (var i2 = 0; i2 < node2.inputs.length; i2++) {\n var slot = node2.inputs[i2];\n var slot_type = slot.type;\n var slot_shape = slot.shape;\n ctx.globalAlpha = editor_alpha;\n if (out_slot && !LiteGraph.isValidConnection(slot.type, out_slot.type)) {\n ctx.globalAlpha = 0.4 * editor_alpha;\n }\n ctx.fillStyle = slot.link != null ? slot.color_on || this.default_connection_color_byType[slot_type] || this.default_connection_color.input_on : slot.color_off || this.default_connection_color_byTypeOff[slot_type] || this.default_connection_color_byType[slot_type] || this.default_connection_color.input_off;\n var pos2 = node2.getConnectionPos(true, i2, slot_pos);\n pos2[0] -= node2.pos[0];\n pos2[1] -= node2.pos[1];\n if (max_y < pos2[1] + LiteGraph.NODE_SLOT_HEIGHT * 0.5) {\n max_y = pos2[1] + LiteGraph.NODE_SLOT_HEIGHT * 0.5;\n }\n ctx.beginPath();\n if (slot_type == \"array\") {\n slot_shape = LiteGraph.GRID_SHAPE;\n }\n var doStroke = true;\n if (slot.type === LiteGraph.EVENT || slot.shape === LiteGraph.BOX_SHAPE) {\n if (horizontal) {\n ctx.rect(\n pos2[0] - 5 + 0.5,\n pos2[1] - 8 + 0.5,\n 10,\n 14\n );\n } else {\n ctx.rect(\n pos2[0] - 6 + 0.5,\n pos2[1] - 5 + 0.5,\n 14,\n 10\n );\n }\n } else if (slot_shape === LiteGraph.ARROW_SHAPE) {\n ctx.moveTo(pos2[0] + 8, pos2[1] + 0.5);\n ctx.lineTo(pos2[0] - 4, pos2[1] + 6 + 0.5);\n ctx.lineTo(pos2[0] - 4, pos2[1] - 6 + 0.5);\n ctx.closePath();\n } else if (slot_shape === LiteGraph.GRID_SHAPE) {\n ctx.rect(pos2[0] - 4, pos2[1] - 4, 2, 2);\n ctx.rect(pos2[0] - 1, pos2[1] - 4, 2, 2);\n ctx.rect(pos2[0] + 2, pos2[1] - 4, 2, 2);\n ctx.rect(pos2[0] - 4, pos2[1] - 1, 2, 2);\n ctx.rect(pos2[0] - 1, pos2[1] - 1, 2, 2);\n ctx.rect(pos2[0] + 2, pos2[1] - 1, 2, 2);\n ctx.rect(pos2[0] - 4, pos2[1] + 2, 2, 2);\n ctx.rect(pos2[0] - 1, pos2[1] + 2, 2, 2);\n ctx.rect(pos2[0] + 2, pos2[1] + 2, 2, 2);\n doStroke = false;\n } else {\n if (low_quality)\n ctx.rect(pos2[0] - 4, pos2[1] - 4, 8, 8);\n else\n ctx.arc(pos2[0], pos2[1], 4, 0, Math.PI * 2);\n }\n ctx.fill();\n if (render_text) {\n var text = slot.label != null ? slot.label : slot.name;\n if (text) {\n ctx.fillStyle = LiteGraph.NODE_TEXT_COLOR;\n if (horizontal || slot.dir == LiteGraph.UP) {\n ctx.fillText(text, pos2[0], pos2[1] - 10);\n } else {\n ctx.fillText(text, pos2[0] + 10, pos2[1] + 5);\n }\n }\n }\n }\n }\n ctx.textAlign = horizontal ? \"center\" : \"right\";\n ctx.strokeStyle = \"black\";\n if (node2.outputs) {\n for (var i2 = 0; i2 < node2.outputs.length; i2++) {\n var slot = node2.outputs[i2];\n var slot_type = slot.type;\n var slot_shape = slot.shape;\n if (in_slot && !LiteGraph.isValidConnection(slot_type, in_slot.type)) {\n ctx.globalAlpha = 0.4 * editor_alpha;\n }\n var pos2 = node2.getConnectionPos(false, i2, slot_pos);\n pos2[0] -= node2.pos[0];\n pos2[1] -= node2.pos[1];\n if (max_y < pos2[1] + LiteGraph.NODE_SLOT_HEIGHT * 0.5) {\n max_y = pos2[1] + LiteGraph.NODE_SLOT_HEIGHT * 0.5;\n }\n ctx.fillStyle = slot.links && slot.links.length ? slot.color_on || this.default_connection_color_byType[slot_type] || this.default_connection_color.output_on : slot.color_off || this.default_connection_color_byTypeOff[slot_type] || this.default_connection_color_byType[slot_type] || this.default_connection_color.output_off;\n ctx.beginPath();\n if (slot_type == \"array\") {\n slot_shape = LiteGraph.GRID_SHAPE;\n }\n var doStroke = true;\n if (slot_type === LiteGraph.EVENT || slot_shape === LiteGraph.BOX_SHAPE) {\n if (horizontal) {\n ctx.rect(\n pos2[0] - 5 + 0.5,\n pos2[1] - 8 + 0.5,\n 10,\n 14\n );\n } else {\n ctx.rect(\n pos2[0] - 6 + 0.5,\n pos2[1] - 5 + 0.5,\n 14,\n 10\n );\n }\n } else if (slot_shape === LiteGraph.ARROW_SHAPE) {\n ctx.moveTo(pos2[0] + 8, pos2[1] + 0.5);\n ctx.lineTo(pos2[0] - 4, pos2[1] + 6 + 0.5);\n ctx.lineTo(pos2[0] - 4, pos2[1] - 6 + 0.5);\n ctx.closePath();\n } else if (slot_shape === LiteGraph.GRID_SHAPE) {\n ctx.rect(pos2[0] - 4, pos2[1] - 4, 2, 2);\n ctx.rect(pos2[0] - 1, pos2[1] - 4, 2, 2);\n ctx.rect(pos2[0] + 2, pos2[1] - 4, 2, 2);\n ctx.rect(pos2[0] - 4, pos2[1] - 1, 2, 2);\n ctx.rect(pos2[0] - 1, pos2[1] - 1, 2, 2);\n ctx.rect(pos2[0] + 2, pos2[1] - 1, 2, 2);\n ctx.rect(pos2[0] - 4, pos2[1] + 2, 2, 2);\n ctx.rect(pos2[0] - 1, pos2[1] + 2, 2, 2);\n ctx.rect(pos2[0] + 2, pos2[1] + 2, 2, 2);\n doStroke = false;\n } else {\n if (low_quality)\n ctx.rect(pos2[0] - 4, pos2[1] - 4, 8, 8);\n else\n ctx.arc(pos2[0], pos2[1], 4, 0, Math.PI * 2);\n }\n ctx.fill();\n if (!low_quality && doStroke)\n ctx.stroke();\n if (render_text) {\n var text = slot.label != null ? slot.label : slot.name;\n if (text) {\n ctx.fillStyle = LiteGraph.NODE_TEXT_COLOR;\n if (horizontal || slot.dir == LiteGraph.DOWN) {\n ctx.fillText(text, pos2[0], pos2[1] - 8);\n } else {\n ctx.fillText(text, pos2[0] - 10, pos2[1] + 5);\n }\n }\n }\n }\n }\n ctx.textAlign = \"left\";\n ctx.globalAlpha = 1;\n if (node2.widgets) {\n var widgets_y = max_y;\n if (horizontal || node2.widgets_up) {\n widgets_y = 2;\n }\n if (node2.widgets_start_y != null)\n widgets_y = node2.widgets_start_y;\n this.drawNodeWidgets(\n node2,\n widgets_y,\n ctx,\n this.node_widget && this.node_widget[0] == node2 ? this.node_widget[1] : null\n );\n }\n } else if (this.render_collapsed_slots) {\n var input_slot = null;\n var output_slot = null;\n if (node2.inputs) {\n for (var i2 = 0; i2 < node2.inputs.length; i2++) {\n var slot = node2.inputs[i2];\n if (slot.link == null) {\n continue;\n }\n input_slot = slot;\n break;\n }\n }\n if (node2.outputs) {\n for (var i2 = 0; i2 < node2.outputs.length; i2++) {\n var slot = node2.outputs[i2];\n if (!slot.links || !slot.links.length) {\n continue;\n }\n output_slot = slot;\n }\n }\n if (input_slot) {\n var x2 = 0;\n var y2 = LiteGraph.NODE_TITLE_HEIGHT * -0.5;\n if (horizontal) {\n x2 = node2._collapsed_width * 0.5;\n y2 = -LiteGraph.NODE_TITLE_HEIGHT;\n }\n ctx.fillStyle = \"#686\";\n ctx.beginPath();\n if (slot.type === LiteGraph.EVENT || slot.shape === LiteGraph.BOX_SHAPE) {\n ctx.rect(x2 - 7 + 0.5, y2 - 4, 14, 8);\n } else if (slot.shape === LiteGraph.ARROW_SHAPE) {\n ctx.moveTo(x2 + 8, y2);\n ctx.lineTo(x2 + -4, y2 - 4);\n ctx.lineTo(x2 + -4, y2 + 4);\n ctx.closePath();\n } else {\n ctx.arc(x2, y2, 4, 0, Math.PI * 2);\n }\n ctx.fill();\n }\n if (output_slot) {\n var x2 = node2._collapsed_width;\n var y2 = LiteGraph.NODE_TITLE_HEIGHT * -0.5;\n if (horizontal) {\n x2 = node2._collapsed_width * 0.5;\n y2 = 0;\n }\n ctx.fillStyle = \"#686\";\n ctx.strokeStyle = \"black\";\n ctx.beginPath();\n if (slot.type === LiteGraph.EVENT || slot.shape === LiteGraph.BOX_SHAPE) {\n ctx.rect(x2 - 7 + 0.5, y2 - 4, 14, 8);\n } else if (slot.shape === LiteGraph.ARROW_SHAPE) {\n ctx.moveTo(x2 + 6, y2);\n ctx.lineTo(x2 - 6, y2 - 4);\n ctx.lineTo(x2 - 6, y2 + 4);\n ctx.closePath();\n } else {\n ctx.arc(x2, y2, 4, 0, Math.PI * 2);\n }\n ctx.fill();\n }\n }\n if (node2.clip_area) {\n ctx.restore();\n }\n ctx.globalAlpha = 1;\n };\n LGraphCanvas.prototype.drawLinkTooltip = function(ctx, link) {\n var pos2 = link._pos;\n ctx.fillStyle = \"black\";\n ctx.beginPath();\n ctx.arc(pos2[0], pos2[1], 3, 0, Math.PI * 2);\n ctx.fill();\n if (link.data == null)\n return;\n if (this.onDrawLinkTooltip) {\n if (this.onDrawLinkTooltip(ctx, link, this) == true)\n return;\n }\n var data = link.data;\n var text = null;\n if (data.constructor === Number)\n text = data.toFixed(2);\n else if (data.constructor === String)\n text = '\"' + data + '\"';\n else if (data.constructor === Boolean)\n text = String(data);\n else if (data.toToolTip)\n text = data.toToolTip();\n else\n text = \"[\" + data.constructor.name + \"]\";\n if (text == null)\n return;\n text = text.substr(0, 30);\n ctx.font = \"14px Courier New\";\n var info = ctx.measureText(text);\n var w2 = info.width + 20;\n var h = 24;\n ctx.shadowColor = \"black\";\n ctx.shadowOffsetX = 2;\n ctx.shadowOffsetY = 2;\n ctx.shadowBlur = 3;\n ctx.fillStyle = \"#454\";\n ctx.beginPath();\n ctx.roundRect(pos2[0] - w2 * 0.5, pos2[1] - 15 - h, w2, h, [3]);\n ctx.moveTo(pos2[0] - 10, pos2[1] - 15);\n ctx.lineTo(pos2[0] + 10, pos2[1] - 15);\n ctx.lineTo(pos2[0], pos2[1] - 5);\n ctx.fill();\n ctx.shadowColor = \"transparent\";\n ctx.textAlign = \"center\";\n ctx.fillStyle = \"#CEC\";\n ctx.fillText(text, pos2[0], pos2[1] - 15 - h * 0.3);\n };\n var tmp_area = new Float32Array(4);\n LGraphCanvas.prototype.drawNodeShape = function(node2, ctx, size, fgcolor, bgcolor, selected, mouse_over) {\n ctx.strokeStyle = fgcolor;\n ctx.fillStyle = bgcolor;\n var title_height = LiteGraph.NODE_TITLE_HEIGHT;\n var low_quality = this.ds.scale < 0.5;\n var shape = node2._shape || node2.constructor.shape || LiteGraph.ROUND_SHAPE;\n var title_mode = node2.constructor.title_mode;\n var render_title = true;\n if (title_mode == LiteGraph.TRANSPARENT_TITLE || title_mode == LiteGraph.NO_TITLE) {\n render_title = false;\n } else if (title_mode == LiteGraph.AUTOHIDE_TITLE && mouse_over) {\n render_title = true;\n }\n var area = tmp_area;\n area[0] = 0;\n area[1] = render_title ? -title_height : 0;\n area[2] = size[0] + 1;\n area[3] = render_title ? size[1] + title_height : size[1];\n var old_alpha = ctx.globalAlpha;\n {\n ctx.beginPath();\n if (shape == LiteGraph.BOX_SHAPE || low_quality) {\n ctx.fillRect(area[0], area[1], area[2], area[3]);\n } else if (shape == LiteGraph.ROUND_SHAPE || shape == LiteGraph.CARD_SHAPE) {\n ctx.roundRect(\n area[0],\n area[1],\n area[2],\n area[3],\n shape == LiteGraph.CARD_SHAPE ? [this.round_radius, this.round_radius, 0, 0] : [this.round_radius]\n );\n } else if (shape == LiteGraph.CIRCLE_SHAPE) {\n ctx.arc(\n size[0] * 0.5,\n size[1] * 0.5,\n size[0] * 0.5,\n 0,\n Math.PI * 2\n );\n }\n ctx.fill();\n if (!node2.flags.collapsed && render_title) {\n ctx.shadowColor = \"transparent\";\n ctx.fillStyle = \"rgba(0,0,0,0.2)\";\n ctx.fillRect(0, -1, area[2], 2);\n }\n }\n ctx.shadowColor = \"transparent\";\n if (node2.onDrawBackground) {\n node2.onDrawBackground(ctx, this, this.canvas, this.graph_mouse);\n }\n if (render_title || title_mode == LiteGraph.TRANSPARENT_TITLE) {\n if (node2.onDrawTitleBar) {\n node2.onDrawTitleBar(ctx, title_height, size, this.ds.scale, fgcolor);\n } else if (title_mode != LiteGraph.TRANSPARENT_TITLE && (node2.constructor.title_color || this.render_title_colored)) {\n var title_color = node2.constructor.title_color || fgcolor;\n if (node2.flags.collapsed) {\n ctx.shadowColor = LiteGraph.DEFAULT_SHADOW_COLOR;\n }\n if (this.use_gradients) {\n var grad = LGraphCanvas.gradients[title_color];\n if (!grad) {\n grad = LGraphCanvas.gradients[title_color] = ctx.createLinearGradient(0, 0, 400, 0);\n grad.addColorStop(0, title_color);\n grad.addColorStop(1, \"#000\");\n }\n ctx.fillStyle = grad;\n } else {\n ctx.fillStyle = title_color;\n }\n ctx.beginPath();\n if (shape == LiteGraph.BOX_SHAPE || low_quality) {\n ctx.rect(0, -title_height, size[0] + 1, title_height);\n } else if (shape == LiteGraph.ROUND_SHAPE || shape == LiteGraph.CARD_SHAPE) {\n ctx.roundRect(\n 0,\n -title_height,\n size[0] + 1,\n title_height,\n node2.flags.collapsed ? [this.round_radius] : [this.round_radius, this.round_radius, 0, 0]\n );\n }\n ctx.fill();\n ctx.shadowColor = \"transparent\";\n }\n var colState = false;\n if (LiteGraph.node_box_coloured_by_mode) {\n if (LiteGraph.NODE_MODES_COLORS[node2.mode]) {\n colState = LiteGraph.NODE_MODES_COLORS[node2.mode];\n }\n }\n if (LiteGraph.node_box_coloured_when_on) {\n colState = node2.action_triggered ? \"#FFF\" : node2.execute_triggered ? \"#AAA\" : colState;\n }\n var box_size = 10;\n if (node2.onDrawTitleBox) {\n node2.onDrawTitleBox(ctx, title_height, size, this.ds.scale);\n } else if (shape == LiteGraph.ROUND_SHAPE || shape == LiteGraph.CIRCLE_SHAPE || shape == LiteGraph.CARD_SHAPE) {\n if (low_quality) {\n ctx.fillStyle = \"black\";\n ctx.beginPath();\n ctx.arc(\n title_height * 0.5,\n title_height * -0.5,\n box_size * 0.5 + 1,\n 0,\n Math.PI * 2\n );\n ctx.fill();\n }\n ctx.fillStyle = node2.boxcolor || colState || LiteGraph.NODE_DEFAULT_BOXCOLOR;\n if (low_quality)\n ctx.fillRect(title_height * 0.5 - box_size * 0.5, title_height * -0.5 - box_size * 0.5, box_size, box_size);\n else {\n ctx.beginPath();\n ctx.arc(\n title_height * 0.5,\n title_height * -0.5,\n box_size * 0.5,\n 0,\n Math.PI * 2\n );\n ctx.fill();\n }\n } else {\n if (low_quality) {\n ctx.fillStyle = \"black\";\n ctx.fillRect(\n (title_height - box_size) * 0.5 - 1,\n (title_height + box_size) * -0.5 - 1,\n box_size + 2,\n box_size + 2\n );\n }\n ctx.fillStyle = node2.boxcolor || colState || LiteGraph.NODE_DEFAULT_BOXCOLOR;\n ctx.fillRect(\n (title_height - box_size) * 0.5,\n (title_height + box_size) * -0.5,\n box_size,\n box_size\n );\n }\n ctx.globalAlpha = old_alpha;\n if (node2.onDrawTitleText) {\n node2.onDrawTitleText(\n ctx,\n title_height,\n size,\n this.ds.scale,\n this.title_text_font,\n selected\n );\n }\n if (!low_quality) {\n ctx.font = this.title_text_font;\n var title = String(node2.getTitle());\n if (title) {\n if (selected) {\n ctx.fillStyle = LiteGraph.NODE_SELECTED_TITLE_COLOR;\n } else {\n ctx.fillStyle = node2.constructor.title_text_color || this.node_title_color;\n }\n if (node2.flags.collapsed) {\n ctx.textAlign = \"left\";\n ctx.measureText(title);\n ctx.fillText(\n title.substr(0, 20),\n //avoid urls too long\n title_height,\n // + measure.width * 0.5,\n LiteGraph.NODE_TITLE_TEXT_Y - title_height\n );\n ctx.textAlign = \"left\";\n } else {\n ctx.textAlign = \"left\";\n ctx.fillText(\n title,\n title_height,\n LiteGraph.NODE_TITLE_TEXT_Y - title_height\n );\n }\n }\n }\n if (!node2.flags.collapsed && node2.subgraph && !node2.skip_subgraph_button) {\n var w2 = LiteGraph.NODE_TITLE_HEIGHT;\n var x2 = node2.size[0] - w2;\n var over = LiteGraph.isInsideRectangle(this.graph_mouse[0] - node2.pos[0], this.graph_mouse[1] - node2.pos[1], x2 + 2, -w2 + 2, w2 - 4, w2 - 4);\n ctx.fillStyle = over ? \"#888\" : \"#555\";\n if (shape == LiteGraph.BOX_SHAPE || low_quality)\n ctx.fillRect(x2 + 2, -w2 + 2, w2 - 4, w2 - 4);\n else {\n ctx.beginPath();\n ctx.roundRect(x2 + 2, -w2 + 2, w2 - 4, w2 - 4, [4]);\n ctx.fill();\n }\n ctx.fillStyle = \"#333\";\n ctx.beginPath();\n ctx.moveTo(x2 + w2 * 0.2, -w2 * 0.6);\n ctx.lineTo(x2 + w2 * 0.8, -w2 * 0.6);\n ctx.lineTo(x2 + w2 * 0.5, -w2 * 0.3);\n ctx.fill();\n }\n if (node2.onDrawTitle) {\n node2.onDrawTitle(ctx);\n }\n }\n if (selected) {\n if (node2.onBounding) {\n node2.onBounding(area);\n }\n if (title_mode == LiteGraph.TRANSPARENT_TITLE) {\n area[1] -= title_height;\n area[3] += title_height;\n }\n ctx.lineWidth = 1;\n ctx.globalAlpha = 0.8;\n ctx.beginPath();\n if (shape == LiteGraph.BOX_SHAPE) {\n ctx.rect(\n -6 + area[0],\n -6 + area[1],\n 12 + area[2],\n 12 + area[3]\n );\n } else if (shape == LiteGraph.ROUND_SHAPE || shape == LiteGraph.CARD_SHAPE && node2.flags.collapsed) {\n ctx.roundRect(\n -6 + area[0],\n -6 + area[1],\n 12 + area[2],\n 12 + area[3],\n [this.round_radius * 2]\n );\n } else if (shape == LiteGraph.CARD_SHAPE) {\n ctx.roundRect(\n -6 + area[0],\n -6 + area[1],\n 12 + area[2],\n 12 + area[3],\n [this.round_radius * 2, 2, this.round_radius * 2, 2]\n );\n } else if (shape == LiteGraph.CIRCLE_SHAPE) {\n ctx.arc(\n size[0] * 0.5,\n size[1] * 0.5,\n size[0] * 0.5 + 6,\n 0,\n Math.PI * 2\n );\n }\n ctx.strokeStyle = LiteGraph.NODE_BOX_OUTLINE_COLOR;\n ctx.stroke();\n ctx.strokeStyle = fgcolor;\n ctx.globalAlpha = 1;\n }\n if (node2.execute_triggered > 0) node2.execute_triggered--;\n if (node2.action_triggered > 0) node2.action_triggered--;\n };\n var margin_area = new Float32Array(4);\n var link_bounding = new Float32Array(4);\n var tempA = new Float32Array(2);\n var tempB = new Float32Array(2);\n LGraphCanvas.prototype.drawConnections = function(ctx) {\n var now = LiteGraph.getTime();\n var visible_area = this.visible_area;\n margin_area[0] = visible_area[0] - 20;\n margin_area[1] = visible_area[1] - 20;\n margin_area[2] = visible_area[2] + 40;\n margin_area[3] = visible_area[3] + 40;\n ctx.lineWidth = this.connections_width;\n ctx.fillStyle = \"#AAA\";\n ctx.strokeStyle = \"#AAA\";\n ctx.globalAlpha = this.editor_alpha;\n var nodes = this.graph._nodes;\n for (var n = 0, l = nodes.length; n < l; ++n) {\n var node2 = nodes[n];\n if (!node2.inputs || !node2.inputs.length) {\n continue;\n }\n for (var i2 = 0; i2 < node2.inputs.length; ++i2) {\n var input = node2.inputs[i2];\n if (!input || input.link == null) {\n continue;\n }\n var link_id = input.link;\n var link = this.graph.links[link_id];\n if (!link) {\n continue;\n }\n var start_node = this.graph.getNodeById(link.origin_id);\n if (start_node == null) {\n continue;\n }\n var start_node_slot = link.origin_slot;\n var start_node_slotpos = null;\n if (start_node_slot == -1) {\n start_node_slotpos = [\n start_node.pos[0] + 10,\n start_node.pos[1] + 10\n ];\n } else {\n start_node_slotpos = start_node.getConnectionPos(\n false,\n start_node_slot,\n tempA\n );\n }\n var end_node_slotpos = node2.getConnectionPos(true, i2, tempB);\n link_bounding[0] = start_node_slotpos[0];\n link_bounding[1] = start_node_slotpos[1];\n link_bounding[2] = end_node_slotpos[0] - start_node_slotpos[0];\n link_bounding[3] = end_node_slotpos[1] - start_node_slotpos[1];\n if (link_bounding[2] < 0) {\n link_bounding[0] += link_bounding[2];\n link_bounding[2] = Math.abs(link_bounding[2]);\n }\n if (link_bounding[3] < 0) {\n link_bounding[1] += link_bounding[3];\n link_bounding[3] = Math.abs(link_bounding[3]);\n }\n if (!overlapBounding(link_bounding, margin_area)) {\n continue;\n }\n var start_slot = start_node.outputs[start_node_slot];\n var end_slot = node2.inputs[i2];\n if (!start_slot || !end_slot) {\n continue;\n }\n var start_dir = start_slot.dir || (start_node.horizontal ? LiteGraph.DOWN : LiteGraph.RIGHT);\n var end_dir = end_slot.dir || (node2.horizontal ? LiteGraph.UP : LiteGraph.LEFT);\n this.renderLink(\n ctx,\n start_node_slotpos,\n end_node_slotpos,\n link,\n false,\n 0,\n null,\n start_dir,\n end_dir\n );\n if (link && link._last_time && now - link._last_time < 1e3) {\n var f = 2 - (now - link._last_time) * 2e-3;\n var tmp = ctx.globalAlpha;\n ctx.globalAlpha = tmp * f;\n this.renderLink(\n ctx,\n start_node_slotpos,\n end_node_slotpos,\n link,\n true,\n f,\n \"white\",\n start_dir,\n end_dir\n );\n ctx.globalAlpha = tmp;\n }\n }\n }\n ctx.globalAlpha = 1;\n };\n LGraphCanvas.prototype.renderLink = function(ctx, a, b, link, skip_border, flow, color, start_dir, end_dir, num_sublines) {\n if (link) {\n this.visible_links.push(link);\n }\n if (!color && link) {\n color = link.color || LGraphCanvas.link_type_colors[link.type];\n }\n if (!color) {\n color = this.default_link_color;\n }\n if (link != null && this.highlighted_links[link.id]) {\n color = \"#FFF\";\n }\n start_dir = start_dir || LiteGraph.RIGHT;\n end_dir = end_dir || LiteGraph.LEFT;\n var dist = distance(a, b);\n if (this.render_connections_border && this.ds.scale > 0.6) {\n ctx.lineWidth = this.connections_width + 4;\n }\n ctx.lineJoin = \"round\";\n num_sublines = num_sublines || 1;\n if (num_sublines > 1) {\n ctx.lineWidth = 0.5;\n }\n ctx.beginPath();\n for (var i2 = 0; i2 < num_sublines; i2 += 1) {\n var offsety = (i2 - (num_sublines - 1) * 0.5) * 5;\n if (this.links_render_mode == LiteGraph.SPLINE_LINK) {\n ctx.moveTo(a[0], a[1] + offsety);\n var start_offset_x = 0;\n var start_offset_y = 0;\n var end_offset_x = 0;\n var end_offset_y = 0;\n switch (start_dir) {\n case LiteGraph.LEFT:\n start_offset_x = dist * -0.25;\n break;\n case LiteGraph.RIGHT:\n start_offset_x = dist * 0.25;\n break;\n case LiteGraph.UP:\n start_offset_y = dist * -0.25;\n break;\n case LiteGraph.DOWN:\n start_offset_y = dist * 0.25;\n break;\n }\n switch (end_dir) {\n case LiteGraph.LEFT:\n end_offset_x = dist * -0.25;\n break;\n case LiteGraph.RIGHT:\n end_offset_x = dist * 0.25;\n break;\n case LiteGraph.UP:\n end_offset_y = dist * -0.25;\n break;\n case LiteGraph.DOWN:\n end_offset_y = dist * 0.25;\n break;\n }\n ctx.bezierCurveTo(\n a[0] + start_offset_x,\n a[1] + start_offset_y + offsety,\n b[0] + end_offset_x,\n b[1] + end_offset_y + offsety,\n b[0],\n b[1] + offsety\n );\n } else if (this.links_render_mode == LiteGraph.LINEAR_LINK) {\n ctx.moveTo(a[0], a[1] + offsety);\n var start_offset_x = 0;\n var start_offset_y = 0;\n var end_offset_x = 0;\n var end_offset_y = 0;\n switch (start_dir) {\n case LiteGraph.LEFT:\n start_offset_x = -1;\n break;\n case LiteGraph.RIGHT:\n start_offset_x = 1;\n break;\n case LiteGraph.UP:\n start_offset_y = -1;\n break;\n case LiteGraph.DOWN:\n start_offset_y = 1;\n break;\n }\n switch (end_dir) {\n case LiteGraph.LEFT:\n end_offset_x = -1;\n break;\n case LiteGraph.RIGHT:\n end_offset_x = 1;\n break;\n case LiteGraph.UP:\n end_offset_y = -1;\n break;\n case LiteGraph.DOWN:\n end_offset_y = 1;\n break;\n }\n var l = 15;\n ctx.lineTo(\n a[0] + start_offset_x * l,\n a[1] + start_offset_y * l + offsety\n );\n ctx.lineTo(\n b[0] + end_offset_x * l,\n b[1] + end_offset_y * l + offsety\n );\n ctx.lineTo(b[0], b[1] + offsety);\n } else if (this.links_render_mode == LiteGraph.STRAIGHT_LINK) {\n ctx.moveTo(a[0], a[1]);\n var start_x = a[0];\n var start_y = a[1];\n var end_x = b[0];\n var end_y = b[1];\n if (start_dir == LiteGraph.RIGHT) {\n start_x += 10;\n } else {\n start_y += 10;\n }\n if (end_dir == LiteGraph.LEFT) {\n end_x -= 10;\n } else {\n end_y -= 10;\n }\n ctx.lineTo(start_x, start_y);\n ctx.lineTo((start_x + end_x) * 0.5, start_y);\n ctx.lineTo((start_x + end_x) * 0.5, end_y);\n ctx.lineTo(end_x, end_y);\n ctx.lineTo(b[0], b[1]);\n } else {\n return;\n }\n }\n if (this.render_connections_border && this.ds.scale > 0.6 && !skip_border) {\n ctx.strokeStyle = \"rgba(0,0,0,0.5)\";\n ctx.stroke();\n }\n ctx.lineWidth = this.connections_width;\n ctx.fillStyle = ctx.strokeStyle = color;\n ctx.stroke();\n var pos2 = this.computeConnectionPoint(a, b, 0.5, start_dir, end_dir);\n if (link && link._pos) {\n link._pos[0] = pos2[0];\n link._pos[1] = pos2[1];\n }\n if (this.ds.scale >= 0.6 && this.highquality_render && end_dir != LiteGraph.CENTER) {\n if (this.render_connection_arrows) {\n var posA = this.computeConnectionPoint(\n a,\n b,\n 0.25,\n start_dir,\n end_dir\n );\n var posB = this.computeConnectionPoint(\n a,\n b,\n 0.26,\n start_dir,\n end_dir\n );\n var posC = this.computeConnectionPoint(\n a,\n b,\n 0.75,\n start_dir,\n end_dir\n );\n var posD = this.computeConnectionPoint(\n a,\n b,\n 0.76,\n start_dir,\n end_dir\n );\n var angleA = 0;\n var angleB = 0;\n if (this.render_curved_connections) {\n angleA = -Math.atan2(posB[0] - posA[0], posB[1] - posA[1]);\n angleB = -Math.atan2(posD[0] - posC[0], posD[1] - posC[1]);\n } else {\n angleB = angleA = b[1] > a[1] ? 0 : Math.PI;\n }\n ctx.save();\n ctx.translate(posA[0], posA[1]);\n ctx.rotate(angleA);\n ctx.beginPath();\n ctx.moveTo(-5, -3);\n ctx.lineTo(0, 7);\n ctx.lineTo(5, -3);\n ctx.fill();\n ctx.restore();\n ctx.save();\n ctx.translate(posC[0], posC[1]);\n ctx.rotate(angleB);\n ctx.beginPath();\n ctx.moveTo(-5, -3);\n ctx.lineTo(0, 7);\n ctx.lineTo(5, -3);\n ctx.fill();\n ctx.restore();\n }\n ctx.beginPath();\n ctx.arc(pos2[0], pos2[1], 5, 0, Math.PI * 2);\n ctx.fill();\n }\n if (flow) {\n ctx.fillStyle = color;\n for (var i2 = 0; i2 < 5; ++i2) {\n var f = (LiteGraph.getTime() * 1e-3 + i2 * 0.2) % 1;\n var pos2 = this.computeConnectionPoint(\n a,\n b,\n f,\n start_dir,\n end_dir\n );\n ctx.beginPath();\n ctx.arc(pos2[0], pos2[1], 5, 0, 2 * Math.PI);\n ctx.fill();\n }\n }\n };\n LGraphCanvas.prototype.computeConnectionPoint = function(a, b, t, start_dir, end_dir) {\n start_dir = start_dir || LiteGraph.RIGHT;\n end_dir = end_dir || LiteGraph.LEFT;\n var dist = distance(a, b);\n var p0 = a;\n var p1 = [a[0], a[1]];\n var p2 = [b[0], b[1]];\n var p3 = b;\n switch (start_dir) {\n case LiteGraph.LEFT:\n p1[0] += dist * -0.25;\n break;\n case LiteGraph.RIGHT:\n p1[0] += dist * 0.25;\n break;\n case LiteGraph.UP:\n p1[1] += dist * -0.25;\n break;\n case LiteGraph.DOWN:\n p1[1] += dist * 0.25;\n break;\n }\n switch (end_dir) {\n case LiteGraph.LEFT:\n p2[0] += dist * -0.25;\n break;\n case LiteGraph.RIGHT:\n p2[0] += dist * 0.25;\n break;\n case LiteGraph.UP:\n p2[1] += dist * -0.25;\n break;\n case LiteGraph.DOWN:\n p2[1] += dist * 0.25;\n break;\n }\n var c1 = (1 - t) * (1 - t) * (1 - t);\n var c2 = 3 * ((1 - t) * (1 - t)) * t;\n var c3 = 3 * (1 - t) * (t * t);\n var c4 = t * t * t;\n var x2 = c1 * p0[0] + c2 * p1[0] + c3 * p2[0] + c4 * p3[0];\n var y2 = c1 * p0[1] + c2 * p1[1] + c3 * p2[1] + c4 * p3[1];\n return [x2, y2];\n };\n LGraphCanvas.prototype.drawExecutionOrder = function(ctx) {\n ctx.shadowColor = \"transparent\";\n ctx.globalAlpha = 0.25;\n ctx.textAlign = \"center\";\n ctx.strokeStyle = \"white\";\n ctx.globalAlpha = 0.75;\n var visible_nodes = this.visible_nodes;\n for (var i2 = 0; i2 < visible_nodes.length; ++i2) {\n var node2 = visible_nodes[i2];\n ctx.fillStyle = \"black\";\n ctx.fillRect(\n node2.pos[0] - LiteGraph.NODE_TITLE_HEIGHT,\n node2.pos[1] - LiteGraph.NODE_TITLE_HEIGHT,\n LiteGraph.NODE_TITLE_HEIGHT,\n LiteGraph.NODE_TITLE_HEIGHT\n );\n if (node2.order == 0) {\n ctx.strokeRect(\n node2.pos[0] - LiteGraph.NODE_TITLE_HEIGHT + 0.5,\n node2.pos[1] - LiteGraph.NODE_TITLE_HEIGHT + 0.5,\n LiteGraph.NODE_TITLE_HEIGHT,\n LiteGraph.NODE_TITLE_HEIGHT\n );\n }\n ctx.fillStyle = \"#FFF\";\n ctx.fillText(\n node2.order,\n node2.pos[0] + LiteGraph.NODE_TITLE_HEIGHT * -0.5,\n node2.pos[1] - 6\n );\n }\n ctx.globalAlpha = 1;\n };\n LGraphCanvas.prototype.drawNodeWidgets = function(node2, posY, ctx, active_widget2) {\n if (!node2.widgets || !node2.widgets.length) {\n return 0;\n }\n var width2 = node2.size[0];\n var widgets = node2.widgets;\n posY += 2;\n var H = LiteGraph.NODE_WIDGET_HEIGHT;\n var show_text = this.ds.scale > 0.5;\n ctx.save();\n ctx.globalAlpha = this.editor_alpha;\n var outline_color = LiteGraph.WIDGET_OUTLINE_COLOR;\n var background_color = LiteGraph.WIDGET_BGCOLOR;\n var text_color = LiteGraph.WIDGET_TEXT_COLOR;\n var secondary_text_color = LiteGraph.WIDGET_SECONDARY_TEXT_COLOR;\n var margin = 15;\n for (var i2 = 0; i2 < widgets.length; ++i2) {\n var w2 = widgets[i2];\n var y2 = posY;\n if (w2.y) {\n y2 = w2.y;\n }\n w2.last_y = y2;\n ctx.strokeStyle = outline_color;\n ctx.fillStyle = \"#222\";\n ctx.textAlign = \"left\";\n if (w2.disabled)\n ctx.globalAlpha *= 0.5;\n var widget_width2 = w2.width || width2;\n switch (w2.type) {\n case \"button\":\n ctx.fillStyle = background_color;\n if (w2.clicked) {\n ctx.fillStyle = \"#AAA\";\n w2.clicked = false;\n this.dirty_canvas = true;\n }\n ctx.fillRect(margin, y2, widget_width2 - margin * 2, H);\n if (show_text && !w2.disabled)\n ctx.strokeRect(margin, y2, widget_width2 - margin * 2, H);\n if (show_text) {\n ctx.textAlign = \"center\";\n ctx.fillStyle = text_color;\n ctx.fillText(w2.label || w2.name, widget_width2 * 0.5, y2 + H * 0.7);\n }\n break;\n case \"toggle\":\n ctx.textAlign = \"left\";\n ctx.strokeStyle = outline_color;\n ctx.fillStyle = background_color;\n ctx.beginPath();\n if (show_text)\n ctx.roundRect(margin, y2, widget_width2 - margin * 2, H, [H * 0.5]);\n else\n ctx.rect(margin, y2, widget_width2 - margin * 2, H);\n ctx.fill();\n if (show_text && !w2.disabled)\n ctx.stroke();\n ctx.fillStyle = w2.value ? \"#89A\" : \"#333\";\n ctx.beginPath();\n ctx.arc(widget_width2 - margin * 2, y2 + H * 0.5, H * 0.36, 0, Math.PI * 2);\n ctx.fill();\n if (show_text) {\n ctx.fillStyle = secondary_text_color;\n const label = w2.label || w2.name;\n if (label != null) {\n ctx.fillText(label, margin * 2, y2 + H * 0.7);\n }\n ctx.fillStyle = w2.value ? text_color : secondary_text_color;\n ctx.textAlign = \"right\";\n ctx.fillText(\n w2.value ? w2.options.on || \"true\" : w2.options.off || \"false\",\n widget_width2 - 40,\n y2 + H * 0.7\n );\n }\n break;\n case \"slider\":\n ctx.fillStyle = background_color;\n ctx.fillRect(margin, y2, widget_width2 - margin * 2, H);\n var range = w2.options.max - w2.options.min;\n var nvalue2 = (w2.value - w2.options.min) / range;\n if (nvalue2 < 0) nvalue2 = 0;\n if (nvalue2 > 1) nvalue2 = 1;\n ctx.fillStyle = w2.options.hasOwnProperty(\"slider_color\") ? w2.options.slider_color : active_widget2 == w2 ? \"#89A\" : \"#678\";\n ctx.fillRect(margin, y2, nvalue2 * (widget_width2 - margin * 2), H);\n if (show_text && !w2.disabled)\n ctx.strokeRect(margin, y2, widget_width2 - margin * 2, H);\n if (w2.marker) {\n var marker_nvalue = (w2.marker - w2.options.min) / range;\n if (marker_nvalue < 0) marker_nvalue = 0;\n if (marker_nvalue > 1) marker_nvalue = 1;\n ctx.fillStyle = w2.options.hasOwnProperty(\"marker_color\") ? w2.options.marker_color : \"#AA9\";\n ctx.fillRect(margin + marker_nvalue * (widget_width2 - margin * 2), y2, 2, H);\n }\n if (show_text) {\n ctx.textAlign = \"center\";\n ctx.fillStyle = text_color;\n ctx.fillText(\n w2.label || w2.name + \" \" + Number(w2.value).toFixed(\n w2.options.precision != null ? w2.options.precision : 3\n ),\n widget_width2 * 0.5,\n y2 + H * 0.7\n );\n }\n break;\n case \"number\":\n case \"combo\":\n ctx.textAlign = \"left\";\n ctx.strokeStyle = outline_color;\n ctx.fillStyle = background_color;\n ctx.beginPath();\n if (show_text)\n ctx.roundRect(margin, y2, widget_width2 - margin * 2, H, [H * 0.5]);\n else\n ctx.rect(margin, y2, widget_width2 - margin * 2, H);\n ctx.fill();\n if (show_text) {\n if (!w2.disabled)\n ctx.stroke();\n ctx.fillStyle = text_color;\n if (!w2.disabled) {\n ctx.beginPath();\n ctx.moveTo(margin + 16, y2 + 5);\n ctx.lineTo(margin + 6, y2 + H * 0.5);\n ctx.lineTo(margin + 16, y2 + H - 5);\n ctx.fill();\n ctx.beginPath();\n ctx.moveTo(widget_width2 - margin - 16, y2 + 5);\n ctx.lineTo(widget_width2 - margin - 6, y2 + H * 0.5);\n ctx.lineTo(widget_width2 - margin - 16, y2 + H - 5);\n ctx.fill();\n }\n ctx.fillStyle = secondary_text_color;\n ctx.fillText(w2.label || w2.name, margin * 2 + 5, y2 + H * 0.7);\n ctx.fillStyle = text_color;\n ctx.textAlign = \"right\";\n if (w2.type == \"number\") {\n ctx.fillText(\n Number(w2.value).toFixed(\n w2.options.precision !== void 0 ? w2.options.precision : 3\n ),\n widget_width2 - margin * 2 - 20,\n y2 + H * 0.7\n );\n } else {\n var v2 = w2.value;\n if (w2.options.values) {\n var values2 = w2.options.values;\n if (values2.constructor === Function)\n values2 = values2();\n if (values2 && values2.constructor !== Array)\n v2 = values2[w2.value];\n }\n const labelWidth = ctx.measureText(w2.label || w2.name).width + margin * 2;\n const inputWidth = widget_width2 - margin * 4;\n const availableWidth = inputWidth - labelWidth;\n const textWidth = ctx.measureText(v2).width;\n if (textWidth > availableWidth) {\n const ELLIPSIS = \"…\";\n const ellipsisWidth = ctx.measureText(ELLIPSIS).width;\n const charWidthAvg = ctx.measureText(\"a\").width;\n if (availableWidth <= ellipsisWidth) {\n v2 = \"․\";\n } else {\n const overflowWidth = textWidth + ellipsisWidth - availableWidth;\n if (overflowWidth + charWidthAvg * 3 > availableWidth) {\n const preciseRange = availableWidth + charWidthAvg * 3;\n const preTruncateCt = Math.floor((preciseRange - ellipsisWidth) / charWidthAvg);\n v2 = v2.substr(0, preTruncateCt);\n }\n while (ctx.measureText(v2).width + ellipsisWidth > availableWidth) {\n v2 = v2.substr(0, v2.length - 1);\n }\n v2 += ELLIPSIS;\n }\n }\n ctx.fillText(\n v2,\n widget_width2 - margin * 2 - 20,\n y2 + H * 0.7\n );\n }\n }\n break;\n case \"string\":\n case \"text\":\n ctx.textAlign = \"left\";\n ctx.strokeStyle = outline_color;\n ctx.fillStyle = background_color;\n ctx.beginPath();\n if (show_text)\n ctx.roundRect(margin, y2, widget_width2 - margin * 2, H, [H * 0.5]);\n else\n ctx.rect(margin, y2, widget_width2 - margin * 2, H);\n ctx.fill();\n if (show_text) {\n if (!w2.disabled)\n ctx.stroke();\n ctx.save();\n ctx.beginPath();\n ctx.rect(margin, y2, widget_width2 - margin * 2, H);\n ctx.clip();\n ctx.fillStyle = secondary_text_color;\n const label = w2.label || w2.name;\n if (label != null) {\n ctx.fillText(label, margin * 2, y2 + H * 0.7);\n }\n ctx.fillStyle = text_color;\n ctx.textAlign = \"right\";\n ctx.fillText(String(w2.value).substr(0, 30), widget_width2 - margin * 2, y2 + H * 0.7);\n ctx.restore();\n }\n break;\n default:\n if (w2.draw) {\n w2.draw(ctx, node2, widget_width2, y2, H);\n }\n break;\n }\n posY += (w2.computeSize ? w2.computeSize(widget_width2)[1] : H) + 4;\n ctx.globalAlpha = this.editor_alpha;\n }\n ctx.restore();\n ctx.textAlign = \"left\";\n };\n LGraphCanvas.prototype.processNodeWidgets = function(node, pos, event, active_widget) {\n if (!node.widgets || !node.widgets.length || !this.allow_interaction && !node.flags.allow_interaction) {\n return null;\n }\n var x = pos[0] - node.pos[0];\n var y = pos[1] - node.pos[1];\n var width = node.size[0];\n var that = this;\n var ref_window = this.getCanvasWindow();\n for (var i = 0; i < node.widgets.length; ++i) {\n var w = node.widgets[i];\n if (!w || w.disabled)\n continue;\n var widget_height = w.computeSize ? w.computeSize(width)[1] : LiteGraph.NODE_WIDGET_HEIGHT;\n var widget_width = w.width || width;\n if (w != active_widget && (x < 6 || x > widget_width - 12 || y < w.last_y || y > w.last_y + widget_height || w.last_y === void 0))\n continue;\n var old_value = w.value;\n switch (w.type) {\n case \"button\":\n if (event.type === LiteGraph.pointerevents_method + \"down\") {\n if (w.callback) {\n setTimeout(function() {\n w.callback(w, that, node, pos, event);\n }, 20);\n }\n w.clicked = true;\n this.dirty_canvas = true;\n }\n break;\n case \"slider\":\n var old_value = w.value;\n var nvalue = clamp((x - 15) / (widget_width - 30), 0, 1);\n if (w.options.read_only) break;\n w.value = w.options.min + (w.options.max - w.options.min) * nvalue;\n if (old_value != w.value) {\n setTimeout(function() {\n inner_value_change(w, w.value);\n }, 20);\n }\n this.dirty_canvas = true;\n break;\n case \"number\":\n case \"combo\":\n var old_value = w.value;\n var delta = x < 40 ? -1 : x > widget_width - 40 ? 1 : 0;\n var allow_scroll = true;\n if (delta) {\n if (x > -3 && x < widget_width + 3) {\n allow_scroll = false;\n }\n }\n if (allow_scroll && event.type == LiteGraph.pointerevents_method + \"move\" && w.type == \"number\") {\n if (event.deltaX)\n w.value += event.deltaX * 0.1 * (w.options.step || 1);\n if (w.options.min != null && w.value < w.options.min) {\n w.value = w.options.min;\n }\n if (w.options.max != null && w.value > w.options.max) {\n w.value = w.options.max;\n }\n } else if (event.type == LiteGraph.pointerevents_method + \"down\") {\n var values = w.options.values;\n if (values && values.constructor === Function) {\n values = w.options.values(w, node);\n }\n var values_list = null;\n if (w.type != \"number\")\n values_list = values.constructor === Array ? values : Object.keys(values);\n var delta = x < 40 ? -1 : x > widget_width - 40 ? 1 : 0;\n if (w.type == \"number\") {\n w.value += delta * 0.1 * (w.options.step || 1);\n if (w.options.min != null && w.value < w.options.min) {\n w.value = w.options.min;\n }\n if (w.options.max != null && w.value > w.options.max) {\n w.value = w.options.max;\n }\n } else if (delta) {\n var index = -1;\n this.last_mouseclick = 0;\n if (values.constructor === Object)\n index = values_list.indexOf(String(w.value)) + delta;\n else\n index = values_list.indexOf(w.value) + delta;\n if (index >= values_list.length) {\n index = values_list.length - 1;\n }\n if (index < 0) {\n index = 0;\n }\n if (values.constructor === Array)\n w.value = values[index];\n else\n w.value = index;\n } else {\n let inner_clicked = function(v2, option, event2) {\n if (values != values_list)\n v2 = text_values.indexOf(v2);\n this.value = v2;\n inner_value_change(this, v2);\n that.dirty_canvas = true;\n return false;\n };\n var text_values = values != values_list ? Object.values(values) : values;\n new LiteGraph.ContextMenu(\n text_values,\n {\n scale: Math.max(1, this.ds.scale),\n event,\n className: \"dark\",\n callback: inner_clicked.bind(w)\n },\n ref_window\n );\n }\n } else if (event.type == LiteGraph.pointerevents_method + \"up\" && w.type == \"number\") {\n var delta = x < 40 ? -1 : x > widget_width - 40 ? 1 : 0;\n if (event.click_time < 200 && delta == 0) {\n this.prompt(\n \"Value\",\n w.value,\n (function(v) {\n if (/^[0-9+\\-*/()\\s]+|\\d+\\.\\d+$/.test(v)) {\n try {\n v = eval(v);\n } catch (e) {\n }\n }\n this.value = Number(v);\n inner_value_change(this, this.value);\n }).bind(w),\n event\n );\n }\n }\n if (old_value != w.value)\n setTimeout(\n (function() {\n inner_value_change(this, this.value);\n }).bind(w),\n 20\n );\n this.dirty_canvas = true;\n break;\n case \"toggle\":\n if (event.type == LiteGraph.pointerevents_method + \"down\") {\n w.value = !w.value;\n setTimeout(function() {\n inner_value_change(w, w.value);\n }, 20);\n }\n break;\n case \"string\":\n case \"text\":\n if (event.type == LiteGraph.pointerevents_method + \"down\") {\n this.prompt(\n \"Value\",\n w.value,\n (function(v2) {\n inner_value_change(this, v2);\n }).bind(w),\n event,\n w.options ? w.options.multiline : false\n );\n }\n break;\n default:\n if (w.mouse) {\n this.dirty_canvas = w.mouse(event, [x, y], node);\n }\n break;\n }\n if (old_value != w.value) {\n if (node.onWidgetChanged)\n node.onWidgetChanged(w.name, w.value, old_value, w);\n node.graph._version++;\n }\n return w;\n }\n function inner_value_change(widget, value) {\n if (widget.type == \"number\") {\n value = Number(value);\n }\n widget.value = value;\n if (widget.options && widget.options.property && node.properties[widget.options.property] !== void 0) {\n node.setProperty(widget.options.property, value);\n }\n if (widget.callback) {\n widget.callback(widget.value, that, node, pos, event);\n }\n }\n return null;\n };\n LGraphCanvas.prototype.drawGroups = function(canvas, ctx) {\n if (!this.graph) {\n return;\n }\n var groups = this.graph._groups;\n ctx.save();\n ctx.globalAlpha = 0.5 * this.editor_alpha;\n for (var i2 = 0; i2 < groups.length; ++i2) {\n var group = groups[i2];\n if (!overlapBounding(this.visible_area, group._bounding)) {\n continue;\n }\n ctx.fillStyle = group.color || \"#335\";\n ctx.strokeStyle = group.color || \"#335\";\n var pos2 = group._pos;\n var size = group._size;\n ctx.globalAlpha = 0.25 * this.editor_alpha;\n ctx.beginPath();\n ctx.rect(pos2[0] + 0.5, pos2[1] + 0.5, size[0], size[1]);\n ctx.fill();\n ctx.globalAlpha = this.editor_alpha;\n ctx.stroke();\n ctx.beginPath();\n ctx.moveTo(pos2[0] + size[0], pos2[1] + size[1]);\n ctx.lineTo(pos2[0] + size[0] - 10, pos2[1] + size[1]);\n ctx.lineTo(pos2[0] + size[0], pos2[1] + size[1] - 10);\n ctx.fill();\n var font_size = group.font_size || LiteGraph.DEFAULT_GROUP_FONT_SIZE;\n ctx.font = font_size + \"px Arial\";\n ctx.textAlign = \"left\";\n ctx.fillText(group.title, pos2[0] + 4, pos2[1] + font_size);\n }\n ctx.restore();\n };\n LGraphCanvas.prototype.adjustNodesSize = function() {\n var nodes = this.graph._nodes;\n for (var i2 = 0; i2 < nodes.length; ++i2) {\n nodes[i2].size = nodes[i2].computeSize();\n }\n this.setDirty(true, true);\n };\n LGraphCanvas.prototype.resize = function(width2, height) {\n if (!width2 && !height) {\n var parent = this.canvas.parentNode;\n width2 = parent.offsetWidth;\n height = parent.offsetHeight;\n }\n if (this.canvas.width == width2 && this.canvas.height == height) {\n return;\n }\n this.canvas.width = width2;\n this.canvas.height = height;\n this.bgcanvas.width = this.canvas.width;\n this.bgcanvas.height = this.canvas.height;\n this.setDirty(true, true);\n };\n LGraphCanvas.prototype.switchLiveMode = function(transition) {\n if (!transition) {\n this.live_mode = !this.live_mode;\n this.dirty_canvas = true;\n this.dirty_bgcanvas = true;\n return;\n }\n var self = this;\n var delta2 = this.live_mode ? 1.1 : 0.9;\n if (this.live_mode) {\n this.live_mode = false;\n this.editor_alpha = 0.1;\n }\n var t = setInterval(function() {\n self.editor_alpha *= delta2;\n self.dirty_canvas = true;\n self.dirty_bgcanvas = true;\n if (delta2 < 1 && self.editor_alpha < 0.01) {\n clearInterval(t);\n if (delta2 < 1) {\n self.live_mode = true;\n }\n }\n if (delta2 > 1 && self.editor_alpha > 0.99) {\n clearInterval(t);\n self.editor_alpha = 1;\n }\n }, 1);\n };\n LGraphCanvas.prototype.onNodeSelectionChange = function(node2) {\n return;\n };\n LGraphCanvas.onGroupAdd = function(info, entry, mouse_event) {\n var canvas = LGraphCanvas.active_canvas;\n canvas.getCanvasWindow();\n var group = new LiteGraph.LGraphGroup();\n group.pos = canvas.convertEventToCanvasOffset(mouse_event);\n canvas.graph.add(group);\n };\n LGraphCanvas.getBoundaryNodes = function(nodes) {\n let top = null;\n let right = null;\n let bottom = null;\n let left = null;\n for (const nID in nodes) {\n const node2 = nodes[nID];\n const [x2, y2] = node2.pos;\n const [width2, height] = node2.size;\n if (top === null || y2 < top.pos[1]) {\n top = node2;\n }\n if (right === null || x2 + width2 > right.pos[0] + right.size[0]) {\n right = node2;\n }\n if (bottom === null || y2 + height > bottom.pos[1] + bottom.size[1]) {\n bottom = node2;\n }\n if (left === null || x2 < left.pos[0]) {\n left = node2;\n }\n }\n return {\n \"top\": top,\n \"right\": right,\n \"bottom\": bottom,\n \"left\": left\n };\n };\n LGraphCanvas.prototype.boundaryNodesForSelection = function() {\n return LGraphCanvas.getBoundaryNodes(Object.values(this.selected_nodes));\n };\n LGraphCanvas.alignNodes = function(nodes, direction, align_to) {\n if (!nodes) {\n return;\n }\n const canvas = LGraphCanvas.active_canvas;\n let boundaryNodes = [];\n if (align_to === void 0) {\n boundaryNodes = LGraphCanvas.getBoundaryNodes(nodes);\n } else {\n boundaryNodes = {\n \"top\": align_to,\n \"right\": align_to,\n \"bottom\": align_to,\n \"left\": align_to\n };\n }\n for (const [_, node2] of Object.entries(canvas.selected_nodes)) {\n switch (direction) {\n case \"right\":\n node2.pos[0] = boundaryNodes[\"right\"].pos[0] + boundaryNodes[\"right\"].size[0] - node2.size[0];\n break;\n case \"left\":\n node2.pos[0] = boundaryNodes[\"left\"].pos[0];\n break;\n case \"top\":\n node2.pos[1] = boundaryNodes[\"top\"].pos[1];\n break;\n case \"bottom\":\n node2.pos[1] = boundaryNodes[\"bottom\"].pos[1] + boundaryNodes[\"bottom\"].size[1] - node2.size[1];\n break;\n }\n }\n canvas.dirty_canvas = true;\n canvas.dirty_bgcanvas = true;\n };\n LGraphCanvas.onNodeAlign = function(value, options, event2, prev_menu, node2) {\n new LiteGraph.ContextMenu([\"Top\", \"Bottom\", \"Left\", \"Right\"], {\n event: event2,\n callback: inner_clicked,\n parentMenu: prev_menu\n });\n function inner_clicked(value2) {\n LGraphCanvas.alignNodes(LGraphCanvas.active_canvas.selected_nodes, value2.toLowerCase(), node2);\n }\n };\n LGraphCanvas.onGroupAlign = function(value, options, event2, prev_menu) {\n new LiteGraph.ContextMenu([\"Top\", \"Bottom\", \"Left\", \"Right\"], {\n event: event2,\n callback: inner_clicked,\n parentMenu: prev_menu\n });\n function inner_clicked(value2) {\n LGraphCanvas.alignNodes(LGraphCanvas.active_canvas.selected_nodes, value2.toLowerCase());\n }\n };\n LGraphCanvas.onMenuAdd = function(node2, options, e, prev_menu, callback) {\n var canvas = LGraphCanvas.active_canvas;\n var ref_window2 = canvas.getCanvasWindow();\n var graph = canvas.graph;\n if (!graph)\n return;\n function inner_onMenuAdded(base_category, prev_menu2) {\n var categories = LiteGraph.getNodeTypesCategories(canvas.filter || graph.filter).filter(function(category) {\n return category.startsWith(base_category);\n });\n var entries = [];\n categories.map(function(category) {\n if (!category)\n return;\n var base_category_regex = new RegExp(\"^(\" + base_category + \")\");\n var category_name = category.replace(base_category_regex, \"\").split(\"/\")[0];\n var category_path = base_category === \"\" ? category_name + \"/\" : base_category + category_name + \"/\";\n var name = category_name;\n if (name.indexOf(\"::\") != -1)\n name = name.split(\"::\")[1];\n var index2 = entries.findIndex(function(entry) {\n return entry.value === category_path;\n });\n if (index2 === -1) {\n entries.push({ value: category_path, content: name, has_submenu: true, callback: function(value, event2, mouseEvent, contextMenu) {\n inner_onMenuAdded(value.value, contextMenu);\n } });\n }\n });\n var nodes = LiteGraph.getNodeTypesInCategory(base_category.slice(0, -1), canvas.filter || graph.filter);\n nodes.map(function(node3) {\n if (node3.skip_list)\n return;\n var entry = {\n value: node3.type,\n content: node3.title,\n has_submenu: false,\n callback: function(value, event2, mouseEvent, contextMenu) {\n var first_event = contextMenu.getFirstEvent();\n canvas.graph.beforeChange();\n var node4 = LiteGraph.createNode(value.value);\n if (node4) {\n node4.pos = canvas.convertEventToCanvasOffset(first_event);\n canvas.graph.add(node4);\n }\n if (callback)\n callback(node4);\n canvas.graph.afterChange();\n }\n };\n entries.push(entry);\n });\n new LiteGraph.ContextMenu(entries, { event: e, parentMenu: prev_menu2 }, ref_window2);\n }\n inner_onMenuAdded(\"\", prev_menu);\n return false;\n };\n LGraphCanvas.onMenuCollapseAll = function() {\n };\n LGraphCanvas.onMenuNodeEdit = function() {\n };\n LGraphCanvas.showMenuNodeOptionalInputs = function(v2, options, e, prev_menu, node2) {\n if (!node2) {\n return;\n }\n var that2 = this;\n var canvas = LGraphCanvas.active_canvas;\n var ref_window2 = canvas.getCanvasWindow();\n var options = node2.optional_inputs;\n if (node2.onGetInputs) {\n options = node2.onGetInputs();\n }\n var entries = [];\n if (options) {\n for (var i2 = 0; i2 < options.length; i2++) {\n var entry = options[i2];\n if (!entry) {\n entries.push(null);\n continue;\n }\n var label = entry[0];\n if (!entry[2])\n entry[2] = {};\n if (entry[2].label) {\n label = entry[2].label;\n }\n entry[2].removable = true;\n var data = { content: label, value: entry };\n if (entry[1] == LiteGraph.ACTION) {\n data.className = \"event\";\n }\n entries.push(data);\n }\n }\n if (node2.onMenuNodeInputs) {\n var retEntries = node2.onMenuNodeInputs(entries);\n if (retEntries) entries = retEntries;\n }\n if (!entries.length) {\n console.log(\"no input entries\");\n return;\n }\n new LiteGraph.ContextMenu(\n entries,\n {\n event: e,\n callback: inner_clicked,\n parentMenu: prev_menu,\n node: node2\n },\n ref_window2\n );\n function inner_clicked(v3, e2, prev) {\n if (!node2) {\n return;\n }\n if (v3.callback) {\n v3.callback.call(that2, node2, v3, e2, prev);\n }\n if (v3.value) {\n node2.graph.beforeChange();\n node2.addInput(v3.value[0], v3.value[1], v3.value[2]);\n if (node2.onNodeInputAdd) {\n node2.onNodeInputAdd(v3.value);\n }\n node2.setDirtyCanvas(true, true);\n node2.graph.afterChange();\n }\n }\n return false;\n };\n LGraphCanvas.showMenuNodeOptionalOutputs = function(v2, options, e, prev_menu, node2) {\n if (!node2) {\n return;\n }\n var that2 = this;\n var canvas = LGraphCanvas.active_canvas;\n var ref_window2 = canvas.getCanvasWindow();\n var options = node2.optional_outputs;\n if (node2.onGetOutputs) {\n options = node2.onGetOutputs();\n }\n var entries = [];\n if (options) {\n for (var i2 = 0; i2 < options.length; i2++) {\n var entry = options[i2];\n if (!entry) {\n entries.push(null);\n continue;\n }\n if (node2.flags && node2.flags.skip_repeated_outputs && node2.findOutputSlot(entry[0]) != -1) {\n continue;\n }\n var label = entry[0];\n if (!entry[2])\n entry[2] = {};\n if (entry[2].label) {\n label = entry[2].label;\n }\n entry[2].removable = true;\n var data = { content: label, value: entry };\n if (entry[1] == LiteGraph.EVENT) {\n data.className = \"event\";\n }\n entries.push(data);\n }\n }\n if (this.onMenuNodeOutputs) {\n entries = this.onMenuNodeOutputs(entries);\n }\n if (LiteGraph.do_add_triggers_slots) {\n if (node2.findOutputSlot(\"onExecuted\") == -1) {\n entries.push({ content: \"On Executed\", value: [\"onExecuted\", LiteGraph.EVENT, { nameLocked: true }], className: \"event\" });\n }\n }\n if (node2.onMenuNodeOutputs) {\n var retEntries = node2.onMenuNodeOutputs(entries);\n if (retEntries) entries = retEntries;\n }\n if (!entries.length) {\n return;\n }\n new LiteGraph.ContextMenu(\n entries,\n {\n event: e,\n callback: inner_clicked,\n parentMenu: prev_menu,\n node: node2\n },\n ref_window2\n );\n function inner_clicked(v3, e2, prev) {\n if (!node2) {\n return;\n }\n if (v3.callback) {\n v3.callback.call(that2, node2, v3, e2, prev);\n }\n if (!v3.value) {\n return;\n }\n var value = v3.value[1];\n if (value && (value.constructor === Object || value.constructor === Array)) {\n var entries2 = [];\n for (var i3 in value) {\n entries2.push({ content: i3, value: value[i3] });\n }\n new LiteGraph.ContextMenu(entries2, {\n event: e2,\n callback: inner_clicked,\n parentMenu: prev_menu,\n node: node2\n });\n return false;\n } else {\n node2.graph.beforeChange();\n node2.addOutput(v3.value[0], v3.value[1], v3.value[2]);\n if (node2.onNodeOutputAdd) {\n node2.onNodeOutputAdd(v3.value);\n }\n node2.setDirtyCanvas(true, true);\n node2.graph.afterChange();\n }\n }\n return false;\n };\n LGraphCanvas.onShowMenuNodeProperties = function(value, options, e, prev_menu, node2) {\n if (!node2 || !node2.properties) {\n return;\n }\n var canvas = LGraphCanvas.active_canvas;\n var ref_window2 = canvas.getCanvasWindow();\n var entries = [];\n for (var i2 in node2.properties) {\n var value = node2.properties[i2] !== void 0 ? node2.properties[i2] : \" \";\n if (typeof value == \"object\")\n value = JSON.stringify(value);\n var info = node2.getPropertyInfo(i2);\n if (info.type == \"enum\" || info.type == \"combo\")\n value = LGraphCanvas.getPropertyPrintableValue(value, info.values);\n value = LGraphCanvas.decodeHTML(value);\n entries.push({\n content: \"\" + (info.label ? info.label : i2) + \"\" + value + \"\",\n value: i2\n });\n }\n if (!entries.length) {\n return;\n }\n new LiteGraph.ContextMenu(\n entries,\n {\n event: e,\n callback: inner_clicked,\n parentMenu: prev_menu,\n allow_html: true,\n node: node2\n },\n ref_window2\n );\n function inner_clicked(v2, options2, e2, prev) {\n if (!node2) {\n return;\n }\n var rect = this.getBoundingClientRect();\n canvas.showEditPropertyValue(node2, v2.value, {\n position: [rect.left, rect.top]\n });\n }\n return false;\n };\n LGraphCanvas.decodeHTML = function(str) {\n var e = document.createElement(\"div\");\n e.innerText = str;\n return e.innerHTML;\n };\n LGraphCanvas.onMenuResizeNode = function(value, options, e, menu, node2) {\n if (!node2) {\n return;\n }\n var fApplyMultiNode = function(node3) {\n node3.size = node3.computeSize();\n if (node3.onResize)\n node3.onResize(node3.size);\n };\n var graphcanvas = LGraphCanvas.active_canvas;\n if (!graphcanvas.selected_nodes || Object.keys(graphcanvas.selected_nodes).length <= 1) {\n fApplyMultiNode(node2);\n } else {\n for (var i2 in graphcanvas.selected_nodes) {\n fApplyMultiNode(graphcanvas.selected_nodes[i2]);\n }\n }\n node2.setDirtyCanvas(true, true);\n };\n LGraphCanvas.prototype.showLinkMenu = function(link, e) {\n var that2 = this;\n var node_left = that2.graph.getNodeById(link.origin_id);\n var node_right = that2.graph.getNodeById(link.target_id);\n var fromType = false;\n if (node_left && node_left.outputs && node_left.outputs[link.origin_slot]) fromType = node_left.outputs[link.origin_slot].type;\n var destType = false;\n if (node_right && node_right.outputs && node_right.outputs[link.target_slot]) destType = node_right.inputs[link.target_slot].type;\n var options = [\"Add Node\", null, \"Delete\", null];\n var menu = new LiteGraph.ContextMenu(options, {\n event: e,\n title: link.data != null ? link.data.constructor.name : null,\n callback: inner_clicked\n });\n function inner_clicked(v2, options2, e2) {\n switch (v2) {\n case \"Add Node\":\n LGraphCanvas.onMenuAdd(null, null, e2, menu, function(node2) {\n if (!node2.inputs || !node2.inputs.length || !node2.outputs || !node2.outputs.length) {\n return;\n }\n if (node_left.connectByType(link.origin_slot, node2, fromType)) {\n node2.connectByType(link.target_slot, node_right, destType);\n node2.pos[0] -= node2.size[0] * 0.5;\n }\n });\n break;\n case \"Delete\":\n that2.graph.removeLink(link.id);\n break;\n }\n }\n return false;\n };\n LGraphCanvas.prototype.createDefaultNodeForSlot = function(optPass) {\n var optPass = optPass || {};\n var opts = Object.assign(\n {\n nodeFrom: null,\n slotFrom: null,\n nodeTo: null,\n slotTo: null,\n position: [],\n nodeType: null,\n posAdd: [0, 0],\n posSizeFix: [0, 0]\n // alpha, adjust the position x,y based on the new node size w,h\n },\n optPass\n );\n var that2 = this;\n var isFrom = opts.nodeFrom && opts.slotFrom !== null;\n var isTo = !isFrom && opts.nodeTo && opts.slotTo !== null;\n if (!isFrom && !isTo) {\n console.warn(\"No data passed to createDefaultNodeForSlot \" + opts.nodeFrom + \" \" + opts.slotFrom + \" \" + opts.nodeTo + \" \" + opts.slotTo);\n return false;\n }\n if (!opts.nodeType) {\n console.warn(\"No type to createDefaultNodeForSlot\");\n return false;\n }\n var nodeX = isFrom ? opts.nodeFrom : opts.nodeTo;\n var slotX = isFrom ? opts.slotFrom : opts.slotTo;\n var iSlotConn = false;\n switch (typeof slotX) {\n case \"string\":\n iSlotConn = isFrom ? nodeX.findOutputSlot(slotX, false) : nodeX.findInputSlot(slotX, false);\n slotX = isFrom ? nodeX.outputs[slotX] : nodeX.inputs[slotX];\n break;\n case \"object\":\n iSlotConn = isFrom ? nodeX.findOutputSlot(slotX.name) : nodeX.findInputSlot(slotX.name);\n break;\n case \"number\":\n iSlotConn = slotX;\n slotX = isFrom ? nodeX.outputs[slotX] : nodeX.inputs[slotX];\n break;\n case \"undefined\":\n default:\n console.warn(\"Cant get slot information \" + slotX);\n return false;\n }\n if (slotX === false || iSlotConn === false) {\n console.warn(\"createDefaultNodeForSlot bad slotX \" + slotX + \" \" + iSlotConn);\n }\n var fromSlotType = slotX.type == LiteGraph.EVENT ? \"_event_\" : slotX.type;\n var slotTypesDefault = isFrom ? LiteGraph.slot_types_default_out : LiteGraph.slot_types_default_in;\n if (slotTypesDefault && slotTypesDefault[fromSlotType]) {\n if (slotX.link !== null) ;\n let nodeNewType = false;\n if (typeof slotTypesDefault[fromSlotType] == \"object\" || typeof slotTypesDefault[fromSlotType] == \"array\") {\n for (var typeX in slotTypesDefault[fromSlotType]) {\n if (opts.nodeType == slotTypesDefault[fromSlotType][typeX] || opts.nodeType == \"AUTO\") {\n nodeNewType = slotTypesDefault[fromSlotType][typeX];\n break;\n }\n }\n } else {\n if (opts.nodeType == slotTypesDefault[fromSlotType] || opts.nodeType == \"AUTO\") nodeNewType = slotTypesDefault[fromSlotType];\n }\n if (nodeNewType) {\n var nodeNewOpts = false;\n if (typeof nodeNewType == \"object\" && nodeNewType.node) {\n nodeNewOpts = nodeNewType;\n nodeNewType = nodeNewType.node;\n }\n var newNode = LiteGraph.createNode(nodeNewType);\n if (newNode) {\n if (nodeNewOpts) {\n if (nodeNewOpts.properties) {\n for (var i2 in nodeNewOpts.properties) {\n newNode.addProperty(i2, nodeNewOpts.properties[i2]);\n }\n }\n if (nodeNewOpts.inputs) {\n newNode.inputs = [];\n for (var i2 in nodeNewOpts.inputs) {\n newNode.addOutput(\n nodeNewOpts.inputs[i2][0],\n nodeNewOpts.inputs[i2][1]\n );\n }\n }\n if (nodeNewOpts.outputs) {\n newNode.outputs = [];\n for (var i2 in nodeNewOpts.outputs) {\n newNode.addOutput(\n nodeNewOpts.outputs[i2][0],\n nodeNewOpts.outputs[i2][1]\n );\n }\n }\n if (nodeNewOpts.title) {\n newNode.title = nodeNewOpts.title;\n }\n if (nodeNewOpts.json) {\n newNode.configure(nodeNewOpts.json);\n }\n }\n that2.graph.add(newNode);\n newNode.pos = [\n opts.position[0] + opts.posAdd[0] + (opts.posSizeFix[0] ? opts.posSizeFix[0] * newNode.size[0] : 0),\n opts.position[1] + opts.posAdd[1] + (opts.posSizeFix[1] ? opts.posSizeFix[1] * newNode.size[1] : 0)\n ];\n if (isFrom) {\n opts.nodeFrom.connectByType(iSlotConn, newNode, fromSlotType);\n } else {\n opts.nodeTo.connectByTypeOutput(iSlotConn, newNode, fromSlotType);\n }\n return true;\n } else {\n console.log(\"failed creating \" + nodeNewType);\n }\n }\n }\n return false;\n };\n LGraphCanvas.prototype.showConnectionMenu = function(optPass) {\n var optPass = optPass || {};\n var opts = Object.assign(\n {\n nodeFrom: null,\n slotFrom: null,\n nodeTo: null,\n slotTo: null,\n e: null\n },\n optPass\n );\n var that2 = this;\n var isFrom = opts.nodeFrom && opts.slotFrom;\n var isTo = !isFrom && opts.nodeTo && opts.slotTo;\n if (!isFrom && !isTo) {\n console.warn(\"No data passed to showConnectionMenu\");\n return false;\n }\n var nodeX = isFrom ? opts.nodeFrom : opts.nodeTo;\n var slotX = isFrom ? opts.slotFrom : opts.slotTo;\n var iSlotConn = false;\n switch (typeof slotX) {\n case \"string\":\n iSlotConn = isFrom ? nodeX.findOutputSlot(slotX, false) : nodeX.findInputSlot(slotX, false);\n slotX = isFrom ? nodeX.outputs[slotX] : nodeX.inputs[slotX];\n break;\n case \"object\":\n iSlotConn = isFrom ? nodeX.findOutputSlot(slotX.name) : nodeX.findInputSlot(slotX.name);\n break;\n case \"number\":\n iSlotConn = slotX;\n slotX = isFrom ? nodeX.outputs[slotX] : nodeX.inputs[slotX];\n break;\n default:\n console.warn(\"Cant get slot information \" + slotX);\n return false;\n }\n var options = [\"Add Node\", null];\n if (that2.allow_searchbox) {\n options.push(\"Search\");\n options.push(null);\n }\n var fromSlotType = slotX.type == LiteGraph.EVENT ? \"_event_\" : slotX.type;\n var slotTypesDefault = isFrom ? LiteGraph.slot_types_default_out : LiteGraph.slot_types_default_in;\n if (slotTypesDefault && slotTypesDefault[fromSlotType]) {\n if (typeof slotTypesDefault[fromSlotType] == \"object\" || typeof slotTypesDefault[fromSlotType] == \"array\") {\n for (var typeX in slotTypesDefault[fromSlotType]) {\n options.push(slotTypesDefault[fromSlotType][typeX]);\n }\n } else {\n options.push(slotTypesDefault[fromSlotType]);\n }\n }\n var menu = new LiteGraph.ContextMenu(options, {\n event: opts.e,\n title: (slotX && slotX.name != \"\" ? slotX.name + (fromSlotType ? \" | \" : \"\") : \"\") + (slotX && fromSlotType ? fromSlotType : \"\"),\n callback: inner_clicked\n });\n function inner_clicked(v2, options2, e) {\n switch (v2) {\n case \"Add Node\":\n LGraphCanvas.onMenuAdd(null, null, e, menu, function(node2) {\n if (isFrom) {\n opts.nodeFrom.connectByType(iSlotConn, node2, fromSlotType);\n } else {\n opts.nodeTo.connectByTypeOutput(iSlotConn, node2, fromSlotType);\n }\n });\n break;\n case \"Search\":\n if (isFrom) {\n that2.showSearchBox(e, { node_from: opts.nodeFrom, slot_from: slotX, type_filter_in: fromSlotType });\n } else {\n that2.showSearchBox(e, { node_to: opts.nodeTo, slot_from: slotX, type_filter_out: fromSlotType });\n }\n break;\n default:\n that2.createDefaultNodeForSlot(Object.assign(opts, {\n position: [opts.e.canvasX, opts.e.canvasY],\n nodeType: v2\n }));\n break;\n }\n }\n return false;\n };\n LGraphCanvas.onShowPropertyEditor = function(item, options, e, menu, node2) {\n var property = item.property || \"title\";\n var value = node2[property];\n var dialog = document.createElement(\"div\");\n dialog.is_modified = false;\n dialog.className = \"graphdialog\";\n dialog.innerHTML = \"OK\";\n dialog.close = function() {\n if (dialog.parentNode) {\n dialog.parentNode.removeChild(dialog);\n }\n };\n var title = dialog.querySelector(\".name\");\n title.innerText = property;\n var input = dialog.querySelector(\".value\");\n if (input) {\n input.value = value;\n input.addEventListener(\"blur\", function(e2) {\n this.focus();\n });\n input.addEventListener(\"keydown\", function(e2) {\n dialog.is_modified = true;\n if (e2.keyCode == 27) {\n dialog.close();\n } else if (e2.keyCode == 13) {\n inner();\n } else if (e2.keyCode != 13 && e2.target.localName != \"textarea\") {\n return;\n }\n e2.preventDefault();\n e2.stopPropagation();\n });\n }\n var graphcanvas = LGraphCanvas.active_canvas;\n var canvas = graphcanvas.canvas;\n var rect = canvas.getBoundingClientRect();\n var offsetx = -20;\n var offsety = -20;\n if (rect) {\n offsetx -= rect.left;\n offsety -= rect.top;\n }\n if (event) {\n dialog.style.left = event.clientX + offsetx + \"px\";\n dialog.style.top = event.clientY + offsety + \"px\";\n } else {\n dialog.style.left = canvas.width * 0.5 + offsetx + \"px\";\n dialog.style.top = canvas.height * 0.5 + offsety + \"px\";\n }\n var button = dialog.querySelector(\"button\");\n button.addEventListener(\"click\", inner);\n canvas.parentNode.appendChild(dialog);\n if (input) input.focus();\n var dialogCloseTimer = null;\n dialog.addEventListener(\"mouseleave\", function(e2) {\n if (LiteGraph.dialog_close_on_mouse_leave) {\n if (!dialog.is_modified && LiteGraph.dialog_close_on_mouse_leave)\n dialogCloseTimer = setTimeout(dialog.close, LiteGraph.dialog_close_on_mouse_leave_delay);\n }\n });\n dialog.addEventListener(\"mouseenter\", function(e2) {\n if (LiteGraph.dialog_close_on_mouse_leave) {\n if (dialogCloseTimer) clearTimeout(dialogCloseTimer);\n }\n });\n function inner() {\n if (input) setValue(input.value);\n }\n function setValue(value2) {\n if (item.type == \"Number\") {\n value2 = Number(value2);\n } else if (item.type == \"Boolean\") {\n value2 = Boolean(value2);\n }\n node2[property] = value2;\n if (dialog.parentNode) {\n dialog.parentNode.removeChild(dialog);\n }\n node2.setDirtyCanvas(true, true);\n }\n };\n LGraphCanvas.prototype.prompt = function(title, value, callback, event2, multiline) {\n var that2 = this;\n title = title || \"\";\n var dialog = document.createElement(\"div\");\n dialog.is_modified = false;\n dialog.className = \"graphdialog rounded\";\n if (multiline)\n dialog.innerHTML = \" OK\";\n else\n dialog.innerHTML = \" OK\";\n dialog.close = function() {\n that2.prompt_box = null;\n if (dialog.parentNode) {\n dialog.parentNode.removeChild(dialog);\n }\n };\n var graphcanvas = LGraphCanvas.active_canvas;\n var canvas = graphcanvas.canvas;\n canvas.parentNode.appendChild(dialog);\n if (this.ds.scale > 1) {\n dialog.style.transform = \"scale(\" + this.ds.scale + \")\";\n }\n var dialogCloseTimer = null;\n var prevent_timeout = false;\n LiteGraph.pointerListenerAdd(dialog, \"leave\", function(e) {\n if (prevent_timeout)\n return;\n if (LiteGraph.dialog_close_on_mouse_leave) {\n if (!dialog.is_modified && LiteGraph.dialog_close_on_mouse_leave)\n dialogCloseTimer = setTimeout(dialog.close, LiteGraph.dialog_close_on_mouse_leave_delay);\n }\n });\n LiteGraph.pointerListenerAdd(dialog, \"enter\", function(e) {\n if (LiteGraph.dialog_close_on_mouse_leave) {\n if (dialogCloseTimer) clearTimeout(dialogCloseTimer);\n }\n });\n var selInDia = dialog.querySelectorAll(\"select\");\n if (selInDia) {\n selInDia.forEach(function(selIn) {\n selIn.addEventListener(\"click\", function(e) {\n prevent_timeout++;\n });\n selIn.addEventListener(\"blur\", function(e) {\n prevent_timeout = 0;\n });\n selIn.addEventListener(\"change\", function(e) {\n prevent_timeout = -1;\n });\n });\n }\n if (that2.prompt_box) {\n that2.prompt_box.close();\n }\n that2.prompt_box = dialog;\n var name_element = dialog.querySelector(\".name\");\n name_element.innerText = title;\n var value_element = dialog.querySelector(\".value\");\n value_element.value = value;\n value_element.select();\n var input = value_element;\n input.addEventListener(\"keydown\", function(e) {\n dialog.is_modified = true;\n if (e.keyCode == 27) {\n dialog.close();\n } else if (e.keyCode == 13 && e.target.localName != \"textarea\") {\n if (callback) {\n callback(this.value);\n }\n dialog.close();\n } else {\n return;\n }\n e.preventDefault();\n e.stopPropagation();\n });\n var button = dialog.querySelector(\"button\");\n button.addEventListener(\"click\", function(e) {\n if (callback) {\n callback(input.value);\n }\n that2.setDirty(true);\n dialog.close();\n });\n var rect = canvas.getBoundingClientRect();\n var offsetx = -20;\n var offsety = -20;\n if (rect) {\n offsetx -= rect.left;\n offsety -= rect.top;\n }\n if (event2) {\n dialog.style.left = event2.clientX + offsetx + \"px\";\n dialog.style.top = event2.clientY + offsety + \"px\";\n } else {\n dialog.style.left = canvas.width * 0.5 + offsetx + \"px\";\n dialog.style.top = canvas.height * 0.5 + offsety + \"px\";\n }\n setTimeout(function() {\n input.focus();\n }, 10);\n return dialog;\n };\n LGraphCanvas.search_limit = -1;\n LGraphCanvas.prototype.showSearchBox = function(event2, options) {\n var def_options = {\n slot_from: null,\n node_from: null,\n node_to: null,\n do_type_filter: LiteGraph.search_filter_enabled,\n type_filter_in: false,\n type_filter_out: false,\n show_general_if_none_on_typefilter: true,\n show_general_after_typefiltered: true,\n hide_on_mouse_leave: LiteGraph.search_hide_on_mouse_leave,\n show_all_if_empty: true,\n show_all_on_open: LiteGraph.search_show_all_on_open\n };\n options = Object.assign(def_options, options || {});\n var that2 = this;\n var graphcanvas = LGraphCanvas.active_canvas;\n var canvas = graphcanvas.canvas;\n var root_document = canvas.ownerDocument || document;\n var dialog = document.createElement(\"div\");\n dialog.className = \"litegraph litesearchbox graphdialog rounded\";\n dialog.innerHTML = \"Search \";\n if (options.do_type_filter) {\n dialog.innerHTML += \"\";\n dialog.innerHTML += \"\";\n }\n dialog.innerHTML += \"\";\n if (root_document.fullscreenElement)\n root_document.fullscreenElement.appendChild(dialog);\n else {\n root_document.body.appendChild(dialog);\n root_document.body.style.overflow = \"hidden\";\n }\n if (options.do_type_filter) {\n var selIn = dialog.querySelector(\".slot_in_type_filter\");\n var selOut = dialog.querySelector(\".slot_out_type_filter\");\n }\n dialog.close = function() {\n that2.search_box = null;\n this.blur();\n canvas.focus();\n root_document.body.style.overflow = \"\";\n setTimeout(function() {\n that2.canvas.focus();\n }, 20);\n if (dialog.parentNode) {\n dialog.parentNode.removeChild(dialog);\n }\n };\n if (this.ds.scale > 1) {\n dialog.style.transform = \"scale(\" + this.ds.scale + \")\";\n }\n if (options.hide_on_mouse_leave) {\n var prevent_timeout = false;\n var timeout_close = null;\n LiteGraph.pointerListenerAdd(dialog, \"enter\", function(e) {\n if (timeout_close) {\n clearTimeout(timeout_close);\n timeout_close = null;\n }\n });\n LiteGraph.pointerListenerAdd(dialog, \"leave\", function(e) {\n if (prevent_timeout) {\n return;\n }\n timeout_close = setTimeout(function() {\n dialog.close();\n }, typeof options.hide_on_mouse_leave === \"number\" ? options.hide_on_mouse_leave : 500);\n });\n if (options.do_type_filter) {\n selIn.addEventListener(\"click\", function(e) {\n prevent_timeout++;\n });\n selIn.addEventListener(\"blur\", function(e) {\n prevent_timeout = 0;\n });\n selIn.addEventListener(\"change\", function(e) {\n prevent_timeout = -1;\n });\n selOut.addEventListener(\"click\", function(e) {\n prevent_timeout++;\n });\n selOut.addEventListener(\"blur\", function(e) {\n prevent_timeout = 0;\n });\n selOut.addEventListener(\"change\", function(e) {\n prevent_timeout = -1;\n });\n }\n }\n if (that2.search_box) {\n that2.search_box.close();\n }\n that2.search_box = dialog;\n var helper = dialog.querySelector(\".helper\");\n var first = null;\n var timeout = null;\n var selected = null;\n var input = dialog.querySelector(\"input\");\n if (input) {\n input.addEventListener(\"blur\", function(e) {\n this.focus();\n });\n input.addEventListener(\"keydown\", function(e) {\n if (e.keyCode == 38) {\n changeSelection(false);\n } else if (e.keyCode == 40) {\n changeSelection(true);\n } else if (e.keyCode == 27) {\n dialog.close();\n } else if (e.keyCode == 13) {\n if (selected) {\n select(unescape(selected.dataset[\"type\"]));\n } else if (first) {\n select(first);\n } else {\n dialog.close();\n }\n } else {\n if (timeout) {\n clearInterval(timeout);\n }\n timeout = setTimeout(refreshHelper, 10);\n return;\n }\n e.preventDefault();\n e.stopPropagation();\n e.stopImmediatePropagation();\n return true;\n });\n }\n if (options.do_type_filter) {\n if (selIn) {\n var aSlots = LiteGraph.slot_types_in;\n var nSlots = aSlots.length;\n if (options.type_filter_in == LiteGraph.EVENT || options.type_filter_in == LiteGraph.ACTION)\n options.type_filter_in = \"_event_\";\n for (var iK = 0; iK < nSlots; iK++) {\n var opt = document.createElement(\"option\");\n opt.value = aSlots[iK];\n opt.innerHTML = aSlots[iK];\n selIn.appendChild(opt);\n if (options.type_filter_in !== false && (options.type_filter_in + \"\").toLowerCase() == (aSlots[iK] + \"\").toLowerCase()) {\n opt.selected = true;\n }\n }\n selIn.addEventListener(\"change\", function() {\n refreshHelper();\n });\n }\n if (selOut) {\n var aSlots = LiteGraph.slot_types_out;\n var nSlots = aSlots.length;\n if (options.type_filter_out == LiteGraph.EVENT || options.type_filter_out == LiteGraph.ACTION)\n options.type_filter_out = \"_event_\";\n for (var iK = 0; iK < nSlots; iK++) {\n var opt = document.createElement(\"option\");\n opt.value = aSlots[iK];\n opt.innerHTML = aSlots[iK];\n selOut.appendChild(opt);\n if (options.type_filter_out !== false && (options.type_filter_out + \"\").toLowerCase() == (aSlots[iK] + \"\").toLowerCase()) {\n opt.selected = true;\n }\n }\n selOut.addEventListener(\"change\", function() {\n refreshHelper();\n });\n }\n }\n var rect = canvas.getBoundingClientRect();\n var left = (event2 ? event2.clientX : rect.left + rect.width * 0.5) - 80;\n var top = (event2 ? event2.clientY : rect.top + rect.height * 0.5) - 20;\n dialog.style.left = left + \"px\";\n dialog.style.top = top + \"px\";\n if (event2.layerY > rect.height - 200)\n helper.style.maxHeight = rect.height - event2.layerY - 20 + \"px\";\n input.focus();\n if (options.show_all_on_open) refreshHelper();\n function select(name) {\n if (name) {\n if (that2.onSearchBoxSelection) {\n that2.onSearchBoxSelection(name, event2, graphcanvas);\n } else {\n var extra = LiteGraph.searchbox_extras[name.toLowerCase()];\n if (extra) {\n name = extra.type;\n }\n graphcanvas.graph.beforeChange();\n var node2 = LiteGraph.createNode(name);\n if (node2) {\n node2.pos = graphcanvas.convertEventToCanvasOffset(\n event2\n );\n graphcanvas.graph.add(node2, false);\n }\n if (extra && extra.data) {\n if (extra.data.properties) {\n for (var i2 in extra.data.properties) {\n node2.addProperty(i2, extra.data.properties[i2]);\n }\n }\n if (extra.data.inputs) {\n node2.inputs = [];\n for (var i2 in extra.data.inputs) {\n node2.addOutput(\n extra.data.inputs[i2][0],\n extra.data.inputs[i2][1]\n );\n }\n }\n if (extra.data.outputs) {\n node2.outputs = [];\n for (var i2 in extra.data.outputs) {\n node2.addOutput(\n extra.data.outputs[i2][0],\n extra.data.outputs[i2][1]\n );\n }\n }\n if (extra.data.title) {\n node2.title = extra.data.title;\n }\n if (extra.data.json) {\n node2.configure(extra.data.json);\n }\n }\n if (options.node_from) {\n var iS = false;\n switch (typeof options.slot_from) {\n case \"string\":\n iS = options.node_from.findOutputSlot(options.slot_from);\n break;\n case \"object\":\n if (options.slot_from.name) {\n iS = options.node_from.findOutputSlot(options.slot_from.name);\n } else {\n iS = -1;\n }\n if (iS == -1 && typeof options.slot_from.slot_index !== \"undefined\") iS = options.slot_from.slot_index;\n break;\n case \"number\":\n iS = options.slot_from;\n break;\n default:\n iS = 0;\n }\n if (typeof options.node_from.outputs[iS] !== \"undefined\") {\n if (iS !== false && iS > -1) {\n options.node_from.connectByType(iS, node2, options.node_from.outputs[iS].type);\n }\n }\n }\n if (options.node_to) {\n var iS = false;\n switch (typeof options.slot_from) {\n case \"string\":\n iS = options.node_to.findInputSlot(options.slot_from);\n break;\n case \"object\":\n if (options.slot_from.name) {\n iS = options.node_to.findInputSlot(options.slot_from.name);\n } else {\n iS = -1;\n }\n if (iS == -1 && typeof options.slot_from.slot_index !== \"undefined\") iS = options.slot_from.slot_index;\n break;\n case \"number\":\n iS = options.slot_from;\n break;\n default:\n iS = 0;\n }\n if (typeof options.node_to.inputs[iS] !== \"undefined\") {\n if (iS !== false && iS > -1) {\n options.node_to.connectByTypeOutput(iS, node2, options.node_to.inputs[iS].type);\n }\n }\n }\n graphcanvas.graph.afterChange();\n }\n }\n dialog.close();\n }\n function changeSelection(forward) {\n var prev = selected;\n if (selected) {\n selected.classList.remove(\"selected\");\n }\n if (!selected) {\n selected = forward ? helper.childNodes[0] : helper.childNodes[helper.childNodes.length];\n } else {\n selected = forward ? selected.nextSibling : selected.previousSibling;\n if (!selected) {\n selected = prev;\n }\n }\n if (!selected) {\n return;\n }\n selected.classList.add(\"selected\");\n selected.scrollIntoView({ block: \"end\", behavior: \"smooth\" });\n }\n function refreshHelper() {\n timeout = null;\n var str = input.value;\n first = null;\n helper.innerHTML = \"\";\n if (!str && !options.show_all_if_empty) {\n return;\n }\n if (that2.onSearchBox) {\n var list = that2.onSearchBox(helper, str, graphcanvas);\n if (list) {\n for (var i2 = 0; i2 < list.length; ++i2) {\n addResult(list[i2]);\n }\n }\n } else {\n let inner_test_filter = function(type, optsIn) {\n var optsIn = optsIn || {};\n var optsDef = {\n skipFilter: false,\n inTypeOverride: false,\n outTypeOverride: false\n };\n var opts = Object.assign(optsDef, optsIn);\n var ctor2 = LiteGraph.registered_node_types[type];\n if (filter && ctor2.filter != filter)\n return false;\n if ((!options.show_all_if_empty || str) && type.toLowerCase().indexOf(str) === -1 && (!ctor2.title || ctor2.title.toLowerCase().indexOf(str) === -1))\n return false;\n if (options.do_type_filter && !opts.skipFilter) {\n var sType = type;\n var sV = sIn.value;\n if (opts.inTypeOverride !== false) sV = opts.inTypeOverride;\n if (sIn && sV) {\n if (LiteGraph.registered_slot_in_types[sV] && LiteGraph.registered_slot_in_types[sV].nodes) {\n var doesInc = LiteGraph.registered_slot_in_types[sV].nodes.includes(sType);\n if (doesInc !== false) ;\n else {\n return false;\n }\n }\n }\n var sV = sOut.value;\n if (opts.outTypeOverride !== false) sV = opts.outTypeOverride;\n if (sOut && sV) {\n if (LiteGraph.registered_slot_out_types[sV] && LiteGraph.registered_slot_out_types[sV].nodes) {\n var doesInc = LiteGraph.registered_slot_out_types[sV].nodes.includes(sType);\n if (doesInc !== false) ;\n else {\n return false;\n }\n }\n }\n }\n return true;\n };\n var c = 0;\n str = str.toLowerCase();\n var filter = graphcanvas.filter || graphcanvas.graph.filter;\n if (options.do_type_filter && that2.search_box) {\n var sIn = that2.search_box.querySelector(\".slot_in_type_filter\");\n var sOut = that2.search_box.querySelector(\".slot_out_type_filter\");\n } else {\n var sIn = false;\n var sOut = false;\n }\n for (var i2 in LiteGraph.searchbox_extras) {\n var extra = LiteGraph.searchbox_extras[i2];\n if ((!options.show_all_if_empty || str) && extra.desc.toLowerCase().indexOf(str) === -1) {\n continue;\n }\n var ctor = LiteGraph.registered_node_types[extra.type];\n if (ctor && ctor.filter != filter)\n continue;\n if (!inner_test_filter(extra.type))\n continue;\n addResult(extra.desc, \"searchbox_extra\");\n if (LGraphCanvas.search_limit !== -1 && c++ > LGraphCanvas.search_limit) {\n break;\n }\n }\n var filtered = null;\n if (Array.prototype.filter) {\n var keys = Object.keys(LiteGraph.registered_node_types);\n var filtered = keys.filter(inner_test_filter);\n } else {\n filtered = [];\n for (var i2 in LiteGraph.registered_node_types) {\n if (inner_test_filter(i2))\n filtered.push(i2);\n }\n }\n for (var i2 = 0; i2 < filtered.length; i2++) {\n addResult(filtered[i2]);\n if (LGraphCanvas.search_limit !== -1 && c++ > LGraphCanvas.search_limit) {\n break;\n }\n }\n if (options.show_general_after_typefiltered && (sIn.value || sOut.value)) {\n filtered_extra = [];\n for (var i2 in LiteGraph.registered_node_types) {\n if (inner_test_filter(i2, { inTypeOverride: sIn && sIn.value ? \"*\" : false, outTypeOverride: sOut && sOut.value ? \"*\" : false }))\n filtered_extra.push(i2);\n }\n for (var i2 = 0; i2 < filtered_extra.length; i2++) {\n addResult(filtered_extra[i2], \"generic_type\");\n if (LGraphCanvas.search_limit !== -1 && c++ > LGraphCanvas.search_limit) {\n break;\n }\n }\n }\n if ((sIn.value || sOut.value) && (helper.childNodes.length == 0 && options.show_general_if_none_on_typefilter)) {\n filtered_extra = [];\n for (var i2 in LiteGraph.registered_node_types) {\n if (inner_test_filter(i2, { skipFilter: true }))\n filtered_extra.push(i2);\n }\n for (var i2 = 0; i2 < filtered_extra.length; i2++) {\n addResult(filtered_extra[i2], \"not_in_filter\");\n if (LGraphCanvas.search_limit !== -1 && c++ > LGraphCanvas.search_limit) {\n break;\n }\n }\n }\n }\n function addResult(type, className) {\n var help = document.createElement(\"div\");\n if (!first) {\n first = type;\n }\n const nodeType = LiteGraph.registered_node_types[type];\n if (nodeType == null ? void 0 : nodeType.title) {\n help.innerText = nodeType == null ? void 0 : nodeType.title;\n const typeEl = document.createElement(\"span\");\n typeEl.className = \"litegraph lite-search-item-type\";\n typeEl.textContent = type;\n help.append(typeEl);\n } else {\n help.innerText = type;\n }\n help.dataset[\"type\"] = escape(type);\n help.className = \"litegraph lite-search-item\";\n if (className) {\n help.className += \" \" + className;\n }\n help.addEventListener(\"click\", function(e) {\n select(unescape(this.dataset[\"type\"]));\n });\n helper.appendChild(help);\n }\n }\n return dialog;\n };\n LGraphCanvas.prototype.showEditPropertyValue = function(node2, property, options) {\n if (!node2 || node2.properties[property] === void 0) {\n return;\n }\n options = options || {};\n var info = node2.getPropertyInfo(property);\n var type = info.type;\n var input_html = \"\";\n if (type == \"string\" || type == \"number\" || type == \"array\" || type == \"object\") {\n input_html = \"\";\n } else if ((type == \"enum\" || type == \"combo\") && info.values) {\n input_html = \"\";\n for (var i2 in info.values) {\n var v2 = i2;\n if (info.values.constructor === Array)\n v2 = info.values[i2];\n input_html += \"\" + info.values[i2] + \"\";\n }\n input_html += \"\";\n } else if (type == \"boolean\" || type == \"toggle\") {\n input_html = \"\";\n } else {\n console.warn(\"unknown type: \" + type);\n return;\n }\n var dialog = this.createDialog(\n \"\" + (info.label ? info.label : property) + \"\" + input_html + \"OK\",\n options\n );\n var input = false;\n if ((type == \"enum\" || type == \"combo\") && info.values) {\n input = dialog.querySelector(\"select\");\n input.addEventListener(\"change\", function(e) {\n dialog.modified();\n setValue(e.target.value);\n });\n } else if (type == \"boolean\" || type == \"toggle\") {\n input = dialog.querySelector(\"input\");\n if (input) {\n input.addEventListener(\"click\", function(e) {\n dialog.modified();\n setValue(!!input.checked);\n });\n }\n } else {\n input = dialog.querySelector(\"input\");\n if (input) {\n input.addEventListener(\"blur\", function(e) {\n this.focus();\n });\n var v2 = node2.properties[property] !== void 0 ? node2.properties[property] : \"\";\n if (type !== \"string\") {\n v2 = JSON.stringify(v2);\n }\n input.value = v2;\n input.addEventListener(\"keydown\", function(e) {\n if (e.keyCode == 27) {\n dialog.close();\n } else if (e.keyCode == 13) {\n inner();\n } else if (e.keyCode != 13) {\n dialog.modified();\n return;\n }\n e.preventDefault();\n e.stopPropagation();\n });\n }\n }\n if (input) input.focus();\n var button = dialog.querySelector(\"button\");\n button.addEventListener(\"click\", inner);\n function inner() {\n setValue(input.value);\n }\n function setValue(value) {\n if (info && info.values && info.values.constructor === Object && info.values[value] != void 0)\n value = info.values[value];\n if (typeof node2.properties[property] == \"number\") {\n value = Number(value);\n }\n if (type == \"array\" || type == \"object\") {\n value = JSON.parse(value);\n }\n node2.properties[property] = value;\n if (node2.graph) {\n node2.graph._version++;\n }\n if (node2.onPropertyChanged) {\n node2.onPropertyChanged(property, value);\n }\n if (options.onclose)\n options.onclose();\n dialog.close();\n node2.setDirtyCanvas(true, true);\n }\n return dialog;\n };\n LGraphCanvas.prototype.createDialog = function(html, options) {\n var def_options = { checkForInput: false, closeOnLeave: true, closeOnLeave_checkModified: true };\n options = Object.assign(def_options, options || {});\n var dialog = document.createElement(\"div\");\n dialog.className = \"graphdialog\";\n dialog.innerHTML = html;\n dialog.is_modified = false;\n var rect = this.canvas.getBoundingClientRect();\n var offsetx = -20;\n var offsety = -20;\n if (rect) {\n offsetx -= rect.left;\n offsety -= rect.top;\n }\n if (options.position) {\n offsetx += options.position[0];\n offsety += options.position[1];\n } else if (options.event) {\n offsetx += options.event.clientX;\n offsety += options.event.clientY;\n } else {\n offsetx += this.canvas.width * 0.5;\n offsety += this.canvas.height * 0.5;\n }\n dialog.style.left = offsetx + \"px\";\n dialog.style.top = offsety + \"px\";\n this.canvas.parentNode.appendChild(dialog);\n if (options.checkForInput) {\n var aI = [];\n var focused = false;\n if (aI = dialog.querySelectorAll(\"input\")) {\n aI.forEach(function(iX) {\n iX.addEventListener(\"keydown\", function(e) {\n dialog.modified();\n if (e.keyCode == 27) {\n dialog.close();\n } else if (e.keyCode != 13) {\n return;\n }\n e.preventDefault();\n e.stopPropagation();\n });\n if (!focused) iX.focus();\n });\n }\n }\n dialog.modified = function() {\n dialog.is_modified = true;\n };\n dialog.close = function() {\n if (dialog.parentNode) {\n dialog.parentNode.removeChild(dialog);\n }\n };\n var dialogCloseTimer = null;\n var prevent_timeout = false;\n dialog.addEventListener(\"mouseleave\", function(e) {\n if (prevent_timeout)\n return;\n if (options.closeOnLeave || LiteGraph.dialog_close_on_mouse_leave) {\n if (!dialog.is_modified && LiteGraph.dialog_close_on_mouse_leave)\n dialogCloseTimer = setTimeout(dialog.close, LiteGraph.dialog_close_on_mouse_leave_delay);\n }\n });\n dialog.addEventListener(\"mouseenter\", function(e) {\n if (options.closeOnLeave || LiteGraph.dialog_close_on_mouse_leave) {\n if (dialogCloseTimer) clearTimeout(dialogCloseTimer);\n }\n });\n var selInDia = dialog.querySelectorAll(\"select\");\n if (selInDia) {\n selInDia.forEach(function(selIn) {\n selIn.addEventListener(\"click\", function(e) {\n prevent_timeout++;\n });\n selIn.addEventListener(\"blur\", function(e) {\n prevent_timeout = 0;\n });\n selIn.addEventListener(\"change\", function(e) {\n prevent_timeout = -1;\n });\n });\n }\n return dialog;\n };\n LGraphCanvas.prototype.createPanel = function(title, options) {\n options = options || {};\n var ref_window2 = options.window || window;\n var root = document.createElement(\"div\");\n root.className = \"litegraph dialog\";\n root.innerHTML = \"\";\n root.header = root.querySelector(\".dialog-header\");\n if (options.width)\n root.style.width = options.width + (options.width.constructor === Number ? \"px\" : \"\");\n if (options.height)\n root.style.height = options.height + (options.height.constructor === Number ? \"px\" : \"\");\n if (options.closable) {\n var close = document.createElement(\"span\");\n close.innerHTML = \"✕\";\n close.classList.add(\"close\");\n close.addEventListener(\"click\", function() {\n root.close();\n });\n root.header.appendChild(close);\n }\n root.title_element = root.querySelector(\".dialog-title\");\n root.title_element.innerText = title;\n root.content = root.querySelector(\".dialog-content\");\n root.alt_content = root.querySelector(\".dialog-alt-content\");\n root.footer = root.querySelector(\".dialog-footer\");\n root.close = function() {\n if (root.onClose && typeof root.onClose == \"function\") {\n root.onClose();\n }\n if (root.parentNode)\n root.parentNode.removeChild(root);\n if (this.parentNode) {\n this.parentNode.removeChild(this);\n }\n };\n root.toggleAltContent = function(force) {\n if (typeof force != \"undefined\") {\n var vTo = force ? \"block\" : \"none\";\n var vAlt = force ? \"none\" : \"block\";\n } else {\n var vTo = root.alt_content.style.display != \"block\" ? \"block\" : \"none\";\n var vAlt = root.alt_content.style.display != \"block\" ? \"none\" : \"block\";\n }\n root.alt_content.style.display = vTo;\n root.content.style.display = vAlt;\n };\n root.toggleFooterVisibility = function(force) {\n if (typeof force != \"undefined\") {\n var vTo = force ? \"block\" : \"none\";\n } else {\n var vTo = root.footer.style.display != \"block\" ? \"block\" : \"none\";\n }\n root.footer.style.display = vTo;\n };\n root.clear = function() {\n this.content.innerHTML = \"\";\n };\n root.addHTML = function(code, classname, on_footer) {\n var elem = document.createElement(\"div\");\n if (classname)\n elem.className = classname;\n elem.innerHTML = code;\n if (on_footer)\n root.footer.appendChild(elem);\n else\n root.content.appendChild(elem);\n return elem;\n };\n root.addButton = function(name, callback, options2) {\n var elem = document.createElement(\"button\");\n elem.innerText = name;\n elem.options = options2;\n elem.classList.add(\"btn\");\n elem.addEventListener(\"click\", callback);\n root.footer.appendChild(elem);\n return elem;\n };\n root.addSeparator = function() {\n var elem = document.createElement(\"div\");\n elem.className = \"separator\";\n root.content.appendChild(elem);\n };\n root.addWidget = function(type, name, value, options2, callback) {\n options2 = options2 || {};\n var str_value = String(value);\n type = type.toLowerCase();\n if (type == \"number\")\n str_value = value.toFixed(3);\n var elem = document.createElement(\"div\");\n elem.className = \"property\";\n elem.innerHTML = \"\";\n elem.querySelector(\".property_name\").innerText = options2.label || name;\n var value_element = elem.querySelector(\".property_value\");\n value_element.innerText = str_value;\n elem.dataset[\"property\"] = name;\n elem.dataset[\"type\"] = options2.type || type;\n elem.options = options2;\n elem.value = value;\n if (type == \"code\")\n elem.addEventListener(\"click\", function(e) {\n root.inner_showCodePad(this.dataset[\"property\"]);\n });\n else if (type == \"boolean\") {\n elem.classList.add(\"boolean\");\n if (value)\n elem.classList.add(\"bool-on\");\n elem.addEventListener(\"click\", function() {\n var propname = this.dataset[\"property\"];\n this.value = !this.value;\n this.classList.toggle(\"bool-on\");\n this.querySelector(\".property_value\").innerText = this.value ? \"true\" : \"false\";\n innerChange(propname, this.value);\n });\n } else if (type == \"string\" || type == \"number\") {\n value_element.setAttribute(\"contenteditable\", true);\n value_element.addEventListener(\"keydown\", function(e) {\n if (e.code == \"Enter\" && (type != \"string\" || !e.shiftKey)) {\n e.preventDefault();\n this.blur();\n }\n });\n value_element.addEventListener(\"blur\", function() {\n var v2 = this.innerText;\n var propname = this.parentNode.dataset[\"property\"];\n var proptype = this.parentNode.dataset[\"type\"];\n if (proptype == \"number\")\n v2 = Number(v2);\n innerChange(propname, v2);\n });\n } else if (type == \"enum\" || type == \"combo\") {\n var str_value = LGraphCanvas.getPropertyPrintableValue(value, options2.values);\n value_element.innerText = str_value;\n value_element.addEventListener(\"click\", function(event2) {\n var values2 = options2.values || [];\n var propname = this.parentNode.dataset[\"property\"];\n var elem_that = this;\n new LiteGraph.ContextMenu(\n values2,\n {\n event: event2,\n className: \"dark\",\n callback: inner_clicked\n },\n ref_window2\n );\n function inner_clicked(v2, option, event3) {\n elem_that.innerText = v2;\n innerChange(propname, v2);\n return false;\n }\n });\n }\n root.content.appendChild(elem);\n function innerChange(name2, value2) {\n if (options2.callback)\n options2.callback(name2, value2, options2);\n if (callback)\n callback(name2, value2, options2);\n }\n return elem;\n };\n if (root.onOpen && typeof root.onOpen == \"function\") root.onOpen();\n return root;\n };\n LGraphCanvas.getPropertyPrintableValue = function(value, values2) {\n if (!values2)\n return String(value);\n if (values2.constructor === Array) {\n return String(value);\n }\n if (values2.constructor === Object) {\n var desc_value = \"\";\n for (var k in values2) {\n if (values2[k] != value)\n continue;\n desc_value = k;\n break;\n }\n return String(value) + \" (\" + desc_value + \")\";\n }\n };\n LGraphCanvas.prototype.closePanels = function() {\n var panel2 = document.querySelector(\"#node-panel\");\n if (panel2)\n panel2.close();\n var panel2 = document.querySelector(\"#option-panel\");\n if (panel2)\n panel2.close();\n };\n LGraphCanvas.prototype.showShowGraphOptionsPanel = function(refOpts, obEv, refMenu, refMenu2) {\n if (this.constructor && this.constructor.name == \"HTMLDivElement\") {\n if (!obEv || !obEv.event || !obEv.event.target || !obEv.event.target.lgraphcanvas) {\n console.warn(\"Canvas not found\");\n return;\n }\n var graphcanvas = obEv.event.target.lgraphcanvas;\n } else {\n var graphcanvas = this;\n }\n graphcanvas.closePanels();\n var ref_window2 = graphcanvas.getCanvasWindow();\n panel = graphcanvas.createPanel(\"Options\", {\n closable: true,\n window: ref_window2,\n onOpen: function() {\n graphcanvas.OPTIONPANEL_IS_OPEN = true;\n },\n onClose: function() {\n graphcanvas.OPTIONPANEL_IS_OPEN = false;\n graphcanvas.options_panel = null;\n }\n });\n graphcanvas.options_panel = panel;\n panel.id = \"option-panel\";\n panel.classList.add(\"settings\");\n function inner_refresh() {\n panel.content.innerHTML = \"\";\n var fUpdate = function(name, value, options) {\n switch (name) {\n default:\n if (options && options.key) {\n name = options.key;\n }\n if (options.values) {\n value = Object.values(options.values).indexOf(value);\n }\n graphcanvas[name] = value;\n break;\n }\n };\n var aProps = LiteGraph.availableCanvasOptions;\n aProps.sort();\n for (var pI in aProps) {\n var pX = aProps[pI];\n panel.addWidget(\"boolean\", pX, graphcanvas[pX], { key: pX, on: \"True\", off: \"False\" }, fUpdate);\n }\n [graphcanvas.links_render_mode];\n panel.addWidget(\"combo\", \"Render mode\", LiteGraph.LINK_RENDER_MODES[graphcanvas.links_render_mode], { key: \"links_render_mode\", values: LiteGraph.LINK_RENDER_MODES }, fUpdate);\n panel.addSeparator();\n panel.footer.innerHTML = \"\";\n }\n inner_refresh();\n graphcanvas.canvas.parentNode.appendChild(panel);\n };\n LGraphCanvas.prototype.showShowNodePanel = function(node2) {\n this.SELECTED_NODE = node2;\n this.closePanels();\n var ref_window2 = this.getCanvasWindow();\n var graphcanvas = this;\n var panel2 = this.createPanel(node2.title || \"\", {\n closable: true,\n window: ref_window2,\n onOpen: function() {\n graphcanvas.NODEPANEL_IS_OPEN = true;\n },\n onClose: function() {\n graphcanvas.NODEPANEL_IS_OPEN = false;\n graphcanvas.node_panel = null;\n }\n });\n graphcanvas.node_panel = panel2;\n panel2.id = \"node-panel\";\n panel2.node = node2;\n panel2.classList.add(\"settings\");\n function inner_refresh() {\n panel2.content.innerHTML = \"\";\n panel2.addHTML(\"\" + node2.type + \"\" + (node2.constructor.desc || \"\") + \"\");\n panel2.addHTML(\"Properties\");\n var fUpdate = function(name, value2) {\n graphcanvas.graph.beforeChange(node2);\n switch (name) {\n case \"Title\":\n node2.title = value2;\n break;\n case \"Mode\":\n var kV = Object.values(LiteGraph.NODE_MODES).indexOf(value2);\n if (kV >= 0 && LiteGraph.NODE_MODES[kV]) {\n node2.changeMode(kV);\n } else {\n console.warn(\"unexpected mode: \" + value2);\n }\n break;\n case \"Color\":\n if (LGraphCanvas.node_colors[value2]) {\n node2.color = LGraphCanvas.node_colors[value2].color;\n node2.bgcolor = LGraphCanvas.node_colors[value2].bgcolor;\n } else {\n console.warn(\"unexpected color: \" + value2);\n }\n break;\n default:\n node2.setProperty(name, value2);\n break;\n }\n graphcanvas.graph.afterChange();\n graphcanvas.dirty_canvas = true;\n };\n panel2.addWidget(\"string\", \"Title\", node2.title, {}, fUpdate);\n panel2.addWidget(\"combo\", \"Mode\", LiteGraph.NODE_MODES[node2.mode], { values: LiteGraph.NODE_MODES }, fUpdate);\n var nodeCol = \"\";\n if (node2.color !== void 0) {\n nodeCol = Object.keys(LGraphCanvas.node_colors).filter(function(nK) {\n return LGraphCanvas.node_colors[nK].color == node2.color;\n });\n }\n panel2.addWidget(\"combo\", \"Color\", nodeCol, { values: Object.keys(LGraphCanvas.node_colors) }, fUpdate);\n for (var pName in node2.properties) {\n var value = node2.properties[pName];\n var info = node2.getPropertyInfo(pName);\n info.type || \"string\";\n if (node2.onAddPropertyToPanel && node2.onAddPropertyToPanel(pName, panel2))\n continue;\n panel2.addWidget(info.widget || info.type, pName, value, info, fUpdate);\n }\n panel2.addSeparator();\n if (node2.onShowCustomPanelInfo)\n node2.onShowCustomPanelInfo(panel2);\n panel2.footer.innerHTML = \"\";\n panel2.addButton(\"Delete\", function() {\n if (node2.block_delete)\n return;\n node2.graph.remove(node2);\n panel2.close();\n }).classList.add(\"delete\");\n }\n panel2.inner_showCodePad = function(propname) {\n panel2.classList.remove(\"settings\");\n panel2.classList.add(\"centered\");\n panel2.alt_content.innerHTML = \"\";\n var textarea = panel2.alt_content.querySelector(\"textarea\");\n var fDoneWith = function() {\n panel2.toggleAltContent(false);\n panel2.toggleFooterVisibility(true);\n textarea.parentNode.removeChild(textarea);\n panel2.classList.add(\"settings\");\n panel2.classList.remove(\"centered\");\n inner_refresh();\n };\n textarea.value = node2.properties[propname];\n textarea.addEventListener(\"keydown\", function(e) {\n if (e.code == \"Enter\" && e.ctrlKey) {\n node2.setProperty(propname, textarea.value);\n fDoneWith();\n }\n });\n panel2.toggleAltContent(true);\n panel2.toggleFooterVisibility(false);\n textarea.style.height = \"calc(100% - 40px)\";\n var assign = panel2.addButton(\"Assign\", function() {\n node2.setProperty(propname, textarea.value);\n fDoneWith();\n });\n panel2.alt_content.appendChild(assign);\n var button = panel2.addButton(\"Close\", fDoneWith);\n button.style.float = \"right\";\n panel2.alt_content.appendChild(button);\n };\n inner_refresh();\n this.canvas.parentNode.appendChild(panel2);\n };\n LGraphCanvas.prototype.showSubgraphPropertiesDialog = function(node2) {\n console.log(\"showing subgraph properties dialog\");\n var old_panel = this.canvas.parentNode.querySelector(\".subgraph_dialog\");\n if (old_panel)\n old_panel.close();\n var panel2 = this.createPanel(\"Subgraph Inputs\", { closable: true, width: 500 });\n panel2.node = node2;\n panel2.classList.add(\"subgraph_dialog\");\n function inner_refresh() {\n panel2.clear();\n if (node2.inputs)\n for (var i2 = 0; i2 < node2.inputs.length; ++i2) {\n var input = node2.inputs[i2];\n if (input.not_subgraph_input)\n continue;\n var html2 = \"✕ \";\n var elem2 = panel2.addHTML(html2, \"subgraph_property\");\n elem2.dataset[\"name\"] = input.name;\n elem2.dataset[\"slot\"] = i2;\n elem2.querySelector(\".name\").innerText = input.name;\n elem2.querySelector(\".type\").innerText = input.type;\n elem2.querySelector(\"button\").addEventListener(\"click\", function(e) {\n node2.removeInput(Number(this.parentNode.dataset[\"slot\"]));\n inner_refresh();\n });\n }\n }\n var html = \" + NameType+\";\n var elem = panel2.addHTML(html, \"subgraph_property extra\", true);\n elem.querySelector(\"button\").addEventListener(\"click\", function(e) {\n var elem2 = this.parentNode;\n var name = elem2.querySelector(\".name\").value;\n var type = elem2.querySelector(\".type\").value;\n if (!name || node2.findInputSlot(name) != -1)\n return;\n node2.addInput(name, type);\n elem2.querySelector(\".name\").value = \"\";\n elem2.querySelector(\".type\").value = \"\";\n inner_refresh();\n });\n inner_refresh();\n this.canvas.parentNode.appendChild(panel2);\n return panel2;\n };\n LGraphCanvas.prototype.showSubgraphPropertiesDialogRight = function(node2) {\n var old_panel = this.canvas.parentNode.querySelector(\".subgraph_dialog\");\n if (old_panel)\n old_panel.close();\n var panel2 = this.createPanel(\"Subgraph Outputs\", { closable: true, width: 500 });\n panel2.node = node2;\n panel2.classList.add(\"subgraph_dialog\");\n function inner_refresh() {\n panel2.clear();\n if (node2.outputs)\n for (var i2 = 0; i2 < node2.outputs.length; ++i2) {\n var input = node2.outputs[i2];\n if (input.not_subgraph_output)\n continue;\n var html2 = \"✕ \";\n var elem2 = panel2.addHTML(html2, \"subgraph_property\");\n elem2.dataset[\"name\"] = input.name;\n elem2.dataset[\"slot\"] = i2;\n elem2.querySelector(\".name\").innerText = input.name;\n elem2.querySelector(\".type\").innerText = input.type;\n elem2.querySelector(\"button\").addEventListener(\"click\", function(e) {\n node2.removeOutput(Number(this.parentNode.dataset[\"slot\"]));\n inner_refresh();\n });\n }\n }\n var html = \" + NameType+\";\n var elem = panel2.addHTML(html, \"subgraph_property extra\", true);\n elem.querySelector(\".name\").addEventListener(\"keydown\", function(e) {\n if (e.keyCode == 13) {\n addOutput.apply(this);\n }\n });\n elem.querySelector(\"button\").addEventListener(\"click\", function(e) {\n addOutput.apply(this);\n });\n function addOutput() {\n var elem2 = this.parentNode;\n var name = elem2.querySelector(\".name\").value;\n var type = elem2.querySelector(\".type\").value;\n if (!name || node2.findOutputSlot(name) != -1)\n return;\n node2.addOutput(name, type);\n elem2.querySelector(\".name\").value = \"\";\n elem2.querySelector(\".type\").value = \"\";\n inner_refresh();\n }\n inner_refresh();\n this.canvas.parentNode.appendChild(panel2);\n return panel2;\n };\n LGraphCanvas.prototype.checkPanels = function() {\n if (!this.canvas)\n return;\n var panels = this.canvas.parentNode.querySelectorAll(\".litegraph.dialog\");\n for (var i2 = 0; i2 < panels.length; ++i2) {\n var panel2 = panels[i2];\n if (!panel2.node)\n continue;\n if (!panel2.node.graph || panel2.graph != this.graph)\n panel2.close();\n }\n };\n LGraphCanvas.onMenuNodeCollapse = function(value, options, e, menu, node2) {\n node2.graph.beforeChange(\n /*?*/\n );\n var fApplyMultiNode = function(node3) {\n node3.collapse();\n };\n var graphcanvas = LGraphCanvas.active_canvas;\n if (!graphcanvas.selected_nodes || Object.keys(graphcanvas.selected_nodes).length <= 1) {\n fApplyMultiNode(node2);\n } else {\n for (var i2 in graphcanvas.selected_nodes) {\n fApplyMultiNode(graphcanvas.selected_nodes[i2]);\n }\n }\n node2.graph.afterChange(\n /*?*/\n );\n };\n LGraphCanvas.onMenuNodePin = function(value, options, e, menu, node2) {\n node2.pin();\n };\n LGraphCanvas.onMenuNodeMode = function(value, options, e, menu, node2) {\n new LiteGraph.ContextMenu(\n LiteGraph.NODE_MODES,\n { event: e, callback: inner_clicked, parentMenu: menu, node: node2 }\n );\n function inner_clicked(v2) {\n if (!node2) {\n return;\n }\n var kV = Object.values(LiteGraph.NODE_MODES).indexOf(v2);\n var fApplyMultiNode = function(node3) {\n if (kV >= 0 && LiteGraph.NODE_MODES[kV])\n node3.changeMode(kV);\n else {\n console.warn(\"unexpected mode: \" + v2);\n node3.changeMode(LiteGraph.ALWAYS);\n }\n };\n var graphcanvas = LGraphCanvas.active_canvas;\n if (!graphcanvas.selected_nodes || Object.keys(graphcanvas.selected_nodes).length <= 1) {\n fApplyMultiNode(node2);\n } else {\n for (var i2 in graphcanvas.selected_nodes) {\n fApplyMultiNode(graphcanvas.selected_nodes[i2]);\n }\n }\n }\n return false;\n };\n LGraphCanvas.onMenuNodeColors = function(value, options, e, menu, node2) {\n if (!node2) {\n throw \"no node for color\";\n }\n var values2 = [];\n values2.push({\n value: null,\n content: \"No color\"\n });\n for (var i2 in LGraphCanvas.node_colors) {\n var color = LGraphCanvas.node_colors[i2];\n var value = {\n value: i2,\n content: \"\" + i2 + \"\"\n };\n values2.push(value);\n }\n new LiteGraph.ContextMenu(values2, {\n event: e,\n callback: inner_clicked,\n parentMenu: menu,\n node: node2\n });\n function inner_clicked(v2) {\n if (!node2) {\n return;\n }\n var color2 = v2.value ? LGraphCanvas.node_colors[v2.value] : null;\n var fApplyColor = function(node3) {\n if (color2) {\n if (node3.constructor === LiteGraph.LGraphGroup) {\n node3.color = color2.groupcolor;\n } else {\n node3.color = color2.color;\n node3.bgcolor = color2.bgcolor;\n }\n } else {\n delete node3.color;\n delete node3.bgcolor;\n }\n };\n var graphcanvas = LGraphCanvas.active_canvas;\n if (!graphcanvas.selected_nodes || Object.keys(graphcanvas.selected_nodes).length <= 1) {\n fApplyColor(node2);\n } else {\n for (var i3 in graphcanvas.selected_nodes) {\n fApplyColor(graphcanvas.selected_nodes[i3]);\n }\n }\n node2.setDirtyCanvas(true, true);\n }\n return false;\n };\n LGraphCanvas.onMenuNodeShapes = function(value, options, e, menu, node2) {\n if (!node2) {\n throw \"no node passed\";\n }\n new LiteGraph.ContextMenu(LiteGraph.VALID_SHAPES, {\n event: e,\n callback: inner_clicked,\n parentMenu: menu,\n node: node2\n });\n function inner_clicked(v2) {\n if (!node2) {\n return;\n }\n node2.graph.beforeChange(\n /*?*/\n );\n var fApplyMultiNode = function(node3) {\n node3.shape = v2;\n };\n var graphcanvas = LGraphCanvas.active_canvas;\n if (!graphcanvas.selected_nodes || Object.keys(graphcanvas.selected_nodes).length <= 1) {\n fApplyMultiNode(node2);\n } else {\n for (var i2 in graphcanvas.selected_nodes) {\n fApplyMultiNode(graphcanvas.selected_nodes[i2]);\n }\n }\n node2.graph.afterChange(\n /*?*/\n );\n node2.setDirtyCanvas(true);\n }\n return false;\n };\n LGraphCanvas.onMenuNodeRemove = function(value, options, e, menu, node2) {\n if (!node2) {\n throw \"no node passed\";\n }\n var graph = node2.graph;\n graph.beforeChange();\n var fApplyMultiNode = function(node3) {\n if (node3.removable === false) {\n return;\n }\n graph.remove(node3);\n };\n var graphcanvas = LGraphCanvas.active_canvas;\n if (!graphcanvas.selected_nodes || Object.keys(graphcanvas.selected_nodes).length <= 1) {\n fApplyMultiNode(node2);\n } else {\n for (var i2 in graphcanvas.selected_nodes) {\n fApplyMultiNode(graphcanvas.selected_nodes[i2]);\n }\n }\n graph.afterChange();\n node2.setDirtyCanvas(true, true);\n };\n LGraphCanvas.onMenuNodeToSubgraph = function(value, options, e, menu, node2) {\n var graph = node2.graph;\n var graphcanvas = LGraphCanvas.active_canvas;\n if (!graphcanvas)\n return;\n var nodes_list = Object.values(graphcanvas.selected_nodes || {});\n if (!nodes_list.length)\n nodes_list = [node2];\n var subgraph_node = LiteGraph.createNode(\"graph/subgraph\");\n subgraph_node.pos = node2.pos.concat();\n graph.add(subgraph_node);\n subgraph_node.buildFromNodes(nodes_list);\n graphcanvas.deselectAllNodes();\n node2.setDirtyCanvas(true, true);\n };\n LGraphCanvas.onMenuNodeClone = function(value, options, e, menu, node2) {\n node2.graph.beforeChange();\n var newSelected = {};\n var fApplyMultiNode = function(node3) {\n if (node3.clonable === false) {\n return;\n }\n var newnode = node3.clone();\n if (!newnode) {\n return;\n }\n newnode.pos = [node3.pos[0] + 5, node3.pos[1] + 5];\n node3.graph.add(newnode);\n newSelected[newnode.id] = newnode;\n };\n var graphcanvas = LGraphCanvas.active_canvas;\n if (!graphcanvas.selected_nodes || Object.keys(graphcanvas.selected_nodes).length <= 1) {\n fApplyMultiNode(node2);\n } else {\n for (var i2 in graphcanvas.selected_nodes) {\n fApplyMultiNode(graphcanvas.selected_nodes[i2]);\n }\n }\n if (Object.keys(newSelected).length) {\n graphcanvas.selectNodes(newSelected);\n }\n node2.graph.afterChange();\n node2.setDirtyCanvas(true, true);\n };\n LGraphCanvas.node_colors = {\n red: { color: \"#322\", bgcolor: \"#533\", groupcolor: \"#A88\" },\n brown: { color: \"#332922\", bgcolor: \"#593930\", groupcolor: \"#b06634\" },\n green: { color: \"#232\", bgcolor: \"#353\", groupcolor: \"#8A8\" },\n blue: { color: \"#223\", bgcolor: \"#335\", groupcolor: \"#88A\" },\n pale_blue: {\n color: \"#2a363b\",\n bgcolor: \"#3f5159\",\n groupcolor: \"#3f789e\"\n },\n cyan: { color: \"#233\", bgcolor: \"#355\", groupcolor: \"#8AA\" },\n purple: { color: \"#323\", bgcolor: \"#535\", groupcolor: \"#a1309b\" },\n yellow: { color: \"#432\", bgcolor: \"#653\", groupcolor: \"#b58b2a\" },\n black: { color: \"#222\", bgcolor: \"#000\", groupcolor: \"#444\" }\n };\n LGraphCanvas.prototype.getCanvasMenuOptions = function() {\n var options = null;\n if (this.getMenuOptions) {\n options = this.getMenuOptions();\n } else {\n options = [\n {\n content: \"Add Node\",\n has_submenu: true,\n callback: LGraphCanvas.onMenuAdd\n },\n { content: \"Add Group\", callback: LGraphCanvas.onGroupAdd }\n //{ content: \"Arrange\", callback: that.graph.arrange },\n //{content:\"Collapse All\", callback: LGraphCanvas.onMenuCollapseAll }\n ];\n if (Object.keys(this.selected_nodes).length > 1) {\n options.push({\n content: \"Align\",\n has_submenu: true,\n callback: LGraphCanvas.onGroupAlign\n });\n }\n if (this._graph_stack && this._graph_stack.length > 0) {\n options.push(null, {\n content: \"Close subgraph\",\n callback: this.closeSubgraph.bind(this)\n });\n }\n }\n if (this.getExtraMenuOptions) {\n var extra = this.getExtraMenuOptions(this, options);\n if (extra) {\n options = options.concat(extra);\n }\n }\n return options;\n };\n LGraphCanvas.prototype.getNodeMenuOptions = function(node2) {\n var _a;\n var options = null;\n if (node2.getMenuOptions) {\n options = node2.getMenuOptions(this);\n } else {\n options = [\n {\n content: \"Inputs\",\n has_submenu: true,\n disabled: true,\n callback: LGraphCanvas.showMenuNodeOptionalInputs\n },\n {\n content: \"Outputs\",\n has_submenu: true,\n disabled: true,\n callback: LGraphCanvas.showMenuNodeOptionalOutputs\n },\n null,\n {\n content: \"Properties\",\n has_submenu: true,\n callback: LGraphCanvas.onShowMenuNodeProperties\n },\n {\n content: \"Properties Panel\",\n callback: function(item, options2, e, menu, node3) {\n LGraphCanvas.active_canvas.showShowNodePanel(node3);\n }\n },\n null,\n {\n content: \"Title\",\n callback: LGraphCanvas.onShowPropertyEditor\n },\n {\n content: \"Mode\",\n has_submenu: true,\n callback: LGraphCanvas.onMenuNodeMode\n }\n ];\n if (node2.resizable !== false) {\n options.push({\n content: \"Resize\",\n callback: LGraphCanvas.onMenuResizeNode\n });\n }\n options.push(\n {\n content: \"Collapse\",\n callback: LGraphCanvas.onMenuNodeCollapse\n },\n {\n content: ((_a = node2.flags) == null ? void 0 : _a.pinned) ? \"Unpin\" : \"Pin\",\n callback: LGraphCanvas.onMenuNodePin\n },\n {\n content: \"Colors\",\n has_submenu: true,\n callback: LGraphCanvas.onMenuNodeColors\n },\n {\n content: \"Shapes\",\n has_submenu: true,\n callback: LGraphCanvas.onMenuNodeShapes\n },\n null\n );\n }\n if (node2.onGetInputs) {\n var inputs = node2.onGetInputs();\n if (inputs && inputs.length) {\n options[0].disabled = false;\n }\n }\n if (node2.onGetOutputs) {\n var outputs = node2.onGetOutputs();\n if (outputs && outputs.length) {\n options[1].disabled = false;\n }\n }\n if (node2.getExtraMenuOptions) {\n var extra = node2.getExtraMenuOptions(this, options);\n if (extra) {\n extra.push(null);\n options = extra.concat(options);\n }\n }\n if (node2.clonable !== false) {\n options.push({\n content: \"Clone\",\n callback: LGraphCanvas.onMenuNodeClone\n });\n }\n if (Object.keys(this.selected_nodes).length > 1) {\n options.push({\n content: \"Align Selected To\",\n has_submenu: true,\n callback: LGraphCanvas.onNodeAlign\n });\n }\n options.push(null, {\n content: \"Remove\",\n disabled: !(node2.removable !== false && !node2.block_delete),\n callback: LGraphCanvas.onMenuNodeRemove\n });\n if (node2.graph && node2.graph.onGetNodeMenuOptions) {\n node2.graph.onGetNodeMenuOptions(options, node2);\n }\n return options;\n };\n LGraphCanvas.prototype.getGroupMenuOptions = function(node2) {\n var o = [\n { content: \"Title\", callback: LGraphCanvas.onShowPropertyEditor },\n {\n content: \"Color\",\n has_submenu: true,\n callback: LGraphCanvas.onMenuNodeColors\n },\n {\n content: \"Font size\",\n property: \"font_size\",\n type: \"Number\",\n callback: LGraphCanvas.onShowPropertyEditor\n },\n null,\n { content: \"Remove\", callback: LGraphCanvas.onMenuNodeRemove }\n ];\n return o;\n };\n LGraphCanvas.prototype.processContextMenu = function(node2, event2) {\n var that2 = this;\n var canvas = LGraphCanvas.active_canvas;\n var ref_window2 = canvas.getCanvasWindow();\n var menu_info = null;\n var options = {\n event: event2,\n callback: inner_option_clicked,\n extra: node2\n };\n if (node2)\n options.title = node2.type;\n var slot = null;\n if (node2) {\n slot = node2.getSlotInPosition(event2.canvasX, event2.canvasY);\n LGraphCanvas.active_node = node2;\n }\n if (slot) {\n menu_info = [];\n if (node2.getSlotMenuOptions) {\n menu_info = node2.getSlotMenuOptions(slot);\n } else {\n if (slot && slot.output && slot.output.links && slot.output.links.length) {\n menu_info.push({ content: \"Disconnect Links\", slot });\n }\n var _slot = slot.input || slot.output;\n if (_slot.removable) {\n menu_info.push(\n _slot.locked ? \"Cannot remove\" : { content: \"Remove Slot\", slot }\n );\n }\n if (!_slot.nameLocked) {\n menu_info.push({ content: \"Rename Slot\", slot });\n }\n }\n options.title = (slot.input ? slot.input.type : slot.output.type) || \"*\";\n if (slot.input && slot.input.type == LiteGraph.ACTION) {\n options.title = \"Action\";\n }\n if (slot.output && slot.output.type == LiteGraph.EVENT) {\n options.title = \"Event\";\n }\n } else {\n if (node2) {\n menu_info = this.getNodeMenuOptions(node2);\n } else {\n menu_info = this.getCanvasMenuOptions();\n var group = this.graph.getGroupOnPos(\n event2.canvasX,\n event2.canvasY\n );\n if (group) {\n menu_info.push(null, {\n content: \"Edit Group\",\n has_submenu: true,\n submenu: {\n title: \"Group\",\n extra: group,\n options: this.getGroupMenuOptions(group)\n }\n });\n }\n }\n }\n if (!menu_info) {\n return;\n }\n new LiteGraph.ContextMenu(menu_info, options, ref_window2);\n function inner_option_clicked(v2, options2, e) {\n if (!v2) {\n return;\n }\n if (v2.content == \"Remove Slot\") {\n var info = v2.slot;\n node2.graph.beforeChange();\n if (info.input) {\n node2.removeInput(info.slot);\n } else if (info.output) {\n node2.removeOutput(info.slot);\n }\n node2.graph.afterChange();\n return;\n } else if (v2.content == \"Disconnect Links\") {\n var info = v2.slot;\n node2.graph.beforeChange();\n if (info.output) {\n node2.disconnectOutput(info.slot);\n } else if (info.input) {\n node2.disconnectInput(info.slot);\n }\n node2.graph.afterChange();\n return;\n } else if (v2.content == \"Rename Slot\") {\n var info = v2.slot;\n var slot_info = info.input ? node2.getInputInfo(info.slot) : node2.getOutputInfo(info.slot);\n var dialog = that2.createDialog(\n \"NameOK\",\n options2\n );\n var input = dialog.querySelector(\"input\");\n if (input && slot_info) {\n input.value = slot_info.label || \"\";\n }\n var inner = function() {\n node2.graph.beforeChange();\n if (input.value) {\n if (slot_info) {\n slot_info.label = input.value;\n }\n that2.setDirty(true);\n }\n dialog.close();\n node2.graph.afterChange();\n };\n dialog.querySelector(\"button\").addEventListener(\"click\", inner);\n input.addEventListener(\"keydown\", function(e2) {\n dialog.is_modified = true;\n if (e2.keyCode == 27) {\n dialog.close();\n } else if (e2.keyCode == 13) {\n inner();\n } else if (e2.keyCode != 13 && e2.target.localName != \"textarea\") {\n return;\n }\n e2.preventDefault();\n e2.stopPropagation();\n });\n input.focus();\n }\n }\n };\n if (typeof window != \"undefined\" && window.CanvasRenderingContext2D && !window.CanvasRenderingContext2D.prototype.roundRect) {\n window.CanvasRenderingContext2D.prototype.roundRect = function(x2, y2, w2, h, radius, radius_low) {\n var top_left_radius = 0;\n var top_right_radius = 0;\n var bottom_left_radius = 0;\n var bottom_right_radius = 0;\n if (radius === 0) {\n this.rect(x2, y2, w2, h);\n return;\n }\n if (radius_low === void 0)\n radius_low = radius;\n if (radius != null && radius.constructor === Array) {\n if (radius.length == 1)\n top_left_radius = top_right_radius = bottom_left_radius = bottom_right_radius = radius[0];\n else if (radius.length == 2) {\n top_left_radius = bottom_right_radius = radius[0];\n top_right_radius = bottom_left_radius = radius[1];\n } else if (radius.length == 4) {\n top_left_radius = radius[0];\n top_right_radius = radius[1];\n bottom_left_radius = radius[2];\n bottom_right_radius = radius[3];\n } else\n return;\n } else {\n top_left_radius = radius || 0;\n top_right_radius = radius || 0;\n bottom_left_radius = radius_low || 0;\n bottom_right_radius = radius_low || 0;\n }\n this.moveTo(x2 + top_left_radius, y2);\n this.lineTo(x2 + w2 - top_right_radius, y2);\n this.quadraticCurveTo(x2 + w2, y2, x2 + w2, y2 + top_right_radius);\n this.lineTo(x2 + w2, y2 + h - bottom_right_radius);\n this.quadraticCurveTo(\n x2 + w2,\n y2 + h,\n x2 + w2 - bottom_right_radius,\n y2 + h\n );\n this.lineTo(x2 + bottom_right_radius, y2 + h);\n this.quadraticCurveTo(x2, y2 + h, x2, y2 + h - bottom_left_radius);\n this.lineTo(x2, y2 + bottom_left_radius);\n this.quadraticCurveTo(x2, y2, x2 + top_left_radius, y2);\n };\n }\n function compareObjects(a, b) {\n for (var i2 in a) {\n if (a[i2] != b[i2]) {\n return false;\n }\n }\n return true;\n }\n LiteGraph.compareObjects = compareObjects;\n function distance(a, b) {\n return Math.sqrt(\n (b[0] - a[0]) * (b[0] - a[0]) + (b[1] - a[1]) * (b[1] - a[1])\n );\n }\n LiteGraph.distance = distance;\n function colorToString(c) {\n return \"rgba(\" + Math.round(c[0] * 255).toFixed() + \",\" + Math.round(c[1] * 255).toFixed() + \",\" + Math.round(c[2] * 255).toFixed() + \",\" + (c.length == 4 ? c[3].toFixed(2) : \"1.0\") + \")\";\n }\n LiteGraph.colorToString = colorToString;\n function isInsideRectangle(x2, y2, left, top, width2, height) {\n if (left < x2 && left + width2 > x2 && top < y2 && top + height > y2) {\n return true;\n }\n return false;\n }\n LiteGraph.isInsideRectangle = isInsideRectangle;\n function growBounding(bounding, x2, y2) {\n if (x2 < bounding[0]) {\n bounding[0] = x2;\n } else if (x2 > bounding[2]) {\n bounding[2] = x2;\n }\n if (y2 < bounding[1]) {\n bounding[1] = y2;\n } else if (y2 > bounding[3]) {\n bounding[3] = y2;\n }\n }\n LiteGraph.growBounding = growBounding;\n function isInsideBounding(p, bb) {\n if (p[0] < bb[0][0] || p[1] < bb[0][1] || p[0] > bb[1][0] || p[1] > bb[1][1]) {\n return false;\n }\n return true;\n }\n LiteGraph.isInsideBounding = isInsideBounding;\n function overlapBounding(a, b) {\n var A_end_x = a[0] + a[2];\n var A_end_y = a[1] + a[3];\n var B_end_x = b[0] + b[2];\n var B_end_y = b[1] + b[3];\n if (a[0] > B_end_x || a[1] > B_end_y || A_end_x < b[0] || A_end_y < b[1]) {\n return false;\n }\n return true;\n }\n LiteGraph.overlapBounding = overlapBounding;\n function hex2num(hex) {\n if (hex.charAt(0) == \"#\") {\n hex = hex.slice(1);\n }\n hex = hex.toUpperCase();\n var hex_alphabets = \"0123456789ABCDEF\";\n var value = new Array(3);\n var k = 0;\n var int1, int2;\n for (var i2 = 0; i2 < 6; i2 += 2) {\n int1 = hex_alphabets.indexOf(hex.charAt(i2));\n int2 = hex_alphabets.indexOf(hex.charAt(i2 + 1));\n value[k] = int1 * 16 + int2;\n k++;\n }\n return value;\n }\n LiteGraph.hex2num = hex2num;\n function num2hex(triplet) {\n var hex_alphabets = \"0123456789ABCDEF\";\n var hex = \"#\";\n var int1, int2;\n for (var i2 = 0; i2 < 3; i2++) {\n int1 = triplet[i2] / 16;\n int2 = triplet[i2] % 16;\n hex += hex_alphabets.charAt(int1) + hex_alphabets.charAt(int2);\n }\n return hex;\n }\n LiteGraph.num2hex = num2hex;\n function ContextMenu(values2, options) {\n options = options || {};\n this.options = options;\n var that2 = this;\n if (options.parentMenu) {\n if (options.parentMenu.constructor !== this.constructor) {\n console.error(\n \"parentMenu must be of class ContextMenu, ignoring it\"\n );\n options.parentMenu = null;\n } else {\n this.parentMenu = options.parentMenu;\n this.parentMenu.lock = true;\n this.parentMenu.current_submenu = this;\n }\n }\n var eventClass = null;\n if (options.event)\n eventClass = options.event.constructor.name;\n if (eventClass !== \"MouseEvent\" && eventClass !== \"CustomEvent\" && eventClass !== \"PointerEvent\") {\n console.error(\n \"Event passed to ContextMenu is not of type MouseEvent or CustomEvent. Ignoring it. (\" + eventClass + \")\"\n );\n options.event = null;\n }\n var root = document.createElement(\"div\");\n root.className = \"litegraph litecontextmenu litemenubar-panel\";\n if (options.className) {\n root.className += \" \" + options.className;\n }\n root.style.minWidth = 100;\n root.style.minHeight = 100;\n root.style.pointerEvents = \"none\";\n setTimeout(function() {\n root.style.pointerEvents = \"auto\";\n }, 100);\n LiteGraph.pointerListenerAdd(\n root,\n \"up\",\n function(e) {\n e.preventDefault();\n return true;\n },\n true\n );\n root.addEventListener(\n \"contextmenu\",\n function(e) {\n if (e.button != 2) {\n return false;\n }\n e.preventDefault();\n return false;\n },\n true\n );\n LiteGraph.pointerListenerAdd(\n root,\n \"down\",\n function(e) {\n if (e.button == 2) {\n that2.close();\n e.preventDefault();\n return true;\n }\n },\n true\n );\n function on_mouse_wheel(e) {\n var pos2 = parseInt(root.style.top);\n root.style.top = (pos2 + e.deltaY * options.scroll_speed).toFixed() + \"px\";\n e.preventDefault();\n return true;\n }\n if (!options.scroll_speed) {\n options.scroll_speed = 0.1;\n }\n root.addEventListener(\"wheel\", on_mouse_wheel, true);\n root.addEventListener(\"mousewheel\", on_mouse_wheel, true);\n this.root = root;\n if (options.title) {\n var element = document.createElement(\"div\");\n element.className = \"litemenu-title\";\n element.innerHTML = options.title;\n root.appendChild(element);\n }\n for (var i2 = 0; i2 < values2.length; i2++) {\n var name = values2.constructor == Array ? values2[i2] : i2;\n if (name != null && name.constructor !== String) {\n name = name.content === void 0 ? String(name) : name.content;\n }\n var value = values2[i2];\n this.addItem(name, value, options);\n }\n LiteGraph.pointerListenerAdd(root, \"enter\", function(e) {\n if (root.closing_timer) {\n clearTimeout(root.closing_timer);\n }\n });\n var root_document = document;\n if (options.event) {\n root_document = options.event.target.ownerDocument;\n }\n if (!root_document) {\n root_document = document;\n }\n if (root_document.fullscreenElement)\n root_document.fullscreenElement.appendChild(root);\n else\n root_document.body.appendChild(root);\n var left = options.left || 0;\n var top = options.top || 0;\n if (options.event) {\n left = options.event.clientX - 10;\n top = options.event.clientY - 10;\n if (options.title) {\n top -= 20;\n }\n if (options.parentMenu) {\n var rect = options.parentMenu.root.getBoundingClientRect();\n left = rect.left + rect.width;\n }\n var body_rect = document.body.getBoundingClientRect();\n var root_rect = root.getBoundingClientRect();\n if (body_rect.height == 0)\n console.error(\"document.body height is 0. That is dangerous, set html,body { height: 100%; }\");\n if (body_rect.width && left > body_rect.width - root_rect.width - 10) {\n left = body_rect.width - root_rect.width - 10;\n }\n if (body_rect.height && top > body_rect.height - root_rect.height - 10) {\n top = body_rect.height - root_rect.height - 10;\n }\n }\n root.style.left = left + \"px\";\n root.style.top = top + \"px\";\n if (options.scale) {\n root.style.transform = \"scale(\" + options.scale + \")\";\n }\n }\n ContextMenu.prototype.addItem = function(name, value, options) {\n var that2 = this;\n options = options || {};\n var element = document.createElement(\"div\");\n element.className = \"litemenu-entry submenu\";\n var disabled = false;\n if (value === null) {\n element.classList.add(\"separator\");\n } else {\n element.innerHTML = value && value.title ? value.title : name;\n element.value = value;\n element.setAttribute(\"role\", \"menuitem\");\n if (value) {\n if (value.disabled) {\n disabled = true;\n element.classList.add(\"disabled\");\n element.setAttribute(\"aria-disabled\", \"true\");\n }\n if (value.submenu || value.has_submenu) {\n element.classList.add(\"has_submenu\");\n element.setAttribute(\"aria-haspopup\", \"true\");\n element.setAttribute(\"aria-expanded\", \"false\");\n }\n }\n if (typeof value == \"function\") {\n element.dataset[\"value\"] = name;\n element.onclick_callback = value;\n } else {\n element.dataset[\"value\"] = value;\n }\n if (value.className) {\n element.className += \" \" + value.className;\n }\n }\n this.root.appendChild(element);\n if (!disabled) {\n element.addEventListener(\"click\", inner_onclick);\n }\n if (!disabled && options.autoopen) {\n LiteGraph.pointerListenerAdd(element, \"enter\", inner_over);\n }\n function setAriaExpanded() {\n const entries = that2.root.querySelectorAll(\"div.litemenu-entry.has_submenu\");\n if (entries) {\n for (let i2 = 0; i2 < entries.length; i2++) {\n entries[i2].setAttribute(\"aria-expanded\", \"false\");\n }\n }\n element.setAttribute(\"aria-expanded\", \"true\");\n }\n function inner_over(e) {\n var value2 = this.value;\n if (!value2 || !value2.has_submenu) {\n return;\n }\n inner_onclick.call(this, e);\n setAriaExpanded();\n }\n function inner_onclick(e) {\n var value2 = this.value;\n var close_parent = true;\n if (that2.current_submenu) {\n that2.current_submenu.close(e);\n }\n if ((value2 == null ? void 0 : value2.has_submenu) || (value2 == null ? void 0 : value2.submenu)) {\n setAriaExpanded();\n }\n if (options.callback) {\n var r = options.callback.call(\n this,\n value2,\n options,\n e,\n that2,\n options.node\n );\n if (r === true) {\n close_parent = false;\n }\n }\n if (value2) {\n if (value2.callback && !options.ignore_item_callbacks && value2.disabled !== true) {\n var r = value2.callback.call(\n this,\n value2,\n options,\n e,\n that2,\n options.extra\n );\n if (r === true) {\n close_parent = false;\n }\n }\n if (value2.submenu) {\n if (!value2.submenu.options) {\n throw \"ContextMenu submenu needs options\";\n }\n new that2.constructor(value2.submenu.options, {\n callback: value2.submenu.callback,\n event: e,\n parentMenu: that2,\n ignore_item_callbacks: value2.submenu.ignore_item_callbacks,\n title: value2.submenu.title,\n extra: value2.submenu.extra,\n autoopen: options.autoopen\n });\n close_parent = false;\n }\n }\n if (close_parent && !that2.lock) {\n that2.close();\n }\n }\n return element;\n };\n ContextMenu.prototype.close = function(e, ignore_parent_menu) {\n if (this.root.parentNode) {\n this.root.parentNode.removeChild(this.root);\n }\n if (this.parentMenu && !ignore_parent_menu) {\n this.parentMenu.lock = false;\n this.parentMenu.current_submenu = null;\n if (e === void 0) {\n this.parentMenu.close();\n } else if (e && !ContextMenu.isCursorOverElement(e, this.parentMenu.root)) {\n ContextMenu.trigger(this.parentMenu.root, LiteGraph.pointerevents_method + \"leave\", e);\n }\n }\n if (this.current_submenu) {\n this.current_submenu.close(e, true);\n }\n if (this.root.closing_timer) {\n clearTimeout(this.root.closing_timer);\n }\n };\n ContextMenu.trigger = function(element, event_name, params, origin) {\n var evt = document.createEvent(\"CustomEvent\");\n evt.initCustomEvent(event_name, true, true, params);\n evt.srcElement = origin;\n if (element.dispatchEvent) {\n element.dispatchEvent(evt);\n } else if (element.__events) {\n element.__events.dispatchEvent(evt);\n }\n return evt;\n };\n ContextMenu.prototype.getTopMenu = function() {\n if (this.options.parentMenu) {\n return this.options.parentMenu.getTopMenu();\n }\n return this;\n };\n ContextMenu.prototype.getFirstEvent = function() {\n if (this.options.parentMenu) {\n return this.options.parentMenu.getFirstEvent();\n }\n return this.options.event;\n };\n ContextMenu.isCursorOverElement = function(event2, element) {\n var left = event2.clientX;\n var top = event2.clientY;\n var rect = element.getBoundingClientRect();\n if (!rect) {\n return false;\n }\n if (top > rect.top && top < rect.top + rect.height && left > rect.left && left < rect.left + rect.width) {\n return true;\n }\n return false;\n };\n LiteGraph.ContextMenu = ContextMenu;\n LiteGraph.closeAllContextMenus = function(ref_window2) {\n ref_window2 = ref_window2 || window;\n var elements = ref_window2.document.querySelectorAll(\".litecontextmenu\");\n if (!elements.length) {\n return;\n }\n var result = [];\n for (var i2 = 0; i2 < elements.length; i2++) {\n result.push(elements[i2]);\n }\n for (var i2 = 0; i2 < result.length; i2++) {\n if (result[i2].close) {\n result[i2].close();\n } else if (result[i2].parentNode) {\n result[i2].parentNode.removeChild(result[i2]);\n }\n }\n };\n LiteGraph.extendClass = function(target, origin) {\n for (var i2 in origin) {\n if (target.hasOwnProperty(i2)) {\n continue;\n }\n target[i2] = origin[i2];\n }\n if (origin.prototype) {\n for (var i2 in origin.prototype) {\n if (!origin.prototype.hasOwnProperty(i2)) {\n continue;\n }\n if (target.prototype.hasOwnProperty(i2)) {\n continue;\n }\n if (origin.prototype.__lookupGetter__(i2)) {\n target.prototype.__defineGetter__(\n i2,\n origin.prototype.__lookupGetter__(i2)\n );\n } else {\n target.prototype[i2] = origin.prototype[i2];\n }\n if (origin.prototype.__lookupSetter__(i2)) {\n target.prototype.__defineSetter__(\n i2,\n origin.prototype.__lookupSetter__(i2)\n );\n }\n }\n }\n };\n function CurveEditor(points) {\n this.points = points;\n this.selected = -1;\n this.nearest = -1;\n this.size = null;\n this.must_update = true;\n this.margin = 5;\n }\n CurveEditor.sampleCurve = function(f, points) {\n if (!points)\n return;\n for (var i2 = 0; i2 < points.length - 1; ++i2) {\n var p = points[i2];\n var pn = points[i2 + 1];\n if (pn[0] < f)\n continue;\n var r = pn[0] - p[0];\n if (Math.abs(r) < 1e-5)\n return p[1];\n var local_f = (f - p[0]) / r;\n return p[1] * (1 - local_f) + pn[1] * local_f;\n }\n return 0;\n };\n CurveEditor.prototype.draw = function(ctx, size, graphcanvas, background_color, line_color, inactive) {\n var points = this.points;\n if (!points)\n return;\n this.size = size;\n var w2 = size[0] - this.margin * 2;\n var h = size[1] - this.margin * 2;\n line_color = line_color || \"#666\";\n ctx.save();\n ctx.translate(this.margin, this.margin);\n if (background_color) {\n ctx.fillStyle = \"#111\";\n ctx.fillRect(0, 0, w2, h);\n ctx.fillStyle = \"#222\";\n ctx.fillRect(w2 * 0.5, 0, 1, h);\n ctx.strokeStyle = \"#333\";\n ctx.strokeRect(0, 0, w2, h);\n }\n ctx.strokeStyle = line_color;\n if (inactive)\n ctx.globalAlpha = 0.5;\n ctx.beginPath();\n for (var i2 = 0; i2 < points.length; ++i2) {\n var p = points[i2];\n ctx.lineTo(p[0] * w2, (1 - p[1]) * h);\n }\n ctx.stroke();\n ctx.globalAlpha = 1;\n if (!inactive)\n for (var i2 = 0; i2 < points.length; ++i2) {\n var p = points[i2];\n ctx.fillStyle = this.selected == i2 ? \"#FFF\" : this.nearest == i2 ? \"#DDD\" : \"#AAA\";\n ctx.beginPath();\n ctx.arc(p[0] * w2, (1 - p[1]) * h, 2, 0, Math.PI * 2);\n ctx.fill();\n }\n ctx.restore();\n };\n CurveEditor.prototype.onMouseDown = function(localpos, graphcanvas) {\n var points = this.points;\n if (!points)\n return;\n if (localpos[1] < 0)\n return;\n var w2 = this.size[0] - this.margin * 2;\n var h = this.size[1] - this.margin * 2;\n var x2 = localpos[0] - this.margin;\n var y2 = localpos[1] - this.margin;\n var pos2 = [x2, y2];\n var max_dist = 30 / graphcanvas.ds.scale;\n this.selected = this.getCloserPoint(pos2, max_dist);\n if (this.selected == -1) {\n var point = [x2 / w2, 1 - y2 / h];\n points.push(point);\n points.sort(function(a, b) {\n return a[0] - b[0];\n });\n this.selected = points.indexOf(point);\n this.must_update = true;\n }\n if (this.selected != -1)\n return true;\n };\n CurveEditor.prototype.onMouseMove = function(localpos, graphcanvas) {\n var points = this.points;\n if (!points)\n return;\n var s = this.selected;\n if (s < 0)\n return;\n var x2 = (localpos[0] - this.margin) / (this.size[0] - this.margin * 2);\n var y2 = (localpos[1] - this.margin) / (this.size[1] - this.margin * 2);\n var curvepos = [localpos[0] - this.margin, localpos[1] - this.margin];\n var max_dist = 30 / graphcanvas.ds.scale;\n this._nearest = this.getCloserPoint(curvepos, max_dist);\n var point = points[s];\n if (point) {\n var is_edge_point = s == 0 || s == points.length - 1;\n if (!is_edge_point && (localpos[0] < -10 || localpos[0] > this.size[0] + 10 || localpos[1] < -10 || localpos[1] > this.size[1] + 10)) {\n points.splice(s, 1);\n this.selected = -1;\n return;\n }\n if (!is_edge_point)\n point[0] = clamp(x2, 0, 1);\n else\n point[0] = s == 0 ? 0 : 1;\n point[1] = 1 - clamp(y2, 0, 1);\n points.sort(function(a, b) {\n return a[0] - b[0];\n });\n this.selected = points.indexOf(point);\n this.must_update = true;\n }\n };\n CurveEditor.prototype.onMouseUp = function(localpos, graphcanvas) {\n this.selected = -1;\n return false;\n };\n CurveEditor.prototype.getCloserPoint = function(pos2, max_dist) {\n var points = this.points;\n if (!points)\n return -1;\n max_dist = max_dist || 30;\n var w2 = this.size[0] - this.margin * 2;\n var h = this.size[1] - this.margin * 2;\n var num = points.length;\n var p2 = [0, 0];\n var min_dist = 1e6;\n var closest = -1;\n for (var i2 = 0; i2 < num; ++i2) {\n var p = points[i2];\n p2[0] = p[0] * w2;\n p2[1] = (1 - p[1]) * h;\n if (p2[0] < pos2[0])\n ;\n var dist = vec2.distance(pos2, p2);\n if (dist > min_dist || dist > max_dist)\n continue;\n closest = i2;\n min_dist = dist;\n }\n return closest;\n };\n LiteGraph.CurveEditor = CurveEditor;\n LiteGraph.getParameterNames = function(func) {\n return (func + \"\").replace(/[/][/].*$/gm, \"\").replace(/\\s+/g, \"\").replace(/[/][*][^/*]*[*][/]/g, \"\").split(\"){\", 1)[0].replace(/^[^(]*[(]/, \"\").replace(/=[^,]+/g, \"\").split(\",\").filter(Boolean);\n };\n LiteGraph.pointerListenerAdd = function(oDOM, sEvIn, fCall, capture = false) {\n if (!oDOM || !oDOM.addEventListener || !sEvIn || typeof fCall !== \"function\") {\n return;\n }\n var sMethod = LiteGraph.pointerevents_method;\n var sEvent = sEvIn;\n if (sMethod == \"pointer\" && !window.PointerEvent) {\n console.warn(\"sMethod=='pointer' && !window.PointerEvent\");\n console.log(\"Converting pointer[\" + sEvent + \"] : down move up cancel enter TO touchstart touchmove touchend, etc ..\");\n switch (sEvent) {\n case \"down\": {\n sMethod = \"touch\";\n sEvent = \"start\";\n break;\n }\n case \"move\": {\n sMethod = \"touch\";\n break;\n }\n case \"up\": {\n sMethod = \"touch\";\n sEvent = \"end\";\n break;\n }\n case \"cancel\": {\n sMethod = \"touch\";\n break;\n }\n case \"enter\": {\n console.log(\"debug: Should I send a move event?\");\n break;\n }\n default: {\n console.warn(\"PointerEvent not available in this browser ? The event \" + sEvent + \" would not be called\");\n }\n }\n }\n switch (sEvent) {\n case \"down\":\n case \"up\":\n case \"move\":\n case \"over\":\n case \"out\":\n case \"enter\": {\n oDOM.addEventListener(sMethod + sEvent, fCall, capture);\n }\n case \"leave\":\n case \"cancel\":\n case \"gotpointercapture\":\n case \"lostpointercapture\": {\n if (sMethod != \"mouse\") {\n return oDOM.addEventListener(sMethod + sEvent, fCall, capture);\n }\n }\n default:\n return oDOM.addEventListener(sEvent, fCall, capture);\n }\n };\n LiteGraph.pointerListenerRemove = function(oDOM, sEvent, fCall, capture = false) {\n if (!oDOM || !oDOM.removeEventListener || !sEvent || typeof fCall !== \"function\") {\n return;\n }\n switch (sEvent) {\n case \"down\":\n case \"up\":\n case \"move\":\n case \"over\":\n case \"out\":\n case \"enter\": {\n if (LiteGraph.pointerevents_method == \"pointer\" || LiteGraph.pointerevents_method == \"mouse\") {\n oDOM.removeEventListener(LiteGraph.pointerevents_method + sEvent, fCall, capture);\n }\n }\n case \"leave\":\n case \"cancel\":\n case \"gotpointercapture\":\n case \"lostpointercapture\": {\n if (LiteGraph.pointerevents_method == \"pointer\") {\n return oDOM.removeEventListener(LiteGraph.pointerevents_method + sEvent, fCall, capture);\n }\n }\n default:\n return oDOM.removeEventListener(sEvent, fCall, capture);\n }\n };\n function clamp(v2, a, b) {\n return a > v2 ? a : b < v2 ? b : v2;\n }\n globalThis.clamp = clamp;\n if (typeof window != \"undefined\" && !window[\"requestAnimationFrame\"]) {\n window.requestAnimationFrame = window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function(callback) {\n window.setTimeout(callback, 1e3 / 60);\n };\n }\n})(globalExport);\nconst LiteGraph = globalExport.LiteGraph;\nconst LGraphES6 = globalExport.LGraph;\nconst LGraph = globalExport.LegacyLGraph;\nconst LLink = globalExport.LLink;\nconst LGraphNode = globalExport.LGraphNode;\nconst LGraphGroup = globalExport.LGraphGroup;\nconst DragAndScale = globalExport.DragAndScale;\nconst LGraphCanvas = globalExport.LGraphCanvas;\nconst ContextMenu = globalExport.ContextMenu;\nexport {\n ContextMenu,\n DragAndScale,\n LGraph,\n LGraphCanvas,\n LGraphES6,\n LGraphGroup,\n LGraphNode,\n LLink,\n LiteGraph\n};\n//# sourceMappingURL=litegraph.es.js.map\n","import { app, ANIM_PREVIEW_WIDGET } from './app'\r\nimport { LGraphCanvas, LGraphNode, LiteGraph } from '@comfyorg/litegraph'\r\nimport type { Vector4 } from '@comfyorg/litegraph'\r\n\r\nconst SIZE = Symbol()\r\n\r\ninterface Rect {\r\n height: number\r\n width: number\r\n x: number\r\n y: number\r\n}\r\n\r\nexport interface DOMWidget {\r\n type: string\r\n name: string\r\n computedHeight?: number\r\n element?: T\r\n options: any\r\n value?: any\r\n y?: number\r\n callback?: (value: any) => void\r\n draw?: (\r\n ctx: CanvasRenderingContext2D,\r\n node: LGraphNode,\r\n widgetWidth: number,\r\n y: number,\r\n widgetHeight: number\r\n ) => void\r\n onRemove?: () => void\r\n}\r\n\r\nfunction intersect(a: Rect, b: Rect): Vector4 | null {\r\n const x = Math.max(a.x, b.x)\r\n const num1 = Math.min(a.x + a.width, b.x + b.width)\r\n const y = Math.max(a.y, b.y)\r\n const num2 = Math.min(a.y + a.height, b.y + b.height)\r\n if (num1 >= x && num2 >= y) return [x, y, num1 - x, num2 - y]\r\n else return null\r\n}\r\n\r\nfunction getClipPath(node: LGraphNode, element: HTMLElement): string {\r\n const selectedNode: LGraphNode = Object.values(\r\n app.canvas.selected_nodes\r\n )[0] as LGraphNode\r\n if (selectedNode && selectedNode !== node) {\r\n const elRect = element.getBoundingClientRect()\r\n const MARGIN = 7\r\n const scale = app.canvas.ds.scale\r\n\r\n const bounding = selectedNode.getBounding()\r\n const intersection = intersect(\r\n {\r\n x: elRect.x / scale,\r\n y: elRect.y / scale,\r\n width: elRect.width / scale,\r\n height: elRect.height / scale\r\n },\r\n {\r\n x: selectedNode.pos[0] + app.canvas.ds.offset[0] - MARGIN,\r\n y:\r\n selectedNode.pos[1] +\r\n app.canvas.ds.offset[1] -\r\n LiteGraph.NODE_TITLE_HEIGHT -\r\n MARGIN,\r\n width: bounding[2] + MARGIN + MARGIN,\r\n height: bounding[3] + MARGIN + MARGIN\r\n }\r\n )\r\n\r\n if (!intersection) {\r\n return ''\r\n }\r\n\r\n const widgetRect = element.getBoundingClientRect()\r\n const clipX = elRect.left + intersection[0] - widgetRect.x / scale + 'px'\r\n const clipY = elRect.top + intersection[1] - widgetRect.y / scale + 'px'\r\n const clipWidth = intersection[2] + 'px'\r\n const clipHeight = intersection[3] + 'px'\r\n const path = `polygon(0% 0%, 0% 100%, ${clipX} 100%, ${clipX} ${clipY}, calc(${clipX} + ${clipWidth}) ${clipY}, calc(${clipX} + ${clipWidth}) calc(${clipY} + ${clipHeight}), ${clipX} calc(${clipY} + ${clipHeight}), ${clipX} 100%, 100% 100%, 100% 0%)`\r\n return path\r\n }\r\n return ''\r\n}\r\n\r\nfunction computeSize(size: [number, number]): void {\r\n if (this.widgets?.[0]?.last_y == null) return\r\n\r\n let y = this.widgets[0].last_y\r\n let freeSpace = size[1] - y\r\n\r\n let widgetHeight = 0\r\n let dom = []\r\n for (const w of this.widgets) {\r\n if (w.type === 'converted-widget') {\r\n // Ignore\r\n delete w.computedHeight\r\n } else if (w.computeSize) {\r\n widgetHeight += w.computeSize()[1] + 4\r\n } else if (w.element) {\r\n // Extract DOM widget size info\r\n const styles = getComputedStyle(w.element)\r\n let minHeight =\r\n w.options.getMinHeight?.() ??\r\n parseInt(styles.getPropertyValue('--comfy-widget-min-height'))\r\n let maxHeight =\r\n w.options.getMaxHeight?.() ??\r\n parseInt(styles.getPropertyValue('--comfy-widget-max-height'))\r\n\r\n let prefHeight =\r\n w.options.getHeight?.() ??\r\n styles.getPropertyValue('--comfy-widget-height')\r\n if (prefHeight.endsWith?.('%')) {\r\n prefHeight =\r\n size[1] *\r\n (parseFloat(prefHeight.substring(0, prefHeight.length - 1)) / 100)\r\n } else {\r\n prefHeight = parseInt(prefHeight)\r\n if (isNaN(minHeight)) {\r\n minHeight = prefHeight\r\n }\r\n }\r\n if (isNaN(minHeight)) {\r\n minHeight = 50\r\n }\r\n if (!isNaN(maxHeight)) {\r\n if (!isNaN(prefHeight)) {\r\n prefHeight = Math.min(prefHeight, maxHeight)\r\n } else {\r\n prefHeight = maxHeight\r\n }\r\n }\r\n dom.push({\r\n minHeight,\r\n prefHeight,\r\n w\r\n })\r\n } else {\r\n widgetHeight += LiteGraph.NODE_WIDGET_HEIGHT + 4\r\n }\r\n }\r\n\r\n freeSpace -= widgetHeight\r\n\r\n // Calculate sizes with all widgets at their min height\r\n const prefGrow = [] // Nodes that want to grow to their prefd size\r\n const canGrow = [] // Nodes that can grow to auto size\r\n let growBy = 0\r\n for (const d of dom) {\r\n freeSpace -= d.minHeight\r\n if (isNaN(d.prefHeight)) {\r\n canGrow.push(d)\r\n d.w.computedHeight = d.minHeight\r\n } else {\r\n const diff = d.prefHeight - d.minHeight\r\n if (diff > 0) {\r\n prefGrow.push(d)\r\n growBy += diff\r\n d.diff = diff\r\n } else {\r\n d.w.computedHeight = d.minHeight\r\n }\r\n }\r\n }\r\n\r\n if (this.imgs && !this.widgets.find((w) => w.name === ANIM_PREVIEW_WIDGET)) {\r\n // Allocate space for image\r\n freeSpace -= 220\r\n }\r\n\r\n this.freeWidgetSpace = freeSpace\r\n\r\n if (freeSpace < 0) {\r\n // Not enough space for all widgets so we need to grow\r\n size[1] -= freeSpace\r\n this.graph.setDirtyCanvas(true)\r\n } else {\r\n // Share the space between each\r\n const growDiff = freeSpace - growBy\r\n if (growDiff > 0) {\r\n // All pref sizes can be fulfilled\r\n freeSpace = growDiff\r\n for (const d of prefGrow) {\r\n d.w.computedHeight = d.prefHeight\r\n }\r\n } else {\r\n // We need to grow evenly\r\n const shared = -growDiff / prefGrow.length\r\n for (const d of prefGrow) {\r\n d.w.computedHeight = d.prefHeight - shared\r\n }\r\n freeSpace = 0\r\n }\r\n\r\n if (freeSpace > 0 && canGrow.length) {\r\n // Grow any that are auto height\r\n const shared = freeSpace / canGrow.length\r\n for (const d of canGrow) {\r\n d.w.computedHeight += shared\r\n }\r\n }\r\n }\r\n\r\n // Position each of the widgets\r\n for (const w of this.widgets) {\r\n w.y = y\r\n if (w.computedHeight) {\r\n y += w.computedHeight\r\n } else if (w.computeSize) {\r\n y += w.computeSize()[1] + 4\r\n } else {\r\n y += LiteGraph.NODE_WIDGET_HEIGHT + 4\r\n }\r\n }\r\n}\r\n\r\n// Override the compute visible nodes function to allow us to hide/show DOM elements when the node goes offscreen\r\nconst elementWidgets = new Set()\r\n//@ts-ignore\r\nconst computeVisibleNodes = LGraphCanvas.prototype.computeVisibleNodes\r\n//@ts-ignore\r\nLGraphCanvas.prototype.computeVisibleNodes = function (): LGraphNode[] {\r\n const visibleNodes = computeVisibleNodes.apply(this, arguments)\r\n // @ts-expect-error\r\n for (const node of app.graph._nodes) {\r\n if (elementWidgets.has(node)) {\r\n const hidden = visibleNodes.indexOf(node) === -1\r\n for (const w of node.widgets) {\r\n if (w.element) {\r\n w.element.hidden = hidden\r\n w.element.style.display = hidden ? 'none' : undefined\r\n if (hidden) {\r\n w.options.onHide?.(w)\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n return visibleNodes\r\n}\r\n\r\nlet enableDomClipping = true\r\n\r\nexport function addDomClippingSetting(): void {\r\n app.ui.settings.addSetting({\r\n id: 'Comfy.DOMClippingEnabled',\r\n name: 'Enable DOM element clipping (enabling may reduce performance)',\r\n type: 'boolean',\r\n defaultValue: enableDomClipping,\r\n onChange(value) {\r\n enableDomClipping = !!value\r\n }\r\n })\r\n}\r\n\r\n//@ts-ignore\r\nLGraphNode.prototype.addDOMWidget = function (\r\n name: string,\r\n type: string,\r\n element: HTMLElement,\r\n options: Record\r\n): DOMWidget {\r\n options = { hideOnZoom: true, selectOn: ['focus', 'click'], ...options }\r\n\r\n if (!element.parentElement) {\r\n app.canvasContainer.append(element)\r\n }\r\n element.hidden = true\r\n element.style.display = 'none'\r\n\r\n let mouseDownHandler\r\n if (element.blur) {\r\n mouseDownHandler = (event) => {\r\n if (!element.contains(event.target)) {\r\n element.blur()\r\n }\r\n }\r\n document.addEventListener('mousedown', mouseDownHandler)\r\n }\r\n\r\n const { nodeData } = this.constructor\r\n const tooltip = (nodeData?.input.required?.[name] ??\r\n nodeData?.input.optional?.[name])?.[1]?.tooltip\r\n if (tooltip && !element.title) {\r\n element.title = tooltip\r\n }\r\n\r\n const widget: DOMWidget = {\r\n type,\r\n name,\r\n get value() {\r\n return options.getValue?.() ?? undefined\r\n },\r\n set value(v) {\r\n options.setValue?.(v)\r\n widget.callback?.(widget.value)\r\n },\r\n draw: function (\r\n ctx: CanvasRenderingContext2D,\r\n node: LGraphNode,\r\n widgetWidth: number,\r\n y: number,\r\n widgetHeight: number\r\n ) {\r\n if (widget.computedHeight == null) {\r\n computeSize.call(node, node.size)\r\n }\r\n\r\n const hidden =\r\n node.flags?.collapsed ||\r\n (!!options.hideOnZoom && app.canvas.ds.scale < 0.5) ||\r\n widget.computedHeight <= 0 ||\r\n widget.type === 'converted-widget' ||\r\n widget.type === 'hidden'\r\n element.hidden = hidden\r\n element.style.display = hidden ? 'none' : null\r\n if (hidden) {\r\n widget.options.onHide?.(widget)\r\n return\r\n }\r\n\r\n const margin = 10\r\n const elRect = ctx.canvas.getBoundingClientRect()\r\n const transform = new DOMMatrix()\r\n .scaleSelf(\r\n elRect.width / ctx.canvas.width,\r\n elRect.height / ctx.canvas.height\r\n )\r\n .multiplySelf(ctx.getTransform())\r\n .translateSelf(margin, margin + y)\r\n\r\n const scale = new DOMMatrix().scaleSelf(transform.a, transform.d)\r\n\r\n Object.assign(element.style, {\r\n transformOrigin: '0 0',\r\n transform: scale,\r\n left: `${transform.a + transform.e}px`,\r\n top: `${transform.d + transform.f}px`,\r\n width: `${widgetWidth - margin * 2}px`,\r\n height: `${(widget.computedHeight ?? 50) - margin * 2}px`,\r\n position: 'absolute',\r\n // @ts-expect-error\r\n zIndex: app.graph._nodes.indexOf(node)\r\n })\r\n\r\n if (enableDomClipping) {\r\n element.style.clipPath = getClipPath(node, element)\r\n element.style.willChange = 'clip-path'\r\n }\r\n\r\n this.options.onDraw?.(widget)\r\n },\r\n element,\r\n options,\r\n onRemove() {\r\n if (mouseDownHandler) {\r\n document.removeEventListener('mousedown', mouseDownHandler)\r\n }\r\n element.remove()\r\n }\r\n }\r\n\r\n for (const evt of options.selectOn) {\r\n element.addEventListener(evt, () => {\r\n app.canvas.selectNode(this)\r\n app.canvas.bringToFront(this)\r\n })\r\n }\r\n\r\n this.addCustomWidget(widget)\r\n elementWidgets.add(this)\r\n\r\n const collapse = this.collapse\r\n this.collapse = function () {\r\n collapse.apply(this, arguments)\r\n if (this.flags?.collapsed) {\r\n element.hidden = true\r\n element.style.display = 'none'\r\n }\r\n }\r\n\r\n const onRemoved = this.onRemoved\r\n this.onRemoved = function () {\r\n element.remove()\r\n elementWidgets.delete(this)\r\n onRemoved?.apply(this, arguments)\r\n }\r\n\r\n if (!this[SIZE]) {\r\n this[SIZE] = true\r\n const onResize = this.onResize\r\n this.onResize = function (size) {\r\n options.beforeResize?.call(widget, this)\r\n computeSize.call(this, size)\r\n onResize?.apply(this, arguments)\r\n options.afterResize?.call(widget, this)\r\n }\r\n }\r\n\r\n return widget\r\n}\r\n","import { api } from './api'\r\nimport './domWidget'\r\nimport type { ComfyApp } from './app'\r\nimport type { IWidget, LGraphNode } from '@comfyorg/litegraph'\r\nimport { ComfyNodeDef } from '@/types/apiTypes'\r\n\r\nexport type ComfyWidgetConstructor = (\r\n node: LGraphNode,\r\n inputName: string,\r\n inputData: ComfyNodeDef,\r\n app?: ComfyApp,\r\n widgetName?: string\r\n) => { widget: IWidget; minWidth?: number; minHeight?: number }\r\n\r\nlet controlValueRunBefore = false\r\nexport function updateControlWidgetLabel(widget) {\r\n let replacement = 'after'\r\n let find = 'before'\r\n if (controlValueRunBefore) {\r\n ;[find, replacement] = [replacement, find]\r\n }\r\n widget.label = (widget.label ?? widget.name).replace(find, replacement)\r\n}\r\n\r\nconst IS_CONTROL_WIDGET = Symbol()\r\nconst HAS_EXECUTED = Symbol()\r\n\r\nfunction getNumberDefaults(\r\n inputData: ComfyNodeDef,\r\n defaultStep,\r\n precision,\r\n enable_rounding\r\n) {\r\n let defaultVal = inputData[1]['default']\r\n let { min, max, step, round } = inputData[1]\r\n\r\n if (defaultVal == undefined) defaultVal = 0\r\n if (min == undefined) min = 0\r\n if (max == undefined) max = 2048\r\n if (step == undefined) step = defaultStep\r\n // precision is the number of decimal places to show.\r\n // by default, display the the smallest number of decimal places such that changes of size step are visible.\r\n if (precision == undefined) {\r\n precision = Math.max(-Math.floor(Math.log10(step)), 0)\r\n }\r\n\r\n if (enable_rounding && (round == undefined || round === true)) {\r\n // by default, round the value to those decimal places shown.\r\n round = Math.round(1000000 * Math.pow(0.1, precision)) / 1000000\r\n }\r\n\r\n return {\r\n val: defaultVal,\r\n config: { min, max, step: 10.0 * step, round, precision }\r\n }\r\n}\r\n\r\nexport function addValueControlWidget(\r\n node,\r\n targetWidget,\r\n defaultValue = 'randomize',\r\n values,\r\n widgetName,\r\n inputData: ComfyNodeDef\r\n) {\r\n let name = inputData[1]?.control_after_generate\r\n if (typeof name !== 'string') {\r\n name = widgetName\r\n }\r\n const widgets = addValueControlWidgets(\r\n node,\r\n targetWidget,\r\n defaultValue,\r\n {\r\n addFilterList: false,\r\n controlAfterGenerateName: name\r\n },\r\n inputData\r\n )\r\n return widgets[0]\r\n}\r\n\r\nexport function addValueControlWidgets(\r\n node,\r\n targetWidget,\r\n defaultValue = 'randomize',\r\n options,\r\n inputData: ComfyNodeDef\r\n) {\r\n if (!defaultValue) defaultValue = 'randomize'\r\n if (!options) options = {}\r\n\r\n const getName = (defaultName, optionName) => {\r\n let name = defaultName\r\n if (options[optionName]) {\r\n name = options[optionName]\r\n } else if (typeof inputData?.[1]?.[defaultName] === 'string') {\r\n name = inputData?.[1]?.[defaultName]\r\n } else if (inputData?.[1]?.control_prefix) {\r\n name = inputData?.[1]?.control_prefix + ' ' + name\r\n }\r\n return name\r\n }\r\n\r\n const widgets = []\r\n const valueControl = node.addWidget(\r\n 'combo',\r\n getName('control_after_generate', 'controlAfterGenerateName'),\r\n defaultValue,\r\n function () {},\r\n {\r\n values: ['fixed', 'increment', 'decrement', 'randomize'],\r\n serialize: false // Don't include this in prompt.\r\n }\r\n )\r\n valueControl.tooltip =\r\n 'Allows the linked widget to be changed automatically, for example randomizing the noise seed.'\r\n valueControl[IS_CONTROL_WIDGET] = true\r\n updateControlWidgetLabel(valueControl)\r\n widgets.push(valueControl)\r\n\r\n const isCombo = targetWidget.type === 'combo'\r\n let comboFilter\r\n if (isCombo) {\r\n valueControl.options.values.push('increment-wrap')\r\n }\r\n if (isCombo && options.addFilterList !== false) {\r\n comboFilter = node.addWidget(\r\n 'string',\r\n getName('control_filter_list', 'controlFilterListName'),\r\n '',\r\n function () {},\r\n {\r\n serialize: false // Don't include this in prompt.\r\n }\r\n )\r\n updateControlWidgetLabel(comboFilter)\r\n comboFilter.tooltip =\r\n \"Allows for filtering the list of values when changing the value via the control generate mode. Allows for RegEx matches in the format /abc/ to only filter to values containing 'abc'.\"\r\n\r\n widgets.push(comboFilter)\r\n }\r\n\r\n const applyWidgetControl = () => {\r\n var v = valueControl.value\r\n\r\n if (isCombo && v !== 'fixed') {\r\n let values = targetWidget.options.values\r\n const filter = comboFilter?.value\r\n if (filter) {\r\n let check\r\n if (filter.startsWith('/') && filter.endsWith('/')) {\r\n try {\r\n const regex = new RegExp(filter.substring(1, filter.length - 1))\r\n check = (item) => regex.test(item)\r\n } catch (error) {\r\n console.error(\r\n 'Error constructing RegExp filter for node ' + node.id,\r\n filter,\r\n error\r\n )\r\n }\r\n }\r\n if (!check) {\r\n const lower = filter.toLocaleLowerCase()\r\n check = (item) => item.toLocaleLowerCase().includes(lower)\r\n }\r\n values = values.filter((item) => check(item))\r\n if (!values.length && targetWidget.options.values.length) {\r\n console.warn(\r\n 'Filter for node ' + node.id + ' has filtered out all items',\r\n filter\r\n )\r\n }\r\n }\r\n let current_index = values.indexOf(targetWidget.value)\r\n let current_length = values.length\r\n\r\n switch (v) {\r\n case 'increment':\r\n current_index += 1\r\n break\r\n case 'increment-wrap':\r\n current_index += 1\r\n if (current_index >= current_length) {\r\n current_index = 0\r\n }\r\n break\r\n case 'decrement':\r\n current_index -= 1\r\n break\r\n case 'randomize':\r\n current_index = Math.floor(Math.random() * current_length)\r\n break\r\n default:\r\n break\r\n }\r\n current_index = Math.max(0, current_index)\r\n current_index = Math.min(current_length - 1, current_index)\r\n if (current_index >= 0) {\r\n let value = values[current_index]\r\n targetWidget.value = value\r\n targetWidget.callback(value)\r\n }\r\n } else {\r\n //number\r\n let min = targetWidget.options.min\r\n let max = targetWidget.options.max\r\n // limit to something that javascript can handle\r\n max = Math.min(1125899906842624, max)\r\n min = Math.max(-1125899906842624, min)\r\n let range = (max - min) / (targetWidget.options.step / 10)\r\n\r\n //adjust values based on valueControl Behaviour\r\n switch (v) {\r\n case 'fixed':\r\n break\r\n case 'increment':\r\n targetWidget.value += targetWidget.options.step / 10\r\n break\r\n case 'decrement':\r\n targetWidget.value -= targetWidget.options.step / 10\r\n break\r\n case 'randomize':\r\n targetWidget.value =\r\n Math.floor(Math.random() * range) *\r\n (targetWidget.options.step / 10) +\r\n min\r\n break\r\n default:\r\n break\r\n }\r\n /*check if values are over or under their respective\r\n * ranges and set them to min or max.*/\r\n if (targetWidget.value < min) targetWidget.value = min\r\n\r\n if (targetWidget.value > max) targetWidget.value = max\r\n targetWidget.callback(targetWidget.value)\r\n }\r\n }\r\n\r\n valueControl.beforeQueued = () => {\r\n if (controlValueRunBefore) {\r\n // Don't run on first execution\r\n if (valueControl[HAS_EXECUTED]) {\r\n applyWidgetControl()\r\n }\r\n }\r\n valueControl[HAS_EXECUTED] = true\r\n }\r\n\r\n valueControl.afterQueued = () => {\r\n if (!controlValueRunBefore) {\r\n applyWidgetControl()\r\n }\r\n }\r\n\r\n return widgets\r\n}\r\n\r\nfunction seedWidget(node, inputName, inputData: ComfyNodeDef, app, widgetName) {\r\n const seed = createIntWidget(node, inputName, inputData, app, true)\r\n const seedControl = addValueControlWidget(\r\n node,\r\n seed.widget,\r\n 'randomize',\r\n undefined,\r\n widgetName,\r\n inputData\r\n )\r\n\r\n seed.widget.linkedWidgets = [seedControl]\r\n return seed\r\n}\r\n\r\nfunction createIntWidget(\r\n node,\r\n inputName,\r\n inputData: ComfyNodeDef,\r\n app,\r\n isSeedInput: boolean = false\r\n) {\r\n const control = inputData[1]?.control_after_generate\r\n if (!isSeedInput && control) {\r\n return seedWidget(\r\n node,\r\n inputName,\r\n inputData,\r\n app,\r\n typeof control === 'string' ? control : undefined\r\n )\r\n }\r\n\r\n let widgetType = isSlider(inputData[1]['display'], app)\r\n const { val, config } = getNumberDefaults(inputData, 1, 0, true)\r\n Object.assign(config, { precision: 0 })\r\n return {\r\n widget: node.addWidget(\r\n widgetType,\r\n inputName,\r\n val,\r\n function (v) {\r\n const s = this.options.step / 10\r\n let sh = this.options.min % s\r\n if (isNaN(sh)) {\r\n sh = 0\r\n }\r\n this.value = Math.round((v - sh) / s) * s + sh\r\n },\r\n config\r\n )\r\n }\r\n}\r\n\r\nfunction addMultilineWidget(node, name, opts, app) {\r\n const inputEl = document.createElement('textarea')\r\n inputEl.className = 'comfy-multiline-input'\r\n inputEl.value = opts.defaultVal\r\n inputEl.placeholder = opts.placeholder || name\r\n inputEl.spellcheck = opts.spellcheck || false\r\n\r\n const widget = node.addDOMWidget(name, 'customtext', inputEl, {\r\n getValue() {\r\n return inputEl.value\r\n },\r\n setValue(v) {\r\n inputEl.value = v\r\n }\r\n })\r\n widget.inputEl = inputEl\r\n\r\n inputEl.addEventListener('input', () => {\r\n widget.callback?.(widget.value)\r\n })\r\n\r\n return { minWidth: 400, minHeight: 200, widget }\r\n}\r\n\r\nfunction isSlider(display, app) {\r\n if (app.ui.settings.getSettingValue('Comfy.DisableSliders')) {\r\n return 'number'\r\n }\r\n\r\n return display === 'slider' ? 'slider' : 'number'\r\n}\r\n\r\nexport function initWidgets(app) {\r\n app.ui.settings.addSetting({\r\n id: 'Comfy.WidgetControlMode',\r\n name: 'Widget Value Control Mode',\r\n type: 'combo',\r\n defaultValue: 'after',\r\n options: ['before', 'after'],\r\n tooltip:\r\n 'Controls when widget values are updated (randomize/increment/decrement), either before the prompt is queued or after.',\r\n onChange(value) {\r\n controlValueRunBefore = value === 'before'\r\n for (const n of app.graph._nodes) {\r\n if (!n.widgets) continue\r\n for (const w of n.widgets) {\r\n if (w[IS_CONTROL_WIDGET]) {\r\n updateControlWidgetLabel(w)\r\n if (w.linkedWidgets) {\r\n for (const l of w.linkedWidgets) {\r\n updateControlWidgetLabel(l)\r\n }\r\n }\r\n }\r\n }\r\n }\r\n app.graph.setDirtyCanvas(true)\r\n }\r\n })\r\n}\r\n\r\nexport const ComfyWidgets: Record = {\r\n 'INT:seed': seedWidget,\r\n 'INT:noise_seed': seedWidget,\r\n FLOAT(node, inputName, inputData: ComfyNodeDef, app) {\r\n let widgetType: 'number' | 'slider' = isSlider(inputData[1]['display'], app)\r\n let precision = app.ui.settings.getSettingValue(\r\n 'Comfy.FloatRoundingPrecision'\r\n )\r\n let disable_rounding = app.ui.settings.getSettingValue(\r\n 'Comfy.DisableFloatRounding'\r\n )\r\n if (precision == 0) precision = undefined\r\n const { val, config } = getNumberDefaults(\r\n inputData,\r\n 0.5,\r\n precision,\r\n !disable_rounding\r\n )\r\n return {\r\n widget: node.addWidget(\r\n widgetType,\r\n inputName,\r\n val,\r\n function (v) {\r\n if (config.round) {\r\n this.value =\r\n Math.round((v + Number.EPSILON) / config.round) * config.round\r\n if (this.value > config.max) this.value = config.max\r\n if (this.value < config.min) this.value = config.min\r\n } else {\r\n this.value = v\r\n }\r\n },\r\n config\r\n )\r\n }\r\n },\r\n INT(node, inputName, inputData: ComfyNodeDef, app) {\r\n return createIntWidget(node, inputName, inputData, app)\r\n },\r\n BOOLEAN(node, inputName, inputData) {\r\n let defaultVal = false\r\n let options = {}\r\n if (inputData[1]) {\r\n if (inputData[1].default) defaultVal = inputData[1].default\r\n if (inputData[1].label_on) options['on'] = inputData[1].label_on\r\n if (inputData[1].label_off) options['off'] = inputData[1].label_off\r\n }\r\n return {\r\n widget: node.addWidget('toggle', inputName, defaultVal, () => {}, options)\r\n }\r\n },\r\n STRING(node, inputName, inputData: ComfyNodeDef, app) {\r\n const defaultVal = inputData[1].default || ''\r\n const multiline = !!inputData[1].multiline\r\n\r\n let res\r\n if (multiline) {\r\n res = addMultilineWidget(\r\n node,\r\n inputName,\r\n { defaultVal, ...inputData[1] },\r\n app\r\n )\r\n } else {\r\n res = {\r\n widget: node.addWidget('text', inputName, defaultVal, () => {}, {})\r\n }\r\n }\r\n\r\n if (inputData[1].dynamicPrompts != undefined)\r\n res.widget.dynamicPrompts = inputData[1].dynamicPrompts\r\n\r\n return res\r\n },\r\n COMBO(node, inputName, inputData: ComfyNodeDef) {\r\n const type = inputData[0]\r\n let defaultValue = type[0]\r\n if (inputData[1] && inputData[1].default) {\r\n defaultValue = inputData[1].default\r\n }\r\n const res = {\r\n widget: node.addWidget('combo', inputName, defaultValue, () => {}, {\r\n values: type\r\n })\r\n }\r\n if (inputData[1]?.control_after_generate) {\r\n // TODO make combo handle a widget node type?\r\n res.widget.linkedWidgets = addValueControlWidgets(\r\n node,\r\n res.widget,\r\n undefined,\r\n undefined,\r\n inputData\r\n )\r\n }\r\n return res\r\n },\r\n IMAGEUPLOAD(\r\n node: LGraphNode,\r\n inputName: string,\r\n inputData: ComfyNodeDef,\r\n app\r\n ) {\r\n // TODO make image upload handle a custom node type?\r\n const imageWidget = node.widgets.find(\r\n (w) => w.name === (inputData[1]?.widget ?? 'image')\r\n )\r\n let uploadWidget\r\n\r\n function showImage(name) {\r\n const img = new Image()\r\n img.onload = () => {\r\n // @ts-expect-error\r\n node.imgs = [img]\r\n app.graph.setDirtyCanvas(true)\r\n }\r\n let folder_separator = name.lastIndexOf('/')\r\n let subfolder = ''\r\n if (folder_separator > -1) {\r\n subfolder = name.substring(0, folder_separator)\r\n name = name.substring(folder_separator + 1)\r\n }\r\n img.src = api.apiURL(\r\n `/view?filename=${encodeURIComponent(name)}&type=input&subfolder=${subfolder}${app.getPreviewFormatParam()}${app.getRandParam()}`\r\n )\r\n // @ts-expect-error\r\n node.setSizeForImage?.()\r\n }\r\n\r\n var default_value = imageWidget.value\r\n Object.defineProperty(imageWidget, 'value', {\r\n set: function (value) {\r\n this._real_value = value\r\n },\r\n\r\n get: function () {\r\n if (!this._real_value) {\r\n return default_value\r\n }\r\n\r\n let value = this._real_value\r\n if (value.filename) {\r\n let real_value = value\r\n value = ''\r\n if (real_value.subfolder) {\r\n value = real_value.subfolder + '/'\r\n }\r\n\r\n value += real_value.filename\r\n\r\n if (real_value.type && real_value.type !== 'input')\r\n value += ` [${real_value.type}]`\r\n }\r\n return value\r\n }\r\n })\r\n\r\n // Add our own callback to the combo widget to render an image when it changes\r\n // TODO: Explain this?\r\n // @ts-expect-error\r\n const cb = node.callback\r\n imageWidget.callback = function () {\r\n showImage(imageWidget.value)\r\n if (cb) {\r\n return cb.apply(this, arguments)\r\n }\r\n }\r\n\r\n // On load if we have a value then render the image\r\n // The value isnt set immediately so we need to wait a moment\r\n // No change callbacks seem to be fired on initial setting of the value\r\n requestAnimationFrame(() => {\r\n if (imageWidget.value) {\r\n showImage(imageWidget.value)\r\n }\r\n })\r\n\r\n async function uploadFile(file, updateNode, pasted = false) {\r\n try {\r\n // Wrap file in formdata so it includes filename\r\n const body = new FormData()\r\n body.append('image', file)\r\n if (pasted) body.append('subfolder', 'pasted')\r\n const resp = await api.fetchApi('/upload/image', {\r\n method: 'POST',\r\n body\r\n })\r\n\r\n if (resp.status === 200) {\r\n const data = await resp.json()\r\n // Add the file to the dropdown list and update the widget value\r\n let path = data.name\r\n if (data.subfolder) path = data.subfolder + '/' + path\r\n\r\n if (!imageWidget.options.values.includes(path)) {\r\n imageWidget.options.values.push(path)\r\n }\r\n\r\n if (updateNode) {\r\n showImage(path)\r\n imageWidget.value = path\r\n }\r\n } else {\r\n alert(resp.status + ' - ' + resp.statusText)\r\n }\r\n } catch (error) {\r\n alert(error)\r\n }\r\n }\r\n\r\n const fileInput = document.createElement('input')\r\n Object.assign(fileInput, {\r\n type: 'file',\r\n accept: 'image/jpeg,image/png,image/webp',\r\n style: 'display: none',\r\n onchange: async () => {\r\n if (fileInput.files.length) {\r\n await uploadFile(fileInput.files[0], true)\r\n }\r\n }\r\n })\r\n document.body.append(fileInput)\r\n\r\n // Create the button widget for selecting the files\r\n uploadWidget = node.addWidget('button', inputName, 'image', () => {\r\n fileInput.click()\r\n })\r\n uploadWidget.label = 'choose file to upload'\r\n uploadWidget.serialize = false\r\n\r\n // Add handler to check if an image is being dragged over our node\r\n // @ts-expect-error\r\n node.onDragOver = function (e) {\r\n if (e.dataTransfer && e.dataTransfer.items) {\r\n const image = [...e.dataTransfer.items].find((f) => f.kind === 'file')\r\n return !!image\r\n }\r\n\r\n return false\r\n }\r\n\r\n // On drop upload files\r\n // @ts-expect-error\r\n node.onDragDrop = function (e) {\r\n console.log('onDragDrop called')\r\n let handled = false\r\n for (const file of e.dataTransfer.files) {\r\n if (file.type.startsWith('image/')) {\r\n uploadFile(file, !handled) // Dont await these, any order is fine, only update on first one\r\n handled = true\r\n }\r\n }\r\n\r\n return handled\r\n }\r\n\r\n // @ts-expect-error\r\n node.pasteFile = function (file) {\r\n if (file.type.startsWith('image/')) {\r\n const is_pasted =\r\n file.name === 'image.png' && file.lastModified - Date.now() < 2000\r\n uploadFile(file, true, is_pasted)\r\n return true\r\n }\r\n return false\r\n }\r\n\r\n return { widget: uploadWidget }\r\n }\r\n}\r\n","import type { ComfyWorkflowJSON } from '@/types/comfyWorkflow'\r\n\r\nexport const defaultGraph: ComfyWorkflowJSON = {\r\n last_node_id: 9,\r\n last_link_id: 9,\r\n nodes: [\r\n {\r\n id: 7,\r\n type: 'CLIPTextEncode',\r\n pos: [413, 389],\r\n size: [425.27801513671875, 180.6060791015625],\r\n flags: {},\r\n order: 3,\r\n mode: 0,\r\n inputs: [{ name: 'clip', type: 'CLIP', link: 5 }],\r\n outputs: [\r\n {\r\n name: 'CONDITIONING',\r\n type: 'CONDITIONING',\r\n links: [6],\r\n slot_index: 0\r\n }\r\n ],\r\n properties: {},\r\n widgets_values: ['text, watermark']\r\n },\r\n {\r\n id: 6,\r\n type: 'CLIPTextEncode',\r\n pos: [415, 186],\r\n size: [422.84503173828125, 164.31304931640625],\r\n flags: {},\r\n order: 2,\r\n mode: 0,\r\n inputs: [{ name: 'clip', type: 'CLIP', link: 3 }],\r\n outputs: [\r\n {\r\n name: 'CONDITIONING',\r\n type: 'CONDITIONING',\r\n links: [4],\r\n slot_index: 0\r\n }\r\n ],\r\n properties: {},\r\n widgets_values: [\r\n 'beautiful scenery nature glass bottle landscape, , purple galaxy bottle,'\r\n ]\r\n },\r\n {\r\n id: 5,\r\n type: 'EmptyLatentImage',\r\n pos: [473, 609],\r\n size: [315, 106],\r\n flags: {},\r\n order: 1,\r\n mode: 0,\r\n outputs: [{ name: 'LATENT', type: 'LATENT', links: [2], slot_index: 0 }],\r\n properties: {},\r\n widgets_values: [512, 512, 1]\r\n },\r\n {\r\n id: 3,\r\n type: 'KSampler',\r\n pos: [863, 186],\r\n size: [315, 262],\r\n flags: {},\r\n order: 4,\r\n mode: 0,\r\n inputs: [\r\n { name: 'model', type: 'MODEL', link: 1 },\r\n { name: 'positive', type: 'CONDITIONING', link: 4 },\r\n { name: 'negative', type: 'CONDITIONING', link: 6 },\r\n { name: 'latent_image', type: 'LATENT', link: 2 }\r\n ],\r\n outputs: [{ name: 'LATENT', type: 'LATENT', links: [7], slot_index: 0 }],\r\n properties: {},\r\n widgets_values: [156680208700286, true, 20, 8, 'euler', 'normal', 1]\r\n },\r\n {\r\n id: 8,\r\n type: 'VAEDecode',\r\n pos: [1209, 188],\r\n size: [210, 46],\r\n flags: {},\r\n order: 5,\r\n mode: 0,\r\n inputs: [\r\n { name: 'samples', type: 'LATENT', link: 7 },\r\n { name: 'vae', type: 'VAE', link: 8 }\r\n ],\r\n outputs: [{ name: 'IMAGE', type: 'IMAGE', links: [9], slot_index: 0 }],\r\n properties: {}\r\n },\r\n {\r\n id: 9,\r\n type: 'SaveImage',\r\n pos: [1451, 189],\r\n size: [210, 26],\r\n flags: {},\r\n order: 6,\r\n mode: 0,\r\n inputs: [{ name: 'images', type: 'IMAGE', link: 9 }],\r\n properties: {}\r\n },\r\n {\r\n id: 4,\r\n type: 'CheckpointLoaderSimple',\r\n pos: [26, 474],\r\n size: [315, 98],\r\n flags: {},\r\n order: 0,\r\n mode: 0,\r\n outputs: [\r\n { name: 'MODEL', type: 'MODEL', links: [1], slot_index: 0 },\r\n { name: 'CLIP', type: 'CLIP', links: [3, 5], slot_index: 1 },\r\n { name: 'VAE', type: 'VAE', links: [8], slot_index: 2 }\r\n ],\r\n properties: {},\r\n widgets_values: ['v1-5-pruned-emaonly.ckpt']\r\n }\r\n ],\r\n links: [\r\n [1, 4, 0, 3, 0, 'MODEL'],\r\n [2, 5, 0, 3, 3, 'LATENT'],\r\n [3, 4, 1, 6, 0, 'CLIP'],\r\n [4, 6, 0, 3, 1, 'CONDITIONING'],\r\n [5, 4, 1, 7, 0, 'CLIP'],\r\n [6, 7, 0, 3, 2, 'CONDITIONING'],\r\n [7, 3, 0, 8, 0, 'LATENT'],\r\n [8, 4, 2, 8, 1, 'VAE'],\r\n [9, 8, 0, 9, 0, 'IMAGE']\r\n ],\r\n groups: [],\r\n config: {},\r\n extra: {},\r\n version: 0.4,\r\n models: [\r\n {\r\n name: 'v1-5-pruned-emaonly.ckpt',\r\n url: 'https://huggingface.co/runwayml/stable-diffusion-v1-5/resolve/main/v1-5-pruned-emaonly.ckpt',\r\n hash: 'cc6cb27103417325ff94f52b7a5d2dde45a7515b25c255d8e396c90014281516',\r\n hash_type: 'SHA256',\r\n directory: 'checkpoints'\r\n }\r\n ]\r\n}\r\n","export function getFromPngBuffer(buffer: ArrayBuffer) {\r\n // Get the PNG data as a Uint8Array\r\n const pngData = new Uint8Array(buffer)\r\n const dataView = new DataView(pngData.buffer)\r\n\r\n // Check that the PNG signature is present\r\n if (dataView.getUint32(0) !== 0x89504e47) {\r\n console.error('Not a valid PNG file')\r\n return\r\n }\r\n\r\n // Start searching for chunks after the PNG signature\r\n let offset = 8\r\n let txt_chunks: Record = {}\r\n // Loop through the chunks in the PNG file\r\n while (offset < pngData.length) {\r\n // Get the length of the chunk\r\n const length = dataView.getUint32(offset)\r\n // Get the chunk type\r\n const type = String.fromCharCode(...pngData.slice(offset + 4, offset + 8))\r\n if (type === 'tEXt' || type == 'comf' || type === 'iTXt') {\r\n // Get the keyword\r\n let keyword_end = offset + 8\r\n while (pngData[keyword_end] !== 0) {\r\n keyword_end++\r\n }\r\n const keyword = String.fromCharCode(\r\n ...pngData.slice(offset + 8, keyword_end)\r\n )\r\n // Get the text\r\n const contentArraySegment = pngData.slice(\r\n keyword_end + 1,\r\n offset + 8 + length\r\n )\r\n const contentJson = new TextDecoder('utf-8').decode(contentArraySegment)\r\n txt_chunks[keyword] = contentJson\r\n }\r\n\r\n offset += 12 + length\r\n }\r\n return txt_chunks\r\n}\r\n\r\nexport function getFromPngFile(file: File) {\r\n return new Promise>((r) => {\r\n const reader = new FileReader()\r\n reader.onload = (event) => {\r\n r(getFromPngBuffer(event.target.result as ArrayBuffer))\r\n }\r\n\r\n reader.readAsArrayBuffer(file)\r\n })\r\n}\r\n","export function getFromFlacBuffer(buffer: ArrayBuffer): Record {\r\n const dataView = new DataView(buffer)\r\n\r\n // Verify the FLAC signature\r\n const signature = String.fromCharCode(...new Uint8Array(buffer, 0, 4))\r\n if (signature !== 'fLaC') {\r\n console.error('Not a valid FLAC file')\r\n return\r\n }\r\n\r\n // Parse metadata blocks\r\n let offset = 4\r\n let vorbisComment = null\r\n while (offset < dataView.byteLength) {\r\n const isLastBlock = dataView.getUint8(offset) & 0x80\r\n const blockType = dataView.getUint8(offset) & 0x7f\r\n const blockSize = dataView.getUint32(offset, false) & 0xffffff\r\n offset += 4\r\n\r\n if (blockType === 4) {\r\n // Vorbis Comment block type\r\n vorbisComment = parseVorbisComment(\r\n new DataView(buffer, offset, blockSize)\r\n )\r\n }\r\n\r\n offset += blockSize\r\n if (isLastBlock) break\r\n }\r\n\r\n return vorbisComment\r\n}\r\n\r\nexport function getFromFlacFile(file: File): Promise> {\r\n return new Promise((r) => {\r\n const reader = new FileReader()\r\n reader.onload = function (event) {\r\n const arrayBuffer = event.target.result as ArrayBuffer\r\n r(getFromFlacBuffer(arrayBuffer))\r\n }\r\n reader.readAsArrayBuffer(file)\r\n })\r\n}\r\n\r\n// Function to parse the Vorbis Comment block\r\nfunction parseVorbisComment(dataView: DataView): Record {\r\n let offset = 0\r\n const vendorLength = dataView.getUint32(offset, true)\r\n offset += 4\r\n const vendorString = getString(dataView, offset, vendorLength)\r\n offset += vendorLength\r\n\r\n const userCommentListLength = dataView.getUint32(offset, true)\r\n offset += 4\r\n const comments = {}\r\n for (let i = 0; i < userCommentListLength; i++) {\r\n const commentLength = dataView.getUint32(offset, true)\r\n offset += 4\r\n const comment = getString(dataView, offset, commentLength)\r\n offset += commentLength\r\n\r\n const ind = comment.indexOf('=')\r\n const key = comment.substring(0, ind)\r\n\r\n comments[key] = comment.substring(ind + 1)\r\n }\r\n\r\n return comments\r\n}\r\n\r\nfunction getString(dataView: DataView, offset: number, length: number): string {\r\n let string = ''\r\n for (let i = 0; i < length; i++) {\r\n string += String.fromCharCode(dataView.getUint8(offset + i))\r\n }\r\n return string\r\n}\r\n","import { LiteGraph } from '@comfyorg/litegraph'\r\nimport { api } from './api'\r\nimport { getFromPngFile } from './metadata/png'\r\nimport { getFromFlacFile } from './metadata/flac'\r\n\r\n// Original functions left in for backwards compatibility\r\nexport function getPngMetadata(file: File): Promise> {\r\n return getFromPngFile(file)\r\n}\r\n\r\nexport function getFlacMetadata(file: File): Promise> {\r\n return getFromFlacFile(file)\r\n}\r\n\r\nfunction parseExifData(exifData) {\r\n // Check for the correct TIFF header (0x4949 for little-endian or 0x4D4D for big-endian)\r\n const isLittleEndian = String.fromCharCode(...exifData.slice(0, 2)) === 'II'\r\n\r\n // Function to read 16-bit and 32-bit integers from binary data\r\n function readInt(offset, isLittleEndian, length) {\r\n let arr = exifData.slice(offset, offset + length)\r\n if (length === 2) {\r\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength).getUint16(\r\n 0,\r\n isLittleEndian\r\n )\r\n } else if (length === 4) {\r\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength).getUint32(\r\n 0,\r\n isLittleEndian\r\n )\r\n }\r\n }\r\n\r\n // Read the offset to the first IFD (Image File Directory)\r\n const ifdOffset = readInt(4, isLittleEndian, 4)\r\n\r\n function parseIFD(offset) {\r\n const numEntries = readInt(offset, isLittleEndian, 2)\r\n const result = {}\r\n\r\n for (let i = 0; i < numEntries; i++) {\r\n const entryOffset = offset + 2 + i * 12\r\n const tag = readInt(entryOffset, isLittleEndian, 2)\r\n const type = readInt(entryOffset + 2, isLittleEndian, 2)\r\n const numValues = readInt(entryOffset + 4, isLittleEndian, 4)\r\n const valueOffset = readInt(entryOffset + 8, isLittleEndian, 4)\r\n\r\n // Read the value(s) based on the data type\r\n let value\r\n if (type === 2) {\r\n // ASCII string\r\n value = String.fromCharCode(\r\n ...exifData.slice(valueOffset, valueOffset + numValues - 1)\r\n )\r\n }\r\n\r\n result[tag] = value\r\n }\r\n\r\n return result\r\n }\r\n\r\n // Parse the first IFD\r\n const ifdData = parseIFD(ifdOffset)\r\n return ifdData\r\n}\r\n\r\nfunction splitValues(input) {\r\n var output = {}\r\n for (var key in input) {\r\n var value = input[key]\r\n var splitValues = value.split(':', 2)\r\n output[splitValues[0]] = splitValues[1]\r\n }\r\n return output\r\n}\r\n\r\nexport function getWebpMetadata(file) {\r\n return new Promise>((r) => {\r\n const reader = new FileReader()\r\n reader.onload = (event) => {\r\n const webp = new Uint8Array(event.target.result as ArrayBuffer)\r\n const dataView = new DataView(webp.buffer)\r\n\r\n // Check that the WEBP signature is present\r\n if (\r\n dataView.getUint32(0) !== 0x52494646 ||\r\n dataView.getUint32(8) !== 0x57454250\r\n ) {\r\n console.error('Not a valid WEBP file')\r\n r({})\r\n return\r\n }\r\n\r\n // Start searching for chunks after the WEBP signature\r\n let offset = 12\r\n let txt_chunks = {}\r\n // Loop through the chunks in the WEBP file\r\n while (offset < webp.length) {\r\n const chunk_length = dataView.getUint32(offset + 4, true)\r\n const chunk_type = String.fromCharCode(\r\n ...webp.slice(offset, offset + 4)\r\n )\r\n if (chunk_type === 'EXIF') {\r\n if (\r\n String.fromCharCode(...webp.slice(offset + 8, offset + 8 + 6)) ==\r\n 'Exif\\0\\0'\r\n ) {\r\n offset += 6\r\n }\r\n let data = parseExifData(\r\n webp.slice(offset + 8, offset + 8 + chunk_length)\r\n )\r\n for (var key in data) {\r\n var value = data[key] as string\r\n let index = value.indexOf(':')\r\n txt_chunks[value.slice(0, index)] = value.slice(index + 1)\r\n }\r\n break\r\n }\r\n\r\n offset += 8 + chunk_length\r\n }\r\n\r\n r(txt_chunks)\r\n }\r\n\r\n reader.readAsArrayBuffer(file)\r\n })\r\n}\r\n\r\nexport function getLatentMetadata(file) {\r\n return new Promise((r) => {\r\n const reader = new FileReader()\r\n reader.onload = (event) => {\r\n const safetensorsData = new Uint8Array(event.target.result as ArrayBuffer)\r\n const dataView = new DataView(safetensorsData.buffer)\r\n let header_size = dataView.getUint32(0, true)\r\n let offset = 8\r\n let header = JSON.parse(\r\n new TextDecoder().decode(\r\n safetensorsData.slice(offset, offset + header_size)\r\n )\r\n )\r\n r(header.__metadata__)\r\n }\r\n\r\n var slice = file.slice(0, 1024 * 1024 * 4)\r\n reader.readAsArrayBuffer(slice)\r\n })\r\n}\r\n\r\nexport async function importA1111(graph, parameters) {\r\n const p = parameters.lastIndexOf('\\nSteps:')\r\n if (p > -1) {\r\n const embeddings = await api.getEmbeddings()\r\n const opts = parameters\r\n .substr(p)\r\n .split('\\n')[1]\r\n .match(\r\n new RegExp('\\\\s*([^:]+:\\\\s*([^\"\\\\{].*?|\".*?\"|\\\\{.*?\\\\}))\\\\s*(,|$)', 'g')\r\n )\r\n .reduce((p, n) => {\r\n const s = n.split(':')\r\n if (s[1].endsWith(',')) {\r\n s[1] = s[1].substr(0, s[1].length - 1)\r\n }\r\n p[s[0].trim().toLowerCase()] = s[1].trim()\r\n return p\r\n }, {})\r\n const p2 = parameters.lastIndexOf('\\nNegative prompt:', p)\r\n if (p2 > -1) {\r\n let positive = parameters.substr(0, p2).trim()\r\n let negative = parameters.substring(p2 + 18, p).trim()\r\n\r\n const ckptNode = LiteGraph.createNode('CheckpointLoaderSimple')\r\n const clipSkipNode = LiteGraph.createNode('CLIPSetLastLayer')\r\n const positiveNode = LiteGraph.createNode('CLIPTextEncode')\r\n const negativeNode = LiteGraph.createNode('CLIPTextEncode')\r\n const samplerNode = LiteGraph.createNode('KSampler')\r\n const imageNode = LiteGraph.createNode('EmptyLatentImage')\r\n const vaeNode = LiteGraph.createNode('VAEDecode')\r\n const vaeLoaderNode = LiteGraph.createNode('VAELoader')\r\n const saveNode = LiteGraph.createNode('SaveImage')\r\n let hrSamplerNode = null\r\n let hrSteps = null\r\n\r\n const ceil64 = (v) => Math.ceil(v / 64) * 64\r\n\r\n const getWidget = (node, name) => {\r\n return node.widgets.find((w) => w.name === name)\r\n }\r\n\r\n const setWidgetValue = (node, name, value, isOptionPrefix?) => {\r\n const w = getWidget(node, name)\r\n if (isOptionPrefix) {\r\n const o = w.options.values.find((w) => w.startsWith(value))\r\n if (o) {\r\n w.value = o\r\n } else {\r\n console.warn(`Unknown value '${value}' for widget '${name}'`, node)\r\n w.value = value\r\n }\r\n } else {\r\n w.value = value\r\n }\r\n }\r\n\r\n const createLoraNodes = (clipNode, text, prevClip, prevModel) => {\r\n const loras = []\r\n text = text.replace(/]+)>/g, function (m, c) {\r\n const s = c.split(':')\r\n const weight = parseFloat(s[1])\r\n if (isNaN(weight)) {\r\n console.warn('Invalid LORA', m)\r\n } else {\r\n loras.push({ name: s[0], weight })\r\n }\r\n return ''\r\n })\r\n\r\n for (const l of loras) {\r\n const loraNode = LiteGraph.createNode('LoraLoader')\r\n graph.add(loraNode)\r\n setWidgetValue(loraNode, 'lora_name', l.name, true)\r\n setWidgetValue(loraNode, 'strength_model', l.weight)\r\n setWidgetValue(loraNode, 'strength_clip', l.weight)\r\n prevModel.node.connect(prevModel.index, loraNode, 0)\r\n prevClip.node.connect(prevClip.index, loraNode, 1)\r\n prevModel = { node: loraNode, index: 0 }\r\n prevClip = { node: loraNode, index: 1 }\r\n }\r\n\r\n prevClip.node.connect(1, clipNode, 0)\r\n prevModel.node.connect(0, samplerNode, 0)\r\n if (hrSamplerNode) {\r\n prevModel.node.connect(0, hrSamplerNode, 0)\r\n }\r\n\r\n return { text, prevModel, prevClip }\r\n }\r\n\r\n const replaceEmbeddings = (text) => {\r\n if (!embeddings.length) return text\r\n return text.replaceAll(\r\n new RegExp(\r\n '\\\\b(' +\r\n embeddings\r\n .map((e) => e.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'))\r\n .join('\\\\b|\\\\b') +\r\n ')\\\\b',\r\n 'ig'\r\n ),\r\n 'embedding:$1'\r\n )\r\n }\r\n\r\n const popOpt = (name) => {\r\n const v = opts[name]\r\n delete opts[name]\r\n return v\r\n }\r\n\r\n graph.clear()\r\n graph.add(ckptNode)\r\n graph.add(clipSkipNode)\r\n graph.add(positiveNode)\r\n graph.add(negativeNode)\r\n graph.add(samplerNode)\r\n graph.add(imageNode)\r\n graph.add(vaeNode)\r\n graph.add(vaeLoaderNode)\r\n graph.add(saveNode)\r\n\r\n ckptNode.connect(1, clipSkipNode, 0)\r\n clipSkipNode.connect(0, positiveNode, 0)\r\n clipSkipNode.connect(0, negativeNode, 0)\r\n ckptNode.connect(0, samplerNode, 0)\r\n positiveNode.connect(0, samplerNode, 1)\r\n negativeNode.connect(0, samplerNode, 2)\r\n imageNode.connect(0, samplerNode, 3)\r\n vaeNode.connect(0, saveNode, 0)\r\n samplerNode.connect(0, vaeNode, 0)\r\n vaeLoaderNode.connect(0, vaeNode, 1)\r\n\r\n const handlers = {\r\n model(v) {\r\n setWidgetValue(ckptNode, 'ckpt_name', v, true)\r\n },\r\n vae(v) {\r\n setWidgetValue(vaeLoaderNode, 'vae_name', v, true)\r\n },\r\n 'cfg scale'(v) {\r\n setWidgetValue(samplerNode, 'cfg', +v)\r\n },\r\n 'clip skip'(v) {\r\n setWidgetValue(clipSkipNode, 'stop_at_clip_layer', -v)\r\n },\r\n sampler(v) {\r\n let name = v.toLowerCase().replace('++', 'pp').replaceAll(' ', '_')\r\n if (name.includes('karras')) {\r\n name = name.replace('karras', '').replace(/_+$/, '')\r\n setWidgetValue(samplerNode, 'scheduler', 'karras')\r\n } else {\r\n setWidgetValue(samplerNode, 'scheduler', 'normal')\r\n }\r\n const w = getWidget(samplerNode, 'sampler_name')\r\n const o = w.options.values.find(\r\n (w) => w === name || w === 'sample_' + name\r\n )\r\n if (o) {\r\n setWidgetValue(samplerNode, 'sampler_name', o)\r\n }\r\n },\r\n size(v) {\r\n const wxh = v.split('x')\r\n const w = ceil64(+wxh[0])\r\n const h = ceil64(+wxh[1])\r\n const hrUp = popOpt('hires upscale')\r\n const hrSz = popOpt('hires resize')\r\n hrSteps = popOpt('hires steps')\r\n let hrMethod = popOpt('hires upscaler')\r\n\r\n setWidgetValue(imageNode, 'width', w)\r\n setWidgetValue(imageNode, 'height', h)\r\n\r\n if (hrUp || hrSz) {\r\n let uw, uh\r\n if (hrUp) {\r\n uw = w * hrUp\r\n uh = h * hrUp\r\n } else {\r\n const s = hrSz.split('x')\r\n uw = +s[0]\r\n uh = +s[1]\r\n }\r\n\r\n let upscaleNode\r\n let latentNode\r\n\r\n if (hrMethod.startsWith('Latent')) {\r\n latentNode = upscaleNode = LiteGraph.createNode('LatentUpscale')\r\n graph.add(upscaleNode)\r\n samplerNode.connect(0, upscaleNode, 0)\r\n\r\n switch (hrMethod) {\r\n case 'Latent (nearest-exact)':\r\n hrMethod = 'nearest-exact'\r\n break\r\n }\r\n setWidgetValue(upscaleNode, 'upscale_method', hrMethod, true)\r\n } else {\r\n const decode = LiteGraph.createNode('VAEDecodeTiled')\r\n graph.add(decode)\r\n samplerNode.connect(0, decode, 0)\r\n vaeLoaderNode.connect(0, decode, 1)\r\n\r\n const upscaleLoaderNode =\r\n LiteGraph.createNode('UpscaleModelLoader')\r\n graph.add(upscaleLoaderNode)\r\n setWidgetValue(upscaleLoaderNode, 'model_name', hrMethod, true)\r\n\r\n const modelUpscaleNode = LiteGraph.createNode(\r\n 'ImageUpscaleWithModel'\r\n )\r\n graph.add(modelUpscaleNode)\r\n decode.connect(0, modelUpscaleNode, 1)\r\n upscaleLoaderNode.connect(0, modelUpscaleNode, 0)\r\n\r\n upscaleNode = LiteGraph.createNode('ImageScale')\r\n graph.add(upscaleNode)\r\n modelUpscaleNode.connect(0, upscaleNode, 0)\r\n\r\n const vaeEncodeNode = (latentNode =\r\n LiteGraph.createNode('VAEEncodeTiled'))\r\n graph.add(vaeEncodeNode)\r\n upscaleNode.connect(0, vaeEncodeNode, 0)\r\n vaeLoaderNode.connect(0, vaeEncodeNode, 1)\r\n }\r\n\r\n setWidgetValue(upscaleNode, 'width', ceil64(uw))\r\n setWidgetValue(upscaleNode, 'height', ceil64(uh))\r\n\r\n hrSamplerNode = LiteGraph.createNode('KSampler')\r\n graph.add(hrSamplerNode)\r\n ckptNode.connect(0, hrSamplerNode, 0)\r\n positiveNode.connect(0, hrSamplerNode, 1)\r\n negativeNode.connect(0, hrSamplerNode, 2)\r\n latentNode.connect(0, hrSamplerNode, 3)\r\n hrSamplerNode.connect(0, vaeNode, 0)\r\n }\r\n },\r\n steps(v) {\r\n setWidgetValue(samplerNode, 'steps', +v)\r\n },\r\n seed(v) {\r\n setWidgetValue(samplerNode, 'seed', +v)\r\n }\r\n }\r\n\r\n for (const opt in opts) {\r\n if (opt in handlers) {\r\n handlers[opt](popOpt(opt))\r\n }\r\n }\r\n\r\n if (hrSamplerNode) {\r\n setWidgetValue(\r\n hrSamplerNode,\r\n 'steps',\r\n hrSteps ? +hrSteps : getWidget(samplerNode, 'steps').value\r\n )\r\n setWidgetValue(\r\n hrSamplerNode,\r\n 'cfg',\r\n getWidget(samplerNode, 'cfg').value\r\n )\r\n setWidgetValue(\r\n hrSamplerNode,\r\n 'scheduler',\r\n getWidget(samplerNode, 'scheduler').value\r\n )\r\n setWidgetValue(\r\n hrSamplerNode,\r\n 'sampler_name',\r\n getWidget(samplerNode, 'sampler_name').value\r\n )\r\n setWidgetValue(\r\n hrSamplerNode,\r\n 'denoise',\r\n +(popOpt('denoising strength') || '1')\r\n )\r\n }\r\n\r\n let n = createLoraNodes(\r\n positiveNode,\r\n positive,\r\n { node: clipSkipNode, index: 0 },\r\n { node: ckptNode, index: 0 }\r\n )\r\n positive = n.text\r\n n = createLoraNodes(negativeNode, negative, n.prevClip, n.prevModel)\r\n negative = n.text\r\n\r\n setWidgetValue(positiveNode, 'text', replaceEmbeddings(positive))\r\n setWidgetValue(negativeNode, 'text', replaceEmbeddings(negative))\r\n\r\n graph.arrange()\r\n\r\n for (const opt of [\r\n 'model hash',\r\n 'ensd',\r\n 'version',\r\n 'vae hash',\r\n 'ti hashes',\r\n 'lora hashes',\r\n 'hashes'\r\n ]) {\r\n delete opts[opt]\r\n }\r\n\r\n console.warn('Unhandled parameters:', opts)\r\n }\r\n }\r\n}\r\n","import { app } from '../app'\r\nimport { $el } from '../ui'\r\n\r\nexport function calculateImageGrid(imgs, dw, dh) {\r\n let best = 0\r\n let w = imgs[0].naturalWidth\r\n let h = imgs[0].naturalHeight\r\n const numImages = imgs.length\r\n\r\n let cellWidth, cellHeight, cols, rows, shiftX\r\n // compact style\r\n for (let c = 1; c <= numImages; c++) {\r\n const r = Math.ceil(numImages / c)\r\n const cW = dw / c\r\n const cH = dh / r\r\n const scaleX = cW / w\r\n const scaleY = cH / h\r\n\r\n const scale = Math.min(scaleX, scaleY, 1)\r\n const imageW = w * scale\r\n const imageH = h * scale\r\n const area = imageW * imageH * numImages\r\n\r\n if (area > best) {\r\n best = area\r\n cellWidth = imageW\r\n cellHeight = imageH\r\n cols = c\r\n rows = r\r\n shiftX = c * ((cW - imageW) / 2)\r\n }\r\n }\r\n\r\n return { cellWidth, cellHeight, cols, rows, shiftX }\r\n}\r\n\r\nexport function createImageHost(node) {\r\n const el = $el('div.comfy-img-preview')\r\n let currentImgs\r\n let first = true\r\n\r\n function updateSize() {\r\n let w = null\r\n let h = null\r\n\r\n if (currentImgs) {\r\n let elH = el.clientHeight\r\n if (first) {\r\n first = false\r\n // On first run, if we are small then grow a bit\r\n if (elH < 190) {\r\n elH = 190\r\n }\r\n el.style.setProperty('--comfy-widget-min-height', elH.toString())\r\n } else {\r\n el.style.setProperty('--comfy-widget-min-height', null)\r\n }\r\n\r\n const nw = node.size[0]\r\n ;({ cellWidth: w, cellHeight: h } = calculateImageGrid(\r\n currentImgs,\r\n nw - 20,\r\n elH\r\n ))\r\n w += 'px'\r\n h += 'px'\r\n\r\n el.style.setProperty('--comfy-img-preview-width', w)\r\n el.style.setProperty('--comfy-img-preview-height', h)\r\n }\r\n }\r\n return {\r\n el,\r\n updateImages(imgs) {\r\n if (imgs !== currentImgs) {\r\n if (currentImgs == null) {\r\n requestAnimationFrame(() => {\r\n updateSize()\r\n })\r\n }\r\n el.replaceChildren(...imgs)\r\n currentImgs = imgs\r\n node.onResize(node.size)\r\n node.graph.setDirtyCanvas(true, true)\r\n }\r\n },\r\n getHeight() {\r\n updateSize()\r\n },\r\n onDraw() {\r\n // Element from point uses a hittest find elements so we need to toggle pointer events\r\n el.style.pointerEvents = 'all'\r\n const over = document.elementFromPoint(\r\n app.canvas.mouse[0],\r\n app.canvas.mouse[1]\r\n )\r\n el.style.pointerEvents = 'none'\r\n\r\n if (!over) return\r\n // Set the overIndex so Open Image etc work\r\n const idx = currentImgs.indexOf(over)\r\n node.overIndex = idx\r\n }\r\n }\r\n}\r\n","/*\r\n Original implementation:\r\n https://github.com/TahaSh/drag-to-reorder\r\n MIT License\r\n\r\n Copyright (c) 2023 Taha Shashtari\r\n\r\n Permission is hereby granted, free of charge, to any person obtaining a copy\r\n of this software and associated documentation files (the \"Software\"), to deal\r\n in the Software without restriction, including without limitation the rights\r\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n copies of the Software, and to permit persons to whom the Software is\r\n furnished to do so, subject to the following conditions:\r\n\r\n The above copyright notice and this permission notice shall be included in all\r\n copies or substantial portions of the Software.\r\n\r\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n SOFTWARE.\r\n*/\r\n\r\nimport { $el } from '../ui'\r\n\r\n$el('style', {\r\n parent: document.head,\r\n textContent: `\r\n .draggable-item {\r\n position: relative;\r\n will-change: transform;\r\n user-select: none;\r\n }\r\n .draggable-item.is-idle {\r\n transition: 0.25s ease transform;\r\n }\r\n .draggable-item.is-draggable {\r\n z-index: 10;\r\n }\r\n `\r\n})\r\n\r\nexport class DraggableList extends EventTarget {\r\n listContainer\r\n draggableItem\r\n pointerStartX\r\n pointerStartY\r\n scrollYMax\r\n itemsGap = 0\r\n items = []\r\n itemSelector\r\n handleClass = 'drag-handle'\r\n off = []\r\n offDrag = []\r\n\r\n constructor(element, itemSelector) {\r\n super()\r\n this.listContainer = element\r\n this.itemSelector = itemSelector\r\n\r\n if (!this.listContainer) return\r\n\r\n this.off.push(this.on(this.listContainer, 'mousedown', this.dragStart))\r\n this.off.push(this.on(this.listContainer, 'touchstart', this.dragStart))\r\n this.off.push(this.on(document, 'mouseup', this.dragEnd))\r\n this.off.push(this.on(document, 'touchend', this.dragEnd))\r\n }\r\n\r\n getAllItems() {\r\n if (!this.items?.length) {\r\n this.items = Array.from(\r\n this.listContainer.querySelectorAll(this.itemSelector)\r\n )\r\n this.items.forEach((element) => {\r\n element.classList.add('is-idle')\r\n })\r\n }\r\n return this.items\r\n }\r\n\r\n getIdleItems() {\r\n return this.getAllItems().filter((item) =>\r\n item.classList.contains('is-idle')\r\n )\r\n }\r\n\r\n isItemAbove(item) {\r\n return item.hasAttribute('data-is-above')\r\n }\r\n\r\n isItemToggled(item) {\r\n return item.hasAttribute('data-is-toggled')\r\n }\r\n\r\n on(source, event, listener, options?) {\r\n listener = listener.bind(this)\r\n source.addEventListener(event, listener, options)\r\n return () => source.removeEventListener(event, listener)\r\n }\r\n\r\n dragStart(e) {\r\n if (e.target.classList.contains(this.handleClass)) {\r\n this.draggableItem = e.target.closest(this.itemSelector)\r\n }\r\n\r\n if (!this.draggableItem) return\r\n\r\n this.pointerStartX = e.clientX || e.touches[0].clientX\r\n this.pointerStartY = e.clientY || e.touches[0].clientY\r\n this.scrollYMax =\r\n this.listContainer.scrollHeight - this.listContainer.clientHeight\r\n\r\n this.setItemsGap()\r\n this.initDraggableItem()\r\n this.initItemsState()\r\n\r\n this.offDrag.push(this.on(document, 'mousemove', this.drag))\r\n this.offDrag.push(\r\n this.on(document, 'touchmove', this.drag, { passive: false })\r\n )\r\n\r\n this.dispatchEvent(\r\n new CustomEvent('dragstart', {\r\n detail: {\r\n element: this.draggableItem,\r\n position: this.getAllItems().indexOf(this.draggableItem)\r\n }\r\n })\r\n )\r\n }\r\n\r\n setItemsGap() {\r\n if (this.getIdleItems().length <= 1) {\r\n this.itemsGap = 0\r\n return\r\n }\r\n\r\n const item1 = this.getIdleItems()[0]\r\n const item2 = this.getIdleItems()[1]\r\n\r\n const item1Rect = item1.getBoundingClientRect()\r\n const item2Rect = item2.getBoundingClientRect()\r\n\r\n this.itemsGap = Math.abs(item1Rect.bottom - item2Rect.top)\r\n }\r\n\r\n initItemsState() {\r\n this.getIdleItems().forEach((item, i) => {\r\n if (this.getAllItems().indexOf(this.draggableItem) > i) {\r\n item.dataset.isAbove = ''\r\n }\r\n })\r\n }\r\n\r\n initDraggableItem() {\r\n this.draggableItem.classList.remove('is-idle')\r\n this.draggableItem.classList.add('is-draggable')\r\n }\r\n\r\n drag(e) {\r\n if (!this.draggableItem) return\r\n\r\n e.preventDefault()\r\n\r\n const clientX = e.clientX || e.touches[0].clientX\r\n const clientY = e.clientY || e.touches[0].clientY\r\n\r\n const listRect = this.listContainer.getBoundingClientRect()\r\n\r\n if (clientY > listRect.bottom) {\r\n if (this.listContainer.scrollTop < this.scrollYMax) {\r\n this.listContainer.scrollBy(0, 10)\r\n this.pointerStartY -= 10\r\n }\r\n } else if (clientY < listRect.top && this.listContainer.scrollTop > 0) {\r\n this.pointerStartY += 10\r\n this.listContainer.scrollBy(0, -10)\r\n }\r\n\r\n const pointerOffsetX = clientX - this.pointerStartX\r\n const pointerOffsetY = clientY - this.pointerStartY\r\n\r\n this.updateIdleItemsStateAndPosition()\r\n this.draggableItem.style.transform = `translate(${pointerOffsetX}px, ${pointerOffsetY}px)`\r\n }\r\n\r\n updateIdleItemsStateAndPosition() {\r\n const draggableItemRect = this.draggableItem.getBoundingClientRect()\r\n const draggableItemY = draggableItemRect.top + draggableItemRect.height / 2\r\n\r\n // Update state\r\n this.getIdleItems().forEach((item) => {\r\n const itemRect = item.getBoundingClientRect()\r\n const itemY = itemRect.top + itemRect.height / 2\r\n if (this.isItemAbove(item)) {\r\n if (draggableItemY <= itemY) {\r\n item.dataset.isToggled = ''\r\n } else {\r\n delete item.dataset.isToggled\r\n }\r\n } else {\r\n if (draggableItemY >= itemY) {\r\n item.dataset.isToggled = ''\r\n } else {\r\n delete item.dataset.isToggled\r\n }\r\n }\r\n })\r\n\r\n // Update position\r\n this.getIdleItems().forEach((item) => {\r\n if (this.isItemToggled(item)) {\r\n const direction = this.isItemAbove(item) ? 1 : -1\r\n item.style.transform = `translateY(${direction * (draggableItemRect.height + this.itemsGap)}px)`\r\n } else {\r\n item.style.transform = ''\r\n }\r\n })\r\n }\r\n\r\n dragEnd() {\r\n if (!this.draggableItem) return\r\n\r\n this.applyNewItemsOrder()\r\n this.cleanup()\r\n }\r\n\r\n applyNewItemsOrder() {\r\n const reorderedItems = []\r\n\r\n let oldPosition = -1\r\n this.getAllItems().forEach((item, index) => {\r\n if (item === this.draggableItem) {\r\n oldPosition = index\r\n return\r\n }\r\n if (!this.isItemToggled(item)) {\r\n reorderedItems[index] = item\r\n return\r\n }\r\n const newIndex = this.isItemAbove(item) ? index + 1 : index - 1\r\n reorderedItems[newIndex] = item\r\n })\r\n\r\n for (let index = 0; index < this.getAllItems().length; index++) {\r\n const item = reorderedItems[index]\r\n if (typeof item === 'undefined') {\r\n reorderedItems[index] = this.draggableItem\r\n }\r\n }\r\n\r\n reorderedItems.forEach((item) => {\r\n this.listContainer.appendChild(item)\r\n })\r\n\r\n this.items = reorderedItems\r\n\r\n this.dispatchEvent(\r\n new CustomEvent('dragend', {\r\n detail: {\r\n element: this.draggableItem,\r\n oldPosition,\r\n newPosition: reorderedItems.indexOf(this.draggableItem)\r\n }\r\n })\r\n )\r\n }\r\n\r\n cleanup() {\r\n this.itemsGap = 0\r\n this.items = []\r\n this.unsetDraggableItem()\r\n this.unsetItemState()\r\n\r\n this.offDrag.forEach((f) => f())\r\n this.offDrag = []\r\n }\r\n\r\n unsetDraggableItem() {\r\n this.draggableItem.style = null\r\n this.draggableItem.classList.remove('is-draggable')\r\n this.draggableItem.classList.add('is-idle')\r\n this.draggableItem = null\r\n }\r\n\r\n unsetItemState() {\r\n this.getIdleItems().forEach((item, i) => {\r\n delete item.dataset.isAbove\r\n delete item.dataset.isToggled\r\n item.style.transform = ''\r\n })\r\n }\r\n\r\n dispose() {\r\n this.off.forEach((f) => f())\r\n }\r\n}\r\n","import { api } from './api'\r\nimport type { ComfyApp } from './app'\r\nimport { $el } from './ui'\r\n\r\n// Simple date formatter\r\nconst parts = {\r\n d: (d) => d.getDate(),\r\n M: (d) => d.getMonth() + 1,\r\n h: (d) => d.getHours(),\r\n m: (d) => d.getMinutes(),\r\n s: (d) => d.getSeconds()\r\n}\r\nconst format =\r\n Object.keys(parts)\r\n .map((k) => k + k + '?')\r\n .join('|') + '|yyy?y?'\r\n\r\nfunction formatDate(text: string, date: Date) {\r\n return text.replace(new RegExp(format, 'g'), (text: string): string => {\r\n if (text === 'yy') return (date.getFullYear() + '').substring(2)\r\n if (text === 'yyyy') return date.getFullYear().toString()\r\n if (text[0] in parts) {\r\n const p = parts[text[0]](date)\r\n return (p + '').padStart(text.length, '0')\r\n }\r\n return text\r\n })\r\n}\r\n\r\nexport function clone(obj) {\r\n try {\r\n if (typeof structuredClone !== 'undefined') {\r\n return structuredClone(obj)\r\n }\r\n } catch (error) {\r\n // structuredClone is stricter than using JSON.parse/stringify so fallback to that\r\n }\r\n\r\n return JSON.parse(JSON.stringify(obj))\r\n}\r\n\r\nexport function applyTextReplacements(app: ComfyApp, value: string): string {\r\n return value.replace(/%([^%]+)%/g, function (match, text) {\r\n const split = text.split('.')\r\n if (split.length !== 2) {\r\n // Special handling for dates\r\n if (split[0].startsWith('date:')) {\r\n return formatDate(split[0].substring(5), new Date())\r\n }\r\n\r\n if (text !== 'width' && text !== 'height') {\r\n // Dont warn on standard replacements\r\n console.warn('Invalid replacement pattern', text)\r\n }\r\n return match\r\n }\r\n\r\n // Find node with matching S&R property name\r\n // @ts-expect-error\r\n let nodes = app.graph._nodes.filter(\r\n (n) => n.properties?.['Node name for S&R'] === split[0]\r\n )\r\n // If we cant, see if there is a node with that title\r\n if (!nodes.length) {\r\n // @ts-expect-error\r\n nodes = app.graph._nodes.filter((n) => n.title === split[0])\r\n }\r\n if (!nodes.length) {\r\n console.warn('Unable to find node', split[0])\r\n return match\r\n }\r\n\r\n if (nodes.length > 1) {\r\n console.warn('Multiple nodes matched', split[0], 'using first match')\r\n }\r\n\r\n const node = nodes[0]\r\n\r\n const widget = node.widgets?.find((w) => w.name === split[1])\r\n if (!widget) {\r\n console.warn('Unable to find widget', split[1], 'on node', split[0], node)\r\n return match\r\n }\r\n\r\n return ((widget.value ?? '') + '').replaceAll(/\\/|\\\\/g, '_')\r\n })\r\n}\r\n\r\nexport async function addStylesheet(\r\n urlOrFile: string,\r\n relativeTo?: string\r\n): Promise {\r\n return new Promise((res, rej) => {\r\n let url\r\n if (urlOrFile.endsWith('.js')) {\r\n url = urlOrFile.substr(0, urlOrFile.length - 2) + 'css'\r\n } else {\r\n url = new URL(\r\n urlOrFile,\r\n relativeTo ?? `${window.location.protocol}//${window.location.host}`\r\n ).toString()\r\n }\r\n $el('link', {\r\n parent: document.head,\r\n rel: 'stylesheet',\r\n type: 'text/css',\r\n href: url,\r\n onload: res,\r\n onerror: rej\r\n })\r\n })\r\n}\r\n\r\n/**\r\n * @param { string } filename\r\n * @param { Blob } blob\r\n */\r\nexport function downloadBlob(filename, blob) {\r\n const url = URL.createObjectURL(blob)\r\n const a = $el('a', {\r\n href: url,\r\n download: filename,\r\n style: { display: 'none' },\r\n parent: document.body\r\n })\r\n a.click()\r\n setTimeout(function () {\r\n a.remove()\r\n window.URL.revokeObjectURL(url)\r\n }, 0)\r\n}\r\n\r\nexport function prop(\r\n target: object,\r\n name: string,\r\n defaultValue: T,\r\n onChanged?: (\r\n currentValue: T,\r\n previousValue: T,\r\n target: object,\r\n name: string\r\n ) => void\r\n): T {\r\n let currentValue\r\n Object.defineProperty(target, name, {\r\n get() {\r\n return currentValue\r\n },\r\n set(newValue) {\r\n const prevValue = currentValue\r\n currentValue = newValue\r\n onChanged?.(currentValue, prevValue, target, name)\r\n }\r\n })\r\n return defaultValue\r\n}\r\n\r\nexport function getStorageValue(id) {\r\n const clientId = api.clientId ?? api.initialClientId\r\n return (\r\n (clientId && sessionStorage.getItem(`${id}:${clientId}`)) ??\r\n localStorage.getItem(id)\r\n )\r\n}\r\n\r\nexport function setStorageValue(id, value) {\r\n const clientId = api.clientId ?? api.initialClientId\r\n if (clientId) {\r\n sessionStorage.setItem(`${id}:${clientId}`, value)\r\n }\r\n localStorage.setItem(id, value)\r\n}\r\n","type RGB = { r: number; g: number; b: number }\r\ntype HSL = { h: number; s: number; l: number }\r\n\r\nfunction rgbToHsl({ r, g, b }: RGB): HSL {\r\n r /= 255\r\n g /= 255\r\n b /= 255\r\n const max = Math.max(r, g, b),\r\n min = Math.min(r, g, b)\r\n let h: number, s: number\r\n const l: number = (max + min) / 2\r\n\r\n if (max === min) {\r\n h = s = 0 // achromatic\r\n } else {\r\n const d = max - min\r\n s = l > 0.5 ? d / (2 - max - min) : d / (max + min)\r\n switch (max) {\r\n case r:\r\n h = (g - b) / d + (g < b ? 6 : 0)\r\n break\r\n case g:\r\n h = (b - r) / d + 2\r\n break\r\n case b:\r\n h = (r - g) / d + 4\r\n break\r\n }\r\n h /= 6\r\n }\r\n\r\n return { h, s, l }\r\n}\r\n\r\nfunction hslToRgb({ h, s, l }: HSL): RGB {\r\n let r: number, g: number, b: number\r\n\r\n if (s === 0) {\r\n r = g = b = l // achromatic\r\n } else {\r\n const hue2rgb = (p: number, q: number, t: number) => {\r\n if (t < 0) t += 1\r\n if (t > 1) t -= 1\r\n if (t < 1 / 6) return p + (q - p) * 6 * t\r\n if (t < 1 / 2) return q\r\n if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6\r\n return p\r\n }\r\n\r\n const q = l < 0.5 ? l * (1 + s) : l + s - l * s\r\n const p = 2 * l - q\r\n r = hue2rgb(p, q, h + 1 / 3)\r\n g = hue2rgb(p, q, h)\r\n b = hue2rgb(p, q, h - 1 / 3)\r\n }\r\n\r\n return {\r\n r: Math.round(r * 255),\r\n g: Math.round(g * 255),\r\n b: Math.round(b * 255)\r\n }\r\n}\r\n\r\nfunction hexToRgb(hex: string): RGB {\r\n let r = 0,\r\n g = 0,\r\n b = 0\r\n // 3 digits\r\n if (hex.length == 4) {\r\n r = parseInt(hex[1] + hex[1], 16)\r\n g = parseInt(hex[2] + hex[2], 16)\r\n b = parseInt(hex[3] + hex[3], 16)\r\n }\r\n // 6 digits\r\n else if (hex.length == 7) {\r\n r = parseInt(hex.slice(1, 3), 16)\r\n g = parseInt(hex.slice(3, 5), 16)\r\n b = parseInt(hex.slice(5, 7), 16)\r\n }\r\n return { r, g, b }\r\n}\r\n\r\nfunction rgbToHex({ r, g, b }: RGB): string {\r\n return (\r\n '#' +\r\n [r, g, b]\r\n .map((x) => {\r\n const hex = x.toString(16)\r\n return hex.length === 1 ? '0' + hex : hex\r\n })\r\n .join('')\r\n )\r\n}\r\n\r\nexport function lightenColor(hex: string, amount: number): string {\r\n let rgb = hexToRgb(hex)\r\n const hsl = rgbToHsl(rgb)\r\n hsl.l = Math.min(1, hsl.l + amount)\r\n rgb = hslToRgb(hsl)\r\n return rgbToHex(rgb)\r\n}\r\n","export type ClassList = string | string[] | Record\r\n\r\nexport function applyClasses(\r\n element: HTMLElement,\r\n classList: ClassList,\r\n ...requiredClasses: string[]\r\n) {\r\n classList ??= ''\r\n\r\n let str: string\r\n if (typeof classList === 'string') {\r\n str = classList\r\n } else if (classList instanceof Array) {\r\n str = classList.join(' ')\r\n } else {\r\n str = Object.entries(classList).reduce((p, c) => {\r\n if (c[1]) {\r\n p += (p.length ? ' ' : '') + c[0]\r\n }\r\n return p\r\n }, '')\r\n }\r\n element.className = str\r\n if (requiredClasses) {\r\n element.classList.add(...requiredClasses)\r\n }\r\n}\r\n\r\nexport function toggleElement(\r\n element: HTMLElement,\r\n {\r\n onHide,\r\n onShow\r\n }: {\r\n onHide?: (el: HTMLElement) => void\r\n onShow?: (el: HTMLElement, value) => void\r\n } = {}\r\n) {\r\n let placeholder: HTMLElement | Comment\r\n let hidden: boolean\r\n return (value) => {\r\n if (value) {\r\n if (hidden) {\r\n hidden = false\r\n placeholder.replaceWith(element)\r\n }\r\n onShow?.(element, value)\r\n } else {\r\n if (!placeholder) {\r\n placeholder = document.createComment('')\r\n }\r\n hidden = true\r\n element.replaceWith(placeholder)\r\n onHide?.(element)\r\n }\r\n }\r\n}\r\n","import { $el } from '../../ui'\r\nimport { applyClasses, ClassList, toggleElement } from '../utils'\r\nimport { prop } from '../../utils'\r\nimport type { ComfyPopup } from './popup'\r\nimport type { ComfyComponent } from '.'\r\nimport type { ComfyApp } from '@/scripts/app'\r\n\r\ntype ComfyButtonProps = {\r\n icon?: string\r\n overIcon?: string\r\n iconSize?: number\r\n content?: string | HTMLElement\r\n tooltip?: string\r\n enabled?: boolean\r\n action?: (e: Event, btn: ComfyButton) => void\r\n classList?: ClassList\r\n visibilitySetting?: { id: string; showValue: any }\r\n app?: ComfyApp\r\n}\r\n\r\nexport class ComfyButton implements ComfyComponent {\r\n #over = 0\r\n #popupOpen = false\r\n isOver = false\r\n iconElement = $el('i.mdi')\r\n contentElement = $el('span')\r\n popup: ComfyPopup\r\n element: HTMLElement\r\n overIcon: string\r\n iconSize: number\r\n content: string | HTMLElement\r\n icon: string\r\n tooltip: string\r\n classList: ClassList\r\n hidden: boolean\r\n enabled: boolean\r\n action: (e: Event, btn: ComfyButton) => void\r\n\r\n constructor({\r\n icon,\r\n overIcon,\r\n iconSize,\r\n content,\r\n tooltip,\r\n action,\r\n classList = 'comfyui-button',\r\n visibilitySetting,\r\n app,\r\n enabled = true\r\n }: ComfyButtonProps) {\r\n this.element = $el(\r\n 'button',\r\n {\r\n onmouseenter: () => {\r\n this.isOver = true\r\n if (this.overIcon) {\r\n this.updateIcon()\r\n }\r\n },\r\n onmouseleave: () => {\r\n this.isOver = false\r\n if (this.overIcon) {\r\n this.updateIcon()\r\n }\r\n }\r\n },\r\n [this.iconElement, this.contentElement]\r\n )\r\n\r\n this.icon = prop(\r\n this,\r\n 'icon',\r\n icon,\r\n toggleElement(this.iconElement, { onShow: this.updateIcon })\r\n )\r\n this.overIcon = prop(this, 'overIcon', overIcon, () => {\r\n if (this.isOver) {\r\n this.updateIcon()\r\n }\r\n })\r\n this.iconSize = prop(this, 'iconSize', iconSize, this.updateIcon)\r\n this.content = prop(\r\n this,\r\n 'content',\r\n content,\r\n toggleElement(this.contentElement, {\r\n onShow: (el, v) => {\r\n if (typeof v === 'string') {\r\n el.textContent = v\r\n } else {\r\n el.replaceChildren(v)\r\n }\r\n }\r\n })\r\n )\r\n\r\n this.tooltip = prop(this, 'tooltip', tooltip, (v) => {\r\n if (v) {\r\n this.element.title = v\r\n } else {\r\n this.element.removeAttribute('title')\r\n }\r\n })\r\n this.classList = prop(this, 'classList', classList, this.updateClasses)\r\n this.hidden = prop(this, 'hidden', false, this.updateClasses)\r\n this.enabled = prop(this, 'enabled', enabled, () => {\r\n this.updateClasses()\r\n ;(this.element as HTMLButtonElement).disabled = !this.enabled\r\n })\r\n this.action = prop(this, 'action', action)\r\n this.element.addEventListener('click', (e) => {\r\n if (this.popup) {\r\n // we are either a touch device or triggered by click not hover\r\n if (!this.#over) {\r\n this.popup.toggle()\r\n }\r\n }\r\n this.action?.(e, this)\r\n })\r\n\r\n if (visibilitySetting?.id) {\r\n const settingUpdated = () => {\r\n this.hidden =\r\n app.ui.settings.getSettingValue(visibilitySetting.id) !==\r\n visibilitySetting.showValue\r\n }\r\n app.ui.settings.addEventListener(\r\n visibilitySetting.id + '.change',\r\n settingUpdated\r\n )\r\n settingUpdated()\r\n }\r\n }\r\n\r\n updateIcon = () =>\r\n (this.iconElement.className = `mdi mdi-${(this.isOver && this.overIcon) || this.icon}${this.iconSize ? ' mdi-' + this.iconSize + 'px' : ''}`)\r\n updateClasses = () => {\r\n const internalClasses = []\r\n if (this.hidden) {\r\n internalClasses.push('hidden')\r\n }\r\n if (!this.enabled) {\r\n internalClasses.push('disabled')\r\n }\r\n if (this.popup) {\r\n if (this.#popupOpen) {\r\n internalClasses.push('popup-open')\r\n } else {\r\n internalClasses.push('popup-closed')\r\n }\r\n }\r\n applyClasses(this.element, this.classList, ...internalClasses)\r\n }\r\n\r\n withPopup(popup: ComfyPopup, mode: 'click' | 'hover' = 'click') {\r\n this.popup = popup\r\n\r\n if (mode === 'hover') {\r\n for (const el of [this.element, this.popup.element]) {\r\n el.addEventListener('mouseenter', () => {\r\n this.popup.open = !!++this.#over\r\n })\r\n el.addEventListener('mouseleave', () => {\r\n this.popup.open = !!--this.#over\r\n })\r\n }\r\n }\r\n\r\n popup.addEventListener('change', () => {\r\n this.#popupOpen = popup.open\r\n this.updateClasses()\r\n })\r\n\r\n return this\r\n }\r\n}\r\n","import { $el } from '../../ui'\r\nimport { ComfyButton } from './button'\r\nimport { prop } from '../../utils'\r\n\r\nexport class ComfyButtonGroup {\r\n element = $el('div.comfyui-button-group')\r\n buttons: (HTMLElement | ComfyButton)[]\r\n\r\n constructor(...buttons: (HTMLElement | ComfyButton)[]) {\r\n this.buttons = prop(this, 'buttons', buttons, () => this.update())\r\n }\r\n\r\n insert(button: ComfyButton, index: number) {\r\n this.buttons.splice(index, 0, button)\r\n this.update()\r\n }\r\n\r\n append(button: ComfyButton) {\r\n this.buttons.push(button)\r\n this.update()\r\n }\r\n\r\n remove(indexOrButton: ComfyButton | number) {\r\n if (typeof indexOrButton !== 'number') {\r\n indexOrButton = this.buttons.indexOf(indexOrButton)\r\n }\r\n if (indexOrButton > -1) {\r\n const r = this.buttons.splice(indexOrButton, 1)\r\n this.update()\r\n return r\r\n }\r\n }\r\n\r\n update() {\r\n this.element.replaceChildren(...this.buttons.map((b) => b['element'] ?? b))\r\n }\r\n}\r\n","import { prop } from '../../utils'\r\nimport { $el } from '../../ui'\r\nimport { applyClasses, ClassList } from '../utils'\r\n\r\nexport class ComfyPopup extends EventTarget {\r\n element = $el('div.comfyui-popup')\r\n open: boolean\r\n children: HTMLElement[]\r\n target: HTMLElement\r\n ignoreTarget: boolean\r\n container: HTMLElement\r\n position: string\r\n closeOnEscape: boolean\r\n horizontal: string\r\n classList: ClassList\r\n\r\n constructor(\r\n {\r\n target,\r\n container = document.body,\r\n classList = '',\r\n ignoreTarget = true,\r\n closeOnEscape = true,\r\n position = 'absolute',\r\n horizontal = 'left'\r\n }: {\r\n target: HTMLElement\r\n container?: HTMLElement\r\n classList?: ClassList\r\n ignoreTarget?: boolean\r\n closeOnEscape?: boolean\r\n position?: 'absolute' | 'relative'\r\n horizontal?: 'left' | 'right'\r\n },\r\n ...children: HTMLElement[]\r\n ) {\r\n super()\r\n this.target = target\r\n this.ignoreTarget = ignoreTarget\r\n this.container = container\r\n this.position = position\r\n this.closeOnEscape = closeOnEscape\r\n this.horizontal = horizontal\r\n\r\n container.append(this.element)\r\n\r\n this.children = prop(this, 'children', children, () => {\r\n this.element.replaceChildren(...this.children)\r\n this.update()\r\n })\r\n this.classList = prop(this, 'classList', classList, () =>\r\n applyClasses(this.element, this.classList, 'comfyui-popup', horizontal)\r\n )\r\n this.open = prop(this, 'open', false, (v, o) => {\r\n if (v === o) return\r\n if (v) {\r\n this.#show()\r\n } else {\r\n this.#hide()\r\n }\r\n })\r\n }\r\n\r\n toggle() {\r\n this.open = !this.open\r\n }\r\n\r\n #hide() {\r\n this.element.classList.remove('open')\r\n window.removeEventListener('resize', this.update)\r\n window.removeEventListener('click', this.#clickHandler, { capture: true })\r\n window.removeEventListener('keydown', this.#escHandler, { capture: true })\r\n\r\n this.dispatchEvent(new CustomEvent('close'))\r\n this.dispatchEvent(new CustomEvent('change'))\r\n }\r\n\r\n #show() {\r\n this.element.classList.add('open')\r\n this.update()\r\n\r\n window.addEventListener('resize', this.update)\r\n window.addEventListener('click', this.#clickHandler, { capture: true })\r\n if (this.closeOnEscape) {\r\n window.addEventListener('keydown', this.#escHandler, { capture: true })\r\n }\r\n\r\n this.dispatchEvent(new CustomEvent('open'))\r\n this.dispatchEvent(new CustomEvent('change'))\r\n }\r\n\r\n #escHandler = (e) => {\r\n if (e.key === 'Escape') {\r\n this.open = false\r\n e.preventDefault()\r\n e.stopImmediatePropagation()\r\n }\r\n }\r\n\r\n #clickHandler = (e) => {\r\n /** @type {any} */\r\n const target = e.target\r\n if (\r\n !this.element.contains(target) &&\r\n this.ignoreTarget &&\r\n !this.target.contains(target)\r\n ) {\r\n this.open = false\r\n }\r\n }\r\n\r\n update = () => {\r\n const rect = this.target.getBoundingClientRect()\r\n this.element.style.setProperty('--bottom', 'unset')\r\n if (this.position === 'absolute') {\r\n if (this.horizontal === 'left') {\r\n this.element.style.setProperty('--left', rect.left + 'px')\r\n } else {\r\n this.element.style.setProperty(\r\n '--left',\r\n rect.right - this.element.clientWidth + 'px'\r\n )\r\n }\r\n this.element.style.setProperty('--top', rect.bottom + 'px')\r\n this.element.style.setProperty('--limit', rect.bottom + 'px')\r\n } else {\r\n this.element.style.setProperty('--left', 0 + 'px')\r\n this.element.style.setProperty('--top', rect.height + 'px')\r\n this.element.style.setProperty('--limit', rect.height + 'px')\r\n }\r\n\r\n const thisRect = this.element.getBoundingClientRect()\r\n if (thisRect.height < 30) {\r\n // Move up instead\r\n this.element.style.setProperty('--top', 'unset')\r\n this.element.style.setProperty('--bottom', rect.height + 5 + 'px')\r\n this.element.style.setProperty('--limit', rect.height + 5 + 'px')\r\n }\r\n }\r\n}\r\n","import { $el } from '../../ui'\r\nimport { ComfyButton } from './button'\r\nimport { prop } from '../../utils'\r\nimport { ComfyPopup } from './popup'\r\n\r\nexport class ComfySplitButton {\r\n arrow: ComfyButton\r\n element: HTMLElement\r\n popup: ComfyPopup\r\n items: Array\r\n\r\n constructor(\r\n {\r\n primary,\r\n mode,\r\n horizontal = 'left',\r\n position = 'relative'\r\n }: {\r\n primary: ComfyButton\r\n mode?: 'hover' | 'click'\r\n horizontal?: 'left' | 'right'\r\n position?: 'relative' | 'absolute'\r\n },\r\n ...items: Array\r\n ) {\r\n this.arrow = new ComfyButton({\r\n icon: 'chevron-down'\r\n })\r\n this.element = $el(\r\n 'div.comfyui-split-button' + (mode === 'hover' ? '.hover' : ''),\r\n [\r\n $el('div.comfyui-split-primary', primary.element),\r\n $el('div.comfyui-split-arrow', this.arrow.element)\r\n ]\r\n )\r\n this.popup = new ComfyPopup({\r\n target: this.element,\r\n container: position === 'relative' ? this.element : document.body,\r\n classList:\r\n 'comfyui-split-button-popup' + (mode === 'hover' ? ' hover' : ''),\r\n closeOnEscape: mode === 'click',\r\n position,\r\n horizontal\r\n })\r\n\r\n this.arrow.withPopup(this.popup, mode)\r\n\r\n this.items = prop(this, 'items', items, () => this.update())\r\n }\r\n\r\n update() {\r\n this.popup.element.replaceChildren(\r\n ...this.items.map((b) => ('element' in b ? b.element : b))\r\n )\r\n }\r\n}\r\n","import type { ComfyApp } from '@/scripts/app'\r\nimport { $el } from '../../ui'\r\nimport { prop } from '../../utils'\r\n\r\nexport class ComfyQueueOptions extends EventTarget {\r\n element = $el('div.comfyui-queue-options')\r\n app: ComfyApp\r\n batchCountInput: HTMLInputElement\r\n batchCount: number\r\n batchCountRange: HTMLInputElement\r\n autoQueueMode: string\r\n autoQueueEl: HTMLElement\r\n\r\n constructor(app: ComfyApp) {\r\n super()\r\n this.app = app\r\n\r\n this.batchCountInput = $el('input', {\r\n className: 'comfyui-queue-batch-value',\r\n type: 'number',\r\n min: '1',\r\n value: '1',\r\n oninput: () => (this.batchCount = +this.batchCountInput.value)\r\n })\r\n\r\n this.batchCountRange = $el('input', {\r\n type: 'range',\r\n min: '1',\r\n max: '100',\r\n value: '1',\r\n oninput: () => (this.batchCount = +this.batchCountRange.value)\r\n })\r\n\r\n this.element.append(\r\n $el('div.comfyui-queue-batch', [\r\n $el(\r\n 'label',\r\n {\r\n textContent: 'Batch count: '\r\n },\r\n this.batchCountInput\r\n ),\r\n this.batchCountRange\r\n ])\r\n )\r\n\r\n const createOption = (text, value, checked = false) =>\r\n $el(\r\n 'label',\r\n { textContent: text },\r\n $el('input', {\r\n type: 'radio',\r\n name: 'AutoQueueMode',\r\n checked,\r\n value,\r\n oninput: (e) => (this.autoQueueMode = e.target['value'])\r\n })\r\n )\r\n\r\n this.autoQueueEl = $el('div.comfyui-queue-mode', [\r\n $el('span', 'Auto Queue:'),\r\n createOption('Disabled', '', true),\r\n createOption('Instant', 'instant'),\r\n createOption('On Change', 'change')\r\n ])\r\n\r\n this.element.append(this.autoQueueEl)\r\n\r\n this.batchCount = prop(this, 'batchCount', 1, () => {\r\n this.batchCountInput.value = this.batchCount + ''\r\n this.batchCountRange.value = this.batchCount + ''\r\n })\r\n\r\n this.autoQueueMode = prop(this, 'autoQueueMode', 'Disabled', () => {\r\n this.dispatchEvent(\r\n new CustomEvent('autoQueueMode', {\r\n detail: this.autoQueueMode\r\n })\r\n )\r\n })\r\n }\r\n}\r\n","import { ComfyButton } from '../components/button'\r\nimport { $el } from '../../ui'\r\nimport { api } from '../../api'\r\nimport { ComfySplitButton } from '../components/splitButton'\r\nimport { ComfyQueueOptions } from './queueOptions'\r\nimport { prop } from '../../utils'\r\nimport type { ComfyApp } from '@/scripts/app'\r\nimport { StatusWsMessageStatus } from '@/types/apiTypes'\r\n\r\nexport class ComfyQueueButton {\r\n element = $el('div.comfyui-queue-button')\r\n #internalQueueSize = 0\r\n\r\n queuePrompt = async (e?: MouseEvent) => {\r\n this.#internalQueueSize += this.queueOptions.batchCount\r\n // Hold shift to queue front, event is undefined when auto-queue is enabled\r\n await this.app.queuePrompt(\r\n e?.shiftKey ? -1 : 0,\r\n this.queueOptions.batchCount\r\n )\r\n }\r\n queueOptions: ComfyQueueOptions\r\n app: ComfyApp\r\n autoQueueMode: string\r\n graphHasChanged: boolean\r\n\r\n constructor(app: ComfyApp) {\r\n this.app = app\r\n\r\n const queue = new ComfyButton({\r\n content: $el('div', [\r\n $el('span', {\r\n textContent: 'Queue'\r\n })\r\n ]),\r\n icon: 'play',\r\n classList: 'comfyui-button',\r\n action: this.queuePrompt\r\n })\r\n\r\n this.queueOptions = new ComfyQueueOptions(app)\r\n\r\n const btn = new ComfySplitButton(\r\n {\r\n primary: queue,\r\n mode: 'click',\r\n position: 'absolute',\r\n horizontal: 'right'\r\n },\r\n this.queueOptions.element\r\n )\r\n btn.element.classList.add('primary')\r\n this.element.append(btn.element)\r\n\r\n this.autoQueueMode = prop(this, 'autoQueueMode', '', () => {\r\n switch (this.autoQueueMode) {\r\n case 'instant':\r\n queue.icon = 'infinity'\r\n break\r\n case 'change':\r\n queue.icon = 'auto-mode'\r\n break\r\n default:\r\n queue.icon = 'play'\r\n break\r\n }\r\n })\r\n\r\n this.queueOptions.addEventListener(\r\n 'autoQueueMode',\r\n (e) => (this.autoQueueMode = e['detail'])\r\n )\r\n\r\n api.addEventListener('graphChanged', () => {\r\n if (this.autoQueueMode === 'change') {\r\n if (this.#internalQueueSize) {\r\n this.graphHasChanged = true\r\n } else {\r\n this.graphHasChanged = false\r\n this.queuePrompt()\r\n }\r\n }\r\n })\r\n\r\n api.addEventListener(\r\n 'status',\r\n ({ detail }: CustomEvent) => {\r\n this.#internalQueueSize = detail?.exec_info?.queue_remaining\r\n if (this.#internalQueueSize != null) {\r\n if (!this.#internalQueueSize && !app.lastExecutionError) {\r\n if (\r\n this.autoQueueMode === 'instant' ||\r\n (this.autoQueueMode === 'change' && this.graphHasChanged)\r\n ) {\r\n this.graphHasChanged = false\r\n this.queuePrompt()\r\n }\r\n }\r\n }\r\n }\r\n )\r\n }\r\n}\r\n","import './spinner.css'\r\n\r\nexport function createSpinner() {\r\n const div = document.createElement('div')\r\n div.innerHTML = ``\r\n return div.firstElementChild\r\n}\r\n","import type { ComfyApp } from './app'\r\nimport { api } from './api'\r\nimport { clone } from './utils'\r\nimport { LGraphCanvas, LiteGraph } from '@comfyorg/litegraph'\r\nimport { ComfyWorkflow } from './workflows'\r\n\r\nexport class ChangeTracker {\r\n static MAX_HISTORY = 50\r\n #app: ComfyApp\r\n undo = []\r\n redo = []\r\n activeState = null\r\n isOurLoad = false\r\n workflow: ComfyWorkflow | null\r\n\r\n ds: { scale: number; offset: [number, number] }\r\n nodeOutputs: any\r\n\r\n get app() {\r\n return this.#app ?? this.workflow.manager.app\r\n }\r\n\r\n constructor(workflow: ComfyWorkflow) {\r\n this.workflow = workflow\r\n }\r\n\r\n #setApp(app) {\r\n this.#app = app\r\n }\r\n\r\n store() {\r\n this.ds = {\r\n scale: this.app.canvas.ds.scale,\r\n offset: [...this.app.canvas.ds.offset]\r\n }\r\n }\r\n\r\n restore() {\r\n if (this.ds) {\r\n this.app.canvas.ds.scale = this.ds.scale\r\n this.app.canvas.ds.offset = this.ds.offset\r\n }\r\n if (this.nodeOutputs) {\r\n this.app.nodeOutputs = this.nodeOutputs\r\n }\r\n }\r\n\r\n checkState() {\r\n if (!this.app.graph) return\r\n\r\n const currentState = this.app.graph.serialize()\r\n if (!this.activeState) {\r\n this.activeState = clone(currentState)\r\n return\r\n }\r\n if (!ChangeTracker.graphEqual(this.activeState, currentState)) {\r\n this.undo.push(this.activeState)\r\n if (this.undo.length > ChangeTracker.MAX_HISTORY) {\r\n this.undo.shift()\r\n }\r\n this.activeState = clone(currentState)\r\n this.redo.length = 0\r\n this.workflow.unsaved = true\r\n api.dispatchEvent(\r\n new CustomEvent('graphChanged', { detail: this.activeState })\r\n )\r\n }\r\n }\r\n\r\n async updateState(source, target) {\r\n const prevState = source.pop()\r\n if (prevState) {\r\n target.push(this.activeState)\r\n this.isOurLoad = true\r\n await this.app.loadGraphData(prevState, false, false, this.workflow)\r\n this.activeState = prevState\r\n }\r\n }\r\n\r\n async undoRedo(e) {\r\n if (e.ctrlKey || e.metaKey) {\r\n if (e.key === 'y') {\r\n this.updateState(this.redo, this.undo)\r\n return true\r\n } else if (e.key === 'z') {\r\n this.updateState(this.undo, this.redo)\r\n return true\r\n }\r\n }\r\n }\r\n\r\n static init(app: ComfyApp) {\r\n const changeTracker = () =>\r\n app.workflowManager.activeWorkflow?.changeTracker ?? globalTracker\r\n globalTracker.#setApp(app)\r\n\r\n const loadGraphData = app.loadGraphData\r\n app.loadGraphData = async function () {\r\n const v = await loadGraphData.apply(this, arguments)\r\n const ct = changeTracker()\r\n if (ct.isOurLoad) {\r\n ct.isOurLoad = false\r\n } else {\r\n ct.checkState()\r\n }\r\n return v\r\n }\r\n\r\n let keyIgnored = false\r\n window.addEventListener(\r\n 'keydown',\r\n (e) => {\r\n const activeEl = document.activeElement\r\n requestAnimationFrame(async () => {\r\n let bindInputEl\r\n // If we are auto queue in change mode then we do want to trigger on inputs\r\n if (!app.ui.autoQueueEnabled || app.ui.autoQueueMode === 'instant') {\r\n if (\r\n activeEl?.tagName === 'INPUT' ||\r\n activeEl?.['type'] === 'textarea'\r\n ) {\r\n // Ignore events on inputs, they have their native history\r\n return\r\n }\r\n bindInputEl = activeEl\r\n }\r\n\r\n keyIgnored =\r\n e.key === 'Control' ||\r\n e.key === 'Shift' ||\r\n e.key === 'Alt' ||\r\n e.key === 'Meta'\r\n if (keyIgnored) return\r\n\r\n // Check if this is a ctrl+z ctrl+y\r\n if (await changeTracker().undoRedo(e)) return\r\n\r\n // If our active element is some type of input then handle changes after they're done\r\n if (ChangeTracker.bindInput(app, bindInputEl)) return\r\n changeTracker().checkState()\r\n })\r\n },\r\n true\r\n )\r\n\r\n window.addEventListener('keyup', (e) => {\r\n if (keyIgnored) {\r\n keyIgnored = false\r\n changeTracker().checkState()\r\n }\r\n })\r\n\r\n // Handle clicking DOM elements (e.g. widgets)\r\n window.addEventListener('mouseup', () => {\r\n changeTracker().checkState()\r\n })\r\n\r\n // Handle prompt queue event for dynamic widget changes\r\n api.addEventListener('promptQueued', () => {\r\n changeTracker().checkState()\r\n })\r\n\r\n api.addEventListener('graphCleared', () => {\r\n changeTracker().checkState()\r\n })\r\n\r\n // Handle litegraph clicks\r\n const processMouseUp = LGraphCanvas.prototype.processMouseUp\r\n LGraphCanvas.prototype.processMouseUp = function (e) {\r\n const v = processMouseUp.apply(this, arguments)\r\n changeTracker().checkState()\r\n return v\r\n }\r\n const processMouseDown = LGraphCanvas.prototype.processMouseDown\r\n LGraphCanvas.prototype.processMouseDown = function (e) {\r\n const v = processMouseDown.apply(this, arguments)\r\n changeTracker().checkState()\r\n return v\r\n }\r\n\r\n // Handle litegraph context menu for COMBO widgets\r\n const close = LiteGraph.ContextMenu.prototype.close\r\n LiteGraph.ContextMenu.prototype.close = function (e) {\r\n const v = close.apply(this, arguments)\r\n changeTracker().checkState()\r\n return v\r\n }\r\n\r\n // Detects nodes being added via the node search dialog\r\n const onNodeAdded = LiteGraph.LGraph.prototype.onNodeAdded\r\n LiteGraph.LGraph.prototype.onNodeAdded = function () {\r\n const v = onNodeAdded?.apply(this, arguments)\r\n if (!app?.configuringGraph) {\r\n const ct = changeTracker()\r\n if (!ct.isOurLoad) {\r\n ct.checkState()\r\n }\r\n }\r\n return v\r\n }\r\n\r\n // Store node outputs\r\n api.addEventListener('executed', ({ detail }) => {\r\n const prompt = app.workflowManager.queuedPrompts[detail.prompt_id]\r\n if (!prompt?.workflow) return\r\n const nodeOutputs = (prompt.workflow.changeTracker.nodeOutputs ??= {})\r\n const output = nodeOutputs[detail.node]\r\n if (detail.merge && output) {\r\n for (const k in detail.output ?? {}) {\r\n const v = output[k]\r\n if (v instanceof Array) {\r\n output[k] = v.concat(detail.output[k])\r\n } else {\r\n output[k] = detail.output[k]\r\n }\r\n }\r\n } else {\r\n nodeOutputs[detail.node] = detail.output\r\n }\r\n })\r\n }\r\n\r\n static bindInput(app, activeEl) {\r\n if (\r\n activeEl &&\r\n activeEl.tagName !== 'CANVAS' &&\r\n activeEl.tagName !== 'BODY'\r\n ) {\r\n for (const evt of ['change', 'input', 'blur']) {\r\n if (`on${evt}` in activeEl) {\r\n const listener = () => {\r\n app.workflowManager.activeWorkflow.changeTracker.checkState()\r\n activeEl.removeEventListener(evt, listener)\r\n }\r\n activeEl.addEventListener(evt, listener)\r\n return true\r\n }\r\n }\r\n }\r\n }\r\n\r\n static graphEqual(a, b, path = '') {\r\n if (a === b) return true\r\n\r\n if (typeof a == 'object' && a && typeof b == 'object' && b) {\r\n const keys = Object.getOwnPropertyNames(a)\r\n\r\n if (keys.length != Object.getOwnPropertyNames(b).length) {\r\n return false\r\n }\r\n\r\n for (const key of keys) {\r\n let av = a[key]\r\n let bv = b[key]\r\n if (!path && key === 'nodes') {\r\n // Nodes need to be sorted as the order changes when selecting nodes\r\n av = [...av].sort((a, b) => a.id - b.id)\r\n bv = [...bv].sort((a, b) => a.id - b.id)\r\n } else if (path === 'extra.ds') {\r\n // Ignore view changes\r\n continue\r\n }\r\n if (!ChangeTracker.graphEqual(av, bv, path + (path ? '.' : '') + key)) {\r\n return false\r\n }\r\n }\r\n\r\n return true\r\n }\r\n\r\n return false\r\n }\r\n}\r\n\r\nconst globalTracker = new ChangeTracker({} as ComfyWorkflow)\r\n","import { ComfyDialog } from '../dialog'\r\nimport { $el } from '../../ui'\r\n\r\nexport class ComfyAsyncDialog extends ComfyDialog {\r\n #resolve: (value: any) => void\r\n\r\n constructor(actions?: Array) {\r\n super(\r\n 'dialog.comfy-dialog.comfyui-dialog',\r\n actions?.map((opt) => {\r\n if (typeof opt === 'string') {\r\n opt = { text: opt }\r\n }\r\n return $el('button.comfyui-button', {\r\n type: 'button',\r\n textContent: opt.text,\r\n onclick: () => this.close(opt.value ?? opt.text)\r\n })\r\n })\r\n )\r\n }\r\n\r\n show(html: string | HTMLElement | HTMLElement[]) {\r\n this.element.addEventListener('close', () => {\r\n this.close()\r\n })\r\n\r\n super.show(html)\r\n\r\n return new Promise((resolve) => {\r\n this.#resolve = resolve\r\n })\r\n }\r\n\r\n showModal(html: string | HTMLElement | HTMLElement[]) {\r\n this.element.addEventListener('close', () => {\r\n this.close()\r\n })\r\n\r\n super.show(html)\r\n this.element.showModal()\r\n\r\n return new Promise((resolve) => {\r\n this.#resolve = resolve\r\n })\r\n }\r\n\r\n close(result = null) {\r\n this.#resolve(result)\r\n this.element.close()\r\n super.close()\r\n }\r\n\r\n static async prompt({ title = null, message, actions }) {\r\n const dialog = new ComfyAsyncDialog(actions)\r\n const content = [$el('span', message)]\r\n if (title) {\r\n content.unshift($el('h3', title))\r\n }\r\n const res = await dialog.showModal(content)\r\n dialog.element.remove()\r\n return res\r\n }\r\n}\r\n","import type { ComfyApp } from './app'\r\nimport { api } from './api'\r\nimport { ChangeTracker } from './changeTracker'\r\nimport { ComfyAsyncDialog } from './ui/components/asyncDialog'\r\nimport { getStorageValue, setStorageValue } from './utils'\r\nimport { LGraphCanvas, LGraph } from '@comfyorg/litegraph'\r\n\r\nfunction appendJsonExt(path: string) {\r\n if (!path.toLowerCase().endsWith('.json')) {\r\n path += '.json'\r\n }\r\n return path\r\n}\r\n\r\nexport function trimJsonExt(path: string) {\r\n return path?.replace(/\\.json$/, '')\r\n}\r\n\r\nexport class ComfyWorkflowManager extends EventTarget {\r\n #activePromptId: string | null = null\r\n #unsavedCount = 0\r\n #activeWorkflow: ComfyWorkflow\r\n\r\n workflowLookup: Record = {}\r\n workflows: Array = []\r\n openWorkflows: Array = []\r\n queuedPrompts: Record<\r\n string,\r\n { workflow?: ComfyWorkflow; nodes?: Record }\r\n > = {}\r\n app: ComfyApp\r\n\r\n get activeWorkflow() {\r\n return this.#activeWorkflow ?? this.openWorkflows[0]\r\n }\r\n\r\n get activePromptId() {\r\n return this.#activePromptId\r\n }\r\n\r\n get activePrompt() {\r\n return this.queuedPrompts[this.#activePromptId]\r\n }\r\n\r\n constructor(app: ComfyApp) {\r\n super()\r\n this.app = app\r\n ChangeTracker.init(app)\r\n\r\n this.#bindExecutionEvents()\r\n }\r\n\r\n #bindExecutionEvents() {\r\n // TODO: on reload, set active prompt based on the latest ws message\r\n\r\n const emit = () =>\r\n this.dispatchEvent(\r\n new CustomEvent('execute', { detail: this.activePrompt })\r\n )\r\n let executing = null\r\n api.addEventListener('execution_start', (e) => {\r\n this.#activePromptId = e.detail.prompt_id\r\n\r\n // This event can fire before the event is stored, so put a placeholder\r\n this.queuedPrompts[this.#activePromptId] ??= { nodes: {} }\r\n emit()\r\n })\r\n api.addEventListener('execution_cached', (e) => {\r\n if (!this.activePrompt) return\r\n for (const n of e.detail.nodes) {\r\n this.activePrompt.nodes[n] = true\r\n }\r\n emit()\r\n })\r\n api.addEventListener('executed', (e) => {\r\n if (!this.activePrompt) return\r\n this.activePrompt.nodes[e.detail.node] = true\r\n emit()\r\n })\r\n api.addEventListener('executing', (e) => {\r\n if (!this.activePrompt) return\r\n\r\n if (executing) {\r\n // Seems sometimes nodes that are cached fire executing but not executed\r\n this.activePrompt.nodes[executing] = true\r\n }\r\n executing = e.detail\r\n if (!executing) {\r\n delete this.queuedPrompts[this.#activePromptId]\r\n this.#activePromptId = null\r\n }\r\n emit()\r\n })\r\n }\r\n\r\n async loadWorkflows() {\r\n try {\r\n let favorites\r\n const resp = await api.getUserData('workflows/.index.json')\r\n let info\r\n if (resp.status === 200) {\r\n info = await resp.json()\r\n favorites = new Set(info?.favorites ?? [])\r\n } else {\r\n favorites = new Set()\r\n }\r\n\r\n const workflows = (await api.listUserData('workflows', true, true)).map(\r\n (w) => {\r\n let workflow = this.workflowLookup[w[0]]\r\n if (!workflow) {\r\n workflow = new ComfyWorkflow(\r\n this,\r\n w[0],\r\n w.slice(1),\r\n favorites.has(w[0])\r\n )\r\n this.workflowLookup[workflow.path] = workflow\r\n }\r\n return workflow\r\n }\r\n )\r\n\r\n this.workflows = workflows\r\n } catch (error) {\r\n alert('Error loading workflows: ' + (error.message ?? error))\r\n this.workflows = []\r\n }\r\n }\r\n\r\n async saveWorkflowMetadata() {\r\n await api.storeUserData('workflows/.index.json', {\r\n favorites: [\r\n ...this.workflows.filter((w) => w.isFavorite).map((w) => w.path)\r\n ]\r\n })\r\n }\r\n\r\n /**\r\n * @param {string | ComfyWorkflow | null} workflow\r\n */\r\n setWorkflow(workflow) {\r\n if (workflow && typeof workflow === 'string') {\r\n // Selected by path, i.e. on reload of last workflow\r\n const found = this.workflows.find((w) => w.path === workflow)\r\n if (found) {\r\n workflow = found\r\n workflow.unsaved =\r\n !workflow ||\r\n getStorageValue('Comfy.PreviousWorkflowUnsaved') === 'true'\r\n }\r\n }\r\n\r\n if (!(workflow instanceof ComfyWorkflow)) {\r\n // Still not found, either reloading a deleted workflow or blank\r\n workflow = new ComfyWorkflow(\r\n this,\r\n workflow ||\r\n 'Unsaved Workflow' +\r\n (this.#unsavedCount++ ? ` (${this.#unsavedCount})` : '')\r\n )\r\n }\r\n\r\n const index = this.openWorkflows.indexOf(workflow)\r\n if (index === -1) {\r\n // Opening a new workflow\r\n this.openWorkflows.push(workflow)\r\n }\r\n\r\n this.#activeWorkflow = workflow\r\n\r\n setStorageValue('Comfy.PreviousWorkflow', this.activeWorkflow.path ?? '')\r\n this.dispatchEvent(new CustomEvent('changeWorkflow'))\r\n }\r\n\r\n storePrompt({ nodes, id }) {\r\n this.queuedPrompts[id] ??= {}\r\n this.queuedPrompts[id].nodes = {\r\n ...nodes.reduce((p, n) => {\r\n p[n] = false\r\n return p\r\n }, {}),\r\n ...this.queuedPrompts[id].nodes\r\n }\r\n this.queuedPrompts[id].workflow = this.activeWorkflow\r\n }\r\n\r\n /**\r\n * @param {ComfyWorkflow} workflow\r\n */\r\n async closeWorkflow(workflow, warnIfUnsaved = true) {\r\n if (!workflow.isOpen) {\r\n return true\r\n }\r\n if (workflow.unsaved && warnIfUnsaved) {\r\n const res = await ComfyAsyncDialog.prompt({\r\n title: 'Save Changes?',\r\n message: `Do you want to save changes to \"${workflow.path ?? workflow.name}\" before closing?`,\r\n actions: ['Yes', 'No', 'Cancel']\r\n })\r\n if (res === 'Yes') {\r\n const active = this.activeWorkflow\r\n if (active !== workflow) {\r\n // We need to switch to the workflow to save it\r\n await workflow.load()\r\n }\r\n\r\n if (!(await workflow.save())) {\r\n // Save was canceled, restore the previous workflow\r\n if (active !== workflow) {\r\n await active.load()\r\n }\r\n return\r\n }\r\n } else if (res === 'Cancel') {\r\n return\r\n }\r\n }\r\n workflow.changeTracker = null\r\n this.openWorkflows.splice(this.openWorkflows.indexOf(workflow), 1)\r\n if (this.openWorkflows.length) {\r\n this.#activeWorkflow = this.openWorkflows[0]\r\n await this.#activeWorkflow.load()\r\n } else {\r\n // Load default\r\n await this.app.loadGraphData()\r\n }\r\n }\r\n}\r\n\r\nexport class ComfyWorkflow {\r\n #name\r\n #path\r\n #pathParts\r\n #isFavorite = false\r\n changeTracker: ChangeTracker | null = null\r\n unsaved = false\r\n manager: ComfyWorkflowManager\r\n\r\n get name() {\r\n return this.#name\r\n }\r\n\r\n get path() {\r\n return this.#path\r\n }\r\n\r\n get pathParts() {\r\n return this.#pathParts\r\n }\r\n\r\n get isFavorite() {\r\n return this.#isFavorite\r\n }\r\n\r\n get isOpen() {\r\n return !!this.changeTracker\r\n }\r\n\r\n constructor(\r\n manager: ComfyWorkflowManager,\r\n path: string,\r\n pathParts?: string[],\r\n isFavorite?: boolean\r\n ) {\r\n this.manager = manager\r\n if (pathParts) {\r\n this.#updatePath(path, pathParts)\r\n this.#isFavorite = isFavorite\r\n } else {\r\n this.#name = path\r\n this.unsaved = true\r\n }\r\n }\r\n\r\n #updatePath(path: string, pathParts: string[]) {\r\n this.#path = path\r\n\r\n if (!pathParts) {\r\n if (!path.includes('\\\\')) {\r\n pathParts = path.split('/')\r\n } else {\r\n pathParts = path.split('\\\\')\r\n }\r\n }\r\n\r\n this.#pathParts = pathParts\r\n this.#name = trimJsonExt(pathParts[pathParts.length - 1])\r\n }\r\n\r\n async getWorkflowData() {\r\n const resp = await api.getUserData('workflows/' + this.path)\r\n if (resp.status !== 200) {\r\n alert(\r\n `Error loading workflow file '${this.path}': ${resp.status} ${resp.statusText}`\r\n )\r\n return\r\n }\r\n return await resp.json()\r\n }\r\n\r\n load = async () => {\r\n if (this.isOpen) {\r\n await this.manager.app.loadGraphData(\r\n this.changeTracker.activeState,\r\n true,\r\n true,\r\n this\r\n )\r\n } else {\r\n const data = await this.getWorkflowData()\r\n if (!data) return\r\n await this.manager.app.loadGraphData(data, true, true, this)\r\n }\r\n }\r\n\r\n async save(saveAs = false) {\r\n if (!this.path || saveAs) {\r\n return !!(await this.#save(null, false))\r\n } else {\r\n return !!(await this.#save(this.path, true))\r\n }\r\n }\r\n\r\n async favorite(value: boolean) {\r\n try {\r\n if (this.#isFavorite === value) return\r\n this.#isFavorite = value\r\n await this.manager.saveWorkflowMetadata()\r\n this.manager.dispatchEvent(new CustomEvent('favorite', { detail: this }))\r\n } catch (error) {\r\n alert(\r\n 'Error favoriting workflow ' +\r\n this.path +\r\n '\\n' +\r\n (error.message ?? error)\r\n )\r\n }\r\n }\r\n\r\n async rename(path: string) {\r\n path = appendJsonExt(path)\r\n let resp = await api.moveUserData(\r\n 'workflows/' + this.path,\r\n 'workflows/' + path\r\n )\r\n\r\n if (resp.status === 409) {\r\n if (\r\n !confirm(\r\n `Workflow '${path}' already exists, do you want to overwrite it?`\r\n )\r\n )\r\n return resp\r\n resp = await api.moveUserData(\r\n 'workflows/' + this.path,\r\n 'workflows/' + path,\r\n { overwrite: true }\r\n )\r\n }\r\n\r\n if (resp.status !== 200) {\r\n alert(\r\n `Error renaming workflow file '${this.path}': ${resp.status} ${resp.statusText}`\r\n )\r\n return\r\n }\r\n\r\n const isFav = this.isFavorite\r\n if (isFav) {\r\n await this.favorite(false)\r\n }\r\n path = (await resp.json()).substring('workflows/'.length)\r\n this.#updatePath(path, null)\r\n if (isFav) {\r\n await this.favorite(true)\r\n }\r\n this.manager.dispatchEvent(new CustomEvent('rename', { detail: this }))\r\n setStorageValue('Comfy.PreviousWorkflow', this.path ?? '')\r\n }\r\n\r\n async insert() {\r\n const data = await this.getWorkflowData()\r\n if (!data) return\r\n\r\n const old = localStorage.getItem('litegrapheditor_clipboard')\r\n const graph = new LGraph(data)\r\n const canvas = new LGraphCanvas(null, graph, {\r\n // @ts-expect-error\r\n skip_events: true,\r\n skip_render: true\r\n })\r\n canvas.selectNodes()\r\n canvas.copyToClipboard()\r\n this.manager.app.canvas.pasteFromClipboard()\r\n localStorage.setItem('litegrapheditor_clipboard', old)\r\n }\r\n\r\n async delete() {\r\n // TODO: fix delete of current workflow - should mark workflow as unsaved and when saving use old name by default\r\n\r\n try {\r\n if (this.isFavorite) {\r\n await this.favorite(false)\r\n }\r\n await api.deleteUserData('workflows/' + this.path)\r\n this.unsaved = true\r\n this.#path = null\r\n this.#pathParts = null\r\n this.manager.workflows.splice(this.manager.workflows.indexOf(this), 1)\r\n this.manager.dispatchEvent(new CustomEvent('delete', { detail: this }))\r\n } catch (error) {\r\n alert(`Error deleting workflow: ${error.message || error}`)\r\n }\r\n }\r\n\r\n track() {\r\n if (this.changeTracker) {\r\n this.changeTracker.restore()\r\n } else {\r\n this.changeTracker = new ChangeTracker(this)\r\n }\r\n }\r\n\r\n async #save(path: string | null, overwrite: boolean) {\r\n if (!path) {\r\n path = prompt(\r\n 'Save workflow as:',\r\n trimJsonExt(this.path) ?? this.name ?? 'workflow'\r\n )\r\n if (!path) return\r\n }\r\n\r\n path = appendJsonExt(path)\r\n\r\n const p = await this.manager.app.graphToPrompt()\r\n const json = JSON.stringify(p.workflow, null, 2)\r\n let resp = await api.storeUserData('workflows/' + path, json, {\r\n stringify: false,\r\n throwOnError: false,\r\n overwrite\r\n })\r\n if (resp.status === 409) {\r\n if (\r\n !confirm(\r\n `Workflow '${path}' already exists, do you want to overwrite it?`\r\n )\r\n )\r\n return\r\n resp = await api.storeUserData('workflows/' + path, json, {\r\n stringify: false\r\n })\r\n }\r\n\r\n if (resp.status !== 200) {\r\n alert(\r\n `Error saving workflow '${this.path}': ${resp.status} ${resp.statusText}`\r\n )\r\n return\r\n }\r\n\r\n path = (await resp.json()).substring('workflows/'.length)\r\n\r\n if (!this.path) {\r\n // Saved new workflow, patch this instance\r\n this.#updatePath(path, null)\r\n await this.manager.loadWorkflows()\r\n this.unsaved = false\r\n this.manager.dispatchEvent(new CustomEvent('rename', { detail: this }))\r\n setStorageValue('Comfy.PreviousWorkflow', this.path ?? '')\r\n } else if (path !== this.path) {\r\n // Saved as, open the new copy\r\n await this.manager.loadWorkflows()\r\n const workflow = this.manager.workflowLookup[path]\r\n await workflow.load()\r\n } else {\r\n // Normal save\r\n this.unsaved = false\r\n this.manager.dispatchEvent(new CustomEvent('save', { detail: this }))\r\n }\r\n\r\n return true\r\n }\r\n}\r\n","import { ComfyButton } from '../components/button'\r\nimport { prop, getStorageValue, setStorageValue } from '../../utils'\r\nimport { $el } from '../../ui'\r\nimport { api } from '../../api'\r\nimport { ComfyPopup } from '../components/popup'\r\nimport { createSpinner } from '../spinner'\r\nimport { ComfyWorkflow, trimJsonExt } from '../../workflows'\r\nimport { ComfyAsyncDialog } from '../components/asyncDialog'\r\nimport type { ComfyApp } from '@/scripts/app'\r\nimport type { ComfyComponent } from '../components'\r\n\r\nexport class ComfyWorkflowsMenu {\r\n #first = true\r\n element = $el('div.comfyui-workflows')\r\n popup: ComfyPopup\r\n app: ComfyApp\r\n buttonProgress: HTMLElement\r\n workflowLabel: HTMLElement\r\n button: ComfyButton\r\n content: ComfyWorkflowsContent\r\n unsaved: boolean\r\n\r\n get open() {\r\n return this.popup.open\r\n }\r\n\r\n set open(open) {\r\n this.popup.open = open\r\n }\r\n\r\n constructor(app: ComfyApp) {\r\n this.app = app\r\n this.#bindEvents()\r\n\r\n const classList = {\r\n 'comfyui-workflows-button': true,\r\n 'comfyui-button': true,\r\n unsaved: getStorageValue('Comfy.PreviousWorkflowUnsaved') === 'true',\r\n running: false\r\n }\r\n this.buttonProgress = $el('div.comfyui-workflows-button-progress')\r\n this.workflowLabel = $el('span.comfyui-workflows-label', '')\r\n this.button = new ComfyButton({\r\n content: $el('div.comfyui-workflows-button-inner', [\r\n $el('i.mdi.mdi-graph'),\r\n this.workflowLabel,\r\n this.buttonProgress\r\n ]),\r\n icon: 'chevron-down',\r\n classList\r\n })\r\n\r\n this.element.append(this.button.element)\r\n\r\n this.popup = new ComfyPopup({\r\n target: this.element,\r\n classList: 'comfyui-workflows-popup'\r\n })\r\n this.content = new ComfyWorkflowsContent(app, this.popup)\r\n this.popup.children = [this.content.element]\r\n this.popup.addEventListener('change', () => {\r\n this.button.icon = 'chevron-' + (this.popup.open ? 'up' : 'down')\r\n })\r\n this.button.withPopup(this.popup)\r\n\r\n this.unsaved = prop(this, 'unsaved', classList.unsaved, (v) => {\r\n classList.unsaved = v\r\n this.button.classList = classList\r\n setStorageValue('Comfy.PreviousWorkflowUnsaved', v)\r\n })\r\n }\r\n\r\n #updateProgress = () => {\r\n const prompt = this.app.workflowManager.activePrompt\r\n let percent = 0\r\n if (this.app.workflowManager.activeWorkflow === prompt?.workflow) {\r\n const total = Object.values(prompt.nodes)\r\n const done = total.filter(Boolean)\r\n percent = (done.length / total.length) * 100\r\n }\r\n this.buttonProgress.style.width = percent + '%'\r\n }\r\n\r\n #updateActive = () => {\r\n const active = this.app.workflowManager.activeWorkflow\r\n this.button.tooltip = active.path\r\n this.workflowLabel.textContent = active.name\r\n this.unsaved = active.unsaved\r\n\r\n if (this.#first) {\r\n this.#first = false\r\n this.content.load()\r\n }\r\n\r\n this.#updateProgress()\r\n }\r\n\r\n #bindEvents() {\r\n this.app.workflowManager.addEventListener(\r\n 'changeWorkflow',\r\n this.#updateActive\r\n )\r\n this.app.workflowManager.addEventListener('rename', this.#updateActive)\r\n this.app.workflowManager.addEventListener('delete', this.#updateActive)\r\n\r\n this.app.workflowManager.addEventListener('save', () => {\r\n this.unsaved = this.app.workflowManager.activeWorkflow.unsaved\r\n })\r\n\r\n this.app.workflowManager.addEventListener('execute', (e) => {\r\n this.#updateProgress()\r\n })\r\n\r\n api.addEventListener('graphChanged', () => {\r\n this.unsaved = true\r\n })\r\n }\r\n\r\n #getMenuOptions(callback) {\r\n const menu = []\r\n const directories = new Map()\r\n for (const workflow of this.app.workflowManager.workflows || []) {\r\n const path = workflow.pathParts\r\n if (!path) continue\r\n let parent = menu\r\n let currentPath = ''\r\n for (let i = 0; i < path.length - 1; i++) {\r\n currentPath += '/' + path[i]\r\n let newParent = directories.get(currentPath)\r\n if (!newParent) {\r\n newParent = {\r\n title: path[i],\r\n has_submenu: true,\r\n submenu: {\r\n options: []\r\n }\r\n }\r\n parent.push(newParent)\r\n newParent = newParent.submenu.options\r\n directories.set(currentPath, newParent)\r\n }\r\n parent = newParent\r\n }\r\n parent.push({\r\n title: trimJsonExt(path[path.length - 1]),\r\n callback: () => callback(workflow)\r\n })\r\n }\r\n return menu\r\n }\r\n\r\n #getFavoriteMenuOptions(callback) {\r\n const menu = []\r\n for (const workflow of this.app.workflowManager.workflows || []) {\r\n if (workflow.isFavorite) {\r\n menu.push({\r\n title: '⭐ ' + workflow.name,\r\n callback: () => callback(workflow)\r\n })\r\n }\r\n }\r\n return menu\r\n }\r\n\r\n registerExtension(app: ComfyApp) {\r\n const self = this\r\n app.registerExtension({\r\n name: 'Comfy.Workflows',\r\n async beforeRegisterNodeDef(nodeType) {\r\n function getImageWidget(node) {\r\n const inputs = {\r\n ...node.constructor?.nodeData?.input?.required,\r\n ...node.constructor?.nodeData?.input?.optional\r\n }\r\n for (const input in inputs) {\r\n if (inputs[input][0] === 'IMAGEUPLOAD') {\r\n const imageWidget = node.widgets.find(\r\n (w) => w.name === (inputs[input]?.[1]?.widget ?? 'image')\r\n )\r\n if (imageWidget) return imageWidget\r\n }\r\n }\r\n }\r\n\r\n function setWidgetImage(node, widget, img) {\r\n const url = new URL(img.src)\r\n const filename = url.searchParams.get('filename')\r\n const subfolder = url.searchParams.get('subfolder')\r\n const type = url.searchParams.get('type')\r\n const imageId = `${subfolder ? subfolder + '/' : ''}${filename} [${type}]`\r\n widget.value = imageId\r\n node.imgs = [img]\r\n app.graph.setDirtyCanvas(true, true)\r\n }\r\n\r\n async function sendToWorkflow(\r\n img: HTMLImageElement,\r\n workflow: ComfyWorkflow\r\n ) {\r\n const openWorkflow = app.workflowManager.openWorkflows.find(\r\n (w) => w.path === workflow.path\r\n )\r\n if (openWorkflow) {\r\n workflow = openWorkflow\r\n }\r\n\r\n await workflow.load()\r\n let options = []\r\n const nodes = app.graph.computeExecutionOrder(false)\r\n for (const node of nodes) {\r\n const widget = getImageWidget(node)\r\n if (widget == null) continue\r\n\r\n if (node.title?.toLowerCase().includes('input')) {\r\n options = [{ widget, node }]\r\n break\r\n } else {\r\n options.push({ widget, node })\r\n }\r\n }\r\n\r\n if (!options.length) {\r\n alert('No image nodes have been found in this workflow!')\r\n return\r\n } else if (options.length > 1) {\r\n const dialog = new WidgetSelectionDialog(options)\r\n const res = await dialog.show(app)\r\n if (!res) return\r\n options = [res]\r\n }\r\n\r\n setWidgetImage(options[0].node, options[0].widget, img)\r\n }\r\n\r\n const getExtraMenuOptions = nodeType.prototype['getExtraMenuOptions']\r\n nodeType.prototype['getExtraMenuOptions'] = function (\r\n this: { imageIndex?: number; overIndex?: number; imgs: string[] },\r\n _,\r\n options\r\n ) {\r\n const r = getExtraMenuOptions?.apply?.(this, arguments)\r\n const setting = app.ui.settings.getSettingValue(\r\n 'Comfy.UseNewMenu',\r\n false\r\n )\r\n if (setting && setting != 'Disabled') {\r\n const t = this\r\n let img\r\n if (t.imageIndex != null) {\r\n // An image is selected so select that\r\n img = t.imgs?.[t.imageIndex]\r\n } else if (t.overIndex != null) {\r\n // No image is selected but one is hovered\r\n img = t.imgs?.[t.overIndex]\r\n }\r\n\r\n if (img) {\r\n let pos = options.findIndex((o) => o.content === 'Save Image')\r\n if (pos === -1) {\r\n pos = 0\r\n } else {\r\n pos++\r\n }\r\n\r\n options.splice(pos, 0, {\r\n content: 'Send to workflow',\r\n has_submenu: true,\r\n submenu: {\r\n options: [\r\n {\r\n callback: () =>\r\n sendToWorkflow(img, app.workflowManager.activeWorkflow),\r\n title: '[Current workflow]'\r\n },\r\n ...self.#getFavoriteMenuOptions(\r\n sendToWorkflow.bind(null, img)\r\n ),\r\n null,\r\n ...self.#getMenuOptions(sendToWorkflow.bind(null, img))\r\n ]\r\n }\r\n })\r\n }\r\n }\r\n\r\n return r\r\n }\r\n }\r\n })\r\n }\r\n}\r\n\r\nexport class ComfyWorkflowsContent {\r\n element = $el('div.comfyui-workflows-panel')\r\n treeState = {}\r\n treeFiles: Record = {}\r\n openFiles: Map> = new Map()\r\n activeElement: WorkflowElement = null\r\n spinner: Element\r\n openElement: HTMLElement\r\n favoritesElement: HTMLElement\r\n treeElement: HTMLElement\r\n app: ComfyApp\r\n popup: ComfyPopup\r\n actions: HTMLElement\r\n filterText: string | undefined\r\n treeRoot: HTMLElement\r\n\r\n constructor(app: ComfyApp, popup: ComfyPopup) {\r\n this.app = app\r\n this.popup = popup\r\n this.actions = $el('div.comfyui-workflows-actions', [\r\n new ComfyButton({\r\n content: 'Default',\r\n icon: 'file-code',\r\n iconSize: 18,\r\n classList: 'comfyui-button primary',\r\n tooltip: 'Load default workflow',\r\n action: () => {\r\n popup.open = false\r\n app.loadGraphData()\r\n app.resetView()\r\n }\r\n }).element,\r\n new ComfyButton({\r\n content: 'Browse',\r\n icon: 'folder',\r\n iconSize: 18,\r\n tooltip: 'Browse for an image or exported workflow',\r\n action: () => {\r\n popup.open = false\r\n app.ui.loadFile()\r\n }\r\n }).element,\r\n new ComfyButton({\r\n content: 'Blank',\r\n icon: 'plus-thick',\r\n iconSize: 18,\r\n tooltip: 'Create a new blank workflow',\r\n action: () => {\r\n app.workflowManager.setWorkflow(null)\r\n app.clean()\r\n app.graph.clear()\r\n app.workflowManager.activeWorkflow.track()\r\n popup.open = false\r\n }\r\n }).element\r\n ])\r\n\r\n this.spinner = createSpinner()\r\n this.element.replaceChildren(this.actions, this.spinner)\r\n\r\n this.popup.addEventListener('open', () => this.load())\r\n this.popup.addEventListener('close', () =>\r\n this.element.replaceChildren(this.actions, this.spinner)\r\n )\r\n\r\n this.app.workflowManager.addEventListener('favorite', (e) => {\r\n const workflow = e['detail']\r\n const button = this.treeFiles[workflow.path]?.primary\r\n if (!button) return // Can happen when a workflow is renamed\r\n button.icon = this.#getFavoriteIcon(workflow)\r\n button.overIcon = this.#getFavoriteOverIcon(workflow)\r\n this.updateFavorites()\r\n })\r\n\r\n for (const e of ['save', 'open', 'close', 'changeWorkflow']) {\r\n // TODO: dont be lazy and just update the specific element\r\n app.workflowManager.addEventListener(e, () => this.updateOpen())\r\n }\r\n this.app.workflowManager.addEventListener('rename', () => this.load())\r\n this.app.workflowManager.addEventListener('execute', (e) =>\r\n this.#updateActive()\r\n )\r\n }\r\n\r\n async load() {\r\n await this.app.workflowManager.loadWorkflows()\r\n this.updateTree()\r\n this.updateFavorites()\r\n this.updateOpen()\r\n this.element.replaceChildren(\r\n this.actions,\r\n this.openElement,\r\n this.favoritesElement,\r\n this.treeElement\r\n )\r\n }\r\n\r\n updateOpen() {\r\n const current = this.openElement\r\n this.openFiles.clear()\r\n\r\n this.openElement = $el('div.comfyui-workflows-open', [\r\n $el('h3', 'Open'),\r\n ...this.app.workflowManager.openWorkflows.map((w) => {\r\n const wrapper = new WorkflowElement(this, w, {\r\n primary: { element: $el('i.mdi.mdi-18px.mdi-progress-pencil') },\r\n buttons: [\r\n this.#getRenameButton(w),\r\n new ComfyButton({\r\n icon: 'close',\r\n iconSize: 18,\r\n classList: 'comfyui-button comfyui-workflows-file-action',\r\n tooltip: 'Close workflow',\r\n action: (e) => {\r\n e.stopImmediatePropagation()\r\n this.app.workflowManager.closeWorkflow(w)\r\n }\r\n })\r\n ]\r\n })\r\n if (w.unsaved) {\r\n wrapper.element.classList.add('unsaved')\r\n }\r\n if (w === this.app.workflowManager.activeWorkflow) {\r\n wrapper.element.classList.add('active')\r\n }\r\n\r\n this.openFiles.set(w, wrapper)\r\n return wrapper.element\r\n })\r\n ])\r\n\r\n this.#updateActive()\r\n current?.replaceWith(this.openElement)\r\n }\r\n\r\n updateFavorites() {\r\n const current = this.favoritesElement\r\n const favorites = [\r\n ...this.app.workflowManager.workflows.filter((w) => w.isFavorite)\r\n ]\r\n\r\n this.favoritesElement = $el('div.comfyui-workflows-favorites', [\r\n $el('h3', 'Favorites'),\r\n ...favorites\r\n .map((w) => {\r\n return this.#getWorkflowElement(w).element\r\n })\r\n .filter(Boolean)\r\n ])\r\n\r\n current?.replaceWith(this.favoritesElement)\r\n }\r\n\r\n filterTree() {\r\n if (!this.filterText) {\r\n this.treeRoot.classList.remove('filtered')\r\n // Unfilter whole tree\r\n for (const item of Object.values(this.treeFiles)) {\r\n item.element.parentElement.style.removeProperty('display')\r\n this.showTreeParents(item.element.parentElement)\r\n }\r\n return\r\n }\r\n this.treeRoot.classList.add('filtered')\r\n const searchTerms = this.filterText.toLocaleLowerCase().split(' ')\r\n for (const item of Object.values(this.treeFiles)) {\r\n const parts = item.workflow.pathParts\r\n let termIndex = 0\r\n let valid = false\r\n for (const part of parts) {\r\n let currentIndex = 0\r\n do {\r\n currentIndex = part.indexOf(searchTerms[termIndex], currentIndex)\r\n if (currentIndex > -1) currentIndex += searchTerms[termIndex].length\r\n } while (currentIndex !== -1 && ++termIndex < searchTerms.length)\r\n\r\n if (termIndex >= searchTerms.length) {\r\n valid = true\r\n break\r\n }\r\n }\r\n if (valid) {\r\n item.element.parentElement.style.removeProperty('display')\r\n this.showTreeParents(item.element.parentElement)\r\n } else {\r\n item.element.parentElement.style.display = 'none'\r\n this.hideTreeParents(item.element.parentElement)\r\n }\r\n }\r\n }\r\n\r\n hideTreeParents(element) {\r\n // Hide all parents if no children are visible\r\n if (\r\n element.parentElement?.classList.contains('comfyui-workflows-tree') ===\r\n false\r\n ) {\r\n for (let i = 1; i < element.parentElement.children.length; i++) {\r\n const c = element.parentElement.children[i]\r\n if (c.style.display !== 'none') {\r\n return\r\n }\r\n }\r\n element.parentElement.style.display = 'none'\r\n this.hideTreeParents(element.parentElement)\r\n }\r\n }\r\n\r\n showTreeParents(element) {\r\n if (\r\n element.parentElement?.classList.contains('comfyui-workflows-tree') ===\r\n false\r\n ) {\r\n element.parentElement.style.removeProperty('display')\r\n this.showTreeParents(element.parentElement)\r\n }\r\n }\r\n\r\n updateTree() {\r\n const current = this.treeElement\r\n const nodes = {}\r\n let typingTimeout\r\n\r\n this.treeFiles = {}\r\n this.treeRoot = $el('ul.comfyui-workflows-tree')\r\n this.treeElement = $el('section', [\r\n $el('header', [\r\n $el('h3', 'Browse'),\r\n $el('div.comfy-ui-workflows-search', [\r\n $el('i.mdi.mdi-18px.mdi-magnify'),\r\n $el('input', {\r\n placeholder: 'Search',\r\n value: this.filterText ?? '',\r\n oninput: (e: InputEvent) => {\r\n this.filterText = e.target['value']?.trim()\r\n clearTimeout(typingTimeout)\r\n typingTimeout = setTimeout(() => this.filterTree(), 250)\r\n }\r\n })\r\n ])\r\n ]),\r\n this.treeRoot\r\n ])\r\n\r\n for (const workflow of this.app.workflowManager.workflows) {\r\n if (!workflow.pathParts) continue\r\n\r\n let currentPath = ''\r\n let currentRoot = this.treeRoot\r\n\r\n for (let i = 0; i < workflow.pathParts.length; i++) {\r\n currentPath += (currentPath ? '\\\\' : '') + workflow.pathParts[i]\r\n const parentNode =\r\n nodes[currentPath] ??\r\n this.#createNode(currentPath, workflow, i, currentRoot)\r\n\r\n nodes[currentPath] = parentNode\r\n currentRoot = parentNode\r\n }\r\n }\r\n\r\n current?.replaceWith(this.treeElement)\r\n this.filterTree()\r\n }\r\n\r\n #expandNode(el, workflow, thisPath, i) {\r\n const expanded = !el.classList.toggle('closed')\r\n if (expanded) {\r\n let c = ''\r\n for (let j = 0; j <= i; j++) {\r\n c += (c ? '\\\\' : '') + workflow.pathParts[j]\r\n this.treeState[c] = true\r\n }\r\n } else {\r\n let c = thisPath\r\n for (let j = i + 1; j < workflow.pathParts.length; j++) {\r\n c += (c ? '\\\\' : '') + workflow.pathParts[j]\r\n delete this.treeState[c]\r\n }\r\n delete this.treeState[thisPath]\r\n }\r\n }\r\n\r\n #updateActive() {\r\n this.#removeActive()\r\n\r\n const active = this.app.workflowManager.activePrompt\r\n if (!active?.workflow) return\r\n\r\n const open = this.openFiles.get(active.workflow)\r\n if (!open) return\r\n\r\n this.activeElement = open\r\n\r\n const total = Object.values(active.nodes)\r\n const done = total.filter(Boolean)\r\n const percent = done.length / total.length\r\n open.element.classList.add('running')\r\n open.element.style.setProperty('--progress', percent * 100 + '%')\r\n open.primary.element.classList.remove('mdi-progress-pencil')\r\n open.primary.element.classList.add('mdi-play')\r\n }\r\n\r\n #removeActive() {\r\n if (!this.activeElement) return\r\n this.activeElement.element.classList.remove('running')\r\n this.activeElement.element.style.removeProperty('--progress')\r\n this.activeElement.primary.element.classList.add('mdi-progress-pencil')\r\n this.activeElement.primary.element.classList.remove('mdi-play')\r\n }\r\n\r\n #getFavoriteIcon(workflow: ComfyWorkflow) {\r\n return workflow.isFavorite ? 'star' : 'file-outline'\r\n }\r\n\r\n #getFavoriteOverIcon(workflow: ComfyWorkflow) {\r\n return workflow.isFavorite ? 'star-off' : 'star-outline'\r\n }\r\n\r\n #getFavoriteTooltip(workflow: ComfyWorkflow) {\r\n return workflow.isFavorite\r\n ? 'Remove this workflow from your favorites'\r\n : 'Add this workflow to your favorites'\r\n }\r\n\r\n #getFavoriteButton(workflow: ComfyWorkflow, primary: boolean) {\r\n return new ComfyButton({\r\n icon: this.#getFavoriteIcon(workflow),\r\n overIcon: this.#getFavoriteOverIcon(workflow),\r\n iconSize: 18,\r\n classList:\r\n 'comfyui-button comfyui-workflows-file-action-favorite' +\r\n (primary ? ' comfyui-workflows-file-action-primary' : ''),\r\n tooltip: this.#getFavoriteTooltip(workflow),\r\n action: (e) => {\r\n e.stopImmediatePropagation()\r\n workflow.favorite(!workflow.isFavorite)\r\n }\r\n })\r\n }\r\n\r\n #getDeleteButton(workflow: ComfyWorkflow) {\r\n const deleteButton = new ComfyButton({\r\n icon: 'delete',\r\n tooltip: 'Delete this workflow',\r\n classList: 'comfyui-button comfyui-workflows-file-action',\r\n iconSize: 18,\r\n action: async (e, btn) => {\r\n e.stopImmediatePropagation()\r\n\r\n if (btn.icon === 'delete-empty') {\r\n btn.enabled = false\r\n await workflow.delete()\r\n await this.load()\r\n } else {\r\n btn.icon = 'delete-empty'\r\n btn.element.style.background = 'red'\r\n }\r\n }\r\n })\r\n deleteButton.element.addEventListener('mouseleave', () => {\r\n deleteButton.icon = 'delete'\r\n deleteButton.element.style.removeProperty('background')\r\n })\r\n return deleteButton\r\n }\r\n\r\n #getInsertButton(workflow: ComfyWorkflow) {\r\n return new ComfyButton({\r\n icon: 'file-move-outline',\r\n iconSize: 18,\r\n tooltip: 'Insert this workflow into the current workflow',\r\n classList: 'comfyui-button comfyui-workflows-file-action',\r\n action: (e) => {\r\n if (!this.app.shiftDown) {\r\n this.popup.open = false\r\n }\r\n e.stopImmediatePropagation()\r\n if (!this.app.shiftDown) {\r\n this.popup.open = false\r\n }\r\n workflow.insert()\r\n }\r\n })\r\n }\r\n\r\n /** @param {ComfyWorkflow} workflow */\r\n #getRenameButton(workflow: ComfyWorkflow) {\r\n return new ComfyButton({\r\n icon: 'pencil',\r\n tooltip: workflow.path\r\n ? 'Rename this workflow'\r\n : \"This workflow can't be renamed as it hasn't been saved.\",\r\n classList: 'comfyui-button comfyui-workflows-file-action',\r\n iconSize: 18,\r\n enabled: !!workflow.path,\r\n action: async (e) => {\r\n e.stopImmediatePropagation()\r\n const newName = prompt('Enter new name', workflow.path)\r\n if (newName) {\r\n await workflow.rename(newName)\r\n }\r\n }\r\n })\r\n }\r\n\r\n #getWorkflowElement(workflow: ComfyWorkflow) {\r\n return new WorkflowElement(this, workflow, {\r\n primary: this.#getFavoriteButton(workflow, true),\r\n buttons: [\r\n this.#getInsertButton(workflow),\r\n this.#getRenameButton(workflow),\r\n this.#getDeleteButton(workflow)\r\n ]\r\n })\r\n }\r\n\r\n #createLeafNode(workflow: ComfyWorkflow) {\r\n const fileNode = this.#getWorkflowElement(workflow)\r\n this.treeFiles[workflow.path] = fileNode\r\n return fileNode\r\n }\r\n\r\n #createNode(currentPath, workflow, i, currentRoot) {\r\n const part = workflow.pathParts[i]\r\n\r\n const parentNode = $el(\r\n 'ul' + (this.treeState[currentPath] ? '' : '.closed'),\r\n {\r\n $: (el) => {\r\n el.onclick = (e) => {\r\n this.#expandNode(el, workflow, currentPath, i)\r\n e.stopImmediatePropagation()\r\n }\r\n }\r\n }\r\n )\r\n currentRoot.append(parentNode)\r\n\r\n // Create a node for the current part and an inner UL for its children if it isnt a leaf node\r\n const leaf = i === workflow.pathParts.length - 1\r\n let nodeElement\r\n if (leaf) {\r\n nodeElement = this.#createLeafNode(workflow).element\r\n } else {\r\n nodeElement = $el('li', [\r\n $el('i.mdi.mdi-18px.mdi-folder'),\r\n $el('span', part)\r\n ])\r\n }\r\n parentNode.append(nodeElement)\r\n return parentNode\r\n }\r\n}\r\n\r\nclass WorkflowElement {\r\n parent: ComfyWorkflowsContent\r\n workflow: ComfyWorkflow\r\n primary: TPrimary\r\n buttons: ComfyButton[]\r\n element: HTMLElement\r\n constructor(\r\n parent: ComfyWorkflowsContent,\r\n workflow: ComfyWorkflow,\r\n {\r\n tagName = 'li',\r\n primary,\r\n buttons\r\n }: { tagName?: string; primary: TPrimary; buttons: ComfyButton[] }\r\n ) {\r\n this.parent = parent\r\n this.workflow = workflow\r\n this.primary = primary\r\n this.buttons = buttons\r\n\r\n this.element = $el(\r\n tagName + '.comfyui-workflows-tree-file',\r\n {\r\n onclick: () => {\r\n workflow.load()\r\n this.parent.popup.open = false\r\n },\r\n title: this.workflow.path\r\n },\r\n [\r\n this.primary?.element,\r\n $el('span', workflow.name),\r\n ...buttons.map((b) => b.element)\r\n ]\r\n )\r\n }\r\n}\r\n\r\ntype WidgetSelectionDialogOptions = Array<{\r\n widget: { name: string }\r\n node: { pos: [number, number]; title: string; id: string; type: string }\r\n}>\r\n\r\nclass WidgetSelectionDialog extends ComfyAsyncDialog {\r\n #options: WidgetSelectionDialogOptions\r\n\r\n constructor(options: WidgetSelectionDialogOptions) {\r\n super()\r\n this.#options = options\r\n }\r\n\r\n show(app) {\r\n this.element.classList.add('comfy-widget-selection-dialog')\r\n return super.show(\r\n $el('div', [\r\n $el('h2', 'Select image target'),\r\n $el(\r\n 'p',\r\n \"This workflow has multiple image loader nodes, you can rename a node to include 'input' in the title for it to be automatically selected, or select one below.\"\r\n ),\r\n $el(\r\n 'section',\r\n this.#options.map((opt) => {\r\n return $el('div.comfy-widget-selection-item', [\r\n $el(\r\n 'span',\r\n { dataset: { id: opt.node.id } },\r\n `${opt.node.title ?? opt.node.type} ${opt.widget.name}`\r\n ),\r\n $el(\r\n 'button.comfyui-button',\r\n {\r\n onclick: () => {\r\n app.canvas.ds.offset[0] = -opt.node.pos[0] + 50\r\n app.canvas.ds.offset[1] = -opt.node.pos[1] + 50\r\n app.canvas.selectNode(opt.node)\r\n app.graph.setDirtyCanvas(true, true)\r\n }\r\n },\r\n 'Show'\r\n ),\r\n $el(\r\n 'button.comfyui-button.primary',\r\n {\r\n onclick: () => {\r\n this.close(opt)\r\n }\r\n },\r\n 'Select'\r\n )\r\n ])\r\n })\r\n )\r\n ])\r\n )\r\n }\r\n}\r\n","import { StatusWsMessageStatus } from '@/types/apiTypes'\r\nimport { api } from '../../api'\r\nimport { ComfyButton } from '../components/button'\r\n\r\nexport function getInterruptButton(visibility: string) {\r\n const btn = new ComfyButton({\r\n icon: 'close',\r\n tooltip: 'Cancel current generation',\r\n enabled: false,\r\n action: () => {\r\n api.interrupt()\r\n },\r\n classList: ['comfyui-button', 'comfyui-interrupt-button', visibility]\r\n })\r\n\r\n api.addEventListener(\r\n 'status',\r\n ({ detail }: CustomEvent) => {\r\n const sz = detail?.exec_info?.queue_remaining\r\n btn.enabled = sz > 0\r\n }\r\n )\r\n\r\n return btn\r\n}\r\n","import type { ComfyApp } from '@/scripts/app'\r\nimport { api } from '../../api'\r\nimport { $el } from '../../ui'\r\nimport { downloadBlob } from '../../utils'\r\nimport { ComfyButton } from '../components/button'\r\nimport { ComfyButtonGroup } from '../components/buttonGroup'\r\nimport { ComfySplitButton } from '../components/splitButton'\r\nimport { ComfyQueueButton } from './queueButton'\r\nimport { ComfyWorkflowsMenu } from './workflows'\r\nimport { getInterruptButton } from './interruptButton'\r\nimport './menu.css'\r\nimport type { ComfySettingsDialog } from '../settings'\r\n\r\ntype MenuPosition = 'Disabled' | 'Top' | 'Bottom'\r\n\r\nconst collapseOnMobile = (t) => {\r\n ;(t.element ?? t).classList.add('comfyui-menu-mobile-collapse')\r\n return t\r\n}\r\nconst showOnMobile = (t) => {\r\n ;(t.element ?? t).classList.add('lt-lg-show')\r\n return t\r\n}\r\n\r\nexport class ComfyAppMenu {\r\n #sizeBreak = 'lg'\r\n #lastSizeBreaks = {\r\n lg: null,\r\n md: null,\r\n sm: null,\r\n xs: null\r\n }\r\n #sizeBreaks = Object.keys(this.#lastSizeBreaks)\r\n #cachedInnerSize = null\r\n #cacheTimeout = null\r\n app: ComfyApp\r\n workflows: ComfyWorkflowsMenu\r\n logo: HTMLElement\r\n saveButton: ComfySplitButton\r\n actionsGroup: ComfyButtonGroup\r\n settingsGroup: ComfyButtonGroup\r\n viewGroup: ComfyButtonGroup\r\n mobileMenuButton: ComfyButton\r\n queueButton: ComfyQueueButton\r\n element: HTMLElement\r\n menuPositionSetting: ReturnType\r\n position: MenuPosition\r\n\r\n constructor(app: ComfyApp) {\r\n this.app = app\r\n\r\n this.workflows = new ComfyWorkflowsMenu(app)\r\n const getSaveButton = (t?: string) =>\r\n new ComfyButton({\r\n icon: 'content-save',\r\n tooltip: 'Save the current workflow',\r\n action: () => app.workflowManager.activeWorkflow.save(),\r\n content: t\r\n })\r\n\r\n this.logo = $el('h1.comfyui-logo.nlg-hide', { title: 'ComfyUI' }, 'ComfyUI')\r\n this.saveButton = new ComfySplitButton(\r\n {\r\n primary: getSaveButton(),\r\n mode: 'hover',\r\n position: 'absolute'\r\n },\r\n getSaveButton('Save'),\r\n new ComfyButton({\r\n icon: 'content-save-edit',\r\n content: 'Save As',\r\n tooltip: 'Save the current graph as a new workflow',\r\n action: () => app.workflowManager.activeWorkflow.save(true)\r\n }),\r\n new ComfyButton({\r\n icon: 'download',\r\n content: 'Export',\r\n tooltip: 'Export the current workflow as JSON',\r\n action: () => this.exportWorkflow('workflow', 'workflow')\r\n }),\r\n new ComfyButton({\r\n icon: 'api',\r\n content: 'Export (API Format)',\r\n tooltip:\r\n 'Export the current workflow as JSON for use with the ComfyUI API',\r\n action: () => this.exportWorkflow('workflow_api', 'output'),\r\n visibilitySetting: { id: 'Comfy.DevMode', showValue: true },\r\n app\r\n })\r\n )\r\n this.actionsGroup = new ComfyButtonGroup(\r\n new ComfyButton({\r\n icon: 'refresh',\r\n content: 'Refresh',\r\n tooltip: 'Refresh widgets in nodes to find new models or files',\r\n action: () => app.refreshComboInNodes()\r\n }),\r\n new ComfyButton({\r\n icon: 'clipboard-edit-outline',\r\n content: 'Clipspace',\r\n tooltip: 'Open Clipspace window',\r\n action: () => app['openClipspace']()\r\n }),\r\n new ComfyButton({\r\n icon: 'fit-to-page-outline',\r\n content: 'Reset View',\r\n tooltip: 'Reset the canvas view',\r\n action: () => app.resetView()\r\n }),\r\n new ComfyButton({\r\n icon: 'cancel',\r\n content: 'Clear',\r\n tooltip: 'Clears current workflow',\r\n action: () => {\r\n if (\r\n !app.ui.settings.getSettingValue('Comfy.ConfirmClear', true) ||\r\n confirm('Clear workflow?')\r\n ) {\r\n app.clean()\r\n app.graph.clear()\r\n api.dispatchEvent(new CustomEvent('graphCleared'))\r\n }\r\n }\r\n })\r\n )\r\n // Keep the settings group as there are custom scripts attaching extra\r\n // elements to it.\r\n this.settingsGroup = new ComfyButtonGroup()\r\n this.viewGroup = new ComfyButtonGroup(\r\n getInterruptButton('nlg-hide').element\r\n )\r\n this.mobileMenuButton = new ComfyButton({\r\n icon: 'menu',\r\n action: (_, btn) => {\r\n btn.icon = this.element.classList.toggle('expanded')\r\n ? 'menu-open'\r\n : 'menu'\r\n window.dispatchEvent(new Event('resize'))\r\n },\r\n classList: 'comfyui-button comfyui-menu-button'\r\n })\r\n this.queueButton = new ComfyQueueButton(app)\r\n\r\n this.element = $el('nav.comfyui-menu.lg', { style: { display: 'none' } }, [\r\n this.logo,\r\n this.workflows.element,\r\n this.saveButton.element,\r\n collapseOnMobile(this.actionsGroup).element,\r\n $el('section.comfyui-menu-push'),\r\n collapseOnMobile(this.settingsGroup).element,\r\n collapseOnMobile(this.viewGroup).element,\r\n\r\n getInterruptButton('lt-lg-show').element,\r\n this.queueButton.element,\r\n showOnMobile(this.mobileMenuButton).element\r\n ])\r\n\r\n let resizeHandler: () => void\r\n this.menuPositionSetting = app.ui.settings.addSetting({\r\n id: 'Comfy.UseNewMenu',\r\n defaultValue: 'Disabled',\r\n name: '[Beta] Use new menu and workflow management. Note: On small screens the menu will always be at the top.',\r\n type: 'combo',\r\n options: ['Disabled', 'Top', 'Bottom'],\r\n onChange: async (v: MenuPosition) => {\r\n if (v && v !== 'Disabled') {\r\n if (!resizeHandler) {\r\n resizeHandler = () => {\r\n this.calculateSizeBreak()\r\n }\r\n window.addEventListener('resize', resizeHandler)\r\n }\r\n this.updatePosition(v)\r\n } else {\r\n if (resizeHandler) {\r\n window.removeEventListener('resize', resizeHandler)\r\n resizeHandler = null\r\n }\r\n document.body.style.removeProperty('display')\r\n app.ui.menuContainer.style.removeProperty('display')\r\n this.element.style.display = 'none'\r\n app.ui.restoreMenuPosition()\r\n }\r\n window.dispatchEvent(new Event('resize'))\r\n }\r\n })\r\n }\r\n\r\n updatePosition(v: MenuPosition) {\r\n document.body.style.display = 'grid'\r\n this.app.ui.menuContainer.style.display = 'none'\r\n this.element.style.removeProperty('display')\r\n this.position = v\r\n if (v === 'Bottom') {\r\n this.app.bodyBottom.append(this.element)\r\n } else {\r\n this.app.bodyTop.prepend(this.element)\r\n }\r\n this.calculateSizeBreak()\r\n }\r\n\r\n updateSizeBreak(idx: number, prevIdx: number, direction: number) {\r\n const newSize = this.#sizeBreaks[idx]\r\n if (newSize === this.#sizeBreak) return\r\n this.#cachedInnerSize = null\r\n clearTimeout(this.#cacheTimeout)\r\n\r\n this.#sizeBreak = this.#sizeBreaks[idx]\r\n for (let i = 0; i < this.#sizeBreaks.length; i++) {\r\n const sz = this.#sizeBreaks[i]\r\n if (sz === this.#sizeBreak) {\r\n this.element.classList.add(sz)\r\n } else {\r\n this.element.classList.remove(sz)\r\n }\r\n if (i < idx) {\r\n this.element.classList.add('lt-' + sz)\r\n } else {\r\n this.element.classList.remove('lt-' + sz)\r\n }\r\n }\r\n\r\n if (idx) {\r\n // We're on a small screen, force the menu at the top\r\n if (this.position !== 'Top') {\r\n this.updatePosition('Top')\r\n }\r\n } else if (this.position != this.menuPositionSetting.value) {\r\n // Restore user position\r\n this.updatePosition(this.menuPositionSetting.value)\r\n }\r\n\r\n // Allow multiple updates, but prevent bouncing\r\n if (!direction) {\r\n direction = prevIdx - idx\r\n } else if (direction != prevIdx - idx) {\r\n return\r\n }\r\n this.calculateSizeBreak(direction)\r\n }\r\n\r\n calculateSizeBreak(direction = 0) {\r\n let idx = this.#sizeBreaks.indexOf(this.#sizeBreak)\r\n const currIdx = idx\r\n const innerSize = this.calculateInnerSize(idx)\r\n if (window.innerWidth >= this.#lastSizeBreaks[this.#sizeBreaks[idx - 1]]) {\r\n if (idx > 0) {\r\n idx--\r\n }\r\n } else if (innerSize > this.element.clientWidth) {\r\n this.#lastSizeBreaks[this.#sizeBreak] = Math.max(\r\n window.innerWidth,\r\n innerSize\r\n )\r\n // We need to shrink\r\n if (idx < this.#sizeBreaks.length - 1) {\r\n idx++\r\n }\r\n }\r\n\r\n this.updateSizeBreak(idx, currIdx, direction)\r\n }\r\n\r\n calculateInnerSize(idx: number) {\r\n // Cache the inner size to prevent too much calculation when resizing the window\r\n clearTimeout(this.#cacheTimeout)\r\n if (this.#cachedInnerSize) {\r\n // Extend cache time\r\n this.#cacheTimeout = setTimeout(() => (this.#cachedInnerSize = null), 100)\r\n } else {\r\n let innerSize = 0\r\n let count = 1\r\n for (const c of this.element.children) {\r\n if (c.classList.contains('comfyui-menu-push')) continue // ignore right push\r\n if (idx && c.classList.contains('comfyui-menu-mobile-collapse'))\r\n continue // ignore collapse items\r\n innerSize += c.clientWidth\r\n count++\r\n }\r\n innerSize += 8 * count\r\n this.#cachedInnerSize = innerSize\r\n this.#cacheTimeout = setTimeout(() => (this.#cachedInnerSize = null), 100)\r\n }\r\n return this.#cachedInnerSize\r\n }\r\n\r\n getFilename(defaultName: string) {\r\n if (this.app.ui.settings.getSettingValue('Comfy.PromptFilename', true)) {\r\n defaultName = prompt('Save workflow as:', defaultName)\r\n if (!defaultName) return\r\n if (!defaultName.toLowerCase().endsWith('.json')) {\r\n defaultName += '.json'\r\n }\r\n }\r\n return defaultName\r\n }\r\n\r\n async exportWorkflow(\r\n filename: string,\r\n promptProperty: 'workflow' | 'output'\r\n ) {\r\n if (this.app.workflowManager.activeWorkflow?.path) {\r\n filename = this.app.workflowManager.activeWorkflow.name\r\n }\r\n const p = await this.app.graphToPrompt()\r\n const json = JSON.stringify(p[promptProperty], null, 2)\r\n const blob = new Blob([json], { type: 'application/json' })\r\n const file = this.getFilename(filename)\r\n if (!file) return\r\n downloadBlob(file, blob)\r\n }\r\n}\r\n","export type NodeSourceType = 'core' | 'custom_nodes'\r\nexport type NodeSource = {\r\n type: NodeSourceType\r\n className: string\r\n displayText: string\r\n}\r\n\r\nexport const getNodeSource = (python_module: string): NodeSource => {\r\n const modules = python_module.split('.')\r\n if (['nodes', 'comfy_extras'].includes(modules[0])) {\r\n return {\r\n type: 'core',\r\n className: 'comfy-core',\r\n displayText: 'Comfy Core'\r\n }\r\n } else if (modules[0] === 'custom_nodes') {\r\n return {\r\n type: 'custom_nodes',\r\n className: 'comfy-custom-nodes',\r\n displayText: modules[1]\r\n }\r\n } else {\r\n throw new Error(`Unknown node source: ${python_module}`)\r\n }\r\n}\r\n","/**\n * Fuse.js v7.0.0 - Lightweight fuzzy-search (http://fusejs.io)\n *\n * Copyright (c) 2023 Kiro Risk (http://kiro.me)\n * All Rights Reserved. Apache Software License 2.0\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n */\n\nfunction isArray(value) {\n return !Array.isArray\n ? getTag(value) === '[object Array]'\n : Array.isArray(value)\n}\n\n// Adapted from: https://github.com/lodash/lodash/blob/master/.internal/baseToString.js\nconst INFINITY = 1 / 0;\nfunction baseToString(value) {\n // Exit early for strings to avoid a performance hit in some environments.\n if (typeof value == 'string') {\n return value\n }\n let result = value + '';\n return result == '0' && 1 / value == -INFINITY ? '-0' : result\n}\n\nfunction toString(value) {\n return value == null ? '' : baseToString(value)\n}\n\nfunction isString(value) {\n return typeof value === 'string'\n}\n\nfunction isNumber(value) {\n return typeof value === 'number'\n}\n\n// Adapted from: https://github.com/lodash/lodash/blob/master/isBoolean.js\nfunction isBoolean(value) {\n return (\n value === true ||\n value === false ||\n (isObjectLike(value) && getTag(value) == '[object Boolean]')\n )\n}\n\nfunction isObject(value) {\n return typeof value === 'object'\n}\n\n// Checks if `value` is object-like.\nfunction isObjectLike(value) {\n return isObject(value) && value !== null\n}\n\nfunction isDefined(value) {\n return value !== undefined && value !== null\n}\n\nfunction isBlank(value) {\n return !value.trim().length\n}\n\n// Gets the `toStringTag` of `value`.\n// Adapted from: https://github.com/lodash/lodash/blob/master/.internal/getTag.js\nfunction getTag(value) {\n return value == null\n ? value === undefined\n ? '[object Undefined]'\n : '[object Null]'\n : Object.prototype.toString.call(value)\n}\n\nconst EXTENDED_SEARCH_UNAVAILABLE = 'Extended search is not available';\n\nconst INCORRECT_INDEX_TYPE = \"Incorrect 'index' type\";\n\nconst LOGICAL_SEARCH_INVALID_QUERY_FOR_KEY = (key) =>\n `Invalid value for key ${key}`;\n\nconst PATTERN_LENGTH_TOO_LARGE = (max) =>\n `Pattern length exceeds max of ${max}.`;\n\nconst MISSING_KEY_PROPERTY = (name) => `Missing ${name} property in key`;\n\nconst INVALID_KEY_WEIGHT_VALUE = (key) =>\n `Property 'weight' in key '${key}' must be a positive integer`;\n\nconst hasOwn = Object.prototype.hasOwnProperty;\n\nclass KeyStore {\n constructor(keys) {\n this._keys = [];\n this._keyMap = {};\n\n let totalWeight = 0;\n\n keys.forEach((key) => {\n let obj = createKey(key);\n\n this._keys.push(obj);\n this._keyMap[obj.id] = obj;\n\n totalWeight += obj.weight;\n });\n\n // Normalize weights so that their sum is equal to 1\n this._keys.forEach((key) => {\n key.weight /= totalWeight;\n });\n }\n get(keyId) {\n return this._keyMap[keyId]\n }\n keys() {\n return this._keys\n }\n toJSON() {\n return JSON.stringify(this._keys)\n }\n}\n\nfunction createKey(key) {\n let path = null;\n let id = null;\n let src = null;\n let weight = 1;\n let getFn = null;\n\n if (isString(key) || isArray(key)) {\n src = key;\n path = createKeyPath(key);\n id = createKeyId(key);\n } else {\n if (!hasOwn.call(key, 'name')) {\n throw new Error(MISSING_KEY_PROPERTY('name'))\n }\n\n const name = key.name;\n src = name;\n\n if (hasOwn.call(key, 'weight')) {\n weight = key.weight;\n\n if (weight <= 0) {\n throw new Error(INVALID_KEY_WEIGHT_VALUE(name))\n }\n }\n\n path = createKeyPath(name);\n id = createKeyId(name);\n getFn = key.getFn;\n }\n\n return { path, id, weight, src, getFn }\n}\n\nfunction createKeyPath(key) {\n return isArray(key) ? key : key.split('.')\n}\n\nfunction createKeyId(key) {\n return isArray(key) ? key.join('.') : key\n}\n\nfunction get(obj, path) {\n let list = [];\n let arr = false;\n\n const deepGet = (obj, path, index) => {\n if (!isDefined(obj)) {\n return\n }\n if (!path[index]) {\n // If there's no path left, we've arrived at the object we care about.\n list.push(obj);\n } else {\n let key = path[index];\n\n const value = obj[key];\n\n if (!isDefined(value)) {\n return\n }\n\n // If we're at the last value in the path, and if it's a string/number/bool,\n // add it to the list\n if (\n index === path.length - 1 &&\n (isString(value) || isNumber(value) || isBoolean(value))\n ) {\n list.push(toString(value));\n } else if (isArray(value)) {\n arr = true;\n // Search each item in the array.\n for (let i = 0, len = value.length; i < len; i += 1) {\n deepGet(value[i], path, index + 1);\n }\n } else if (path.length) {\n // An object. Recurse further.\n deepGet(value, path, index + 1);\n }\n }\n };\n\n // Backwards compatibility (since path used to be a string)\n deepGet(obj, isString(path) ? path.split('.') : path, 0);\n\n return arr ? list : list[0]\n}\n\nconst MatchOptions = {\n // Whether the matches should be included in the result set. When `true`, each record in the result\n // set will include the indices of the matched characters.\n // These can consequently be used for highlighting purposes.\n includeMatches: false,\n // When `true`, the matching function will continue to the end of a search pattern even if\n // a perfect match has already been located in the string.\n findAllMatches: false,\n // Minimum number of characters that must be matched before a result is considered a match\n minMatchCharLength: 1\n};\n\nconst BasicOptions = {\n // When `true`, the algorithm continues searching to the end of the input even if a perfect\n // match is found before the end of the same input.\n isCaseSensitive: false,\n // When true, the matching function will continue to the end of a search pattern even if\n includeScore: false,\n // List of properties that will be searched. This also supports nested properties.\n keys: [],\n // Whether to sort the result list, by score\n shouldSort: true,\n // Default sort function: sort by ascending score, ascending index\n sortFn: (a, b) =>\n a.score === b.score ? (a.idx < b.idx ? -1 : 1) : a.score < b.score ? -1 : 1\n};\n\nconst FuzzyOptions = {\n // Approximately where in the text is the pattern expected to be found?\n location: 0,\n // At what point does the match algorithm give up. A threshold of '0.0' requires a perfect match\n // (of both letters and location), a threshold of '1.0' would match anything.\n threshold: 0.6,\n // Determines how close the match must be to the fuzzy location (specified above).\n // An exact letter match which is 'distance' characters away from the fuzzy location\n // would score as a complete mismatch. A distance of '0' requires the match be at\n // the exact location specified, a threshold of '1000' would require a perfect match\n // to be within 800 characters of the fuzzy location to be found using a 0.8 threshold.\n distance: 100\n};\n\nconst AdvancedOptions = {\n // When `true`, it enables the use of unix-like search commands\n useExtendedSearch: false,\n // The get function to use when fetching an object's properties.\n // The default will search nested paths *ie foo.bar.baz*\n getFn: get,\n // When `true`, search will ignore `location` and `distance`, so it won't matter\n // where in the string the pattern appears.\n // More info: https://fusejs.io/concepts/scoring-theory.html#fuzziness-score\n ignoreLocation: false,\n // When `true`, the calculation for the relevance score (used for sorting) will\n // ignore the field-length norm.\n // More info: https://fusejs.io/concepts/scoring-theory.html#field-length-norm\n ignoreFieldNorm: false,\n // The weight to determine how much field length norm effects scoring.\n fieldNormWeight: 1\n};\n\nvar Config = {\n ...BasicOptions,\n ...MatchOptions,\n ...FuzzyOptions,\n ...AdvancedOptions\n};\n\nconst SPACE = /[^ ]+/g;\n\n// Field-length norm: the shorter the field, the higher the weight.\n// Set to 3 decimals to reduce index size.\nfunction norm(weight = 1, mantissa = 3) {\n const cache = new Map();\n const m = Math.pow(10, mantissa);\n\n return {\n get(value) {\n const numTokens = value.match(SPACE).length;\n\n if (cache.has(numTokens)) {\n return cache.get(numTokens)\n }\n\n // Default function is 1/sqrt(x), weight makes that variable\n const norm = 1 / Math.pow(numTokens, 0.5 * weight);\n\n // In place of `toFixed(mantissa)`, for faster computation\n const n = parseFloat(Math.round(norm * m) / m);\n\n cache.set(numTokens, n);\n\n return n\n },\n clear() {\n cache.clear();\n }\n }\n}\n\nclass FuseIndex {\n constructor({\n getFn = Config.getFn,\n fieldNormWeight = Config.fieldNormWeight\n } = {}) {\n this.norm = norm(fieldNormWeight, 3);\n this.getFn = getFn;\n this.isCreated = false;\n\n this.setIndexRecords();\n }\n setSources(docs = []) {\n this.docs = docs;\n }\n setIndexRecords(records = []) {\n this.records = records;\n }\n setKeys(keys = []) {\n this.keys = keys;\n this._keysMap = {};\n keys.forEach((key, idx) => {\n this._keysMap[key.id] = idx;\n });\n }\n create() {\n if (this.isCreated || !this.docs.length) {\n return\n }\n\n this.isCreated = true;\n\n // List is Array\n if (isString(this.docs[0])) {\n this.docs.forEach((doc, docIndex) => {\n this._addString(doc, docIndex);\n });\n } else {\n // List is Array\n this.docs.forEach((doc, docIndex) => {\n this._addObject(doc, docIndex);\n });\n }\n\n this.norm.clear();\n }\n // Adds a doc to the end of the index\n add(doc) {\n const idx = this.size();\n\n if (isString(doc)) {\n this._addString(doc, idx);\n } else {\n this._addObject(doc, idx);\n }\n }\n // Removes the doc at the specified index of the index\n removeAt(idx) {\n this.records.splice(idx, 1);\n\n // Change ref index of every subsquent doc\n for (let i = idx, len = this.size(); i < len; i += 1) {\n this.records[i].i -= 1;\n }\n }\n getValueForItemAtKeyId(item, keyId) {\n return item[this._keysMap[keyId]]\n }\n size() {\n return this.records.length\n }\n _addString(doc, docIndex) {\n if (!isDefined(doc) || isBlank(doc)) {\n return\n }\n\n let record = {\n v: doc,\n i: docIndex,\n n: this.norm.get(doc)\n };\n\n this.records.push(record);\n }\n _addObject(doc, docIndex) {\n let record = { i: docIndex, $: {} };\n\n // Iterate over every key (i.e, path), and fetch the value at that key\n this.keys.forEach((key, keyIndex) => {\n let value = key.getFn ? key.getFn(doc) : this.getFn(doc, key.path);\n\n if (!isDefined(value)) {\n return\n }\n\n if (isArray(value)) {\n let subRecords = [];\n const stack = [{ nestedArrIndex: -1, value }];\n\n while (stack.length) {\n const { nestedArrIndex, value } = stack.pop();\n\n if (!isDefined(value)) {\n continue\n }\n\n if (isString(value) && !isBlank(value)) {\n let subRecord = {\n v: value,\n i: nestedArrIndex,\n n: this.norm.get(value)\n };\n\n subRecords.push(subRecord);\n } else if (isArray(value)) {\n value.forEach((item, k) => {\n stack.push({\n nestedArrIndex: k,\n value: item\n });\n });\n } else ;\n }\n record.$[keyIndex] = subRecords;\n } else if (isString(value) && !isBlank(value)) {\n let subRecord = {\n v: value,\n n: this.norm.get(value)\n };\n\n record.$[keyIndex] = subRecord;\n }\n });\n\n this.records.push(record);\n }\n toJSON() {\n return {\n keys: this.keys,\n records: this.records\n }\n }\n}\n\nfunction createIndex(\n keys,\n docs,\n { getFn = Config.getFn, fieldNormWeight = Config.fieldNormWeight } = {}\n) {\n const myIndex = new FuseIndex({ getFn, fieldNormWeight });\n myIndex.setKeys(keys.map(createKey));\n myIndex.setSources(docs);\n myIndex.create();\n return myIndex\n}\n\nfunction parseIndex(\n data,\n { getFn = Config.getFn, fieldNormWeight = Config.fieldNormWeight } = {}\n) {\n const { keys, records } = data;\n const myIndex = new FuseIndex({ getFn, fieldNormWeight });\n myIndex.setKeys(keys);\n myIndex.setIndexRecords(records);\n return myIndex\n}\n\nfunction computeScore$1(\n pattern,\n {\n errors = 0,\n currentLocation = 0,\n expectedLocation = 0,\n distance = Config.distance,\n ignoreLocation = Config.ignoreLocation\n } = {}\n) {\n const accuracy = errors / pattern.length;\n\n if (ignoreLocation) {\n return accuracy\n }\n\n const proximity = Math.abs(expectedLocation - currentLocation);\n\n if (!distance) {\n // Dodge divide by zero error.\n return proximity ? 1.0 : accuracy\n }\n\n return accuracy + proximity / distance\n}\n\nfunction convertMaskToIndices(\n matchmask = [],\n minMatchCharLength = Config.minMatchCharLength\n) {\n let indices = [];\n let start = -1;\n let end = -1;\n let i = 0;\n\n for (let len = matchmask.length; i < len; i += 1) {\n let match = matchmask[i];\n if (match && start === -1) {\n start = i;\n } else if (!match && start !== -1) {\n end = i - 1;\n if (end - start + 1 >= minMatchCharLength) {\n indices.push([start, end]);\n }\n start = -1;\n }\n }\n\n // (i-1 - start) + 1 => i - start\n if (matchmask[i - 1] && i - start >= minMatchCharLength) {\n indices.push([start, i - 1]);\n }\n\n return indices\n}\n\n// Machine word size\nconst MAX_BITS = 32;\n\nfunction search(\n text,\n pattern,\n patternAlphabet,\n {\n location = Config.location,\n distance = Config.distance,\n threshold = Config.threshold,\n findAllMatches = Config.findAllMatches,\n minMatchCharLength = Config.minMatchCharLength,\n includeMatches = Config.includeMatches,\n ignoreLocation = Config.ignoreLocation\n } = {}\n) {\n if (pattern.length > MAX_BITS) {\n throw new Error(PATTERN_LENGTH_TOO_LARGE(MAX_BITS))\n }\n\n const patternLen = pattern.length;\n // Set starting location at beginning text and initialize the alphabet.\n const textLen = text.length;\n // Handle the case when location > text.length\n const expectedLocation = Math.max(0, Math.min(location, textLen));\n // Highest score beyond which we give up.\n let currentThreshold = threshold;\n // Is there a nearby exact match? (speedup)\n let bestLocation = expectedLocation;\n\n // Performance: only computer matches when the minMatchCharLength > 1\n // OR if `includeMatches` is true.\n const computeMatches = minMatchCharLength > 1 || includeMatches;\n // A mask of the matches, used for building the indices\n const matchMask = computeMatches ? Array(textLen) : [];\n\n let index;\n\n // Get all exact matches, here for speed up\n while ((index = text.indexOf(pattern, bestLocation)) > -1) {\n let score = computeScore$1(pattern, {\n currentLocation: index,\n expectedLocation,\n distance,\n ignoreLocation\n });\n\n currentThreshold = Math.min(score, currentThreshold);\n bestLocation = index + patternLen;\n\n if (computeMatches) {\n let i = 0;\n while (i < patternLen) {\n matchMask[index + i] = 1;\n i += 1;\n }\n }\n }\n\n // Reset the best location\n bestLocation = -1;\n\n let lastBitArr = [];\n let finalScore = 1;\n let binMax = patternLen + textLen;\n\n const mask = 1 << (patternLen - 1);\n\n for (let i = 0; i < patternLen; i += 1) {\n // Scan for the best match; each iteration allows for one more error.\n // Run a binary search to determine how far from the match location we can stray\n // at this error level.\n let binMin = 0;\n let binMid = binMax;\n\n while (binMin < binMid) {\n const score = computeScore$1(pattern, {\n errors: i,\n currentLocation: expectedLocation + binMid,\n expectedLocation,\n distance,\n ignoreLocation\n });\n\n if (score <= currentThreshold) {\n binMin = binMid;\n } else {\n binMax = binMid;\n }\n\n binMid = Math.floor((binMax - binMin) / 2 + binMin);\n }\n\n // Use the result from this iteration as the maximum for the next.\n binMax = binMid;\n\n let start = Math.max(1, expectedLocation - binMid + 1);\n let finish = findAllMatches\n ? textLen\n : Math.min(expectedLocation + binMid, textLen) + patternLen;\n\n // Initialize the bit array\n let bitArr = Array(finish + 2);\n\n bitArr[finish + 1] = (1 << i) - 1;\n\n for (let j = finish; j >= start; j -= 1) {\n let currentLocation = j - 1;\n let charMatch = patternAlphabet[text.charAt(currentLocation)];\n\n if (computeMatches) {\n // Speed up: quick bool to int conversion (i.e, `charMatch ? 1 : 0`)\n matchMask[currentLocation] = +!!charMatch;\n }\n\n // First pass: exact match\n bitArr[j] = ((bitArr[j + 1] << 1) | 1) & charMatch;\n\n // Subsequent passes: fuzzy match\n if (i) {\n bitArr[j] |=\n ((lastBitArr[j + 1] | lastBitArr[j]) << 1) | 1 | lastBitArr[j + 1];\n }\n\n if (bitArr[j] & mask) {\n finalScore = computeScore$1(pattern, {\n errors: i,\n currentLocation,\n expectedLocation,\n distance,\n ignoreLocation\n });\n\n // This match will almost certainly be better than any existing match.\n // But check anyway.\n if (finalScore <= currentThreshold) {\n // Indeed it is\n currentThreshold = finalScore;\n bestLocation = currentLocation;\n\n // Already passed `loc`, downhill from here on in.\n if (bestLocation <= expectedLocation) {\n break\n }\n\n // When passing `bestLocation`, don't exceed our current distance from `expectedLocation`.\n start = Math.max(1, 2 * expectedLocation - bestLocation);\n }\n }\n }\n\n // No hope for a (better) match at greater error levels.\n const score = computeScore$1(pattern, {\n errors: i + 1,\n currentLocation: expectedLocation,\n expectedLocation,\n distance,\n ignoreLocation\n });\n\n if (score > currentThreshold) {\n break\n }\n\n lastBitArr = bitArr;\n }\n\n const result = {\n isMatch: bestLocation >= 0,\n // Count exact matches (those with a score of 0) to be \"almost\" exact\n score: Math.max(0.001, finalScore)\n };\n\n if (computeMatches) {\n const indices = convertMaskToIndices(matchMask, minMatchCharLength);\n if (!indices.length) {\n result.isMatch = false;\n } else if (includeMatches) {\n result.indices = indices;\n }\n }\n\n return result\n}\n\nfunction createPatternAlphabet(pattern) {\n let mask = {};\n\n for (let i = 0, len = pattern.length; i < len; i += 1) {\n const char = pattern.charAt(i);\n mask[char] = (mask[char] || 0) | (1 << (len - i - 1));\n }\n\n return mask\n}\n\nclass BitapSearch {\n constructor(\n pattern,\n {\n location = Config.location,\n threshold = Config.threshold,\n distance = Config.distance,\n includeMatches = Config.includeMatches,\n findAllMatches = Config.findAllMatches,\n minMatchCharLength = Config.minMatchCharLength,\n isCaseSensitive = Config.isCaseSensitive,\n ignoreLocation = Config.ignoreLocation\n } = {}\n ) {\n this.options = {\n location,\n threshold,\n distance,\n includeMatches,\n findAllMatches,\n minMatchCharLength,\n isCaseSensitive,\n ignoreLocation\n };\n\n this.pattern = isCaseSensitive ? pattern : pattern.toLowerCase();\n\n this.chunks = [];\n\n if (!this.pattern.length) {\n return\n }\n\n const addChunk = (pattern, startIndex) => {\n this.chunks.push({\n pattern,\n alphabet: createPatternAlphabet(pattern),\n startIndex\n });\n };\n\n const len = this.pattern.length;\n\n if (len > MAX_BITS) {\n let i = 0;\n const remainder = len % MAX_BITS;\n const end = len - remainder;\n\n while (i < end) {\n addChunk(this.pattern.substr(i, MAX_BITS), i);\n i += MAX_BITS;\n }\n\n if (remainder) {\n const startIndex = len - MAX_BITS;\n addChunk(this.pattern.substr(startIndex), startIndex);\n }\n } else {\n addChunk(this.pattern, 0);\n }\n }\n\n searchIn(text) {\n const { isCaseSensitive, includeMatches } = this.options;\n\n if (!isCaseSensitive) {\n text = text.toLowerCase();\n }\n\n // Exact match\n if (this.pattern === text) {\n let result = {\n isMatch: true,\n score: 0\n };\n\n if (includeMatches) {\n result.indices = [[0, text.length - 1]];\n }\n\n return result\n }\n\n // Otherwise, use Bitap algorithm\n const {\n location,\n distance,\n threshold,\n findAllMatches,\n minMatchCharLength,\n ignoreLocation\n } = this.options;\n\n let allIndices = [];\n let totalScore = 0;\n let hasMatches = false;\n\n this.chunks.forEach(({ pattern, alphabet, startIndex }) => {\n const { isMatch, score, indices } = search(text, pattern, alphabet, {\n location: location + startIndex,\n distance,\n threshold,\n findAllMatches,\n minMatchCharLength,\n includeMatches,\n ignoreLocation\n });\n\n if (isMatch) {\n hasMatches = true;\n }\n\n totalScore += score;\n\n if (isMatch && indices) {\n allIndices = [...allIndices, ...indices];\n }\n });\n\n let result = {\n isMatch: hasMatches,\n score: hasMatches ? totalScore / this.chunks.length : 1\n };\n\n if (hasMatches && includeMatches) {\n result.indices = allIndices;\n }\n\n return result\n }\n}\n\nclass BaseMatch {\n constructor(pattern) {\n this.pattern = pattern;\n }\n static isMultiMatch(pattern) {\n return getMatch(pattern, this.multiRegex)\n }\n static isSingleMatch(pattern) {\n return getMatch(pattern, this.singleRegex)\n }\n search(/*text*/) {}\n}\n\nfunction getMatch(pattern, exp) {\n const matches = pattern.match(exp);\n return matches ? matches[1] : null\n}\n\n// Token: 'file\n\nclass ExactMatch extends BaseMatch {\n constructor(pattern) {\n super(pattern);\n }\n static get type() {\n return 'exact'\n }\n static get multiRegex() {\n return /^=\"(.*)\"$/\n }\n static get singleRegex() {\n return /^=(.*)$/\n }\n search(text) {\n const isMatch = text === this.pattern;\n\n return {\n isMatch,\n score: isMatch ? 0 : 1,\n indices: [0, this.pattern.length - 1]\n }\n }\n}\n\n// Token: !fire\n\nclass InverseExactMatch extends BaseMatch {\n constructor(pattern) {\n super(pattern);\n }\n static get type() {\n return 'inverse-exact'\n }\n static get multiRegex() {\n return /^!\"(.*)\"$/\n }\n static get singleRegex() {\n return /^!(.*)$/\n }\n search(text) {\n const index = text.indexOf(this.pattern);\n const isMatch = index === -1;\n\n return {\n isMatch,\n score: isMatch ? 0 : 1,\n indices: [0, text.length - 1]\n }\n }\n}\n\n// Token: ^file\n\nclass PrefixExactMatch extends BaseMatch {\n constructor(pattern) {\n super(pattern);\n }\n static get type() {\n return 'prefix-exact'\n }\n static get multiRegex() {\n return /^\\^\"(.*)\"$/\n }\n static get singleRegex() {\n return /^\\^(.*)$/\n }\n search(text) {\n const isMatch = text.startsWith(this.pattern);\n\n return {\n isMatch,\n score: isMatch ? 0 : 1,\n indices: [0, this.pattern.length - 1]\n }\n }\n}\n\n// Token: !^fire\n\nclass InversePrefixExactMatch extends BaseMatch {\n constructor(pattern) {\n super(pattern);\n }\n static get type() {\n return 'inverse-prefix-exact'\n }\n static get multiRegex() {\n return /^!\\^\"(.*)\"$/\n }\n static get singleRegex() {\n return /^!\\^(.*)$/\n }\n search(text) {\n const isMatch = !text.startsWith(this.pattern);\n\n return {\n isMatch,\n score: isMatch ? 0 : 1,\n indices: [0, text.length - 1]\n }\n }\n}\n\n// Token: .file$\n\nclass SuffixExactMatch extends BaseMatch {\n constructor(pattern) {\n super(pattern);\n }\n static get type() {\n return 'suffix-exact'\n }\n static get multiRegex() {\n return /^\"(.*)\"\\$$/\n }\n static get singleRegex() {\n return /^(.*)\\$$/\n }\n search(text) {\n const isMatch = text.endsWith(this.pattern);\n\n return {\n isMatch,\n score: isMatch ? 0 : 1,\n indices: [text.length - this.pattern.length, text.length - 1]\n }\n }\n}\n\n// Token: !.file$\n\nclass InverseSuffixExactMatch extends BaseMatch {\n constructor(pattern) {\n super(pattern);\n }\n static get type() {\n return 'inverse-suffix-exact'\n }\n static get multiRegex() {\n return /^!\"(.*)\"\\$$/\n }\n static get singleRegex() {\n return /^!(.*)\\$$/\n }\n search(text) {\n const isMatch = !text.endsWith(this.pattern);\n return {\n isMatch,\n score: isMatch ? 0 : 1,\n indices: [0, text.length - 1]\n }\n }\n}\n\nclass FuzzyMatch extends BaseMatch {\n constructor(\n pattern,\n {\n location = Config.location,\n threshold = Config.threshold,\n distance = Config.distance,\n includeMatches = Config.includeMatches,\n findAllMatches = Config.findAllMatches,\n minMatchCharLength = Config.minMatchCharLength,\n isCaseSensitive = Config.isCaseSensitive,\n ignoreLocation = Config.ignoreLocation\n } = {}\n ) {\n super(pattern);\n this._bitapSearch = new BitapSearch(pattern, {\n location,\n threshold,\n distance,\n includeMatches,\n findAllMatches,\n minMatchCharLength,\n isCaseSensitive,\n ignoreLocation\n });\n }\n static get type() {\n return 'fuzzy'\n }\n static get multiRegex() {\n return /^\"(.*)\"$/\n }\n static get singleRegex() {\n return /^(.*)$/\n }\n search(text) {\n return this._bitapSearch.searchIn(text)\n }\n}\n\n// Token: 'file\n\nclass IncludeMatch extends BaseMatch {\n constructor(pattern) {\n super(pattern);\n }\n static get type() {\n return 'include'\n }\n static get multiRegex() {\n return /^'\"(.*)\"$/\n }\n static get singleRegex() {\n return /^'(.*)$/\n }\n search(text) {\n let location = 0;\n let index;\n\n const indices = [];\n const patternLen = this.pattern.length;\n\n // Get all exact matches\n while ((index = text.indexOf(this.pattern, location)) > -1) {\n location = index + patternLen;\n indices.push([index, location - 1]);\n }\n\n const isMatch = !!indices.length;\n\n return {\n isMatch,\n score: isMatch ? 0 : 1,\n indices\n }\n }\n}\n\n// ❗Order is important. DO NOT CHANGE.\nconst searchers = [\n ExactMatch,\n IncludeMatch,\n PrefixExactMatch,\n InversePrefixExactMatch,\n InverseSuffixExactMatch,\n SuffixExactMatch,\n InverseExactMatch,\n FuzzyMatch\n];\n\nconst searchersLen = searchers.length;\n\n// Regex to split by spaces, but keep anything in quotes together\nconst SPACE_RE = / +(?=(?:[^\\\"]*\\\"[^\\\"]*\\\")*[^\\\"]*$)/;\nconst OR_TOKEN = '|';\n\n// Return a 2D array representation of the query, for simpler parsing.\n// Example:\n// \"^core go$ | rb$ | py$ xy$\" => [[\"^core\", \"go$\"], [\"rb$\"], [\"py$\", \"xy$\"]]\nfunction parseQuery(pattern, options = {}) {\n return pattern.split(OR_TOKEN).map((item) => {\n let query = item\n .trim()\n .split(SPACE_RE)\n .filter((item) => item && !!item.trim());\n\n let results = [];\n for (let i = 0, len = query.length; i < len; i += 1) {\n const queryItem = query[i];\n\n // 1. Handle multiple query match (i.e, once that are quoted, like `\"hello world\"`)\n let found = false;\n let idx = -1;\n while (!found && ++idx < searchersLen) {\n const searcher = searchers[idx];\n let token = searcher.isMultiMatch(queryItem);\n if (token) {\n results.push(new searcher(token, options));\n found = true;\n }\n }\n\n if (found) {\n continue\n }\n\n // 2. Handle single query matches (i.e, once that are *not* quoted)\n idx = -1;\n while (++idx < searchersLen) {\n const searcher = searchers[idx];\n let token = searcher.isSingleMatch(queryItem);\n if (token) {\n results.push(new searcher(token, options));\n break\n }\n }\n }\n\n return results\n })\n}\n\n// These extended matchers can return an array of matches, as opposed\n// to a singl match\nconst MultiMatchSet = new Set([FuzzyMatch.type, IncludeMatch.type]);\n\n/**\n * Command-like searching\n * ======================\n *\n * Given multiple search terms delimited by spaces.e.g. `^jscript .python$ ruby !java`,\n * search in a given text.\n *\n * Search syntax:\n *\n * | Token | Match type | Description |\n * | ----------- | -------------------------- | -------------------------------------- |\n * | `jscript` | fuzzy-match | Items that fuzzy match `jscript` |\n * | `=scheme` | exact-match | Items that are `scheme` |\n * | `'python` | include-match | Items that include `python` |\n * | `!ruby` | inverse-exact-match | Items that do not include `ruby` |\n * | `^java` | prefix-exact-match | Items that start with `java` |\n * | `!^earlang` | inverse-prefix-exact-match | Items that do not start with `earlang` |\n * | `.js$` | suffix-exact-match | Items that end with `.js` |\n * | `!.go$` | inverse-suffix-exact-match | Items that do not end with `.go` |\n *\n * A single pipe character acts as an OR operator. For example, the following\n * query matches entries that start with `core` and end with either`go`, `rb`,\n * or`py`.\n *\n * ```\n * ^core go$ | rb$ | py$\n * ```\n */\nclass ExtendedSearch {\n constructor(\n pattern,\n {\n isCaseSensitive = Config.isCaseSensitive,\n includeMatches = Config.includeMatches,\n minMatchCharLength = Config.minMatchCharLength,\n ignoreLocation = Config.ignoreLocation,\n findAllMatches = Config.findAllMatches,\n location = Config.location,\n threshold = Config.threshold,\n distance = Config.distance\n } = {}\n ) {\n this.query = null;\n this.options = {\n isCaseSensitive,\n includeMatches,\n minMatchCharLength,\n findAllMatches,\n ignoreLocation,\n location,\n threshold,\n distance\n };\n\n this.pattern = isCaseSensitive ? pattern : pattern.toLowerCase();\n this.query = parseQuery(this.pattern, this.options);\n }\n\n static condition(_, options) {\n return options.useExtendedSearch\n }\n\n searchIn(text) {\n const query = this.query;\n\n if (!query) {\n return {\n isMatch: false,\n score: 1\n }\n }\n\n const { includeMatches, isCaseSensitive } = this.options;\n\n text = isCaseSensitive ? text : text.toLowerCase();\n\n let numMatches = 0;\n let allIndices = [];\n let totalScore = 0;\n\n // ORs\n for (let i = 0, qLen = query.length; i < qLen; i += 1) {\n const searchers = query[i];\n\n // Reset indices\n allIndices.length = 0;\n numMatches = 0;\n\n // ANDs\n for (let j = 0, pLen = searchers.length; j < pLen; j += 1) {\n const searcher = searchers[j];\n const { isMatch, indices, score } = searcher.search(text);\n\n if (isMatch) {\n numMatches += 1;\n totalScore += score;\n if (includeMatches) {\n const type = searcher.constructor.type;\n if (MultiMatchSet.has(type)) {\n allIndices = [...allIndices, ...indices];\n } else {\n allIndices.push(indices);\n }\n }\n } else {\n totalScore = 0;\n numMatches = 0;\n allIndices.length = 0;\n break\n }\n }\n\n // OR condition, so if TRUE, return\n if (numMatches) {\n let result = {\n isMatch: true,\n score: totalScore / numMatches\n };\n\n if (includeMatches) {\n result.indices = allIndices;\n }\n\n return result\n }\n }\n\n // Nothing was matched\n return {\n isMatch: false,\n score: 1\n }\n }\n}\n\nconst registeredSearchers = [];\n\nfunction register(...args) {\n registeredSearchers.push(...args);\n}\n\nfunction createSearcher(pattern, options) {\n for (let i = 0, len = registeredSearchers.length; i < len; i += 1) {\n let searcherClass = registeredSearchers[i];\n if (searcherClass.condition(pattern, options)) {\n return new searcherClass(pattern, options)\n }\n }\n\n return new BitapSearch(pattern, options)\n}\n\nconst LogicalOperator = {\n AND: '$and',\n OR: '$or'\n};\n\nconst KeyType = {\n PATH: '$path',\n PATTERN: '$val'\n};\n\nconst isExpression = (query) =>\n !!(query[LogicalOperator.AND] || query[LogicalOperator.OR]);\n\nconst isPath = (query) => !!query[KeyType.PATH];\n\nconst isLeaf = (query) =>\n !isArray(query) && isObject(query) && !isExpression(query);\n\nconst convertToExplicit = (query) => ({\n [LogicalOperator.AND]: Object.keys(query).map((key) => ({\n [key]: query[key]\n }))\n});\n\n// When `auto` is `true`, the parse function will infer and initialize and add\n// the appropriate `Searcher` instance\nfunction parse(query, options, { auto = true } = {}) {\n const next = (query) => {\n let keys = Object.keys(query);\n\n const isQueryPath = isPath(query);\n\n if (!isQueryPath && keys.length > 1 && !isExpression(query)) {\n return next(convertToExplicit(query))\n }\n\n if (isLeaf(query)) {\n const key = isQueryPath ? query[KeyType.PATH] : keys[0];\n\n const pattern = isQueryPath ? query[KeyType.PATTERN] : query[key];\n\n if (!isString(pattern)) {\n throw new Error(LOGICAL_SEARCH_INVALID_QUERY_FOR_KEY(key))\n }\n\n const obj = {\n keyId: createKeyId(key),\n pattern\n };\n\n if (auto) {\n obj.searcher = createSearcher(pattern, options);\n }\n\n return obj\n }\n\n let node = {\n children: [],\n operator: keys[0]\n };\n\n keys.forEach((key) => {\n const value = query[key];\n\n if (isArray(value)) {\n value.forEach((item) => {\n node.children.push(next(item));\n });\n }\n });\n\n return node\n };\n\n if (!isExpression(query)) {\n query = convertToExplicit(query);\n }\n\n return next(query)\n}\n\n// Practical scoring function\nfunction computeScore(\n results,\n { ignoreFieldNorm = Config.ignoreFieldNorm }\n) {\n results.forEach((result) => {\n let totalScore = 1;\n\n result.matches.forEach(({ key, norm, score }) => {\n const weight = key ? key.weight : null;\n\n totalScore *= Math.pow(\n score === 0 && weight ? Number.EPSILON : score,\n (weight || 1) * (ignoreFieldNorm ? 1 : norm)\n );\n });\n\n result.score = totalScore;\n });\n}\n\nfunction transformMatches(result, data) {\n const matches = result.matches;\n data.matches = [];\n\n if (!isDefined(matches)) {\n return\n }\n\n matches.forEach((match) => {\n if (!isDefined(match.indices) || !match.indices.length) {\n return\n }\n\n const { indices, value } = match;\n\n let obj = {\n indices,\n value\n };\n\n if (match.key) {\n obj.key = match.key.src;\n }\n\n if (match.idx > -1) {\n obj.refIndex = match.idx;\n }\n\n data.matches.push(obj);\n });\n}\n\nfunction transformScore(result, data) {\n data.score = result.score;\n}\n\nfunction format(\n results,\n docs,\n {\n includeMatches = Config.includeMatches,\n includeScore = Config.includeScore\n } = {}\n) {\n const transformers = [];\n\n if (includeMatches) transformers.push(transformMatches);\n if (includeScore) transformers.push(transformScore);\n\n return results.map((result) => {\n const { idx } = result;\n\n const data = {\n item: docs[idx],\n refIndex: idx\n };\n\n if (transformers.length) {\n transformers.forEach((transformer) => {\n transformer(result, data);\n });\n }\n\n return data\n })\n}\n\nclass Fuse {\n constructor(docs, options = {}, index) {\n this.options = { ...Config, ...options };\n\n if (\n this.options.useExtendedSearch &&\n !true\n ) {\n throw new Error(EXTENDED_SEARCH_UNAVAILABLE)\n }\n\n this._keyStore = new KeyStore(this.options.keys);\n\n this.setCollection(docs, index);\n }\n\n setCollection(docs, index) {\n this._docs = docs;\n\n if (index && !(index instanceof FuseIndex)) {\n throw new Error(INCORRECT_INDEX_TYPE)\n }\n\n this._myIndex =\n index ||\n createIndex(this.options.keys, this._docs, {\n getFn: this.options.getFn,\n fieldNormWeight: this.options.fieldNormWeight\n });\n }\n\n add(doc) {\n if (!isDefined(doc)) {\n return\n }\n\n this._docs.push(doc);\n this._myIndex.add(doc);\n }\n\n remove(predicate = (/* doc, idx */) => false) {\n const results = [];\n\n for (let i = 0, len = this._docs.length; i < len; i += 1) {\n const doc = this._docs[i];\n if (predicate(doc, i)) {\n this.removeAt(i);\n i -= 1;\n len -= 1;\n\n results.push(doc);\n }\n }\n\n return results\n }\n\n removeAt(idx) {\n this._docs.splice(idx, 1);\n this._myIndex.removeAt(idx);\n }\n\n getIndex() {\n return this._myIndex\n }\n\n search(query, { limit = -1 } = {}) {\n const {\n includeMatches,\n includeScore,\n shouldSort,\n sortFn,\n ignoreFieldNorm\n } = this.options;\n\n let results = isString(query)\n ? isString(this._docs[0])\n ? this._searchStringList(query)\n : this._searchObjectList(query)\n : this._searchLogical(query);\n\n computeScore(results, { ignoreFieldNorm });\n\n if (shouldSort) {\n results.sort(sortFn);\n }\n\n if (isNumber(limit) && limit > -1) {\n results = results.slice(0, limit);\n }\n\n return format(results, this._docs, {\n includeMatches,\n includeScore\n })\n }\n\n _searchStringList(query) {\n const searcher = createSearcher(query, this.options);\n const { records } = this._myIndex;\n const results = [];\n\n // Iterate over every string in the index\n records.forEach(({ v: text, i: idx, n: norm }) => {\n if (!isDefined(text)) {\n return\n }\n\n const { isMatch, score, indices } = searcher.searchIn(text);\n\n if (isMatch) {\n results.push({\n item: text,\n idx,\n matches: [{ score, value: text, norm, indices }]\n });\n }\n });\n\n return results\n }\n\n _searchLogical(query) {\n\n const expression = parse(query, this.options);\n\n const evaluate = (node, item, idx) => {\n if (!node.children) {\n const { keyId, searcher } = node;\n\n const matches = this._findMatches({\n key: this._keyStore.get(keyId),\n value: this._myIndex.getValueForItemAtKeyId(item, keyId),\n searcher\n });\n\n if (matches && matches.length) {\n return [\n {\n idx,\n item,\n matches\n }\n ]\n }\n\n return []\n }\n\n const res = [];\n for (let i = 0, len = node.children.length; i < len; i += 1) {\n const child = node.children[i];\n const result = evaluate(child, item, idx);\n if (result.length) {\n res.push(...result);\n } else if (node.operator === LogicalOperator.AND) {\n return []\n }\n }\n return res\n };\n\n const records = this._myIndex.records;\n const resultMap = {};\n const results = [];\n\n records.forEach(({ $: item, i: idx }) => {\n if (isDefined(item)) {\n let expResults = evaluate(expression, item, idx);\n\n if (expResults.length) {\n // Dedupe when adding\n if (!resultMap[idx]) {\n resultMap[idx] = { idx, item, matches: [] };\n results.push(resultMap[idx]);\n }\n expResults.forEach(({ matches }) => {\n resultMap[idx].matches.push(...matches);\n });\n }\n }\n });\n\n return results\n }\n\n _searchObjectList(query) {\n const searcher = createSearcher(query, this.options);\n const { keys, records } = this._myIndex;\n const results = [];\n\n // List is Array\n records.forEach(({ $: item, i: idx }) => {\n if (!isDefined(item)) {\n return\n }\n\n let matches = [];\n\n // Iterate over every key (i.e, path), and fetch the value at that key\n keys.forEach((key, keyIndex) => {\n matches.push(\n ...this._findMatches({\n key,\n value: item[keyIndex],\n searcher\n })\n );\n });\n\n if (matches.length) {\n results.push({\n idx,\n item,\n matches\n });\n }\n });\n\n return results\n }\n _findMatches({ key, value, searcher }) {\n if (!isDefined(value)) {\n return []\n }\n\n let matches = [];\n\n if (isArray(value)) {\n value.forEach(({ v: text, i: idx, n: norm }) => {\n if (!isDefined(text)) {\n return\n }\n\n const { isMatch, score, indices } = searcher.searchIn(text);\n\n if (isMatch) {\n matches.push({\n score,\n key,\n value: text,\n idx,\n norm,\n indices\n });\n }\n });\n } else {\n const { v: text, n: norm } = value;\n\n const { isMatch, score, indices } = searcher.searchIn(text);\n\n if (isMatch) {\n matches.push({ score, key, value: text, norm, indices });\n }\n }\n\n return matches\n }\n}\n\nFuse.version = '7.0.0';\nFuse.createIndex = createIndex;\nFuse.parseIndex = parseIndex;\nFuse.config = Config;\n\n{\n Fuse.parseQuery = parse;\n}\n\n{\n register(ExtendedSearch);\n}\n\nexport { Fuse as default };\n","/**\n * @license\n * Lodash \n * Copyright OpenJS Foundation and other contributors \n * Released under MIT license \n * Based on Underscore.js 1.8.3 \n * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n */\n;(function() {\n\n /** Used as a safe reference for `undefined` in pre-ES5 environments. */\n var undefined;\n\n /** Used as the semantic version number. */\n var VERSION = '4.17.21';\n\n /** Used as the size to enable large array optimizations. */\n var LARGE_ARRAY_SIZE = 200;\n\n /** Error message constants. */\n var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.',\n FUNC_ERROR_TEXT = 'Expected a function',\n INVALID_TEMPL_VAR_ERROR_TEXT = 'Invalid `variable` option passed into `_.template`';\n\n /** Used to stand-in for `undefined` hash values. */\n var HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n /** Used as the maximum memoize cache size. */\n var MAX_MEMOIZE_SIZE = 500;\n\n /** Used as the internal argument placeholder. */\n var PLACEHOLDER = '__lodash_placeholder__';\n\n /** Used to compose bitmasks for cloning. */\n var CLONE_DEEP_FLAG = 1,\n CLONE_FLAT_FLAG = 2,\n CLONE_SYMBOLS_FLAG = 4;\n\n /** Used to compose bitmasks for value comparisons. */\n var COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n /** Used to compose bitmasks for function metadata. */\n var WRAP_BIND_FLAG = 1,\n WRAP_BIND_KEY_FLAG = 2,\n WRAP_CURRY_BOUND_FLAG = 4,\n WRAP_CURRY_FLAG = 8,\n WRAP_CURRY_RIGHT_FLAG = 16,\n WRAP_PARTIAL_FLAG = 32,\n WRAP_PARTIAL_RIGHT_FLAG = 64,\n WRAP_ARY_FLAG = 128,\n WRAP_REARG_FLAG = 256,\n WRAP_FLIP_FLAG = 512;\n\n /** Used as default options for `_.truncate`. */\n var DEFAULT_TRUNC_LENGTH = 30,\n DEFAULT_TRUNC_OMISSION = '...';\n\n /** Used to detect hot functions by number of calls within a span of milliseconds. */\n var HOT_COUNT = 800,\n HOT_SPAN = 16;\n\n /** Used to indicate the type of lazy iteratees. */\n var LAZY_FILTER_FLAG = 1,\n LAZY_MAP_FLAG = 2,\n LAZY_WHILE_FLAG = 3;\n\n /** Used as references for various `Number` constants. */\n var INFINITY = 1 / 0,\n MAX_SAFE_INTEGER = 9007199254740991,\n MAX_INTEGER = 1.7976931348623157e+308,\n NAN = 0 / 0;\n\n /** Used as references for the maximum length and index of an array. */\n var MAX_ARRAY_LENGTH = 4294967295,\n MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1,\n HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1;\n\n /** Used to associate wrap methods with their bit flags. */\n var wrapFlags = [\n ['ary', WRAP_ARY_FLAG],\n ['bind', WRAP_BIND_FLAG],\n ['bindKey', WRAP_BIND_KEY_FLAG],\n ['curry', WRAP_CURRY_FLAG],\n ['curryRight', WRAP_CURRY_RIGHT_FLAG],\n ['flip', WRAP_FLIP_FLAG],\n ['partial', WRAP_PARTIAL_FLAG],\n ['partialRight', WRAP_PARTIAL_RIGHT_FLAG],\n ['rearg', WRAP_REARG_FLAG]\n ];\n\n /** `Object#toString` result references. */\n var argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n asyncTag = '[object AsyncFunction]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n domExcTag = '[object DOMException]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n nullTag = '[object Null]',\n objectTag = '[object Object]',\n promiseTag = '[object Promise]',\n proxyTag = '[object Proxy]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]',\n undefinedTag = '[object Undefined]',\n weakMapTag = '[object WeakMap]',\n weakSetTag = '[object WeakSet]';\n\n var arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n /** Used to match empty string literals in compiled template source. */\n var reEmptyStringLeading = /\\b__p \\+= '';/g,\n reEmptyStringMiddle = /\\b(__p \\+=) '' \\+/g,\n reEmptyStringTrailing = /(__e\\(.*?\\)|\\b__t\\)) \\+\\n'';/g;\n\n /** Used to match HTML entities and HTML characters. */\n var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g,\n reUnescapedHtml = /[&<>\"']/g,\n reHasEscapedHtml = RegExp(reEscapedHtml.source),\n reHasUnescapedHtml = RegExp(reUnescapedHtml.source);\n\n /** Used to match template delimiters. */\n var reEscape = /<%-([\\s\\S]+?)%>/g,\n reEvaluate = /<%([\\s\\S]+?)%>/g,\n reInterpolate = /<%=([\\s\\S]+?)%>/g;\n\n /** Used to match property names within property paths. */\n var reIsDeepProp = /\\.|\\[(?:[^[\\]]*|([\"'])(?:(?!\\1)[^\\\\]|\\\\.)*?\\1)\\]/,\n reIsPlainProp = /^\\w*$/,\n rePropName = /[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g;\n\n /**\n * Used to match `RegExp`\n * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).\n */\n var reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g,\n reHasRegExpChar = RegExp(reRegExpChar.source);\n\n /** Used to match leading whitespace. */\n var reTrimStart = /^\\s+/;\n\n /** Used to match a single whitespace character. */\n var reWhitespace = /\\s/;\n\n /** Used to match wrap detail comments. */\n var reWrapComment = /\\{(?:\\n\\/\\* \\[wrapped with .+\\] \\*\\/)?\\n?/,\n reWrapDetails = /\\{\\n\\/\\* \\[wrapped with (.+)\\] \\*/,\n reSplitDetails = /,? & /;\n\n /** Used to match words composed of alphanumeric characters. */\n var reAsciiWord = /[^\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\x7f]+/g;\n\n /**\n * Used to validate the `validate` option in `_.template` variable.\n *\n * Forbids characters which could potentially change the meaning of the function argument definition:\n * - \"(),\" (modification of function parameters)\n * - \"=\" (default value)\n * - \"[]{}\" (destructuring of function parameters)\n * - \"/\" (beginning of a comment)\n * - whitespace\n */\n var reForbiddenIdentifierChars = /[()=,{}\\[\\]\\/\\s]/;\n\n /** Used to match backslashes in property paths. */\n var reEscapeChar = /\\\\(\\\\)?/g;\n\n /**\n * Used to match\n * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components).\n */\n var reEsTemplate = /\\$\\{([^\\\\}]*(?:\\\\.[^\\\\}]*)*)\\}/g;\n\n /** Used to match `RegExp` flags from their coerced string values. */\n var reFlags = /\\w*$/;\n\n /** Used to detect bad signed hexadecimal string values. */\n var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;\n\n /** Used to detect binary string values. */\n var reIsBinary = /^0b[01]+$/i;\n\n /** Used to detect host constructors (Safari). */\n var reIsHostCtor = /^\\[object .+?Constructor\\]$/;\n\n /** Used to detect octal string values. */\n var reIsOctal = /^0o[0-7]+$/i;\n\n /** Used to detect unsigned integer values. */\n var reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n /** Used to match Latin Unicode letters (excluding mathematical operators). */\n var reLatin = /[\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\xff\\u0100-\\u017f]/g;\n\n /** Used to ensure capturing order of template delimiters. */\n var reNoMatch = /($^)/;\n\n /** Used to match unescaped characters in compiled string literals. */\n var reUnescapedString = /['\\n\\r\\u2028\\u2029\\\\]/g;\n\n /** Used to compose unicode character classes. */\n var rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsDingbatRange = '\\\\u2700-\\\\u27bf',\n rsLowerRange = 'a-z\\\\xdf-\\\\xf6\\\\xf8-\\\\xff',\n rsMathOpRange = '\\\\xac\\\\xb1\\\\xd7\\\\xf7',\n rsNonCharRange = '\\\\x00-\\\\x2f\\\\x3a-\\\\x40\\\\x5b-\\\\x60\\\\x7b-\\\\xbf',\n rsPunctuationRange = '\\\\u2000-\\\\u206f',\n rsSpaceRange = ' \\\\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',\n rsUpperRange = 'A-Z\\\\xc0-\\\\xd6\\\\xd8-\\\\xde',\n rsVarRange = '\\\\ufe0e\\\\ufe0f',\n rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;\n\n /** Used to compose unicode capture groups. */\n var rsApos = \"['\\u2019]\",\n rsAstral = '[' + rsAstralRange + ']',\n rsBreak = '[' + rsBreakRange + ']',\n rsCombo = '[' + rsComboRange + ']',\n rsDigits = '\\\\d+',\n rsDingbat = '[' + rsDingbatRange + ']',\n rsLower = '[' + rsLowerRange + ']',\n rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']',\n rsFitz = '\\\\ud83c[\\\\udffb-\\\\udfff]',\n rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',\n rsNonAstral = '[^' + rsAstralRange + ']',\n rsRegional = '(?:\\\\ud83c[\\\\udde6-\\\\uddff]){2}',\n rsSurrPair = '[\\\\ud800-\\\\udbff][\\\\udc00-\\\\udfff]',\n rsUpper = '[' + rsUpperRange + ']',\n rsZWJ = '\\\\u200d';\n\n /** Used to compose unicode regexes. */\n var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')',\n rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')',\n rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?',\n rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?',\n reOptMod = rsModifier + '?',\n rsOptVar = '[' + rsVarRange + ']?',\n rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',\n rsOrdLower = '\\\\d*(?:1st|2nd|3rd|(?![123])\\\\dth)(?=\\\\b|[A-Z_])',\n rsOrdUpper = '\\\\d*(?:1ST|2ND|3RD|(?![123])\\\\dTH)(?=\\\\b|[a-z_])',\n rsSeq = rsOptVar + reOptMod + rsOptJoin,\n rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq,\n rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';\n\n /** Used to match apostrophes. */\n var reApos = RegExp(rsApos, 'g');\n\n /**\n * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and\n * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).\n */\n var reComboMark = RegExp(rsCombo, 'g');\n\n /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */\n var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');\n\n /** Used to match complex or compound words. */\n var reUnicodeWord = RegExp([\n rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')',\n rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')',\n rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower,\n rsUpper + '+' + rsOptContrUpper,\n rsOrdUpper,\n rsOrdLower,\n rsDigits,\n rsEmoji\n ].join('|'), 'g');\n\n /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */\n var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');\n\n /** Used to detect strings that need a more robust regexp to match words. */\n var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;\n\n /** Used to assign default `context` object properties. */\n var contextProps = [\n 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array',\n 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object',\n 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array',\n 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap',\n '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout'\n ];\n\n /** Used to make template sourceURLs easier to identify. */\n var templateCounter = -1;\n\n /** Used to identify `toStringTag` values of typed arrays. */\n var typedArrayTags = {};\n typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =\n typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =\n typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =\n typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =\n typedArrayTags[uint32Tag] = true;\n typedArrayTags[argsTag] = typedArrayTags[arrayTag] =\n typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =\n typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =\n typedArrayTags[errorTag] = typedArrayTags[funcTag] =\n typedArrayTags[mapTag] = typedArrayTags[numberTag] =\n typedArrayTags[objectTag] = typedArrayTags[regexpTag] =\n typedArrayTags[setTag] = typedArrayTags[stringTag] =\n typedArrayTags[weakMapTag] = false;\n\n /** Used to identify `toStringTag` values supported by `_.clone`. */\n var cloneableTags = {};\n cloneableTags[argsTag] = cloneableTags[arrayTag] =\n cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =\n cloneableTags[boolTag] = cloneableTags[dateTag] =\n cloneableTags[float32Tag] = cloneableTags[float64Tag] =\n cloneableTags[int8Tag] = cloneableTags[int16Tag] =\n cloneableTags[int32Tag] = cloneableTags[mapTag] =\n cloneableTags[numberTag] = cloneableTags[objectTag] =\n cloneableTags[regexpTag] = cloneableTags[setTag] =\n cloneableTags[stringTag] = cloneableTags[symbolTag] =\n cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =\n cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;\n cloneableTags[errorTag] = cloneableTags[funcTag] =\n cloneableTags[weakMapTag] = false;\n\n /** Used to map Latin Unicode letters to basic Latin letters. */\n var deburredLetters = {\n // Latin-1 Supplement block.\n '\\xc0': 'A', '\\xc1': 'A', '\\xc2': 'A', '\\xc3': 'A', '\\xc4': 'A', '\\xc5': 'A',\n '\\xe0': 'a', '\\xe1': 'a', '\\xe2': 'a', '\\xe3': 'a', '\\xe4': 'a', '\\xe5': 'a',\n '\\xc7': 'C', '\\xe7': 'c',\n '\\xd0': 'D', '\\xf0': 'd',\n '\\xc8': 'E', '\\xc9': 'E', '\\xca': 'E', '\\xcb': 'E',\n '\\xe8': 'e', '\\xe9': 'e', '\\xea': 'e', '\\xeb': 'e',\n '\\xcc': 'I', '\\xcd': 'I', '\\xce': 'I', '\\xcf': 'I',\n '\\xec': 'i', '\\xed': 'i', '\\xee': 'i', '\\xef': 'i',\n '\\xd1': 'N', '\\xf1': 'n',\n '\\xd2': 'O', '\\xd3': 'O', '\\xd4': 'O', '\\xd5': 'O', '\\xd6': 'O', '\\xd8': 'O',\n '\\xf2': 'o', '\\xf3': 'o', '\\xf4': 'o', '\\xf5': 'o', '\\xf6': 'o', '\\xf8': 'o',\n '\\xd9': 'U', '\\xda': 'U', '\\xdb': 'U', '\\xdc': 'U',\n '\\xf9': 'u', '\\xfa': 'u', '\\xfb': 'u', '\\xfc': 'u',\n '\\xdd': 'Y', '\\xfd': 'y', '\\xff': 'y',\n '\\xc6': 'Ae', '\\xe6': 'ae',\n '\\xde': 'Th', '\\xfe': 'th',\n '\\xdf': 'ss',\n // Latin Extended-A block.\n '\\u0100': 'A', '\\u0102': 'A', '\\u0104': 'A',\n '\\u0101': 'a', '\\u0103': 'a', '\\u0105': 'a',\n '\\u0106': 'C', '\\u0108': 'C', '\\u010a': 'C', '\\u010c': 'C',\n '\\u0107': 'c', '\\u0109': 'c', '\\u010b': 'c', '\\u010d': 'c',\n '\\u010e': 'D', '\\u0110': 'D', '\\u010f': 'd', '\\u0111': 'd',\n '\\u0112': 'E', '\\u0114': 'E', '\\u0116': 'E', '\\u0118': 'E', '\\u011a': 'E',\n '\\u0113': 'e', '\\u0115': 'e', '\\u0117': 'e', '\\u0119': 'e', '\\u011b': 'e',\n '\\u011c': 'G', '\\u011e': 'G', '\\u0120': 'G', '\\u0122': 'G',\n '\\u011d': 'g', '\\u011f': 'g', '\\u0121': 'g', '\\u0123': 'g',\n '\\u0124': 'H', '\\u0126': 'H', '\\u0125': 'h', '\\u0127': 'h',\n '\\u0128': 'I', '\\u012a': 'I', '\\u012c': 'I', '\\u012e': 'I', '\\u0130': 'I',\n '\\u0129': 'i', '\\u012b': 'i', '\\u012d': 'i', '\\u012f': 'i', '\\u0131': 'i',\n '\\u0134': 'J', '\\u0135': 'j',\n '\\u0136': 'K', '\\u0137': 'k', '\\u0138': 'k',\n '\\u0139': 'L', '\\u013b': 'L', '\\u013d': 'L', '\\u013f': 'L', '\\u0141': 'L',\n '\\u013a': 'l', '\\u013c': 'l', '\\u013e': 'l', '\\u0140': 'l', '\\u0142': 'l',\n '\\u0143': 'N', '\\u0145': 'N', '\\u0147': 'N', '\\u014a': 'N',\n '\\u0144': 'n', '\\u0146': 'n', '\\u0148': 'n', '\\u014b': 'n',\n '\\u014c': 'O', '\\u014e': 'O', '\\u0150': 'O',\n '\\u014d': 'o', '\\u014f': 'o', '\\u0151': 'o',\n '\\u0154': 'R', '\\u0156': 'R', '\\u0158': 'R',\n '\\u0155': 'r', '\\u0157': 'r', '\\u0159': 'r',\n '\\u015a': 'S', '\\u015c': 'S', '\\u015e': 'S', '\\u0160': 'S',\n '\\u015b': 's', '\\u015d': 's', '\\u015f': 's', '\\u0161': 's',\n '\\u0162': 'T', '\\u0164': 'T', '\\u0166': 'T',\n '\\u0163': 't', '\\u0165': 't', '\\u0167': 't',\n '\\u0168': 'U', '\\u016a': 'U', '\\u016c': 'U', '\\u016e': 'U', '\\u0170': 'U', '\\u0172': 'U',\n '\\u0169': 'u', '\\u016b': 'u', '\\u016d': 'u', '\\u016f': 'u', '\\u0171': 'u', '\\u0173': 'u',\n '\\u0174': 'W', '\\u0175': 'w',\n '\\u0176': 'Y', '\\u0177': 'y', '\\u0178': 'Y',\n '\\u0179': 'Z', '\\u017b': 'Z', '\\u017d': 'Z',\n '\\u017a': 'z', '\\u017c': 'z', '\\u017e': 'z',\n '\\u0132': 'IJ', '\\u0133': 'ij',\n '\\u0152': 'Oe', '\\u0153': 'oe',\n '\\u0149': \"'n\", '\\u017f': 's'\n };\n\n /** Used to map characters to HTML entities. */\n var htmlEscapes = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": '''\n };\n\n /** Used to map HTML entities to characters. */\n var htmlUnescapes = {\n '&': '&',\n '<': '<',\n '>': '>',\n '"': '\"',\n ''': \"'\"\n };\n\n /** Used to escape characters for inclusion in compiled string literals. */\n var stringEscapes = {\n '\\\\': '\\\\',\n \"'\": \"'\",\n '\\n': 'n',\n '\\r': 'r',\n '\\u2028': 'u2028',\n '\\u2029': 'u2029'\n };\n\n /** Built-in method references without a dependency on `root`. */\n var freeParseFloat = parseFloat,\n freeParseInt = parseInt;\n\n /** Detect free variable `global` from Node.js. */\n var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\n /** Detect free variable `self`. */\n var freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n /** Used as a reference to the global object. */\n var root = freeGlobal || freeSelf || Function('return this')();\n\n /** Detect free variable `exports`. */\n var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n /** Detect free variable `module`. */\n var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n /** Detect the popular CommonJS extension `module.exports`. */\n var moduleExports = freeModule && freeModule.exports === freeExports;\n\n /** Detect free variable `process` from Node.js. */\n var freeProcess = moduleExports && freeGlobal.process;\n\n /** Used to access faster Node.js helpers. */\n var nodeUtil = (function() {\n try {\n // Use `util.types` for Node.js 10+.\n var types = freeModule && freeModule.require && freeModule.require('util').types;\n\n if (types) {\n return types;\n }\n\n // Legacy `process.binding('util')` for Node.js < 10.\n return freeProcess && freeProcess.binding && freeProcess.binding('util');\n } catch (e) {}\n }());\n\n /* Node.js helper references. */\n var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer,\n nodeIsDate = nodeUtil && nodeUtil.isDate,\n nodeIsMap = nodeUtil && nodeUtil.isMap,\n nodeIsRegExp = nodeUtil && nodeUtil.isRegExp,\n nodeIsSet = nodeUtil && nodeUtil.isSet,\n nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;\n\n /*--------------------------------------------------------------------------*/\n\n /**\n * A faster alternative to `Function#apply`, this function invokes `func`\n * with the `this` binding of `thisArg` and the arguments of `args`.\n *\n * @private\n * @param {Function} func The function to invoke.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} args The arguments to invoke `func` with.\n * @returns {*} Returns the result of `func`.\n */\n function apply(func, thisArg, args) {\n switch (args.length) {\n case 0: return func.call(thisArg);\n case 1: return func.call(thisArg, args[0]);\n case 2: return func.call(thisArg, args[0], args[1]);\n case 3: return func.call(thisArg, args[0], args[1], args[2]);\n }\n return func.apply(thisArg, args);\n }\n\n /**\n * A specialized version of `baseAggregator` for arrays.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} setter The function to set `accumulator` values.\n * @param {Function} iteratee The iteratee to transform keys.\n * @param {Object} accumulator The initial aggregated object.\n * @returns {Function} Returns `accumulator`.\n */\n function arrayAggregator(array, setter, iteratee, accumulator) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n var value = array[index];\n setter(accumulator, value, iteratee(value), array);\n }\n return accumulator;\n }\n\n /**\n * A specialized version of `_.forEach` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns `array`.\n */\n function arrayEach(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (iteratee(array[index], index, array) === false) {\n break;\n }\n }\n return array;\n }\n\n /**\n * A specialized version of `_.forEachRight` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns `array`.\n */\n function arrayEachRight(array, iteratee) {\n var length = array == null ? 0 : array.length;\n\n while (length--) {\n if (iteratee(array[length], length, array) === false) {\n break;\n }\n }\n return array;\n }\n\n /**\n * A specialized version of `_.every` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if all elements pass the predicate check,\n * else `false`.\n */\n function arrayEvery(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (!predicate(array[index], index, array)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * A specialized version of `_.filter` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\n function arrayFilter(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result[resIndex++] = value;\n }\n }\n return result;\n }\n\n /**\n * A specialized version of `_.includes` for arrays without support for\n * specifying an index to search from.\n *\n * @private\n * @param {Array} [array] The array to inspect.\n * @param {*} target The value to search for.\n * @returns {boolean} Returns `true` if `target` is found, else `false`.\n */\n function arrayIncludes(array, value) {\n var length = array == null ? 0 : array.length;\n return !!length && baseIndexOf(array, value, 0) > -1;\n }\n\n /**\n * This function is like `arrayIncludes` except that it accepts a comparator.\n *\n * @private\n * @param {Array} [array] The array to inspect.\n * @param {*} target The value to search for.\n * @param {Function} comparator The comparator invoked per element.\n * @returns {boolean} Returns `true` if `target` is found, else `false`.\n */\n function arrayIncludesWith(array, value, comparator) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (comparator(value, array[index])) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * A specialized version of `_.map` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\n function arrayMap(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length,\n result = Array(length);\n\n while (++index < length) {\n result[index] = iteratee(array[index], index, array);\n }\n return result;\n }\n\n /**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\n function arrayPush(array, values) {\n var index = -1,\n length = values.length,\n offset = array.length;\n\n while (++index < length) {\n array[offset + index] = values[index];\n }\n return array;\n }\n\n /**\n * A specialized version of `_.reduce` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {*} [accumulator] The initial value.\n * @param {boolean} [initAccum] Specify using the first element of `array` as\n * the initial value.\n * @returns {*} Returns the accumulated value.\n */\n function arrayReduce(array, iteratee, accumulator, initAccum) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n if (initAccum && length) {\n accumulator = array[++index];\n }\n while (++index < length) {\n accumulator = iteratee(accumulator, array[index], index, array);\n }\n return accumulator;\n }\n\n /**\n * A specialized version of `_.reduceRight` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {*} [accumulator] The initial value.\n * @param {boolean} [initAccum] Specify using the last element of `array` as\n * the initial value.\n * @returns {*} Returns the accumulated value.\n */\n function arrayReduceRight(array, iteratee, accumulator, initAccum) {\n var length = array == null ? 0 : array.length;\n if (initAccum && length) {\n accumulator = array[--length];\n }\n while (length--) {\n accumulator = iteratee(accumulator, array[length], length, array);\n }\n return accumulator;\n }\n\n /**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\n function arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Gets the size of an ASCII `string`.\n *\n * @private\n * @param {string} string The string inspect.\n * @returns {number} Returns the string size.\n */\n var asciiSize = baseProperty('length');\n\n /**\n * Converts an ASCII `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\n function asciiToArray(string) {\n return string.split('');\n }\n\n /**\n * Splits an ASCII `string` into an array of its words.\n *\n * @private\n * @param {string} The string to inspect.\n * @returns {Array} Returns the words of `string`.\n */\n function asciiWords(string) {\n return string.match(reAsciiWord) || [];\n }\n\n /**\n * The base implementation of methods like `_.findKey` and `_.findLastKey`,\n * without support for iteratee shorthands, which iterates over `collection`\n * using `eachFunc`.\n *\n * @private\n * @param {Array|Object} collection The collection to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {Function} eachFunc The function to iterate over `collection`.\n * @returns {*} Returns the found element or its key, else `undefined`.\n */\n function baseFindKey(collection, predicate, eachFunc) {\n var result;\n eachFunc(collection, function(value, key, collection) {\n if (predicate(value, key, collection)) {\n result = key;\n return false;\n }\n });\n return result;\n }\n\n /**\n * The base implementation of `_.findIndex` and `_.findLastIndex` without\n * support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {number} fromIndex The index to search from.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\n function baseFindIndex(array, predicate, fromIndex, fromRight) {\n var length = array.length,\n index = fromIndex + (fromRight ? 1 : -1);\n\n while ((fromRight ? index-- : ++index < length)) {\n if (predicate(array[index], index, array)) {\n return index;\n }\n }\n return -1;\n }\n\n /**\n * The base implementation of `_.indexOf` without `fromIndex` bounds checks.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\n function baseIndexOf(array, value, fromIndex) {\n return value === value\n ? strictIndexOf(array, value, fromIndex)\n : baseFindIndex(array, baseIsNaN, fromIndex);\n }\n\n /**\n * This function is like `baseIndexOf` except that it accepts a comparator.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @param {Function} comparator The comparator invoked per element.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\n function baseIndexOfWith(array, value, fromIndex, comparator) {\n var index = fromIndex - 1,\n length = array.length;\n\n while (++index < length) {\n if (comparator(array[index], value)) {\n return index;\n }\n }\n return -1;\n }\n\n /**\n * The base implementation of `_.isNaN` without support for number objects.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.\n */\n function baseIsNaN(value) {\n return value !== value;\n }\n\n /**\n * The base implementation of `_.mean` and `_.meanBy` without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {number} Returns the mean.\n */\n function baseMean(array, iteratee) {\n var length = array == null ? 0 : array.length;\n return length ? (baseSum(array, iteratee) / length) : NAN;\n }\n\n /**\n * The base implementation of `_.property` without support for deep paths.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @returns {Function} Returns the new accessor function.\n */\n function baseProperty(key) {\n return function(object) {\n return object == null ? undefined : object[key];\n };\n }\n\n /**\n * The base implementation of `_.propertyOf` without support for deep paths.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Function} Returns the new accessor function.\n */\n function basePropertyOf(object) {\n return function(key) {\n return object == null ? undefined : object[key];\n };\n }\n\n /**\n * The base implementation of `_.reduce` and `_.reduceRight`, without support\n * for iteratee shorthands, which iterates over `collection` using `eachFunc`.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {*} accumulator The initial value.\n * @param {boolean} initAccum Specify using the first or last element of\n * `collection` as the initial value.\n * @param {Function} eachFunc The function to iterate over `collection`.\n * @returns {*} Returns the accumulated value.\n */\n function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) {\n eachFunc(collection, function(value, index, collection) {\n accumulator = initAccum\n ? (initAccum = false, value)\n : iteratee(accumulator, value, index, collection);\n });\n return accumulator;\n }\n\n /**\n * The base implementation of `_.sortBy` which uses `comparer` to define the\n * sort order of `array` and replaces criteria objects with their corresponding\n * values.\n *\n * @private\n * @param {Array} array The array to sort.\n * @param {Function} comparer The function to define sort order.\n * @returns {Array} Returns `array`.\n */\n function baseSortBy(array, comparer) {\n var length = array.length;\n\n array.sort(comparer);\n while (length--) {\n array[length] = array[length].value;\n }\n return array;\n }\n\n /**\n * The base implementation of `_.sum` and `_.sumBy` without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {number} Returns the sum.\n */\n function baseSum(array, iteratee) {\n var result,\n index = -1,\n length = array.length;\n\n while (++index < length) {\n var current = iteratee(array[index]);\n if (current !== undefined) {\n result = result === undefined ? current : (result + current);\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\n function baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n }\n\n /**\n * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array\n * of key-value pairs for `object` corresponding to the property names of `props`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array} props The property names to get values for.\n * @returns {Object} Returns the key-value pairs.\n */\n function baseToPairs(object, props) {\n return arrayMap(props, function(key) {\n return [key, object[key]];\n });\n }\n\n /**\n * The base implementation of `_.trim`.\n *\n * @private\n * @param {string} string The string to trim.\n * @returns {string} Returns the trimmed string.\n */\n function baseTrim(string) {\n return string\n ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '')\n : string;\n }\n\n /**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\n function baseUnary(func) {\n return function(value) {\n return func(value);\n };\n }\n\n /**\n * The base implementation of `_.values` and `_.valuesIn` which creates an\n * array of `object` property values corresponding to the property names\n * of `props`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array} props The property names to get values for.\n * @returns {Object} Returns the array of property values.\n */\n function baseValues(object, props) {\n return arrayMap(props, function(key) {\n return object[key];\n });\n }\n\n /**\n * Checks if a `cache` value for `key` exists.\n *\n * @private\n * @param {Object} cache The cache to query.\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\n function cacheHas(cache, key) {\n return cache.has(key);\n }\n\n /**\n * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol\n * that is not found in the character symbols.\n *\n * @private\n * @param {Array} strSymbols The string symbols to inspect.\n * @param {Array} chrSymbols The character symbols to find.\n * @returns {number} Returns the index of the first unmatched string symbol.\n */\n function charsStartIndex(strSymbols, chrSymbols) {\n var index = -1,\n length = strSymbols.length;\n\n while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}\n return index;\n }\n\n /**\n * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol\n * that is not found in the character symbols.\n *\n * @private\n * @param {Array} strSymbols The string symbols to inspect.\n * @param {Array} chrSymbols The character symbols to find.\n * @returns {number} Returns the index of the last unmatched string symbol.\n */\n function charsEndIndex(strSymbols, chrSymbols) {\n var index = strSymbols.length;\n\n while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}\n return index;\n }\n\n /**\n * Gets the number of `placeholder` occurrences in `array`.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} placeholder The placeholder to search for.\n * @returns {number} Returns the placeholder count.\n */\n function countHolders(array, placeholder) {\n var length = array.length,\n result = 0;\n\n while (length--) {\n if (array[length] === placeholder) {\n ++result;\n }\n }\n return result;\n }\n\n /**\n * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A\n * letters to basic Latin letters.\n *\n * @private\n * @param {string} letter The matched letter to deburr.\n * @returns {string} Returns the deburred letter.\n */\n var deburrLetter = basePropertyOf(deburredLetters);\n\n /**\n * Used by `_.escape` to convert characters to HTML entities.\n *\n * @private\n * @param {string} chr The matched character to escape.\n * @returns {string} Returns the escaped character.\n */\n var escapeHtmlChar = basePropertyOf(htmlEscapes);\n\n /**\n * Used by `_.template` to escape characters for inclusion in compiled string literals.\n *\n * @private\n * @param {string} chr The matched character to escape.\n * @returns {string} Returns the escaped character.\n */\n function escapeStringChar(chr) {\n return '\\\\' + stringEscapes[chr];\n }\n\n /**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\n function getValue(object, key) {\n return object == null ? undefined : object[key];\n }\n\n /**\n * Checks if `string` contains Unicode symbols.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {boolean} Returns `true` if a symbol is found, else `false`.\n */\n function hasUnicode(string) {\n return reHasUnicode.test(string);\n }\n\n /**\n * Checks if `string` contains a word composed of Unicode symbols.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {boolean} Returns `true` if a word is found, else `false`.\n */\n function hasUnicodeWord(string) {\n return reHasUnicodeWord.test(string);\n }\n\n /**\n * Converts `iterator` to an array.\n *\n * @private\n * @param {Object} iterator The iterator to convert.\n * @returns {Array} Returns the converted array.\n */\n function iteratorToArray(iterator) {\n var data,\n result = [];\n\n while (!(data = iterator.next()).done) {\n result.push(data.value);\n }\n return result;\n }\n\n /**\n * Converts `map` to its key-value pairs.\n *\n * @private\n * @param {Object} map The map to convert.\n * @returns {Array} Returns the key-value pairs.\n */\n function mapToArray(map) {\n var index = -1,\n result = Array(map.size);\n\n map.forEach(function(value, key) {\n result[++index] = [key, value];\n });\n return result;\n }\n\n /**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\n function overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n }\n\n /**\n * Replaces all `placeholder` elements in `array` with an internal placeholder\n * and returns an array of their indexes.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {*} placeholder The placeholder to replace.\n * @returns {Array} Returns the new array of placeholder indexes.\n */\n function replaceHolders(array, placeholder) {\n var index = -1,\n length = array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (value === placeholder || value === PLACEHOLDER) {\n array[index] = PLACEHOLDER;\n result[resIndex++] = index;\n }\n }\n return result;\n }\n\n /**\n * Converts `set` to an array of its values.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the values.\n */\n function setToArray(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = value;\n });\n return result;\n }\n\n /**\n * Converts `set` to its value-value pairs.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the value-value pairs.\n */\n function setToPairs(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = [value, value];\n });\n return result;\n }\n\n /**\n * A specialized version of `_.indexOf` which performs strict equality\n * comparisons of values, i.e. `===`.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\n function strictIndexOf(array, value, fromIndex) {\n var index = fromIndex - 1,\n length = array.length;\n\n while (++index < length) {\n if (array[index] === value) {\n return index;\n }\n }\n return -1;\n }\n\n /**\n * A specialized version of `_.lastIndexOf` which performs strict equality\n * comparisons of values, i.e. `===`.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\n function strictLastIndexOf(array, value, fromIndex) {\n var index = fromIndex + 1;\n while (index--) {\n if (array[index] === value) {\n return index;\n }\n }\n return index;\n }\n\n /**\n * Gets the number of symbols in `string`.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {number} Returns the string size.\n */\n function stringSize(string) {\n return hasUnicode(string)\n ? unicodeSize(string)\n : asciiSize(string);\n }\n\n /**\n * Converts `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\n function stringToArray(string) {\n return hasUnicode(string)\n ? unicodeToArray(string)\n : asciiToArray(string);\n }\n\n /**\n * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace\n * character of `string`.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {number} Returns the index of the last non-whitespace character.\n */\n function trimmedEndIndex(string) {\n var index = string.length;\n\n while (index-- && reWhitespace.test(string.charAt(index))) {}\n return index;\n }\n\n /**\n * Used by `_.unescape` to convert HTML entities to characters.\n *\n * @private\n * @param {string} chr The matched character to unescape.\n * @returns {string} Returns the unescaped character.\n */\n var unescapeHtmlChar = basePropertyOf(htmlUnescapes);\n\n /**\n * Gets the size of a Unicode `string`.\n *\n * @private\n * @param {string} string The string inspect.\n * @returns {number} Returns the string size.\n */\n function unicodeSize(string) {\n var result = reUnicode.lastIndex = 0;\n while (reUnicode.test(string)) {\n ++result;\n }\n return result;\n }\n\n /**\n * Converts a Unicode `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\n function unicodeToArray(string) {\n return string.match(reUnicode) || [];\n }\n\n /**\n * Splits a Unicode `string` into an array of its words.\n *\n * @private\n * @param {string} The string to inspect.\n * @returns {Array} Returns the words of `string`.\n */\n function unicodeWords(string) {\n return string.match(reUnicodeWord) || [];\n }\n\n /*--------------------------------------------------------------------------*/\n\n /**\n * Create a new pristine `lodash` function using the `context` object.\n *\n * @static\n * @memberOf _\n * @since 1.1.0\n * @category Util\n * @param {Object} [context=root] The context object.\n * @returns {Function} Returns a new `lodash` function.\n * @example\n *\n * _.mixin({ 'foo': _.constant('foo') });\n *\n * var lodash = _.runInContext();\n * lodash.mixin({ 'bar': lodash.constant('bar') });\n *\n * _.isFunction(_.foo);\n * // => true\n * _.isFunction(_.bar);\n * // => false\n *\n * lodash.isFunction(lodash.foo);\n * // => false\n * lodash.isFunction(lodash.bar);\n * // => true\n *\n * // Create a suped-up `defer` in Node.js.\n * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer;\n */\n var runInContext = (function runInContext(context) {\n context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps));\n\n /** Built-in constructor references. */\n var Array = context.Array,\n Date = context.Date,\n Error = context.Error,\n Function = context.Function,\n Math = context.Math,\n Object = context.Object,\n RegExp = context.RegExp,\n String = context.String,\n TypeError = context.TypeError;\n\n /** Used for built-in method references. */\n var arrayProto = Array.prototype,\n funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n /** Used to detect overreaching core-js shims. */\n var coreJsData = context['__core-js_shared__'];\n\n /** Used to resolve the decompiled source of functions. */\n var funcToString = funcProto.toString;\n\n /** Used to check objects for own properties. */\n var hasOwnProperty = objectProto.hasOwnProperty;\n\n /** Used to generate unique IDs. */\n var idCounter = 0;\n\n /** Used to detect methods masquerading as native. */\n var maskSrcKey = (function() {\n var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');\n return uid ? ('Symbol(src)_1.' + uid) : '';\n }());\n\n /**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\n var nativeObjectToString = objectProto.toString;\n\n /** Used to infer the `Object` constructor. */\n var objectCtorString = funcToString.call(Object);\n\n /** Used to restore the original `_` reference in `_.noConflict`. */\n var oldDash = root._;\n\n /** Used to detect if a method is native. */\n var reIsNative = RegExp('^' +\n funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\\\$&')\n .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '$1.*?') + '$'\n );\n\n /** Built-in value references. */\n var Buffer = moduleExports ? context.Buffer : undefined,\n Symbol = context.Symbol,\n Uint8Array = context.Uint8Array,\n allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined,\n getPrototype = overArg(Object.getPrototypeOf, Object),\n objectCreate = Object.create,\n propertyIsEnumerable = objectProto.propertyIsEnumerable,\n splice = arrayProto.splice,\n spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined,\n symIterator = Symbol ? Symbol.iterator : undefined,\n symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n var defineProperty = (function() {\n try {\n var func = getNative(Object, 'defineProperty');\n func({}, '', {});\n return func;\n } catch (e) {}\n }());\n\n /** Mocked built-ins. */\n var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout,\n ctxNow = Date && Date.now !== root.Date.now && Date.now,\n ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout;\n\n /* Built-in method references for those with the same name as other `lodash` methods. */\n var nativeCeil = Math.ceil,\n nativeFloor = Math.floor,\n nativeGetSymbols = Object.getOwnPropertySymbols,\n nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,\n nativeIsFinite = context.isFinite,\n nativeJoin = arrayProto.join,\n nativeKeys = overArg(Object.keys, Object),\n nativeMax = Math.max,\n nativeMin = Math.min,\n nativeNow = Date.now,\n nativeParseInt = context.parseInt,\n nativeRandom = Math.random,\n nativeReverse = arrayProto.reverse;\n\n /* Built-in method references that are verified to be native. */\n var DataView = getNative(context, 'DataView'),\n Map = getNative(context, 'Map'),\n Promise = getNative(context, 'Promise'),\n Set = getNative(context, 'Set'),\n WeakMap = getNative(context, 'WeakMap'),\n nativeCreate = getNative(Object, 'create');\n\n /** Used to store function metadata. */\n var metaMap = WeakMap && new WeakMap;\n\n /** Used to lookup unminified function names. */\n var realNames = {};\n\n /** Used to detect maps, sets, and weakmaps. */\n var dataViewCtorString = toSource(DataView),\n mapCtorString = toSource(Map),\n promiseCtorString = toSource(Promise),\n setCtorString = toSource(Set),\n weakMapCtorString = toSource(WeakMap);\n\n /** Used to convert symbols to primitives and strings. */\n var symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolValueOf = symbolProto ? symbolProto.valueOf : undefined,\n symbolToString = symbolProto ? symbolProto.toString : undefined;\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates a `lodash` object which wraps `value` to enable implicit method\n * chain sequences. Methods that operate on and return arrays, collections,\n * and functions can be chained together. Methods that retrieve a single value\n * or may return a primitive value will automatically end the chain sequence\n * and return the unwrapped value. Otherwise, the value must be unwrapped\n * with `_#value`.\n *\n * Explicit chain sequences, which must be unwrapped with `_#value`, may be\n * enabled using `_.chain`.\n *\n * The execution of chained methods is lazy, that is, it's deferred until\n * `_#value` is implicitly or explicitly called.\n *\n * Lazy evaluation allows several methods to support shortcut fusion.\n * Shortcut fusion is an optimization to merge iteratee calls; this avoids\n * the creation of intermediate arrays and can greatly reduce the number of\n * iteratee executions. Sections of a chain sequence qualify for shortcut\n * fusion if the section is applied to an array and iteratees accept only\n * one argument. The heuristic for whether a section qualifies for shortcut\n * fusion is subject to change.\n *\n * Chaining is supported in custom builds as long as the `_#value` method is\n * directly or indirectly included in the build.\n *\n * In addition to lodash methods, wrappers have `Array` and `String` methods.\n *\n * The wrapper `Array` methods are:\n * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift`\n *\n * The wrapper `String` methods are:\n * `replace` and `split`\n *\n * The wrapper methods that support shortcut fusion are:\n * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`,\n * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`,\n * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray`\n *\n * The chainable wrapper methods are:\n * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`,\n * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`,\n * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`,\n * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`,\n * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`,\n * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`,\n * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`,\n * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`,\n * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`,\n * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`,\n * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`,\n * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`,\n * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`,\n * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`,\n * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`,\n * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`,\n * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`,\n * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`,\n * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`,\n * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`,\n * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`,\n * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`,\n * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`,\n * `zipObject`, `zipObjectDeep`, and `zipWith`\n *\n * The wrapper methods that are **not** chainable by default are:\n * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`,\n * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`,\n * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`,\n * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`,\n * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`,\n * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`,\n * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`,\n * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`,\n * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`,\n * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`,\n * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`,\n * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`,\n * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`,\n * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`,\n * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`,\n * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`,\n * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`,\n * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`,\n * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`,\n * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`,\n * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`,\n * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`,\n * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`,\n * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`,\n * `upperFirst`, `value`, and `words`\n *\n * @name _\n * @constructor\n * @category Seq\n * @param {*} value The value to wrap in a `lodash` instance.\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * function square(n) {\n * return n * n;\n * }\n *\n * var wrapped = _([1, 2, 3]);\n *\n * // Returns an unwrapped value.\n * wrapped.reduce(_.add);\n * // => 6\n *\n * // Returns a wrapped value.\n * var squares = wrapped.map(square);\n *\n * _.isArray(squares);\n * // => false\n *\n * _.isArray(squares.value());\n * // => true\n */\n function lodash(value) {\n if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) {\n if (value instanceof LodashWrapper) {\n return value;\n }\n if (hasOwnProperty.call(value, '__wrapped__')) {\n return wrapperClone(value);\n }\n }\n return new LodashWrapper(value);\n }\n\n /**\n * The base implementation of `_.create` without support for assigning\n * properties to the created object.\n *\n * @private\n * @param {Object} proto The object to inherit from.\n * @returns {Object} Returns the new object.\n */\n var baseCreate = (function() {\n function object() {}\n return function(proto) {\n if (!isObject(proto)) {\n return {};\n }\n if (objectCreate) {\n return objectCreate(proto);\n }\n object.prototype = proto;\n var result = new object;\n object.prototype = undefined;\n return result;\n };\n }());\n\n /**\n * The function whose prototype chain sequence wrappers inherit from.\n *\n * @private\n */\n function baseLodash() {\n // No operation performed.\n }\n\n /**\n * The base constructor for creating `lodash` wrapper objects.\n *\n * @private\n * @param {*} value The value to wrap.\n * @param {boolean} [chainAll] Enable explicit method chain sequences.\n */\n function LodashWrapper(value, chainAll) {\n this.__wrapped__ = value;\n this.__actions__ = [];\n this.__chain__ = !!chainAll;\n this.__index__ = 0;\n this.__values__ = undefined;\n }\n\n /**\n * By default, the template delimiters used by lodash are like those in\n * embedded Ruby (ERB) as well as ES2015 template strings. Change the\n * following template settings to use alternative delimiters.\n *\n * @static\n * @memberOf _\n * @type {Object}\n */\n lodash.templateSettings = {\n\n /**\n * Used to detect `data` property values to be HTML-escaped.\n *\n * @memberOf _.templateSettings\n * @type {RegExp}\n */\n 'escape': reEscape,\n\n /**\n * Used to detect code to be evaluated.\n *\n * @memberOf _.templateSettings\n * @type {RegExp}\n */\n 'evaluate': reEvaluate,\n\n /**\n * Used to detect `data` property values to inject.\n *\n * @memberOf _.templateSettings\n * @type {RegExp}\n */\n 'interpolate': reInterpolate,\n\n /**\n * Used to reference the data object in the template text.\n *\n * @memberOf _.templateSettings\n * @type {string}\n */\n 'variable': '',\n\n /**\n * Used to import variables into the compiled template.\n *\n * @memberOf _.templateSettings\n * @type {Object}\n */\n 'imports': {\n\n /**\n * A reference to the `lodash` function.\n *\n * @memberOf _.templateSettings.imports\n * @type {Function}\n */\n '_': lodash\n }\n };\n\n // Ensure wrappers are instances of `baseLodash`.\n lodash.prototype = baseLodash.prototype;\n lodash.prototype.constructor = lodash;\n\n LodashWrapper.prototype = baseCreate(baseLodash.prototype);\n LodashWrapper.prototype.constructor = LodashWrapper;\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.\n *\n * @private\n * @constructor\n * @param {*} value The value to wrap.\n */\n function LazyWrapper(value) {\n this.__wrapped__ = value;\n this.__actions__ = [];\n this.__dir__ = 1;\n this.__filtered__ = false;\n this.__iteratees__ = [];\n this.__takeCount__ = MAX_ARRAY_LENGTH;\n this.__views__ = [];\n }\n\n /**\n * Creates a clone of the lazy wrapper object.\n *\n * @private\n * @name clone\n * @memberOf LazyWrapper\n * @returns {Object} Returns the cloned `LazyWrapper` object.\n */\n function lazyClone() {\n var result = new LazyWrapper(this.__wrapped__);\n result.__actions__ = copyArray(this.__actions__);\n result.__dir__ = this.__dir__;\n result.__filtered__ = this.__filtered__;\n result.__iteratees__ = copyArray(this.__iteratees__);\n result.__takeCount__ = this.__takeCount__;\n result.__views__ = copyArray(this.__views__);\n return result;\n }\n\n /**\n * Reverses the direction of lazy iteration.\n *\n * @private\n * @name reverse\n * @memberOf LazyWrapper\n * @returns {Object} Returns the new reversed `LazyWrapper` object.\n */\n function lazyReverse() {\n if (this.__filtered__) {\n var result = new LazyWrapper(this);\n result.__dir__ = -1;\n result.__filtered__ = true;\n } else {\n result = this.clone();\n result.__dir__ *= -1;\n }\n return result;\n }\n\n /**\n * Extracts the unwrapped value from its lazy wrapper.\n *\n * @private\n * @name value\n * @memberOf LazyWrapper\n * @returns {*} Returns the unwrapped value.\n */\n function lazyValue() {\n var array = this.__wrapped__.value(),\n dir = this.__dir__,\n isArr = isArray(array),\n isRight = dir < 0,\n arrLength = isArr ? array.length : 0,\n view = getView(0, arrLength, this.__views__),\n start = view.start,\n end = view.end,\n length = end - start,\n index = isRight ? end : (start - 1),\n iteratees = this.__iteratees__,\n iterLength = iteratees.length,\n resIndex = 0,\n takeCount = nativeMin(length, this.__takeCount__);\n\n if (!isArr || (!isRight && arrLength == length && takeCount == length)) {\n return baseWrapperValue(array, this.__actions__);\n }\n var result = [];\n\n outer:\n while (length-- && resIndex < takeCount) {\n index += dir;\n\n var iterIndex = -1,\n value = array[index];\n\n while (++iterIndex < iterLength) {\n var data = iteratees[iterIndex],\n iteratee = data.iteratee,\n type = data.type,\n computed = iteratee(value);\n\n if (type == LAZY_MAP_FLAG) {\n value = computed;\n } else if (!computed) {\n if (type == LAZY_FILTER_FLAG) {\n continue outer;\n } else {\n break outer;\n }\n }\n }\n result[resIndex++] = value;\n }\n return result;\n }\n\n // Ensure `LazyWrapper` is an instance of `baseLodash`.\n LazyWrapper.prototype = baseCreate(baseLodash.prototype);\n LazyWrapper.prototype.constructor = LazyWrapper;\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates a hash object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\n function Hash(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n }\n\n /**\n * Removes all key-value entries from the hash.\n *\n * @private\n * @name clear\n * @memberOf Hash\n */\n function hashClear() {\n this.__data__ = nativeCreate ? nativeCreate(null) : {};\n this.size = 0;\n }\n\n /**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\n function hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n }\n\n /**\n * Gets the hash value for `key`.\n *\n * @private\n * @name get\n * @memberOf Hash\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\n function hashGet(key) {\n var data = this.__data__;\n if (nativeCreate) {\n var result = data[key];\n return result === HASH_UNDEFINED ? undefined : result;\n }\n return hasOwnProperty.call(data, key) ? data[key] : undefined;\n }\n\n /**\n * Checks if a hash value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Hash\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\n function hashHas(key) {\n var data = this.__data__;\n return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);\n }\n\n /**\n * Sets the hash `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Hash\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the hash instance.\n */\n function hashSet(key, value) {\n var data = this.__data__;\n this.size += this.has(key) ? 0 : 1;\n data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;\n return this;\n }\n\n // Add methods to `Hash`.\n Hash.prototype.clear = hashClear;\n Hash.prototype['delete'] = hashDelete;\n Hash.prototype.get = hashGet;\n Hash.prototype.has = hashHas;\n Hash.prototype.set = hashSet;\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates an list cache object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\n function ListCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n }\n\n /**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\n function listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n }\n\n /**\n * Removes `key` and its value from the list cache.\n *\n * @private\n * @name delete\n * @memberOf ListCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\n function listCacheDelete(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n return false;\n }\n var lastIndex = data.length - 1;\n if (index == lastIndex) {\n data.pop();\n } else {\n splice.call(data, index, 1);\n }\n --this.size;\n return true;\n }\n\n /**\n * Gets the list cache value for `key`.\n *\n * @private\n * @name get\n * @memberOf ListCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\n function listCacheGet(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n return index < 0 ? undefined : data[index][1];\n }\n\n /**\n * Checks if a list cache value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf ListCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\n function listCacheHas(key) {\n return assocIndexOf(this.__data__, key) > -1;\n }\n\n /**\n * Sets the list cache `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf ListCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the list cache instance.\n */\n function listCacheSet(key, value) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n ++this.size;\n data.push([key, value]);\n } else {\n data[index][1] = value;\n }\n return this;\n }\n\n // Add methods to `ListCache`.\n ListCache.prototype.clear = listCacheClear;\n ListCache.prototype['delete'] = listCacheDelete;\n ListCache.prototype.get = listCacheGet;\n ListCache.prototype.has = listCacheHas;\n ListCache.prototype.set = listCacheSet;\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates a map cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\n function MapCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n }\n\n /**\n * Removes all key-value entries from the map.\n *\n * @private\n * @name clear\n * @memberOf MapCache\n */\n function mapCacheClear() {\n this.size = 0;\n this.__data__ = {\n 'hash': new Hash,\n 'map': new (Map || ListCache),\n 'string': new Hash\n };\n }\n\n /**\n * Removes `key` and its value from the map.\n *\n * @private\n * @name delete\n * @memberOf MapCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\n function mapCacheDelete(key) {\n var result = getMapData(this, key)['delete'](key);\n this.size -= result ? 1 : 0;\n return result;\n }\n\n /**\n * Gets the map value for `key`.\n *\n * @private\n * @name get\n * @memberOf MapCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\n function mapCacheGet(key) {\n return getMapData(this, key).get(key);\n }\n\n /**\n * Checks if a map value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf MapCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\n function mapCacheHas(key) {\n return getMapData(this, key).has(key);\n }\n\n /**\n * Sets the map `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf MapCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the map cache instance.\n */\n function mapCacheSet(key, value) {\n var data = getMapData(this, key),\n size = data.size;\n\n data.set(key, value);\n this.size += data.size == size ? 0 : 1;\n return this;\n }\n\n // Add methods to `MapCache`.\n MapCache.prototype.clear = mapCacheClear;\n MapCache.prototype['delete'] = mapCacheDelete;\n MapCache.prototype.get = mapCacheGet;\n MapCache.prototype.has = mapCacheHas;\n MapCache.prototype.set = mapCacheSet;\n\n /*------------------------------------------------------------------------*/\n\n /**\n *\n * Creates an array cache object to store unique values.\n *\n * @private\n * @constructor\n * @param {Array} [values] The values to cache.\n */\n function SetCache(values) {\n var index = -1,\n length = values == null ? 0 : values.length;\n\n this.__data__ = new MapCache;\n while (++index < length) {\n this.add(values[index]);\n }\n }\n\n /**\n * Adds `value` to the array cache.\n *\n * @private\n * @name add\n * @memberOf SetCache\n * @alias push\n * @param {*} value The value to cache.\n * @returns {Object} Returns the cache instance.\n */\n function setCacheAdd(value) {\n this.__data__.set(value, HASH_UNDEFINED);\n return this;\n }\n\n /**\n * Checks if `value` is in the array cache.\n *\n * @private\n * @name has\n * @memberOf SetCache\n * @param {*} value The value to search for.\n * @returns {number} Returns `true` if `value` is found, else `false`.\n */\n function setCacheHas(value) {\n return this.__data__.has(value);\n }\n\n // Add methods to `SetCache`.\n SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;\n SetCache.prototype.has = setCacheHas;\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates a stack cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\n function Stack(entries) {\n var data = this.__data__ = new ListCache(entries);\n this.size = data.size;\n }\n\n /**\n * Removes all key-value entries from the stack.\n *\n * @private\n * @name clear\n * @memberOf Stack\n */\n function stackClear() {\n this.__data__ = new ListCache;\n this.size = 0;\n }\n\n /**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\n function stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n }\n\n /**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\n function stackGet(key) {\n return this.__data__.get(key);\n }\n\n /**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\n function stackHas(key) {\n return this.__data__.has(key);\n }\n\n /**\n * Sets the stack `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Stack\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the stack cache instance.\n */\n function stackSet(key, value) {\n var data = this.__data__;\n if (data instanceof ListCache) {\n var pairs = data.__data__;\n if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {\n pairs.push([key, value]);\n this.size = ++data.size;\n return this;\n }\n data = this.__data__ = new MapCache(pairs);\n }\n data.set(key, value);\n this.size = data.size;\n return this;\n }\n\n // Add methods to `Stack`.\n Stack.prototype.clear = stackClear;\n Stack.prototype['delete'] = stackDelete;\n Stack.prototype.get = stackGet;\n Stack.prototype.has = stackHas;\n Stack.prototype.set = stackSet;\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates an array of the enumerable property names of the array-like `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @param {boolean} inherited Specify returning inherited property names.\n * @returns {Array} Returns the array of property names.\n */\n function arrayLikeKeys(value, inherited) {\n var isArr = isArray(value),\n isArg = !isArr && isArguments(value),\n isBuff = !isArr && !isArg && isBuffer(value),\n isType = !isArr && !isArg && !isBuff && isTypedArray(value),\n skipIndexes = isArr || isArg || isBuff || isType,\n result = skipIndexes ? baseTimes(value.length, String) : [],\n length = result.length;\n\n for (var key in value) {\n if ((inherited || hasOwnProperty.call(value, key)) &&\n !(skipIndexes && (\n // Safari 9 has enumerable `arguments.length` in strict mode.\n key == 'length' ||\n // Node.js 0.10 has enumerable non-index properties on buffers.\n (isBuff && (key == 'offset' || key == 'parent')) ||\n // PhantomJS 2 has enumerable non-index properties on typed arrays.\n (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||\n // Skip index properties.\n isIndex(key, length)\n ))) {\n result.push(key);\n }\n }\n return result;\n }\n\n /**\n * A specialized version of `_.sample` for arrays.\n *\n * @private\n * @param {Array} array The array to sample.\n * @returns {*} Returns the random element.\n */\n function arraySample(array) {\n var length = array.length;\n return length ? array[baseRandom(0, length - 1)] : undefined;\n }\n\n /**\n * A specialized version of `_.sampleSize` for arrays.\n *\n * @private\n * @param {Array} array The array to sample.\n * @param {number} n The number of elements to sample.\n * @returns {Array} Returns the random elements.\n */\n function arraySampleSize(array, n) {\n return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length));\n }\n\n /**\n * A specialized version of `_.shuffle` for arrays.\n *\n * @private\n * @param {Array} array The array to shuffle.\n * @returns {Array} Returns the new shuffled array.\n */\n function arrayShuffle(array) {\n return shuffleSelf(copyArray(array));\n }\n\n /**\n * This function is like `assignValue` except that it doesn't assign\n * `undefined` values.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\n function assignMergeValue(object, key, value) {\n if ((value !== undefined && !eq(object[key], value)) ||\n (value === undefined && !(key in object))) {\n baseAssignValue(object, key, value);\n }\n }\n\n /**\n * Assigns `value` to `key` of `object` if the existing value is not equivalent\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\n function assignValue(object, key, value) {\n var objValue = object[key];\n if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||\n (value === undefined && !(key in object))) {\n baseAssignValue(object, key, value);\n }\n }\n\n /**\n * Gets the index at which the `key` is found in `array` of key-value pairs.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} key The key to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\n function assocIndexOf(array, key) {\n var length = array.length;\n while (length--) {\n if (eq(array[length][0], key)) {\n return length;\n }\n }\n return -1;\n }\n\n /**\n * Aggregates elements of `collection` on `accumulator` with keys transformed\n * by `iteratee` and values set by `setter`.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} setter The function to set `accumulator` values.\n * @param {Function} iteratee The iteratee to transform keys.\n * @param {Object} accumulator The initial aggregated object.\n * @returns {Function} Returns `accumulator`.\n */\n function baseAggregator(collection, setter, iteratee, accumulator) {\n baseEach(collection, function(value, key, collection) {\n setter(accumulator, value, iteratee(value), collection);\n });\n return accumulator;\n }\n\n /**\n * The base implementation of `_.assign` without support for multiple sources\n * or `customizer` functions.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @returns {Object} Returns `object`.\n */\n function baseAssign(object, source) {\n return object && copyObject(source, keys(source), object);\n }\n\n /**\n * The base implementation of `_.assignIn` without support for multiple sources\n * or `customizer` functions.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @returns {Object} Returns `object`.\n */\n function baseAssignIn(object, source) {\n return object && copyObject(source, keysIn(source), object);\n }\n\n /**\n * The base implementation of `assignValue` and `assignMergeValue` without\n * value checks.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\n function baseAssignValue(object, key, value) {\n if (key == '__proto__' && defineProperty) {\n defineProperty(object, key, {\n 'configurable': true,\n 'enumerable': true,\n 'value': value,\n 'writable': true\n });\n } else {\n object[key] = value;\n }\n }\n\n /**\n * The base implementation of `_.at` without support for individual paths.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {string[]} paths The property paths to pick.\n * @returns {Array} Returns the picked elements.\n */\n function baseAt(object, paths) {\n var index = -1,\n length = paths.length,\n result = Array(length),\n skip = object == null;\n\n while (++index < length) {\n result[index] = skip ? undefined : get(object, paths[index]);\n }\n return result;\n }\n\n /**\n * The base implementation of `_.clamp` which doesn't coerce arguments.\n *\n * @private\n * @param {number} number The number to clamp.\n * @param {number} [lower] The lower bound.\n * @param {number} upper The upper bound.\n * @returns {number} Returns the clamped number.\n */\n function baseClamp(number, lower, upper) {\n if (number === number) {\n if (upper !== undefined) {\n number = number <= upper ? number : upper;\n }\n if (lower !== undefined) {\n number = number >= lower ? number : lower;\n }\n }\n return number;\n }\n\n /**\n * The base implementation of `_.clone` and `_.cloneDeep` which tracks\n * traversed objects.\n *\n * @private\n * @param {*} value The value to clone.\n * @param {boolean} bitmask The bitmask flags.\n * 1 - Deep clone\n * 2 - Flatten inherited properties\n * 4 - Clone symbols\n * @param {Function} [customizer] The function to customize cloning.\n * @param {string} [key] The key of `value`.\n * @param {Object} [object] The parent object of `value`.\n * @param {Object} [stack] Tracks traversed objects and their clone counterparts.\n * @returns {*} Returns the cloned value.\n */\n function baseClone(value, bitmask, customizer, key, object, stack) {\n var result,\n isDeep = bitmask & CLONE_DEEP_FLAG,\n isFlat = bitmask & CLONE_FLAT_FLAG,\n isFull = bitmask & CLONE_SYMBOLS_FLAG;\n\n if (customizer) {\n result = object ? customizer(value, key, object, stack) : customizer(value);\n }\n if (result !== undefined) {\n return result;\n }\n if (!isObject(value)) {\n return value;\n }\n var isArr = isArray(value);\n if (isArr) {\n result = initCloneArray(value);\n if (!isDeep) {\n return copyArray(value, result);\n }\n } else {\n var tag = getTag(value),\n isFunc = tag == funcTag || tag == genTag;\n\n if (isBuffer(value)) {\n return cloneBuffer(value, isDeep);\n }\n if (tag == objectTag || tag == argsTag || (isFunc && !object)) {\n result = (isFlat || isFunc) ? {} : initCloneObject(value);\n if (!isDeep) {\n return isFlat\n ? copySymbolsIn(value, baseAssignIn(result, value))\n : copySymbols(value, baseAssign(result, value));\n }\n } else {\n if (!cloneableTags[tag]) {\n return object ? value : {};\n }\n result = initCloneByTag(value, tag, isDeep);\n }\n }\n // Check for circular references and return its corresponding clone.\n stack || (stack = new Stack);\n var stacked = stack.get(value);\n if (stacked) {\n return stacked;\n }\n stack.set(value, result);\n\n if (isSet(value)) {\n value.forEach(function(subValue) {\n result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));\n });\n } else if (isMap(value)) {\n value.forEach(function(subValue, key) {\n result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));\n });\n }\n\n var keysFunc = isFull\n ? (isFlat ? getAllKeysIn : getAllKeys)\n : (isFlat ? keysIn : keys);\n\n var props = isArr ? undefined : keysFunc(value);\n arrayEach(props || value, function(subValue, key) {\n if (props) {\n key = subValue;\n subValue = value[key];\n }\n // Recursively populate clone (susceptible to call stack limits).\n assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));\n });\n return result;\n }\n\n /**\n * The base implementation of `_.conforms` which doesn't clone `source`.\n *\n * @private\n * @param {Object} source The object of property predicates to conform to.\n * @returns {Function} Returns the new spec function.\n */\n function baseConforms(source) {\n var props = keys(source);\n return function(object) {\n return baseConformsTo(object, source, props);\n };\n }\n\n /**\n * The base implementation of `_.conformsTo` which accepts `props` to check.\n *\n * @private\n * @param {Object} object The object to inspect.\n * @param {Object} source The object of property predicates to conform to.\n * @returns {boolean} Returns `true` if `object` conforms, else `false`.\n */\n function baseConformsTo(object, source, props) {\n var length = props.length;\n if (object == null) {\n return !length;\n }\n object = Object(object);\n while (length--) {\n var key = props[length],\n predicate = source[key],\n value = object[key];\n\n if ((value === undefined && !(key in object)) || !predicate(value)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * The base implementation of `_.delay` and `_.defer` which accepts `args`\n * to provide to `func`.\n *\n * @private\n * @param {Function} func The function to delay.\n * @param {number} wait The number of milliseconds to delay invocation.\n * @param {Array} args The arguments to provide to `func`.\n * @returns {number|Object} Returns the timer id or timeout object.\n */\n function baseDelay(func, wait, args) {\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n return setTimeout(function() { func.apply(undefined, args); }, wait);\n }\n\n /**\n * The base implementation of methods like `_.difference` without support\n * for excluding multiple arrays or iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Array} values The values to exclude.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of filtered values.\n */\n function baseDifference(array, values, iteratee, comparator) {\n var index = -1,\n includes = arrayIncludes,\n isCommon = true,\n length = array.length,\n result = [],\n valuesLength = values.length;\n\n if (!length) {\n return result;\n }\n if (iteratee) {\n values = arrayMap(values, baseUnary(iteratee));\n }\n if (comparator) {\n includes = arrayIncludesWith;\n isCommon = false;\n }\n else if (values.length >= LARGE_ARRAY_SIZE) {\n includes = cacheHas;\n isCommon = false;\n values = new SetCache(values);\n }\n outer:\n while (++index < length) {\n var value = array[index],\n computed = iteratee == null ? value : iteratee(value);\n\n value = (comparator || value !== 0) ? value : 0;\n if (isCommon && computed === computed) {\n var valuesIndex = valuesLength;\n while (valuesIndex--) {\n if (values[valuesIndex] === computed) {\n continue outer;\n }\n }\n result.push(value);\n }\n else if (!includes(values, computed, comparator)) {\n result.push(value);\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.forEach` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array|Object} Returns `collection`.\n */\n var baseEach = createBaseEach(baseForOwn);\n\n /**\n * The base implementation of `_.forEachRight` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array|Object} Returns `collection`.\n */\n var baseEachRight = createBaseEach(baseForOwnRight, true);\n\n /**\n * The base implementation of `_.every` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if all elements pass the predicate check,\n * else `false`\n */\n function baseEvery(collection, predicate) {\n var result = true;\n baseEach(collection, function(value, index, collection) {\n result = !!predicate(value, index, collection);\n return result;\n });\n return result;\n }\n\n /**\n * The base implementation of methods like `_.max` and `_.min` which accepts a\n * `comparator` to determine the extremum value.\n *\n * @private\n * @param {Array} array The array to iterate over.\n * @param {Function} iteratee The iteratee invoked per iteration.\n * @param {Function} comparator The comparator used to compare values.\n * @returns {*} Returns the extremum value.\n */\n function baseExtremum(array, iteratee, comparator) {\n var index = -1,\n length = array.length;\n\n while (++index < length) {\n var value = array[index],\n current = iteratee(value);\n\n if (current != null && (computed === undefined\n ? (current === current && !isSymbol(current))\n : comparator(current, computed)\n )) {\n var computed = current,\n result = value;\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.fill` without an iteratee call guard.\n *\n * @private\n * @param {Array} array The array to fill.\n * @param {*} value The value to fill `array` with.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns `array`.\n */\n function baseFill(array, value, start, end) {\n var length = array.length;\n\n start = toInteger(start);\n if (start < 0) {\n start = -start > length ? 0 : (length + start);\n }\n end = (end === undefined || end > length) ? length : toInteger(end);\n if (end < 0) {\n end += length;\n }\n end = start > end ? 0 : toLength(end);\n while (start < end) {\n array[start++] = value;\n }\n return array;\n }\n\n /**\n * The base implementation of `_.filter` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\n function baseFilter(collection, predicate) {\n var result = [];\n baseEach(collection, function(value, index, collection) {\n if (predicate(value, index, collection)) {\n result.push(value);\n }\n });\n return result;\n }\n\n /**\n * The base implementation of `_.flatten` with support for restricting flattening.\n *\n * @private\n * @param {Array} array The array to flatten.\n * @param {number} depth The maximum recursion depth.\n * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.\n * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.\n * @param {Array} [result=[]] The initial result value.\n * @returns {Array} Returns the new flattened array.\n */\n function baseFlatten(array, depth, predicate, isStrict, result) {\n var index = -1,\n length = array.length;\n\n predicate || (predicate = isFlattenable);\n result || (result = []);\n\n while (++index < length) {\n var value = array[index];\n if (depth > 0 && predicate(value)) {\n if (depth > 1) {\n // Recursively flatten arrays (susceptible to call stack limits).\n baseFlatten(value, depth - 1, predicate, isStrict, result);\n } else {\n arrayPush(result, value);\n }\n } else if (!isStrict) {\n result[result.length] = value;\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `baseForOwn` which iterates over `object`\n * properties returned by `keysFunc` and invokes `iteratee` for each property.\n * Iteratee functions may exit iteration early by explicitly returning `false`.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @returns {Object} Returns `object`.\n */\n var baseFor = createBaseFor();\n\n /**\n * This function is like `baseFor` except that it iterates over properties\n * in the opposite order.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @returns {Object} Returns `object`.\n */\n var baseForRight = createBaseFor(true);\n\n /**\n * The base implementation of `_.forOwn` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Object} Returns `object`.\n */\n function baseForOwn(object, iteratee) {\n return object && baseFor(object, iteratee, keys);\n }\n\n /**\n * The base implementation of `_.forOwnRight` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Object} Returns `object`.\n */\n function baseForOwnRight(object, iteratee) {\n return object && baseForRight(object, iteratee, keys);\n }\n\n /**\n * The base implementation of `_.functions` which creates an array of\n * `object` function property names filtered from `props`.\n *\n * @private\n * @param {Object} object The object to inspect.\n * @param {Array} props The property names to filter.\n * @returns {Array} Returns the function names.\n */\n function baseFunctions(object, props) {\n return arrayFilter(props, function(key) {\n return isFunction(object[key]);\n });\n }\n\n /**\n * The base implementation of `_.get` without support for default values.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the property to get.\n * @returns {*} Returns the resolved value.\n */\n function baseGet(object, path) {\n path = castPath(path, object);\n\n var index = 0,\n length = path.length;\n\n while (object != null && index < length) {\n object = object[toKey(path[index++])];\n }\n return (index && index == length) ? object : undefined;\n }\n\n /**\n * The base implementation of `getAllKeys` and `getAllKeysIn` which uses\n * `keysFunc` and `symbolsFunc` to get the enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @param {Function} symbolsFunc The function to get the symbols of `object`.\n * @returns {Array} Returns the array of property names and symbols.\n */\n function baseGetAllKeys(object, keysFunc, symbolsFunc) {\n var result = keysFunc(object);\n return isArray(object) ? result : arrayPush(result, symbolsFunc(object));\n }\n\n /**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\n function baseGetTag(value) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return (symToStringTag && symToStringTag in Object(value))\n ? getRawTag(value)\n : objectToString(value);\n }\n\n /**\n * The base implementation of `_.gt` which doesn't coerce arguments.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if `value` is greater than `other`,\n * else `false`.\n */\n function baseGt(value, other) {\n return value > other;\n }\n\n /**\n * The base implementation of `_.has` without support for deep paths.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {Array|string} key The key to check.\n * @returns {boolean} Returns `true` if `key` exists, else `false`.\n */\n function baseHas(object, key) {\n return object != null && hasOwnProperty.call(object, key);\n }\n\n /**\n * The base implementation of `_.hasIn` without support for deep paths.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {Array|string} key The key to check.\n * @returns {boolean} Returns `true` if `key` exists, else `false`.\n */\n function baseHasIn(object, key) {\n return object != null && key in Object(object);\n }\n\n /**\n * The base implementation of `_.inRange` which doesn't coerce arguments.\n *\n * @private\n * @param {number} number The number to check.\n * @param {number} start The start of the range.\n * @param {number} end The end of the range.\n * @returns {boolean} Returns `true` if `number` is in the range, else `false`.\n */\n function baseInRange(number, start, end) {\n return number >= nativeMin(start, end) && number < nativeMax(start, end);\n }\n\n /**\n * The base implementation of methods like `_.intersection`, without support\n * for iteratee shorthands, that accepts an array of arrays to inspect.\n *\n * @private\n * @param {Array} arrays The arrays to inspect.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of shared values.\n */\n function baseIntersection(arrays, iteratee, comparator) {\n var includes = comparator ? arrayIncludesWith : arrayIncludes,\n length = arrays[0].length,\n othLength = arrays.length,\n othIndex = othLength,\n caches = Array(othLength),\n maxLength = Infinity,\n result = [];\n\n while (othIndex--) {\n var array = arrays[othIndex];\n if (othIndex && iteratee) {\n array = arrayMap(array, baseUnary(iteratee));\n }\n maxLength = nativeMin(array.length, maxLength);\n caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120))\n ? new SetCache(othIndex && array)\n : undefined;\n }\n array = arrays[0];\n\n var index = -1,\n seen = caches[0];\n\n outer:\n while (++index < length && result.length < maxLength) {\n var value = array[index],\n computed = iteratee ? iteratee(value) : value;\n\n value = (comparator || value !== 0) ? value : 0;\n if (!(seen\n ? cacheHas(seen, computed)\n : includes(result, computed, comparator)\n )) {\n othIndex = othLength;\n while (--othIndex) {\n var cache = caches[othIndex];\n if (!(cache\n ? cacheHas(cache, computed)\n : includes(arrays[othIndex], computed, comparator))\n ) {\n continue outer;\n }\n }\n if (seen) {\n seen.push(computed);\n }\n result.push(value);\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.invert` and `_.invertBy` which inverts\n * `object` with values transformed by `iteratee` and set by `setter`.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} setter The function to set `accumulator` values.\n * @param {Function} iteratee The iteratee to transform values.\n * @param {Object} accumulator The initial inverted object.\n * @returns {Function} Returns `accumulator`.\n */\n function baseInverter(object, setter, iteratee, accumulator) {\n baseForOwn(object, function(value, key, object) {\n setter(accumulator, iteratee(value), key, object);\n });\n return accumulator;\n }\n\n /**\n * The base implementation of `_.invoke` without support for individual\n * method arguments.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the method to invoke.\n * @param {Array} args The arguments to invoke the method with.\n * @returns {*} Returns the result of the invoked method.\n */\n function baseInvoke(object, path, args) {\n path = castPath(path, object);\n object = parent(object, path);\n var func = object == null ? object : object[toKey(last(path))];\n return func == null ? undefined : apply(func, object, args);\n }\n\n /**\n * The base implementation of `_.isArguments`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n */\n function baseIsArguments(value) {\n return isObjectLike(value) && baseGetTag(value) == argsTag;\n }\n\n /**\n * The base implementation of `_.isArrayBuffer` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`.\n */\n function baseIsArrayBuffer(value) {\n return isObjectLike(value) && baseGetTag(value) == arrayBufferTag;\n }\n\n /**\n * The base implementation of `_.isDate` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a date object, else `false`.\n */\n function baseIsDate(value) {\n return isObjectLike(value) && baseGetTag(value) == dateTag;\n }\n\n /**\n * The base implementation of `_.isEqual` which supports partial comparisons\n * and tracks traversed objects.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @param {boolean} bitmask The bitmask flags.\n * 1 - Unordered comparison\n * 2 - Partial comparison\n * @param {Function} [customizer] The function to customize comparisons.\n * @param {Object} [stack] Tracks traversed `value` and `other` objects.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n */\n function baseIsEqual(value, other, bitmask, customizer, stack) {\n if (value === other) {\n return true;\n }\n if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {\n return value !== value && other !== other;\n }\n return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);\n }\n\n /**\n * A specialized version of `baseIsEqual` for arrays and objects which performs\n * deep comparisons and tracks traversed objects enabling objects with circular\n * references to be compared.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} [stack] Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\n function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {\n var objIsArr = isArray(object),\n othIsArr = isArray(other),\n objTag = objIsArr ? arrayTag : getTag(object),\n othTag = othIsArr ? arrayTag : getTag(other);\n\n objTag = objTag == argsTag ? objectTag : objTag;\n othTag = othTag == argsTag ? objectTag : othTag;\n\n var objIsObj = objTag == objectTag,\n othIsObj = othTag == objectTag,\n isSameTag = objTag == othTag;\n\n if (isSameTag && isBuffer(object)) {\n if (!isBuffer(other)) {\n return false;\n }\n objIsArr = true;\n objIsObj = false;\n }\n if (isSameTag && !objIsObj) {\n stack || (stack = new Stack);\n return (objIsArr || isTypedArray(object))\n ? equalArrays(object, other, bitmask, customizer, equalFunc, stack)\n : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);\n }\n if (!(bitmask & COMPARE_PARTIAL_FLAG)) {\n var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),\n othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');\n\n if (objIsWrapped || othIsWrapped) {\n var objUnwrapped = objIsWrapped ? object.value() : object,\n othUnwrapped = othIsWrapped ? other.value() : other;\n\n stack || (stack = new Stack);\n return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);\n }\n }\n if (!isSameTag) {\n return false;\n }\n stack || (stack = new Stack);\n return equalObjects(object, other, bitmask, customizer, equalFunc, stack);\n }\n\n /**\n * The base implementation of `_.isMap` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a map, else `false`.\n */\n function baseIsMap(value) {\n return isObjectLike(value) && getTag(value) == mapTag;\n }\n\n /**\n * The base implementation of `_.isMatch` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The object to inspect.\n * @param {Object} source The object of property values to match.\n * @param {Array} matchData The property names, values, and compare flags to match.\n * @param {Function} [customizer] The function to customize comparisons.\n * @returns {boolean} Returns `true` if `object` is a match, else `false`.\n */\n function baseIsMatch(object, source, matchData, customizer) {\n var index = matchData.length,\n length = index,\n noCustomizer = !customizer;\n\n if (object == null) {\n return !length;\n }\n object = Object(object);\n while (index--) {\n var data = matchData[index];\n if ((noCustomizer && data[2])\n ? data[1] !== object[data[0]]\n : !(data[0] in object)\n ) {\n return false;\n }\n }\n while (++index < length) {\n data = matchData[index];\n var key = data[0],\n objValue = object[key],\n srcValue = data[1];\n\n if (noCustomizer && data[2]) {\n if (objValue === undefined && !(key in object)) {\n return false;\n }\n } else {\n var stack = new Stack;\n if (customizer) {\n var result = customizer(objValue, srcValue, key, object, source, stack);\n }\n if (!(result === undefined\n ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack)\n : result\n )) {\n return false;\n }\n }\n }\n return true;\n }\n\n /**\n * The base implementation of `_.isNative` without bad shim checks.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a native function,\n * else `false`.\n */\n function baseIsNative(value) {\n if (!isObject(value) || isMasked(value)) {\n return false;\n }\n var pattern = isFunction(value) ? reIsNative : reIsHostCtor;\n return pattern.test(toSource(value));\n }\n\n /**\n * The base implementation of `_.isRegExp` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a regexp, else `false`.\n */\n function baseIsRegExp(value) {\n return isObjectLike(value) && baseGetTag(value) == regexpTag;\n }\n\n /**\n * The base implementation of `_.isSet` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a set, else `false`.\n */\n function baseIsSet(value) {\n return isObjectLike(value) && getTag(value) == setTag;\n }\n\n /**\n * The base implementation of `_.isTypedArray` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n */\n function baseIsTypedArray(value) {\n return isObjectLike(value) &&\n isLength(value.length) && !!typedArrayTags[baseGetTag(value)];\n }\n\n /**\n * The base implementation of `_.iteratee`.\n *\n * @private\n * @param {*} [value=_.identity] The value to convert to an iteratee.\n * @returns {Function} Returns the iteratee.\n */\n function baseIteratee(value) {\n // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.\n // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.\n if (typeof value == 'function') {\n return value;\n }\n if (value == null) {\n return identity;\n }\n if (typeof value == 'object') {\n return isArray(value)\n ? baseMatchesProperty(value[0], value[1])\n : baseMatches(value);\n }\n return property(value);\n }\n\n /**\n * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\n function baseKeys(object) {\n if (!isPrototype(object)) {\n return nativeKeys(object);\n }\n var result = [];\n for (var key in Object(object)) {\n if (hasOwnProperty.call(object, key) && key != 'constructor') {\n result.push(key);\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\n function baseKeysIn(object) {\n if (!isObject(object)) {\n return nativeKeysIn(object);\n }\n var isProto = isPrototype(object),\n result = [];\n\n for (var key in object) {\n if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {\n result.push(key);\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.lt` which doesn't coerce arguments.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if `value` is less than `other`,\n * else `false`.\n */\n function baseLt(value, other) {\n return value < other;\n }\n\n /**\n * The base implementation of `_.map` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\n function baseMap(collection, iteratee) {\n var index = -1,\n result = isArrayLike(collection) ? Array(collection.length) : [];\n\n baseEach(collection, function(value, key, collection) {\n result[++index] = iteratee(value, key, collection);\n });\n return result;\n }\n\n /**\n * The base implementation of `_.matches` which doesn't clone `source`.\n *\n * @private\n * @param {Object} source The object of property values to match.\n * @returns {Function} Returns the new spec function.\n */\n function baseMatches(source) {\n var matchData = getMatchData(source);\n if (matchData.length == 1 && matchData[0][2]) {\n return matchesStrictComparable(matchData[0][0], matchData[0][1]);\n }\n return function(object) {\n return object === source || baseIsMatch(object, source, matchData);\n };\n }\n\n /**\n * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.\n *\n * @private\n * @param {string} path The path of the property to get.\n * @param {*} srcValue The value to match.\n * @returns {Function} Returns the new spec function.\n */\n function baseMatchesProperty(path, srcValue) {\n if (isKey(path) && isStrictComparable(srcValue)) {\n return matchesStrictComparable(toKey(path), srcValue);\n }\n return function(object) {\n var objValue = get(object, path);\n return (objValue === undefined && objValue === srcValue)\n ? hasIn(object, path)\n : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);\n };\n }\n\n /**\n * The base implementation of `_.merge` without support for multiple sources.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @param {number} srcIndex The index of `source`.\n * @param {Function} [customizer] The function to customize merged values.\n * @param {Object} [stack] Tracks traversed source values and their merged\n * counterparts.\n */\n function baseMerge(object, source, srcIndex, customizer, stack) {\n if (object === source) {\n return;\n }\n baseFor(source, function(srcValue, key) {\n stack || (stack = new Stack);\n if (isObject(srcValue)) {\n baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);\n }\n else {\n var newValue = customizer\n ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack)\n : undefined;\n\n if (newValue === undefined) {\n newValue = srcValue;\n }\n assignMergeValue(object, key, newValue);\n }\n }, keysIn);\n }\n\n /**\n * A specialized version of `baseMerge` for arrays and objects which performs\n * deep merges and tracks traversed objects enabling objects with circular\n * references to be merged.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @param {string} key The key of the value to merge.\n * @param {number} srcIndex The index of `source`.\n * @param {Function} mergeFunc The function to merge values.\n * @param {Function} [customizer] The function to customize assigned values.\n * @param {Object} [stack] Tracks traversed source values and their merged\n * counterparts.\n */\n function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {\n var objValue = safeGet(object, key),\n srcValue = safeGet(source, key),\n stacked = stack.get(srcValue);\n\n if (stacked) {\n assignMergeValue(object, key, stacked);\n return;\n }\n var newValue = customizer\n ? customizer(objValue, srcValue, (key + ''), object, source, stack)\n : undefined;\n\n var isCommon = newValue === undefined;\n\n if (isCommon) {\n var isArr = isArray(srcValue),\n isBuff = !isArr && isBuffer(srcValue),\n isTyped = !isArr && !isBuff && isTypedArray(srcValue);\n\n newValue = srcValue;\n if (isArr || isBuff || isTyped) {\n if (isArray(objValue)) {\n newValue = objValue;\n }\n else if (isArrayLikeObject(objValue)) {\n newValue = copyArray(objValue);\n }\n else if (isBuff) {\n isCommon = false;\n newValue = cloneBuffer(srcValue, true);\n }\n else if (isTyped) {\n isCommon = false;\n newValue = cloneTypedArray(srcValue, true);\n }\n else {\n newValue = [];\n }\n }\n else if (isPlainObject(srcValue) || isArguments(srcValue)) {\n newValue = objValue;\n if (isArguments(objValue)) {\n newValue = toPlainObject(objValue);\n }\n else if (!isObject(objValue) || isFunction(objValue)) {\n newValue = initCloneObject(srcValue);\n }\n }\n else {\n isCommon = false;\n }\n }\n if (isCommon) {\n // Recursively merge objects and arrays (susceptible to call stack limits).\n stack.set(srcValue, newValue);\n mergeFunc(newValue, srcValue, srcIndex, customizer, stack);\n stack['delete'](srcValue);\n }\n assignMergeValue(object, key, newValue);\n }\n\n /**\n * The base implementation of `_.nth` which doesn't coerce arguments.\n *\n * @private\n * @param {Array} array The array to query.\n * @param {number} n The index of the element to return.\n * @returns {*} Returns the nth element of `array`.\n */\n function baseNth(array, n) {\n var length = array.length;\n if (!length) {\n return;\n }\n n += n < 0 ? length : 0;\n return isIndex(n, length) ? array[n] : undefined;\n }\n\n /**\n * The base implementation of `_.orderBy` without param guards.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.\n * @param {string[]} orders The sort orders of `iteratees`.\n * @returns {Array} Returns the new sorted array.\n */\n function baseOrderBy(collection, iteratees, orders) {\n if (iteratees.length) {\n iteratees = arrayMap(iteratees, function(iteratee) {\n if (isArray(iteratee)) {\n return function(value) {\n return baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee);\n }\n }\n return iteratee;\n });\n } else {\n iteratees = [identity];\n }\n\n var index = -1;\n iteratees = arrayMap(iteratees, baseUnary(getIteratee()));\n\n var result = baseMap(collection, function(value, key, collection) {\n var criteria = arrayMap(iteratees, function(iteratee) {\n return iteratee(value);\n });\n return { 'criteria': criteria, 'index': ++index, 'value': value };\n });\n\n return baseSortBy(result, function(object, other) {\n return compareMultiple(object, other, orders);\n });\n }\n\n /**\n * The base implementation of `_.pick` without support for individual\n * property identifiers.\n *\n * @private\n * @param {Object} object The source object.\n * @param {string[]} paths The property paths to pick.\n * @returns {Object} Returns the new object.\n */\n function basePick(object, paths) {\n return basePickBy(object, paths, function(value, path) {\n return hasIn(object, path);\n });\n }\n\n /**\n * The base implementation of `_.pickBy` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The source object.\n * @param {string[]} paths The property paths to pick.\n * @param {Function} predicate The function invoked per property.\n * @returns {Object} Returns the new object.\n */\n function basePickBy(object, paths, predicate) {\n var index = -1,\n length = paths.length,\n result = {};\n\n while (++index < length) {\n var path = paths[index],\n value = baseGet(object, path);\n\n if (predicate(value, path)) {\n baseSet(result, castPath(path, object), value);\n }\n }\n return result;\n }\n\n /**\n * A specialized version of `baseProperty` which supports deep paths.\n *\n * @private\n * @param {Array|string} path The path of the property to get.\n * @returns {Function} Returns the new accessor function.\n */\n function basePropertyDeep(path) {\n return function(object) {\n return baseGet(object, path);\n };\n }\n\n /**\n * The base implementation of `_.pullAllBy` without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to remove.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns `array`.\n */\n function basePullAll(array, values, iteratee, comparator) {\n var indexOf = comparator ? baseIndexOfWith : baseIndexOf,\n index = -1,\n length = values.length,\n seen = array;\n\n if (array === values) {\n values = copyArray(values);\n }\n if (iteratee) {\n seen = arrayMap(array, baseUnary(iteratee));\n }\n while (++index < length) {\n var fromIndex = 0,\n value = values[index],\n computed = iteratee ? iteratee(value) : value;\n\n while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) {\n if (seen !== array) {\n splice.call(seen, fromIndex, 1);\n }\n splice.call(array, fromIndex, 1);\n }\n }\n return array;\n }\n\n /**\n * The base implementation of `_.pullAt` without support for individual\n * indexes or capturing the removed elements.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {number[]} indexes The indexes of elements to remove.\n * @returns {Array} Returns `array`.\n */\n function basePullAt(array, indexes) {\n var length = array ? indexes.length : 0,\n lastIndex = length - 1;\n\n while (length--) {\n var index = indexes[length];\n if (length == lastIndex || index !== previous) {\n var previous = index;\n if (isIndex(index)) {\n splice.call(array, index, 1);\n } else {\n baseUnset(array, index);\n }\n }\n }\n return array;\n }\n\n /**\n * The base implementation of `_.random` without support for returning\n * floating-point numbers.\n *\n * @private\n * @param {number} lower The lower bound.\n * @param {number} upper The upper bound.\n * @returns {number} Returns the random number.\n */\n function baseRandom(lower, upper) {\n return lower + nativeFloor(nativeRandom() * (upper - lower + 1));\n }\n\n /**\n * The base implementation of `_.range` and `_.rangeRight` which doesn't\n * coerce arguments.\n *\n * @private\n * @param {number} start The start of the range.\n * @param {number} end The end of the range.\n * @param {number} step The value to increment or decrement by.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Array} Returns the range of numbers.\n */\n function baseRange(start, end, step, fromRight) {\n var index = -1,\n length = nativeMax(nativeCeil((end - start) / (step || 1)), 0),\n result = Array(length);\n\n while (length--) {\n result[fromRight ? length : ++index] = start;\n start += step;\n }\n return result;\n }\n\n /**\n * The base implementation of `_.repeat` which doesn't coerce arguments.\n *\n * @private\n * @param {string} string The string to repeat.\n * @param {number} n The number of times to repeat the string.\n * @returns {string} Returns the repeated string.\n */\n function baseRepeat(string, n) {\n var result = '';\n if (!string || n < 1 || n > MAX_SAFE_INTEGER) {\n return result;\n }\n // Leverage the exponentiation by squaring algorithm for a faster repeat.\n // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details.\n do {\n if (n % 2) {\n result += string;\n }\n n = nativeFloor(n / 2);\n if (n) {\n string += string;\n }\n } while (n);\n\n return result;\n }\n\n /**\n * The base implementation of `_.rest` which doesn't validate or coerce arguments.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @returns {Function} Returns the new function.\n */\n function baseRest(func, start) {\n return setToString(overRest(func, start, identity), func + '');\n }\n\n /**\n * The base implementation of `_.sample`.\n *\n * @private\n * @param {Array|Object} collection The collection to sample.\n * @returns {*} Returns the random element.\n */\n function baseSample(collection) {\n return arraySample(values(collection));\n }\n\n /**\n * The base implementation of `_.sampleSize` without param guards.\n *\n * @private\n * @param {Array|Object} collection The collection to sample.\n * @param {number} n The number of elements to sample.\n * @returns {Array} Returns the random elements.\n */\n function baseSampleSize(collection, n) {\n var array = values(collection);\n return shuffleSelf(array, baseClamp(n, 0, array.length));\n }\n\n /**\n * The base implementation of `_.set`.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to set.\n * @param {*} value The value to set.\n * @param {Function} [customizer] The function to customize path creation.\n * @returns {Object} Returns `object`.\n */\n function baseSet(object, path, value, customizer) {\n if (!isObject(object)) {\n return object;\n }\n path = castPath(path, object);\n\n var index = -1,\n length = path.length,\n lastIndex = length - 1,\n nested = object;\n\n while (nested != null && ++index < length) {\n var key = toKey(path[index]),\n newValue = value;\n\n if (key === '__proto__' || key === 'constructor' || key === 'prototype') {\n return object;\n }\n\n if (index != lastIndex) {\n var objValue = nested[key];\n newValue = customizer ? customizer(objValue, key, nested) : undefined;\n if (newValue === undefined) {\n newValue = isObject(objValue)\n ? objValue\n : (isIndex(path[index + 1]) ? [] : {});\n }\n }\n assignValue(nested, key, newValue);\n nested = nested[key];\n }\n return object;\n }\n\n /**\n * The base implementation of `setData` without support for hot loop shorting.\n *\n * @private\n * @param {Function} func The function to associate metadata with.\n * @param {*} data The metadata.\n * @returns {Function} Returns `func`.\n */\n var baseSetData = !metaMap ? identity : function(func, data) {\n metaMap.set(func, data);\n return func;\n };\n\n /**\n * The base implementation of `setToString` without support for hot loop shorting.\n *\n * @private\n * @param {Function} func The function to modify.\n * @param {Function} string The `toString` result.\n * @returns {Function} Returns `func`.\n */\n var baseSetToString = !defineProperty ? identity : function(func, string) {\n return defineProperty(func, 'toString', {\n 'configurable': true,\n 'enumerable': false,\n 'value': constant(string),\n 'writable': true\n });\n };\n\n /**\n * The base implementation of `_.shuffle`.\n *\n * @private\n * @param {Array|Object} collection The collection to shuffle.\n * @returns {Array} Returns the new shuffled array.\n */\n function baseShuffle(collection) {\n return shuffleSelf(values(collection));\n }\n\n /**\n * The base implementation of `_.slice` without an iteratee call guard.\n *\n * @private\n * @param {Array} array The array to slice.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns the slice of `array`.\n */\n function baseSlice(array, start, end) {\n var index = -1,\n length = array.length;\n\n if (start < 0) {\n start = -start > length ? 0 : (length + start);\n }\n end = end > length ? length : end;\n if (end < 0) {\n end += length;\n }\n length = start > end ? 0 : ((end - start) >>> 0);\n start >>>= 0;\n\n var result = Array(length);\n while (++index < length) {\n result[index] = array[index + start];\n }\n return result;\n }\n\n /**\n * The base implementation of `_.some` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\n function baseSome(collection, predicate) {\n var result;\n\n baseEach(collection, function(value, index, collection) {\n result = predicate(value, index, collection);\n return !result;\n });\n return !!result;\n }\n\n /**\n * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which\n * performs a binary search of `array` to determine the index at which `value`\n * should be inserted into `array` in order to maintain its sort order.\n *\n * @private\n * @param {Array} array The sorted array to inspect.\n * @param {*} value The value to evaluate.\n * @param {boolean} [retHighest] Specify returning the highest qualified index.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n */\n function baseSortedIndex(array, value, retHighest) {\n var low = 0,\n high = array == null ? low : array.length;\n\n if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) {\n while (low < high) {\n var mid = (low + high) >>> 1,\n computed = array[mid];\n\n if (computed !== null && !isSymbol(computed) &&\n (retHighest ? (computed <= value) : (computed < value))) {\n low = mid + 1;\n } else {\n high = mid;\n }\n }\n return high;\n }\n return baseSortedIndexBy(array, value, identity, retHighest);\n }\n\n /**\n * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy`\n * which invokes `iteratee` for `value` and each element of `array` to compute\n * their sort ranking. The iteratee is invoked with one argument; (value).\n *\n * @private\n * @param {Array} array The sorted array to inspect.\n * @param {*} value The value to evaluate.\n * @param {Function} iteratee The iteratee invoked per element.\n * @param {boolean} [retHighest] Specify returning the highest qualified index.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n */\n function baseSortedIndexBy(array, value, iteratee, retHighest) {\n var low = 0,\n high = array == null ? 0 : array.length;\n if (high === 0) {\n return 0;\n }\n\n value = iteratee(value);\n var valIsNaN = value !== value,\n valIsNull = value === null,\n valIsSymbol = isSymbol(value),\n valIsUndefined = value === undefined;\n\n while (low < high) {\n var mid = nativeFloor((low + high) / 2),\n computed = iteratee(array[mid]),\n othIsDefined = computed !== undefined,\n othIsNull = computed === null,\n othIsReflexive = computed === computed,\n othIsSymbol = isSymbol(computed);\n\n if (valIsNaN) {\n var setLow = retHighest || othIsReflexive;\n } else if (valIsUndefined) {\n setLow = othIsReflexive && (retHighest || othIsDefined);\n } else if (valIsNull) {\n setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull);\n } else if (valIsSymbol) {\n setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol);\n } else if (othIsNull || othIsSymbol) {\n setLow = false;\n } else {\n setLow = retHighest ? (computed <= value) : (computed < value);\n }\n if (setLow) {\n low = mid + 1;\n } else {\n high = mid;\n }\n }\n return nativeMin(high, MAX_ARRAY_INDEX);\n }\n\n /**\n * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without\n * support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @returns {Array} Returns the new duplicate free array.\n */\n function baseSortedUniq(array, iteratee) {\n var index = -1,\n length = array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index],\n computed = iteratee ? iteratee(value) : value;\n\n if (!index || !eq(computed, seen)) {\n var seen = computed;\n result[resIndex++] = value === 0 ? 0 : value;\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.toNumber` which doesn't ensure correct\n * conversions of binary, hexadecimal, or octal string values.\n *\n * @private\n * @param {*} value The value to process.\n * @returns {number} Returns the number.\n */\n function baseToNumber(value) {\n if (typeof value == 'number') {\n return value;\n }\n if (isSymbol(value)) {\n return NAN;\n }\n return +value;\n }\n\n /**\n * The base implementation of `_.toString` which doesn't convert nullish\n * values to empty strings.\n *\n * @private\n * @param {*} value The value to process.\n * @returns {string} Returns the string.\n */\n function baseToString(value) {\n // Exit early for strings to avoid a performance hit in some environments.\n if (typeof value == 'string') {\n return value;\n }\n if (isArray(value)) {\n // Recursively convert values (susceptible to call stack limits).\n return arrayMap(value, baseToString) + '';\n }\n if (isSymbol(value)) {\n return symbolToString ? symbolToString.call(value) : '';\n }\n var result = (value + '');\n return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;\n }\n\n /**\n * The base implementation of `_.uniqBy` without support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new duplicate free array.\n */\n function baseUniq(array, iteratee, comparator) {\n var index = -1,\n includes = arrayIncludes,\n length = array.length,\n isCommon = true,\n result = [],\n seen = result;\n\n if (comparator) {\n isCommon = false;\n includes = arrayIncludesWith;\n }\n else if (length >= LARGE_ARRAY_SIZE) {\n var set = iteratee ? null : createSet(array);\n if (set) {\n return setToArray(set);\n }\n isCommon = false;\n includes = cacheHas;\n seen = new SetCache;\n }\n else {\n seen = iteratee ? [] : result;\n }\n outer:\n while (++index < length) {\n var value = array[index],\n computed = iteratee ? iteratee(value) : value;\n\n value = (comparator || value !== 0) ? value : 0;\n if (isCommon && computed === computed) {\n var seenIndex = seen.length;\n while (seenIndex--) {\n if (seen[seenIndex] === computed) {\n continue outer;\n }\n }\n if (iteratee) {\n seen.push(computed);\n }\n result.push(value);\n }\n else if (!includes(seen, computed, comparator)) {\n if (seen !== result) {\n seen.push(computed);\n }\n result.push(value);\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.unset`.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {Array|string} path The property path to unset.\n * @returns {boolean} Returns `true` if the property is deleted, else `false`.\n */\n function baseUnset(object, path) {\n path = castPath(path, object);\n object = parent(object, path);\n return object == null || delete object[toKey(last(path))];\n }\n\n /**\n * The base implementation of `_.update`.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to update.\n * @param {Function} updater The function to produce the updated value.\n * @param {Function} [customizer] The function to customize path creation.\n * @returns {Object} Returns `object`.\n */\n function baseUpdate(object, path, updater, customizer) {\n return baseSet(object, path, updater(baseGet(object, path)), customizer);\n }\n\n /**\n * The base implementation of methods like `_.dropWhile` and `_.takeWhile`\n * without support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to query.\n * @param {Function} predicate The function invoked per iteration.\n * @param {boolean} [isDrop] Specify dropping elements instead of taking them.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Array} Returns the slice of `array`.\n */\n function baseWhile(array, predicate, isDrop, fromRight) {\n var length = array.length,\n index = fromRight ? length : -1;\n\n while ((fromRight ? index-- : ++index < length) &&\n predicate(array[index], index, array)) {}\n\n return isDrop\n ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length))\n : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index));\n }\n\n /**\n * The base implementation of `wrapperValue` which returns the result of\n * performing a sequence of actions on the unwrapped `value`, where each\n * successive action is supplied the return value of the previous.\n *\n * @private\n * @param {*} value The unwrapped value.\n * @param {Array} actions Actions to perform to resolve the unwrapped value.\n * @returns {*} Returns the resolved value.\n */\n function baseWrapperValue(value, actions) {\n var result = value;\n if (result instanceof LazyWrapper) {\n result = result.value();\n }\n return arrayReduce(actions, function(result, action) {\n return action.func.apply(action.thisArg, arrayPush([result], action.args));\n }, result);\n }\n\n /**\n * The base implementation of methods like `_.xor`, without support for\n * iteratee shorthands, that accepts an array of arrays to inspect.\n *\n * @private\n * @param {Array} arrays The arrays to inspect.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of values.\n */\n function baseXor(arrays, iteratee, comparator) {\n var length = arrays.length;\n if (length < 2) {\n return length ? baseUniq(arrays[0]) : [];\n }\n var index = -1,\n result = Array(length);\n\n while (++index < length) {\n var array = arrays[index],\n othIndex = -1;\n\n while (++othIndex < length) {\n if (othIndex != index) {\n result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator);\n }\n }\n }\n return baseUniq(baseFlatten(result, 1), iteratee, comparator);\n }\n\n /**\n * This base implementation of `_.zipObject` which assigns values using `assignFunc`.\n *\n * @private\n * @param {Array} props The property identifiers.\n * @param {Array} values The property values.\n * @param {Function} assignFunc The function to assign values.\n * @returns {Object} Returns the new object.\n */\n function baseZipObject(props, values, assignFunc) {\n var index = -1,\n length = props.length,\n valsLength = values.length,\n result = {};\n\n while (++index < length) {\n var value = index < valsLength ? values[index] : undefined;\n assignFunc(result, props[index], value);\n }\n return result;\n }\n\n /**\n * Casts `value` to an empty array if it's not an array like object.\n *\n * @private\n * @param {*} value The value to inspect.\n * @returns {Array|Object} Returns the cast array-like object.\n */\n function castArrayLikeObject(value) {\n return isArrayLikeObject(value) ? value : [];\n }\n\n /**\n * Casts `value` to `identity` if it's not a function.\n *\n * @private\n * @param {*} value The value to inspect.\n * @returns {Function} Returns cast function.\n */\n function castFunction(value) {\n return typeof value == 'function' ? value : identity;\n }\n\n /**\n * Casts `value` to a path array if it's not one.\n *\n * @private\n * @param {*} value The value to inspect.\n * @param {Object} [object] The object to query keys on.\n * @returns {Array} Returns the cast property path array.\n */\n function castPath(value, object) {\n if (isArray(value)) {\n return value;\n }\n return isKey(value, object) ? [value] : stringToPath(toString(value));\n }\n\n /**\n * A `baseRest` alias which can be replaced with `identity` by module\n * replacement plugins.\n *\n * @private\n * @type {Function}\n * @param {Function} func The function to apply a rest parameter to.\n * @returns {Function} Returns the new function.\n */\n var castRest = baseRest;\n\n /**\n * Casts `array` to a slice if it's needed.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {number} start The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns the cast slice.\n */\n function castSlice(array, start, end) {\n var length = array.length;\n end = end === undefined ? length : end;\n return (!start && end >= length) ? array : baseSlice(array, start, end);\n }\n\n /**\n * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout).\n *\n * @private\n * @param {number|Object} id The timer id or timeout object of the timer to clear.\n */\n var clearTimeout = ctxClearTimeout || function(id) {\n return root.clearTimeout(id);\n };\n\n /**\n * Creates a clone of `buffer`.\n *\n * @private\n * @param {Buffer} buffer The buffer to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Buffer} Returns the cloned buffer.\n */\n function cloneBuffer(buffer, isDeep) {\n if (isDeep) {\n return buffer.slice();\n }\n var length = buffer.length,\n result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);\n\n buffer.copy(result);\n return result;\n }\n\n /**\n * Creates a clone of `arrayBuffer`.\n *\n * @private\n * @param {ArrayBuffer} arrayBuffer The array buffer to clone.\n * @returns {ArrayBuffer} Returns the cloned array buffer.\n */\n function cloneArrayBuffer(arrayBuffer) {\n var result = new arrayBuffer.constructor(arrayBuffer.byteLength);\n new Uint8Array(result).set(new Uint8Array(arrayBuffer));\n return result;\n }\n\n /**\n * Creates a clone of `dataView`.\n *\n * @private\n * @param {Object} dataView The data view to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the cloned data view.\n */\n function cloneDataView(dataView, isDeep) {\n var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;\n return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);\n }\n\n /**\n * Creates a clone of `regexp`.\n *\n * @private\n * @param {Object} regexp The regexp to clone.\n * @returns {Object} Returns the cloned regexp.\n */\n function cloneRegExp(regexp) {\n var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));\n result.lastIndex = regexp.lastIndex;\n return result;\n }\n\n /**\n * Creates a clone of the `symbol` object.\n *\n * @private\n * @param {Object} symbol The symbol object to clone.\n * @returns {Object} Returns the cloned symbol object.\n */\n function cloneSymbol(symbol) {\n return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};\n }\n\n /**\n * Creates a clone of `typedArray`.\n *\n * @private\n * @param {Object} typedArray The typed array to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the cloned typed array.\n */\n function cloneTypedArray(typedArray, isDeep) {\n var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;\n return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);\n }\n\n /**\n * Compares values to sort them in ascending order.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {number} Returns the sort order indicator for `value`.\n */\n function compareAscending(value, other) {\n if (value !== other) {\n var valIsDefined = value !== undefined,\n valIsNull = value === null,\n valIsReflexive = value === value,\n valIsSymbol = isSymbol(value);\n\n var othIsDefined = other !== undefined,\n othIsNull = other === null,\n othIsReflexive = other === other,\n othIsSymbol = isSymbol(other);\n\n if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) ||\n (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) ||\n (valIsNull && othIsDefined && othIsReflexive) ||\n (!valIsDefined && othIsReflexive) ||\n !valIsReflexive) {\n return 1;\n }\n if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) ||\n (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) ||\n (othIsNull && valIsDefined && valIsReflexive) ||\n (!othIsDefined && valIsReflexive) ||\n !othIsReflexive) {\n return -1;\n }\n }\n return 0;\n }\n\n /**\n * Used by `_.orderBy` to compare multiple properties of a value to another\n * and stable sort them.\n *\n * If `orders` is unspecified, all values are sorted in ascending order. Otherwise,\n * specify an order of \"desc\" for descending or \"asc\" for ascending sort order\n * of corresponding values.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {boolean[]|string[]} orders The order to sort by for each property.\n * @returns {number} Returns the sort order indicator for `object`.\n */\n function compareMultiple(object, other, orders) {\n var index = -1,\n objCriteria = object.criteria,\n othCriteria = other.criteria,\n length = objCriteria.length,\n ordersLength = orders.length;\n\n while (++index < length) {\n var result = compareAscending(objCriteria[index], othCriteria[index]);\n if (result) {\n if (index >= ordersLength) {\n return result;\n }\n var order = orders[index];\n return result * (order == 'desc' ? -1 : 1);\n }\n }\n // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications\n // that causes it, under certain circumstances, to provide the same value for\n // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247\n // for more details.\n //\n // This also ensures a stable sort in V8 and other engines.\n // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details.\n return object.index - other.index;\n }\n\n /**\n * Creates an array that is the composition of partially applied arguments,\n * placeholders, and provided arguments into a single array of arguments.\n *\n * @private\n * @param {Array} args The provided arguments.\n * @param {Array} partials The arguments to prepend to those provided.\n * @param {Array} holders The `partials` placeholder indexes.\n * @params {boolean} [isCurried] Specify composing for a curried function.\n * @returns {Array} Returns the new array of composed arguments.\n */\n function composeArgs(args, partials, holders, isCurried) {\n var argsIndex = -1,\n argsLength = args.length,\n holdersLength = holders.length,\n leftIndex = -1,\n leftLength = partials.length,\n rangeLength = nativeMax(argsLength - holdersLength, 0),\n result = Array(leftLength + rangeLength),\n isUncurried = !isCurried;\n\n while (++leftIndex < leftLength) {\n result[leftIndex] = partials[leftIndex];\n }\n while (++argsIndex < holdersLength) {\n if (isUncurried || argsIndex < argsLength) {\n result[holders[argsIndex]] = args[argsIndex];\n }\n }\n while (rangeLength--) {\n result[leftIndex++] = args[argsIndex++];\n }\n return result;\n }\n\n /**\n * This function is like `composeArgs` except that the arguments composition\n * is tailored for `_.partialRight`.\n *\n * @private\n * @param {Array} args The provided arguments.\n * @param {Array} partials The arguments to append to those provided.\n * @param {Array} holders The `partials` placeholder indexes.\n * @params {boolean} [isCurried] Specify composing for a curried function.\n * @returns {Array} Returns the new array of composed arguments.\n */\n function composeArgsRight(args, partials, holders, isCurried) {\n var argsIndex = -1,\n argsLength = args.length,\n holdersIndex = -1,\n holdersLength = holders.length,\n rightIndex = -1,\n rightLength = partials.length,\n rangeLength = nativeMax(argsLength - holdersLength, 0),\n result = Array(rangeLength + rightLength),\n isUncurried = !isCurried;\n\n while (++argsIndex < rangeLength) {\n result[argsIndex] = args[argsIndex];\n }\n var offset = argsIndex;\n while (++rightIndex < rightLength) {\n result[offset + rightIndex] = partials[rightIndex];\n }\n while (++holdersIndex < holdersLength) {\n if (isUncurried || argsIndex < argsLength) {\n result[offset + holders[holdersIndex]] = args[argsIndex++];\n }\n }\n return result;\n }\n\n /**\n * Copies the values of `source` to `array`.\n *\n * @private\n * @param {Array} source The array to copy values from.\n * @param {Array} [array=[]] The array to copy values to.\n * @returns {Array} Returns `array`.\n */\n function copyArray(source, array) {\n var index = -1,\n length = source.length;\n\n array || (array = Array(length));\n while (++index < length) {\n array[index] = source[index];\n }\n return array;\n }\n\n /**\n * Copies properties of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy properties from.\n * @param {Array} props The property identifiers to copy.\n * @param {Object} [object={}] The object to copy properties to.\n * @param {Function} [customizer] The function to customize copied values.\n * @returns {Object} Returns `object`.\n */\n function copyObject(source, props, object, customizer) {\n var isNew = !object;\n object || (object = {});\n\n var index = -1,\n length = props.length;\n\n while (++index < length) {\n var key = props[index];\n\n var newValue = customizer\n ? customizer(object[key], source[key], key, object, source)\n : undefined;\n\n if (newValue === undefined) {\n newValue = source[key];\n }\n if (isNew) {\n baseAssignValue(object, key, newValue);\n } else {\n assignValue(object, key, newValue);\n }\n }\n return object;\n }\n\n /**\n * Copies own symbols of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy symbols from.\n * @param {Object} [object={}] The object to copy symbols to.\n * @returns {Object} Returns `object`.\n */\n function copySymbols(source, object) {\n return copyObject(source, getSymbols(source), object);\n }\n\n /**\n * Copies own and inherited symbols of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy symbols from.\n * @param {Object} [object={}] The object to copy symbols to.\n * @returns {Object} Returns `object`.\n */\n function copySymbolsIn(source, object) {\n return copyObject(source, getSymbolsIn(source), object);\n }\n\n /**\n * Creates a function like `_.groupBy`.\n *\n * @private\n * @param {Function} setter The function to set accumulator values.\n * @param {Function} [initializer] The accumulator object initializer.\n * @returns {Function} Returns the new aggregator function.\n */\n function createAggregator(setter, initializer) {\n return function(collection, iteratee) {\n var func = isArray(collection) ? arrayAggregator : baseAggregator,\n accumulator = initializer ? initializer() : {};\n\n return func(collection, setter, getIteratee(iteratee, 2), accumulator);\n };\n }\n\n /**\n * Creates a function like `_.assign`.\n *\n * @private\n * @param {Function} assigner The function to assign values.\n * @returns {Function} Returns the new assigner function.\n */\n function createAssigner(assigner) {\n return baseRest(function(object, sources) {\n var index = -1,\n length = sources.length,\n customizer = length > 1 ? sources[length - 1] : undefined,\n guard = length > 2 ? sources[2] : undefined;\n\n customizer = (assigner.length > 3 && typeof customizer == 'function')\n ? (length--, customizer)\n : undefined;\n\n if (guard && isIterateeCall(sources[0], sources[1], guard)) {\n customizer = length < 3 ? undefined : customizer;\n length = 1;\n }\n object = Object(object);\n while (++index < length) {\n var source = sources[index];\n if (source) {\n assigner(object, source, index, customizer);\n }\n }\n return object;\n });\n }\n\n /**\n * Creates a `baseEach` or `baseEachRight` function.\n *\n * @private\n * @param {Function} eachFunc The function to iterate over a collection.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\n function createBaseEach(eachFunc, fromRight) {\n return function(collection, iteratee) {\n if (collection == null) {\n return collection;\n }\n if (!isArrayLike(collection)) {\n return eachFunc(collection, iteratee);\n }\n var length = collection.length,\n index = fromRight ? length : -1,\n iterable = Object(collection);\n\n while ((fromRight ? index-- : ++index < length)) {\n if (iteratee(iterable[index], index, iterable) === false) {\n break;\n }\n }\n return collection;\n };\n }\n\n /**\n * Creates a base function for methods like `_.forIn` and `_.forOwn`.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\n function createBaseFor(fromRight) {\n return function(object, iteratee, keysFunc) {\n var index = -1,\n iterable = Object(object),\n props = keysFunc(object),\n length = props.length;\n\n while (length--) {\n var key = props[fromRight ? length : ++index];\n if (iteratee(iterable[key], key, iterable) === false) {\n break;\n }\n }\n return object;\n };\n }\n\n /**\n * Creates a function that wraps `func` to invoke it with the optional `this`\n * binding of `thisArg`.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @param {*} [thisArg] The `this` binding of `func`.\n * @returns {Function} Returns the new wrapped function.\n */\n function createBind(func, bitmask, thisArg) {\n var isBind = bitmask & WRAP_BIND_FLAG,\n Ctor = createCtor(func);\n\n function wrapper() {\n var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;\n return fn.apply(isBind ? thisArg : this, arguments);\n }\n return wrapper;\n }\n\n /**\n * Creates a function like `_.lowerFirst`.\n *\n * @private\n * @param {string} methodName The name of the `String` case method to use.\n * @returns {Function} Returns the new case function.\n */\n function createCaseFirst(methodName) {\n return function(string) {\n string = toString(string);\n\n var strSymbols = hasUnicode(string)\n ? stringToArray(string)\n : undefined;\n\n var chr = strSymbols\n ? strSymbols[0]\n : string.charAt(0);\n\n var trailing = strSymbols\n ? castSlice(strSymbols, 1).join('')\n : string.slice(1);\n\n return chr[methodName]() + trailing;\n };\n }\n\n /**\n * Creates a function like `_.camelCase`.\n *\n * @private\n * @param {Function} callback The function to combine each word.\n * @returns {Function} Returns the new compounder function.\n */\n function createCompounder(callback) {\n return function(string) {\n return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');\n };\n }\n\n /**\n * Creates a function that produces an instance of `Ctor` regardless of\n * whether it was invoked as part of a `new` expression or by `call` or `apply`.\n *\n * @private\n * @param {Function} Ctor The constructor to wrap.\n * @returns {Function} Returns the new wrapped function.\n */\n function createCtor(Ctor) {\n return function() {\n // Use a `switch` statement to work with class constructors. See\n // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist\n // for more details.\n var args = arguments;\n switch (args.length) {\n case 0: return new Ctor;\n case 1: return new Ctor(args[0]);\n case 2: return new Ctor(args[0], args[1]);\n case 3: return new Ctor(args[0], args[1], args[2]);\n case 4: return new Ctor(args[0], args[1], args[2], args[3]);\n case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);\n case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);\n case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);\n }\n var thisBinding = baseCreate(Ctor.prototype),\n result = Ctor.apply(thisBinding, args);\n\n // Mimic the constructor's `return` behavior.\n // See https://es5.github.io/#x13.2.2 for more details.\n return isObject(result) ? result : thisBinding;\n };\n }\n\n /**\n * Creates a function that wraps `func` to enable currying.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @param {number} arity The arity of `func`.\n * @returns {Function} Returns the new wrapped function.\n */\n function createCurry(func, bitmask, arity) {\n var Ctor = createCtor(func);\n\n function wrapper() {\n var length = arguments.length,\n args = Array(length),\n index = length,\n placeholder = getHolder(wrapper);\n\n while (index--) {\n args[index] = arguments[index];\n }\n var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder)\n ? []\n : replaceHolders(args, placeholder);\n\n length -= holders.length;\n if (length < arity) {\n return createRecurry(\n func, bitmask, createHybrid, wrapper.placeholder, undefined,\n args, holders, undefined, undefined, arity - length);\n }\n var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;\n return apply(fn, this, args);\n }\n return wrapper;\n }\n\n /**\n * Creates a `_.find` or `_.findLast` function.\n *\n * @private\n * @param {Function} findIndexFunc The function to find the collection index.\n * @returns {Function} Returns the new find function.\n */\n function createFind(findIndexFunc) {\n return function(collection, predicate, fromIndex) {\n var iterable = Object(collection);\n if (!isArrayLike(collection)) {\n var iteratee = getIteratee(predicate, 3);\n collection = keys(collection);\n predicate = function(key) { return iteratee(iterable[key], key, iterable); };\n }\n var index = findIndexFunc(collection, predicate, fromIndex);\n return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined;\n };\n }\n\n /**\n * Creates a `_.flow` or `_.flowRight` function.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new flow function.\n */\n function createFlow(fromRight) {\n return flatRest(function(funcs) {\n var length = funcs.length,\n index = length,\n prereq = LodashWrapper.prototype.thru;\n\n if (fromRight) {\n funcs.reverse();\n }\n while (index--) {\n var func = funcs[index];\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n if (prereq && !wrapper && getFuncName(func) == 'wrapper') {\n var wrapper = new LodashWrapper([], true);\n }\n }\n index = wrapper ? index : length;\n while (++index < length) {\n func = funcs[index];\n\n var funcName = getFuncName(func),\n data = funcName == 'wrapper' ? getData(func) : undefined;\n\n if (data && isLaziable(data[0]) &&\n data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) &&\n !data[4].length && data[9] == 1\n ) {\n wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]);\n } else {\n wrapper = (func.length == 1 && isLaziable(func))\n ? wrapper[funcName]()\n : wrapper.thru(func);\n }\n }\n return function() {\n var args = arguments,\n value = args[0];\n\n if (wrapper && args.length == 1 && isArray(value)) {\n return wrapper.plant(value).value();\n }\n var index = 0,\n result = length ? funcs[index].apply(this, args) : value;\n\n while (++index < length) {\n result = funcs[index].call(this, result);\n }\n return result;\n };\n });\n }\n\n /**\n * Creates a function that wraps `func` to invoke it with optional `this`\n * binding of `thisArg`, partial application, and currying.\n *\n * @private\n * @param {Function|string} func The function or method name to wrap.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @param {*} [thisArg] The `this` binding of `func`.\n * @param {Array} [partials] The arguments to prepend to those provided to\n * the new function.\n * @param {Array} [holders] The `partials` placeholder indexes.\n * @param {Array} [partialsRight] The arguments to append to those provided\n * to the new function.\n * @param {Array} [holdersRight] The `partialsRight` placeholder indexes.\n * @param {Array} [argPos] The argument positions of the new function.\n * @param {number} [ary] The arity cap of `func`.\n * @param {number} [arity] The arity of `func`.\n * @returns {Function} Returns the new wrapped function.\n */\n function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {\n var isAry = bitmask & WRAP_ARY_FLAG,\n isBind = bitmask & WRAP_BIND_FLAG,\n isBindKey = bitmask & WRAP_BIND_KEY_FLAG,\n isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG),\n isFlip = bitmask & WRAP_FLIP_FLAG,\n Ctor = isBindKey ? undefined : createCtor(func);\n\n function wrapper() {\n var length = arguments.length,\n args = Array(length),\n index = length;\n\n while (index--) {\n args[index] = arguments[index];\n }\n if (isCurried) {\n var placeholder = getHolder(wrapper),\n holdersCount = countHolders(args, placeholder);\n }\n if (partials) {\n args = composeArgs(args, partials, holders, isCurried);\n }\n if (partialsRight) {\n args = composeArgsRight(args, partialsRight, holdersRight, isCurried);\n }\n length -= holdersCount;\n if (isCurried && length < arity) {\n var newHolders = replaceHolders(args, placeholder);\n return createRecurry(\n func, bitmask, createHybrid, wrapper.placeholder, thisArg,\n args, newHolders, argPos, ary, arity - length\n );\n }\n var thisBinding = isBind ? thisArg : this,\n fn = isBindKey ? thisBinding[func] : func;\n\n length = args.length;\n if (argPos) {\n args = reorder(args, argPos);\n } else if (isFlip && length > 1) {\n args.reverse();\n }\n if (isAry && ary < length) {\n args.length = ary;\n }\n if (this && this !== root && this instanceof wrapper) {\n fn = Ctor || createCtor(fn);\n }\n return fn.apply(thisBinding, args);\n }\n return wrapper;\n }\n\n /**\n * Creates a function like `_.invertBy`.\n *\n * @private\n * @param {Function} setter The function to set accumulator values.\n * @param {Function} toIteratee The function to resolve iteratees.\n * @returns {Function} Returns the new inverter function.\n */\n function createInverter(setter, toIteratee) {\n return function(object, iteratee) {\n return baseInverter(object, setter, toIteratee(iteratee), {});\n };\n }\n\n /**\n * Creates a function that performs a mathematical operation on two values.\n *\n * @private\n * @param {Function} operator The function to perform the operation.\n * @param {number} [defaultValue] The value used for `undefined` arguments.\n * @returns {Function} Returns the new mathematical operation function.\n */\n function createMathOperation(operator, defaultValue) {\n return function(value, other) {\n var result;\n if (value === undefined && other === undefined) {\n return defaultValue;\n }\n if (value !== undefined) {\n result = value;\n }\n if (other !== undefined) {\n if (result === undefined) {\n return other;\n }\n if (typeof value == 'string' || typeof other == 'string') {\n value = baseToString(value);\n other = baseToString(other);\n } else {\n value = baseToNumber(value);\n other = baseToNumber(other);\n }\n result = operator(value, other);\n }\n return result;\n };\n }\n\n /**\n * Creates a function like `_.over`.\n *\n * @private\n * @param {Function} arrayFunc The function to iterate over iteratees.\n * @returns {Function} Returns the new over function.\n */\n function createOver(arrayFunc) {\n return flatRest(function(iteratees) {\n iteratees = arrayMap(iteratees, baseUnary(getIteratee()));\n return baseRest(function(args) {\n var thisArg = this;\n return arrayFunc(iteratees, function(iteratee) {\n return apply(iteratee, thisArg, args);\n });\n });\n });\n }\n\n /**\n * Creates the padding for `string` based on `length`. The `chars` string\n * is truncated if the number of characters exceeds `length`.\n *\n * @private\n * @param {number} length The padding length.\n * @param {string} [chars=' '] The string used as padding.\n * @returns {string} Returns the padding for `string`.\n */\n function createPadding(length, chars) {\n chars = chars === undefined ? ' ' : baseToString(chars);\n\n var charsLength = chars.length;\n if (charsLength < 2) {\n return charsLength ? baseRepeat(chars, length) : chars;\n }\n var result = baseRepeat(chars, nativeCeil(length / stringSize(chars)));\n return hasUnicode(chars)\n ? castSlice(stringToArray(result), 0, length).join('')\n : result.slice(0, length);\n }\n\n /**\n * Creates a function that wraps `func` to invoke it with the `this` binding\n * of `thisArg` and `partials` prepended to the arguments it receives.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} partials The arguments to prepend to those provided to\n * the new function.\n * @returns {Function} Returns the new wrapped function.\n */\n function createPartial(func, bitmask, thisArg, partials) {\n var isBind = bitmask & WRAP_BIND_FLAG,\n Ctor = createCtor(func);\n\n function wrapper() {\n var argsIndex = -1,\n argsLength = arguments.length,\n leftIndex = -1,\n leftLength = partials.length,\n args = Array(leftLength + argsLength),\n fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;\n\n while (++leftIndex < leftLength) {\n args[leftIndex] = partials[leftIndex];\n }\n while (argsLength--) {\n args[leftIndex++] = arguments[++argsIndex];\n }\n return apply(fn, isBind ? thisArg : this, args);\n }\n return wrapper;\n }\n\n /**\n * Creates a `_.range` or `_.rangeRight` function.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new range function.\n */\n function createRange(fromRight) {\n return function(start, end, step) {\n if (step && typeof step != 'number' && isIterateeCall(start, end, step)) {\n end = step = undefined;\n }\n // Ensure the sign of `-0` is preserved.\n start = toFinite(start);\n if (end === undefined) {\n end = start;\n start = 0;\n } else {\n end = toFinite(end);\n }\n step = step === undefined ? (start < end ? 1 : -1) : toFinite(step);\n return baseRange(start, end, step, fromRight);\n };\n }\n\n /**\n * Creates a function that performs a relational operation on two values.\n *\n * @private\n * @param {Function} operator The function to perform the operation.\n * @returns {Function} Returns the new relational operation function.\n */\n function createRelationalOperation(operator) {\n return function(value, other) {\n if (!(typeof value == 'string' && typeof other == 'string')) {\n value = toNumber(value);\n other = toNumber(other);\n }\n return operator(value, other);\n };\n }\n\n /**\n * Creates a function that wraps `func` to continue currying.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @param {Function} wrapFunc The function to create the `func` wrapper.\n * @param {*} placeholder The placeholder value.\n * @param {*} [thisArg] The `this` binding of `func`.\n * @param {Array} [partials] The arguments to prepend to those provided to\n * the new function.\n * @param {Array} [holders] The `partials` placeholder indexes.\n * @param {Array} [argPos] The argument positions of the new function.\n * @param {number} [ary] The arity cap of `func`.\n * @param {number} [arity] The arity of `func`.\n * @returns {Function} Returns the new wrapped function.\n */\n function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) {\n var isCurry = bitmask & WRAP_CURRY_FLAG,\n newHolders = isCurry ? holders : undefined,\n newHoldersRight = isCurry ? undefined : holders,\n newPartials = isCurry ? partials : undefined,\n newPartialsRight = isCurry ? undefined : partials;\n\n bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG);\n bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG);\n\n if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) {\n bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG);\n }\n var newData = [\n func, bitmask, thisArg, newPartials, newHolders, newPartialsRight,\n newHoldersRight, argPos, ary, arity\n ];\n\n var result = wrapFunc.apply(undefined, newData);\n if (isLaziable(func)) {\n setData(result, newData);\n }\n result.placeholder = placeholder;\n return setWrapToString(result, func, bitmask);\n }\n\n /**\n * Creates a function like `_.round`.\n *\n * @private\n * @param {string} methodName The name of the `Math` method to use when rounding.\n * @returns {Function} Returns the new round function.\n */\n function createRound(methodName) {\n var func = Math[methodName];\n return function(number, precision) {\n number = toNumber(number);\n precision = precision == null ? 0 : nativeMin(toInteger(precision), 292);\n if (precision && nativeIsFinite(number)) {\n // Shift with exponential notation to avoid floating-point issues.\n // See [MDN](https://mdn.io/round#Examples) for more details.\n var pair = (toString(number) + 'e').split('e'),\n value = func(pair[0] + 'e' + (+pair[1] + precision));\n\n pair = (toString(value) + 'e').split('e');\n return +(pair[0] + 'e' + (+pair[1] - precision));\n }\n return func(number);\n };\n }\n\n /**\n * Creates a set object of `values`.\n *\n * @private\n * @param {Array} values The values to add to the set.\n * @returns {Object} Returns the new set.\n */\n var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) {\n return new Set(values);\n };\n\n /**\n * Creates a `_.toPairs` or `_.toPairsIn` function.\n *\n * @private\n * @param {Function} keysFunc The function to get the keys of a given object.\n * @returns {Function} Returns the new pairs function.\n */\n function createToPairs(keysFunc) {\n return function(object) {\n var tag = getTag(object);\n if (tag == mapTag) {\n return mapToArray(object);\n }\n if (tag == setTag) {\n return setToPairs(object);\n }\n return baseToPairs(object, keysFunc(object));\n };\n }\n\n /**\n * Creates a function that either curries or invokes `func` with optional\n * `this` binding and partially applied arguments.\n *\n * @private\n * @param {Function|string} func The function or method name to wrap.\n * @param {number} bitmask The bitmask flags.\n * 1 - `_.bind`\n * 2 - `_.bindKey`\n * 4 - `_.curry` or `_.curryRight` of a bound function\n * 8 - `_.curry`\n * 16 - `_.curryRight`\n * 32 - `_.partial`\n * 64 - `_.partialRight`\n * 128 - `_.rearg`\n * 256 - `_.ary`\n * 512 - `_.flip`\n * @param {*} [thisArg] The `this` binding of `func`.\n * @param {Array} [partials] The arguments to be partially applied.\n * @param {Array} [holders] The `partials` placeholder indexes.\n * @param {Array} [argPos] The argument positions of the new function.\n * @param {number} [ary] The arity cap of `func`.\n * @param {number} [arity] The arity of `func`.\n * @returns {Function} Returns the new wrapped function.\n */\n function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {\n var isBindKey = bitmask & WRAP_BIND_KEY_FLAG;\n if (!isBindKey && typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n var length = partials ? partials.length : 0;\n if (!length) {\n bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG);\n partials = holders = undefined;\n }\n ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0);\n arity = arity === undefined ? arity : toInteger(arity);\n length -= holders ? holders.length : 0;\n\n if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) {\n var partialsRight = partials,\n holdersRight = holders;\n\n partials = holders = undefined;\n }\n var data = isBindKey ? undefined : getData(func);\n\n var newData = [\n func, bitmask, thisArg, partials, holders, partialsRight, holdersRight,\n argPos, ary, arity\n ];\n\n if (data) {\n mergeData(newData, data);\n }\n func = newData[0];\n bitmask = newData[1];\n thisArg = newData[2];\n partials = newData[3];\n holders = newData[4];\n arity = newData[9] = newData[9] === undefined\n ? (isBindKey ? 0 : func.length)\n : nativeMax(newData[9] - length, 0);\n\n if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) {\n bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG);\n }\n if (!bitmask || bitmask == WRAP_BIND_FLAG) {\n var result = createBind(func, bitmask, thisArg);\n } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) {\n result = createCurry(func, bitmask, arity);\n } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) {\n result = createPartial(func, bitmask, thisArg, partials);\n } else {\n result = createHybrid.apply(undefined, newData);\n }\n var setter = data ? baseSetData : setData;\n return setWrapToString(setter(result, newData), func, bitmask);\n }\n\n /**\n * Used by `_.defaults` to customize its `_.assignIn` use to assign properties\n * of source objects to the destination object for all destination properties\n * that resolve to `undefined`.\n *\n * @private\n * @param {*} objValue The destination value.\n * @param {*} srcValue The source value.\n * @param {string} key The key of the property to assign.\n * @param {Object} object The parent object of `objValue`.\n * @returns {*} Returns the value to assign.\n */\n function customDefaultsAssignIn(objValue, srcValue, key, object) {\n if (objValue === undefined ||\n (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) {\n return srcValue;\n }\n return objValue;\n }\n\n /**\n * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source\n * objects into destination objects that are passed thru.\n *\n * @private\n * @param {*} objValue The destination value.\n * @param {*} srcValue The source value.\n * @param {string} key The key of the property to merge.\n * @param {Object} object The parent object of `objValue`.\n * @param {Object} source The parent object of `srcValue`.\n * @param {Object} [stack] Tracks traversed source values and their merged\n * counterparts.\n * @returns {*} Returns the value to assign.\n */\n function customDefaultsMerge(objValue, srcValue, key, object, source, stack) {\n if (isObject(objValue) && isObject(srcValue)) {\n // Recursively merge objects and arrays (susceptible to call stack limits).\n stack.set(srcValue, objValue);\n baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack);\n stack['delete'](srcValue);\n }\n return objValue;\n }\n\n /**\n * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain\n * objects.\n *\n * @private\n * @param {*} value The value to inspect.\n * @param {string} key The key of the property to inspect.\n * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`.\n */\n function customOmitClone(value) {\n return isPlainObject(value) ? undefined : value;\n }\n\n /**\n * A specialized version of `baseIsEqualDeep` for arrays with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Array} array The array to compare.\n * @param {Array} other The other array to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `array` and `other` objects.\n * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.\n */\n function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n arrLength = array.length,\n othLength = other.length;\n\n if (arrLength != othLength && !(isPartial && othLength > arrLength)) {\n return false;\n }\n // Check that cyclic values are equal.\n var arrStacked = stack.get(array);\n var othStacked = stack.get(other);\n if (arrStacked && othStacked) {\n return arrStacked == other && othStacked == array;\n }\n var index = -1,\n result = true,\n seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;\n\n stack.set(array, other);\n stack.set(other, array);\n\n // Ignore non-index properties.\n while (++index < arrLength) {\n var arrValue = array[index],\n othValue = other[index];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, arrValue, index, other, array, stack)\n : customizer(arrValue, othValue, index, array, other, stack);\n }\n if (compared !== undefined) {\n if (compared) {\n continue;\n }\n result = false;\n break;\n }\n // Recursively compare arrays (susceptible to call stack limits).\n if (seen) {\n if (!arraySome(other, function(othValue, othIndex) {\n if (!cacheHas(seen, othIndex) &&\n (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {\n return seen.push(othIndex);\n }\n })) {\n result = false;\n break;\n }\n } else if (!(\n arrValue === othValue ||\n equalFunc(arrValue, othValue, bitmask, customizer, stack)\n )) {\n result = false;\n break;\n }\n }\n stack['delete'](array);\n stack['delete'](other);\n return result;\n }\n\n /**\n * A specialized version of `baseIsEqualDeep` for comparing objects of\n * the same `toStringTag`.\n *\n * **Note:** This function only supports comparing values with tags of\n * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {string} tag The `toStringTag` of the objects to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\n function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {\n switch (tag) {\n case dataViewTag:\n if ((object.byteLength != other.byteLength) ||\n (object.byteOffset != other.byteOffset)) {\n return false;\n }\n object = object.buffer;\n other = other.buffer;\n\n case arrayBufferTag:\n if ((object.byteLength != other.byteLength) ||\n !equalFunc(new Uint8Array(object), new Uint8Array(other))) {\n return false;\n }\n return true;\n\n case boolTag:\n case dateTag:\n case numberTag:\n // Coerce booleans to `1` or `0` and dates to milliseconds.\n // Invalid dates are coerced to `NaN`.\n return eq(+object, +other);\n\n case errorTag:\n return object.name == other.name && object.message == other.message;\n\n case regexpTag:\n case stringTag:\n // Coerce regexes to strings and treat strings, primitives and objects,\n // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring\n // for more details.\n return object == (other + '');\n\n case mapTag:\n var convert = mapToArray;\n\n case setTag:\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG;\n convert || (convert = setToArray);\n\n if (object.size != other.size && !isPartial) {\n return false;\n }\n // Assume cyclic values are equal.\n var stacked = stack.get(object);\n if (stacked) {\n return stacked == other;\n }\n bitmask |= COMPARE_UNORDERED_FLAG;\n\n // Recursively compare objects (susceptible to call stack limits).\n stack.set(object, other);\n var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);\n stack['delete'](object);\n return result;\n\n case symbolTag:\n if (symbolValueOf) {\n return symbolValueOf.call(object) == symbolValueOf.call(other);\n }\n }\n return false;\n }\n\n /**\n * A specialized version of `baseIsEqualDeep` for objects with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\n function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n objProps = getAllKeys(object),\n objLength = objProps.length,\n othProps = getAllKeys(other),\n othLength = othProps.length;\n\n if (objLength != othLength && !isPartial) {\n return false;\n }\n var index = objLength;\n while (index--) {\n var key = objProps[index];\n if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {\n return false;\n }\n }\n // Check that cyclic values are equal.\n var objStacked = stack.get(object);\n var othStacked = stack.get(other);\n if (objStacked && othStacked) {\n return objStacked == other && othStacked == object;\n }\n var result = true;\n stack.set(object, other);\n stack.set(other, object);\n\n var skipCtor = isPartial;\n while (++index < objLength) {\n key = objProps[index];\n var objValue = object[key],\n othValue = other[key];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, objValue, key, other, object, stack)\n : customizer(objValue, othValue, key, object, other, stack);\n }\n // Recursively compare objects (susceptible to call stack limits).\n if (!(compared === undefined\n ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))\n : compared\n )) {\n result = false;\n break;\n }\n skipCtor || (skipCtor = key == 'constructor');\n }\n if (result && !skipCtor) {\n var objCtor = object.constructor,\n othCtor = other.constructor;\n\n // Non `Object` object instances with different constructors are not equal.\n if (objCtor != othCtor &&\n ('constructor' in object && 'constructor' in other) &&\n !(typeof objCtor == 'function' && objCtor instanceof objCtor &&\n typeof othCtor == 'function' && othCtor instanceof othCtor)) {\n result = false;\n }\n }\n stack['delete'](object);\n stack['delete'](other);\n return result;\n }\n\n /**\n * A specialized version of `baseRest` which flattens the rest array.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @returns {Function} Returns the new function.\n */\n function flatRest(func) {\n return setToString(overRest(func, undefined, flatten), func + '');\n }\n\n /**\n * Creates an array of own enumerable property names and symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\n function getAllKeys(object) {\n return baseGetAllKeys(object, keys, getSymbols);\n }\n\n /**\n * Creates an array of own and inherited enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\n function getAllKeysIn(object) {\n return baseGetAllKeys(object, keysIn, getSymbolsIn);\n }\n\n /**\n * Gets metadata for `func`.\n *\n * @private\n * @param {Function} func The function to query.\n * @returns {*} Returns the metadata for `func`.\n */\n var getData = !metaMap ? noop : function(func) {\n return metaMap.get(func);\n };\n\n /**\n * Gets the name of `func`.\n *\n * @private\n * @param {Function} func The function to query.\n * @returns {string} Returns the function name.\n */\n function getFuncName(func) {\n var result = (func.name + ''),\n array = realNames[result],\n length = hasOwnProperty.call(realNames, result) ? array.length : 0;\n\n while (length--) {\n var data = array[length],\n otherFunc = data.func;\n if (otherFunc == null || otherFunc == func) {\n return data.name;\n }\n }\n return result;\n }\n\n /**\n * Gets the argument placeholder value for `func`.\n *\n * @private\n * @param {Function} func The function to inspect.\n * @returns {*} Returns the placeholder value.\n */\n function getHolder(func) {\n var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func;\n return object.placeholder;\n }\n\n /**\n * Gets the appropriate \"iteratee\" function. If `_.iteratee` is customized,\n * this function returns the custom method, otherwise it returns `baseIteratee`.\n * If arguments are provided, the chosen function is invoked with them and\n * its result is returned.\n *\n * @private\n * @param {*} [value] The value to convert to an iteratee.\n * @param {number} [arity] The arity of the created iteratee.\n * @returns {Function} Returns the chosen function or its result.\n */\n function getIteratee() {\n var result = lodash.iteratee || iteratee;\n result = result === iteratee ? baseIteratee : result;\n return arguments.length ? result(arguments[0], arguments[1]) : result;\n }\n\n /**\n * Gets the data for `map`.\n *\n * @private\n * @param {Object} map The map to query.\n * @param {string} key The reference key.\n * @returns {*} Returns the map data.\n */\n function getMapData(map, key) {\n var data = map.__data__;\n return isKeyable(key)\n ? data[typeof key == 'string' ? 'string' : 'hash']\n : data.map;\n }\n\n /**\n * Gets the property names, values, and compare flags of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the match data of `object`.\n */\n function getMatchData(object) {\n var result = keys(object),\n length = result.length;\n\n while (length--) {\n var key = result[length],\n value = object[key];\n\n result[length] = [key, value, isStrictComparable(value)];\n }\n return result;\n }\n\n /**\n * Gets the native function at `key` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the method to get.\n * @returns {*} Returns the function if it's native, else `undefined`.\n */\n function getNative(object, key) {\n var value = getValue(object, key);\n return baseIsNative(value) ? value : undefined;\n }\n\n /**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\n function getRawTag(value) {\n var isOwn = hasOwnProperty.call(value, symToStringTag),\n tag = value[symToStringTag];\n\n try {\n value[symToStringTag] = undefined;\n var unmasked = true;\n } catch (e) {}\n\n var result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag] = tag;\n } else {\n delete value[symToStringTag];\n }\n }\n return result;\n }\n\n /**\n * Creates an array of the own enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\n var getSymbols = !nativeGetSymbols ? stubArray : function(object) {\n if (object == null) {\n return [];\n }\n object = Object(object);\n return arrayFilter(nativeGetSymbols(object), function(symbol) {\n return propertyIsEnumerable.call(object, symbol);\n });\n };\n\n /**\n * Creates an array of the own and inherited enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\n var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) {\n var result = [];\n while (object) {\n arrayPush(result, getSymbols(object));\n object = getPrototype(object);\n }\n return result;\n };\n\n /**\n * Gets the `toStringTag` of `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\n var getTag = baseGetTag;\n\n // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.\n if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||\n (Map && getTag(new Map) != mapTag) ||\n (Promise && getTag(Promise.resolve()) != promiseTag) ||\n (Set && getTag(new Set) != setTag) ||\n (WeakMap && getTag(new WeakMap) != weakMapTag)) {\n getTag = function(value) {\n var result = baseGetTag(value),\n Ctor = result == objectTag ? value.constructor : undefined,\n ctorString = Ctor ? toSource(Ctor) : '';\n\n if (ctorString) {\n switch (ctorString) {\n case dataViewCtorString: return dataViewTag;\n case mapCtorString: return mapTag;\n case promiseCtorString: return promiseTag;\n case setCtorString: return setTag;\n case weakMapCtorString: return weakMapTag;\n }\n }\n return result;\n };\n }\n\n /**\n * Gets the view, applying any `transforms` to the `start` and `end` positions.\n *\n * @private\n * @param {number} start The start of the view.\n * @param {number} end The end of the view.\n * @param {Array} transforms The transformations to apply to the view.\n * @returns {Object} Returns an object containing the `start` and `end`\n * positions of the view.\n */\n function getView(start, end, transforms) {\n var index = -1,\n length = transforms.length;\n\n while (++index < length) {\n var data = transforms[index],\n size = data.size;\n\n switch (data.type) {\n case 'drop': start += size; break;\n case 'dropRight': end -= size; break;\n case 'take': end = nativeMin(end, start + size); break;\n case 'takeRight': start = nativeMax(start, end - size); break;\n }\n }\n return { 'start': start, 'end': end };\n }\n\n /**\n * Extracts wrapper details from the `source` body comment.\n *\n * @private\n * @param {string} source The source to inspect.\n * @returns {Array} Returns the wrapper details.\n */\n function getWrapDetails(source) {\n var match = source.match(reWrapDetails);\n return match ? match[1].split(reSplitDetails) : [];\n }\n\n /**\n * Checks if `path` exists on `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array|string} path The path to check.\n * @param {Function} hasFunc The function to check properties.\n * @returns {boolean} Returns `true` if `path` exists, else `false`.\n */\n function hasPath(object, path, hasFunc) {\n path = castPath(path, object);\n\n var index = -1,\n length = path.length,\n result = false;\n\n while (++index < length) {\n var key = toKey(path[index]);\n if (!(result = object != null && hasFunc(object, key))) {\n break;\n }\n object = object[key];\n }\n if (result || ++index != length) {\n return result;\n }\n length = object == null ? 0 : object.length;\n return !!length && isLength(length) && isIndex(key, length) &&\n (isArray(object) || isArguments(object));\n }\n\n /**\n * Initializes an array clone.\n *\n * @private\n * @param {Array} array The array to clone.\n * @returns {Array} Returns the initialized clone.\n */\n function initCloneArray(array) {\n var length = array.length,\n result = new array.constructor(length);\n\n // Add properties assigned by `RegExp#exec`.\n if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {\n result.index = array.index;\n result.input = array.input;\n }\n return result;\n }\n\n /**\n * Initializes an object clone.\n *\n * @private\n * @param {Object} object The object to clone.\n * @returns {Object} Returns the initialized clone.\n */\n function initCloneObject(object) {\n return (typeof object.constructor == 'function' && !isPrototype(object))\n ? baseCreate(getPrototype(object))\n : {};\n }\n\n /**\n * Initializes an object clone based on its `toStringTag`.\n *\n * **Note:** This function only supports cloning values with tags of\n * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.\n *\n * @private\n * @param {Object} object The object to clone.\n * @param {string} tag The `toStringTag` of the object to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the initialized clone.\n */\n function initCloneByTag(object, tag, isDeep) {\n var Ctor = object.constructor;\n switch (tag) {\n case arrayBufferTag:\n return cloneArrayBuffer(object);\n\n case boolTag:\n case dateTag:\n return new Ctor(+object);\n\n case dataViewTag:\n return cloneDataView(object, isDeep);\n\n case float32Tag: case float64Tag:\n case int8Tag: case int16Tag: case int32Tag:\n case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:\n return cloneTypedArray(object, isDeep);\n\n case mapTag:\n return new Ctor;\n\n case numberTag:\n case stringTag:\n return new Ctor(object);\n\n case regexpTag:\n return cloneRegExp(object);\n\n case setTag:\n return new Ctor;\n\n case symbolTag:\n return cloneSymbol(object);\n }\n }\n\n /**\n * Inserts wrapper `details` in a comment at the top of the `source` body.\n *\n * @private\n * @param {string} source The source to modify.\n * @returns {Array} details The details to insert.\n * @returns {string} Returns the modified source.\n */\n function insertWrapDetails(source, details) {\n var length = details.length;\n if (!length) {\n return source;\n }\n var lastIndex = length - 1;\n details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex];\n details = details.join(length > 2 ? ', ' : ' ');\n return source.replace(reWrapComment, '{\\n/* [wrapped with ' + details + '] */\\n');\n }\n\n /**\n * Checks if `value` is a flattenable `arguments` object or array.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.\n */\n function isFlattenable(value) {\n return isArray(value) || isArguments(value) ||\n !!(spreadableSymbol && value && value[spreadableSymbol]);\n }\n\n /**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\n function isIndex(value, length) {\n var type = typeof value;\n length = length == null ? MAX_SAFE_INTEGER : length;\n\n return !!length &&\n (type == 'number' ||\n (type != 'symbol' && reIsUint.test(value))) &&\n (value > -1 && value % 1 == 0 && value < length);\n }\n\n /**\n * Checks if the given arguments are from an iteratee call.\n *\n * @private\n * @param {*} value The potential iteratee value argument.\n * @param {*} index The potential iteratee index or key argument.\n * @param {*} object The potential iteratee object argument.\n * @returns {boolean} Returns `true` if the arguments are from an iteratee call,\n * else `false`.\n */\n function isIterateeCall(value, index, object) {\n if (!isObject(object)) {\n return false;\n }\n var type = typeof index;\n if (type == 'number'\n ? (isArrayLike(object) && isIndex(index, object.length))\n : (type == 'string' && index in object)\n ) {\n return eq(object[index], value);\n }\n return false;\n }\n\n /**\n * Checks if `value` is a property name and not a property path.\n *\n * @private\n * @param {*} value The value to check.\n * @param {Object} [object] The object to query keys on.\n * @returns {boolean} Returns `true` if `value` is a property name, else `false`.\n */\n function isKey(value, object) {\n if (isArray(value)) {\n return false;\n }\n var type = typeof value;\n if (type == 'number' || type == 'symbol' || type == 'boolean' ||\n value == null || isSymbol(value)) {\n return true;\n }\n return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||\n (object != null && value in Object(object));\n }\n\n /**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\n function isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n }\n\n /**\n * Checks if `func` has a lazy counterpart.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` has a lazy counterpart,\n * else `false`.\n */\n function isLaziable(func) {\n var funcName = getFuncName(func),\n other = lodash[funcName];\n\n if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) {\n return false;\n }\n if (func === other) {\n return true;\n }\n var data = getData(other);\n return !!data && func === data[0];\n }\n\n /**\n * Checks if `func` has its source masked.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` is masked, else `false`.\n */\n function isMasked(func) {\n return !!maskSrcKey && (maskSrcKey in func);\n }\n\n /**\n * Checks if `func` is capable of being masked.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `func` is maskable, else `false`.\n */\n var isMaskable = coreJsData ? isFunction : stubFalse;\n\n /**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\n function isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n }\n\n /**\n * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` if suitable for strict\n * equality comparisons, else `false`.\n */\n function isStrictComparable(value) {\n return value === value && !isObject(value);\n }\n\n /**\n * A specialized version of `matchesProperty` for source values suitable\n * for strict equality comparisons, i.e. `===`.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @param {*} srcValue The value to match.\n * @returns {Function} Returns the new spec function.\n */\n function matchesStrictComparable(key, srcValue) {\n return function(object) {\n if (object == null) {\n return false;\n }\n return object[key] === srcValue &&\n (srcValue !== undefined || (key in Object(object)));\n };\n }\n\n /**\n * A specialized version of `_.memoize` which clears the memoized function's\n * cache when it exceeds `MAX_MEMOIZE_SIZE`.\n *\n * @private\n * @param {Function} func The function to have its output memoized.\n * @returns {Function} Returns the new memoized function.\n */\n function memoizeCapped(func) {\n var result = memoize(func, function(key) {\n if (cache.size === MAX_MEMOIZE_SIZE) {\n cache.clear();\n }\n return key;\n });\n\n var cache = result.cache;\n return result;\n }\n\n /**\n * Merges the function metadata of `source` into `data`.\n *\n * Merging metadata reduces the number of wrappers used to invoke a function.\n * This is possible because methods like `_.bind`, `_.curry`, and `_.partial`\n * may be applied regardless of execution order. Methods like `_.ary` and\n * `_.rearg` modify function arguments, making the order in which they are\n * executed important, preventing the merging of metadata. However, we make\n * an exception for a safe combined case where curried functions have `_.ary`\n * and or `_.rearg` applied.\n *\n * @private\n * @param {Array} data The destination metadata.\n * @param {Array} source The source metadata.\n * @returns {Array} Returns `data`.\n */\n function mergeData(data, source) {\n var bitmask = data[1],\n srcBitmask = source[1],\n newBitmask = bitmask | srcBitmask,\n isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG);\n\n var isCombo =\n ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) ||\n ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) ||\n ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG));\n\n // Exit early if metadata can't be merged.\n if (!(isCommon || isCombo)) {\n return data;\n }\n // Use source `thisArg` if available.\n if (srcBitmask & WRAP_BIND_FLAG) {\n data[2] = source[2];\n // Set when currying a bound function.\n newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG;\n }\n // Compose partial arguments.\n var value = source[3];\n if (value) {\n var partials = data[3];\n data[3] = partials ? composeArgs(partials, value, source[4]) : value;\n data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4];\n }\n // Compose partial right arguments.\n value = source[5];\n if (value) {\n partials = data[5];\n data[5] = partials ? composeArgsRight(partials, value, source[6]) : value;\n data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6];\n }\n // Use source `argPos` if available.\n value = source[7];\n if (value) {\n data[7] = value;\n }\n // Use source `ary` if it's smaller.\n if (srcBitmask & WRAP_ARY_FLAG) {\n data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);\n }\n // Use source `arity` if one is not provided.\n if (data[9] == null) {\n data[9] = source[9];\n }\n // Use source `func` and merge bitmasks.\n data[0] = source[0];\n data[1] = newBitmask;\n\n return data;\n }\n\n /**\n * This function is like\n * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * except that it includes inherited enumerable properties.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\n function nativeKeysIn(object) {\n var result = [];\n if (object != null) {\n for (var key in Object(object)) {\n result.push(key);\n }\n }\n return result;\n }\n\n /**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\n function objectToString(value) {\n return nativeObjectToString.call(value);\n }\n\n /**\n * A specialized version of `baseRest` which transforms the rest array.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @param {Function} transform The rest array transform.\n * @returns {Function} Returns the new function.\n */\n function overRest(func, start, transform) {\n start = nativeMax(start === undefined ? (func.length - 1) : start, 0);\n return function() {\n var args = arguments,\n index = -1,\n length = nativeMax(args.length - start, 0),\n array = Array(length);\n\n while (++index < length) {\n array[index] = args[start + index];\n }\n index = -1;\n var otherArgs = Array(start + 1);\n while (++index < start) {\n otherArgs[index] = args[index];\n }\n otherArgs[start] = transform(array);\n return apply(func, this, otherArgs);\n };\n }\n\n /**\n * Gets the parent value at `path` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array} path The path to get the parent value of.\n * @returns {*} Returns the parent value.\n */\n function parent(object, path) {\n return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1));\n }\n\n /**\n * Reorder `array` according to the specified indexes where the element at\n * the first index is assigned as the first element, the element at\n * the second index is assigned as the second element, and so on.\n *\n * @private\n * @param {Array} array The array to reorder.\n * @param {Array} indexes The arranged array indexes.\n * @returns {Array} Returns `array`.\n */\n function reorder(array, indexes) {\n var arrLength = array.length,\n length = nativeMin(indexes.length, arrLength),\n oldArray = copyArray(array);\n\n while (length--) {\n var index = indexes[length];\n array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined;\n }\n return array;\n }\n\n /**\n * Gets the value at `key`, unless `key` is \"__proto__\" or \"constructor\".\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\n function safeGet(object, key) {\n if (key === 'constructor' && typeof object[key] === 'function') {\n return;\n }\n\n if (key == '__proto__') {\n return;\n }\n\n return object[key];\n }\n\n /**\n * Sets metadata for `func`.\n *\n * **Note:** If this function becomes hot, i.e. is invoked a lot in a short\n * period of time, it will trip its breaker and transition to an identity\n * function to avoid garbage collection pauses in V8. See\n * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070)\n * for more details.\n *\n * @private\n * @param {Function} func The function to associate metadata with.\n * @param {*} data The metadata.\n * @returns {Function} Returns `func`.\n */\n var setData = shortOut(baseSetData);\n\n /**\n * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout).\n *\n * @private\n * @param {Function} func The function to delay.\n * @param {number} wait The number of milliseconds to delay invocation.\n * @returns {number|Object} Returns the timer id or timeout object.\n */\n var setTimeout = ctxSetTimeout || function(func, wait) {\n return root.setTimeout(func, wait);\n };\n\n /**\n * Sets the `toString` method of `func` to return `string`.\n *\n * @private\n * @param {Function} func The function to modify.\n * @param {Function} string The `toString` result.\n * @returns {Function} Returns `func`.\n */\n var setToString = shortOut(baseSetToString);\n\n /**\n * Sets the `toString` method of `wrapper` to mimic the source of `reference`\n * with wrapper details in a comment at the top of the source body.\n *\n * @private\n * @param {Function} wrapper The function to modify.\n * @param {Function} reference The reference function.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @returns {Function} Returns `wrapper`.\n */\n function setWrapToString(wrapper, reference, bitmask) {\n var source = (reference + '');\n return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask)));\n }\n\n /**\n * Creates a function that'll short out and invoke `identity` instead\n * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`\n * milliseconds.\n *\n * @private\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new shortable function.\n */\n function shortOut(func) {\n var count = 0,\n lastCalled = 0;\n\n return function() {\n var stamp = nativeNow(),\n remaining = HOT_SPAN - (stamp - lastCalled);\n\n lastCalled = stamp;\n if (remaining > 0) {\n if (++count >= HOT_COUNT) {\n return arguments[0];\n }\n } else {\n count = 0;\n }\n return func.apply(undefined, arguments);\n };\n }\n\n /**\n * A specialized version of `_.shuffle` which mutates and sets the size of `array`.\n *\n * @private\n * @param {Array} array The array to shuffle.\n * @param {number} [size=array.length] The size of `array`.\n * @returns {Array} Returns `array`.\n */\n function shuffleSelf(array, size) {\n var index = -1,\n length = array.length,\n lastIndex = length - 1;\n\n size = size === undefined ? length : size;\n while (++index < size) {\n var rand = baseRandom(index, lastIndex),\n value = array[rand];\n\n array[rand] = array[index];\n array[index] = value;\n }\n array.length = size;\n return array;\n }\n\n /**\n * Converts `string` to a property path array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the property path array.\n */\n var stringToPath = memoizeCapped(function(string) {\n var result = [];\n if (string.charCodeAt(0) === 46 /* . */) {\n result.push('');\n }\n string.replace(rePropName, function(match, number, quote, subString) {\n result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));\n });\n return result;\n });\n\n /**\n * Converts `value` to a string key if it's not a string or symbol.\n *\n * @private\n * @param {*} value The value to inspect.\n * @returns {string|symbol} Returns the key.\n */\n function toKey(value) {\n if (typeof value == 'string' || isSymbol(value)) {\n return value;\n }\n var result = (value + '');\n return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;\n }\n\n /**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\n function toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n }\n\n /**\n * Updates wrapper `details` based on `bitmask` flags.\n *\n * @private\n * @returns {Array} details The details to modify.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @returns {Array} Returns `details`.\n */\n function updateWrapDetails(details, bitmask) {\n arrayEach(wrapFlags, function(pair) {\n var value = '_.' + pair[0];\n if ((bitmask & pair[1]) && !arrayIncludes(details, value)) {\n details.push(value);\n }\n });\n return details.sort();\n }\n\n /**\n * Creates a clone of `wrapper`.\n *\n * @private\n * @param {Object} wrapper The wrapper to clone.\n * @returns {Object} Returns the cloned wrapper.\n */\n function wrapperClone(wrapper) {\n if (wrapper instanceof LazyWrapper) {\n return wrapper.clone();\n }\n var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__);\n result.__actions__ = copyArray(wrapper.__actions__);\n result.__index__ = wrapper.__index__;\n result.__values__ = wrapper.__values__;\n return result;\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates an array of elements split into groups the length of `size`.\n * If `array` can't be split evenly, the final chunk will be the remaining\n * elements.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to process.\n * @param {number} [size=1] The length of each chunk\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the new array of chunks.\n * @example\n *\n * _.chunk(['a', 'b', 'c', 'd'], 2);\n * // => [['a', 'b'], ['c', 'd']]\n *\n * _.chunk(['a', 'b', 'c', 'd'], 3);\n * // => [['a', 'b', 'c'], ['d']]\n */\n function chunk(array, size, guard) {\n if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) {\n size = 1;\n } else {\n size = nativeMax(toInteger(size), 0);\n }\n var length = array == null ? 0 : array.length;\n if (!length || size < 1) {\n return [];\n }\n var index = 0,\n resIndex = 0,\n result = Array(nativeCeil(length / size));\n\n while (index < length) {\n result[resIndex++] = baseSlice(array, index, (index += size));\n }\n return result;\n }\n\n /**\n * Creates an array with all falsey values removed. The values `false`, `null`,\n * `0`, `\"\"`, `undefined`, and `NaN` are falsey.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to compact.\n * @returns {Array} Returns the new array of filtered values.\n * @example\n *\n * _.compact([0, 1, false, 2, '', 3]);\n * // => [1, 2, 3]\n */\n function compact(array) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (value) {\n result[resIndex++] = value;\n }\n }\n return result;\n }\n\n /**\n * Creates a new array concatenating `array` with any additional arrays\n * and/or values.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to concatenate.\n * @param {...*} [values] The values to concatenate.\n * @returns {Array} Returns the new concatenated array.\n * @example\n *\n * var array = [1];\n * var other = _.concat(array, 2, [3], [[4]]);\n *\n * console.log(other);\n * // => [1, 2, 3, [4]]\n *\n * console.log(array);\n * // => [1]\n */\n function concat() {\n var length = arguments.length;\n if (!length) {\n return [];\n }\n var args = Array(length - 1),\n array = arguments[0],\n index = length;\n\n while (index--) {\n args[index - 1] = arguments[index];\n }\n return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1));\n }\n\n /**\n * Creates an array of `array` values not included in the other given arrays\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons. The order and references of result values are\n * determined by the first array.\n *\n * **Note:** Unlike `_.pullAll`, this method returns a new array.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {...Array} [values] The values to exclude.\n * @returns {Array} Returns the new array of filtered values.\n * @see _.without, _.xor\n * @example\n *\n * _.difference([2, 1], [2, 3]);\n * // => [1]\n */\n var difference = baseRest(function(array, values) {\n return isArrayLikeObject(array)\n ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true))\n : [];\n });\n\n /**\n * This method is like `_.difference` except that it accepts `iteratee` which\n * is invoked for each element of `array` and `values` to generate the criterion\n * by which they're compared. The order and references of result values are\n * determined by the first array. The iteratee is invoked with one argument:\n * (value).\n *\n * **Note:** Unlike `_.pullAllBy`, this method returns a new array.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {...Array} [values] The values to exclude.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Array} Returns the new array of filtered values.\n * @example\n *\n * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor);\n * // => [1.2]\n *\n * // The `_.property` iteratee shorthand.\n * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x');\n * // => [{ 'x': 2 }]\n */\n var differenceBy = baseRest(function(array, values) {\n var iteratee = last(values);\n if (isArrayLikeObject(iteratee)) {\n iteratee = undefined;\n }\n return isArrayLikeObject(array)\n ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2))\n : [];\n });\n\n /**\n * This method is like `_.difference` except that it accepts `comparator`\n * which is invoked to compare elements of `array` to `values`. The order and\n * references of result values are determined by the first array. The comparator\n * is invoked with two arguments: (arrVal, othVal).\n *\n * **Note:** Unlike `_.pullAllWith`, this method returns a new array.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {...Array} [values] The values to exclude.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of filtered values.\n * @example\n *\n * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];\n *\n * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual);\n * // => [{ 'x': 2, 'y': 1 }]\n */\n var differenceWith = baseRest(function(array, values) {\n var comparator = last(values);\n if (isArrayLikeObject(comparator)) {\n comparator = undefined;\n }\n return isArrayLikeObject(array)\n ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator)\n : [];\n });\n\n /**\n * Creates a slice of `array` with `n` elements dropped from the beginning.\n *\n * @static\n * @memberOf _\n * @since 0.5.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {number} [n=1] The number of elements to drop.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.drop([1, 2, 3]);\n * // => [2, 3]\n *\n * _.drop([1, 2, 3], 2);\n * // => [3]\n *\n * _.drop([1, 2, 3], 5);\n * // => []\n *\n * _.drop([1, 2, 3], 0);\n * // => [1, 2, 3]\n */\n function drop(array, n, guard) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return [];\n }\n n = (guard || n === undefined) ? 1 : toInteger(n);\n return baseSlice(array, n < 0 ? 0 : n, length);\n }\n\n /**\n * Creates a slice of `array` with `n` elements dropped from the end.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {number} [n=1] The number of elements to drop.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.dropRight([1, 2, 3]);\n * // => [1, 2]\n *\n * _.dropRight([1, 2, 3], 2);\n * // => [1]\n *\n * _.dropRight([1, 2, 3], 5);\n * // => []\n *\n * _.dropRight([1, 2, 3], 0);\n * // => [1, 2, 3]\n */\n function dropRight(array, n, guard) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return [];\n }\n n = (guard || n === undefined) ? 1 : toInteger(n);\n n = length - n;\n return baseSlice(array, 0, n < 0 ? 0 : n);\n }\n\n /**\n * Creates a slice of `array` excluding elements dropped from the end.\n * Elements are dropped until `predicate` returns falsey. The predicate is\n * invoked with three arguments: (value, index, array).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'active': true },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': false }\n * ];\n *\n * _.dropRightWhile(users, function(o) { return !o.active; });\n * // => objects for ['barney']\n *\n * // The `_.matches` iteratee shorthand.\n * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false });\n * // => objects for ['barney', 'fred']\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.dropRightWhile(users, ['active', false]);\n * // => objects for ['barney']\n *\n * // The `_.property` iteratee shorthand.\n * _.dropRightWhile(users, 'active');\n * // => objects for ['barney', 'fred', 'pebbles']\n */\n function dropRightWhile(array, predicate) {\n return (array && array.length)\n ? baseWhile(array, getIteratee(predicate, 3), true, true)\n : [];\n }\n\n /**\n * Creates a slice of `array` excluding elements dropped from the beginning.\n * Elements are dropped until `predicate` returns falsey. The predicate is\n * invoked with three arguments: (value, index, array).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'active': false },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': true }\n * ];\n *\n * _.dropWhile(users, function(o) { return !o.active; });\n * // => objects for ['pebbles']\n *\n * // The `_.matches` iteratee shorthand.\n * _.dropWhile(users, { 'user': 'barney', 'active': false });\n * // => objects for ['fred', 'pebbles']\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.dropWhile(users, ['active', false]);\n * // => objects for ['pebbles']\n *\n * // The `_.property` iteratee shorthand.\n * _.dropWhile(users, 'active');\n * // => objects for ['barney', 'fred', 'pebbles']\n */\n function dropWhile(array, predicate) {\n return (array && array.length)\n ? baseWhile(array, getIteratee(predicate, 3), true)\n : [];\n }\n\n /**\n * Fills elements of `array` with `value` from `start` up to, but not\n * including, `end`.\n *\n * **Note:** This method mutates `array`.\n *\n * @static\n * @memberOf _\n * @since 3.2.0\n * @category Array\n * @param {Array} array The array to fill.\n * @param {*} value The value to fill `array` with.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns `array`.\n * @example\n *\n * var array = [1, 2, 3];\n *\n * _.fill(array, 'a');\n * console.log(array);\n * // => ['a', 'a', 'a']\n *\n * _.fill(Array(3), 2);\n * // => [2, 2, 2]\n *\n * _.fill([4, 6, 8, 10], '*', 1, 3);\n * // => [4, '*', '*', 10]\n */\n function fill(array, value, start, end) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return [];\n }\n if (start && typeof start != 'number' && isIterateeCall(array, value, start)) {\n start = 0;\n end = length;\n }\n return baseFill(array, value, start, end);\n }\n\n /**\n * This method is like `_.find` except that it returns the index of the first\n * element `predicate` returns truthy for instead of the element itself.\n *\n * @static\n * @memberOf _\n * @since 1.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @param {number} [fromIndex=0] The index to search from.\n * @returns {number} Returns the index of the found element, else `-1`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'active': false },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': true }\n * ];\n *\n * _.findIndex(users, function(o) { return o.user == 'barney'; });\n * // => 0\n *\n * // The `_.matches` iteratee shorthand.\n * _.findIndex(users, { 'user': 'fred', 'active': false });\n * // => 1\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.findIndex(users, ['active', false]);\n * // => 0\n *\n * // The `_.property` iteratee shorthand.\n * _.findIndex(users, 'active');\n * // => 2\n */\n function findIndex(array, predicate, fromIndex) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return -1;\n }\n var index = fromIndex == null ? 0 : toInteger(fromIndex);\n if (index < 0) {\n index = nativeMax(length + index, 0);\n }\n return baseFindIndex(array, getIteratee(predicate, 3), index);\n }\n\n /**\n * This method is like `_.findIndex` except that it iterates over elements\n * of `collection` from right to left.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @param {number} [fromIndex=array.length-1] The index to search from.\n * @returns {number} Returns the index of the found element, else `-1`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'active': true },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': false }\n * ];\n *\n * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; });\n * // => 2\n *\n * // The `_.matches` iteratee shorthand.\n * _.findLastIndex(users, { 'user': 'barney', 'active': true });\n * // => 0\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.findLastIndex(users, ['active', false]);\n * // => 2\n *\n * // The `_.property` iteratee shorthand.\n * _.findLastIndex(users, 'active');\n * // => 0\n */\n function findLastIndex(array, predicate, fromIndex) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return -1;\n }\n var index = length - 1;\n if (fromIndex !== undefined) {\n index = toInteger(fromIndex);\n index = fromIndex < 0\n ? nativeMax(length + index, 0)\n : nativeMin(index, length - 1);\n }\n return baseFindIndex(array, getIteratee(predicate, 3), index, true);\n }\n\n /**\n * Flattens `array` a single level deep.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to flatten.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * _.flatten([1, [2, [3, [4]], 5]]);\n * // => [1, 2, [3, [4]], 5]\n */\n function flatten(array) {\n var length = array == null ? 0 : array.length;\n return length ? baseFlatten(array, 1) : [];\n }\n\n /**\n * Recursively flattens `array`.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to flatten.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * _.flattenDeep([1, [2, [3, [4]], 5]]);\n * // => [1, 2, 3, 4, 5]\n */\n function flattenDeep(array) {\n var length = array == null ? 0 : array.length;\n return length ? baseFlatten(array, INFINITY) : [];\n }\n\n /**\n * Recursively flatten `array` up to `depth` times.\n *\n * @static\n * @memberOf _\n * @since 4.4.0\n * @category Array\n * @param {Array} array The array to flatten.\n * @param {number} [depth=1] The maximum recursion depth.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * var array = [1, [2, [3, [4]], 5]];\n *\n * _.flattenDepth(array, 1);\n * // => [1, 2, [3, [4]], 5]\n *\n * _.flattenDepth(array, 2);\n * // => [1, 2, 3, [4], 5]\n */\n function flattenDepth(array, depth) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return [];\n }\n depth = depth === undefined ? 1 : toInteger(depth);\n return baseFlatten(array, depth);\n }\n\n /**\n * The inverse of `_.toPairs`; this method returns an object composed\n * from key-value `pairs`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} pairs The key-value pairs.\n * @returns {Object} Returns the new object.\n * @example\n *\n * _.fromPairs([['a', 1], ['b', 2]]);\n * // => { 'a': 1, 'b': 2 }\n */\n function fromPairs(pairs) {\n var index = -1,\n length = pairs == null ? 0 : pairs.length,\n result = {};\n\n while (++index < length) {\n var pair = pairs[index];\n result[pair[0]] = pair[1];\n }\n return result;\n }\n\n /**\n * Gets the first element of `array`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @alias first\n * @category Array\n * @param {Array} array The array to query.\n * @returns {*} Returns the first element of `array`.\n * @example\n *\n * _.head([1, 2, 3]);\n * // => 1\n *\n * _.head([]);\n * // => undefined\n */\n function head(array) {\n return (array && array.length) ? array[0] : undefined;\n }\n\n /**\n * Gets the index at which the first occurrence of `value` is found in `array`\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons. If `fromIndex` is negative, it's used as the\n * offset from the end of `array`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} [fromIndex=0] The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n * @example\n *\n * _.indexOf([1, 2, 1, 2], 2);\n * // => 1\n *\n * // Search from the `fromIndex`.\n * _.indexOf([1, 2, 1, 2], 2, 2);\n * // => 3\n */\n function indexOf(array, value, fromIndex) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return -1;\n }\n var index = fromIndex == null ? 0 : toInteger(fromIndex);\n if (index < 0) {\n index = nativeMax(length + index, 0);\n }\n return baseIndexOf(array, value, index);\n }\n\n /**\n * Gets all but the last element of `array`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to query.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.initial([1, 2, 3]);\n * // => [1, 2]\n */\n function initial(array) {\n var length = array == null ? 0 : array.length;\n return length ? baseSlice(array, 0, -1) : [];\n }\n\n /**\n * Creates an array of unique values that are included in all given arrays\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons. The order and references of result values are\n * determined by the first array.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @returns {Array} Returns the new array of intersecting values.\n * @example\n *\n * _.intersection([2, 1], [2, 3]);\n * // => [2]\n */\n var intersection = baseRest(function(arrays) {\n var mapped = arrayMap(arrays, castArrayLikeObject);\n return (mapped.length && mapped[0] === arrays[0])\n ? baseIntersection(mapped)\n : [];\n });\n\n /**\n * This method is like `_.intersection` except that it accepts `iteratee`\n * which is invoked for each element of each `arrays` to generate the criterion\n * by which they're compared. The order and references of result values are\n * determined by the first array. The iteratee is invoked with one argument:\n * (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Array} Returns the new array of intersecting values.\n * @example\n *\n * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor);\n * // => [2.1]\n *\n * // The `_.property` iteratee shorthand.\n * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');\n * // => [{ 'x': 1 }]\n */\n var intersectionBy = baseRest(function(arrays) {\n var iteratee = last(arrays),\n mapped = arrayMap(arrays, castArrayLikeObject);\n\n if (iteratee === last(mapped)) {\n iteratee = undefined;\n } else {\n mapped.pop();\n }\n return (mapped.length && mapped[0] === arrays[0])\n ? baseIntersection(mapped, getIteratee(iteratee, 2))\n : [];\n });\n\n /**\n * This method is like `_.intersection` except that it accepts `comparator`\n * which is invoked to compare elements of `arrays`. The order and references\n * of result values are determined by the first array. The comparator is\n * invoked with two arguments: (arrVal, othVal).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of intersecting values.\n * @example\n *\n * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];\n * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];\n *\n * _.intersectionWith(objects, others, _.isEqual);\n * // => [{ 'x': 1, 'y': 2 }]\n */\n var intersectionWith = baseRest(function(arrays) {\n var comparator = last(arrays),\n mapped = arrayMap(arrays, castArrayLikeObject);\n\n comparator = typeof comparator == 'function' ? comparator : undefined;\n if (comparator) {\n mapped.pop();\n }\n return (mapped.length && mapped[0] === arrays[0])\n ? baseIntersection(mapped, undefined, comparator)\n : [];\n });\n\n /**\n * Converts all elements in `array` into a string separated by `separator`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to convert.\n * @param {string} [separator=','] The element separator.\n * @returns {string} Returns the joined string.\n * @example\n *\n * _.join(['a', 'b', 'c'], '~');\n * // => 'a~b~c'\n */\n function join(array, separator) {\n return array == null ? '' : nativeJoin.call(array, separator);\n }\n\n /**\n * Gets the last element of `array`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to query.\n * @returns {*} Returns the last element of `array`.\n * @example\n *\n * _.last([1, 2, 3]);\n * // => 3\n */\n function last(array) {\n var length = array == null ? 0 : array.length;\n return length ? array[length - 1] : undefined;\n }\n\n /**\n * This method is like `_.indexOf` except that it iterates over elements of\n * `array` from right to left.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} [fromIndex=array.length-1] The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n * @example\n *\n * _.lastIndexOf([1, 2, 1, 2], 2);\n * // => 3\n *\n * // Search from the `fromIndex`.\n * _.lastIndexOf([1, 2, 1, 2], 2, 2);\n * // => 1\n */\n function lastIndexOf(array, value, fromIndex) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return -1;\n }\n var index = length;\n if (fromIndex !== undefined) {\n index = toInteger(fromIndex);\n index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1);\n }\n return value === value\n ? strictLastIndexOf(array, value, index)\n : baseFindIndex(array, baseIsNaN, index, true);\n }\n\n /**\n * Gets the element at index `n` of `array`. If `n` is negative, the nth\n * element from the end is returned.\n *\n * @static\n * @memberOf _\n * @since 4.11.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {number} [n=0] The index of the element to return.\n * @returns {*} Returns the nth element of `array`.\n * @example\n *\n * var array = ['a', 'b', 'c', 'd'];\n *\n * _.nth(array, 1);\n * // => 'b'\n *\n * _.nth(array, -2);\n * // => 'c';\n */\n function nth(array, n) {\n return (array && array.length) ? baseNth(array, toInteger(n)) : undefined;\n }\n\n /**\n * Removes all given values from `array` using\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove`\n * to remove elements from an array by predicate.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Array\n * @param {Array} array The array to modify.\n * @param {...*} [values] The values to remove.\n * @returns {Array} Returns `array`.\n * @example\n *\n * var array = ['a', 'b', 'c', 'a', 'b', 'c'];\n *\n * _.pull(array, 'a', 'c');\n * console.log(array);\n * // => ['b', 'b']\n */\n var pull = baseRest(pullAll);\n\n /**\n * This method is like `_.pull` except that it accepts an array of values to remove.\n *\n * **Note:** Unlike `_.difference`, this method mutates `array`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to modify.\n * @param {Array} values The values to remove.\n * @returns {Array} Returns `array`.\n * @example\n *\n * var array = ['a', 'b', 'c', 'a', 'b', 'c'];\n *\n * _.pullAll(array, ['a', 'c']);\n * console.log(array);\n * // => ['b', 'b']\n */\n function pullAll(array, values) {\n return (array && array.length && values && values.length)\n ? basePullAll(array, values)\n : array;\n }\n\n /**\n * This method is like `_.pullAll` except that it accepts `iteratee` which is\n * invoked for each element of `array` and `values` to generate the criterion\n * by which they're compared. The iteratee is invoked with one argument: (value).\n *\n * **Note:** Unlike `_.differenceBy`, this method mutates `array`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to modify.\n * @param {Array} values The values to remove.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Array} Returns `array`.\n * @example\n *\n * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }];\n *\n * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x');\n * console.log(array);\n * // => [{ 'x': 2 }]\n */\n function pullAllBy(array, values, iteratee) {\n return (array && array.length && values && values.length)\n ? basePullAll(array, values, getIteratee(iteratee, 2))\n : array;\n }\n\n /**\n * This method is like `_.pullAll` except that it accepts `comparator` which\n * is invoked to compare elements of `array` to `values`. The comparator is\n * invoked with two arguments: (arrVal, othVal).\n *\n * **Note:** Unlike `_.differenceWith`, this method mutates `array`.\n *\n * @static\n * @memberOf _\n * @since 4.6.0\n * @category Array\n * @param {Array} array The array to modify.\n * @param {Array} values The values to remove.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns `array`.\n * @example\n *\n * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }];\n *\n * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual);\n * console.log(array);\n * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }]\n */\n function pullAllWith(array, values, comparator) {\n return (array && array.length && values && values.length)\n ? basePullAll(array, values, undefined, comparator)\n : array;\n }\n\n /**\n * Removes elements from `array` corresponding to `indexes` and returns an\n * array of removed elements.\n *\n * **Note:** Unlike `_.at`, this method mutates `array`.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to modify.\n * @param {...(number|number[])} [indexes] The indexes of elements to remove.\n * @returns {Array} Returns the new array of removed elements.\n * @example\n *\n * var array = ['a', 'b', 'c', 'd'];\n * var pulled = _.pullAt(array, [1, 3]);\n *\n * console.log(array);\n * // => ['a', 'c']\n *\n * console.log(pulled);\n * // => ['b', 'd']\n */\n var pullAt = flatRest(function(array, indexes) {\n var length = array == null ? 0 : array.length,\n result = baseAt(array, indexes);\n\n basePullAt(array, arrayMap(indexes, function(index) {\n return isIndex(index, length) ? +index : index;\n }).sort(compareAscending));\n\n return result;\n });\n\n /**\n * Removes all elements from `array` that `predicate` returns truthy for\n * and returns an array of the removed elements. The predicate is invoked\n * with three arguments: (value, index, array).\n *\n * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull`\n * to pull elements from an array by value.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Array\n * @param {Array} array The array to modify.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the new array of removed elements.\n * @example\n *\n * var array = [1, 2, 3, 4];\n * var evens = _.remove(array, function(n) {\n * return n % 2 == 0;\n * });\n *\n * console.log(array);\n * // => [1, 3]\n *\n * console.log(evens);\n * // => [2, 4]\n */\n function remove(array, predicate) {\n var result = [];\n if (!(array && array.length)) {\n return result;\n }\n var index = -1,\n indexes = [],\n length = array.length;\n\n predicate = getIteratee(predicate, 3);\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result.push(value);\n indexes.push(index);\n }\n }\n basePullAt(array, indexes);\n return result;\n }\n\n /**\n * Reverses `array` so that the first element becomes the last, the second\n * element becomes the second to last, and so on.\n *\n * **Note:** This method mutates `array` and is based on\n * [`Array#reverse`](https://mdn.io/Array/reverse).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to modify.\n * @returns {Array} Returns `array`.\n * @example\n *\n * var array = [1, 2, 3];\n *\n * _.reverse(array);\n * // => [3, 2, 1]\n *\n * console.log(array);\n * // => [3, 2, 1]\n */\n function reverse(array) {\n return array == null ? array : nativeReverse.call(array);\n }\n\n /**\n * Creates a slice of `array` from `start` up to, but not including, `end`.\n *\n * **Note:** This method is used instead of\n * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are\n * returned.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to slice.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns the slice of `array`.\n */\n function slice(array, start, end) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return [];\n }\n if (end && typeof end != 'number' && isIterateeCall(array, start, end)) {\n start = 0;\n end = length;\n }\n else {\n start = start == null ? 0 : toInteger(start);\n end = end === undefined ? length : toInteger(end);\n }\n return baseSlice(array, start, end);\n }\n\n /**\n * Uses a binary search to determine the lowest index at which `value`\n * should be inserted into `array` in order to maintain its sort order.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The sorted array to inspect.\n * @param {*} value The value to evaluate.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n * @example\n *\n * _.sortedIndex([30, 50], 40);\n * // => 1\n */\n function sortedIndex(array, value) {\n return baseSortedIndex(array, value);\n }\n\n /**\n * This method is like `_.sortedIndex` except that it accepts `iteratee`\n * which is invoked for `value` and each element of `array` to compute their\n * sort ranking. The iteratee is invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The sorted array to inspect.\n * @param {*} value The value to evaluate.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n * @example\n *\n * var objects = [{ 'x': 4 }, { 'x': 5 }];\n *\n * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });\n * // => 0\n *\n * // The `_.property` iteratee shorthand.\n * _.sortedIndexBy(objects, { 'x': 4 }, 'x');\n * // => 0\n */\n function sortedIndexBy(array, value, iteratee) {\n return baseSortedIndexBy(array, value, getIteratee(iteratee, 2));\n }\n\n /**\n * This method is like `_.indexOf` except that it performs a binary\n * search on a sorted `array`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n * @example\n *\n * _.sortedIndexOf([4, 5, 5, 5, 6], 5);\n * // => 1\n */\n function sortedIndexOf(array, value) {\n var length = array == null ? 0 : array.length;\n if (length) {\n var index = baseSortedIndex(array, value);\n if (index < length && eq(array[index], value)) {\n return index;\n }\n }\n return -1;\n }\n\n /**\n * This method is like `_.sortedIndex` except that it returns the highest\n * index at which `value` should be inserted into `array` in order to\n * maintain its sort order.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The sorted array to inspect.\n * @param {*} value The value to evaluate.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n * @example\n *\n * _.sortedLastIndex([4, 5, 5, 5, 6], 5);\n * // => 4\n */\n function sortedLastIndex(array, value) {\n return baseSortedIndex(array, value, true);\n }\n\n /**\n * This method is like `_.sortedLastIndex` except that it accepts `iteratee`\n * which is invoked for `value` and each element of `array` to compute their\n * sort ranking. The iteratee is invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The sorted array to inspect.\n * @param {*} value The value to evaluate.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n * @example\n *\n * var objects = [{ 'x': 4 }, { 'x': 5 }];\n *\n * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });\n * // => 1\n *\n * // The `_.property` iteratee shorthand.\n * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x');\n * // => 1\n */\n function sortedLastIndexBy(array, value, iteratee) {\n return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true);\n }\n\n /**\n * This method is like `_.lastIndexOf` except that it performs a binary\n * search on a sorted `array`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n * @example\n *\n * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5);\n * // => 3\n */\n function sortedLastIndexOf(array, value) {\n var length = array == null ? 0 : array.length;\n if (length) {\n var index = baseSortedIndex(array, value, true) - 1;\n if (eq(array[index], value)) {\n return index;\n }\n }\n return -1;\n }\n\n /**\n * This method is like `_.uniq` except that it's designed and optimized\n * for sorted arrays.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @returns {Array} Returns the new duplicate free array.\n * @example\n *\n * _.sortedUniq([1, 1, 2]);\n * // => [1, 2]\n */\n function sortedUniq(array) {\n return (array && array.length)\n ? baseSortedUniq(array)\n : [];\n }\n\n /**\n * This method is like `_.uniqBy` except that it's designed and optimized\n * for sorted arrays.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @returns {Array} Returns the new duplicate free array.\n * @example\n *\n * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor);\n * // => [1.1, 2.3]\n */\n function sortedUniqBy(array, iteratee) {\n return (array && array.length)\n ? baseSortedUniq(array, getIteratee(iteratee, 2))\n : [];\n }\n\n /**\n * Gets all but the first element of `array`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.tail([1, 2, 3]);\n * // => [2, 3]\n */\n function tail(array) {\n var length = array == null ? 0 : array.length;\n return length ? baseSlice(array, 1, length) : [];\n }\n\n /**\n * Creates a slice of `array` with `n` elements taken from the beginning.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {number} [n=1] The number of elements to take.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.take([1, 2, 3]);\n * // => [1]\n *\n * _.take([1, 2, 3], 2);\n * // => [1, 2]\n *\n * _.take([1, 2, 3], 5);\n * // => [1, 2, 3]\n *\n * _.take([1, 2, 3], 0);\n * // => []\n */\n function take(array, n, guard) {\n if (!(array && array.length)) {\n return [];\n }\n n = (guard || n === undefined) ? 1 : toInteger(n);\n return baseSlice(array, 0, n < 0 ? 0 : n);\n }\n\n /**\n * Creates a slice of `array` with `n` elements taken from the end.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {number} [n=1] The number of elements to take.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.takeRight([1, 2, 3]);\n * // => [3]\n *\n * _.takeRight([1, 2, 3], 2);\n * // => [2, 3]\n *\n * _.takeRight([1, 2, 3], 5);\n * // => [1, 2, 3]\n *\n * _.takeRight([1, 2, 3], 0);\n * // => []\n */\n function takeRight(array, n, guard) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return [];\n }\n n = (guard || n === undefined) ? 1 : toInteger(n);\n n = length - n;\n return baseSlice(array, n < 0 ? 0 : n, length);\n }\n\n /**\n * Creates a slice of `array` with elements taken from the end. Elements are\n * taken until `predicate` returns falsey. The predicate is invoked with\n * three arguments: (value, index, array).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'active': true },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': false }\n * ];\n *\n * _.takeRightWhile(users, function(o) { return !o.active; });\n * // => objects for ['fred', 'pebbles']\n *\n * // The `_.matches` iteratee shorthand.\n * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false });\n * // => objects for ['pebbles']\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.takeRightWhile(users, ['active', false]);\n * // => objects for ['fred', 'pebbles']\n *\n * // The `_.property` iteratee shorthand.\n * _.takeRightWhile(users, 'active');\n * // => []\n */\n function takeRightWhile(array, predicate) {\n return (array && array.length)\n ? baseWhile(array, getIteratee(predicate, 3), false, true)\n : [];\n }\n\n /**\n * Creates a slice of `array` with elements taken from the beginning. Elements\n * are taken until `predicate` returns falsey. The predicate is invoked with\n * three arguments: (value, index, array).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'active': false },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': true }\n * ];\n *\n * _.takeWhile(users, function(o) { return !o.active; });\n * // => objects for ['barney', 'fred']\n *\n * // The `_.matches` iteratee shorthand.\n * _.takeWhile(users, { 'user': 'barney', 'active': false });\n * // => objects for ['barney']\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.takeWhile(users, ['active', false]);\n * // => objects for ['barney', 'fred']\n *\n * // The `_.property` iteratee shorthand.\n * _.takeWhile(users, 'active');\n * // => []\n */\n function takeWhile(array, predicate) {\n return (array && array.length)\n ? baseWhile(array, getIteratee(predicate, 3))\n : [];\n }\n\n /**\n * Creates an array of unique values, in order, from all given arrays using\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @returns {Array} Returns the new array of combined values.\n * @example\n *\n * _.union([2], [1, 2]);\n * // => [2, 1]\n */\n var union = baseRest(function(arrays) {\n return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true));\n });\n\n /**\n * This method is like `_.union` except that it accepts `iteratee` which is\n * invoked for each element of each `arrays` to generate the criterion by\n * which uniqueness is computed. Result values are chosen from the first\n * array in which the value occurs. The iteratee is invoked with one argument:\n * (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Array} Returns the new array of combined values.\n * @example\n *\n * _.unionBy([2.1], [1.2, 2.3], Math.floor);\n * // => [2.1, 1.2]\n *\n * // The `_.property` iteratee shorthand.\n * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');\n * // => [{ 'x': 1 }, { 'x': 2 }]\n */\n var unionBy = baseRest(function(arrays) {\n var iteratee = last(arrays);\n if (isArrayLikeObject(iteratee)) {\n iteratee = undefined;\n }\n return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2));\n });\n\n /**\n * This method is like `_.union` except that it accepts `comparator` which\n * is invoked to compare elements of `arrays`. Result values are chosen from\n * the first array in which the value occurs. The comparator is invoked\n * with two arguments: (arrVal, othVal).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of combined values.\n * @example\n *\n * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];\n * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];\n *\n * _.unionWith(objects, others, _.isEqual);\n * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]\n */\n var unionWith = baseRest(function(arrays) {\n var comparator = last(arrays);\n comparator = typeof comparator == 'function' ? comparator : undefined;\n return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator);\n });\n\n /**\n * Creates a duplicate-free version of an array, using\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons, in which only the first occurrence of each element\n * is kept. The order of result values is determined by the order they occur\n * in the array.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @returns {Array} Returns the new duplicate free array.\n * @example\n *\n * _.uniq([2, 1, 2]);\n * // => [2, 1]\n */\n function uniq(array) {\n return (array && array.length) ? baseUniq(array) : [];\n }\n\n /**\n * This method is like `_.uniq` except that it accepts `iteratee` which is\n * invoked for each element in `array` to generate the criterion by which\n * uniqueness is computed. The order of result values is determined by the\n * order they occur in the array. The iteratee is invoked with one argument:\n * (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Array} Returns the new duplicate free array.\n * @example\n *\n * _.uniqBy([2.1, 1.2, 2.3], Math.floor);\n * // => [2.1, 1.2]\n *\n * // The `_.property` iteratee shorthand.\n * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');\n * // => [{ 'x': 1 }, { 'x': 2 }]\n */\n function uniqBy(array, iteratee) {\n return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : [];\n }\n\n /**\n * This method is like `_.uniq` except that it accepts `comparator` which\n * is invoked to compare elements of `array`. The order of result values is\n * determined by the order they occur in the array.The comparator is invoked\n * with two arguments: (arrVal, othVal).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new duplicate free array.\n * @example\n *\n * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];\n *\n * _.uniqWith(objects, _.isEqual);\n * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]\n */\n function uniqWith(array, comparator) {\n comparator = typeof comparator == 'function' ? comparator : undefined;\n return (array && array.length) ? baseUniq(array, undefined, comparator) : [];\n }\n\n /**\n * This method is like `_.zip` except that it accepts an array of grouped\n * elements and creates an array regrouping the elements to their pre-zip\n * configuration.\n *\n * @static\n * @memberOf _\n * @since 1.2.0\n * @category Array\n * @param {Array} array The array of grouped elements to process.\n * @returns {Array} Returns the new array of regrouped elements.\n * @example\n *\n * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]);\n * // => [['a', 1, true], ['b', 2, false]]\n *\n * _.unzip(zipped);\n * // => [['a', 'b'], [1, 2], [true, false]]\n */\n function unzip(array) {\n if (!(array && array.length)) {\n return [];\n }\n var length = 0;\n array = arrayFilter(array, function(group) {\n if (isArrayLikeObject(group)) {\n length = nativeMax(group.length, length);\n return true;\n }\n });\n return baseTimes(length, function(index) {\n return arrayMap(array, baseProperty(index));\n });\n }\n\n /**\n * This method is like `_.unzip` except that it accepts `iteratee` to specify\n * how regrouped values should be combined. The iteratee is invoked with the\n * elements of each group: (...group).\n *\n * @static\n * @memberOf _\n * @since 3.8.0\n * @category Array\n * @param {Array} array The array of grouped elements to process.\n * @param {Function} [iteratee=_.identity] The function to combine\n * regrouped values.\n * @returns {Array} Returns the new array of regrouped elements.\n * @example\n *\n * var zipped = _.zip([1, 2], [10, 20], [100, 200]);\n * // => [[1, 10, 100], [2, 20, 200]]\n *\n * _.unzipWith(zipped, _.add);\n * // => [3, 30, 300]\n */\n function unzipWith(array, iteratee) {\n if (!(array && array.length)) {\n return [];\n }\n var result = unzip(array);\n if (iteratee == null) {\n return result;\n }\n return arrayMap(result, function(group) {\n return apply(iteratee, undefined, group);\n });\n }\n\n /**\n * Creates an array excluding all given values using\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * **Note:** Unlike `_.pull`, this method returns a new array.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {...*} [values] The values to exclude.\n * @returns {Array} Returns the new array of filtered values.\n * @see _.difference, _.xor\n * @example\n *\n * _.without([2, 1, 2, 3], 1, 2);\n * // => [3]\n */\n var without = baseRest(function(array, values) {\n return isArrayLikeObject(array)\n ? baseDifference(array, values)\n : [];\n });\n\n /**\n * Creates an array of unique values that is the\n * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference)\n * of the given arrays. The order of result values is determined by the order\n * they occur in the arrays.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @returns {Array} Returns the new array of filtered values.\n * @see _.difference, _.without\n * @example\n *\n * _.xor([2, 1], [2, 3]);\n * // => [1, 3]\n */\n var xor = baseRest(function(arrays) {\n return baseXor(arrayFilter(arrays, isArrayLikeObject));\n });\n\n /**\n * This method is like `_.xor` except that it accepts `iteratee` which is\n * invoked for each element of each `arrays` to generate the criterion by\n * which by which they're compared. The order of result values is determined\n * by the order they occur in the arrays. The iteratee is invoked with one\n * argument: (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Array} Returns the new array of filtered values.\n * @example\n *\n * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor);\n * // => [1.2, 3.4]\n *\n * // The `_.property` iteratee shorthand.\n * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');\n * // => [{ 'x': 2 }]\n */\n var xorBy = baseRest(function(arrays) {\n var iteratee = last(arrays);\n if (isArrayLikeObject(iteratee)) {\n iteratee = undefined;\n }\n return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2));\n });\n\n /**\n * This method is like `_.xor` except that it accepts `comparator` which is\n * invoked to compare elements of `arrays`. The order of result values is\n * determined by the order they occur in the arrays. The comparator is invoked\n * with two arguments: (arrVal, othVal).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of filtered values.\n * @example\n *\n * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];\n * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];\n *\n * _.xorWith(objects, others, _.isEqual);\n * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]\n */\n var xorWith = baseRest(function(arrays) {\n var comparator = last(arrays);\n comparator = typeof comparator == 'function' ? comparator : undefined;\n return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator);\n });\n\n /**\n * Creates an array of grouped elements, the first of which contains the\n * first elements of the given arrays, the second of which contains the\n * second elements of the given arrays, and so on.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {...Array} [arrays] The arrays to process.\n * @returns {Array} Returns the new array of grouped elements.\n * @example\n *\n * _.zip(['a', 'b'], [1, 2], [true, false]);\n * // => [['a', 1, true], ['b', 2, false]]\n */\n var zip = baseRest(unzip);\n\n /**\n * This method is like `_.fromPairs` except that it accepts two arrays,\n * one of property identifiers and one of corresponding values.\n *\n * @static\n * @memberOf _\n * @since 0.4.0\n * @category Array\n * @param {Array} [props=[]] The property identifiers.\n * @param {Array} [values=[]] The property values.\n * @returns {Object} Returns the new object.\n * @example\n *\n * _.zipObject(['a', 'b'], [1, 2]);\n * // => { 'a': 1, 'b': 2 }\n */\n function zipObject(props, values) {\n return baseZipObject(props || [], values || [], assignValue);\n }\n\n /**\n * This method is like `_.zipObject` except that it supports property paths.\n *\n * @static\n * @memberOf _\n * @since 4.1.0\n * @category Array\n * @param {Array} [props=[]] The property identifiers.\n * @param {Array} [values=[]] The property values.\n * @returns {Object} Returns the new object.\n * @example\n *\n * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]);\n * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } }\n */\n function zipObjectDeep(props, values) {\n return baseZipObject(props || [], values || [], baseSet);\n }\n\n /**\n * This method is like `_.zip` except that it accepts `iteratee` to specify\n * how grouped values should be combined. The iteratee is invoked with the\n * elements of each group: (...group).\n *\n * @static\n * @memberOf _\n * @since 3.8.0\n * @category Array\n * @param {...Array} [arrays] The arrays to process.\n * @param {Function} [iteratee=_.identity] The function to combine\n * grouped values.\n * @returns {Array} Returns the new array of grouped elements.\n * @example\n *\n * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) {\n * return a + b + c;\n * });\n * // => [111, 222]\n */\n var zipWith = baseRest(function(arrays) {\n var length = arrays.length,\n iteratee = length > 1 ? arrays[length - 1] : undefined;\n\n iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined;\n return unzipWith(arrays, iteratee);\n });\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates a `lodash` wrapper instance that wraps `value` with explicit method\n * chain sequences enabled. The result of such sequences must be unwrapped\n * with `_#value`.\n *\n * @static\n * @memberOf _\n * @since 1.3.0\n * @category Seq\n * @param {*} value The value to wrap.\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36 },\n * { 'user': 'fred', 'age': 40 },\n * { 'user': 'pebbles', 'age': 1 }\n * ];\n *\n * var youngest = _\n * .chain(users)\n * .sortBy('age')\n * .map(function(o) {\n * return o.user + ' is ' + o.age;\n * })\n * .head()\n * .value();\n * // => 'pebbles is 1'\n */\n function chain(value) {\n var result = lodash(value);\n result.__chain__ = true;\n return result;\n }\n\n /**\n * This method invokes `interceptor` and returns `value`. The interceptor\n * is invoked with one argument; (value). The purpose of this method is to\n * \"tap into\" a method chain sequence in order to modify intermediate results.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Seq\n * @param {*} value The value to provide to `interceptor`.\n * @param {Function} interceptor The function to invoke.\n * @returns {*} Returns `value`.\n * @example\n *\n * _([1, 2, 3])\n * .tap(function(array) {\n * // Mutate input array.\n * array.pop();\n * })\n * .reverse()\n * .value();\n * // => [2, 1]\n */\n function tap(value, interceptor) {\n interceptor(value);\n return value;\n }\n\n /**\n * This method is like `_.tap` except that it returns the result of `interceptor`.\n * The purpose of this method is to \"pass thru\" values replacing intermediate\n * results in a method chain sequence.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Seq\n * @param {*} value The value to provide to `interceptor`.\n * @param {Function} interceptor The function to invoke.\n * @returns {*} Returns the result of `interceptor`.\n * @example\n *\n * _(' abc ')\n * .chain()\n * .trim()\n * .thru(function(value) {\n * return [value];\n * })\n * .value();\n * // => ['abc']\n */\n function thru(value, interceptor) {\n return interceptor(value);\n }\n\n /**\n * This method is the wrapper version of `_.at`.\n *\n * @name at\n * @memberOf _\n * @since 1.0.0\n * @category Seq\n * @param {...(string|string[])} [paths] The property paths to pick.\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };\n *\n * _(object).at(['a[0].b.c', 'a[1]']).value();\n * // => [3, 4]\n */\n var wrapperAt = flatRest(function(paths) {\n var length = paths.length,\n start = length ? paths[0] : 0,\n value = this.__wrapped__,\n interceptor = function(object) { return baseAt(object, paths); };\n\n if (length > 1 || this.__actions__.length ||\n !(value instanceof LazyWrapper) || !isIndex(start)) {\n return this.thru(interceptor);\n }\n value = value.slice(start, +start + (length ? 1 : 0));\n value.__actions__.push({\n 'func': thru,\n 'args': [interceptor],\n 'thisArg': undefined\n });\n return new LodashWrapper(value, this.__chain__).thru(function(array) {\n if (length && !array.length) {\n array.push(undefined);\n }\n return array;\n });\n });\n\n /**\n * Creates a `lodash` wrapper instance with explicit method chain sequences enabled.\n *\n * @name chain\n * @memberOf _\n * @since 0.1.0\n * @category Seq\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36 },\n * { 'user': 'fred', 'age': 40 }\n * ];\n *\n * // A sequence without explicit chaining.\n * _(users).head();\n * // => { 'user': 'barney', 'age': 36 }\n *\n * // A sequence with explicit chaining.\n * _(users)\n * .chain()\n * .head()\n * .pick('user')\n * .value();\n * // => { 'user': 'barney' }\n */\n function wrapperChain() {\n return chain(this);\n }\n\n /**\n * Executes the chain sequence and returns the wrapped result.\n *\n * @name commit\n * @memberOf _\n * @since 3.2.0\n * @category Seq\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * var array = [1, 2];\n * var wrapped = _(array).push(3);\n *\n * console.log(array);\n * // => [1, 2]\n *\n * wrapped = wrapped.commit();\n * console.log(array);\n * // => [1, 2, 3]\n *\n * wrapped.last();\n * // => 3\n *\n * console.log(array);\n * // => [1, 2, 3]\n */\n function wrapperCommit() {\n return new LodashWrapper(this.value(), this.__chain__);\n }\n\n /**\n * Gets the next value on a wrapped object following the\n * [iterator protocol](https://mdn.io/iteration_protocols#iterator).\n *\n * @name next\n * @memberOf _\n * @since 4.0.0\n * @category Seq\n * @returns {Object} Returns the next iterator value.\n * @example\n *\n * var wrapped = _([1, 2]);\n *\n * wrapped.next();\n * // => { 'done': false, 'value': 1 }\n *\n * wrapped.next();\n * // => { 'done': false, 'value': 2 }\n *\n * wrapped.next();\n * // => { 'done': true, 'value': undefined }\n */\n function wrapperNext() {\n if (this.__values__ === undefined) {\n this.__values__ = toArray(this.value());\n }\n var done = this.__index__ >= this.__values__.length,\n value = done ? undefined : this.__values__[this.__index__++];\n\n return { 'done': done, 'value': value };\n }\n\n /**\n * Enables the wrapper to be iterable.\n *\n * @name Symbol.iterator\n * @memberOf _\n * @since 4.0.0\n * @category Seq\n * @returns {Object} Returns the wrapper object.\n * @example\n *\n * var wrapped = _([1, 2]);\n *\n * wrapped[Symbol.iterator]() === wrapped;\n * // => true\n *\n * Array.from(wrapped);\n * // => [1, 2]\n */\n function wrapperToIterator() {\n return this;\n }\n\n /**\n * Creates a clone of the chain sequence planting `value` as the wrapped value.\n *\n * @name plant\n * @memberOf _\n * @since 3.2.0\n * @category Seq\n * @param {*} value The value to plant.\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * function square(n) {\n * return n * n;\n * }\n *\n * var wrapped = _([1, 2]).map(square);\n * var other = wrapped.plant([3, 4]);\n *\n * other.value();\n * // => [9, 16]\n *\n * wrapped.value();\n * // => [1, 4]\n */\n function wrapperPlant(value) {\n var result,\n parent = this;\n\n while (parent instanceof baseLodash) {\n var clone = wrapperClone(parent);\n clone.__index__ = 0;\n clone.__values__ = undefined;\n if (result) {\n previous.__wrapped__ = clone;\n } else {\n result = clone;\n }\n var previous = clone;\n parent = parent.__wrapped__;\n }\n previous.__wrapped__ = value;\n return result;\n }\n\n /**\n * This method is the wrapper version of `_.reverse`.\n *\n * **Note:** This method mutates the wrapped array.\n *\n * @name reverse\n * @memberOf _\n * @since 0.1.0\n * @category Seq\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * var array = [1, 2, 3];\n *\n * _(array).reverse().value()\n * // => [3, 2, 1]\n *\n * console.log(array);\n * // => [3, 2, 1]\n */\n function wrapperReverse() {\n var value = this.__wrapped__;\n if (value instanceof LazyWrapper) {\n var wrapped = value;\n if (this.__actions__.length) {\n wrapped = new LazyWrapper(this);\n }\n wrapped = wrapped.reverse();\n wrapped.__actions__.push({\n 'func': thru,\n 'args': [reverse],\n 'thisArg': undefined\n });\n return new LodashWrapper(wrapped, this.__chain__);\n }\n return this.thru(reverse);\n }\n\n /**\n * Executes the chain sequence to resolve the unwrapped value.\n *\n * @name value\n * @memberOf _\n * @since 0.1.0\n * @alias toJSON, valueOf\n * @category Seq\n * @returns {*} Returns the resolved unwrapped value.\n * @example\n *\n * _([1, 2, 3]).value();\n * // => [1, 2, 3]\n */\n function wrapperValue() {\n return baseWrapperValue(this.__wrapped__, this.__actions__);\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates an object composed of keys generated from the results of running\n * each element of `collection` thru `iteratee`. The corresponding value of\n * each key is the number of times the key was returned by `iteratee`. The\n * iteratee is invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 0.5.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The iteratee to transform keys.\n * @returns {Object} Returns the composed aggregate object.\n * @example\n *\n * _.countBy([6.1, 4.2, 6.3], Math.floor);\n * // => { '4': 1, '6': 2 }\n *\n * // The `_.property` iteratee shorthand.\n * _.countBy(['one', 'two', 'three'], 'length');\n * // => { '3': 2, '5': 1 }\n */\n var countBy = createAggregator(function(result, value, key) {\n if (hasOwnProperty.call(result, key)) {\n ++result[key];\n } else {\n baseAssignValue(result, key, 1);\n }\n });\n\n /**\n * Checks if `predicate` returns truthy for **all** elements of `collection`.\n * Iteration is stopped once `predicate` returns falsey. The predicate is\n * invoked with three arguments: (value, index|key, collection).\n *\n * **Note:** This method returns `true` for\n * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because\n * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of\n * elements of empty collections.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {boolean} Returns `true` if all elements pass the predicate check,\n * else `false`.\n * @example\n *\n * _.every([true, 1, null, 'yes'], Boolean);\n * // => false\n *\n * var users = [\n * { 'user': 'barney', 'age': 36, 'active': false },\n * { 'user': 'fred', 'age': 40, 'active': false }\n * ];\n *\n * // The `_.matches` iteratee shorthand.\n * _.every(users, { 'user': 'barney', 'active': false });\n * // => false\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.every(users, ['active', false]);\n * // => true\n *\n * // The `_.property` iteratee shorthand.\n * _.every(users, 'active');\n * // => false\n */\n function every(collection, predicate, guard) {\n var func = isArray(collection) ? arrayEvery : baseEvery;\n if (guard && isIterateeCall(collection, predicate, guard)) {\n predicate = undefined;\n }\n return func(collection, getIteratee(predicate, 3));\n }\n\n /**\n * Iterates over elements of `collection`, returning an array of all elements\n * `predicate` returns truthy for. The predicate is invoked with three\n * arguments: (value, index|key, collection).\n *\n * **Note:** Unlike `_.remove`, this method returns a new array.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n * @see _.reject\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36, 'active': true },\n * { 'user': 'fred', 'age': 40, 'active': false }\n * ];\n *\n * _.filter(users, function(o) { return !o.active; });\n * // => objects for ['fred']\n *\n * // The `_.matches` iteratee shorthand.\n * _.filter(users, { 'age': 36, 'active': true });\n * // => objects for ['barney']\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.filter(users, ['active', false]);\n * // => objects for ['fred']\n *\n * // The `_.property` iteratee shorthand.\n * _.filter(users, 'active');\n * // => objects for ['barney']\n *\n * // Combining several predicates using `_.overEvery` or `_.overSome`.\n * _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]]));\n * // => objects for ['fred', 'barney']\n */\n function filter(collection, predicate) {\n var func = isArray(collection) ? arrayFilter : baseFilter;\n return func(collection, getIteratee(predicate, 3));\n }\n\n /**\n * Iterates over elements of `collection`, returning the first element\n * `predicate` returns truthy for. The predicate is invoked with three\n * arguments: (value, index|key, collection).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to inspect.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @param {number} [fromIndex=0] The index to search from.\n * @returns {*} Returns the matched element, else `undefined`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36, 'active': true },\n * { 'user': 'fred', 'age': 40, 'active': false },\n * { 'user': 'pebbles', 'age': 1, 'active': true }\n * ];\n *\n * _.find(users, function(o) { return o.age < 40; });\n * // => object for 'barney'\n *\n * // The `_.matches` iteratee shorthand.\n * _.find(users, { 'age': 1, 'active': true });\n * // => object for 'pebbles'\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.find(users, ['active', false]);\n * // => object for 'fred'\n *\n * // The `_.property` iteratee shorthand.\n * _.find(users, 'active');\n * // => object for 'barney'\n */\n var find = createFind(findIndex);\n\n /**\n * This method is like `_.find` except that it iterates over elements of\n * `collection` from right to left.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to inspect.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @param {number} [fromIndex=collection.length-1] The index to search from.\n * @returns {*} Returns the matched element, else `undefined`.\n * @example\n *\n * _.findLast([1, 2, 3, 4], function(n) {\n * return n % 2 == 1;\n * });\n * // => 3\n */\n var findLast = createFind(findLastIndex);\n\n /**\n * Creates a flattened array of values by running each element in `collection`\n * thru `iteratee` and flattening the mapped results. The iteratee is invoked\n * with three arguments: (value, index|key, collection).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * function duplicate(n) {\n * return [n, n];\n * }\n *\n * _.flatMap([1, 2], duplicate);\n * // => [1, 1, 2, 2]\n */\n function flatMap(collection, iteratee) {\n return baseFlatten(map(collection, iteratee), 1);\n }\n\n /**\n * This method is like `_.flatMap` except that it recursively flattens the\n * mapped results.\n *\n * @static\n * @memberOf _\n * @since 4.7.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * function duplicate(n) {\n * return [[[n, n]]];\n * }\n *\n * _.flatMapDeep([1, 2], duplicate);\n * // => [1, 1, 2, 2]\n */\n function flatMapDeep(collection, iteratee) {\n return baseFlatten(map(collection, iteratee), INFINITY);\n }\n\n /**\n * This method is like `_.flatMap` except that it recursively flattens the\n * mapped results up to `depth` times.\n *\n * @static\n * @memberOf _\n * @since 4.7.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @param {number} [depth=1] The maximum recursion depth.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * function duplicate(n) {\n * return [[[n, n]]];\n * }\n *\n * _.flatMapDepth([1, 2], duplicate, 2);\n * // => [[1, 1], [2, 2]]\n */\n function flatMapDepth(collection, iteratee, depth) {\n depth = depth === undefined ? 1 : toInteger(depth);\n return baseFlatten(map(collection, iteratee), depth);\n }\n\n /**\n * Iterates over elements of `collection` and invokes `iteratee` for each element.\n * The iteratee is invoked with three arguments: (value, index|key, collection).\n * Iteratee functions may exit iteration early by explicitly returning `false`.\n *\n * **Note:** As with other \"Collections\" methods, objects with a \"length\"\n * property are iterated like arrays. To avoid this behavior use `_.forIn`\n * or `_.forOwn` for object iteration.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @alias each\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Array|Object} Returns `collection`.\n * @see _.forEachRight\n * @example\n *\n * _.forEach([1, 2], function(value) {\n * console.log(value);\n * });\n * // => Logs `1` then `2`.\n *\n * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {\n * console.log(key);\n * });\n * // => Logs 'a' then 'b' (iteration order is not guaranteed).\n */\n function forEach(collection, iteratee) {\n var func = isArray(collection) ? arrayEach : baseEach;\n return func(collection, getIteratee(iteratee, 3));\n }\n\n /**\n * This method is like `_.forEach` except that it iterates over elements of\n * `collection` from right to left.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @alias eachRight\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Array|Object} Returns `collection`.\n * @see _.forEach\n * @example\n *\n * _.forEachRight([1, 2], function(value) {\n * console.log(value);\n * });\n * // => Logs `2` then `1`.\n */\n function forEachRight(collection, iteratee) {\n var func = isArray(collection) ? arrayEachRight : baseEachRight;\n return func(collection, getIteratee(iteratee, 3));\n }\n\n /**\n * Creates an object composed of keys generated from the results of running\n * each element of `collection` thru `iteratee`. The order of grouped values\n * is determined by the order they occur in `collection`. The corresponding\n * value of each key is an array of elements responsible for generating the\n * key. The iteratee is invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The iteratee to transform keys.\n * @returns {Object} Returns the composed aggregate object.\n * @example\n *\n * _.groupBy([6.1, 4.2, 6.3], Math.floor);\n * // => { '4': [4.2], '6': [6.1, 6.3] }\n *\n * // The `_.property` iteratee shorthand.\n * _.groupBy(['one', 'two', 'three'], 'length');\n * // => { '3': ['one', 'two'], '5': ['three'] }\n */\n var groupBy = createAggregator(function(result, value, key) {\n if (hasOwnProperty.call(result, key)) {\n result[key].push(value);\n } else {\n baseAssignValue(result, key, [value]);\n }\n });\n\n /**\n * Checks if `value` is in `collection`. If `collection` is a string, it's\n * checked for a substring of `value`, otherwise\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * is used for equality comparisons. If `fromIndex` is negative, it's used as\n * the offset from the end of `collection`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object|string} collection The collection to inspect.\n * @param {*} value The value to search for.\n * @param {number} [fromIndex=0] The index to search from.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.\n * @returns {boolean} Returns `true` if `value` is found, else `false`.\n * @example\n *\n * _.includes([1, 2, 3], 1);\n * // => true\n *\n * _.includes([1, 2, 3], 1, 2);\n * // => false\n *\n * _.includes({ 'a': 1, 'b': 2 }, 1);\n * // => true\n *\n * _.includes('abcd', 'bc');\n * // => true\n */\n function includes(collection, value, fromIndex, guard) {\n collection = isArrayLike(collection) ? collection : values(collection);\n fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0;\n\n var length = collection.length;\n if (fromIndex < 0) {\n fromIndex = nativeMax(length + fromIndex, 0);\n }\n return isString(collection)\n ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1)\n : (!!length && baseIndexOf(collection, value, fromIndex) > -1);\n }\n\n /**\n * Invokes the method at `path` of each element in `collection`, returning\n * an array of the results of each invoked method. Any additional arguments\n * are provided to each invoked method. If `path` is a function, it's invoked\n * for, and `this` bound to, each element in `collection`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Array|Function|string} path The path of the method to invoke or\n * the function invoked per iteration.\n * @param {...*} [args] The arguments to invoke each method with.\n * @returns {Array} Returns the array of results.\n * @example\n *\n * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort');\n * // => [[1, 5, 7], [1, 2, 3]]\n *\n * _.invokeMap([123, 456], String.prototype.split, '');\n * // => [['1', '2', '3'], ['4', '5', '6']]\n */\n var invokeMap = baseRest(function(collection, path, args) {\n var index = -1,\n isFunc = typeof path == 'function',\n result = isArrayLike(collection) ? Array(collection.length) : [];\n\n baseEach(collection, function(value) {\n result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args);\n });\n return result;\n });\n\n /**\n * Creates an object composed of keys generated from the results of running\n * each element of `collection` thru `iteratee`. The corresponding value of\n * each key is the last element responsible for generating the key. The\n * iteratee is invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The iteratee to transform keys.\n * @returns {Object} Returns the composed aggregate object.\n * @example\n *\n * var array = [\n * { 'dir': 'left', 'code': 97 },\n * { 'dir': 'right', 'code': 100 }\n * ];\n *\n * _.keyBy(array, function(o) {\n * return String.fromCharCode(o.code);\n * });\n * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }\n *\n * _.keyBy(array, 'dir');\n * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }\n */\n var keyBy = createAggregator(function(result, value, key) {\n baseAssignValue(result, key, value);\n });\n\n /**\n * Creates an array of values by running each element in `collection` thru\n * `iteratee`. The iteratee is invoked with three arguments:\n * (value, index|key, collection).\n *\n * Many lodash methods are guarded to work as iteratees for methods like\n * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.\n *\n * The guarded methods are:\n * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`,\n * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`,\n * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`,\n * `template`, `trim`, `trimEnd`, `trimStart`, and `words`\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n * @example\n *\n * function square(n) {\n * return n * n;\n * }\n *\n * _.map([4, 8], square);\n * // => [16, 64]\n *\n * _.map({ 'a': 4, 'b': 8 }, square);\n * // => [16, 64] (iteration order is not guaranteed)\n *\n * var users = [\n * { 'user': 'barney' },\n * { 'user': 'fred' }\n * ];\n *\n * // The `_.property` iteratee shorthand.\n * _.map(users, 'user');\n * // => ['barney', 'fred']\n */\n function map(collection, iteratee) {\n var func = isArray(collection) ? arrayMap : baseMap;\n return func(collection, getIteratee(iteratee, 3));\n }\n\n /**\n * This method is like `_.sortBy` except that it allows specifying the sort\n * orders of the iteratees to sort by. If `orders` is unspecified, all values\n * are sorted in ascending order. Otherwise, specify an order of \"desc\" for\n * descending or \"asc\" for ascending sort order of corresponding values.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]]\n * The iteratees to sort by.\n * @param {string[]} [orders] The sort orders of `iteratees`.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.\n * @returns {Array} Returns the new sorted array.\n * @example\n *\n * var users = [\n * { 'user': 'fred', 'age': 48 },\n * { 'user': 'barney', 'age': 34 },\n * { 'user': 'fred', 'age': 40 },\n * { 'user': 'barney', 'age': 36 }\n * ];\n *\n * // Sort by `user` in ascending order and by `age` in descending order.\n * _.orderBy(users, ['user', 'age'], ['asc', 'desc']);\n * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]\n */\n function orderBy(collection, iteratees, orders, guard) {\n if (collection == null) {\n return [];\n }\n if (!isArray(iteratees)) {\n iteratees = iteratees == null ? [] : [iteratees];\n }\n orders = guard ? undefined : orders;\n if (!isArray(orders)) {\n orders = orders == null ? [] : [orders];\n }\n return baseOrderBy(collection, iteratees, orders);\n }\n\n /**\n * Creates an array of elements split into two groups, the first of which\n * contains elements `predicate` returns truthy for, the second of which\n * contains elements `predicate` returns falsey for. The predicate is\n * invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the array of grouped elements.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36, 'active': false },\n * { 'user': 'fred', 'age': 40, 'active': true },\n * { 'user': 'pebbles', 'age': 1, 'active': false }\n * ];\n *\n * _.partition(users, function(o) { return o.active; });\n * // => objects for [['fred'], ['barney', 'pebbles']]\n *\n * // The `_.matches` iteratee shorthand.\n * _.partition(users, { 'age': 1, 'active': false });\n * // => objects for [['pebbles'], ['barney', 'fred']]\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.partition(users, ['active', false]);\n * // => objects for [['barney', 'pebbles'], ['fred']]\n *\n * // The `_.property` iteratee shorthand.\n * _.partition(users, 'active');\n * // => objects for [['fred'], ['barney', 'pebbles']]\n */\n var partition = createAggregator(function(result, value, key) {\n result[key ? 0 : 1].push(value);\n }, function() { return [[], []]; });\n\n /**\n * Reduces `collection` to a value which is the accumulated result of running\n * each element in `collection` thru `iteratee`, where each successive\n * invocation is supplied the return value of the previous. If `accumulator`\n * is not given, the first element of `collection` is used as the initial\n * value. The iteratee is invoked with four arguments:\n * (accumulator, value, index|key, collection).\n *\n * Many lodash methods are guarded to work as iteratees for methods like\n * `_.reduce`, `_.reduceRight`, and `_.transform`.\n *\n * The guarded methods are:\n * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`,\n * and `sortBy`\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @param {*} [accumulator] The initial value.\n * @returns {*} Returns the accumulated value.\n * @see _.reduceRight\n * @example\n *\n * _.reduce([1, 2], function(sum, n) {\n * return sum + n;\n * }, 0);\n * // => 3\n *\n * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {\n * (result[value] || (result[value] = [])).push(key);\n * return result;\n * }, {});\n * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)\n */\n function reduce(collection, iteratee, accumulator) {\n var func = isArray(collection) ? arrayReduce : baseReduce,\n initAccum = arguments.length < 3;\n\n return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach);\n }\n\n /**\n * This method is like `_.reduce` except that it iterates over elements of\n * `collection` from right to left.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @param {*} [accumulator] The initial value.\n * @returns {*} Returns the accumulated value.\n * @see _.reduce\n * @example\n *\n * var array = [[0, 1], [2, 3], [4, 5]];\n *\n * _.reduceRight(array, function(flattened, other) {\n * return flattened.concat(other);\n * }, []);\n * // => [4, 5, 2, 3, 0, 1]\n */\n function reduceRight(collection, iteratee, accumulator) {\n var func = isArray(collection) ? arrayReduceRight : baseReduce,\n initAccum = arguments.length < 3;\n\n return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight);\n }\n\n /**\n * The opposite of `_.filter`; this method returns the elements of `collection`\n * that `predicate` does **not** return truthy for.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n * @see _.filter\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36, 'active': false },\n * { 'user': 'fred', 'age': 40, 'active': true }\n * ];\n *\n * _.reject(users, function(o) { return !o.active; });\n * // => objects for ['fred']\n *\n * // The `_.matches` iteratee shorthand.\n * _.reject(users, { 'age': 40, 'active': true });\n * // => objects for ['barney']\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.reject(users, ['active', false]);\n * // => objects for ['fred']\n *\n * // The `_.property` iteratee shorthand.\n * _.reject(users, 'active');\n * // => objects for ['barney']\n */\n function reject(collection, predicate) {\n var func = isArray(collection) ? arrayFilter : baseFilter;\n return func(collection, negate(getIteratee(predicate, 3)));\n }\n\n /**\n * Gets a random element from `collection`.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to sample.\n * @returns {*} Returns the random element.\n * @example\n *\n * _.sample([1, 2, 3, 4]);\n * // => 2\n */\n function sample(collection) {\n var func = isArray(collection) ? arraySample : baseSample;\n return func(collection);\n }\n\n /**\n * Gets `n` random elements at unique keys from `collection` up to the\n * size of `collection`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to sample.\n * @param {number} [n=1] The number of elements to sample.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the random elements.\n * @example\n *\n * _.sampleSize([1, 2, 3], 2);\n * // => [3, 1]\n *\n * _.sampleSize([1, 2, 3], 4);\n * // => [2, 3, 1]\n */\n function sampleSize(collection, n, guard) {\n if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) {\n n = 1;\n } else {\n n = toInteger(n);\n }\n var func = isArray(collection) ? arraySampleSize : baseSampleSize;\n return func(collection, n);\n }\n\n /**\n * Creates an array of shuffled values, using a version of the\n * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to shuffle.\n * @returns {Array} Returns the new shuffled array.\n * @example\n *\n * _.shuffle([1, 2, 3, 4]);\n * // => [4, 1, 3, 2]\n */\n function shuffle(collection) {\n var func = isArray(collection) ? arrayShuffle : baseShuffle;\n return func(collection);\n }\n\n /**\n * Gets the size of `collection` by returning its length for array-like\n * values or the number of own enumerable string keyed properties for objects.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object|string} collection The collection to inspect.\n * @returns {number} Returns the collection size.\n * @example\n *\n * _.size([1, 2, 3]);\n * // => 3\n *\n * _.size({ 'a': 1, 'b': 2 });\n * // => 2\n *\n * _.size('pebbles');\n * // => 7\n */\n function size(collection) {\n if (collection == null) {\n return 0;\n }\n if (isArrayLike(collection)) {\n return isString(collection) ? stringSize(collection) : collection.length;\n }\n var tag = getTag(collection);\n if (tag == mapTag || tag == setTag) {\n return collection.size;\n }\n return baseKeys(collection).length;\n }\n\n /**\n * Checks if `predicate` returns truthy for **any** element of `collection`.\n * Iteration is stopped once `predicate` returns truthy. The predicate is\n * invoked with three arguments: (value, index|key, collection).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n * @example\n *\n * _.some([null, 0, 'yes', false], Boolean);\n * // => true\n *\n * var users = [\n * { 'user': 'barney', 'active': true },\n * { 'user': 'fred', 'active': false }\n * ];\n *\n * // The `_.matches` iteratee shorthand.\n * _.some(users, { 'user': 'barney', 'active': false });\n * // => false\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.some(users, ['active', false]);\n * // => true\n *\n * // The `_.property` iteratee shorthand.\n * _.some(users, 'active');\n * // => true\n */\n function some(collection, predicate, guard) {\n var func = isArray(collection) ? arraySome : baseSome;\n if (guard && isIterateeCall(collection, predicate, guard)) {\n predicate = undefined;\n }\n return func(collection, getIteratee(predicate, 3));\n }\n\n /**\n * Creates an array of elements, sorted in ascending order by the results of\n * running each element in a collection thru each iteratee. This method\n * performs a stable sort, that is, it preserves the original sort order of\n * equal elements. The iteratees are invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {...(Function|Function[])} [iteratees=[_.identity]]\n * The iteratees to sort by.\n * @returns {Array} Returns the new sorted array.\n * @example\n *\n * var users = [\n * { 'user': 'fred', 'age': 48 },\n * { 'user': 'barney', 'age': 36 },\n * { 'user': 'fred', 'age': 30 },\n * { 'user': 'barney', 'age': 34 }\n * ];\n *\n * _.sortBy(users, [function(o) { return o.user; }]);\n * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]]\n *\n * _.sortBy(users, ['user', 'age']);\n * // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]]\n */\n var sortBy = baseRest(function(collection, iteratees) {\n if (collection == null) {\n return [];\n }\n var length = iteratees.length;\n if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) {\n iteratees = [];\n } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) {\n iteratees = [iteratees[0]];\n }\n return baseOrderBy(collection, baseFlatten(iteratees, 1), []);\n });\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Gets the timestamp of the number of milliseconds that have elapsed since\n * the Unix epoch (1 January 1970 00:00:00 UTC).\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Date\n * @returns {number} Returns the timestamp.\n * @example\n *\n * _.defer(function(stamp) {\n * console.log(_.now() - stamp);\n * }, _.now());\n * // => Logs the number of milliseconds it took for the deferred invocation.\n */\n var now = ctxNow || function() {\n return root.Date.now();\n };\n\n /*------------------------------------------------------------------------*/\n\n /**\n * The opposite of `_.before`; this method creates a function that invokes\n * `func` once it's called `n` or more times.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {number} n The number of calls before `func` is invoked.\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new restricted function.\n * @example\n *\n * var saves = ['profile', 'settings'];\n *\n * var done = _.after(saves.length, function() {\n * console.log('done saving!');\n * });\n *\n * _.forEach(saves, function(type) {\n * asyncSave({ 'type': type, 'complete': done });\n * });\n * // => Logs 'done saving!' after the two async saves have completed.\n */\n function after(n, func) {\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n n = toInteger(n);\n return function() {\n if (--n < 1) {\n return func.apply(this, arguments);\n }\n };\n }\n\n /**\n * Creates a function that invokes `func`, with up to `n` arguments,\n * ignoring any additional arguments.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {Function} func The function to cap arguments for.\n * @param {number} [n=func.length] The arity cap.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Function} Returns the new capped function.\n * @example\n *\n * _.map(['6', '8', '10'], _.ary(parseInt, 1));\n * // => [6, 8, 10]\n */\n function ary(func, n, guard) {\n n = guard ? undefined : n;\n n = (func && n == null) ? func.length : n;\n return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n);\n }\n\n /**\n * Creates a function that invokes `func`, with the `this` binding and arguments\n * of the created function, while it's called less than `n` times. Subsequent\n * calls to the created function return the result of the last `func` invocation.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {number} n The number of calls at which `func` is no longer invoked.\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new restricted function.\n * @example\n *\n * jQuery(element).on('click', _.before(5, addContactToList));\n * // => Allows adding up to 4 contacts to the list.\n */\n function before(n, func) {\n var result;\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n n = toInteger(n);\n return function() {\n if (--n > 0) {\n result = func.apply(this, arguments);\n }\n if (n <= 1) {\n func = undefined;\n }\n return result;\n };\n }\n\n /**\n * Creates a function that invokes `func` with the `this` binding of `thisArg`\n * and `partials` prepended to the arguments it receives.\n *\n * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,\n * may be used as a placeholder for partially applied arguments.\n *\n * **Note:** Unlike native `Function#bind`, this method doesn't set the \"length\"\n * property of bound functions.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to bind.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {...*} [partials] The arguments to be partially applied.\n * @returns {Function} Returns the new bound function.\n * @example\n *\n * function greet(greeting, punctuation) {\n * return greeting + ' ' + this.user + punctuation;\n * }\n *\n * var object = { 'user': 'fred' };\n *\n * var bound = _.bind(greet, object, 'hi');\n * bound('!');\n * // => 'hi fred!'\n *\n * // Bound with placeholders.\n * var bound = _.bind(greet, object, _, '!');\n * bound('hi');\n * // => 'hi fred!'\n */\n var bind = baseRest(function(func, thisArg, partials) {\n var bitmask = WRAP_BIND_FLAG;\n if (partials.length) {\n var holders = replaceHolders(partials, getHolder(bind));\n bitmask |= WRAP_PARTIAL_FLAG;\n }\n return createWrap(func, bitmask, thisArg, partials, holders);\n });\n\n /**\n * Creates a function that invokes the method at `object[key]` with `partials`\n * prepended to the arguments it receives.\n *\n * This method differs from `_.bind` by allowing bound functions to reference\n * methods that may be redefined or don't yet exist. See\n * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern)\n * for more details.\n *\n * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic\n * builds, may be used as a placeholder for partially applied arguments.\n *\n * @static\n * @memberOf _\n * @since 0.10.0\n * @category Function\n * @param {Object} object The object to invoke the method on.\n * @param {string} key The key of the method.\n * @param {...*} [partials] The arguments to be partially applied.\n * @returns {Function} Returns the new bound function.\n * @example\n *\n * var object = {\n * 'user': 'fred',\n * 'greet': function(greeting, punctuation) {\n * return greeting + ' ' + this.user + punctuation;\n * }\n * };\n *\n * var bound = _.bindKey(object, 'greet', 'hi');\n * bound('!');\n * // => 'hi fred!'\n *\n * object.greet = function(greeting, punctuation) {\n * return greeting + 'ya ' + this.user + punctuation;\n * };\n *\n * bound('!');\n * // => 'hiya fred!'\n *\n * // Bound with placeholders.\n * var bound = _.bindKey(object, 'greet', _, '!');\n * bound('hi');\n * // => 'hiya fred!'\n */\n var bindKey = baseRest(function(object, key, partials) {\n var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG;\n if (partials.length) {\n var holders = replaceHolders(partials, getHolder(bindKey));\n bitmask |= WRAP_PARTIAL_FLAG;\n }\n return createWrap(key, bitmask, object, partials, holders);\n });\n\n /**\n * Creates a function that accepts arguments of `func` and either invokes\n * `func` returning its result, if at least `arity` number of arguments have\n * been provided, or returns a function that accepts the remaining `func`\n * arguments, and so on. The arity of `func` may be specified if `func.length`\n * is not sufficient.\n *\n * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds,\n * may be used as a placeholder for provided arguments.\n *\n * **Note:** This method doesn't set the \"length\" property of curried functions.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Function\n * @param {Function} func The function to curry.\n * @param {number} [arity=func.length] The arity of `func`.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Function} Returns the new curried function.\n * @example\n *\n * var abc = function(a, b, c) {\n * return [a, b, c];\n * };\n *\n * var curried = _.curry(abc);\n *\n * curried(1)(2)(3);\n * // => [1, 2, 3]\n *\n * curried(1, 2)(3);\n * // => [1, 2, 3]\n *\n * curried(1, 2, 3);\n * // => [1, 2, 3]\n *\n * // Curried with placeholders.\n * curried(1)(_, 3)(2);\n * // => [1, 2, 3]\n */\n function curry(func, arity, guard) {\n arity = guard ? undefined : arity;\n var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity);\n result.placeholder = curry.placeholder;\n return result;\n }\n\n /**\n * This method is like `_.curry` except that arguments are applied to `func`\n * in the manner of `_.partialRight` instead of `_.partial`.\n *\n * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic\n * builds, may be used as a placeholder for provided arguments.\n *\n * **Note:** This method doesn't set the \"length\" property of curried functions.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {Function} func The function to curry.\n * @param {number} [arity=func.length] The arity of `func`.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Function} Returns the new curried function.\n * @example\n *\n * var abc = function(a, b, c) {\n * return [a, b, c];\n * };\n *\n * var curried = _.curryRight(abc);\n *\n * curried(3)(2)(1);\n * // => [1, 2, 3]\n *\n * curried(2, 3)(1);\n * // => [1, 2, 3]\n *\n * curried(1, 2, 3);\n * // => [1, 2, 3]\n *\n * // Curried with placeholders.\n * curried(3)(1, _)(2);\n * // => [1, 2, 3]\n */\n function curryRight(func, arity, guard) {\n arity = guard ? undefined : arity;\n var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity);\n result.placeholder = curryRight.placeholder;\n return result;\n }\n\n /**\n * Creates a debounced function that delays invoking `func` until after `wait`\n * milliseconds have elapsed since the last time the debounced function was\n * invoked. The debounced function comes with a `cancel` method to cancel\n * delayed `func` invocations and a `flush` method to immediately invoke them.\n * Provide `options` to indicate whether `func` should be invoked on the\n * leading and/or trailing edge of the `wait` timeout. The `func` is invoked\n * with the last arguments provided to the debounced function. Subsequent\n * calls to the debounced function return the result of the last `func`\n * invocation.\n *\n * **Note:** If `leading` and `trailing` options are `true`, `func` is\n * invoked on the trailing edge of the timeout only if the debounced function\n * is invoked more than once during the `wait` timeout.\n *\n * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred\n * until to the next tick, similar to `setTimeout` with a timeout of `0`.\n *\n * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)\n * for details over the differences between `_.debounce` and `_.throttle`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to debounce.\n * @param {number} [wait=0] The number of milliseconds to delay.\n * @param {Object} [options={}] The options object.\n * @param {boolean} [options.leading=false]\n * Specify invoking on the leading edge of the timeout.\n * @param {number} [options.maxWait]\n * The maximum time `func` is allowed to be delayed before it's invoked.\n * @param {boolean} [options.trailing=true]\n * Specify invoking on the trailing edge of the timeout.\n * @returns {Function} Returns the new debounced function.\n * @example\n *\n * // Avoid costly calculations while the window size is in flux.\n * jQuery(window).on('resize', _.debounce(calculateLayout, 150));\n *\n * // Invoke `sendMail` when clicked, debouncing subsequent calls.\n * jQuery(element).on('click', _.debounce(sendMail, 300, {\n * 'leading': true,\n * 'trailing': false\n * }));\n *\n * // Ensure `batchLog` is invoked once after 1 second of debounced calls.\n * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });\n * var source = new EventSource('/stream');\n * jQuery(source).on('message', debounced);\n *\n * // Cancel the trailing debounced invocation.\n * jQuery(window).on('popstate', debounced.cancel);\n */\n function debounce(func, wait, options) {\n var lastArgs,\n lastThis,\n maxWait,\n result,\n timerId,\n lastCallTime,\n lastInvokeTime = 0,\n leading = false,\n maxing = false,\n trailing = true;\n\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n wait = toNumber(wait) || 0;\n if (isObject(options)) {\n leading = !!options.leading;\n maxing = 'maxWait' in options;\n maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;\n trailing = 'trailing' in options ? !!options.trailing : trailing;\n }\n\n function invokeFunc(time) {\n var args = lastArgs,\n thisArg = lastThis;\n\n lastArgs = lastThis = undefined;\n lastInvokeTime = time;\n result = func.apply(thisArg, args);\n return result;\n }\n\n function leadingEdge(time) {\n // Reset any `maxWait` timer.\n lastInvokeTime = time;\n // Start the timer for the trailing edge.\n timerId = setTimeout(timerExpired, wait);\n // Invoke the leading edge.\n return leading ? invokeFunc(time) : result;\n }\n\n function remainingWait(time) {\n var timeSinceLastCall = time - lastCallTime,\n timeSinceLastInvoke = time - lastInvokeTime,\n timeWaiting = wait - timeSinceLastCall;\n\n return maxing\n ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke)\n : timeWaiting;\n }\n\n function shouldInvoke(time) {\n var timeSinceLastCall = time - lastCallTime,\n timeSinceLastInvoke = time - lastInvokeTime;\n\n // Either this is the first call, activity has stopped and we're at the\n // trailing edge, the system time has gone backwards and we're treating\n // it as the trailing edge, or we've hit the `maxWait` limit.\n return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||\n (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));\n }\n\n function timerExpired() {\n var time = now();\n if (shouldInvoke(time)) {\n return trailingEdge(time);\n }\n // Restart the timer.\n timerId = setTimeout(timerExpired, remainingWait(time));\n }\n\n function trailingEdge(time) {\n timerId = undefined;\n\n // Only invoke if we have `lastArgs` which means `func` has been\n // debounced at least once.\n if (trailing && lastArgs) {\n return invokeFunc(time);\n }\n lastArgs = lastThis = undefined;\n return result;\n }\n\n function cancel() {\n if (timerId !== undefined) {\n clearTimeout(timerId);\n }\n lastInvokeTime = 0;\n lastArgs = lastCallTime = lastThis = timerId = undefined;\n }\n\n function flush() {\n return timerId === undefined ? result : trailingEdge(now());\n }\n\n function debounced() {\n var time = now(),\n isInvoking = shouldInvoke(time);\n\n lastArgs = arguments;\n lastThis = this;\n lastCallTime = time;\n\n if (isInvoking) {\n if (timerId === undefined) {\n return leadingEdge(lastCallTime);\n }\n if (maxing) {\n // Handle invocations in a tight loop.\n clearTimeout(timerId);\n timerId = setTimeout(timerExpired, wait);\n return invokeFunc(lastCallTime);\n }\n }\n if (timerId === undefined) {\n timerId = setTimeout(timerExpired, wait);\n }\n return result;\n }\n debounced.cancel = cancel;\n debounced.flush = flush;\n return debounced;\n }\n\n /**\n * Defers invoking the `func` until the current call stack has cleared. Any\n * additional arguments are provided to `func` when it's invoked.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to defer.\n * @param {...*} [args] The arguments to invoke `func` with.\n * @returns {number} Returns the timer id.\n * @example\n *\n * _.defer(function(text) {\n * console.log(text);\n * }, 'deferred');\n * // => Logs 'deferred' after one millisecond.\n */\n var defer = baseRest(function(func, args) {\n return baseDelay(func, 1, args);\n });\n\n /**\n * Invokes `func` after `wait` milliseconds. Any additional arguments are\n * provided to `func` when it's invoked.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to delay.\n * @param {number} wait The number of milliseconds to delay invocation.\n * @param {...*} [args] The arguments to invoke `func` with.\n * @returns {number} Returns the timer id.\n * @example\n *\n * _.delay(function(text) {\n * console.log(text);\n * }, 1000, 'later');\n * // => Logs 'later' after one second.\n */\n var delay = baseRest(function(func, wait, args) {\n return baseDelay(func, toNumber(wait) || 0, args);\n });\n\n /**\n * Creates a function that invokes `func` with arguments reversed.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Function\n * @param {Function} func The function to flip arguments for.\n * @returns {Function} Returns the new flipped function.\n * @example\n *\n * var flipped = _.flip(function() {\n * return _.toArray(arguments);\n * });\n *\n * flipped('a', 'b', 'c', 'd');\n * // => ['d', 'c', 'b', 'a']\n */\n function flip(func) {\n return createWrap(func, WRAP_FLIP_FLAG);\n }\n\n /**\n * Creates a function that memoizes the result of `func`. If `resolver` is\n * provided, it determines the cache key for storing the result based on the\n * arguments provided to the memoized function. By default, the first argument\n * provided to the memoized function is used as the map cache key. The `func`\n * is invoked with the `this` binding of the memoized function.\n *\n * **Note:** The cache is exposed as the `cache` property on the memoized\n * function. Its creation may be customized by replacing the `_.memoize.Cache`\n * constructor with one whose instances implement the\n * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)\n * method interface of `clear`, `delete`, `get`, `has`, and `set`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to have its output memoized.\n * @param {Function} [resolver] The function to resolve the cache key.\n * @returns {Function} Returns the new memoized function.\n * @example\n *\n * var object = { 'a': 1, 'b': 2 };\n * var other = { 'c': 3, 'd': 4 };\n *\n * var values = _.memoize(_.values);\n * values(object);\n * // => [1, 2]\n *\n * values(other);\n * // => [3, 4]\n *\n * object.a = 2;\n * values(object);\n * // => [1, 2]\n *\n * // Modify the result cache.\n * values.cache.set(object, ['a', 'b']);\n * values(object);\n * // => ['a', 'b']\n *\n * // Replace `_.memoize.Cache`.\n * _.memoize.Cache = WeakMap;\n */\n function memoize(func, resolver) {\n if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n var memoized = function() {\n var args = arguments,\n key = resolver ? resolver.apply(this, args) : args[0],\n cache = memoized.cache;\n\n if (cache.has(key)) {\n return cache.get(key);\n }\n var result = func.apply(this, args);\n memoized.cache = cache.set(key, result) || cache;\n return result;\n };\n memoized.cache = new (memoize.Cache || MapCache);\n return memoized;\n }\n\n // Expose `MapCache`.\n memoize.Cache = MapCache;\n\n /**\n * Creates a function that negates the result of the predicate `func`. The\n * `func` predicate is invoked with the `this` binding and arguments of the\n * created function.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {Function} predicate The predicate to negate.\n * @returns {Function} Returns the new negated function.\n * @example\n *\n * function isEven(n) {\n * return n % 2 == 0;\n * }\n *\n * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));\n * // => [1, 3, 5]\n */\n function negate(predicate) {\n if (typeof predicate != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n return function() {\n var args = arguments;\n switch (args.length) {\n case 0: return !predicate.call(this);\n case 1: return !predicate.call(this, args[0]);\n case 2: return !predicate.call(this, args[0], args[1]);\n case 3: return !predicate.call(this, args[0], args[1], args[2]);\n }\n return !predicate.apply(this, args);\n };\n }\n\n /**\n * Creates a function that is restricted to invoking `func` once. Repeat calls\n * to the function return the value of the first invocation. The `func` is\n * invoked with the `this` binding and arguments of the created function.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new restricted function.\n * @example\n *\n * var initialize = _.once(createApplication);\n * initialize();\n * initialize();\n * // => `createApplication` is invoked once\n */\n function once(func) {\n return before(2, func);\n }\n\n /**\n * Creates a function that invokes `func` with its arguments transformed.\n *\n * @static\n * @since 4.0.0\n * @memberOf _\n * @category Function\n * @param {Function} func The function to wrap.\n * @param {...(Function|Function[])} [transforms=[_.identity]]\n * The argument transforms.\n * @returns {Function} Returns the new function.\n * @example\n *\n * function doubled(n) {\n * return n * 2;\n * }\n *\n * function square(n) {\n * return n * n;\n * }\n *\n * var func = _.overArgs(function(x, y) {\n * return [x, y];\n * }, [square, doubled]);\n *\n * func(9, 3);\n * // => [81, 6]\n *\n * func(10, 5);\n * // => [100, 10]\n */\n var overArgs = castRest(function(func, transforms) {\n transforms = (transforms.length == 1 && isArray(transforms[0]))\n ? arrayMap(transforms[0], baseUnary(getIteratee()))\n : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee()));\n\n var funcsLength = transforms.length;\n return baseRest(function(args) {\n var index = -1,\n length = nativeMin(args.length, funcsLength);\n\n while (++index < length) {\n args[index] = transforms[index].call(this, args[index]);\n }\n return apply(func, this, args);\n });\n });\n\n /**\n * Creates a function that invokes `func` with `partials` prepended to the\n * arguments it receives. This method is like `_.bind` except it does **not**\n * alter the `this` binding.\n *\n * The `_.partial.placeholder` value, which defaults to `_` in monolithic\n * builds, may be used as a placeholder for partially applied arguments.\n *\n * **Note:** This method doesn't set the \"length\" property of partially\n * applied functions.\n *\n * @static\n * @memberOf _\n * @since 0.2.0\n * @category Function\n * @param {Function} func The function to partially apply arguments to.\n * @param {...*} [partials] The arguments to be partially applied.\n * @returns {Function} Returns the new partially applied function.\n * @example\n *\n * function greet(greeting, name) {\n * return greeting + ' ' + name;\n * }\n *\n * var sayHelloTo = _.partial(greet, 'hello');\n * sayHelloTo('fred');\n * // => 'hello fred'\n *\n * // Partially applied with placeholders.\n * var greetFred = _.partial(greet, _, 'fred');\n * greetFred('hi');\n * // => 'hi fred'\n */\n var partial = baseRest(function(func, partials) {\n var holders = replaceHolders(partials, getHolder(partial));\n return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders);\n });\n\n /**\n * This method is like `_.partial` except that partially applied arguments\n * are appended to the arguments it receives.\n *\n * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic\n * builds, may be used as a placeholder for partially applied arguments.\n *\n * **Note:** This method doesn't set the \"length\" property of partially\n * applied functions.\n *\n * @static\n * @memberOf _\n * @since 1.0.0\n * @category Function\n * @param {Function} func The function to partially apply arguments to.\n * @param {...*} [partials] The arguments to be partially applied.\n * @returns {Function} Returns the new partially applied function.\n * @example\n *\n * function greet(greeting, name) {\n * return greeting + ' ' + name;\n * }\n *\n * var greetFred = _.partialRight(greet, 'fred');\n * greetFred('hi');\n * // => 'hi fred'\n *\n * // Partially applied with placeholders.\n * var sayHelloTo = _.partialRight(greet, 'hello', _);\n * sayHelloTo('fred');\n * // => 'hello fred'\n */\n var partialRight = baseRest(function(func, partials) {\n var holders = replaceHolders(partials, getHolder(partialRight));\n return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders);\n });\n\n /**\n * Creates a function that invokes `func` with arguments arranged according\n * to the specified `indexes` where the argument value at the first index is\n * provided as the first argument, the argument value at the second index is\n * provided as the second argument, and so on.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {Function} func The function to rearrange arguments for.\n * @param {...(number|number[])} indexes The arranged argument indexes.\n * @returns {Function} Returns the new function.\n * @example\n *\n * var rearged = _.rearg(function(a, b, c) {\n * return [a, b, c];\n * }, [2, 0, 1]);\n *\n * rearged('b', 'c', 'a')\n * // => ['a', 'b', 'c']\n */\n var rearg = flatRest(function(func, indexes) {\n return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes);\n });\n\n /**\n * Creates a function that invokes `func` with the `this` binding of the\n * created function and arguments from `start` and beyond provided as\n * an array.\n *\n * **Note:** This method is based on the\n * [rest parameter](https://mdn.io/rest_parameters).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Function\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @returns {Function} Returns the new function.\n * @example\n *\n * var say = _.rest(function(what, names) {\n * return what + ' ' + _.initial(names).join(', ') +\n * (_.size(names) > 1 ? ', & ' : '') + _.last(names);\n * });\n *\n * say('hello', 'fred', 'barney', 'pebbles');\n * // => 'hello fred, barney, & pebbles'\n */\n function rest(func, start) {\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n start = start === undefined ? start : toInteger(start);\n return baseRest(func, start);\n }\n\n /**\n * Creates a function that invokes `func` with the `this` binding of the\n * create function and an array of arguments much like\n * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply).\n *\n * **Note:** This method is based on the\n * [spread operator](https://mdn.io/spread_operator).\n *\n * @static\n * @memberOf _\n * @since 3.2.0\n * @category Function\n * @param {Function} func The function to spread arguments over.\n * @param {number} [start=0] The start position of the spread.\n * @returns {Function} Returns the new function.\n * @example\n *\n * var say = _.spread(function(who, what) {\n * return who + ' says ' + what;\n * });\n *\n * say(['fred', 'hello']);\n * // => 'fred says hello'\n *\n * var numbers = Promise.all([\n * Promise.resolve(40),\n * Promise.resolve(36)\n * ]);\n *\n * numbers.then(_.spread(function(x, y) {\n * return x + y;\n * }));\n * // => a Promise of 76\n */\n function spread(func, start) {\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n start = start == null ? 0 : nativeMax(toInteger(start), 0);\n return baseRest(function(args) {\n var array = args[start],\n otherArgs = castSlice(args, 0, start);\n\n if (array) {\n arrayPush(otherArgs, array);\n }\n return apply(func, this, otherArgs);\n });\n }\n\n /**\n * Creates a throttled function that only invokes `func` at most once per\n * every `wait` milliseconds. The throttled function comes with a `cancel`\n * method to cancel delayed `func` invocations and a `flush` method to\n * immediately invoke them. Provide `options` to indicate whether `func`\n * should be invoked on the leading and/or trailing edge of the `wait`\n * timeout. The `func` is invoked with the last arguments provided to the\n * throttled function. Subsequent calls to the throttled function return the\n * result of the last `func` invocation.\n *\n * **Note:** If `leading` and `trailing` options are `true`, `func` is\n * invoked on the trailing edge of the timeout only if the throttled function\n * is invoked more than once during the `wait` timeout.\n *\n * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred\n * until to the next tick, similar to `setTimeout` with a timeout of `0`.\n *\n * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)\n * for details over the differences between `_.throttle` and `_.debounce`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to throttle.\n * @param {number} [wait=0] The number of milliseconds to throttle invocations to.\n * @param {Object} [options={}] The options object.\n * @param {boolean} [options.leading=true]\n * Specify invoking on the leading edge of the timeout.\n * @param {boolean} [options.trailing=true]\n * Specify invoking on the trailing edge of the timeout.\n * @returns {Function} Returns the new throttled function.\n * @example\n *\n * // Avoid excessively updating the position while scrolling.\n * jQuery(window).on('scroll', _.throttle(updatePosition, 100));\n *\n * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.\n * var throttled = _.throttle(renewToken, 300000, { 'trailing': false });\n * jQuery(element).on('click', throttled);\n *\n * // Cancel the trailing throttled invocation.\n * jQuery(window).on('popstate', throttled.cancel);\n */\n function throttle(func, wait, options) {\n var leading = true,\n trailing = true;\n\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n if (isObject(options)) {\n leading = 'leading' in options ? !!options.leading : leading;\n trailing = 'trailing' in options ? !!options.trailing : trailing;\n }\n return debounce(func, wait, {\n 'leading': leading,\n 'maxWait': wait,\n 'trailing': trailing\n });\n }\n\n /**\n * Creates a function that accepts up to one argument, ignoring any\n * additional arguments.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Function\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n * @example\n *\n * _.map(['6', '8', '10'], _.unary(parseInt));\n * // => [6, 8, 10]\n */\n function unary(func) {\n return ary(func, 1);\n }\n\n /**\n * Creates a function that provides `value` to `wrapper` as its first\n * argument. Any additional arguments provided to the function are appended\n * to those provided to the `wrapper`. The wrapper is invoked with the `this`\n * binding of the created function.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {*} value The value to wrap.\n * @param {Function} [wrapper=identity] The wrapper function.\n * @returns {Function} Returns the new function.\n * @example\n *\n * var p = _.wrap(_.escape, function(func, text) {\n * return '' + func(text) + '';\n * });\n *\n * p('fred, barney, & pebbles');\n * // => 'fred, barney, & pebbles'\n */\n function wrap(value, wrapper) {\n return partial(castFunction(wrapper), value);\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Casts `value` as an array if it's not one.\n *\n * @static\n * @memberOf _\n * @since 4.4.0\n * @category Lang\n * @param {*} value The value to inspect.\n * @returns {Array} Returns the cast array.\n * @example\n *\n * _.castArray(1);\n * // => [1]\n *\n * _.castArray({ 'a': 1 });\n * // => [{ 'a': 1 }]\n *\n * _.castArray('abc');\n * // => ['abc']\n *\n * _.castArray(null);\n * // => [null]\n *\n * _.castArray(undefined);\n * // => [undefined]\n *\n * _.castArray();\n * // => []\n *\n * var array = [1, 2, 3];\n * console.log(_.castArray(array) === array);\n * // => true\n */\n function castArray() {\n if (!arguments.length) {\n return [];\n }\n var value = arguments[0];\n return isArray(value) ? value : [value];\n }\n\n /**\n * Creates a shallow clone of `value`.\n *\n * **Note:** This method is loosely based on the\n * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)\n * and supports cloning arrays, array buffers, booleans, date objects, maps,\n * numbers, `Object` objects, regexes, sets, strings, symbols, and typed\n * arrays. The own enumerable properties of `arguments` objects are cloned\n * as plain objects. An empty object is returned for uncloneable values such\n * as error objects, functions, DOM nodes, and WeakMaps.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to clone.\n * @returns {*} Returns the cloned value.\n * @see _.cloneDeep\n * @example\n *\n * var objects = [{ 'a': 1 }, { 'b': 2 }];\n *\n * var shallow = _.clone(objects);\n * console.log(shallow[0] === objects[0]);\n * // => true\n */\n function clone(value) {\n return baseClone(value, CLONE_SYMBOLS_FLAG);\n }\n\n /**\n * This method is like `_.clone` except that it accepts `customizer` which\n * is invoked to produce the cloned value. If `customizer` returns `undefined`,\n * cloning is handled by the method instead. The `customizer` is invoked with\n * up to four arguments; (value [, index|key, object, stack]).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to clone.\n * @param {Function} [customizer] The function to customize cloning.\n * @returns {*} Returns the cloned value.\n * @see _.cloneDeepWith\n * @example\n *\n * function customizer(value) {\n * if (_.isElement(value)) {\n * return value.cloneNode(false);\n * }\n * }\n *\n * var el = _.cloneWith(document.body, customizer);\n *\n * console.log(el === document.body);\n * // => false\n * console.log(el.nodeName);\n * // => 'BODY'\n * console.log(el.childNodes.length);\n * // => 0\n */\n function cloneWith(value, customizer) {\n customizer = typeof customizer == 'function' ? customizer : undefined;\n return baseClone(value, CLONE_SYMBOLS_FLAG, customizer);\n }\n\n /**\n * This method is like `_.clone` except that it recursively clones `value`.\n *\n * @static\n * @memberOf _\n * @since 1.0.0\n * @category Lang\n * @param {*} value The value to recursively clone.\n * @returns {*} Returns the deep cloned value.\n * @see _.clone\n * @example\n *\n * var objects = [{ 'a': 1 }, { 'b': 2 }];\n *\n * var deep = _.cloneDeep(objects);\n * console.log(deep[0] === objects[0]);\n * // => false\n */\n function cloneDeep(value) {\n return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG);\n }\n\n /**\n * This method is like `_.cloneWith` except that it recursively clones `value`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to recursively clone.\n * @param {Function} [customizer] The function to customize cloning.\n * @returns {*} Returns the deep cloned value.\n * @see _.cloneWith\n * @example\n *\n * function customizer(value) {\n * if (_.isElement(value)) {\n * return value.cloneNode(true);\n * }\n * }\n *\n * var el = _.cloneDeepWith(document.body, customizer);\n *\n * console.log(el === document.body);\n * // => false\n * console.log(el.nodeName);\n * // => 'BODY'\n * console.log(el.childNodes.length);\n * // => 20\n */\n function cloneDeepWith(value, customizer) {\n customizer = typeof customizer == 'function' ? customizer : undefined;\n return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer);\n }\n\n /**\n * Checks if `object` conforms to `source` by invoking the predicate\n * properties of `source` with the corresponding property values of `object`.\n *\n * **Note:** This method is equivalent to `_.conforms` when `source` is\n * partially applied.\n *\n * @static\n * @memberOf _\n * @since 4.14.0\n * @category Lang\n * @param {Object} object The object to inspect.\n * @param {Object} source The object of property predicates to conform to.\n * @returns {boolean} Returns `true` if `object` conforms, else `false`.\n * @example\n *\n * var object = { 'a': 1, 'b': 2 };\n *\n * _.conformsTo(object, { 'b': function(n) { return n > 1; } });\n * // => true\n *\n * _.conformsTo(object, { 'b': function(n) { return n > 2; } });\n * // => false\n */\n function conformsTo(object, source) {\n return source == null || baseConformsTo(object, source, keys(source));\n }\n\n /**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\n function eq(value, other) {\n return value === other || (value !== value && other !== other);\n }\n\n /**\n * Checks if `value` is greater than `other`.\n *\n * @static\n * @memberOf _\n * @since 3.9.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if `value` is greater than `other`,\n * else `false`.\n * @see _.lt\n * @example\n *\n * _.gt(3, 1);\n * // => true\n *\n * _.gt(3, 3);\n * // => false\n *\n * _.gt(1, 3);\n * // => false\n */\n var gt = createRelationalOperation(baseGt);\n\n /**\n * Checks if `value` is greater than or equal to `other`.\n *\n * @static\n * @memberOf _\n * @since 3.9.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if `value` is greater than or equal to\n * `other`, else `false`.\n * @see _.lte\n * @example\n *\n * _.gte(3, 1);\n * // => true\n *\n * _.gte(3, 3);\n * // => true\n *\n * _.gte(1, 3);\n * // => false\n */\n var gte = createRelationalOperation(function(value, other) {\n return value >= other;\n });\n\n /**\n * Checks if `value` is likely an `arguments` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n * else `false`.\n * @example\n *\n * _.isArguments(function() { return arguments; }());\n * // => true\n *\n * _.isArguments([1, 2, 3]);\n * // => false\n */\n var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {\n return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&\n !propertyIsEnumerable.call(value, 'callee');\n };\n\n /**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\n var isArray = Array.isArray;\n\n /**\n * Checks if `value` is classified as an `ArrayBuffer` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`.\n * @example\n *\n * _.isArrayBuffer(new ArrayBuffer(2));\n * // => true\n *\n * _.isArrayBuffer(new Array(2));\n * // => false\n */\n var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer;\n\n /**\n * Checks if `value` is array-like. A value is considered array-like if it's\n * not a function and has a `value.length` that's an integer greater than or\n * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is array-like, else `false`.\n * @example\n *\n * _.isArrayLike([1, 2, 3]);\n * // => true\n *\n * _.isArrayLike(document.body.children);\n * // => true\n *\n * _.isArrayLike('abc');\n * // => true\n *\n * _.isArrayLike(_.noop);\n * // => false\n */\n function isArrayLike(value) {\n return value != null && isLength(value.length) && !isFunction(value);\n }\n\n /**\n * This method is like `_.isArrayLike` except that it also checks if `value`\n * is an object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array-like object,\n * else `false`.\n * @example\n *\n * _.isArrayLikeObject([1, 2, 3]);\n * // => true\n *\n * _.isArrayLikeObject(document.body.children);\n * // => true\n *\n * _.isArrayLikeObject('abc');\n * // => false\n *\n * _.isArrayLikeObject(_.noop);\n * // => false\n */\n function isArrayLikeObject(value) {\n return isObjectLike(value) && isArrayLike(value);\n }\n\n /**\n * Checks if `value` is classified as a boolean primitive or object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a boolean, else `false`.\n * @example\n *\n * _.isBoolean(false);\n * // => true\n *\n * _.isBoolean(null);\n * // => false\n */\n function isBoolean(value) {\n return value === true || value === false ||\n (isObjectLike(value) && baseGetTag(value) == boolTag);\n }\n\n /**\n * Checks if `value` is a buffer.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.\n * @example\n *\n * _.isBuffer(new Buffer(2));\n * // => true\n *\n * _.isBuffer(new Uint8Array(2));\n * // => false\n */\n var isBuffer = nativeIsBuffer || stubFalse;\n\n /**\n * Checks if `value` is classified as a `Date` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a date object, else `false`.\n * @example\n *\n * _.isDate(new Date);\n * // => true\n *\n * _.isDate('Mon April 23 2012');\n * // => false\n */\n var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate;\n\n /**\n * Checks if `value` is likely a DOM element.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`.\n * @example\n *\n * _.isElement(document.body);\n * // => true\n *\n * _.isElement('');\n * // => false\n */\n function isElement(value) {\n return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value);\n }\n\n /**\n * Checks if `value` is an empty object, collection, map, or set.\n *\n * Objects are considered empty if they have no own enumerable string keyed\n * properties.\n *\n * Array-like values such as `arguments` objects, arrays, buffers, strings, or\n * jQuery-like collections are considered empty if they have a `length` of `0`.\n * Similarly, maps and sets are considered empty if they have a `size` of `0`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is empty, else `false`.\n * @example\n *\n * _.isEmpty(null);\n * // => true\n *\n * _.isEmpty(true);\n * // => true\n *\n * _.isEmpty(1);\n * // => true\n *\n * _.isEmpty([1, 2, 3]);\n * // => false\n *\n * _.isEmpty({ 'a': 1 });\n * // => false\n */\n function isEmpty(value) {\n if (value == null) {\n return true;\n }\n if (isArrayLike(value) &&\n (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' ||\n isBuffer(value) || isTypedArray(value) || isArguments(value))) {\n return !value.length;\n }\n var tag = getTag(value);\n if (tag == mapTag || tag == setTag) {\n return !value.size;\n }\n if (isPrototype(value)) {\n return !baseKeys(value).length;\n }\n for (var key in value) {\n if (hasOwnProperty.call(value, key)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Performs a deep comparison between two values to determine if they are\n * equivalent.\n *\n * **Note:** This method supports comparing arrays, array buffers, booleans,\n * date objects, error objects, maps, numbers, `Object` objects, regexes,\n * sets, strings, symbols, and typed arrays. `Object` objects are compared\n * by their own, not inherited, enumerable properties. Functions and DOM\n * nodes are compared by strict equality, i.e. `===`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.isEqual(object, other);\n * // => true\n *\n * object === other;\n * // => false\n */\n function isEqual(value, other) {\n return baseIsEqual(value, other);\n }\n\n /**\n * This method is like `_.isEqual` except that it accepts `customizer` which\n * is invoked to compare values. If `customizer` returns `undefined`, comparisons\n * are handled by the method instead. The `customizer` is invoked with up to\n * six arguments: (objValue, othValue [, index|key, object, other, stack]).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @param {Function} [customizer] The function to customize comparisons.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * function isGreeting(value) {\n * return /^h(?:i|ello)$/.test(value);\n * }\n *\n * function customizer(objValue, othValue) {\n * if (isGreeting(objValue) && isGreeting(othValue)) {\n * return true;\n * }\n * }\n *\n * var array = ['hello', 'goodbye'];\n * var other = ['hi', 'goodbye'];\n *\n * _.isEqualWith(array, other, customizer);\n * // => true\n */\n function isEqualWith(value, other, customizer) {\n customizer = typeof customizer == 'function' ? customizer : undefined;\n var result = customizer ? customizer(value, other) : undefined;\n return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result;\n }\n\n /**\n * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,\n * `SyntaxError`, `TypeError`, or `URIError` object.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an error object, else `false`.\n * @example\n *\n * _.isError(new Error);\n * // => true\n *\n * _.isError(Error);\n * // => false\n */\n function isError(value) {\n if (!isObjectLike(value)) {\n return false;\n }\n var tag = baseGetTag(value);\n return tag == errorTag || tag == domExcTag ||\n (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value));\n }\n\n /**\n * Checks if `value` is a finite primitive number.\n *\n * **Note:** This method is based on\n * [`Number.isFinite`](https://mdn.io/Number/isFinite).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a finite number, else `false`.\n * @example\n *\n * _.isFinite(3);\n * // => true\n *\n * _.isFinite(Number.MIN_VALUE);\n * // => true\n *\n * _.isFinite(Infinity);\n * // => false\n *\n * _.isFinite('3');\n * // => false\n */\n function isFinite(value) {\n return typeof value == 'number' && nativeIsFinite(value);\n }\n\n /**\n * Checks if `value` is classified as a `Function` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a function, else `false`.\n * @example\n *\n * _.isFunction(_);\n * // => true\n *\n * _.isFunction(/abc/);\n * // => false\n */\n function isFunction(value) {\n if (!isObject(value)) {\n return false;\n }\n // The use of `Object#toString` avoids issues with the `typeof` operator\n // in Safari 9 which returns 'object' for typed arrays and other constructors.\n var tag = baseGetTag(value);\n return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;\n }\n\n /**\n * Checks if `value` is an integer.\n *\n * **Note:** This method is based on\n * [`Number.isInteger`](https://mdn.io/Number/isInteger).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an integer, else `false`.\n * @example\n *\n * _.isInteger(3);\n * // => true\n *\n * _.isInteger(Number.MIN_VALUE);\n * // => false\n *\n * _.isInteger(Infinity);\n * // => false\n *\n * _.isInteger('3');\n * // => false\n */\n function isInteger(value) {\n return typeof value == 'number' && value == toInteger(value);\n }\n\n /**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\n function isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n }\n\n /**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\n function isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n }\n\n /**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\n function isObjectLike(value) {\n return value != null && typeof value == 'object';\n }\n\n /**\n * Checks if `value` is classified as a `Map` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a map, else `false`.\n * @example\n *\n * _.isMap(new Map);\n * // => true\n *\n * _.isMap(new WeakMap);\n * // => false\n */\n var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap;\n\n /**\n * Performs a partial deep comparison between `object` and `source` to\n * determine if `object` contains equivalent property values.\n *\n * **Note:** This method is equivalent to `_.matches` when `source` is\n * partially applied.\n *\n * Partial comparisons will match empty array and empty object `source`\n * values against any array or object value, respectively. See `_.isEqual`\n * for a list of supported value comparisons.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {Object} object The object to inspect.\n * @param {Object} source The object of property values to match.\n * @returns {boolean} Returns `true` if `object` is a match, else `false`.\n * @example\n *\n * var object = { 'a': 1, 'b': 2 };\n *\n * _.isMatch(object, { 'b': 2 });\n * // => true\n *\n * _.isMatch(object, { 'b': 1 });\n * // => false\n */\n function isMatch(object, source) {\n return object === source || baseIsMatch(object, source, getMatchData(source));\n }\n\n /**\n * This method is like `_.isMatch` except that it accepts `customizer` which\n * is invoked to compare values. If `customizer` returns `undefined`, comparisons\n * are handled by the method instead. The `customizer` is invoked with five\n * arguments: (objValue, srcValue, index|key, object, source).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {Object} object The object to inspect.\n * @param {Object} source The object of property values to match.\n * @param {Function} [customizer] The function to customize comparisons.\n * @returns {boolean} Returns `true` if `object` is a match, else `false`.\n * @example\n *\n * function isGreeting(value) {\n * return /^h(?:i|ello)$/.test(value);\n * }\n *\n * function customizer(objValue, srcValue) {\n * if (isGreeting(objValue) && isGreeting(srcValue)) {\n * return true;\n * }\n * }\n *\n * var object = { 'greeting': 'hello' };\n * var source = { 'greeting': 'hi' };\n *\n * _.isMatchWith(object, source, customizer);\n * // => true\n */\n function isMatchWith(object, source, customizer) {\n customizer = typeof customizer == 'function' ? customizer : undefined;\n return baseIsMatch(object, source, getMatchData(source), customizer);\n }\n\n /**\n * Checks if `value` is `NaN`.\n *\n * **Note:** This method is based on\n * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as\n * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for\n * `undefined` and other non-number values.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.\n * @example\n *\n * _.isNaN(NaN);\n * // => true\n *\n * _.isNaN(new Number(NaN));\n * // => true\n *\n * isNaN(undefined);\n * // => true\n *\n * _.isNaN(undefined);\n * // => false\n */\n function isNaN(value) {\n // An `NaN` primitive is the only value that is not equal to itself.\n // Perform the `toStringTag` check first to avoid errors with some\n // ActiveX objects in IE.\n return isNumber(value) && value != +value;\n }\n\n /**\n * Checks if `value` is a pristine native function.\n *\n * **Note:** This method can't reliably detect native functions in the presence\n * of the core-js package because core-js circumvents this kind of detection.\n * Despite multiple requests, the core-js maintainer has made it clear: any\n * attempt to fix the detection will be obstructed. As a result, we're left\n * with little choice but to throw an error. Unfortunately, this also affects\n * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill),\n * which rely on core-js.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a native function,\n * else `false`.\n * @example\n *\n * _.isNative(Array.prototype.push);\n * // => true\n *\n * _.isNative(_);\n * // => false\n */\n function isNative(value) {\n if (isMaskable(value)) {\n throw new Error(CORE_ERROR_TEXT);\n }\n return baseIsNative(value);\n }\n\n /**\n * Checks if `value` is `null`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `null`, else `false`.\n * @example\n *\n * _.isNull(null);\n * // => true\n *\n * _.isNull(void 0);\n * // => false\n */\n function isNull(value) {\n return value === null;\n }\n\n /**\n * Checks if `value` is `null` or `undefined`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is nullish, else `false`.\n * @example\n *\n * _.isNil(null);\n * // => true\n *\n * _.isNil(void 0);\n * // => true\n *\n * _.isNil(NaN);\n * // => false\n */\n function isNil(value) {\n return value == null;\n }\n\n /**\n * Checks if `value` is classified as a `Number` primitive or object.\n *\n * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are\n * classified as numbers, use the `_.isFinite` method.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a number, else `false`.\n * @example\n *\n * _.isNumber(3);\n * // => true\n *\n * _.isNumber(Number.MIN_VALUE);\n * // => true\n *\n * _.isNumber(Infinity);\n * // => true\n *\n * _.isNumber('3');\n * // => false\n */\n function isNumber(value) {\n return typeof value == 'number' ||\n (isObjectLike(value) && baseGetTag(value) == numberTag);\n }\n\n /**\n * Checks if `value` is a plain object, that is, an object created by the\n * `Object` constructor or one with a `[[Prototype]]` of `null`.\n *\n * @static\n * @memberOf _\n * @since 0.8.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * }\n *\n * _.isPlainObject(new Foo);\n * // => false\n *\n * _.isPlainObject([1, 2, 3]);\n * // => false\n *\n * _.isPlainObject({ 'x': 0, 'y': 0 });\n * // => true\n *\n * _.isPlainObject(Object.create(null));\n * // => true\n */\n function isPlainObject(value) {\n if (!isObjectLike(value) || baseGetTag(value) != objectTag) {\n return false;\n }\n var proto = getPrototype(value);\n if (proto === null) {\n return true;\n }\n var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;\n return typeof Ctor == 'function' && Ctor instanceof Ctor &&\n funcToString.call(Ctor) == objectCtorString;\n }\n\n /**\n * Checks if `value` is classified as a `RegExp` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a regexp, else `false`.\n * @example\n *\n * _.isRegExp(/abc/);\n * // => true\n *\n * _.isRegExp('/abc/');\n * // => false\n */\n var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp;\n\n /**\n * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754\n * double precision number which isn't the result of a rounded unsafe integer.\n *\n * **Note:** This method is based on\n * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`.\n * @example\n *\n * _.isSafeInteger(3);\n * // => true\n *\n * _.isSafeInteger(Number.MIN_VALUE);\n * // => false\n *\n * _.isSafeInteger(Infinity);\n * // => false\n *\n * _.isSafeInteger('3');\n * // => false\n */\n function isSafeInteger(value) {\n return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER;\n }\n\n /**\n * Checks if `value` is classified as a `Set` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a set, else `false`.\n * @example\n *\n * _.isSet(new Set);\n * // => true\n *\n * _.isSet(new WeakSet);\n * // => false\n */\n var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet;\n\n /**\n * Checks if `value` is classified as a `String` primitive or object.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a string, else `false`.\n * @example\n *\n * _.isString('abc');\n * // => true\n *\n * _.isString(1);\n * // => false\n */\n function isString(value) {\n return typeof value == 'string' ||\n (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag);\n }\n\n /**\n * Checks if `value` is classified as a `Symbol` primitive or object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.\n * @example\n *\n * _.isSymbol(Symbol.iterator);\n * // => true\n *\n * _.isSymbol('abc');\n * // => false\n */\n function isSymbol(value) {\n return typeof value == 'symbol' ||\n (isObjectLike(value) && baseGetTag(value) == symbolTag);\n }\n\n /**\n * Checks if `value` is classified as a typed array.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n * @example\n *\n * _.isTypedArray(new Uint8Array);\n * // => true\n *\n * _.isTypedArray([]);\n * // => false\n */\n var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;\n\n /**\n * Checks if `value` is `undefined`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.\n * @example\n *\n * _.isUndefined(void 0);\n * // => true\n *\n * _.isUndefined(null);\n * // => false\n */\n function isUndefined(value) {\n return value === undefined;\n }\n\n /**\n * Checks if `value` is classified as a `WeakMap` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a weak map, else `false`.\n * @example\n *\n * _.isWeakMap(new WeakMap);\n * // => true\n *\n * _.isWeakMap(new Map);\n * // => false\n */\n function isWeakMap(value) {\n return isObjectLike(value) && getTag(value) == weakMapTag;\n }\n\n /**\n * Checks if `value` is classified as a `WeakSet` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a weak set, else `false`.\n * @example\n *\n * _.isWeakSet(new WeakSet);\n * // => true\n *\n * _.isWeakSet(new Set);\n * // => false\n */\n function isWeakSet(value) {\n return isObjectLike(value) && baseGetTag(value) == weakSetTag;\n }\n\n /**\n * Checks if `value` is less than `other`.\n *\n * @static\n * @memberOf _\n * @since 3.9.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if `value` is less than `other`,\n * else `false`.\n * @see _.gt\n * @example\n *\n * _.lt(1, 3);\n * // => true\n *\n * _.lt(3, 3);\n * // => false\n *\n * _.lt(3, 1);\n * // => false\n */\n var lt = createRelationalOperation(baseLt);\n\n /**\n * Checks if `value` is less than or equal to `other`.\n *\n * @static\n * @memberOf _\n * @since 3.9.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if `value` is less than or equal to\n * `other`, else `false`.\n * @see _.gte\n * @example\n *\n * _.lte(1, 3);\n * // => true\n *\n * _.lte(3, 3);\n * // => true\n *\n * _.lte(3, 1);\n * // => false\n */\n var lte = createRelationalOperation(function(value, other) {\n return value <= other;\n });\n\n /**\n * Converts `value` to an array.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {Array} Returns the converted array.\n * @example\n *\n * _.toArray({ 'a': 1, 'b': 2 });\n * // => [1, 2]\n *\n * _.toArray('abc');\n * // => ['a', 'b', 'c']\n *\n * _.toArray(1);\n * // => []\n *\n * _.toArray(null);\n * // => []\n */\n function toArray(value) {\n if (!value) {\n return [];\n }\n if (isArrayLike(value)) {\n return isString(value) ? stringToArray(value) : copyArray(value);\n }\n if (symIterator && value[symIterator]) {\n return iteratorToArray(value[symIterator]());\n }\n var tag = getTag(value),\n func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values);\n\n return func(value);\n }\n\n /**\n * Converts `value` to a finite number.\n *\n * @static\n * @memberOf _\n * @since 4.12.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {number} Returns the converted number.\n * @example\n *\n * _.toFinite(3.2);\n * // => 3.2\n *\n * _.toFinite(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toFinite(Infinity);\n * // => 1.7976931348623157e+308\n *\n * _.toFinite('3.2');\n * // => 3.2\n */\n function toFinite(value) {\n if (!value) {\n return value === 0 ? value : 0;\n }\n value = toNumber(value);\n if (value === INFINITY || value === -INFINITY) {\n var sign = (value < 0 ? -1 : 1);\n return sign * MAX_INTEGER;\n }\n return value === value ? value : 0;\n }\n\n /**\n * Converts `value` to an integer.\n *\n * **Note:** This method is loosely based on\n * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {number} Returns the converted integer.\n * @example\n *\n * _.toInteger(3.2);\n * // => 3\n *\n * _.toInteger(Number.MIN_VALUE);\n * // => 0\n *\n * _.toInteger(Infinity);\n * // => 1.7976931348623157e+308\n *\n * _.toInteger('3.2');\n * // => 3\n */\n function toInteger(value) {\n var result = toFinite(value),\n remainder = result % 1;\n\n return result === result ? (remainder ? result - remainder : result) : 0;\n }\n\n /**\n * Converts `value` to an integer suitable for use as the length of an\n * array-like object.\n *\n * **Note:** This method is based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {number} Returns the converted integer.\n * @example\n *\n * _.toLength(3.2);\n * // => 3\n *\n * _.toLength(Number.MIN_VALUE);\n * // => 0\n *\n * _.toLength(Infinity);\n * // => 4294967295\n *\n * _.toLength('3.2');\n * // => 3\n */\n function toLength(value) {\n return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0;\n }\n\n /**\n * Converts `value` to a number.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to process.\n * @returns {number} Returns the number.\n * @example\n *\n * _.toNumber(3.2);\n * // => 3.2\n *\n * _.toNumber(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toNumber(Infinity);\n * // => Infinity\n *\n * _.toNumber('3.2');\n * // => 3.2\n */\n function toNumber(value) {\n if (typeof value == 'number') {\n return value;\n }\n if (isSymbol(value)) {\n return NAN;\n }\n if (isObject(value)) {\n var other = typeof value.valueOf == 'function' ? value.valueOf() : value;\n value = isObject(other) ? (other + '') : other;\n }\n if (typeof value != 'string') {\n return value === 0 ? value : +value;\n }\n value = baseTrim(value);\n var isBinary = reIsBinary.test(value);\n return (isBinary || reIsOctal.test(value))\n ? freeParseInt(value.slice(2), isBinary ? 2 : 8)\n : (reIsBadHex.test(value) ? NAN : +value);\n }\n\n /**\n * Converts `value` to a plain object flattening inherited enumerable string\n * keyed properties of `value` to own properties of the plain object.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {Object} Returns the converted plain object.\n * @example\n *\n * function Foo() {\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.assign({ 'a': 1 }, new Foo);\n * // => { 'a': 1, 'b': 2 }\n *\n * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));\n * // => { 'a': 1, 'b': 2, 'c': 3 }\n */\n function toPlainObject(value) {\n return copyObject(value, keysIn(value));\n }\n\n /**\n * Converts `value` to a safe integer. A safe integer can be compared and\n * represented correctly.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {number} Returns the converted integer.\n * @example\n *\n * _.toSafeInteger(3.2);\n * // => 3\n *\n * _.toSafeInteger(Number.MIN_VALUE);\n * // => 0\n *\n * _.toSafeInteger(Infinity);\n * // => 9007199254740991\n *\n * _.toSafeInteger('3.2');\n * // => 3\n */\n function toSafeInteger(value) {\n return value\n ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER)\n : (value === 0 ? value : 0);\n }\n\n /**\n * Converts `value` to a string. An empty string is returned for `null`\n * and `undefined` values. The sign of `-0` is preserved.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n * @example\n *\n * _.toString(null);\n * // => ''\n *\n * _.toString(-0);\n * // => '-0'\n *\n * _.toString([1, 2, 3]);\n * // => '1,2,3'\n */\n function toString(value) {\n return value == null ? '' : baseToString(value);\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Assigns own enumerable string keyed properties of source objects to the\n * destination object. Source objects are applied from left to right.\n * Subsequent sources overwrite property assignments of previous sources.\n *\n * **Note:** This method mutates `object` and is loosely based on\n * [`Object.assign`](https://mdn.io/Object/assign).\n *\n * @static\n * @memberOf _\n * @since 0.10.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @see _.assignIn\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * }\n *\n * function Bar() {\n * this.c = 3;\n * }\n *\n * Foo.prototype.b = 2;\n * Bar.prototype.d = 4;\n *\n * _.assign({ 'a': 0 }, new Foo, new Bar);\n * // => { 'a': 1, 'c': 3 }\n */\n var assign = createAssigner(function(object, source) {\n if (isPrototype(source) || isArrayLike(source)) {\n copyObject(source, keys(source), object);\n return;\n }\n for (var key in source) {\n if (hasOwnProperty.call(source, key)) {\n assignValue(object, key, source[key]);\n }\n }\n });\n\n /**\n * This method is like `_.assign` except that it iterates over own and\n * inherited source properties.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @alias extend\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @see _.assign\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * }\n *\n * function Bar() {\n * this.c = 3;\n * }\n *\n * Foo.prototype.b = 2;\n * Bar.prototype.d = 4;\n *\n * _.assignIn({ 'a': 0 }, new Foo, new Bar);\n * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }\n */\n var assignIn = createAssigner(function(object, source) {\n copyObject(source, keysIn(source), object);\n });\n\n /**\n * This method is like `_.assignIn` except that it accepts `customizer`\n * which is invoked to produce the assigned values. If `customizer` returns\n * `undefined`, assignment is handled by the method instead. The `customizer`\n * is invoked with five arguments: (objValue, srcValue, key, object, source).\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @alias extendWith\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} sources The source objects.\n * @param {Function} [customizer] The function to customize assigned values.\n * @returns {Object} Returns `object`.\n * @see _.assignWith\n * @example\n *\n * function customizer(objValue, srcValue) {\n * return _.isUndefined(objValue) ? srcValue : objValue;\n * }\n *\n * var defaults = _.partialRight(_.assignInWith, customizer);\n *\n * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });\n * // => { 'a': 1, 'b': 2 }\n */\n var assignInWith = createAssigner(function(object, source, srcIndex, customizer) {\n copyObject(source, keysIn(source), object, customizer);\n });\n\n /**\n * This method is like `_.assign` except that it accepts `customizer`\n * which is invoked to produce the assigned values. If `customizer` returns\n * `undefined`, assignment is handled by the method instead. The `customizer`\n * is invoked with five arguments: (objValue, srcValue, key, object, source).\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} sources The source objects.\n * @param {Function} [customizer] The function to customize assigned values.\n * @returns {Object} Returns `object`.\n * @see _.assignInWith\n * @example\n *\n * function customizer(objValue, srcValue) {\n * return _.isUndefined(objValue) ? srcValue : objValue;\n * }\n *\n * var defaults = _.partialRight(_.assignWith, customizer);\n *\n * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });\n * // => { 'a': 1, 'b': 2 }\n */\n var assignWith = createAssigner(function(object, source, srcIndex, customizer) {\n copyObject(source, keys(source), object, customizer);\n });\n\n /**\n * Creates an array of values corresponding to `paths` of `object`.\n *\n * @static\n * @memberOf _\n * @since 1.0.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {...(string|string[])} [paths] The property paths to pick.\n * @returns {Array} Returns the picked values.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };\n *\n * _.at(object, ['a[0].b.c', 'a[1]']);\n * // => [3, 4]\n */\n var at = flatRest(baseAt);\n\n /**\n * Creates an object that inherits from the `prototype` object. If a\n * `properties` object is given, its own enumerable string keyed properties\n * are assigned to the created object.\n *\n * @static\n * @memberOf _\n * @since 2.3.0\n * @category Object\n * @param {Object} prototype The object to inherit from.\n * @param {Object} [properties] The properties to assign to the object.\n * @returns {Object} Returns the new object.\n * @example\n *\n * function Shape() {\n * this.x = 0;\n * this.y = 0;\n * }\n *\n * function Circle() {\n * Shape.call(this);\n * }\n *\n * Circle.prototype = _.create(Shape.prototype, {\n * 'constructor': Circle\n * });\n *\n * var circle = new Circle;\n * circle instanceof Circle;\n * // => true\n *\n * circle instanceof Shape;\n * // => true\n */\n function create(prototype, properties) {\n var result = baseCreate(prototype);\n return properties == null ? result : baseAssign(result, properties);\n }\n\n /**\n * Assigns own and inherited enumerable string keyed properties of source\n * objects to the destination object for all destination properties that\n * resolve to `undefined`. Source objects are applied from left to right.\n * Once a property is set, additional values of the same property are ignored.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @see _.defaultsDeep\n * @example\n *\n * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });\n * // => { 'a': 1, 'b': 2 }\n */\n var defaults = baseRest(function(object, sources) {\n object = Object(object);\n\n var index = -1;\n var length = sources.length;\n var guard = length > 2 ? sources[2] : undefined;\n\n if (guard && isIterateeCall(sources[0], sources[1], guard)) {\n length = 1;\n }\n\n while (++index < length) {\n var source = sources[index];\n var props = keysIn(source);\n var propsIndex = -1;\n var propsLength = props.length;\n\n while (++propsIndex < propsLength) {\n var key = props[propsIndex];\n var value = object[key];\n\n if (value === undefined ||\n (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) {\n object[key] = source[key];\n }\n }\n }\n\n return object;\n });\n\n /**\n * This method is like `_.defaults` except that it recursively assigns\n * default properties.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 3.10.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @see _.defaults\n * @example\n *\n * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } });\n * // => { 'a': { 'b': 2, 'c': 3 } }\n */\n var defaultsDeep = baseRest(function(args) {\n args.push(undefined, customDefaultsMerge);\n return apply(mergeWith, undefined, args);\n });\n\n /**\n * This method is like `_.find` except that it returns the key of the first\n * element `predicate` returns truthy for instead of the element itself.\n *\n * @static\n * @memberOf _\n * @since 1.1.0\n * @category Object\n * @param {Object} object The object to inspect.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {string|undefined} Returns the key of the matched element,\n * else `undefined`.\n * @example\n *\n * var users = {\n * 'barney': { 'age': 36, 'active': true },\n * 'fred': { 'age': 40, 'active': false },\n * 'pebbles': { 'age': 1, 'active': true }\n * };\n *\n * _.findKey(users, function(o) { return o.age < 40; });\n * // => 'barney' (iteration order is not guaranteed)\n *\n * // The `_.matches` iteratee shorthand.\n * _.findKey(users, { 'age': 1, 'active': true });\n * // => 'pebbles'\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.findKey(users, ['active', false]);\n * // => 'fred'\n *\n * // The `_.property` iteratee shorthand.\n * _.findKey(users, 'active');\n * // => 'barney'\n */\n function findKey(object, predicate) {\n return baseFindKey(object, getIteratee(predicate, 3), baseForOwn);\n }\n\n /**\n * This method is like `_.findKey` except that it iterates over elements of\n * a collection in the opposite order.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Object\n * @param {Object} object The object to inspect.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {string|undefined} Returns the key of the matched element,\n * else `undefined`.\n * @example\n *\n * var users = {\n * 'barney': { 'age': 36, 'active': true },\n * 'fred': { 'age': 40, 'active': false },\n * 'pebbles': { 'age': 1, 'active': true }\n * };\n *\n * _.findLastKey(users, function(o) { return o.age < 40; });\n * // => returns 'pebbles' assuming `_.findKey` returns 'barney'\n *\n * // The `_.matches` iteratee shorthand.\n * _.findLastKey(users, { 'age': 36, 'active': true });\n * // => 'barney'\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.findLastKey(users, ['active', false]);\n * // => 'fred'\n *\n * // The `_.property` iteratee shorthand.\n * _.findLastKey(users, 'active');\n * // => 'pebbles'\n */\n function findLastKey(object, predicate) {\n return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight);\n }\n\n /**\n * Iterates over own and inherited enumerable string keyed properties of an\n * object and invokes `iteratee` for each property. The iteratee is invoked\n * with three arguments: (value, key, object). Iteratee functions may exit\n * iteration early by explicitly returning `false`.\n *\n * @static\n * @memberOf _\n * @since 0.3.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Object} Returns `object`.\n * @see _.forInRight\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.forIn(new Foo, function(value, key) {\n * console.log(key);\n * });\n * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed).\n */\n function forIn(object, iteratee) {\n return object == null\n ? object\n : baseFor(object, getIteratee(iteratee, 3), keysIn);\n }\n\n /**\n * This method is like `_.forIn` except that it iterates over properties of\n * `object` in the opposite order.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Object} Returns `object`.\n * @see _.forIn\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.forInRight(new Foo, function(value, key) {\n * console.log(key);\n * });\n * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'.\n */\n function forInRight(object, iteratee) {\n return object == null\n ? object\n : baseForRight(object, getIteratee(iteratee, 3), keysIn);\n }\n\n /**\n * Iterates over own enumerable string keyed properties of an object and\n * invokes `iteratee` for each property. The iteratee is invoked with three\n * arguments: (value, key, object). Iteratee functions may exit iteration\n * early by explicitly returning `false`.\n *\n * @static\n * @memberOf _\n * @since 0.3.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Object} Returns `object`.\n * @see _.forOwnRight\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.forOwn(new Foo, function(value, key) {\n * console.log(key);\n * });\n * // => Logs 'a' then 'b' (iteration order is not guaranteed).\n */\n function forOwn(object, iteratee) {\n return object && baseForOwn(object, getIteratee(iteratee, 3));\n }\n\n /**\n * This method is like `_.forOwn` except that it iterates over properties of\n * `object` in the opposite order.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Object} Returns `object`.\n * @see _.forOwn\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.forOwnRight(new Foo, function(value, key) {\n * console.log(key);\n * });\n * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'.\n */\n function forOwnRight(object, iteratee) {\n return object && baseForOwnRight(object, getIteratee(iteratee, 3));\n }\n\n /**\n * Creates an array of function property names from own enumerable properties\n * of `object`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to inspect.\n * @returns {Array} Returns the function names.\n * @see _.functionsIn\n * @example\n *\n * function Foo() {\n * this.a = _.constant('a');\n * this.b = _.constant('b');\n * }\n *\n * Foo.prototype.c = _.constant('c');\n *\n * _.functions(new Foo);\n * // => ['a', 'b']\n */\n function functions(object) {\n return object == null ? [] : baseFunctions(object, keys(object));\n }\n\n /**\n * Creates an array of function property names from own and inherited\n * enumerable properties of `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to inspect.\n * @returns {Array} Returns the function names.\n * @see _.functions\n * @example\n *\n * function Foo() {\n * this.a = _.constant('a');\n * this.b = _.constant('b');\n * }\n *\n * Foo.prototype.c = _.constant('c');\n *\n * _.functionsIn(new Foo);\n * // => ['a', 'b', 'c']\n */\n function functionsIn(object) {\n return object == null ? [] : baseFunctions(object, keysIn(object));\n }\n\n /**\n * Gets the value at `path` of `object`. If the resolved value is\n * `undefined`, the `defaultValue` is returned in its place.\n *\n * @static\n * @memberOf _\n * @since 3.7.0\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the property to get.\n * @param {*} [defaultValue] The value returned for `undefined` resolved values.\n * @returns {*} Returns the resolved value.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }] };\n *\n * _.get(object, 'a[0].b.c');\n * // => 3\n *\n * _.get(object, ['a', '0', 'b', 'c']);\n * // => 3\n *\n * _.get(object, 'a.b.c', 'default');\n * // => 'default'\n */\n function get(object, path, defaultValue) {\n var result = object == null ? undefined : baseGet(object, path);\n return result === undefined ? defaultValue : result;\n }\n\n /**\n * Checks if `path` is a direct property of `object`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path to check.\n * @returns {boolean} Returns `true` if `path` exists, else `false`.\n * @example\n *\n * var object = { 'a': { 'b': 2 } };\n * var other = _.create({ 'a': _.create({ 'b': 2 }) });\n *\n * _.has(object, 'a');\n * // => true\n *\n * _.has(object, 'a.b');\n * // => true\n *\n * _.has(object, ['a', 'b']);\n * // => true\n *\n * _.has(other, 'a');\n * // => false\n */\n function has(object, path) {\n return object != null && hasPath(object, path, baseHas);\n }\n\n /**\n * Checks if `path` is a direct or inherited property of `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path to check.\n * @returns {boolean} Returns `true` if `path` exists, else `false`.\n * @example\n *\n * var object = _.create({ 'a': _.create({ 'b': 2 }) });\n *\n * _.hasIn(object, 'a');\n * // => true\n *\n * _.hasIn(object, 'a.b');\n * // => true\n *\n * _.hasIn(object, ['a', 'b']);\n * // => true\n *\n * _.hasIn(object, 'b');\n * // => false\n */\n function hasIn(object, path) {\n return object != null && hasPath(object, path, baseHasIn);\n }\n\n /**\n * Creates an object composed of the inverted keys and values of `object`.\n * If `object` contains duplicate values, subsequent values overwrite\n * property assignments of previous values.\n *\n * @static\n * @memberOf _\n * @since 0.7.0\n * @category Object\n * @param {Object} object The object to invert.\n * @returns {Object} Returns the new inverted object.\n * @example\n *\n * var object = { 'a': 1, 'b': 2, 'c': 1 };\n *\n * _.invert(object);\n * // => { '1': 'c', '2': 'b' }\n */\n var invert = createInverter(function(result, value, key) {\n if (value != null &&\n typeof value.toString != 'function') {\n value = nativeObjectToString.call(value);\n }\n\n result[value] = key;\n }, constant(identity));\n\n /**\n * This method is like `_.invert` except that the inverted object is generated\n * from the results of running each element of `object` thru `iteratee`. The\n * corresponding inverted value of each inverted key is an array of keys\n * responsible for generating the inverted value. The iteratee is invoked\n * with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 4.1.0\n * @category Object\n * @param {Object} object The object to invert.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Object} Returns the new inverted object.\n * @example\n *\n * var object = { 'a': 1, 'b': 2, 'c': 1 };\n *\n * _.invertBy(object);\n * // => { '1': ['a', 'c'], '2': ['b'] }\n *\n * _.invertBy(object, function(value) {\n * return 'group' + value;\n * });\n * // => { 'group1': ['a', 'c'], 'group2': ['b'] }\n */\n var invertBy = createInverter(function(result, value, key) {\n if (value != null &&\n typeof value.toString != 'function') {\n value = nativeObjectToString.call(value);\n }\n\n if (hasOwnProperty.call(result, value)) {\n result[value].push(key);\n } else {\n result[value] = [key];\n }\n }, getIteratee);\n\n /**\n * Invokes the method at `path` of `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the method to invoke.\n * @param {...*} [args] The arguments to invoke the method with.\n * @returns {*} Returns the result of the invoked method.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] };\n *\n * _.invoke(object, 'a[0].b.c.slice', 1, 3);\n * // => [2, 3]\n */\n var invoke = baseRest(baseInvoke);\n\n /**\n * Creates an array of the own enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects. See the\n * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * for more details.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keys(new Foo);\n * // => ['a', 'b'] (iteration order is not guaranteed)\n *\n * _.keys('hi');\n * // => ['0', '1']\n */\n function keys(object) {\n return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);\n }\n\n /**\n * Creates an array of the own and inherited enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keysIn(new Foo);\n * // => ['a', 'b', 'c'] (iteration order is not guaranteed)\n */\n function keysIn(object) {\n return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);\n }\n\n /**\n * The opposite of `_.mapValues`; this method creates an object with the\n * same values as `object` and keys generated by running each own enumerable\n * string keyed property of `object` thru `iteratee`. The iteratee is invoked\n * with three arguments: (value, key, object).\n *\n * @static\n * @memberOf _\n * @since 3.8.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Object} Returns the new mapped object.\n * @see _.mapValues\n * @example\n *\n * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {\n * return key + value;\n * });\n * // => { 'a1': 1, 'b2': 2 }\n */\n function mapKeys(object, iteratee) {\n var result = {};\n iteratee = getIteratee(iteratee, 3);\n\n baseForOwn(object, function(value, key, object) {\n baseAssignValue(result, iteratee(value, key, object), value);\n });\n return result;\n }\n\n /**\n * Creates an object with the same keys as `object` and values generated\n * by running each own enumerable string keyed property of `object` thru\n * `iteratee`. The iteratee is invoked with three arguments:\n * (value, key, object).\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Object} Returns the new mapped object.\n * @see _.mapKeys\n * @example\n *\n * var users = {\n * 'fred': { 'user': 'fred', 'age': 40 },\n * 'pebbles': { 'user': 'pebbles', 'age': 1 }\n * };\n *\n * _.mapValues(users, function(o) { return o.age; });\n * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)\n *\n * // The `_.property` iteratee shorthand.\n * _.mapValues(users, 'age');\n * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)\n */\n function mapValues(object, iteratee) {\n var result = {};\n iteratee = getIteratee(iteratee, 3);\n\n baseForOwn(object, function(value, key, object) {\n baseAssignValue(result, key, iteratee(value, key, object));\n });\n return result;\n }\n\n /**\n * This method is like `_.assign` except that it recursively merges own and\n * inherited enumerable string keyed properties of source objects into the\n * destination object. Source properties that resolve to `undefined` are\n * skipped if a destination value exists. Array and plain object properties\n * are merged recursively. Other objects and value types are overridden by\n * assignment. Source objects are applied from left to right. Subsequent\n * sources overwrite property assignments of previous sources.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 0.5.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = {\n * 'a': [{ 'b': 2 }, { 'd': 4 }]\n * };\n *\n * var other = {\n * 'a': [{ 'c': 3 }, { 'e': 5 }]\n * };\n *\n * _.merge(object, other);\n * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }\n */\n var merge = createAssigner(function(object, source, srcIndex) {\n baseMerge(object, source, srcIndex);\n });\n\n /**\n * This method is like `_.merge` except that it accepts `customizer` which\n * is invoked to produce the merged values of the destination and source\n * properties. If `customizer` returns `undefined`, merging is handled by the\n * method instead. The `customizer` is invoked with six arguments:\n * (objValue, srcValue, key, object, source, stack).\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} sources The source objects.\n * @param {Function} customizer The function to customize assigned values.\n * @returns {Object} Returns `object`.\n * @example\n *\n * function customizer(objValue, srcValue) {\n * if (_.isArray(objValue)) {\n * return objValue.concat(srcValue);\n * }\n * }\n *\n * var object = { 'a': [1], 'b': [2] };\n * var other = { 'a': [3], 'b': [4] };\n *\n * _.mergeWith(object, other, customizer);\n * // => { 'a': [1, 3], 'b': [2, 4] }\n */\n var mergeWith = createAssigner(function(object, source, srcIndex, customizer) {\n baseMerge(object, source, srcIndex, customizer);\n });\n\n /**\n * The opposite of `_.pick`; this method creates an object composed of the\n * own and inherited enumerable property paths of `object` that are not omitted.\n *\n * **Note:** This method is considerably slower than `_.pick`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The source object.\n * @param {...(string|string[])} [paths] The property paths to omit.\n * @returns {Object} Returns the new object.\n * @example\n *\n * var object = { 'a': 1, 'b': '2', 'c': 3 };\n *\n * _.omit(object, ['a', 'c']);\n * // => { 'b': '2' }\n */\n var omit = flatRest(function(object, paths) {\n var result = {};\n if (object == null) {\n return result;\n }\n var isDeep = false;\n paths = arrayMap(paths, function(path) {\n path = castPath(path, object);\n isDeep || (isDeep = path.length > 1);\n return path;\n });\n copyObject(object, getAllKeysIn(object), result);\n if (isDeep) {\n result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone);\n }\n var length = paths.length;\n while (length--) {\n baseUnset(result, paths[length]);\n }\n return result;\n });\n\n /**\n * The opposite of `_.pickBy`; this method creates an object composed of\n * the own and inherited enumerable string keyed properties of `object` that\n * `predicate` doesn't return truthy for. The predicate is invoked with two\n * arguments: (value, key).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The source object.\n * @param {Function} [predicate=_.identity] The function invoked per property.\n * @returns {Object} Returns the new object.\n * @example\n *\n * var object = { 'a': 1, 'b': '2', 'c': 3 };\n *\n * _.omitBy(object, _.isNumber);\n * // => { 'b': '2' }\n */\n function omitBy(object, predicate) {\n return pickBy(object, negate(getIteratee(predicate)));\n }\n\n /**\n * Creates an object composed of the picked `object` properties.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The source object.\n * @param {...(string|string[])} [paths] The property paths to pick.\n * @returns {Object} Returns the new object.\n * @example\n *\n * var object = { 'a': 1, 'b': '2', 'c': 3 };\n *\n * _.pick(object, ['a', 'c']);\n * // => { 'a': 1, 'c': 3 }\n */\n var pick = flatRest(function(object, paths) {\n return object == null ? {} : basePick(object, paths);\n });\n\n /**\n * Creates an object composed of the `object` properties `predicate` returns\n * truthy for. The predicate is invoked with two arguments: (value, key).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The source object.\n * @param {Function} [predicate=_.identity] The function invoked per property.\n * @returns {Object} Returns the new object.\n * @example\n *\n * var object = { 'a': 1, 'b': '2', 'c': 3 };\n *\n * _.pickBy(object, _.isNumber);\n * // => { 'a': 1, 'c': 3 }\n */\n function pickBy(object, predicate) {\n if (object == null) {\n return {};\n }\n var props = arrayMap(getAllKeysIn(object), function(prop) {\n return [prop];\n });\n predicate = getIteratee(predicate);\n return basePickBy(object, props, function(value, path) {\n return predicate(value, path[0]);\n });\n }\n\n /**\n * This method is like `_.get` except that if the resolved value is a\n * function it's invoked with the `this` binding of its parent object and\n * its result is returned.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the property to resolve.\n * @param {*} [defaultValue] The value returned for `undefined` resolved values.\n * @returns {*} Returns the resolved value.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };\n *\n * _.result(object, 'a[0].b.c1');\n * // => 3\n *\n * _.result(object, 'a[0].b.c2');\n * // => 4\n *\n * _.result(object, 'a[0].b.c3', 'default');\n * // => 'default'\n *\n * _.result(object, 'a[0].b.c3', _.constant('default'));\n * // => 'default'\n */\n function result(object, path, defaultValue) {\n path = castPath(path, object);\n\n var index = -1,\n length = path.length;\n\n // Ensure the loop is entered when path is empty.\n if (!length) {\n length = 1;\n object = undefined;\n }\n while (++index < length) {\n var value = object == null ? undefined : object[toKey(path[index])];\n if (value === undefined) {\n index = length;\n value = defaultValue;\n }\n object = isFunction(value) ? value.call(object) : value;\n }\n return object;\n }\n\n /**\n * Sets the value at `path` of `object`. If a portion of `path` doesn't exist,\n * it's created. Arrays are created for missing index properties while objects\n * are created for all other missing properties. Use `_.setWith` to customize\n * `path` creation.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 3.7.0\n * @category Object\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }] };\n *\n * _.set(object, 'a[0].b.c', 4);\n * console.log(object.a[0].b.c);\n * // => 4\n *\n * _.set(object, ['x', '0', 'y', 'z'], 5);\n * console.log(object.x[0].y.z);\n * // => 5\n */\n function set(object, path, value) {\n return object == null ? object : baseSet(object, path, value);\n }\n\n /**\n * This method is like `_.set` except that it accepts `customizer` which is\n * invoked to produce the objects of `path`. If `customizer` returns `undefined`\n * path creation is handled by the method instead. The `customizer` is invoked\n * with three arguments: (nsValue, key, nsObject).\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to set.\n * @param {*} value The value to set.\n * @param {Function} [customizer] The function to customize assigned values.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = {};\n *\n * _.setWith(object, '[0][1]', 'a', Object);\n * // => { '0': { '1': 'a' } }\n */\n function setWith(object, path, value, customizer) {\n customizer = typeof customizer == 'function' ? customizer : undefined;\n return object == null ? object : baseSet(object, path, value, customizer);\n }\n\n /**\n * Creates an array of own enumerable string keyed-value pairs for `object`\n * which can be consumed by `_.fromPairs`. If `object` is a map or set, its\n * entries are returned.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @alias entries\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the key-value pairs.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.toPairs(new Foo);\n * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed)\n */\n var toPairs = createToPairs(keys);\n\n /**\n * Creates an array of own and inherited enumerable string keyed-value pairs\n * for `object` which can be consumed by `_.fromPairs`. If `object` is a map\n * or set, its entries are returned.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @alias entriesIn\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the key-value pairs.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.toPairsIn(new Foo);\n * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed)\n */\n var toPairsIn = createToPairs(keysIn);\n\n /**\n * An alternative to `_.reduce`; this method transforms `object` to a new\n * `accumulator` object which is the result of running each of its own\n * enumerable string keyed properties thru `iteratee`, with each invocation\n * potentially mutating the `accumulator` object. If `accumulator` is not\n * provided, a new object with the same `[[Prototype]]` will be used. The\n * iteratee is invoked with four arguments: (accumulator, value, key, object).\n * Iteratee functions may exit iteration early by explicitly returning `false`.\n *\n * @static\n * @memberOf _\n * @since 1.3.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @param {*} [accumulator] The custom accumulator value.\n * @returns {*} Returns the accumulated value.\n * @example\n *\n * _.transform([2, 3, 4], function(result, n) {\n * result.push(n *= n);\n * return n % 2 == 0;\n * }, []);\n * // => [4, 9]\n *\n * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {\n * (result[value] || (result[value] = [])).push(key);\n * }, {});\n * // => { '1': ['a', 'c'], '2': ['b'] }\n */\n function transform(object, iteratee, accumulator) {\n var isArr = isArray(object),\n isArrLike = isArr || isBuffer(object) || isTypedArray(object);\n\n iteratee = getIteratee(iteratee, 4);\n if (accumulator == null) {\n var Ctor = object && object.constructor;\n if (isArrLike) {\n accumulator = isArr ? new Ctor : [];\n }\n else if (isObject(object)) {\n accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {};\n }\n else {\n accumulator = {};\n }\n }\n (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) {\n return iteratee(accumulator, value, index, object);\n });\n return accumulator;\n }\n\n /**\n * Removes the property at `path` of `object`.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to unset.\n * @returns {boolean} Returns `true` if the property is deleted, else `false`.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 7 } }] };\n * _.unset(object, 'a[0].b.c');\n * // => true\n *\n * console.log(object);\n * // => { 'a': [{ 'b': {} }] };\n *\n * _.unset(object, ['a', '0', 'b', 'c']);\n * // => true\n *\n * console.log(object);\n * // => { 'a': [{ 'b': {} }] };\n */\n function unset(object, path) {\n return object == null ? true : baseUnset(object, path);\n }\n\n /**\n * This method is like `_.set` except that accepts `updater` to produce the\n * value to set. Use `_.updateWith` to customize `path` creation. The `updater`\n * is invoked with one argument: (value).\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.6.0\n * @category Object\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to set.\n * @param {Function} updater The function to produce the updated value.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }] };\n *\n * _.update(object, 'a[0].b.c', function(n) { return n * n; });\n * console.log(object.a[0].b.c);\n * // => 9\n *\n * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; });\n * console.log(object.x[0].y.z);\n * // => 0\n */\n function update(object, path, updater) {\n return object == null ? object : baseUpdate(object, path, castFunction(updater));\n }\n\n /**\n * This method is like `_.update` except that it accepts `customizer` which is\n * invoked to produce the objects of `path`. If `customizer` returns `undefined`\n * path creation is handled by the method instead. The `customizer` is invoked\n * with three arguments: (nsValue, key, nsObject).\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.6.0\n * @category Object\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to set.\n * @param {Function} updater The function to produce the updated value.\n * @param {Function} [customizer] The function to customize assigned values.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = {};\n *\n * _.updateWith(object, '[0][1]', _.constant('a'), Object);\n * // => { '0': { '1': 'a' } }\n */\n function updateWith(object, path, updater, customizer) {\n customizer = typeof customizer == 'function' ? customizer : undefined;\n return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer);\n }\n\n /**\n * Creates an array of the own enumerable string keyed property values of `object`.\n *\n * **Note:** Non-object values are coerced to objects.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property values.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.values(new Foo);\n * // => [1, 2] (iteration order is not guaranteed)\n *\n * _.values('hi');\n * // => ['h', 'i']\n */\n function values(object) {\n return object == null ? [] : baseValues(object, keys(object));\n }\n\n /**\n * Creates an array of the own and inherited enumerable string keyed property\n * values of `object`.\n *\n * **Note:** Non-object values are coerced to objects.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property values.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.valuesIn(new Foo);\n * // => [1, 2, 3] (iteration order is not guaranteed)\n */\n function valuesIn(object) {\n return object == null ? [] : baseValues(object, keysIn(object));\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Clamps `number` within the inclusive `lower` and `upper` bounds.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Number\n * @param {number} number The number to clamp.\n * @param {number} [lower] The lower bound.\n * @param {number} upper The upper bound.\n * @returns {number} Returns the clamped number.\n * @example\n *\n * _.clamp(-10, -5, 5);\n * // => -5\n *\n * _.clamp(10, -5, 5);\n * // => 5\n */\n function clamp(number, lower, upper) {\n if (upper === undefined) {\n upper = lower;\n lower = undefined;\n }\n if (upper !== undefined) {\n upper = toNumber(upper);\n upper = upper === upper ? upper : 0;\n }\n if (lower !== undefined) {\n lower = toNumber(lower);\n lower = lower === lower ? lower : 0;\n }\n return baseClamp(toNumber(number), lower, upper);\n }\n\n /**\n * Checks if `n` is between `start` and up to, but not including, `end`. If\n * `end` is not specified, it's set to `start` with `start` then set to `0`.\n * If `start` is greater than `end` the params are swapped to support\n * negative ranges.\n *\n * @static\n * @memberOf _\n * @since 3.3.0\n * @category Number\n * @param {number} number The number to check.\n * @param {number} [start=0] The start of the range.\n * @param {number} end The end of the range.\n * @returns {boolean} Returns `true` if `number` is in the range, else `false`.\n * @see _.range, _.rangeRight\n * @example\n *\n * _.inRange(3, 2, 4);\n * // => true\n *\n * _.inRange(4, 8);\n * // => true\n *\n * _.inRange(4, 2);\n * // => false\n *\n * _.inRange(2, 2);\n * // => false\n *\n * _.inRange(1.2, 2);\n * // => true\n *\n * _.inRange(5.2, 4);\n * // => false\n *\n * _.inRange(-3, -2, -6);\n * // => true\n */\n function inRange(number, start, end) {\n start = toFinite(start);\n if (end === undefined) {\n end = start;\n start = 0;\n } else {\n end = toFinite(end);\n }\n number = toNumber(number);\n return baseInRange(number, start, end);\n }\n\n /**\n * Produces a random number between the inclusive `lower` and `upper` bounds.\n * If only one argument is provided a number between `0` and the given number\n * is returned. If `floating` is `true`, or either `lower` or `upper` are\n * floats, a floating-point number is returned instead of an integer.\n *\n * **Note:** JavaScript follows the IEEE-754 standard for resolving\n * floating-point values which can produce unexpected results.\n *\n * @static\n * @memberOf _\n * @since 0.7.0\n * @category Number\n * @param {number} [lower=0] The lower bound.\n * @param {number} [upper=1] The upper bound.\n * @param {boolean} [floating] Specify returning a floating-point number.\n * @returns {number} Returns the random number.\n * @example\n *\n * _.random(0, 5);\n * // => an integer between 0 and 5\n *\n * _.random(5);\n * // => also an integer between 0 and 5\n *\n * _.random(5, true);\n * // => a floating-point number between 0 and 5\n *\n * _.random(1.2, 5.2);\n * // => a floating-point number between 1.2 and 5.2\n */\n function random(lower, upper, floating) {\n if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) {\n upper = floating = undefined;\n }\n if (floating === undefined) {\n if (typeof upper == 'boolean') {\n floating = upper;\n upper = undefined;\n }\n else if (typeof lower == 'boolean') {\n floating = lower;\n lower = undefined;\n }\n }\n if (lower === undefined && upper === undefined) {\n lower = 0;\n upper = 1;\n }\n else {\n lower = toFinite(lower);\n if (upper === undefined) {\n upper = lower;\n lower = 0;\n } else {\n upper = toFinite(upper);\n }\n }\n if (lower > upper) {\n var temp = lower;\n lower = upper;\n upper = temp;\n }\n if (floating || lower % 1 || upper % 1) {\n var rand = nativeRandom();\n return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper);\n }\n return baseRandom(lower, upper);\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the camel cased string.\n * @example\n *\n * _.camelCase('Foo Bar');\n * // => 'fooBar'\n *\n * _.camelCase('--foo-bar--');\n * // => 'fooBar'\n *\n * _.camelCase('__FOO_BAR__');\n * // => 'fooBar'\n */\n var camelCase = createCompounder(function(result, word, index) {\n word = word.toLowerCase();\n return result + (index ? capitalize(word) : word);\n });\n\n /**\n * Converts the first character of `string` to upper case and the remaining\n * to lower case.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to capitalize.\n * @returns {string} Returns the capitalized string.\n * @example\n *\n * _.capitalize('FRED');\n * // => 'Fred'\n */\n function capitalize(string) {\n return upperFirst(toString(string).toLowerCase());\n }\n\n /**\n * Deburrs `string` by converting\n * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)\n * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)\n * letters to basic Latin letters and removing\n * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to deburr.\n * @returns {string} Returns the deburred string.\n * @example\n *\n * _.deburr('déjà vu');\n * // => 'deja vu'\n */\n function deburr(string) {\n string = toString(string);\n return string && string.replace(reLatin, deburrLetter).replace(reComboMark, '');\n }\n\n /**\n * Checks if `string` ends with the given target string.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to inspect.\n * @param {string} [target] The string to search for.\n * @param {number} [position=string.length] The position to search up to.\n * @returns {boolean} Returns `true` if `string` ends with `target`,\n * else `false`.\n * @example\n *\n * _.endsWith('abc', 'c');\n * // => true\n *\n * _.endsWith('abc', 'b');\n * // => false\n *\n * _.endsWith('abc', 'b', 2);\n * // => true\n */\n function endsWith(string, target, position) {\n string = toString(string);\n target = baseToString(target);\n\n var length = string.length;\n position = position === undefined\n ? length\n : baseClamp(toInteger(position), 0, length);\n\n var end = position;\n position -= target.length;\n return position >= 0 && string.slice(position, end) == target;\n }\n\n /**\n * Converts the characters \"&\", \"<\", \">\", '\"', and \"'\" in `string` to their\n * corresponding HTML entities.\n *\n * **Note:** No other characters are escaped. To escape additional\n * characters use a third-party library like [_he_](https://mths.be/he).\n *\n * Though the \">\" character is escaped for symmetry, characters like\n * \">\" and \"/\" don't need escaping in HTML and have no special meaning\n * unless they're part of a tag or unquoted attribute value. See\n * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)\n * (under \"semi-related fun fact\") for more details.\n *\n * When working with HTML you should always\n * [quote attribute values](http://wonko.com/post/html-escaping) to reduce\n * XSS vectors.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category String\n * @param {string} [string=''] The string to escape.\n * @returns {string} Returns the escaped string.\n * @example\n *\n * _.escape('fred, barney, & pebbles');\n * // => 'fred, barney, & pebbles'\n */\n function escape(string) {\n string = toString(string);\n return (string && reHasUnescapedHtml.test(string))\n ? string.replace(reUnescapedHtml, escapeHtmlChar)\n : string;\n }\n\n /**\n * Escapes the `RegExp` special characters \"^\", \"$\", \"\\\", \".\", \"*\", \"+\",\n * \"?\", \"(\", \")\", \"[\", \"]\", \"{\", \"}\", and \"|\" in `string`.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to escape.\n * @returns {string} Returns the escaped string.\n * @example\n *\n * _.escapeRegExp('[lodash](https://lodash.com/)');\n * // => '\\[lodash\\]\\(https://lodash\\.com/\\)'\n */\n function escapeRegExp(string) {\n string = toString(string);\n return (string && reHasRegExpChar.test(string))\n ? string.replace(reRegExpChar, '\\\\$&')\n : string;\n }\n\n /**\n * Converts `string` to\n * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the kebab cased string.\n * @example\n *\n * _.kebabCase('Foo Bar');\n * // => 'foo-bar'\n *\n * _.kebabCase('fooBar');\n * // => 'foo-bar'\n *\n * _.kebabCase('__FOO_BAR__');\n * // => 'foo-bar'\n */\n var kebabCase = createCompounder(function(result, word, index) {\n return result + (index ? '-' : '') + word.toLowerCase();\n });\n\n /**\n * Converts `string`, as space separated words, to lower case.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the lower cased string.\n * @example\n *\n * _.lowerCase('--Foo-Bar--');\n * // => 'foo bar'\n *\n * _.lowerCase('fooBar');\n * // => 'foo bar'\n *\n * _.lowerCase('__FOO_BAR__');\n * // => 'foo bar'\n */\n var lowerCase = createCompounder(function(result, word, index) {\n return result + (index ? ' ' : '') + word.toLowerCase();\n });\n\n /**\n * Converts the first character of `string` to lower case.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the converted string.\n * @example\n *\n * _.lowerFirst('Fred');\n * // => 'fred'\n *\n * _.lowerFirst('FRED');\n * // => 'fRED'\n */\n var lowerFirst = createCaseFirst('toLowerCase');\n\n /**\n * Pads `string` on the left and right sides if it's shorter than `length`.\n * Padding characters are truncated if they can't be evenly divided by `length`.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to pad.\n * @param {number} [length=0] The padding length.\n * @param {string} [chars=' '] The string used as padding.\n * @returns {string} Returns the padded string.\n * @example\n *\n * _.pad('abc', 8);\n * // => ' abc '\n *\n * _.pad('abc', 8, '_-');\n * // => '_-abc_-_'\n *\n * _.pad('abc', 3);\n * // => 'abc'\n */\n function pad(string, length, chars) {\n string = toString(string);\n length = toInteger(length);\n\n var strLength = length ? stringSize(string) : 0;\n if (!length || strLength >= length) {\n return string;\n }\n var mid = (length - strLength) / 2;\n return (\n createPadding(nativeFloor(mid), chars) +\n string +\n createPadding(nativeCeil(mid), chars)\n );\n }\n\n /**\n * Pads `string` on the right side if it's shorter than `length`. Padding\n * characters are truncated if they exceed `length`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to pad.\n * @param {number} [length=0] The padding length.\n * @param {string} [chars=' '] The string used as padding.\n * @returns {string} Returns the padded string.\n * @example\n *\n * _.padEnd('abc', 6);\n * // => 'abc '\n *\n * _.padEnd('abc', 6, '_-');\n * // => 'abc_-_'\n *\n * _.padEnd('abc', 3);\n * // => 'abc'\n */\n function padEnd(string, length, chars) {\n string = toString(string);\n length = toInteger(length);\n\n var strLength = length ? stringSize(string) : 0;\n return (length && strLength < length)\n ? (string + createPadding(length - strLength, chars))\n : string;\n }\n\n /**\n * Pads `string` on the left side if it's shorter than `length`. Padding\n * characters are truncated if they exceed `length`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to pad.\n * @param {number} [length=0] The padding length.\n * @param {string} [chars=' '] The string used as padding.\n * @returns {string} Returns the padded string.\n * @example\n *\n * _.padStart('abc', 6);\n * // => ' abc'\n *\n * _.padStart('abc', 6, '_-');\n * // => '_-_abc'\n *\n * _.padStart('abc', 3);\n * // => 'abc'\n */\n function padStart(string, length, chars) {\n string = toString(string);\n length = toInteger(length);\n\n var strLength = length ? stringSize(string) : 0;\n return (length && strLength < length)\n ? (createPadding(length - strLength, chars) + string)\n : string;\n }\n\n /**\n * Converts `string` to an integer of the specified radix. If `radix` is\n * `undefined` or `0`, a `radix` of `10` is used unless `value` is a\n * hexadecimal, in which case a `radix` of `16` is used.\n *\n * **Note:** This method aligns with the\n * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`.\n *\n * @static\n * @memberOf _\n * @since 1.1.0\n * @category String\n * @param {string} string The string to convert.\n * @param {number} [radix=10] The radix to interpret `value` by.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {number} Returns the converted integer.\n * @example\n *\n * _.parseInt('08');\n * // => 8\n *\n * _.map(['6', '08', '10'], _.parseInt);\n * // => [6, 8, 10]\n */\n function parseInt(string, radix, guard) {\n if (guard || radix == null) {\n radix = 0;\n } else if (radix) {\n radix = +radix;\n }\n return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0);\n }\n\n /**\n * Repeats the given string `n` times.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to repeat.\n * @param {number} [n=1] The number of times to repeat the string.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {string} Returns the repeated string.\n * @example\n *\n * _.repeat('*', 3);\n * // => '***'\n *\n * _.repeat('abc', 2);\n * // => 'abcabc'\n *\n * _.repeat('abc', 0);\n * // => ''\n */\n function repeat(string, n, guard) {\n if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) {\n n = 1;\n } else {\n n = toInteger(n);\n }\n return baseRepeat(toString(string), n);\n }\n\n /**\n * Replaces matches for `pattern` in `string` with `replacement`.\n *\n * **Note:** This method is based on\n * [`String#replace`](https://mdn.io/String/replace).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to modify.\n * @param {RegExp|string} pattern The pattern to replace.\n * @param {Function|string} replacement The match replacement.\n * @returns {string} Returns the modified string.\n * @example\n *\n * _.replace('Hi Fred', 'Fred', 'Barney');\n * // => 'Hi Barney'\n */\n function replace() {\n var args = arguments,\n string = toString(args[0]);\n\n return args.length < 3 ? string : string.replace(args[1], args[2]);\n }\n\n /**\n * Converts `string` to\n * [snake case](https://en.wikipedia.org/wiki/Snake_case).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the snake cased string.\n * @example\n *\n * _.snakeCase('Foo Bar');\n * // => 'foo_bar'\n *\n * _.snakeCase('fooBar');\n * // => 'foo_bar'\n *\n * _.snakeCase('--FOO-BAR--');\n * // => 'foo_bar'\n */\n var snakeCase = createCompounder(function(result, word, index) {\n return result + (index ? '_' : '') + word.toLowerCase();\n });\n\n /**\n * Splits `string` by `separator`.\n *\n * **Note:** This method is based on\n * [`String#split`](https://mdn.io/String/split).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to split.\n * @param {RegExp|string} separator The separator pattern to split by.\n * @param {number} [limit] The length to truncate results to.\n * @returns {Array} Returns the string segments.\n * @example\n *\n * _.split('a-b-c', '-', 2);\n * // => ['a', 'b']\n */\n function split(string, separator, limit) {\n if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) {\n separator = limit = undefined;\n }\n limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0;\n if (!limit) {\n return [];\n }\n string = toString(string);\n if (string && (\n typeof separator == 'string' ||\n (separator != null && !isRegExp(separator))\n )) {\n separator = baseToString(separator);\n if (!separator && hasUnicode(string)) {\n return castSlice(stringToArray(string), 0, limit);\n }\n }\n return string.split(separator, limit);\n }\n\n /**\n * Converts `string` to\n * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage).\n *\n * @static\n * @memberOf _\n * @since 3.1.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the start cased string.\n * @example\n *\n * _.startCase('--foo-bar--');\n * // => 'Foo Bar'\n *\n * _.startCase('fooBar');\n * // => 'Foo Bar'\n *\n * _.startCase('__FOO_BAR__');\n * // => 'FOO BAR'\n */\n var startCase = createCompounder(function(result, word, index) {\n return result + (index ? ' ' : '') + upperFirst(word);\n });\n\n /**\n * Checks if `string` starts with the given target string.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to inspect.\n * @param {string} [target] The string to search for.\n * @param {number} [position=0] The position to search from.\n * @returns {boolean} Returns `true` if `string` starts with `target`,\n * else `false`.\n * @example\n *\n * _.startsWith('abc', 'a');\n * // => true\n *\n * _.startsWith('abc', 'b');\n * // => false\n *\n * _.startsWith('abc', 'b', 1);\n * // => true\n */\n function startsWith(string, target, position) {\n string = toString(string);\n position = position == null\n ? 0\n : baseClamp(toInteger(position), 0, string.length);\n\n target = baseToString(target);\n return string.slice(position, position + target.length) == target;\n }\n\n /**\n * Creates a compiled template function that can interpolate data properties\n * in \"interpolate\" delimiters, HTML-escape interpolated data properties in\n * \"escape\" delimiters, and execute JavaScript in \"evaluate\" delimiters. Data\n * properties may be accessed as free variables in the template. If a setting\n * object is given, it takes precedence over `_.templateSettings` values.\n *\n * **Note:** In the development build `_.template` utilizes\n * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)\n * for easier debugging.\n *\n * For more information on precompiling templates see\n * [lodash's custom builds documentation](https://lodash.com/custom-builds).\n *\n * For more information on Chrome extension sandboxes see\n * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval).\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category String\n * @param {string} [string=''] The template string.\n * @param {Object} [options={}] The options object.\n * @param {RegExp} [options.escape=_.templateSettings.escape]\n * The HTML \"escape\" delimiter.\n * @param {RegExp} [options.evaluate=_.templateSettings.evaluate]\n * The \"evaluate\" delimiter.\n * @param {Object} [options.imports=_.templateSettings.imports]\n * An object to import into the template as free variables.\n * @param {RegExp} [options.interpolate=_.templateSettings.interpolate]\n * The \"interpolate\" delimiter.\n * @param {string} [options.sourceURL='lodash.templateSources[n]']\n * The sourceURL of the compiled template.\n * @param {string} [options.variable='obj']\n * The data object variable name.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Function} Returns the compiled template function.\n * @example\n *\n * // Use the \"interpolate\" delimiter to create a compiled template.\n * var compiled = _.template('hello <%= user %>!');\n * compiled({ 'user': 'fred' });\n * // => 'hello fred!'\n *\n * // Use the HTML \"escape\" delimiter to escape data property values.\n * var compiled = _.template('<%- value %>');\n * compiled({ 'value': '\r\n\r\n\r\n\r\n\r\n","import { useDialogStore } from '@/stores/dialogStore'\r\nimport LoadWorkflowWarning from '@/components/dialog/content/LoadWorkflowWarning.vue'\r\nimport { markRaw } from 'vue'\r\n\r\nexport function showLoadWorkflowWarning(props: {\r\n missingNodeTypes: any[]\r\n hasAddedNodes: boolean\r\n [key: string]: any\r\n}) {\r\n const dialogStore = useDialogStore()\r\n dialogStore.showDialog({\r\n component: markRaw(LoadWorkflowWarning),\r\n props\r\n })\r\n}\r\n","import { ComfyLogging } from './logging'\r\nimport { ComfyWidgetConstructor, ComfyWidgets, initWidgets } from './widgets'\r\nimport { ComfyUI, $el } from './ui'\r\nimport { api } from './api'\r\nimport { defaultGraph } from './defaultGraph'\r\nimport {\r\n getPngMetadata,\r\n getWebpMetadata,\r\n getFlacMetadata,\r\n importA1111,\r\n getLatentMetadata\r\n} from './pnginfo'\r\nimport { addDomClippingSetting } from './domWidget'\r\nimport { createImageHost, calculateImageGrid } from './ui/imagePreview'\r\nimport { DraggableList } from './ui/draggableList'\r\nimport { applyTextReplacements, addStylesheet } from './utils'\r\nimport type { ComfyExtension } from '@/types/comfy'\r\nimport {\r\n type ComfyWorkflowJSON,\r\n validateComfyWorkflow\r\n} from '../types/comfyWorkflow'\r\nimport { ComfyNodeDef, StatusWsMessageStatus } from '@/types/apiTypes'\r\nimport { lightenColor } from '@/utils/colorUtil'\r\nimport { ComfyAppMenu } from './ui/menu/index'\r\nimport { getStorageValue } from './utils'\r\nimport { ComfyWorkflowManager, ComfyWorkflow } from './workflows'\r\nimport {\r\n LGraphCanvas,\r\n LGraph,\r\n LGraphNode,\r\n LiteGraph\r\n} from '@comfyorg/litegraph'\r\nimport { StorageLocation } from '@/types/settingTypes'\r\n\r\n// CSS imports. style.css must be imported later as it overwrites some litegraph styles.\r\nimport '@comfyorg/litegraph/style.css'\r\nimport '../assets/css/style.css'\r\nimport { ExtensionManager } from '@/types/extensionTypes'\r\nimport {\r\n ComfyNodeDefImpl,\r\n SYSTEM_NODE_DEFS,\r\n useNodeDefStore\r\n} from '@/stores/nodeDefStore'\r\nimport { Vector2 } from '@comfyorg/litegraph'\r\nimport _ from 'lodash'\r\nimport { showLoadWorkflowWarning } from '@/services/dialogService'\r\nimport { useSettingStore } from '@/stores/settingStore'\r\n\r\nexport const ANIM_PREVIEW_WIDGET = '$$comfy_animation_preview'\r\n\r\nfunction sanitizeNodeName(string) {\r\n let entityMap = {\r\n '&': '',\r\n '<': '',\r\n '>': '',\r\n '\"': '',\r\n \"'\": '',\r\n '`': '',\r\n '=': ''\r\n }\r\n return String(string).replace(/[&<>\"'`=]/g, function fromEntityMap(s) {\r\n return entityMap[s]\r\n })\r\n}\r\n\r\n/**\r\n * @typedef {import(\"types/comfy\").ComfyExtension} ComfyExtension\r\n */\r\n\r\nexport class ComfyApp {\r\n /**\r\n * List of entries to queue\r\n * @type {{number: number, batchCount: number}[]}\r\n */\r\n #queueItems = []\r\n /**\r\n * If the queue is currently being processed\r\n * @type {boolean}\r\n */\r\n #processingQueue = false\r\n\r\n /**\r\n * Content Clipboard\r\n * @type {serialized node object}\r\n */\r\n static clipspace = null\r\n static clipspace_invalidate_handler = null\r\n static open_maskeditor = null\r\n static clipspace_return_node = null\r\n\r\n // Force vite to import utils.ts as part of index.\r\n // Force import of DraggableList.\r\n static utils = {\r\n applyTextReplacements,\r\n addStylesheet,\r\n DraggableList\r\n }\r\n\r\n vueAppReady: boolean\r\n ui: ComfyUI\r\n logging: ComfyLogging\r\n extensions: ComfyExtension[]\r\n extensionManager: ExtensionManager\r\n _nodeOutputs: Record\r\n nodePreviewImages: Record\r\n shiftDown: boolean\r\n graph: LGraph\r\n enableWorkflowViewRestore: any\r\n canvas: LGraphCanvas\r\n dragOverNode: LGraphNode | null\r\n canvasEl: HTMLCanvasElement\r\n // x, y, scale\r\n zoom_drag_start: [number, number, number] | null\r\n lastNodeErrors: any[] | null\r\n runningNodeId: number | null\r\n lastExecutionError: { node_id: number } | null\r\n progress: { value: number; max: number } | null\r\n configuringGraph: boolean\r\n isNewUserSession: boolean\r\n storageLocation: StorageLocation\r\n multiUserServer: boolean\r\n ctx: CanvasRenderingContext2D\r\n widgets: Record\r\n workflowManager: ComfyWorkflowManager\r\n bodyTop: HTMLElement\r\n bodyLeft: HTMLElement\r\n bodyRight: HTMLElement\r\n bodyBottom: HTMLElement\r\n canvasContainer: HTMLElement\r\n menu: ComfyAppMenu\r\n\r\n constructor() {\r\n this.vueAppReady = false\r\n this.ui = new ComfyUI(this)\r\n this.logging = new ComfyLogging(this)\r\n this.workflowManager = new ComfyWorkflowManager(this)\r\n this.bodyTop = $el('div.comfyui-body-top', { parent: document.body })\r\n this.bodyLeft = $el('div.comfyui-body-left', { parent: document.body })\r\n this.bodyRight = $el('div.comfyui-body-right', { parent: document.body })\r\n this.bodyBottom = $el('div.comfyui-body-bottom', { parent: document.body })\r\n this.canvasContainer = $el('div.graph-canvas-container', {\r\n parent: document.body\r\n })\r\n this.menu = new ComfyAppMenu(this)\r\n\r\n /**\r\n * List of extensions that are registered with the app\r\n * @type {ComfyExtension[]}\r\n */\r\n this.extensions = []\r\n\r\n /**\r\n * Stores the execution output data for each node\r\n * @type {Record}\r\n */\r\n this.nodeOutputs = {}\r\n\r\n /**\r\n * Stores the preview image data for each node\r\n * @type {Record}\r\n */\r\n this.nodePreviewImages = {}\r\n\r\n /**\r\n * If the shift key on the keyboard is pressed\r\n * @type {boolean}\r\n */\r\n this.shiftDown = false\r\n }\r\n\r\n get nodeOutputs() {\r\n return this._nodeOutputs\r\n }\r\n\r\n set nodeOutputs(value) {\r\n this._nodeOutputs = value\r\n this.#invokeExtensions('onNodeOutputsUpdated', value)\r\n }\r\n\r\n getPreviewFormatParam() {\r\n let preview_format = this.ui.settings.getSettingValue('Comfy.PreviewFormat')\r\n if (preview_format) return `&preview=${preview_format}`\r\n else return ''\r\n }\r\n\r\n getRandParam() {\r\n return '&rand=' + Math.random()\r\n }\r\n\r\n static isImageNode(node) {\r\n return (\r\n node.imgs ||\r\n (node &&\r\n node.widgets &&\r\n node.widgets.findIndex((obj) => obj.name === 'image') >= 0)\r\n )\r\n }\r\n\r\n static onClipspaceEditorSave() {\r\n if (ComfyApp.clipspace_return_node) {\r\n ComfyApp.pasteFromClipspace(ComfyApp.clipspace_return_node)\r\n }\r\n }\r\n\r\n static onClipspaceEditorClosed() {\r\n ComfyApp.clipspace_return_node = null\r\n }\r\n\r\n static copyToClipspace(node) {\r\n var widgets = null\r\n if (node.widgets) {\r\n widgets = node.widgets.map(({ type, name, value }) => ({\r\n type,\r\n name,\r\n value\r\n }))\r\n }\r\n\r\n var imgs = undefined\r\n var orig_imgs = undefined\r\n if (node.imgs != undefined) {\r\n imgs = []\r\n orig_imgs = []\r\n\r\n for (let i = 0; i < node.imgs.length; i++) {\r\n imgs[i] = new Image()\r\n imgs[i].src = node.imgs[i].src\r\n orig_imgs[i] = imgs[i]\r\n }\r\n }\r\n\r\n var selectedIndex = 0\r\n if (node.imageIndex) {\r\n selectedIndex = node.imageIndex\r\n }\r\n\r\n ComfyApp.clipspace = {\r\n widgets: widgets,\r\n imgs: imgs,\r\n original_imgs: orig_imgs,\r\n images: node.images,\r\n selectedIndex: selectedIndex,\r\n img_paste_mode: 'selected' // reset to default im_paste_mode state on copy action\r\n }\r\n\r\n ComfyApp.clipspace_return_node = null\r\n\r\n if (ComfyApp.clipspace_invalidate_handler) {\r\n ComfyApp.clipspace_invalidate_handler()\r\n }\r\n }\r\n\r\n static pasteFromClipspace(node) {\r\n if (ComfyApp.clipspace) {\r\n // image paste\r\n if (ComfyApp.clipspace.imgs && node.imgs) {\r\n if (node.images && ComfyApp.clipspace.images) {\r\n if (ComfyApp.clipspace['img_paste_mode'] == 'selected') {\r\n node.images = [\r\n ComfyApp.clipspace.images[ComfyApp.clipspace['selectedIndex']]\r\n ]\r\n } else {\r\n node.images = ComfyApp.clipspace.images\r\n }\r\n\r\n if (app.nodeOutputs[node.id + ''])\r\n app.nodeOutputs[node.id + ''].images = node.images\r\n }\r\n\r\n if (ComfyApp.clipspace.imgs) {\r\n // deep-copy to cut link with clipspace\r\n if (ComfyApp.clipspace['img_paste_mode'] == 'selected') {\r\n const img = new Image()\r\n img.src =\r\n ComfyApp.clipspace.imgs[ComfyApp.clipspace['selectedIndex']].src\r\n node.imgs = [img]\r\n node.imageIndex = 0\r\n } else {\r\n const imgs = []\r\n for (let i = 0; i < ComfyApp.clipspace.imgs.length; i++) {\r\n imgs[i] = new Image()\r\n imgs[i].src = ComfyApp.clipspace.imgs[i].src\r\n node.imgs = imgs\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (node.widgets) {\r\n if (ComfyApp.clipspace.images) {\r\n const clip_image =\r\n ComfyApp.clipspace.images[ComfyApp.clipspace['selectedIndex']]\r\n const index = node.widgets.findIndex((obj) => obj.name === 'image')\r\n if (index >= 0) {\r\n if (\r\n node.widgets[index].type != 'image' &&\r\n typeof node.widgets[index].value == 'string' &&\r\n clip_image.filename\r\n ) {\r\n node.widgets[index].value =\r\n (clip_image.subfolder ? clip_image.subfolder + '/' : '') +\r\n clip_image.filename +\r\n (clip_image.type ? ` [${clip_image.type}]` : '')\r\n } else {\r\n node.widgets[index].value = clip_image\r\n }\r\n }\r\n }\r\n if (ComfyApp.clipspace.widgets) {\r\n ComfyApp.clipspace.widgets.forEach(({ type, name, value }) => {\r\n const prop = Object.values(node.widgets).find(\r\n // @ts-expect-errorg\r\n (obj) => obj.type === type && obj.name === name\r\n )\r\n // @ts-expect-error\r\n if (prop && prop.type != 'button') {\r\n if (\r\n // @ts-expect-error\r\n prop.type != 'image' &&\r\n // @ts-expect-error\r\n typeof prop.value == 'string' &&\r\n value.filename\r\n ) {\r\n // @ts-expect-error\r\n prop.value =\r\n (value.subfolder ? value.subfolder + '/' : '') +\r\n value.filename +\r\n (value.type ? ` [${value.type}]` : '')\r\n } else {\r\n // @ts-expect-error\r\n prop.value = value\r\n // @ts-expect-error\r\n prop.callback(value)\r\n }\r\n }\r\n })\r\n }\r\n }\r\n\r\n app.graph.setDirtyCanvas(true)\r\n }\r\n }\r\n\r\n /**\r\n * Invoke an extension callback\r\n * @param {keyof ComfyExtension} method The extension callback to execute\r\n * @param {any[]} args Any arguments to pass to the callback\r\n * @returns\r\n */\r\n #invokeExtensions(method, ...args) {\r\n let results = []\r\n for (const ext of this.extensions) {\r\n if (method in ext) {\r\n try {\r\n results.push(ext[method](...args, this))\r\n } catch (error) {\r\n console.error(\r\n `Error calling extension '${ext.name}' method '${method}'`,\r\n { error },\r\n { extension: ext },\r\n { args }\r\n )\r\n }\r\n }\r\n }\r\n return results\r\n }\r\n\r\n /**\r\n * Invoke an async extension callback\r\n * Each callback will be invoked concurrently\r\n * @param {string} method The extension callback to execute\r\n * @param {...any} args Any arguments to pass to the callback\r\n * @returns\r\n */\r\n async #invokeExtensionsAsync(method, ...args) {\r\n return await Promise.all(\r\n this.extensions.map(async (ext) => {\r\n if (method in ext) {\r\n try {\r\n return await ext[method](...args, this)\r\n } catch (error) {\r\n console.error(\r\n `Error calling extension '${ext.name}' method '${method}'`,\r\n { error },\r\n { extension: ext },\r\n { args }\r\n )\r\n }\r\n }\r\n })\r\n )\r\n }\r\n\r\n #addRestoreWorkflowView() {\r\n const serialize = LGraph.prototype.serialize\r\n const self = this\r\n LGraph.prototype.serialize = function () {\r\n const workflow = serialize.apply(this, arguments)\r\n\r\n // Store the drag & scale info in the serialized workflow if the setting is enabled\r\n if (self.enableWorkflowViewRestore.value) {\r\n if (!workflow.extra) {\r\n workflow.extra = {}\r\n }\r\n workflow.extra.ds = {\r\n scale: self.canvas.ds.scale,\r\n offset: self.canvas.ds.offset\r\n }\r\n } else if (workflow.extra?.ds) {\r\n // Clear any old view data\r\n delete workflow.extra.ds\r\n }\r\n\r\n return workflow\r\n }\r\n this.enableWorkflowViewRestore = this.ui.settings.addSetting({\r\n id: 'Comfy.EnableWorkflowViewRestore',\r\n name: 'Save and restore canvas position and zoom level in workflows',\r\n type: 'boolean',\r\n defaultValue: true\r\n })\r\n }\r\n\r\n /**\r\n * Adds special context menu handling for nodes\r\n * e.g. this adds Open Image functionality for nodes that show images\r\n * @param {*} node The node to add the menu handler\r\n */\r\n #addNodeContextMenuHandler(node) {\r\n function getCopyImageOption(img) {\r\n if (typeof window.ClipboardItem === 'undefined') return []\r\n return [\r\n {\r\n content: 'Copy Image',\r\n callback: async () => {\r\n const url = new URL(img.src)\r\n url.searchParams.delete('preview')\r\n\r\n const writeImage = async (blob) => {\r\n await navigator.clipboard.write([\r\n new ClipboardItem({\r\n [blob.type]: blob\r\n })\r\n ])\r\n }\r\n\r\n try {\r\n const data = await fetch(url)\r\n const blob = await data.blob()\r\n try {\r\n await writeImage(blob)\r\n } catch (error) {\r\n // Chrome seems to only support PNG on write, convert and try again\r\n if (blob.type !== 'image/png') {\r\n const canvas = $el('canvas', {\r\n width: img.naturalWidth,\r\n height: img.naturalHeight\r\n }) as HTMLCanvasElement\r\n const ctx = canvas.getContext('2d')\r\n let image\r\n if (typeof window.createImageBitmap === 'undefined') {\r\n image = new Image()\r\n const p = new Promise((resolve, reject) => {\r\n image.onload = resolve\r\n image.onerror = reject\r\n }).finally(() => {\r\n URL.revokeObjectURL(image.src)\r\n })\r\n image.src = URL.createObjectURL(blob)\r\n await p\r\n } else {\r\n image = await createImageBitmap(blob)\r\n }\r\n try {\r\n ctx.drawImage(image, 0, 0)\r\n canvas.toBlob(writeImage, 'image/png')\r\n } finally {\r\n if (typeof image.close === 'function') {\r\n image.close()\r\n }\r\n }\r\n\r\n return\r\n }\r\n throw error\r\n }\r\n } catch (error) {\r\n alert('Error copying image: ' + (error.message ?? error))\r\n }\r\n }\r\n }\r\n ]\r\n }\r\n\r\n node.prototype.getExtraMenuOptions = function (_, options) {\r\n if (this.imgs) {\r\n // If this node has images then we add an open in new tab item\r\n let img\r\n if (this.imageIndex != null) {\r\n // An image is selected so select that\r\n img = this.imgs[this.imageIndex]\r\n } else if (this.overIndex != null) {\r\n // No image is selected but one is hovered\r\n img = this.imgs[this.overIndex]\r\n }\r\n if (img) {\r\n options.unshift(\r\n {\r\n content: 'Open Image',\r\n callback: () => {\r\n let url = new URL(img.src)\r\n url.searchParams.delete('preview')\r\n window.open(url, '_blank')\r\n }\r\n },\r\n ...getCopyImageOption(img),\r\n {\r\n content: 'Save Image',\r\n callback: () => {\r\n const a = document.createElement('a')\r\n let url = new URL(img.src)\r\n url.searchParams.delete('preview')\r\n a.href = url.toString()\r\n a.setAttribute(\r\n 'download',\r\n new URLSearchParams(url.search).get('filename')\r\n )\r\n document.body.append(a)\r\n a.click()\r\n requestAnimationFrame(() => a.remove())\r\n }\r\n }\r\n )\r\n }\r\n }\r\n\r\n options.push({\r\n content: 'Bypass',\r\n callback: (obj) => {\r\n if (this.mode === 4) this.mode = 0\r\n else this.mode = 4\r\n this.graph.change()\r\n }\r\n })\r\n\r\n // prevent conflict of clipspace content\r\n if (!ComfyApp.clipspace_return_node) {\r\n options.push({\r\n content: 'Copy (Clipspace)',\r\n callback: (obj) => {\r\n ComfyApp.copyToClipspace(this)\r\n }\r\n })\r\n\r\n if (ComfyApp.clipspace != null) {\r\n options.push({\r\n content: 'Paste (Clipspace)',\r\n callback: () => {\r\n ComfyApp.pasteFromClipspace(this)\r\n }\r\n })\r\n }\r\n\r\n if (ComfyApp.isImageNode(this)) {\r\n options.push({\r\n content: 'Open in MaskEditor',\r\n callback: (obj) => {\r\n ComfyApp.copyToClipspace(this)\r\n ComfyApp.clipspace_return_node = this\r\n ComfyApp.open_maskeditor()\r\n }\r\n })\r\n }\r\n }\r\n }\r\n }\r\n\r\n #addNodeKeyHandler(node) {\r\n const app = this\r\n const origNodeOnKeyDown = node.prototype.onKeyDown\r\n\r\n node.prototype.onKeyDown = function (e) {\r\n if (origNodeOnKeyDown && origNodeOnKeyDown.apply(this, e) === false) {\r\n return false\r\n }\r\n\r\n if (this.flags.collapsed || !this.imgs || this.imageIndex === null) {\r\n return\r\n }\r\n\r\n let handled = false\r\n\r\n if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') {\r\n if (e.key === 'ArrowLeft') {\r\n this.imageIndex -= 1\r\n } else if (e.key === 'ArrowRight') {\r\n this.imageIndex += 1\r\n }\r\n this.imageIndex %= this.imgs.length\r\n\r\n if (this.imageIndex < 0) {\r\n this.imageIndex = this.imgs.length + this.imageIndex\r\n }\r\n handled = true\r\n } else if (e.key === 'Escape') {\r\n this.imageIndex = null\r\n handled = true\r\n }\r\n\r\n if (handled === true) {\r\n e.preventDefault()\r\n e.stopImmediatePropagation()\r\n return false\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Adds Custom drawing logic for nodes\r\n * e.g. Draws images and handles thumbnail navigation on nodes that output images\r\n * @param {*} node The node to add the draw handler\r\n */\r\n #addDrawBackgroundHandler(node) {\r\n const app = this\r\n\r\n function getImageTop(node) {\r\n let shiftY\r\n if (node.imageOffset != null) {\r\n shiftY = node.imageOffset\r\n } else {\r\n if (node.widgets?.length) {\r\n const w = node.widgets[node.widgets.length - 1]\r\n shiftY = w.last_y\r\n if (w.computeSize) {\r\n shiftY += w.computeSize()[1] + 4\r\n } else if (w.computedHeight) {\r\n shiftY += w.computedHeight\r\n } else {\r\n shiftY += LiteGraph.NODE_WIDGET_HEIGHT + 4\r\n }\r\n } else {\r\n shiftY = node.computeSize()[1]\r\n }\r\n }\r\n return shiftY\r\n }\r\n\r\n node.prototype.setSizeForImage = function (force) {\r\n if (!force && this.animatedImages) return\r\n\r\n if (this.inputHeight || this.freeWidgetSpace > 210) {\r\n this.setSize(this.size)\r\n return\r\n }\r\n const minHeight = getImageTop(this) + 220\r\n if (this.size[1] < minHeight) {\r\n this.setSize([this.size[0], minHeight])\r\n }\r\n }\r\n\r\n function unsafeDrawBackground(ctx) {\r\n if (!this.flags.collapsed) {\r\n let imgURLs = []\r\n let imagesChanged = false\r\n\r\n const output = app.nodeOutputs[this.id + '']\r\n if (output?.images) {\r\n this.animatedImages = output?.animated?.find(Boolean)\r\n if (this.images !== output.images) {\r\n this.images = output.images\r\n imagesChanged = true\r\n imgURLs = imgURLs.concat(\r\n output.images.map((params) => {\r\n return api.apiURL(\r\n '/view?' +\r\n new URLSearchParams(params).toString() +\r\n (this.animatedImages ? '' : app.getPreviewFormatParam()) +\r\n app.getRandParam()\r\n )\r\n })\r\n )\r\n }\r\n }\r\n\r\n const preview = app.nodePreviewImages[this.id + '']\r\n if (this.preview !== preview) {\r\n this.preview = preview\r\n imagesChanged = true\r\n if (preview != null) {\r\n imgURLs.push(preview)\r\n }\r\n }\r\n\r\n if (imagesChanged) {\r\n this.imageIndex = null\r\n if (imgURLs.length > 0) {\r\n Promise.all(\r\n imgURLs.map((src) => {\r\n return new Promise((r) => {\r\n const img = new Image()\r\n img.onload = () => r(img)\r\n img.onerror = () => r(null)\r\n img.src = src\r\n })\r\n })\r\n ).then((imgs) => {\r\n if (\r\n (!output || this.images === output.images) &&\r\n (!preview || this.preview === preview)\r\n ) {\r\n this.imgs = imgs.filter(Boolean)\r\n this.setSizeForImage?.()\r\n app.graph.setDirtyCanvas(true)\r\n }\r\n })\r\n } else {\r\n this.imgs = null\r\n }\r\n }\r\n\r\n const calculateGrid = (w, h, n) => {\r\n let columns, rows, cellsize\r\n\r\n if (w > h) {\r\n cellsize = h\r\n columns = Math.ceil(w / cellsize)\r\n rows = Math.ceil(n / columns)\r\n } else {\r\n cellsize = w\r\n rows = Math.ceil(h / cellsize)\r\n columns = Math.ceil(n / rows)\r\n }\r\n\r\n while (columns * rows < n) {\r\n cellsize++\r\n if (w >= h) {\r\n columns = Math.ceil(w / cellsize)\r\n rows = Math.ceil(n / columns)\r\n } else {\r\n rows = Math.ceil(h / cellsize)\r\n columns = Math.ceil(n / rows)\r\n }\r\n }\r\n\r\n const cell_size = Math.min(w / columns, h / rows)\r\n return { cell_size, columns, rows }\r\n }\r\n\r\n const is_all_same_aspect_ratio = (imgs) => {\r\n // assume: imgs.length >= 2\r\n let ratio = imgs[0].naturalWidth / imgs[0].naturalHeight\r\n\r\n for (let i = 1; i < imgs.length; i++) {\r\n let this_ratio = imgs[i].naturalWidth / imgs[i].naturalHeight\r\n if (ratio != this_ratio) return false\r\n }\r\n\r\n return true\r\n }\r\n\r\n if (this.imgs?.length) {\r\n const widgetIdx = this.widgets?.findIndex(\r\n (w) => w.name === ANIM_PREVIEW_WIDGET\r\n )\r\n\r\n if (this.animatedImages) {\r\n // Instead of using the canvas we'll use a IMG\r\n if (widgetIdx > -1) {\r\n // Replace content\r\n const widget = this.widgets[widgetIdx]\r\n widget.options.host.updateImages(this.imgs)\r\n } else {\r\n const host = createImageHost(this)\r\n this.setSizeForImage(true)\r\n const widget = this.addDOMWidget(\r\n ANIM_PREVIEW_WIDGET,\r\n 'img',\r\n host.el,\r\n {\r\n host,\r\n getHeight: host.getHeight,\r\n onDraw: host.onDraw,\r\n hideOnZoom: false\r\n }\r\n )\r\n widget.serializeValue = () => undefined\r\n widget.options.host.updateImages(this.imgs)\r\n }\r\n return\r\n }\r\n\r\n if (widgetIdx > -1) {\r\n this.widgets[widgetIdx].onRemove?.()\r\n this.widgets.splice(widgetIdx, 1)\r\n }\r\n\r\n const canvas = app.graph.list_of_graphcanvas[0]\r\n const mouse = canvas.graph_mouse\r\n if (!canvas.pointer_is_down && this.pointerDown) {\r\n if (\r\n mouse[0] === this.pointerDown.pos[0] &&\r\n mouse[1] === this.pointerDown.pos[1]\r\n ) {\r\n this.imageIndex = this.pointerDown.index\r\n }\r\n this.pointerDown = null\r\n }\r\n\r\n let imageIndex = this.imageIndex\r\n const numImages = this.imgs.length\r\n if (numImages === 1 && !imageIndex) {\r\n this.imageIndex = imageIndex = 0\r\n }\r\n\r\n const top = getImageTop(this)\r\n var shiftY = top\r\n\r\n let dw = this.size[0]\r\n let dh = this.size[1]\r\n dh -= shiftY\r\n\r\n if (imageIndex == null) {\r\n var cellWidth, cellHeight, shiftX, cell_padding, cols\r\n\r\n const compact_mode = is_all_same_aspect_ratio(this.imgs)\r\n if (!compact_mode) {\r\n // use rectangle cell style and border line\r\n cell_padding = 2\r\n const { cell_size, columns, rows } = calculateGrid(\r\n dw,\r\n dh,\r\n numImages\r\n )\r\n cols = columns\r\n\r\n cellWidth = cell_size\r\n cellHeight = cell_size\r\n shiftX = (dw - cell_size * cols) / 2\r\n shiftY = (dh - cell_size * rows) / 2 + top\r\n } else {\r\n cell_padding = 0\r\n ;({ cellWidth, cellHeight, cols, shiftX } = calculateImageGrid(\r\n this.imgs,\r\n dw,\r\n dh\r\n ))\r\n }\r\n\r\n let anyHovered = false\r\n this.imageRects = []\r\n for (let i = 0; i < numImages; i++) {\r\n const img = this.imgs[i]\r\n const row = Math.floor(i / cols)\r\n const col = i % cols\r\n const x = col * cellWidth + shiftX\r\n const y = row * cellHeight + shiftY\r\n if (!anyHovered) {\r\n anyHovered = LiteGraph.isInsideRectangle(\r\n mouse[0],\r\n mouse[1],\r\n x + this.pos[0],\r\n y + this.pos[1],\r\n cellWidth,\r\n cellHeight\r\n )\r\n if (anyHovered) {\r\n this.overIndex = i\r\n let value = 110\r\n if (canvas.pointer_is_down) {\r\n if (!this.pointerDown || this.pointerDown.index !== i) {\r\n this.pointerDown = { index: i, pos: [...mouse] }\r\n }\r\n value = 125\r\n }\r\n ctx.filter = `contrast(${value}%) brightness(${value}%)`\r\n canvas.canvas.style.cursor = 'pointer'\r\n }\r\n }\r\n this.imageRects.push([x, y, cellWidth, cellHeight])\r\n\r\n let wratio = cellWidth / img.width\r\n let hratio = cellHeight / img.height\r\n var ratio = Math.min(wratio, hratio)\r\n\r\n let imgHeight = ratio * img.height\r\n let imgY =\r\n row * cellHeight + shiftY + (cellHeight - imgHeight) / 2\r\n let imgWidth = ratio * img.width\r\n let imgX = col * cellWidth + shiftX + (cellWidth - imgWidth) / 2\r\n\r\n ctx.drawImage(\r\n img,\r\n imgX + cell_padding,\r\n imgY + cell_padding,\r\n imgWidth - cell_padding * 2,\r\n imgHeight - cell_padding * 2\r\n )\r\n if (!compact_mode) {\r\n // rectangle cell and border line style\r\n ctx.strokeStyle = '#8F8F8F'\r\n ctx.lineWidth = 1\r\n ctx.strokeRect(\r\n x + cell_padding,\r\n y + cell_padding,\r\n cellWidth - cell_padding * 2,\r\n cellHeight - cell_padding * 2\r\n )\r\n }\r\n\r\n ctx.filter = 'none'\r\n }\r\n\r\n if (!anyHovered) {\r\n this.pointerDown = null\r\n this.overIndex = null\r\n }\r\n } else {\r\n // Draw individual\r\n let w = this.imgs[imageIndex].naturalWidth\r\n let h = this.imgs[imageIndex].naturalHeight\r\n\r\n const scaleX = dw / w\r\n const scaleY = dh / h\r\n const scale = Math.min(scaleX, scaleY, 1)\r\n\r\n w *= scale\r\n h *= scale\r\n\r\n let x = (dw - w) / 2\r\n let y = (dh - h) / 2 + shiftY\r\n ctx.drawImage(this.imgs[imageIndex], x, y, w, h)\r\n\r\n const drawButton = (x, y, sz, text) => {\r\n const hovered = LiteGraph.isInsideRectangle(\r\n mouse[0],\r\n mouse[1],\r\n x + this.pos[0],\r\n y + this.pos[1],\r\n sz,\r\n sz\r\n )\r\n let fill = '#333'\r\n let textFill = '#fff'\r\n let isClicking = false\r\n if (hovered) {\r\n canvas.canvas.style.cursor = 'pointer'\r\n if (canvas.pointer_is_down) {\r\n fill = '#1e90ff'\r\n isClicking = true\r\n } else {\r\n fill = '#eee'\r\n textFill = '#000'\r\n }\r\n } else {\r\n this.pointerWasDown = null\r\n }\r\n\r\n ctx.fillStyle = fill\r\n ctx.beginPath()\r\n ctx.roundRect(x, y, sz, sz, [4])\r\n ctx.fill()\r\n ctx.fillStyle = textFill\r\n ctx.font = '12px Arial'\r\n ctx.textAlign = 'center'\r\n ctx.fillText(text, x + 15, y + 20)\r\n\r\n return isClicking\r\n }\r\n\r\n if (numImages > 1) {\r\n if (\r\n drawButton(\r\n dw - 40,\r\n dh + top - 40,\r\n 30,\r\n `${this.imageIndex + 1}/${numImages}`\r\n )\r\n ) {\r\n let i =\r\n this.imageIndex + 1 >= numImages ? 0 : this.imageIndex + 1\r\n if (!this.pointerDown || !this.pointerDown.index === i) {\r\n this.pointerDown = { index: i, pos: [...mouse] }\r\n }\r\n }\r\n\r\n if (drawButton(dw - 40, top + 10, 30, `x`)) {\r\n if (!this.pointerDown || !this.pointerDown.index === null) {\r\n this.pointerDown = { index: null, pos: [...mouse] }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n node.prototype.onDrawBackground = function (ctx) {\r\n try {\r\n unsafeDrawBackground.call(this, ctx)\r\n } catch (error) {\r\n console.error('Error drawing node background', error)\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Adds a handler allowing drag+drop of files onto the window to load workflows\r\n */\r\n #addDropHandler() {\r\n // Get prompt from dropped PNG or json\r\n document.addEventListener('drop', async (event) => {\r\n event.preventDefault()\r\n event.stopPropagation()\r\n\r\n const n = this.dragOverNode\r\n this.dragOverNode = null\r\n // Node handles file drop, we dont use the built in onDropFile handler as its buggy\r\n // If you drag multiple files it will call it multiple times with the same file\r\n // @ts-expect-error This is not a standard event. TODO fix it.\r\n if (n && n.onDragDrop && (await n.onDragDrop(event))) {\r\n return\r\n }\r\n // Dragging from Chrome->Firefox there is a file but its a bmp, so ignore that\r\n if (\r\n event.dataTransfer.files.length &&\r\n event.dataTransfer.files[0].type !== 'image/bmp'\r\n ) {\r\n await this.handleFile(event.dataTransfer.files[0])\r\n } else {\r\n // Try loading the first URI in the transfer list\r\n const validTypes = ['text/uri-list', 'text/x-moz-url']\r\n const match = [...event.dataTransfer.types].find((t) =>\r\n validTypes.find((v) => t === v)\r\n )\r\n if (match) {\r\n const uri = event.dataTransfer.getData(match)?.split('\\n')?.[0]\r\n if (uri) {\r\n await this.handleFile(await (await fetch(uri)).blob())\r\n }\r\n }\r\n }\r\n })\r\n\r\n // Always clear over node on drag leave\r\n this.canvasEl.addEventListener('dragleave', async () => {\r\n if (this.dragOverNode) {\r\n this.dragOverNode = null\r\n this.graph.setDirtyCanvas(false, true)\r\n }\r\n })\r\n\r\n // Add handler for dropping onto a specific node\r\n this.canvasEl.addEventListener(\r\n 'dragover',\r\n (e) => {\r\n this.canvas.adjustMouseEvent(e)\r\n // @ts-expect-error: canvasX and canvasY are added by adjustMouseEvent in litegraph\r\n const node = this.graph.getNodeOnPos(e.canvasX, e.canvasY)\r\n if (node) {\r\n // @ts-expect-error This is not a standard event. TODO fix it.\r\n if (node.onDragOver && node.onDragOver(e)) {\r\n this.dragOverNode = node\r\n\r\n // dragover event is fired very frequently, run this on an animation frame\r\n requestAnimationFrame(() => {\r\n this.graph.setDirtyCanvas(false, true)\r\n })\r\n return\r\n }\r\n }\r\n this.dragOverNode = null\r\n },\r\n false\r\n )\r\n }\r\n\r\n /**\r\n * Adds a handler on paste that extracts and loads images or workflows from pasted JSON data\r\n */\r\n #addPasteHandler() {\r\n document.addEventListener('paste', async (e: ClipboardEvent) => {\r\n // ctrl+shift+v is used to paste nodes with connections\r\n // this is handled by litegraph\r\n if (this.shiftDown) return\r\n\r\n // @ts-expect-error: Property 'clipboardData' does not exist on type 'Window & typeof globalThis'.\r\n // Did you mean 'Clipboard'?ts(2551)\r\n // TODO: Not sure what the code wants to do.\r\n let data = e.clipboardData || window.clipboardData\r\n const items = data.items\r\n\r\n // Look for image paste data\r\n for (const item of items) {\r\n if (item.type.startsWith('image/')) {\r\n var imageNode = null\r\n\r\n // If an image node is selected, paste into it\r\n if (\r\n this.canvas.current_node &&\r\n this.canvas.current_node.is_selected &&\r\n ComfyApp.isImageNode(this.canvas.current_node)\r\n ) {\r\n imageNode = this.canvas.current_node\r\n }\r\n\r\n // No image node selected: add a new one\r\n if (!imageNode) {\r\n const newNode = LiteGraph.createNode('LoadImage')\r\n newNode.pos = [...this.canvas.graph_mouse]\r\n imageNode = this.graph.add(newNode)\r\n this.graph.change()\r\n }\r\n const blob = item.getAsFile()\r\n imageNode.pasteFile(blob)\r\n return\r\n }\r\n }\r\n\r\n // No image found. Look for node data\r\n data = data.getData('text/plain')\r\n let workflow: ComfyWorkflowJSON\r\n try {\r\n data = data.slice(data.indexOf('{'))\r\n workflow = JSON.parse(data)\r\n } catch (err) {\r\n try {\r\n data = data.slice(data.indexOf('workflow\\n'))\r\n data = data.slice(data.indexOf('{'))\r\n workflow = JSON.parse(data)\r\n } catch (error) {\r\n console.error(error)\r\n }\r\n }\r\n\r\n if (workflow && workflow.version && workflow.nodes && workflow.extra) {\r\n await this.loadGraphData(workflow)\r\n } else {\r\n if (\r\n (e.target instanceof HTMLTextAreaElement &&\r\n e.target.type === 'textarea') ||\r\n (e.target instanceof HTMLInputElement && e.target.type === 'text')\r\n ) {\r\n return\r\n }\r\n\r\n // Litegraph default paste\r\n this.canvas.pasteFromClipboard()\r\n }\r\n })\r\n }\r\n\r\n /**\r\n * Adds a handler on copy that serializes selected nodes to JSON\r\n */\r\n #addCopyHandler() {\r\n document.addEventListener('copy', (e) => {\r\n if (!(e.target instanceof Element)) {\r\n return\r\n }\r\n if (\r\n (e.target instanceof HTMLTextAreaElement &&\r\n e.target.type === 'textarea') ||\r\n (e.target instanceof HTMLInputElement && e.target.type === 'text')\r\n ) {\r\n // Default system copy\r\n return\r\n }\r\n const isTargetInGraph =\r\n e.target.classList.contains('litegraph') ||\r\n e.target.classList.contains('graph-canvas-container')\r\n\r\n // copy nodes and clear clipboard\r\n if (isTargetInGraph && this.canvas.selected_nodes) {\r\n this.canvas.copyToClipboard()\r\n e.clipboardData.setData('text', ' ') //clearData doesn't remove images from clipboard\r\n e.preventDefault()\r\n e.stopImmediatePropagation()\r\n return false\r\n }\r\n })\r\n }\r\n\r\n /**\r\n * Handle mouse\r\n *\r\n * Move group by header\r\n */\r\n #addProcessMouseHandler() {\r\n const self = this\r\n\r\n const origProcessMouseDown = LGraphCanvas.prototype.processMouseDown\r\n LGraphCanvas.prototype.processMouseDown = function (e) {\r\n // prepare for ctrl+shift drag: zoom start\r\n if (e.ctrlKey && e.shiftKey && e.buttons) {\r\n self.zoom_drag_start = [e.x, e.y, this.ds.scale]\r\n return\r\n }\r\n\r\n const res = origProcessMouseDown.apply(this, arguments)\r\n\r\n this.selected_group_moving = false\r\n\r\n if (this.selected_group && !this.selected_group_resizing) {\r\n var font_size =\r\n this.selected_group.font_size || LiteGraph.DEFAULT_GROUP_FONT_SIZE\r\n var height = font_size * 1.4\r\n\r\n // Move group by header\r\n if (\r\n LiteGraph.isInsideRectangle(\r\n // @ts-expect-error\r\n e.canvasX,\r\n // @ts-expect-error\r\n e.canvasY,\r\n this.selected_group.pos[0],\r\n this.selected_group.pos[1],\r\n this.selected_group.size[0],\r\n height\r\n )\r\n ) {\r\n this.selected_group_moving = true\r\n }\r\n }\r\n\r\n return res\r\n }\r\n const origProcessMouseMove = LGraphCanvas.prototype.processMouseMove\r\n LGraphCanvas.prototype.processMouseMove = function (e) {\r\n // handle ctrl+shift drag\r\n if (e.ctrlKey && e.shiftKey && self.zoom_drag_start) {\r\n // stop canvas zoom action\r\n if (!e.buttons) {\r\n self.zoom_drag_start = null\r\n return\r\n }\r\n\r\n // calculate delta\r\n let deltaY = e.y - self.zoom_drag_start[1]\r\n let startScale = self.zoom_drag_start[2]\r\n\r\n let scale = startScale - deltaY / 100\r\n\r\n this.ds.changeScale(scale, [\r\n this.ds.element.width / 2,\r\n this.ds.element.height / 2\r\n ])\r\n this.graph.change()\r\n\r\n return\r\n }\r\n\r\n const orig_selected_group = this.selected_group\r\n\r\n if (\r\n this.selected_group &&\r\n !this.selected_group_resizing &&\r\n !this.selected_group_moving\r\n ) {\r\n this.selected_group = null\r\n }\r\n\r\n const res = origProcessMouseMove.apply(this, arguments)\r\n\r\n if (\r\n orig_selected_group &&\r\n !this.selected_group_resizing &&\r\n !this.selected_group_moving\r\n ) {\r\n this.selected_group = orig_selected_group\r\n }\r\n\r\n return res\r\n }\r\n }\r\n\r\n /**\r\n * Handle keypress\r\n *\r\n * Ctrl + M mute/unmute selected nodes\r\n */\r\n #addProcessKeyHandler() {\r\n const self = this\r\n const origProcessKey = LGraphCanvas.prototype.processKey\r\n LGraphCanvas.prototype.processKey = function (e) {\r\n if (!this.graph) {\r\n return\r\n }\r\n\r\n var block_default = false\r\n\r\n if (e.target instanceof Element && e.target.localName == 'input') {\r\n return\r\n }\r\n\r\n if (e.type == 'keydown' && !e.repeat) {\r\n // Ctrl + M mute/unmute\r\n if (e.key === 'm' && e.ctrlKey) {\r\n if (this.selected_nodes) {\r\n for (var i in this.selected_nodes) {\r\n if (this.selected_nodes[i].mode === 2) {\r\n // never\r\n this.selected_nodes[i].mode = 0 // always\r\n } else {\r\n this.selected_nodes[i].mode = 2 // never\r\n }\r\n }\r\n }\r\n block_default = true\r\n }\r\n\r\n // Ctrl + B bypass\r\n if (e.key === 'b' && e.ctrlKey) {\r\n if (this.selected_nodes) {\r\n for (var i in this.selected_nodes) {\r\n if (this.selected_nodes[i].mode === 4) {\r\n // never\r\n this.selected_nodes[i].mode = 0 // always\r\n } else {\r\n this.selected_nodes[i].mode = 4 // never\r\n }\r\n }\r\n }\r\n block_default = true\r\n }\r\n\r\n // Alt + C collapse/uncollapse\r\n if (e.key === 'c' && e.altKey) {\r\n if (this.selected_nodes) {\r\n for (var i in this.selected_nodes) {\r\n this.selected_nodes[i].collapse()\r\n }\r\n }\r\n block_default = true\r\n }\r\n\r\n // Ctrl+C Copy\r\n if (e.key === 'c' && (e.metaKey || e.ctrlKey)) {\r\n // Trigger onCopy\r\n return true\r\n }\r\n\r\n // Ctrl+V Paste\r\n if (\r\n (e.key === 'v' || e.key == 'V') &&\r\n (e.metaKey || e.ctrlKey) &&\r\n !e.shiftKey\r\n ) {\r\n // Trigger onPaste\r\n return true\r\n }\r\n\r\n if (e.key === '+' && e.altKey) {\r\n block_default = true\r\n let scale = this.ds.scale * 1.1\r\n this.ds.changeScale(scale, [\r\n this.ds.element.width / 2,\r\n this.ds.element.height / 2\r\n ])\r\n this.graph.change()\r\n }\r\n\r\n if (e.key === '-' && e.altKey) {\r\n block_default = true\r\n let scale = (this.ds.scale * 1) / 1.1\r\n this.ds.changeScale(scale, [\r\n this.ds.element.width / 2,\r\n this.ds.element.height / 2\r\n ])\r\n this.graph.change()\r\n }\r\n }\r\n\r\n this.graph.change()\r\n\r\n if (block_default) {\r\n e.preventDefault()\r\n e.stopImmediatePropagation()\r\n return false\r\n }\r\n\r\n // Fall through to Litegraph defaults\r\n return origProcessKey.apply(this, arguments)\r\n }\r\n }\r\n\r\n /**\r\n * Draws group header bar\r\n */\r\n #addDrawGroupsHandler() {\r\n const self = this\r\n const origDrawGroups = LGraphCanvas.prototype.drawGroups\r\n LGraphCanvas.prototype.drawGroups = function (canvas, ctx) {\r\n if (!this.graph) {\r\n return\r\n }\r\n\r\n var groups = this.graph._groups\r\n\r\n ctx.save()\r\n ctx.globalAlpha = 0.7 * this.editor_alpha\r\n\r\n for (var i = 0; i < groups.length; ++i) {\r\n var group = groups[i]\r\n\r\n if (!LiteGraph.overlapBounding(this.visible_area, group._bounding)) {\r\n continue\r\n } //out of the visible area\r\n\r\n ctx.fillStyle = group.color || '#335'\r\n ctx.strokeStyle = group.color || '#335'\r\n var pos = group._pos\r\n var size = group._size\r\n ctx.globalAlpha = 0.25 * this.editor_alpha\r\n ctx.beginPath()\r\n var font_size = group.font_size || LiteGraph.DEFAULT_GROUP_FONT_SIZE\r\n ctx.rect(pos[0] + 0.5, pos[1] + 0.5, size[0], font_size * 1.4)\r\n ctx.fill()\r\n ctx.globalAlpha = this.editor_alpha\r\n }\r\n\r\n ctx.restore()\r\n\r\n const res = origDrawGroups.apply(this, arguments)\r\n return res\r\n }\r\n }\r\n\r\n /**\r\n * Draws node highlights (executing, drag drop) and progress bar\r\n */\r\n #addDrawNodeHandler() {\r\n const origDrawNodeShape = LGraphCanvas.prototype.drawNodeShape\r\n const self = this\r\n LGraphCanvas.prototype.drawNodeShape = function (\r\n node,\r\n ctx,\r\n size,\r\n fgcolor,\r\n bgcolor,\r\n selected,\r\n mouse_over\r\n ) {\r\n const res = origDrawNodeShape.apply(this, arguments)\r\n\r\n const nodeErrors = self.lastNodeErrors?.[node.id]\r\n\r\n let color = null\r\n let lineWidth = 1\r\n if (node.id === +self.runningNodeId) {\r\n color = '#0f0'\r\n } else if (self.dragOverNode && node.id === self.dragOverNode.id) {\r\n color = 'dodgerblue'\r\n } else if (nodeErrors?.errors) {\r\n color = 'red'\r\n lineWidth = 2\r\n } else if (\r\n self.lastExecutionError &&\r\n +self.lastExecutionError.node_id === node.id\r\n ) {\r\n color = '#f0f'\r\n lineWidth = 2\r\n }\r\n\r\n if (color) {\r\n const shape =\r\n // @ts-expect-error\r\n node._shape || node.constructor.shape || LiteGraph.ROUND_SHAPE\r\n ctx.lineWidth = lineWidth\r\n ctx.globalAlpha = 0.8\r\n ctx.beginPath()\r\n if (shape == LiteGraph.BOX_SHAPE)\r\n ctx.rect(\r\n -6,\r\n -6 - LiteGraph.NODE_TITLE_HEIGHT,\r\n 12 + size[0] + 1,\r\n 12 + size[1] + LiteGraph.NODE_TITLE_HEIGHT\r\n )\r\n else if (\r\n shape == LiteGraph.ROUND_SHAPE ||\r\n (shape == LiteGraph.CARD_SHAPE && node.flags.collapsed)\r\n )\r\n ctx.roundRect(\r\n -6,\r\n -6 - LiteGraph.NODE_TITLE_HEIGHT,\r\n 12 + size[0] + 1,\r\n 12 + size[1] + LiteGraph.NODE_TITLE_HEIGHT,\r\n this.round_radius * 2\r\n )\r\n else if (shape == LiteGraph.CARD_SHAPE)\r\n ctx.roundRect(\r\n -6,\r\n -6 - LiteGraph.NODE_TITLE_HEIGHT,\r\n 12 + size[0] + 1,\r\n 12 + size[1] + LiteGraph.NODE_TITLE_HEIGHT,\r\n [this.round_radius * 2, this.round_radius * 2, 2, 2]\r\n )\r\n else if (shape == LiteGraph.CIRCLE_SHAPE)\r\n ctx.arc(\r\n size[0] * 0.5,\r\n size[1] * 0.5,\r\n size[0] * 0.5 + 6,\r\n 0,\r\n Math.PI * 2\r\n )\r\n ctx.strokeStyle = color\r\n ctx.stroke()\r\n ctx.strokeStyle = fgcolor\r\n ctx.globalAlpha = 1\r\n }\r\n\r\n if (self.progress && node.id === +self.runningNodeId) {\r\n ctx.fillStyle = 'green'\r\n ctx.fillRect(\r\n 0,\r\n 0,\r\n size[0] * (self.progress.value / self.progress.max),\r\n 6\r\n )\r\n ctx.fillStyle = bgcolor\r\n }\r\n\r\n // Highlight inputs that failed validation\r\n if (nodeErrors) {\r\n ctx.lineWidth = 2\r\n ctx.strokeStyle = 'red'\r\n for (const error of nodeErrors.errors) {\r\n if (error.extra_info && error.extra_info.input_name) {\r\n const inputIndex = node.findInputSlot(error.extra_info.input_name)\r\n if (inputIndex !== -1) {\r\n let pos = node.getConnectionPos(true, inputIndex)\r\n ctx.beginPath()\r\n ctx.arc(\r\n pos[0] - node.pos[0],\r\n pos[1] - node.pos[1],\r\n 12,\r\n 0,\r\n 2 * Math.PI,\r\n false\r\n )\r\n ctx.stroke()\r\n }\r\n }\r\n }\r\n }\r\n\r\n return res\r\n }\r\n\r\n const origDrawNode = LGraphCanvas.prototype.drawNode\r\n LGraphCanvas.prototype.drawNode = function (node, ctx) {\r\n var editor_alpha = this.editor_alpha\r\n var old_color = node.color\r\n var old_bgcolor = node.bgcolor\r\n\r\n if (node.mode === 2) {\r\n // never\r\n this.editor_alpha = 0.4\r\n }\r\n\r\n // ComfyUI's custom node mode enum value 4 => bypass/never.\r\n // @ts-expect-error\r\n if (node.mode === 4) {\r\n // never\r\n node.bgcolor = '#FF00FF'\r\n this.editor_alpha = 0.2\r\n }\r\n\r\n const adjustColor = (color?: string) => {\r\n return color ? lightenColor(color, 0.5) : color\r\n }\r\n if (app.ui.settings.getSettingValue('Comfy.ColorPalette') === 'light') {\r\n node.bgcolor = adjustColor(node.bgcolor)\r\n node.color = adjustColor(node.color)\r\n }\r\n\r\n const res = origDrawNode.apply(this, arguments)\r\n\r\n this.editor_alpha = editor_alpha\r\n node.color = old_color\r\n node.bgcolor = old_bgcolor\r\n\r\n return res\r\n }\r\n }\r\n\r\n /**\r\n * Handles updates from the API socket\r\n */\r\n #addApiUpdateHandlers() {\r\n api.addEventListener(\r\n 'status',\r\n ({ detail }: CustomEvent) => {\r\n this.ui.setStatus(detail)\r\n }\r\n )\r\n\r\n api.addEventListener('reconnecting', () => {\r\n this.ui.dialog.show('Reconnecting...')\r\n })\r\n\r\n api.addEventListener('reconnected', () => {\r\n this.ui.dialog.close()\r\n })\r\n\r\n api.addEventListener('progress', ({ detail }) => {\r\n if (\r\n this.workflowManager.activePrompt?.workflow &&\r\n this.workflowManager.activePrompt.workflow !==\r\n this.workflowManager.activeWorkflow\r\n )\r\n return\r\n this.progress = detail\r\n this.graph.setDirtyCanvas(true, false)\r\n })\r\n\r\n api.addEventListener('executing', ({ detail }) => {\r\n if (\r\n this.workflowManager.activePrompt?.workflow &&\r\n this.workflowManager.activePrompt.workflow !==\r\n this.workflowManager.activeWorkflow\r\n )\r\n return\r\n this.progress = null\r\n this.runningNodeId = detail\r\n this.graph.setDirtyCanvas(true, false)\r\n delete this.nodePreviewImages[this.runningNodeId]\r\n })\r\n\r\n api.addEventListener('executed', ({ detail }) => {\r\n if (\r\n this.workflowManager.activePrompt?.workflow &&\r\n this.workflowManager.activePrompt.workflow !==\r\n this.workflowManager.activeWorkflow\r\n )\r\n return\r\n const output = this.nodeOutputs[detail.display_node || detail.node]\r\n if (detail.merge && output) {\r\n for (const k in detail.output ?? {}) {\r\n const v = output[k]\r\n if (v instanceof Array) {\r\n output[k] = v.concat(detail.output[k])\r\n } else {\r\n output[k] = detail.output[k]\r\n }\r\n }\r\n } else {\r\n this.nodeOutputs[detail.display_node || detail.node] = detail.output\r\n }\r\n const node = this.graph.getNodeById(detail.display_node || detail.node)\r\n if (node) {\r\n // @ts-expect-error\r\n if (node.onExecuted)\r\n // @ts-expect-error\r\n node.onExecuted(detail.output)\r\n }\r\n })\r\n\r\n api.addEventListener('execution_start', ({ detail }) => {\r\n this.runningNodeId = null\r\n this.lastExecutionError = null\r\n // @ts-expect-error\r\n this.graph._nodes.forEach((node) => {\r\n // @ts-expect-error\r\n if (node.onExecutionStart)\r\n // @ts-expect-error\r\n node.onExecutionStart()\r\n })\r\n })\r\n\r\n api.addEventListener('execution_error', ({ detail }) => {\r\n this.lastExecutionError = detail\r\n const formattedError = this.#formatExecutionError(detail)\r\n this.ui.dialog.show(formattedError)\r\n this.canvas.draw(true, true)\r\n })\r\n\r\n api.addEventListener('b_preview', ({ detail }) => {\r\n const id = this.runningNodeId\r\n if (id == null) return\r\n\r\n const blob = detail\r\n const blobUrl = URL.createObjectURL(blob)\r\n // @ts-expect-error\r\n this.nodePreviewImages[id] = [blobUrl]\r\n })\r\n\r\n api.init()\r\n }\r\n\r\n #addKeyboardHandler() {\r\n window.addEventListener('keydown', (e) => {\r\n this.shiftDown = e.shiftKey\r\n })\r\n window.addEventListener('keyup', (e) => {\r\n this.shiftDown = e.shiftKey\r\n })\r\n }\r\n\r\n #addConfigureHandler() {\r\n const app = this\r\n const configure = LGraph.prototype.configure\r\n // Flag that the graph is configuring to prevent nodes from running checks while its still loading\r\n LGraph.prototype.configure = function () {\r\n app.configuringGraph = true\r\n try {\r\n return configure.apply(this, arguments)\r\n } finally {\r\n app.configuringGraph = false\r\n }\r\n }\r\n }\r\n\r\n #addAfterConfigureHandler() {\r\n const app = this\r\n // @ts-expect-error\r\n const onConfigure = app.graph.onConfigure\r\n // @ts-expect-error\r\n app.graph.onConfigure = function () {\r\n // Fire callbacks before the onConfigure, this is used by widget inputs to setup the config\r\n // @ts-expect-error\r\n for (const node of app.graph._nodes) {\r\n // @ts-expect-error\r\n node.onGraphConfigured?.()\r\n }\r\n\r\n const r = onConfigure?.apply(this, arguments)\r\n\r\n // Fire after onConfigure, used by primitives to generate widget using input nodes config\r\n // @ts-expect-error _nodes is private.\r\n for (const node of app.graph._nodes) {\r\n node.onAfterGraphConfigured?.()\r\n }\r\n\r\n return r\r\n }\r\n }\r\n\r\n /**\r\n * Loads all extensions from the API into the window in parallel\r\n */\r\n async #loadExtensions() {\r\n const extensions = await api.getExtensions()\r\n this.logging.addEntry('Comfy.App', 'debug', { Extensions: extensions })\r\n\r\n // Need to load core extensions first as some custom extensions\r\n // may depend on them.\r\n await import('../extensions/core/index')\r\n await Promise.all(\r\n extensions\r\n .filter((extension) => !extension.includes('extensions/core'))\r\n .map(async (ext) => {\r\n try {\r\n await import(/* @vite-ignore */ api.fileURL(ext))\r\n } catch (error) {\r\n console.error('Error loading extension', ext, error)\r\n }\r\n })\r\n )\r\n\r\n try {\r\n this.menu.workflows.registerExtension(this)\r\n } catch (error) {\r\n console.error(error)\r\n }\r\n }\r\n\r\n async #migrateSettings() {\r\n this.isNewUserSession = true\r\n // Store all current settings\r\n const settings = Object.keys(this.ui.settings).reduce((p, n) => {\r\n const v = localStorage[`Comfy.Settings.${n}`]\r\n if (v) {\r\n try {\r\n p[n] = JSON.parse(v)\r\n } catch (error) {}\r\n }\r\n return p\r\n }, {})\r\n\r\n await api.storeSettings(settings)\r\n }\r\n\r\n async #setUser() {\r\n const userConfig = await api.getUserConfig()\r\n this.storageLocation = userConfig.storage\r\n if (typeof userConfig.migrated == 'boolean') {\r\n // Single user mode migrated true/false for if the default user is created\r\n if (!userConfig.migrated && this.storageLocation === 'server') {\r\n // Default user not created yet\r\n await this.#migrateSettings()\r\n }\r\n return\r\n }\r\n\r\n this.multiUserServer = true\r\n let user = localStorage['Comfy.userId']\r\n const users = userConfig.users ?? {}\r\n if (!user || !users[user]) {\r\n // This will rarely be hit so move the loading to on demand\r\n const { UserSelectionScreen } = await import('./ui/userSelection')\r\n\r\n this.ui.menuContainer.style.display = 'none'\r\n const { userId, username, created } =\r\n await new UserSelectionScreen().show(users, user)\r\n this.ui.menuContainer.style.display = ''\r\n\r\n user = userId\r\n localStorage['Comfy.userName'] = username\r\n localStorage['Comfy.userId'] = user\r\n\r\n if (created) {\r\n api.user = user\r\n await this.#migrateSettings()\r\n }\r\n }\r\n\r\n api.user = user\r\n\r\n this.ui.settings.addSetting({\r\n id: 'Comfy.SwitchUser',\r\n name: 'Switch User',\r\n type: (name) => {\r\n let currentUser = localStorage['Comfy.userName']\r\n if (currentUser) {\r\n currentUser = ` (${currentUser})`\r\n }\r\n return $el('tr', [\r\n $el('td', [\r\n $el('label', {\r\n textContent: name\r\n })\r\n ]),\r\n $el('td', [\r\n $el('button', {\r\n textContent: name + (currentUser ?? ''),\r\n onclick: () => {\r\n delete localStorage['Comfy.userId']\r\n delete localStorage['Comfy.userName']\r\n window.location.reload()\r\n }\r\n })\r\n ])\r\n ])\r\n },\r\n // TODO: Is that the correct default value?\r\n defaultValue: undefined\r\n })\r\n }\r\n\r\n /**\r\n * Set up the app on the page\r\n */\r\n async setup(canvasEl: HTMLCanvasElement) {\r\n this.canvasEl = canvasEl\r\n await this.#setUser()\r\n\r\n // Create and mount the LiteGraph in the DOM\r\n const mainCanvas = document.createElement('canvas')\r\n mainCanvas.style.touchAction = 'none'\r\n\r\n this.resizeCanvas()\r\n\r\n await Promise.all([\r\n this.workflowManager.loadWorkflows(),\r\n this.ui.settings.load()\r\n ])\r\n await this.#loadExtensions()\r\n\r\n addDomClippingSetting()\r\n this.#addProcessMouseHandler()\r\n this.#addProcessKeyHandler()\r\n this.#addConfigureHandler()\r\n this.#addApiUpdateHandlers()\r\n this.#addRestoreWorkflowView()\r\n\r\n this.graph = new LGraph()\r\n\r\n this.#addAfterConfigureHandler()\r\n\r\n this.canvas = new LGraphCanvas(canvasEl, this.graph)\r\n this.ctx = canvasEl.getContext('2d')\r\n\r\n LiteGraph.alt_drag_do_clone_nodes = true\r\n\r\n this.graph.start()\r\n\r\n // Ensure the canvas fills the window\r\n this.resizeCanvas()\r\n window.addEventListener('resize', () => this.resizeCanvas())\r\n const ro = new ResizeObserver(() => this.resizeCanvas())\r\n ro.observe(this.bodyTop)\r\n ro.observe(this.bodyLeft)\r\n ro.observe(this.bodyRight)\r\n ro.observe(this.bodyBottom)\r\n\r\n await this.#invokeExtensionsAsync('init')\r\n await this.registerNodes()\r\n initWidgets(this)\r\n\r\n // Load previous workflow\r\n let restored = false\r\n try {\r\n const loadWorkflow = async (json) => {\r\n if (json) {\r\n const workflow = JSON.parse(json)\r\n const workflowName = getStorageValue('Comfy.PreviousWorkflow')\r\n await this.loadGraphData(workflow, true, true, workflowName)\r\n return true\r\n }\r\n }\r\n const clientId = api.initialClientId ?? api.clientId\r\n restored =\r\n (clientId &&\r\n (await loadWorkflow(\r\n sessionStorage.getItem(`workflow:${clientId}`)\r\n ))) ||\r\n (await loadWorkflow(localStorage.getItem('workflow')))\r\n } catch (err) {\r\n console.error('Error loading previous workflow', err)\r\n }\r\n\r\n // We failed to restore a workflow so load the default\r\n if (!restored) {\r\n await this.loadGraphData()\r\n }\r\n\r\n // Save current workflow automatically\r\n setInterval(() => {\r\n const workflow = JSON.stringify(this.graph.serialize())\r\n localStorage.setItem('workflow', workflow)\r\n if (api.clientId) {\r\n sessionStorage.setItem(`workflow:${api.clientId}`, workflow)\r\n }\r\n }, 1000)\r\n\r\n this.#addDrawNodeHandler()\r\n this.#addDrawGroupsHandler()\r\n this.#addDropHandler()\r\n this.#addCopyHandler()\r\n this.#addPasteHandler()\r\n this.#addKeyboardHandler()\r\n\r\n await this.#invokeExtensionsAsync('setup')\r\n }\r\n\r\n resizeCanvas() {\r\n // Limit minimal scale to 1, see https://github.com/comfyanonymous/ComfyUI/pull/845\r\n const scale = Math.max(window.devicePixelRatio, 1)\r\n\r\n // Clear fixed width and height while calculating rect so it uses 100% instead\r\n this.canvasEl.height = this.canvasEl.width = NaN\r\n const { width, height } = this.canvasEl.getBoundingClientRect()\r\n this.canvasEl.width = Math.round(width * scale)\r\n this.canvasEl.height = Math.round(height * scale)\r\n this.canvasEl.getContext('2d').scale(scale, scale)\r\n this.canvas?.draw(true, true)\r\n }\r\n\r\n /**\r\n * Registers nodes with the graph\r\n */\r\n async registerNodes() {\r\n // Load node definitions from the backend\r\n const defs = await api.getNodeDefs()\r\n await this.registerNodesFromDefs(defs)\r\n if (this.vueAppReady) {\r\n const nodeDefStore = useNodeDefStore()\r\n nodeDefStore.updateNodeDefs([...Object.values(defs), ...SYSTEM_NODE_DEFS])\r\n nodeDefStore.updateWidgets(this.widgets)\r\n }\r\n await this.#invokeExtensionsAsync('registerCustomNodes')\r\n }\r\n\r\n getWidgetType(inputData, inputName) {\r\n const type = inputData[0]\r\n\r\n if (Array.isArray(type)) {\r\n return 'COMBO'\r\n } else if (`${type}:${inputName}` in this.widgets) {\r\n return `${type}:${inputName}`\r\n } else if (type in this.widgets) {\r\n return type\r\n } else {\r\n return null\r\n }\r\n }\r\n\r\n async registerNodeDef(nodeId: string, nodeData: ComfyNodeDef) {\r\n const self = this\r\n const node = Object.assign(\r\n function ComfyNode() {\r\n var inputs = nodeData['input']['required']\r\n if (nodeData['input']['optional'] != undefined) {\r\n inputs = Object.assign(\r\n {},\r\n nodeData['input']['required'],\r\n nodeData['input']['optional']\r\n )\r\n }\r\n const config = { minWidth: 1, minHeight: 1 }\r\n for (const inputName in inputs) {\r\n const inputData = inputs[inputName]\r\n const type = inputData[0]\r\n\r\n let widgetCreated = true\r\n const widgetType = self.getWidgetType(inputData, inputName)\r\n if (widgetType) {\r\n if (widgetType === 'COMBO') {\r\n Object.assign(\r\n config,\r\n self.widgets.COMBO(this, inputName, inputData, app) || {}\r\n )\r\n } else {\r\n Object.assign(\r\n config,\r\n self.widgets[widgetType](this, inputName, inputData, app) || {}\r\n )\r\n }\r\n } else {\r\n // Node connection inputs\r\n this.addInput(inputName, type)\r\n widgetCreated = false\r\n }\r\n // @ts-expect-error\r\n if (widgetCreated && inputData[1]?.forceInput && config?.widget) {\r\n // @ts-expect-error\r\n if (!config.widget.options) config.widget.options = {}\r\n // @ts-expect-error\r\n config.widget.options.forceInput = inputData[1].forceInput\r\n }\r\n // @ts-expect-error\r\n if (widgetCreated && inputData[1]?.defaultInput && config?.widget) {\r\n // @ts-expect-error\r\n if (!config.widget.options) config.widget.options = {}\r\n // @ts-expect-error\r\n config.widget.options.defaultInput = inputData[1].defaultInput\r\n }\r\n }\r\n\r\n for (const o in nodeData['output']) {\r\n let output = nodeData['output'][o]\r\n if (output instanceof Array) output = 'COMBO'\r\n const outputName = nodeData['output_name'][o] || output\r\n const outputShape = nodeData['output_is_list'][o]\r\n ? LiteGraph.GRID_SHAPE\r\n : LiteGraph.CIRCLE_SHAPE\r\n this.addOutput(outputName, output, { shape: outputShape })\r\n }\r\n\r\n const s = this.computeSize()\r\n s[0] = Math.max(config.minWidth, s[0] * 1.5)\r\n s[1] = Math.max(config.minHeight, s[1])\r\n this.size = s\r\n this.serialize_widgets = true\r\n\r\n app.#invokeExtensionsAsync('nodeCreated', this)\r\n },\r\n {\r\n title: nodeData.display_name || nodeData.name,\r\n comfyClass: nodeData.name,\r\n nodeData\r\n }\r\n )\r\n node.prototype.comfyClass = nodeData.name\r\n\r\n this.#addNodeContextMenuHandler(node)\r\n this.#addDrawBackgroundHandler(node)\r\n this.#addNodeKeyHandler(node)\r\n\r\n await this.#invokeExtensionsAsync('beforeRegisterNodeDef', node, nodeData)\r\n // @ts-expect-error\r\n LiteGraph.registerNodeType(nodeId, node)\r\n // @ts-expect-error\r\n node.category = nodeData.category\r\n }\r\n\r\n async registerNodesFromDefs(defs: Record) {\r\n await this.#invokeExtensionsAsync('addCustomNodeDefs', defs)\r\n\r\n // Generate list of known widgets\r\n this.widgets = Object.assign(\r\n {},\r\n ComfyWidgets,\r\n ...(await this.#invokeExtensionsAsync('getCustomWidgets')).filter(Boolean)\r\n )\r\n\r\n // Register a node for each definition\r\n for (const nodeId in defs) {\r\n this.registerNodeDef(nodeId, defs[nodeId])\r\n }\r\n }\r\n\r\n loadTemplateData(templateData) {\r\n if (!templateData?.templates) {\r\n return\r\n }\r\n\r\n const old = localStorage.getItem('litegrapheditor_clipboard')\r\n\r\n var maxY, nodeBottom, node\r\n\r\n for (const template of templateData.templates) {\r\n if (!template?.data) {\r\n continue\r\n }\r\n\r\n localStorage.setItem('litegrapheditor_clipboard', template.data)\r\n app.canvas.pasteFromClipboard()\r\n\r\n // Move mouse position down to paste the next template below\r\n\r\n maxY = false\r\n\r\n for (const i in app.canvas.selected_nodes) {\r\n node = app.canvas.selected_nodes[i]\r\n\r\n nodeBottom = node.pos[1] + node.size[1]\r\n\r\n if (maxY === false || nodeBottom > maxY) {\r\n maxY = nodeBottom\r\n }\r\n }\r\n\r\n app.canvas.graph_mouse[1] = maxY + 50\r\n }\r\n\r\n localStorage.setItem('litegrapheditor_clipboard', old)\r\n }\r\n\r\n showMissingNodesError(missingNodeTypes, hasAddedNodes = true) {\r\n if (this.vueAppReady)\r\n showLoadWorkflowWarning({\r\n missingNodeTypes,\r\n hasAddedNodes,\r\n maximizable: true\r\n })\r\n\r\n this.logging.addEntry('Comfy.App', 'warn', {\r\n MissingNodes: missingNodeTypes\r\n })\r\n }\r\n\r\n async changeWorkflow(callback, workflow = null) {\r\n try {\r\n this.workflowManager.activeWorkflow?.changeTracker?.store()\r\n } catch (error) {\r\n console.error(error)\r\n }\r\n await callback()\r\n try {\r\n this.workflowManager.setWorkflow(workflow)\r\n this.workflowManager.activeWorkflow?.track()\r\n } catch (error) {\r\n console.error(error)\r\n }\r\n }\r\n\r\n async loadGraphData(\r\n graphData?: ComfyWorkflowJSON,\r\n clean: boolean = true,\r\n restore_view: boolean = true,\r\n workflow: string | null | ComfyWorkflow = null\r\n ) {\r\n if (clean !== false) {\r\n this.clean()\r\n }\r\n\r\n let reset_invalid_values = false\r\n if (!graphData) {\r\n graphData = defaultGraph\r\n reset_invalid_values = true\r\n }\r\n\r\n if (typeof structuredClone === 'undefined') {\r\n graphData = JSON.parse(JSON.stringify(graphData))\r\n } else {\r\n graphData = structuredClone(graphData)\r\n }\r\n\r\n try {\r\n this.workflowManager.setWorkflow(workflow)\r\n } catch (error) {\r\n console.error(error)\r\n }\r\n\r\n if (\r\n this.vueAppReady &&\r\n useSettingStore().get('Comfy.Validation.Workflows')\r\n ) {\r\n graphData = await validateComfyWorkflow(graphData, /* onError=*/ alert)\r\n if (!graphData) return\r\n }\r\n\r\n const missingNodeTypes = []\r\n await this.#invokeExtensionsAsync(\r\n 'beforeConfigureGraph',\r\n graphData,\r\n missingNodeTypes\r\n )\r\n for (let n of graphData.nodes) {\r\n // Patch T2IAdapterLoader to ControlNetLoader since they are the same node now\r\n if (n.type == 'T2IAdapterLoader') n.type = 'ControlNetLoader'\r\n if (n.type == 'ConditioningAverage ') n.type = 'ConditioningAverage' //typo fix\r\n if (n.type == 'SDV_img2vid_Conditioning')\r\n n.type = 'SVD_img2vid_Conditioning' //typo fix\r\n\r\n // Find missing node types\r\n if (!(n.type in LiteGraph.registered_node_types)) {\r\n missingNodeTypes.push(n.type)\r\n n.type = sanitizeNodeName(n.type)\r\n }\r\n }\r\n\r\n try {\r\n this.graph.configure(graphData)\r\n if (\r\n restore_view &&\r\n this.enableWorkflowViewRestore.value &&\r\n graphData.extra?.ds\r\n ) {\r\n // @ts-expect-error\r\n // Need to set strict: true for zod to match the type [number, number]\r\n // https://github.com/colinhacks/zod/issues/3056\r\n this.canvas.ds.offset = graphData.extra.ds.offset\r\n this.canvas.ds.scale = graphData.extra.ds.scale\r\n }\r\n\r\n try {\r\n this.workflowManager.activeWorkflow?.track()\r\n } catch (error) {\r\n // TODO: Do we want silently fail here?\r\n }\r\n } catch (error) {\r\n let errorHint = []\r\n // Try extracting filename to see if it was caused by an extension script\r\n const filename =\r\n error.fileName ||\r\n (error.stack || '').match(/(\\/extensions\\/.*\\.js)/)?.[1]\r\n const pos = (filename || '').indexOf('/extensions/')\r\n if (pos > -1) {\r\n errorHint.push(\r\n $el('span', {\r\n textContent: 'This may be due to the following script:'\r\n }),\r\n $el('br'),\r\n $el('span', {\r\n style: {\r\n fontWeight: 'bold'\r\n },\r\n textContent: filename.substring(pos)\r\n })\r\n )\r\n }\r\n\r\n // Show dialog to let the user know something went wrong loading the data\r\n this.ui.dialog.show(\r\n $el('div', [\r\n $el('p', {\r\n textContent: 'Loading aborted due to error reloading workflow data'\r\n }),\r\n $el('pre', {\r\n style: { padding: '5px', backgroundColor: 'rgba(255,0,0,0.2)' },\r\n textContent: error.toString()\r\n }),\r\n $el('pre', {\r\n style: {\r\n padding: '5px',\r\n color: '#ccc',\r\n fontSize: '10px',\r\n maxHeight: '50vh',\r\n overflow: 'auto',\r\n backgroundColor: 'rgba(0,0,0,0.2)'\r\n },\r\n textContent: error.stack || 'No stacktrace available'\r\n }),\r\n ...errorHint\r\n ]).outerHTML\r\n )\r\n\r\n return\r\n }\r\n // @ts-expect-error\r\n for (const node of this.graph._nodes) {\r\n const size = node.computeSize()\r\n size[0] = Math.max(node.size[0], size[0])\r\n size[1] = Math.max(node.size[1], size[1])\r\n node.size = size\r\n if (node.widgets) {\r\n // If you break something in the backend and want to patch workflows in the frontend\r\n // This is the place to do this\r\n for (let widget of node.widgets) {\r\n if (node.type == 'KSampler' || node.type == 'KSamplerAdvanced') {\r\n if (widget.name == 'sampler_name') {\r\n if (widget.value.startsWith('sample_')) {\r\n widget.value = widget.value.slice(7)\r\n }\r\n }\r\n }\r\n if (\r\n node.type == 'KSampler' ||\r\n node.type == 'KSamplerAdvanced' ||\r\n node.type == 'PrimitiveNode'\r\n ) {\r\n if (widget.name == 'control_after_generate') {\r\n if (widget.value === true) {\r\n widget.value = 'randomize'\r\n } else if (widget.value === false) {\r\n widget.value = 'fixed'\r\n }\r\n }\r\n }\r\n if (reset_invalid_values) {\r\n if (widget.type == 'combo') {\r\n if (\r\n !widget.options.values.includes(widget.value) &&\r\n widget.options.values.length > 0\r\n ) {\r\n widget.value = widget.options.values[0]\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n this.#invokeExtensions('loadedGraphNode', node)\r\n }\r\n\r\n if (missingNodeTypes.length) {\r\n this.showMissingNodesError(missingNodeTypes)\r\n }\r\n await this.#invokeExtensionsAsync('afterConfigureGraph', missingNodeTypes)\r\n requestAnimationFrame(() => {\r\n this.graph.setDirtyCanvas(true, true)\r\n })\r\n }\r\n\r\n /**\r\n * Converts the current graph workflow for sending to the API\r\n * @returns The workflow and node links\r\n */\r\n async graphToPrompt(graph = this.graph, clean = true) {\r\n for (const outerNode of this.graph.computeExecutionOrder(false)) {\r\n if (outerNode.widgets) {\r\n for (const widget of outerNode.widgets) {\r\n // Allow widgets to run callbacks before a prompt has been queued\r\n // e.g. random seed before every gen\r\n widget.beforeQueued?.()\r\n }\r\n }\r\n\r\n const innerNodes = outerNode.getInnerNodes\r\n ? outerNode.getInnerNodes()\r\n : [outerNode]\r\n for (const node of innerNodes) {\r\n if (node.isVirtualNode) {\r\n // Don't serialize frontend only nodes but let them make changes\r\n if (node.applyToGraph) {\r\n node.applyToGraph()\r\n }\r\n }\r\n }\r\n }\r\n\r\n const workflow = graph.serialize()\r\n const output = {}\r\n // Process nodes in order of execution\r\n for (const outerNode of graph.computeExecutionOrder(false)) {\r\n const skipNode = outerNode.mode === 2 || outerNode.mode === 4\r\n const innerNodes =\r\n !skipNode && outerNode.getInnerNodes\r\n ? outerNode.getInnerNodes()\r\n : [outerNode]\r\n for (const node of innerNodes) {\r\n if (node.isVirtualNode) {\r\n continue\r\n }\r\n\r\n if (node.mode === 2 || node.mode === 4) {\r\n // Don't serialize muted nodes\r\n continue\r\n }\r\n\r\n const inputs = {}\r\n const widgets = node.widgets\r\n\r\n // Store all widget values\r\n if (widgets) {\r\n for (const i in widgets) {\r\n const widget = widgets[i]\r\n if (!widget.options || widget.options.serialize !== false) {\r\n inputs[widget.name] = widget.serializeValue\r\n ? await widget.serializeValue(node, i)\r\n : widget.value\r\n }\r\n }\r\n }\r\n\r\n // Store all node links\r\n for (let i in node.inputs) {\r\n let parent = node.getInputNode(i)\r\n if (parent) {\r\n let link = node.getInputLink(i)\r\n while (parent.mode === 4 || parent.isVirtualNode) {\r\n let found = false\r\n if (parent.isVirtualNode) {\r\n link = parent.getInputLink(link.origin_slot)\r\n if (link) {\r\n parent = parent.getInputNode(link.target_slot)\r\n if (parent) {\r\n found = true\r\n }\r\n }\r\n } else if (link && parent.mode === 4) {\r\n let all_inputs = [link.origin_slot]\r\n if (parent.inputs) {\r\n all_inputs = all_inputs.concat(Object.keys(parent.inputs))\r\n for (let parent_input in all_inputs) {\r\n parent_input = all_inputs[parent_input]\r\n if (\r\n parent.inputs[parent_input]?.type === node.inputs[i].type\r\n ) {\r\n link = parent.getInputLink(parent_input)\r\n if (link) {\r\n parent = parent.getInputNode(parent_input)\r\n }\r\n found = true\r\n break\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (!found) {\r\n break\r\n }\r\n }\r\n\r\n if (link) {\r\n if (parent?.updateLink) {\r\n link = parent.updateLink(link)\r\n }\r\n if (link) {\r\n inputs[node.inputs[i].name] = [\r\n String(link.origin_id),\r\n parseInt(link.origin_slot)\r\n ]\r\n }\r\n }\r\n }\r\n }\r\n\r\n let node_data = {\r\n inputs,\r\n class_type: node.comfyClass\r\n }\r\n\r\n if (this.ui.settings.getSettingValue('Comfy.DevMode')) {\r\n // Ignored by the backend.\r\n node_data['_meta'] = {\r\n title: node.title\r\n }\r\n }\r\n\r\n output[String(node.id)] = node_data\r\n }\r\n }\r\n\r\n // Remove inputs connected to removed nodes\r\n if (clean) {\r\n for (const o in output) {\r\n for (const i in output[o].inputs) {\r\n if (\r\n Array.isArray(output[o].inputs[i]) &&\r\n output[o].inputs[i].length === 2 &&\r\n !output[output[o].inputs[i][0]]\r\n ) {\r\n delete output[o].inputs[i]\r\n }\r\n }\r\n }\r\n }\r\n\r\n return { workflow, output }\r\n }\r\n\r\n #formatPromptError(error) {\r\n if (error == null) {\r\n return '(unknown error)'\r\n } else if (typeof error === 'string') {\r\n return error\r\n } else if (error.stack && error.message) {\r\n return error.toString()\r\n } else if (error.response) {\r\n let message = error.response.error.message\r\n if (error.response.error.details)\r\n message += ': ' + error.response.error.details\r\n for (const [nodeID, nodeError] of Object.entries(\r\n error.response.node_errors\r\n )) {\r\n // @ts-expect-error\r\n message += '\\n' + nodeError.class_type + ':'\r\n // @ts-expect-error\r\n for (const errorReason of nodeError.errors) {\r\n message +=\r\n '\\n - ' + errorReason.message + ': ' + errorReason.details\r\n }\r\n }\r\n return message\r\n }\r\n return '(unknown error)'\r\n }\r\n\r\n #formatExecutionError(error) {\r\n if (error == null) {\r\n return '(unknown error)'\r\n }\r\n\r\n const traceback = error.traceback.join('')\r\n const nodeId = error.node_id\r\n const nodeType = error.node_type\r\n\r\n return `Error occurred when executing ${nodeType}:\\n\\n${error.exception_message}\\n\\n${traceback}`\r\n }\r\n\r\n async queuePrompt(number, batchCount = 1) {\r\n this.#queueItems.push({ number, batchCount })\r\n\r\n // Only have one action process the items so each one gets a unique seed correctly\r\n if (this.#processingQueue) {\r\n return\r\n }\r\n\r\n this.#processingQueue = true\r\n this.lastNodeErrors = null\r\n\r\n try {\r\n while (this.#queueItems.length) {\r\n ;({ number, batchCount } = this.#queueItems.pop())\r\n\r\n for (let i = 0; i < batchCount; i++) {\r\n const p = await this.graphToPrompt()\r\n\r\n try {\r\n const res = await api.queuePrompt(number, p)\r\n this.lastNodeErrors = res.node_errors\r\n if (this.lastNodeErrors.length > 0) {\r\n this.canvas.draw(true, true)\r\n } else {\r\n try {\r\n this.workflowManager.storePrompt({\r\n id: res.prompt_id,\r\n nodes: Object.keys(p.output)\r\n })\r\n } catch (error) {}\r\n }\r\n } catch (error) {\r\n const formattedError = this.#formatPromptError(error)\r\n this.ui.dialog.show(formattedError)\r\n if (error.response) {\r\n this.lastNodeErrors = error.response.node_errors\r\n this.canvas.draw(true, true)\r\n }\r\n break\r\n }\r\n\r\n for (const n of p.workflow.nodes) {\r\n const node = this.graph.getNodeById(n.id)\r\n if (node.widgets) {\r\n for (const widget of node.widgets) {\r\n // Allow widgets to run callbacks after a prompt has been queued\r\n // e.g. random seed after every gen\r\n // @ts-expect-error\r\n if (widget.afterQueued) {\r\n // @ts-expect-error\r\n widget.afterQueued()\r\n }\r\n }\r\n }\r\n }\r\n\r\n this.canvas.draw(true, true)\r\n await this.ui.queue.update()\r\n }\r\n }\r\n } finally {\r\n this.#processingQueue = false\r\n }\r\n api.dispatchEvent(\r\n new CustomEvent('promptQueued', { detail: { number, batchCount } })\r\n )\r\n return !this.lastNodeErrors\r\n }\r\n\r\n showErrorOnFileLoad(file) {\r\n this.ui.dialog.show(\r\n $el('div', [\r\n $el('p', { textContent: `Unable to find workflow in ${file.name}` })\r\n ]).outerHTML\r\n )\r\n }\r\n\r\n /**\r\n * Loads workflow data from the specified file\r\n * @param {File} file\r\n */\r\n async handleFile(file) {\r\n const removeExt = (f) => {\r\n if (!f) return f\r\n const p = f.lastIndexOf('.')\r\n if (p === -1) return f\r\n return f.substring(0, p)\r\n }\r\n const fileName = removeExt(file.name)\r\n if (file.type === 'image/png') {\r\n const pngInfo = await getPngMetadata(file)\r\n if (pngInfo?.workflow) {\r\n await this.loadGraphData(\r\n JSON.parse(pngInfo.workflow),\r\n true,\r\n true,\r\n fileName\r\n )\r\n } else if (pngInfo?.prompt) {\r\n this.loadApiJson(JSON.parse(pngInfo.prompt), fileName)\r\n } else if (pngInfo?.parameters) {\r\n this.changeWorkflow(() => {\r\n importA1111(this.graph, pngInfo.parameters)\r\n }, fileName)\r\n } else {\r\n this.showErrorOnFileLoad(file)\r\n }\r\n } else if (file.type === 'image/webp') {\r\n const pngInfo = await getWebpMetadata(file)\r\n // Support loading workflows from that webp custom node.\r\n const workflow = pngInfo?.workflow || pngInfo?.Workflow\r\n const prompt = pngInfo?.prompt || pngInfo?.Prompt\r\n\r\n if (workflow) {\r\n this.loadGraphData(JSON.parse(workflow), true, true, fileName)\r\n } else if (prompt) {\r\n this.loadApiJson(JSON.parse(prompt), fileName)\r\n } else {\r\n this.showErrorOnFileLoad(file)\r\n }\r\n } else if (file.type === 'audio/flac' || file.type === 'audio/x-flac') {\r\n const pngInfo = await getFlacMetadata(file)\r\n const workflow = pngInfo?.workflow || pngInfo?.Workflow\r\n const prompt = pngInfo?.prompt || pngInfo?.Prompt\r\n\r\n if (workflow) {\r\n this.loadGraphData(JSON.parse(workflow), true, true, fileName)\r\n } else if (prompt) {\r\n this.loadApiJson(JSON.parse(prompt), fileName)\r\n } else {\r\n this.showErrorOnFileLoad(file)\r\n }\r\n } else if (\r\n file.type === 'application/json' ||\r\n file.name?.endsWith('.json')\r\n ) {\r\n const reader = new FileReader()\r\n reader.onload = async () => {\r\n const readerResult = reader.result as string\r\n const jsonContent = JSON.parse(readerResult)\r\n if (jsonContent?.templates) {\r\n this.loadTemplateData(jsonContent)\r\n } else if (this.isApiJson(jsonContent)) {\r\n this.loadApiJson(jsonContent, fileName)\r\n } else {\r\n await this.loadGraphData(JSON.parse(readerResult), true, fileName)\r\n }\r\n }\r\n reader.readAsText(file)\r\n } else if (\r\n file.name?.endsWith('.latent') ||\r\n file.name?.endsWith('.safetensors')\r\n ) {\r\n const info = await getLatentMetadata(file)\r\n // TODO define schema to LatentMetadata\r\n // @ts-expect-error\r\n if (info.workflow) {\r\n await this.loadGraphData(\r\n // @ts-expect-error\r\n JSON.parse(info.workflow),\r\n true,\r\n true,\r\n fileName\r\n )\r\n // @ts-expect-error\r\n } else if (info.prompt) {\r\n // @ts-expect-error\r\n this.loadApiJson(JSON.parse(info.prompt))\r\n } else {\r\n this.showErrorOnFileLoad(file)\r\n }\r\n } else {\r\n this.showErrorOnFileLoad(file)\r\n }\r\n }\r\n\r\n isApiJson(data) {\r\n // @ts-expect-error\r\n return Object.values(data).every((v) => v.class_type)\r\n }\r\n\r\n loadApiJson(apiData, fileName: string) {\r\n const missingNodeTypes = Object.values(apiData).filter(\r\n // @ts-expect-error\r\n (n) => !LiteGraph.registered_node_types[n.class_type]\r\n )\r\n if (missingNodeTypes.length) {\r\n this.showMissingNodesError(\r\n // @ts-expect-error\r\n missingNodeTypes.map((t) => t.class_type),\r\n false\r\n )\r\n return\r\n }\r\n\r\n const ids = Object.keys(apiData)\r\n app.graph.clear()\r\n for (const id of ids) {\r\n const data = apiData[id]\r\n const node = LiteGraph.createNode(data.class_type)\r\n // @ts-expect-error\r\n node.id = isNaN(+id) ? id : +id\r\n node.title = data._meta?.title ?? node.title\r\n app.graph.add(node)\r\n }\r\n\r\n this.changeWorkflow(() => {\r\n for (const id of ids) {\r\n const data = apiData[id]\r\n const node = app.graph.getNodeById(Number.parseInt(id))\r\n for (const input in data.inputs ?? {}) {\r\n const value = data.inputs[input]\r\n if (value instanceof Array) {\r\n const [fromId, fromSlot] = value\r\n const fromNode = app.graph.getNodeById(fromId)\r\n let toSlot = node.inputs?.findIndex((inp) => inp.name === input)\r\n if (toSlot == null || toSlot === -1) {\r\n try {\r\n // Target has no matching input, most likely a converted widget\r\n const widget = node.widgets?.find((w) => w.name === input)\r\n // @ts-expect-error\r\n if (widget && node.convertWidgetToInput?.(widget)) {\r\n toSlot = node.inputs?.length - 1\r\n }\r\n } catch (error) {}\r\n }\r\n if (toSlot != null || toSlot !== -1) {\r\n fromNode.connect(fromSlot, node, toSlot)\r\n }\r\n } else {\r\n const widget = node.widgets?.find((w) => w.name === input)\r\n if (widget) {\r\n widget.value = value\r\n // @ts-expect-error\r\n widget.callback?.(value)\r\n }\r\n }\r\n }\r\n }\r\n app.graph.arrange()\r\n }, fileName)\r\n\r\n for (const id of ids) {\r\n const data = apiData[id]\r\n const node = app.graph.getNodeById(Number.parseInt(id))\r\n for (const input in data.inputs ?? {}) {\r\n const value = data.inputs[input]\r\n if (value instanceof Array) {\r\n const [fromId, fromSlot] = value\r\n const fromNode = app.graph.getNodeById(fromId)\r\n let toSlot = node.inputs?.findIndex((inp) => inp.name === input)\r\n if (toSlot == null || toSlot === -1) {\r\n try {\r\n // Target has no matching input, most likely a converted widget\r\n const widget = node.widgets?.find((w) => w.name === input)\r\n // @ts-expect-error\r\n if (widget && node.convertWidgetToInput?.(widget)) {\r\n toSlot = node.inputs?.length - 1\r\n }\r\n } catch (error) {}\r\n }\r\n if (toSlot != null || toSlot !== -1) {\r\n fromNode.connect(fromSlot, node, toSlot)\r\n }\r\n } else {\r\n const widget = node.widgets?.find((w) => w.name === input)\r\n if (widget) {\r\n widget.value = value\r\n // @ts-expect-error\r\n widget.callback?.(value)\r\n }\r\n }\r\n }\r\n }\r\n\r\n app.graph.arrange()\r\n }\r\n\r\n /**\r\n * Registers a Comfy web extension with the app\r\n * @param {ComfyExtension} extension\r\n */\r\n registerExtension(extension) {\r\n if (!extension.name) {\r\n throw new Error(\"Extensions must have a 'name' property.\")\r\n }\r\n if (this.extensions.find((ext) => ext.name === extension.name)) {\r\n throw new Error(`Extension named '${extension.name}' already registered.`)\r\n }\r\n this.extensions.push(extension)\r\n }\r\n\r\n /**\r\n * Refresh combo list on whole nodes\r\n */\r\n async refreshComboInNodes() {\r\n const defs = await api.getNodeDefs()\r\n\r\n for (const nodeId in defs) {\r\n this.registerNodeDef(nodeId, defs[nodeId])\r\n }\r\n // @ts-expect-error\r\n for (let nodeNum in this.graph._nodes) {\r\n // @ts-expect-error\r\n const node = this.graph._nodes[nodeNum]\r\n const def = defs[node.type]\r\n // @ts-expect-error\r\n // Allow primitive nodes to handle refresh\r\n node.refreshComboInNode?.(defs)\r\n\r\n if (!def) continue\r\n\r\n for (const widgetNum in node.widgets) {\r\n const widget = node.widgets[widgetNum]\r\n if (\r\n widget.type == 'combo' &&\r\n def['input']['required'][widget.name] !== undefined\r\n ) {\r\n widget.options.values = def['input']['required'][widget.name][0]\r\n\r\n if (\r\n widget.name != 'image' &&\r\n !widget.options.values.includes(widget.value)\r\n ) {\r\n widget.value = widget.options.values[0]\r\n // @ts-expect-error\r\n widget.callback(widget.value)\r\n }\r\n }\r\n }\r\n }\r\n\r\n await this.#invokeExtensionsAsync('refreshComboInNodes', defs)\r\n }\r\n\r\n resetView() {\r\n app.canvas.ds.scale = 1\r\n app.canvas.ds.offset = [0, 0]\r\n app.graph.setDirtyCanvas(true, true)\r\n }\r\n\r\n /**\r\n * Clean current state\r\n */\r\n clean() {\r\n this.nodeOutputs = {}\r\n this.nodePreviewImages = {}\r\n this.lastNodeErrors = null\r\n this.lastExecutionError = null\r\n this.runningNodeId = null\r\n }\r\n\r\n addNodeOnGraph(\r\n nodeDef: ComfyNodeDef | ComfyNodeDefImpl,\r\n options: Record = {}\r\n ): LGraphNode {\r\n const node = LiteGraph.createNode(\r\n nodeDef.name,\r\n nodeDef.display_name,\r\n options\r\n )\r\n this.graph.add(node)\r\n return node\r\n }\r\n\r\n clientPosToCanvasPos(pos: Vector2): Vector2 {\r\n const rect = this.canvasContainer.getBoundingClientRect()\r\n const containerOffsets = [rect.left, rect.top]\r\n return _.zip(pos, this.canvas.ds.offset, containerOffsets).map(\r\n ([p, o1, o2]) => (p - o2) / this.canvas.ds.scale - o1\r\n ) as Vector2\r\n }\r\n}\r\n\r\nexport const app = new ComfyApp()\r\n","export enum LinkReleaseTriggerMode {\r\n ALWAYS = 'always',\r\n HOLD_SHIFT = 'hold shift',\r\n NOT_HOLD_SHIFT = 'NOT hold shift'\r\n}\r\n","/**\r\n * TODO: Migrate scripts/ui/settings.ts here\r\n *\r\n * Currently the reactive settings act as a proxy of the legacy settings.\r\n * Every time a setting is changed, the settingStore dispatch the change to the\r\n * legacy settings. Every time the legacy settings are changed, the legacy\r\n * settings directly updates the settingStore.settingValues.\r\n */\r\n\r\nimport { app } from '@/scripts/app'\r\nimport { ComfySettingsDialog } from '@/scripts/ui/settings'\r\nimport { LinkReleaseTriggerMode } from '@/types/searchBoxTypes'\r\nimport { SettingParams } from '@/types/settingTypes'\r\nimport { buildTree } from '@/utils/treeUtil'\r\nimport { defineStore } from 'pinia'\r\nimport type { TreeNode } from 'primevue/treenode'\r\n\r\nexport interface SettingTreeNode extends TreeNode {\r\n data?: SettingParams\r\n}\r\n\r\ninterface State {\r\n settingValues: Record\r\n settings: Record\r\n}\r\n\r\nexport const useSettingStore = defineStore('setting', {\r\n state: (): State => ({\r\n settingValues: {},\r\n settings: {}\r\n }),\r\n getters: {\r\n settingTree(): SettingTreeNode {\r\n const root = buildTree(\r\n Object.values(this.settings),\r\n (setting: SettingParams) => setting.id.split('.')\r\n )\r\n\r\n const floatingSettings = root.children.filter((node) => node.leaf)\r\n if (floatingSettings.length) {\r\n root.children = root.children.filter((node) => !node.leaf)\r\n root.children.push({\r\n key: 'Other',\r\n label: 'Other',\r\n leaf: false,\r\n children: floatingSettings\r\n })\r\n }\r\n\r\n return root\r\n }\r\n },\r\n actions: {\r\n addSettings(settings: ComfySettingsDialog) {\r\n for (const id in settings.settingsLookup) {\r\n const value = settings.getSettingValue(id)\r\n this.settingValues[id] = value\r\n }\r\n this.settings = settings.settingsParamLookup\r\n\r\n app.ui.settings.addSetting({\r\n id: 'Comfy.Validation.Workflows',\r\n name: 'Validate workflows',\r\n type: 'boolean',\r\n defaultValue: true\r\n })\r\n\r\n app.ui.settings.addSetting({\r\n id: 'Comfy.NodeSearchBoxImpl',\r\n name: 'Node Search box implementation',\r\n type: 'combo',\r\n options: ['default', 'litegraph (legacy)'],\r\n defaultValue: 'default'\r\n })\r\n\r\n app.ui.settings.addSetting({\r\n id: 'Comfy.NodeSearchBoxImpl.LinkReleaseTrigger',\r\n name: 'Trigger on link release',\r\n tooltip: 'Only applies to the default implementation',\r\n type: 'combo',\r\n options: Object.values(LinkReleaseTriggerMode),\r\n defaultValue: LinkReleaseTriggerMode.ALWAYS\r\n })\r\n\r\n app.ui.settings.addSetting({\r\n id: 'Comfy.NodeSearchBoxImpl.NodePreview',\r\n name: 'Node Preview',\r\n tooltip: 'Only applies to the default implementation',\r\n type: 'boolean',\r\n defaultValue: true\r\n })\r\n\r\n app.ui.settings.addSetting({\r\n id: 'Comfy.Sidebar.Location',\r\n name: 'Sidebar location',\r\n type: 'combo',\r\n options: ['left', 'right'],\r\n defaultValue: 'left'\r\n })\r\n\r\n app.ui.settings.addSetting({\r\n id: 'Comfy.Sidebar.Size',\r\n name: 'Sidebar size',\r\n type: 'combo',\r\n options: ['normal', 'small'],\r\n defaultValue: window.innerWidth < 1600 ? 'small' : 'normal'\r\n })\r\n },\r\n\r\n set(key: string, value: any) {\r\n this.settingValues[key] = value\r\n app.ui.settings.setSettingValue(key, value)\r\n },\r\n\r\n get(key: string): T {\r\n return (\r\n this.settingValues[key] ?? app.ui.settings.getSettingDefaultValue(key)\r\n )\r\n }\r\n }\r\n})\r\n","\r\n \r\n\r\n\r\n\r\n","import BaseStyle from '@primevue/core/base/style';\n\nvar theme = function theme(_ref) {\n var dt = _ref.dt;\n return \"\\n.p-tabs {\\n display: flex;\\n flex-direction: column;\\n}\\n\\n.p-tablist {\\n position: relative;\\n}\\n\\n.p-tabs-scrollable > .p-tablist {\\n overflow: hidden;\\n}\\n\\n.p-tablist-viewport {\\n overflow-x: auto;\\n overflow-y: hidden;\\n scroll-behavior: smooth;\\n scrollbar-width: none;\\n overscroll-behavior: contain auto;\\n}\\n\\n.p-tablist-viewport::-webkit-scrollbar {\\n display: none;\\n}\\n\\n.p-tablist-tab-list {\\n position: relative;\\n display: flex;\\n background: \".concat(dt('tabs.tablist.background'), \";\\n border-style: solid;\\n border-color: \").concat(dt('tabs.tablist.border.color'), \";\\n border-width: \").concat(dt('tabs.tablist.border.width'), \";\\n}\\n\\n.p-tablist-nav-button {\\n all: unset;\\n position: absolute;\\n top: 0;\\n z-index: 2;\\n height: 100%;\\n display: flex;\\n align-items: center;\\n justify-content: center;\\n background: \").concat(dt('tabs.nav.button.background'), \";\\n color: \").concat(dt('tabs.nav.button.color'), \";\\n width: \").concat(dt('tabs.nav.button.width'), \";\\n transition: color \").concat(dt('tabs.transition.duration'), \", outline-color \").concat(dt('tabs.transition.duration'), \", box-shadow \").concat(dt('tabs.transition.duration'), \";\\n box-shadow: \").concat(dt('tabs.nav.button.shadow'), \";\\n outline-color: transparent;\\n cursor: pointer;\\n}\\n\\n.p-tablist-nav-button:focus-visible {\\n z-index: 1;\\n box-shadow: \").concat(dt('tabs.nav.button.focus.ring.shadow'), \";\\n outline: \").concat(dt('tabs.nav.button.focus.ring.width'), \" \").concat(dt('tabs.nav.button.focus.ring.style'), \" \").concat(dt('tabs.nav.button.focus.ring.color'), \";\\n outline-offset: \").concat(dt('tabs.nav.button.focus.ring.offset'), \";\\n}\\n\\n.p-tablist-nav-button:hover {\\n color: \").concat(dt('tabs.nav.button.hover.color'), \";\\n}\\n\\n.p-tablist-prev-button {\\n left: 0;\\n}\\n\\n.p-tablist-next-button {\\n right: 0;\\n}\\n\\n.p-tab {\\n cursor: pointer;\\n user-select: none;\\n position: relative;\\n border-style: solid;\\n white-space: nowrap;\\n background: \").concat(dt('tabs.tab.background'), \";\\n border-width: \").concat(dt('tabs.tab.border.width'), \";\\n border-color: \").concat(dt('tabs.tab.border.color'), \";\\n color: \").concat(dt('tabs.tab.color'), \";\\n padding: \").concat(dt('tabs.tab.padding'), \";\\n font-weight: \").concat(dt('tabs.tab.font.weight'), \";\\n transition: background \").concat(dt('tabs.transition.duration'), \", border-color \").concat(dt('tabs.transition.duration'), \", color \").concat(dt('tabs.transition.duration'), \", outline-color \").concat(dt('tabs.transition.duration'), \", box-shadow \").concat(dt('tabs.transition.duration'), \";\\n margin: \").concat(dt('tabs.tab.margin'), \";\\n outline-color: transparent;\\n}\\n\\n.p-tab:not(.p-disabled):focus-visible {\\n z-index: 1;\\n box-shadow: \").concat(dt('tabs.tab.focus.ring.shadow'), \";\\n outline: \").concat(dt('tabs.tab.focus.ring.width'), \" \").concat(dt('tabs.tab.focus.ring.style'), \" \").concat(dt('tabs.tab.focus.ring.color'), \";\\n outline-offset: \").concat(dt('tabs.tab.focus.ring.offset'), \";\\n}\\n\\n.p-tab:not(.p-tab-active):not(.p-disabled):hover {\\n background: \").concat(dt('tabs.tab.hover.background'), \";\\n border-color: \").concat(dt('tabs.tab.hover.border.color'), \";\\n color: \").concat(dt('tabs.tab.hover.color'), \";\\n}\\n\\n.p-tab-active {\\n background: \").concat(dt('tabs.tab.active.background'), \";\\n border-color: \").concat(dt('tabs.tab.active.border.color'), \";\\n color: \").concat(dt('tabs.tab.active.color'), \";\\n}\\n\\n.p-tabpanels {\\n background: \").concat(dt('tabs.tabpanel.background'), \";\\n color: \").concat(dt('tabs.tabpanel.color'), \";\\n padding: \").concat(dt('tabs.tabpanel.padding'), \";\\n outline: 0 none;\\n}\\n\\n.p-tabpanel:focus-visible {\\n box-shadow: \").concat(dt('tabs.tabpanel.focus.ring.shadow'), \";\\n outline: \").concat(dt('tabs.tabpanel.focus.ring.width'), \" \").concat(dt('tabs.tabpanel.focus.ring.style'), \" \").concat(dt('tabs.tabpanel.focus.ring.color'), \";\\n outline-offset: \").concat(dt('tabs.tabpanel.focus.ring.offset'), \";\\n}\\n\\n.p-tablist-active-bar {\\n z-index: 1;\\n display: block;\\n position: absolute;\\n bottom: \").concat(dt('tabs.active.bar.bottom'), \";\\n height: \").concat(dt('tabs.active.bar.height'), \";\\n background: \").concat(dt('tabs.active.bar.background'), \";\\n transition: 250ms cubic-bezier(0.35, 0, 0.25, 1);\\n}\\n\");\n};\nvar classes = {\n root: function root(_ref2) {\n var props = _ref2.props;\n return ['p-tabs p-component', {\n 'p-tabs-scrollable': props.scrollable\n }];\n }\n};\nvar TabsStyle = BaseStyle.extend({\n name: 'tabs',\n theme: theme,\n classes: classes\n});\n\nexport { TabsStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import { UniqueComponentId } from '@primevue/core/utils';\nimport BaseComponent from '@primevue/core/basecomponent';\nimport TabsStyle from 'primevue/tabs/style';\nimport { openBlock, createElementBlock, mergeProps, renderSlot } from 'vue';\n\nvar script$1 = {\n name: 'BaseTabs',\n \"extends\": BaseComponent,\n props: {\n value: {\n type: String,\n \"default\": undefined\n },\n lazy: {\n type: Boolean,\n \"default\": false\n },\n scrollable: {\n type: Boolean,\n \"default\": false\n },\n showNavigators: {\n type: Boolean,\n \"default\": true\n },\n tabindex: {\n type: Number,\n \"default\": 0\n },\n selectOnFocus: {\n type: Boolean,\n \"default\": false\n }\n },\n style: TabsStyle,\n provide: function provide() {\n return {\n $pcTabs: this,\n $parentInstance: this\n };\n }\n};\n\nvar script = {\n name: 'Tabs',\n \"extends\": script$1,\n inheritAttrs: false,\n emits: ['update:value'],\n data: function data() {\n return {\n id: this.$attrs.id,\n d_value: this.value\n };\n },\n watch: {\n '$attrs.id': function $attrsId(newValue) {\n this.id = newValue || UniqueComponentId();\n },\n value: function value(newValue) {\n this.d_value = newValue;\n }\n },\n mounted: function mounted() {\n this.id = this.id || UniqueComponentId();\n },\n methods: {\n updateValue: function updateValue(newValue) {\n if (this.d_value !== newValue) {\n this.d_value = newValue;\n this.$emit('update:value', newValue);\n }\n },\n isVertical: function isVertical() {\n return this.orientation === 'vertical';\n }\n }\n};\n\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"div\", mergeProps({\n \"class\": _ctx.cx('root')\n }, _ctx.ptmi('root')), [renderSlot(_ctx.$slots, \"default\")], 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseStyle from '@primevue/core/base/style';\n\nvar classes = {\n root: 'p-tabpanels'\n};\nvar TabPanelsStyle = BaseStyle.extend({\n name: 'tabpanels',\n classes: classes\n});\n\nexport { TabPanelsStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseComponent from '@primevue/core/basecomponent';\nimport TabPanelsStyle from 'primevue/tabpanels/style';\nimport { openBlock, createElementBlock, mergeProps, renderSlot } from 'vue';\n\nvar script$1 = {\n name: 'BaseTabPanels',\n \"extends\": BaseComponent,\n props: {},\n style: TabPanelsStyle,\n provide: function provide() {\n return {\n $pcTabPanels: this,\n $parentInstance: this\n };\n }\n};\n\nvar script = {\n name: 'TabPanels',\n \"extends\": script$1,\n inheritAttrs: false\n};\n\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"div\", mergeProps({\n \"class\": _ctx.cx('root'),\n role: \"presentation\"\n }, _ctx.ptmi('root')), [renderSlot(_ctx.$slots, \"default\")], 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseStyle from '@primevue/core/base/style';\n\nvar classes = {\n root: function root(_ref) {\n var instance = _ref.instance;\n return ['p-tabpanel', {\n 'p-tabpanel-active': instance.active\n }];\n }\n};\nvar TabPanelStyle = BaseStyle.extend({\n name: 'tabpanel',\n classes: classes\n});\n\nexport { TabPanelStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import { equals } from '@primeuix/utils/object';\nimport { mergeProps, renderSlot, openBlock, createElementBlock, Fragment, withDirectives, createBlock, resolveDynamicComponent, withCtx, vShow, createCommentVNode, normalizeClass } from 'vue';\nimport BaseComponent from '@primevue/core/basecomponent';\nimport TabPanelStyle from 'primevue/tabpanel/style';\n\nvar script$1 = {\n name: 'BaseTabPanel',\n \"extends\": BaseComponent,\n props: {\n // in Tabs\n value: {\n type: String,\n \"default\": undefined\n },\n as: {\n type: String,\n \"default\": 'DIV'\n },\n asChild: {\n type: Boolean,\n \"default\": false\n },\n // in TabView\n header: null,\n headerStyle: null,\n headerClass: null,\n headerProps: null,\n headerActionProps: null,\n contentStyle: null,\n contentClass: null,\n contentProps: null,\n disabled: Boolean\n },\n style: TabPanelStyle,\n provide: function provide() {\n return {\n $pcTabPanel: this,\n $parentInstance: this\n };\n }\n};\n\nvar script = {\n name: 'TabPanel',\n \"extends\": script$1,\n inheritAttrs: false,\n inject: ['$pcTabs'],\n computed: {\n active: function active() {\n var _this$$pcTabs;\n return equals((_this$$pcTabs = this.$pcTabs) === null || _this$$pcTabs === void 0 ? void 0 : _this$$pcTabs.d_value, this.value);\n },\n id: function id() {\n var _this$$pcTabs2;\n return \"\".concat((_this$$pcTabs2 = this.$pcTabs) === null || _this$$pcTabs2 === void 0 ? void 0 : _this$$pcTabs2.id, \"_tabpanel_\").concat(this.value);\n },\n ariaLabelledby: function ariaLabelledby() {\n var _this$$pcTabs3;\n return \"\".concat((_this$$pcTabs3 = this.$pcTabs) === null || _this$$pcTabs3 === void 0 ? void 0 : _this$$pcTabs3.id, \"_tab_\").concat(this.value);\n },\n attrs: function attrs() {\n return mergeProps(this.a11yAttrs, this.ptmi('root', this.ptParams));\n },\n a11yAttrs: function a11yAttrs() {\n var _this$$pcTabs4;\n return {\n id: this.id,\n tabindex: (_this$$pcTabs4 = this.$pcTabs) === null || _this$$pcTabs4 === void 0 ? void 0 : _this$$pcTabs4.tabindex,\n role: 'tabpanel',\n 'aria-labelledby': this.ariaLabelledby,\n 'data-pc-name': 'tabpanel',\n 'data-p-active': this.active\n };\n },\n ptParams: function ptParams() {\n return {\n context: {\n active: this.active\n }\n };\n }\n }\n};\n\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n var _$options$$pcTabs, _$options$$pcTabs2;\n return !$options.$pcTabs ? renderSlot(_ctx.$slots, \"default\", {\n key: 0\n }) : (openBlock(), createElementBlock(Fragment, {\n key: 1\n }, [!_ctx.asChild ? (openBlock(), createElementBlock(Fragment, {\n key: 0\n }, [((_$options$$pcTabs = $options.$pcTabs) !== null && _$options$$pcTabs !== void 0 && _$options$$pcTabs.lazy ? $options.active : true) ? withDirectives((openBlock(), createBlock(resolveDynamicComponent(_ctx.as), mergeProps({\n key: 0,\n \"class\": _ctx.cx('root')\n }, $options.attrs), {\n \"default\": withCtx(function () {\n return [renderSlot(_ctx.$slots, \"default\")];\n }),\n _: 3\n }, 16, [\"class\"])), [[vShow, (_$options$$pcTabs2 = $options.$pcTabs) !== null && _$options$$pcTabs2 !== void 0 && _$options$$pcTabs2.lazy ? true : $options.active]]) : createCommentVNode(\"\", true)], 64)) : renderSlot(_ctx.$slots, \"default\", {\n key: 1,\n \"class\": normalizeClass(_ctx.cx('root')),\n active: $options.active,\n a11yAttrs: $options.a11yAttrs\n })], 64));\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseStyle from '@primevue/core/base/style';\n\nvar theme = function theme(_ref) {\n var dt = _ref.dt;\n return \"\\n.p-divider-horizontal {\\n display: flex;\\n width: 100%;\\n position: relative;\\n align-items: center;\\n margin: \".concat(dt('divider.horizontal.margin'), \";\\n padding: \").concat(dt('divider.horizontal.padding'), \";\\n}\\n\\n.p-divider-horizontal:before {\\n position: absolute;\\n display: block;\\n top: 50%;\\n left: 0;\\n width: 100%;\\n content: \\\"\\\";\\n border-top: 1px solid \").concat(dt('divider.border.color'), \";\\n}\\n\\n.p-divider-horizontal .p-divider-content {\\n padding: \").concat(dt('divider.horizontal.content.padding'), \";\\n}\\n\\n.p-divider-vertical {\\n min-height: 100%;\\n margin: 0 1rem;\\n display: flex;\\n position: relative;\\n justify-content: center;\\n margin: \").concat(dt('divider.vertical.margin'), \";\\n padding: \").concat(dt('divider.vertical.padding'), \";\\n}\\n\\n.p-divider-vertical:before {\\n position: absolute;\\n display: block;\\n top: 0;\\n left: 50%;\\n height: 100%;\\n content: \\\"\\\";\\n border-left: 1px solid \").concat(dt('divider.border.color'), \";\\n}\\n\\n.p-divider.p-divider-vertical .p-divider-content {\\n padding: \").concat(dt('divider.vertical.content.padding'), \";\\n}\\n\\n.p-divider-content {\\n z-index: 1;\\n background: \").concat(dt('divider.content.background'), \";\\n color: \").concat(dt('divider.content.color'), \";\\n}\\n\\n.p-divider-solid.p-divider-horizontal:before {\\n border-top-style: solid;\\n}\\n\\n.p-divider-solid.p-divider-vertical:before {\\n border-left-style: solid;\\n}\\n\\n.p-divider-dashed.p-divider-horizontal:before {\\n border-top-style: dashed;\\n}\\n\\n.p-divider-dashed.p-divider-vertical:before {\\n border-left-style: dashed;\\n}\\n\\n.p-divider-dotted.p-divider-horizontal:before {\\n border-top-style: dotted;\\n}\\n\\n.p-divider-dotted.p-divider-vertical:before {\\n border-left-style: dotted;\\n}\\n\");\n};\n\n/* Position */\nvar inlineStyles = {\n root: function root(_ref2) {\n var props = _ref2.props;\n return {\n justifyContent: props.layout === 'horizontal' ? props.align === 'center' || props.align === null ? 'center' : props.align === 'left' ? 'flex-start' : props.align === 'right' ? 'flex-end' : null : null,\n alignItems: props.layout === 'vertical' ? props.align === 'center' || props.align === null ? 'center' : props.align === 'top' ? 'flex-start' : props.align === 'bottom' ? 'flex-end' : null : null\n };\n }\n};\nvar classes = {\n root: function root(_ref3) {\n var props = _ref3.props;\n return ['p-divider p-component', 'p-divider-' + props.layout, 'p-divider-' + props.type, {\n 'p-divider-left': props.layout === 'horizontal' && (!props.align || props.align === 'left')\n }, {\n 'p-divider-center': props.layout === 'horizontal' && props.align === 'center'\n }, {\n 'p-divider-right': props.layout === 'horizontal' && props.align === 'right'\n }, {\n 'p-divider-top': props.layout === 'vertical' && props.align === 'top'\n }, {\n 'p-divider-center': props.layout === 'vertical' && (!props.align || props.align === 'center')\n }, {\n 'p-divider-bottom': props.layout === 'vertical' && props.align === 'bottom'\n }];\n },\n content: 'p-divider-content'\n};\nvar DividerStyle = BaseStyle.extend({\n name: 'divider',\n theme: theme,\n classes: classes,\n inlineStyles: inlineStyles\n});\n\nexport { DividerStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseComponent from '@primevue/core/basecomponent';\nimport DividerStyle from 'primevue/divider/style';\nimport { openBlock, createElementBlock, mergeProps, renderSlot, createCommentVNode } from 'vue';\n\nvar script$1 = {\n name: 'BaseDivider',\n \"extends\": BaseComponent,\n props: {\n align: {\n type: String,\n \"default\": null\n },\n layout: {\n type: String,\n \"default\": 'horizontal'\n },\n type: {\n type: String,\n \"default\": 'solid'\n }\n },\n style: DividerStyle,\n provide: function provide() {\n return {\n $pcDivider: this,\n $parentInstance: this\n };\n }\n};\n\nvar script = {\n name: 'Divider',\n \"extends\": script$1,\n inheritAttrs: false\n};\n\nvar _hoisted_1 = [\"aria-orientation\"];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"div\", mergeProps({\n \"class\": _ctx.cx('root'),\n style: _ctx.sx('root'),\n role: \"separator\",\n \"aria-orientation\": _ctx.layout\n }, _ctx.ptmi('root')), [_ctx.$slots[\"default\"] ? (openBlock(), createElementBlock(\"div\", mergeProps({\n key: 0,\n \"class\": _ctx.cx('content')\n }, _ctx.ptm('content')), [renderSlot(_ctx.$slots, \"default\")], 16)) : createCommentVNode(\"\", true)], 16, _hoisted_1);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseIcon from '@primevue/icons/baseicon';\nimport { openBlock, createElementBlock, mergeProps, createElementVNode } from 'vue';\n\nvar script = {\n name: 'AngleDownIcon',\n \"extends\": BaseIcon\n};\n\nvar _hoisted_1 = /*#__PURE__*/createElementVNode(\"path\", {\n d: \"M3.58659 4.5007C3.68513 4.50023 3.78277 4.51945 3.87379 4.55723C3.9648 4.59501 4.04735 4.65058 4.11659 4.7207L7.11659 7.7207L10.1166 4.7207C10.2619 4.65055 10.4259 4.62911 10.5843 4.65956C10.7427 4.69002 10.8871 4.77074 10.996 4.88976C11.1049 5.00877 11.1726 5.15973 11.1889 5.32022C11.2052 5.48072 11.1693 5.6422 11.0866 5.7807L7.58659 9.2807C7.44597 9.42115 7.25534 9.50004 7.05659 9.50004C6.85784 9.50004 6.66722 9.42115 6.52659 9.2807L3.02659 5.7807C2.88614 5.64007 2.80725 5.44945 2.80725 5.2507C2.80725 5.05195 2.88614 4.86132 3.02659 4.7207C3.09932 4.64685 3.18675 4.58911 3.28322 4.55121C3.37969 4.51331 3.48305 4.4961 3.58659 4.5007Z\",\n fill: \"currentColor\"\n}, null, -1);\nvar _hoisted_2 = [_hoisted_1];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"svg\", mergeProps({\n width: \"14\",\n height: \"14\",\n viewBox: \"0 0 14 14\",\n fill: \"none\",\n xmlns: \"http://www.w3.org/2000/svg\"\n }, _ctx.pti()), _hoisted_2, 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseIcon from '@primevue/icons/baseicon';\nimport { openBlock, createElementBlock, mergeProps, createElementVNode } from 'vue';\n\nvar script = {\n name: 'AngleUpIcon',\n \"extends\": BaseIcon\n};\n\nvar _hoisted_1 = /*#__PURE__*/createElementVNode(\"path\", {\n d: \"M10.4134 9.49931C10.3148 9.49977 10.2172 9.48055 10.1262 9.44278C10.0352 9.405 9.95263 9.34942 9.88338 9.27931L6.88338 6.27931L3.88338 9.27931C3.73811 9.34946 3.57409 9.3709 3.41567 9.34044C3.25724 9.30999 3.11286 9.22926 3.00395 9.11025C2.89504 8.99124 2.82741 8.84028 2.8111 8.67978C2.79478 8.51928 2.83065 8.35781 2.91338 8.21931L6.41338 4.71931C6.55401 4.57886 6.74463 4.49997 6.94338 4.49997C7.14213 4.49997 7.33276 4.57886 7.47338 4.71931L10.9734 8.21931C11.1138 8.35994 11.1927 8.55056 11.1927 8.74931C11.1927 8.94806 11.1138 9.13868 10.9734 9.27931C10.9007 9.35315 10.8132 9.41089 10.7168 9.44879C10.6203 9.48669 10.5169 9.5039 10.4134 9.49931Z\",\n fill: \"currentColor\"\n}, null, -1);\nvar _hoisted_2 = [_hoisted_1];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"svg\", mergeProps({\n width: \"14\",\n height: \"14\",\n viewBox: \"0 0 14 14\",\n fill: \"none\",\n xmlns: \"http://www.w3.org/2000/svg\"\n }, _ctx.pti()), _hoisted_2, 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseStyle from '@primevue/core/base/style';\n\nvar theme = function theme(_ref) {\n var dt = _ref.dt;\n return \"\\n.p-inputnumber {\\n display: inline-flex;\\n position: relative;\\n}\\n\\n.p-inputnumber-button {\\n display: flex;\\n align-items: center;\\n justify-content: center;\\n flex: 0 0 auto;\\n cursor: pointer;\\n background: \".concat(dt('inputnumber.button.background'), \";\\n color: \").concat(dt('inputnumber.button.color'), \";\\n width: \").concat(dt('inputnumber.button.width'), \";\\n transition: background \").concat(dt('inputnumber.transition.duration'), \", color \").concat(dt('inputnumber.transition.duration'), \", border-color \").concat(dt('inputnumber.transition.duration'), \", outline-color \").concat(dt('inputnumber.transition.duration'), \";\\n}\\n\\n.p-inputnumber-button:hover {\\n background: \").concat(dt('inputnumber.button.hover.background'), \";\\n color: \").concat(dt('inputnumber.button.hover.color'), \";\\n}\\n\\n.p-inputnumber-button:active {\\n background: \").concat(dt('inputnumber.button.active.background'), \";\\n color: \").concat(dt('inputnumber.button.active.color'), \";\\n}\\n\\n.p-inputnumber-stacked .p-inputnumber-button {\\n position: relative;\\n border: 0 none;\\n}\\n\\n.p-inputnumber-stacked .p-inputnumber-button-group {\\n display: flex;\\n flex-direction: column;\\n position: absolute;\\n top: 1px;\\n right: 1px;\\n height: calc(100% - 2px);\\n}\\n\\n.p-inputnumber-stacked .p-inputnumber-increment-button {\\n padding: 0;\\n border-top-right-radius: calc(\").concat(dt('inputnumber.button.border.radius'), \" - 1px);\\n}\\n\\n.p-inputnumber-stacked .p-inputnumber-decrement-button {\\n padding: 0;\\n border-bottom-right-radius: calc(\").concat(dt('inputnumber.button.border.radius'), \" - 1px);\\n}\\n\\n.p-inputnumber-stacked .p-inputnumber-button {\\n flex: 1 1 auto;\\n border: 0 none;\\n}\\n\\n.p-inputnumber-horizontal .p-inputnumber-button {\\n border: 1px solid \").concat(dt('inputnumber.button.border.color'), \";\\n}\\n\\n.p-inputnumber-horizontal .p-inputnumber-button:hover {\\n border-color: \").concat(dt('inputnumber.button.hover.border.color'), \";\\n}\\n\\n.p-inputnumber-horizontal .p-inputnumber-button:active {\\n border-color: \").concat(dt('inputnumber.button.active.border.color'), \";\\n}\\n\\n.p-inputnumber-horizontal .p-inputnumber-increment-button {\\n order: 3;\\n border-top-right-radius: \").concat(dt('inputnumber.button.border.radius'), \";\\n border-bottom-right-radius: \").concat(dt('inputnumber.button.border.radius'), \";\\n border-left: 0 none;\\n}\\n\\n.p-inputnumber-horizontal .p-inputnumber-input {\\n order: 2;\\n border-radius: 0;\\n}\\n\\n.p-inputnumber-horizontal .p-inputnumber-decrement-button {\\n order: 1;\\n border-top-left-radius: \").concat(dt('inputnumber.button.border.radius'), \";\\n border-bottom-left-radius: \").concat(dt('inputnumber.button.border.radius'), \";\\n border-right: 0 none;\\n}\\n\\n.p-inputnumber-vertical {\\n flex-direction: column;\\n}\\n\\n.p-inputnumber-vertical .p-inputnumber-button {\\n border: 1px solid \").concat(dt('inputnumber.button.border.color'), \";\\n padding: \").concat(dt('inputnumber.button.vertical.padding'), \"; 0;\\n}\\n\\n.p-inputnumber-vertical .p-inputnumber-button:hover {\\n border-color: \").concat(dt('inputnumber.button.hover.border.color'), \";\\n}\\n\\n.p-inputnumber-vertical .p-inputnumber-button:active {\\n border-color: \").concat(dt('inputnumber.button.active.border.color'), \";\\n}\\n\\n.p-inputnumber-vertical .p-inputnumber-increment-button {\\n order: 1;\\n border-top-left-radius: \").concat(dt('inputnumber.button.border.radius'), \";\\n border-top-right-radius: \").concat(dt('inputnumber.button.border.radius'), \";\\n width: 100%;\\n border-bottom: 0 none;\\n}\\n\\n.p-inputnumber-vertical .p-inputnumber-input {\\n order: 2;\\n border-radius: 0;\\n text-align: center;\\n}\\n\\n.p-inputnumber-vertical .p-inputnumber-decrement-button {\\n order: 3;\\n border-bottom-left-radius: \").concat(dt('inputnumber.button.border.radius'), \";\\n border-bottom-right-radius: \").concat(dt('inputnumber.button.border.radius'), \";\\n width: 100%;\\n border-top: 0 none;\\n}\\n\\n.p-inputnumber-input {\\n flex: 1 1 auto;\\n}\\n\\n.p-inputnumber-fluid {\\n width: 100%;\\n}\\n\\n.p-inputnumber-fluid .p-inputnumber-input {\\n width: 1%;\\n}\\n\\n.p-inputnumber-fluid.p-inputnumber-vertical .p-inputnumber-input {\\n width: 100%;\\n}\\n\");\n};\nvar classes = {\n root: function root(_ref2) {\n var instance = _ref2.instance,\n props = _ref2.props;\n return ['p-inputnumber p-component p-inputwrapper', {\n 'p-inputwrapper-filled': instance.filled || props.allowEmpty === false,\n 'p-inputwrapper-focus': instance.focused,\n 'p-inputnumber-stacked': props.showButtons && props.buttonLayout === 'stacked',\n 'p-inputnumber-horizontal': props.showButtons && props.buttonLayout === 'horizontal',\n 'p-inputnumber-vertical': props.showButtons && props.buttonLayout === 'vertical',\n 'p-inputnumber-fluid': instance.fluid\n }];\n },\n pcInput: 'p-inputnumber-input',\n buttonGroup: 'p-inputnumber-button-group',\n incrementButton: function incrementButton(_ref3) {\n var instance = _ref3.instance,\n props = _ref3.props;\n return ['p-inputnumber-button p-inputnumber-increment-button', {\n 'p-disabled': props.showButtons && props.max !== null && instance.maxBoundry()\n }];\n },\n decrementButton: function decrementButton(_ref4) {\n var instance = _ref4.instance,\n props = _ref4.props;\n return ['p-inputnumber-button p-inputnumber-decrement-button', {\n 'p-disabled': props.showButtons && props.min !== null && instance.minBoundry()\n }];\n }\n};\nvar InputNumberStyle = BaseStyle.extend({\n name: 'inputnumber',\n theme: theme,\n classes: classes\n});\n\nexport { InputNumberStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import { getSelection, clearSelection } from '@primeuix/utils/dom';\nimport { isNotEmpty } from '@primeuix/utils/object';\nimport AngleDownIcon from '@primevue/icons/angledown';\nimport AngleUpIcon from '@primevue/icons/angleup';\nimport InputText from 'primevue/inputtext';\nimport BaseComponent from '@primevue/core/basecomponent';\nimport InputNumberStyle from 'primevue/inputnumber/style';\nimport { resolveComponent, openBlock, createElementBlock, mergeProps, createVNode, normalizeClass, normalizeStyle, renderSlot, createElementVNode, toHandlers, createBlock, resolveDynamicComponent, createCommentVNode } from 'vue';\n\nvar script$1 = {\n name: 'BaseInputNumber',\n \"extends\": BaseComponent,\n props: {\n modelValue: {\n type: Number,\n \"default\": null\n },\n format: {\n type: Boolean,\n \"default\": true\n },\n showButtons: {\n type: Boolean,\n \"default\": false\n },\n buttonLayout: {\n type: String,\n \"default\": 'stacked'\n },\n incrementButtonClass: {\n type: String,\n \"default\": null\n },\n decrementButtonClass: {\n type: String,\n \"default\": null\n },\n incrementButtonIcon: {\n type: String,\n \"default\": undefined\n },\n incrementIcon: {\n type: String,\n \"default\": undefined\n },\n decrementButtonIcon: {\n type: String,\n \"default\": undefined\n },\n decrementIcon: {\n type: String,\n \"default\": undefined\n },\n locale: {\n type: String,\n \"default\": undefined\n },\n localeMatcher: {\n type: String,\n \"default\": undefined\n },\n mode: {\n type: String,\n \"default\": 'decimal'\n },\n prefix: {\n type: String,\n \"default\": null\n },\n suffix: {\n type: String,\n \"default\": null\n },\n currency: {\n type: String,\n \"default\": undefined\n },\n currencyDisplay: {\n type: String,\n \"default\": undefined\n },\n useGrouping: {\n type: Boolean,\n \"default\": true\n },\n minFractionDigits: {\n type: Number,\n \"default\": undefined\n },\n maxFractionDigits: {\n type: Number,\n \"default\": undefined\n },\n roundingMode: {\n type: String,\n \"default\": 'halfExpand',\n validator: function validator(value) {\n return ['ceil', 'floor', 'expand', 'trunc', 'halfCeil', 'halfFloor', 'halfExpand', 'halfTrunc', 'halfEven'].includes(value);\n }\n },\n min: {\n type: Number,\n \"default\": null\n },\n max: {\n type: Number,\n \"default\": null\n },\n step: {\n type: Number,\n \"default\": 1\n },\n allowEmpty: {\n type: Boolean,\n \"default\": true\n },\n highlightOnFocus: {\n type: Boolean,\n \"default\": false\n },\n readonly: {\n type: Boolean,\n \"default\": false\n },\n variant: {\n type: String,\n \"default\": null\n },\n invalid: {\n type: Boolean,\n \"default\": false\n },\n disabled: {\n type: Boolean,\n \"default\": false\n },\n placeholder: {\n type: String,\n \"default\": null\n },\n fluid: {\n type: Boolean,\n \"default\": false\n },\n inputId: {\n type: String,\n \"default\": null\n },\n inputClass: {\n type: [String, Object],\n \"default\": null\n },\n inputStyle: {\n type: Object,\n \"default\": null\n },\n ariaLabelledby: {\n type: String,\n \"default\": null\n },\n ariaLabel: {\n type: String,\n \"default\": null\n }\n },\n style: InputNumberStyle,\n provide: function provide() {\n return {\n $pcInputNumber: this,\n $parentInstance: this\n };\n }\n};\n\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nfunction _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _unsupportedIterableToArray(r, a) { if (r) { if (\"string\" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return \"Object\" === t && r.constructor && (t = r.constructor.name), \"Map\" === t || \"Set\" === t ? Array.from(r) : \"Arguments\" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }\nfunction _iterableToArray(r) { if (\"undefined\" != typeof Symbol && null != r[Symbol.iterator] || null != r[\"@@iterator\"]) return Array.from(r); }\nfunction _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }\nfunction _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }\nvar script = {\n name: 'InputNumber',\n \"extends\": script$1,\n inheritAttrs: false,\n emits: ['update:modelValue', 'input', 'focus', 'blur'],\n numberFormat: null,\n _numeral: null,\n _decimal: null,\n _group: null,\n _minusSign: null,\n _currency: null,\n _suffix: null,\n _prefix: null,\n _index: null,\n groupChar: '',\n isSpecialChar: null,\n prefixChar: null,\n suffixChar: null,\n timer: null,\n data: function data() {\n return {\n d_modelValue: this.modelValue,\n focused: false\n };\n },\n watch: {\n modelValue: function modelValue(newValue) {\n this.d_modelValue = newValue;\n },\n locale: function locale(newValue, oldValue) {\n this.updateConstructParser(newValue, oldValue);\n },\n localeMatcher: function localeMatcher(newValue, oldValue) {\n this.updateConstructParser(newValue, oldValue);\n },\n mode: function mode(newValue, oldValue) {\n this.updateConstructParser(newValue, oldValue);\n },\n currency: function currency(newValue, oldValue) {\n this.updateConstructParser(newValue, oldValue);\n },\n currencyDisplay: function currencyDisplay(newValue, oldValue) {\n this.updateConstructParser(newValue, oldValue);\n },\n useGrouping: function useGrouping(newValue, oldValue) {\n this.updateConstructParser(newValue, oldValue);\n },\n minFractionDigits: function minFractionDigits(newValue, oldValue) {\n this.updateConstructParser(newValue, oldValue);\n },\n maxFractionDigits: function maxFractionDigits(newValue, oldValue) {\n this.updateConstructParser(newValue, oldValue);\n },\n suffix: function suffix(newValue, oldValue) {\n this.updateConstructParser(newValue, oldValue);\n },\n prefix: function prefix(newValue, oldValue) {\n this.updateConstructParser(newValue, oldValue);\n }\n },\n created: function created() {\n this.constructParser();\n },\n methods: {\n getOptions: function getOptions() {\n return {\n localeMatcher: this.localeMatcher,\n style: this.mode,\n currency: this.currency,\n currencyDisplay: this.currencyDisplay,\n useGrouping: this.useGrouping,\n minimumFractionDigits: this.minFractionDigits,\n maximumFractionDigits: this.maxFractionDigits,\n roundingMode: this.roundingMode\n };\n },\n constructParser: function constructParser() {\n this.numberFormat = new Intl.NumberFormat(this.locale, this.getOptions());\n var numerals = _toConsumableArray(new Intl.NumberFormat(this.locale, {\n useGrouping: false\n }).format(9876543210)).reverse();\n var index = new Map(numerals.map(function (d, i) {\n return [d, i];\n }));\n this._numeral = new RegExp(\"[\".concat(numerals.join(''), \"]\"), 'g');\n this._group = this.getGroupingExpression();\n this._minusSign = this.getMinusSignExpression();\n this._currency = this.getCurrencyExpression();\n this._decimal = this.getDecimalExpression();\n this._suffix = this.getSuffixExpression();\n this._prefix = this.getPrefixExpression();\n this._index = function (d) {\n return index.get(d);\n };\n },\n updateConstructParser: function updateConstructParser(newValue, oldValue) {\n if (newValue !== oldValue) {\n this.constructParser();\n }\n },\n escapeRegExp: function escapeRegExp(text) {\n return text.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&');\n },\n getDecimalExpression: function getDecimalExpression() {\n var formatter = new Intl.NumberFormat(this.locale, _objectSpread(_objectSpread({}, this.getOptions()), {}, {\n useGrouping: false\n }));\n return new RegExp(\"[\".concat(formatter.format(1.1).replace(this._currency, '').trim().replace(this._numeral, ''), \"]\"), 'g');\n },\n getGroupingExpression: function getGroupingExpression() {\n var formatter = new Intl.NumberFormat(this.locale, {\n useGrouping: true\n });\n this.groupChar = formatter.format(1000000).trim().replace(this._numeral, '').charAt(0);\n return new RegExp(\"[\".concat(this.groupChar, \"]\"), 'g');\n },\n getMinusSignExpression: function getMinusSignExpression() {\n var formatter = new Intl.NumberFormat(this.locale, {\n useGrouping: false\n });\n return new RegExp(\"[\".concat(formatter.format(-1).trim().replace(this._numeral, ''), \"]\"), 'g');\n },\n getCurrencyExpression: function getCurrencyExpression() {\n if (this.currency) {\n var formatter = new Intl.NumberFormat(this.locale, {\n style: 'currency',\n currency: this.currency,\n currencyDisplay: this.currencyDisplay,\n minimumFractionDigits: 0,\n maximumFractionDigits: 0,\n roundingMode: this.roundingMode\n });\n return new RegExp(\"[\".concat(formatter.format(1).replace(/\\s/g, '').replace(this._numeral, '').replace(this._group, ''), \"]\"), 'g');\n }\n return new RegExp(\"[]\", 'g');\n },\n getPrefixExpression: function getPrefixExpression() {\n if (this.prefix) {\n this.prefixChar = this.prefix;\n } else {\n var formatter = new Intl.NumberFormat(this.locale, {\n style: this.mode,\n currency: this.currency,\n currencyDisplay: this.currencyDisplay\n });\n this.prefixChar = formatter.format(1).split('1')[0];\n }\n return new RegExp(\"\".concat(this.escapeRegExp(this.prefixChar || '')), 'g');\n },\n getSuffixExpression: function getSuffixExpression() {\n if (this.suffix) {\n this.suffixChar = this.suffix;\n } else {\n var formatter = new Intl.NumberFormat(this.locale, {\n style: this.mode,\n currency: this.currency,\n currencyDisplay: this.currencyDisplay,\n minimumFractionDigits: 0,\n maximumFractionDigits: 0,\n roundingMode: this.roundingMode\n });\n this.suffixChar = formatter.format(1).split('1')[1];\n }\n return new RegExp(\"\".concat(this.escapeRegExp(this.suffixChar || '')), 'g');\n },\n formatValue: function formatValue(value) {\n if (value != null) {\n if (value === '-') {\n // Minus sign\n return value;\n }\n if (this.format) {\n var formatter = new Intl.NumberFormat(this.locale, this.getOptions());\n var formattedValue = formatter.format(value);\n if (this.prefix) {\n formattedValue = this.prefix + formattedValue;\n }\n if (this.suffix) {\n formattedValue = formattedValue + this.suffix;\n }\n return formattedValue;\n }\n return value.toString();\n }\n return '';\n },\n parseValue: function parseValue(text) {\n var filteredText = text.replace(this._suffix, '').replace(this._prefix, '').trim().replace(/\\s/g, '').replace(this._currency, '').replace(this._group, '').replace(this._minusSign, '-').replace(this._decimal, '.').replace(this._numeral, this._index);\n if (filteredText) {\n if (filteredText === '-')\n // Minus sign\n return filteredText;\n var parsedValue = +filteredText;\n return isNaN(parsedValue) ? null : parsedValue;\n }\n return null;\n },\n repeat: function repeat(event, interval, dir) {\n var _this = this;\n if (this.readonly) {\n return;\n }\n var i = interval || 500;\n this.clearTimer();\n this.timer = setTimeout(function () {\n _this.repeat(event, 40, dir);\n }, i);\n this.spin(event, dir);\n },\n spin: function spin(event, dir) {\n if (this.$refs.input) {\n var step = this.step * dir;\n var currentValue = this.parseValue(this.$refs.input.$el.value) || 0;\n var newValue = this.validateValue(currentValue + step);\n this.updateInput(newValue, null, 'spin');\n this.updateModel(event, newValue);\n this.handleOnInput(event, currentValue, newValue);\n }\n },\n onUpButtonMouseDown: function onUpButtonMouseDown(event) {\n if (!this.disabled) {\n this.$refs.input.$el.focus();\n this.repeat(event, null, 1);\n event.preventDefault();\n }\n },\n onUpButtonMouseUp: function onUpButtonMouseUp() {\n if (!this.disabled) {\n this.clearTimer();\n }\n },\n onUpButtonMouseLeave: function onUpButtonMouseLeave() {\n if (!this.disabled) {\n this.clearTimer();\n }\n },\n onUpButtonKeyUp: function onUpButtonKeyUp() {\n if (!this.disabled) {\n this.clearTimer();\n }\n },\n onUpButtonKeyDown: function onUpButtonKeyDown(event) {\n if (event.code === 'Space' || event.code === 'Enter' || event.code === 'NumpadEnter') {\n this.repeat(event, null, 1);\n }\n },\n onDownButtonMouseDown: function onDownButtonMouseDown(event) {\n if (!this.disabled) {\n this.$refs.input.$el.focus();\n this.repeat(event, null, -1);\n event.preventDefault();\n }\n },\n onDownButtonMouseUp: function onDownButtonMouseUp() {\n if (!this.disabled) {\n this.clearTimer();\n }\n },\n onDownButtonMouseLeave: function onDownButtonMouseLeave() {\n if (!this.disabled) {\n this.clearTimer();\n }\n },\n onDownButtonKeyUp: function onDownButtonKeyUp() {\n if (!this.disabled) {\n this.clearTimer();\n }\n },\n onDownButtonKeyDown: function onDownButtonKeyDown(event) {\n if (event.code === 'Space' || event.code === 'Enter' || event.code === 'NumpadEnter') {\n this.repeat(event, null, -1);\n }\n },\n onUserInput: function onUserInput() {\n if (this.isSpecialChar) {\n this.$refs.input.$el.value = this.lastValue;\n }\n this.isSpecialChar = false;\n },\n onInputKeyDown: function onInputKeyDown(event) {\n if (this.readonly) {\n return;\n }\n if (event.altKey || event.ctrlKey || event.metaKey) {\n this.isSpecialChar = true;\n this.lastValue = this.$refs.input.$el.value;\n return;\n }\n this.lastValue = event.target.value;\n var selectionStart = event.target.selectionStart;\n var selectionEnd = event.target.selectionEnd;\n var inputValue = event.target.value;\n var newValueStr = null;\n switch (event.code) {\n case 'ArrowUp':\n this.spin(event, 1);\n event.preventDefault();\n break;\n case 'ArrowDown':\n this.spin(event, -1);\n event.preventDefault();\n break;\n case 'ArrowLeft':\n if (!this.isNumeralChar(inputValue.charAt(selectionStart - 1))) {\n event.preventDefault();\n }\n break;\n case 'ArrowRight':\n if (!this.isNumeralChar(inputValue.charAt(selectionStart))) {\n event.preventDefault();\n }\n break;\n case 'Tab':\n case 'Enter':\n case 'NumpadEnter':\n newValueStr = this.validateValue(this.parseValue(inputValue));\n this.$refs.input.$el.value = this.formatValue(newValueStr);\n this.$refs.input.$el.setAttribute('aria-valuenow', newValueStr);\n this.updateModel(event, newValueStr);\n break;\n case 'Backspace':\n {\n event.preventDefault();\n if (selectionStart === selectionEnd) {\n var deleteChar = inputValue.charAt(selectionStart - 1);\n var _this$getDecimalCharI = this.getDecimalCharIndexes(inputValue),\n decimalCharIndex = _this$getDecimalCharI.decimalCharIndex,\n decimalCharIndexWithoutPrefix = _this$getDecimalCharI.decimalCharIndexWithoutPrefix;\n if (this.isNumeralChar(deleteChar)) {\n var decimalLength = this.getDecimalLength(inputValue);\n if (this._group.test(deleteChar)) {\n this._group.lastIndex = 0;\n newValueStr = inputValue.slice(0, selectionStart - 2) + inputValue.slice(selectionStart - 1);\n } else if (this._decimal.test(deleteChar)) {\n this._decimal.lastIndex = 0;\n if (decimalLength) {\n this.$refs.input.$el.setSelectionRange(selectionStart - 1, selectionStart - 1);\n } else {\n newValueStr = inputValue.slice(0, selectionStart - 1) + inputValue.slice(selectionStart);\n }\n } else if (decimalCharIndex > 0 && selectionStart > decimalCharIndex) {\n var insertedText = this.isDecimalMode() && (this.minFractionDigits || 0) < decimalLength ? '' : '0';\n newValueStr = inputValue.slice(0, selectionStart - 1) + insertedText + inputValue.slice(selectionStart);\n } else if (decimalCharIndexWithoutPrefix === 1) {\n newValueStr = inputValue.slice(0, selectionStart - 1) + '0' + inputValue.slice(selectionStart);\n newValueStr = this.parseValue(newValueStr) > 0 ? newValueStr : '';\n } else {\n newValueStr = inputValue.slice(0, selectionStart - 1) + inputValue.slice(selectionStart);\n }\n }\n this.updateValue(event, newValueStr, null, 'delete-single');\n } else {\n newValueStr = this.deleteRange(inputValue, selectionStart, selectionEnd);\n this.updateValue(event, newValueStr, null, 'delete-range');\n }\n break;\n }\n case 'Delete':\n event.preventDefault();\n if (selectionStart === selectionEnd) {\n var _deleteChar = inputValue.charAt(selectionStart);\n var _this$getDecimalCharI2 = this.getDecimalCharIndexes(inputValue),\n _decimalCharIndex = _this$getDecimalCharI2.decimalCharIndex,\n _decimalCharIndexWithoutPrefix = _this$getDecimalCharI2.decimalCharIndexWithoutPrefix;\n if (this.isNumeralChar(_deleteChar)) {\n var _decimalLength = this.getDecimalLength(inputValue);\n if (this._group.test(_deleteChar)) {\n this._group.lastIndex = 0;\n newValueStr = inputValue.slice(0, selectionStart) + inputValue.slice(selectionStart + 2);\n } else if (this._decimal.test(_deleteChar)) {\n this._decimal.lastIndex = 0;\n if (_decimalLength) {\n this.$refs.input.$el.setSelectionRange(selectionStart + 1, selectionStart + 1);\n } else {\n newValueStr = inputValue.slice(0, selectionStart) + inputValue.slice(selectionStart + 1);\n }\n } else if (_decimalCharIndex > 0 && selectionStart > _decimalCharIndex) {\n var _insertedText = this.isDecimalMode() && (this.minFractionDigits || 0) < _decimalLength ? '' : '0';\n newValueStr = inputValue.slice(0, selectionStart) + _insertedText + inputValue.slice(selectionStart + 1);\n } else if (_decimalCharIndexWithoutPrefix === 1) {\n newValueStr = inputValue.slice(0, selectionStart) + '0' + inputValue.slice(selectionStart + 1);\n newValueStr = this.parseValue(newValueStr) > 0 ? newValueStr : '';\n } else {\n newValueStr = inputValue.slice(0, selectionStart) + inputValue.slice(selectionStart + 1);\n }\n }\n this.updateValue(event, newValueStr, null, 'delete-back-single');\n } else {\n newValueStr = this.deleteRange(inputValue, selectionStart, selectionEnd);\n this.updateValue(event, newValueStr, null, 'delete-range');\n }\n break;\n case 'Home':\n event.preventDefault();\n if (isNotEmpty(this.min)) {\n this.updateModel(event, this.min);\n }\n break;\n case 'End':\n event.preventDefault();\n if (isNotEmpty(this.max)) {\n this.updateModel(event, this.max);\n }\n break;\n }\n },\n onInputKeyPress: function onInputKeyPress(event) {\n if (this.readonly) {\n return;\n }\n var _char = event.key;\n var isDecimalSign = this.isDecimalSign(_char);\n var isMinusSign = this.isMinusSign(_char);\n if (event.code !== 'Enter') {\n event.preventDefault();\n }\n if (Number(_char) >= 0 && Number(_char) <= 9 || isMinusSign || isDecimalSign) {\n this.insert(event, _char, {\n isDecimalSign: isDecimalSign,\n isMinusSign: isMinusSign\n });\n }\n },\n onPaste: function onPaste(event) {\n event.preventDefault();\n var data = (event.clipboardData || window['clipboardData']).getData('Text');\n if (data) {\n var filteredData = this.parseValue(data);\n if (filteredData != null) {\n this.insert(event, filteredData.toString());\n }\n }\n },\n allowMinusSign: function allowMinusSign() {\n return this.min === null || this.min < 0;\n },\n isMinusSign: function isMinusSign(_char2) {\n if (this._minusSign.test(_char2) || _char2 === '-') {\n this._minusSign.lastIndex = 0;\n return true;\n }\n return false;\n },\n isDecimalSign: function isDecimalSign(_char3) {\n if (this._decimal.test(_char3)) {\n this._decimal.lastIndex = 0;\n return true;\n }\n return false;\n },\n isDecimalMode: function isDecimalMode() {\n return this.mode === 'decimal';\n },\n getDecimalCharIndexes: function getDecimalCharIndexes(val) {\n var decimalCharIndex = val.search(this._decimal);\n this._decimal.lastIndex = 0;\n var filteredVal = val.replace(this._prefix, '').trim().replace(/\\s/g, '').replace(this._currency, '');\n var decimalCharIndexWithoutPrefix = filteredVal.search(this._decimal);\n this._decimal.lastIndex = 0;\n return {\n decimalCharIndex: decimalCharIndex,\n decimalCharIndexWithoutPrefix: decimalCharIndexWithoutPrefix\n };\n },\n getCharIndexes: function getCharIndexes(val) {\n var decimalCharIndex = val.search(this._decimal);\n this._decimal.lastIndex = 0;\n var minusCharIndex = val.search(this._minusSign);\n this._minusSign.lastIndex = 0;\n var suffixCharIndex = val.search(this._suffix);\n this._suffix.lastIndex = 0;\n var currencyCharIndex = val.search(this._currency);\n this._currency.lastIndex = 0;\n return {\n decimalCharIndex: decimalCharIndex,\n minusCharIndex: minusCharIndex,\n suffixCharIndex: suffixCharIndex,\n currencyCharIndex: currencyCharIndex\n };\n },\n insert: function insert(event, text) {\n var sign = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {\n isDecimalSign: false,\n isMinusSign: false\n };\n var minusCharIndexOnText = text.search(this._minusSign);\n this._minusSign.lastIndex = 0;\n if (!this.allowMinusSign() && minusCharIndexOnText !== -1) {\n return;\n }\n var selectionStart = this.$refs.input.$el.selectionStart;\n var selectionEnd = this.$refs.input.$el.selectionEnd;\n var inputValue = this.$refs.input.$el.value.trim();\n var _this$getCharIndexes = this.getCharIndexes(inputValue),\n decimalCharIndex = _this$getCharIndexes.decimalCharIndex,\n minusCharIndex = _this$getCharIndexes.minusCharIndex,\n suffixCharIndex = _this$getCharIndexes.suffixCharIndex,\n currencyCharIndex = _this$getCharIndexes.currencyCharIndex;\n var newValueStr;\n if (sign.isMinusSign) {\n if (selectionStart === 0) {\n newValueStr = inputValue;\n if (minusCharIndex === -1 || selectionEnd !== 0) {\n newValueStr = this.insertText(inputValue, text, 0, selectionEnd);\n }\n this.updateValue(event, newValueStr, text, 'insert');\n }\n } else if (sign.isDecimalSign) {\n if (decimalCharIndex > 0 && selectionStart === decimalCharIndex) {\n this.updateValue(event, inputValue, text, 'insert');\n } else if (decimalCharIndex > selectionStart && decimalCharIndex < selectionEnd) {\n newValueStr = this.insertText(inputValue, text, selectionStart, selectionEnd);\n this.updateValue(event, newValueStr, text, 'insert');\n } else if (decimalCharIndex === -1 && this.maxFractionDigits) {\n newValueStr = this.insertText(inputValue, text, selectionStart, selectionEnd);\n this.updateValue(event, newValueStr, text, 'insert');\n }\n } else {\n var maxFractionDigits = this.numberFormat.resolvedOptions().maximumFractionDigits;\n var operation = selectionStart !== selectionEnd ? 'range-insert' : 'insert';\n if (decimalCharIndex > 0 && selectionStart > decimalCharIndex) {\n if (selectionStart + text.length - (decimalCharIndex + 1) <= maxFractionDigits) {\n var charIndex = currencyCharIndex >= selectionStart ? currencyCharIndex - 1 : suffixCharIndex >= selectionStart ? suffixCharIndex : inputValue.length;\n newValueStr = inputValue.slice(0, selectionStart) + text + inputValue.slice(selectionStart + text.length, charIndex) + inputValue.slice(charIndex);\n this.updateValue(event, newValueStr, text, operation);\n }\n } else {\n newValueStr = this.insertText(inputValue, text, selectionStart, selectionEnd);\n this.updateValue(event, newValueStr, text, operation);\n }\n }\n },\n insertText: function insertText(value, text, start, end) {\n var textSplit = text === '.' ? text : text.split('.');\n if (textSplit.length === 2) {\n var decimalCharIndex = value.slice(start, end).search(this._decimal);\n this._decimal.lastIndex = 0;\n return decimalCharIndex > 0 ? value.slice(0, start) + this.formatValue(text) + value.slice(end) : this.formatValue(text) || value;\n } else if (end - start === value.length) {\n return this.formatValue(text);\n } else if (start === 0) {\n return text + value.slice(end);\n } else if (end === value.length) {\n return value.slice(0, start) + text;\n } else {\n return value.slice(0, start) + text + value.slice(end);\n }\n },\n deleteRange: function deleteRange(value, start, end) {\n var newValueStr;\n if (end - start === value.length) newValueStr = '';else if (start === 0) newValueStr = value.slice(end);else if (end === value.length) newValueStr = value.slice(0, start);else newValueStr = value.slice(0, start) + value.slice(end);\n return newValueStr;\n },\n initCursor: function initCursor() {\n var selectionStart = this.$refs.input.$el.selectionStart;\n var inputValue = this.$refs.input.$el.value;\n var valueLength = inputValue.length;\n var index = null;\n\n // remove prefix\n var prefixLength = (this.prefixChar || '').length;\n inputValue = inputValue.replace(this._prefix, '');\n selectionStart = selectionStart - prefixLength;\n var _char4 = inputValue.charAt(selectionStart);\n if (this.isNumeralChar(_char4)) {\n return selectionStart + prefixLength;\n }\n\n //left\n var i = selectionStart - 1;\n while (i >= 0) {\n _char4 = inputValue.charAt(i);\n if (this.isNumeralChar(_char4)) {\n index = i + prefixLength;\n break;\n } else {\n i--;\n }\n }\n if (index !== null) {\n this.$refs.input.$el.setSelectionRange(index + 1, index + 1);\n } else {\n i = selectionStart;\n while (i < valueLength) {\n _char4 = inputValue.charAt(i);\n if (this.isNumeralChar(_char4)) {\n index = i + prefixLength;\n break;\n } else {\n i++;\n }\n }\n if (index !== null) {\n this.$refs.input.$el.setSelectionRange(index, index);\n }\n }\n return index || 0;\n },\n onInputClick: function onInputClick() {\n var currentValue = this.$refs.input.$el.value;\n if (!this.readonly && currentValue !== getSelection()) {\n this.initCursor();\n }\n },\n isNumeralChar: function isNumeralChar(_char5) {\n if (_char5.length === 1 && (this._numeral.test(_char5) || this._decimal.test(_char5) || this._group.test(_char5) || this._minusSign.test(_char5))) {\n this.resetRegex();\n return true;\n }\n return false;\n },\n resetRegex: function resetRegex() {\n this._numeral.lastIndex = 0;\n this._decimal.lastIndex = 0;\n this._group.lastIndex = 0;\n this._minusSign.lastIndex = 0;\n },\n updateValue: function updateValue(event, valueStr, insertedValueStr, operation) {\n var currentValue = this.$refs.input.$el.value;\n var newValue = null;\n if (valueStr != null) {\n newValue = this.parseValue(valueStr);\n newValue = !newValue && !this.allowEmpty ? 0 : newValue;\n this.updateInput(newValue, insertedValueStr, operation, valueStr);\n this.handleOnInput(event, currentValue, newValue);\n }\n },\n handleOnInput: function handleOnInput(event, currentValue, newValue) {\n if (this.isValueChanged(currentValue, newValue)) {\n this.$emit('input', {\n originalEvent: event,\n value: newValue,\n formattedValue: currentValue\n });\n }\n },\n isValueChanged: function isValueChanged(currentValue, newValue) {\n if (newValue === null && currentValue !== null) {\n return true;\n }\n if (newValue != null) {\n var parsedCurrentValue = typeof currentValue === 'string' ? this.parseValue(currentValue) : currentValue;\n return newValue !== parsedCurrentValue;\n }\n return false;\n },\n validateValue: function validateValue(value) {\n if (value === '-' || value == null) {\n return null;\n }\n if (this.min != null && value < this.min) {\n return this.min;\n }\n if (this.max != null && value > this.max) {\n return this.max;\n }\n return value;\n },\n updateInput: function updateInput(value, insertedValueStr, operation, valueStr) {\n insertedValueStr = insertedValueStr || '';\n var inputValue = this.$refs.input.$el.value;\n var newValue = this.formatValue(value);\n var currentLength = inputValue.length;\n if (newValue !== valueStr) {\n newValue = this.concatValues(newValue, valueStr);\n }\n if (currentLength === 0) {\n this.$refs.input.$el.value = newValue;\n this.$refs.input.$el.setSelectionRange(0, 0);\n var index = this.initCursor();\n var selectionEnd = index + insertedValueStr.length;\n this.$refs.input.$el.setSelectionRange(selectionEnd, selectionEnd);\n } else {\n var selectionStart = this.$refs.input.$el.selectionStart;\n var _selectionEnd = this.$refs.input.$el.selectionEnd;\n this.$refs.input.$el.value = newValue;\n var newLength = newValue.length;\n if (operation === 'range-insert') {\n var startValue = this.parseValue((inputValue || '').slice(0, selectionStart));\n var startValueStr = startValue !== null ? startValue.toString() : '';\n var startExpr = startValueStr.split('').join(\"(\".concat(this.groupChar, \")?\"));\n var sRegex = new RegExp(startExpr, 'g');\n sRegex.test(newValue);\n var tExpr = insertedValueStr.split('').join(\"(\".concat(this.groupChar, \")?\"));\n var tRegex = new RegExp(tExpr, 'g');\n tRegex.test(newValue.slice(sRegex.lastIndex));\n _selectionEnd = sRegex.lastIndex + tRegex.lastIndex;\n this.$refs.input.$el.setSelectionRange(_selectionEnd, _selectionEnd);\n } else if (newLength === currentLength) {\n if (operation === 'insert' || operation === 'delete-back-single') {\n this.$refs.input.$el.setSelectionRange(_selectionEnd + 1, _selectionEnd + 1);\n } else if (operation === 'delete-single') {\n this.$refs.input.$el.setSelectionRange(_selectionEnd - 1, _selectionEnd - 1);\n } else if (operation === 'delete-range' || operation === 'spin') {\n this.$refs.input.$el.setSelectionRange(_selectionEnd, _selectionEnd);\n }\n } else if (operation === 'delete-back-single') {\n var prevChar = inputValue.charAt(_selectionEnd - 1);\n var nextChar = inputValue.charAt(_selectionEnd);\n var diff = currentLength - newLength;\n var isGroupChar = this._group.test(nextChar);\n if (isGroupChar && diff === 1) {\n _selectionEnd += 1;\n } else if (!isGroupChar && this.isNumeralChar(prevChar)) {\n _selectionEnd += -1 * diff + 1;\n }\n this._group.lastIndex = 0;\n this.$refs.input.$el.setSelectionRange(_selectionEnd, _selectionEnd);\n } else if (inputValue === '-' && operation === 'insert') {\n this.$refs.input.$el.setSelectionRange(0, 0);\n var _index = this.initCursor();\n var _selectionEnd2 = _index + insertedValueStr.length + 1;\n this.$refs.input.$el.setSelectionRange(_selectionEnd2, _selectionEnd2);\n } else {\n _selectionEnd = _selectionEnd + (newLength - currentLength);\n this.$refs.input.$el.setSelectionRange(_selectionEnd, _selectionEnd);\n }\n }\n this.$refs.input.$el.setAttribute('aria-valuenow', value);\n },\n concatValues: function concatValues(val1, val2) {\n if (val1 && val2) {\n var decimalCharIndex = val2.search(this._decimal);\n this._decimal.lastIndex = 0;\n if (this.suffixChar) {\n return decimalCharIndex !== -1 ? val1.replace(this.suffixChar, '').split(this._decimal)[0] + val2.replace(this.suffixChar, '').slice(decimalCharIndex) + this.suffixChar : val1;\n } else {\n return decimalCharIndex !== -1 ? val1.split(this._decimal)[0] + val2.slice(decimalCharIndex) : val1;\n }\n }\n return val1;\n },\n getDecimalLength: function getDecimalLength(value) {\n if (value) {\n var valueSplit = value.split(this._decimal);\n if (valueSplit.length === 2) {\n return valueSplit[1].replace(this._suffix, '').trim().replace(/\\s/g, '').replace(this._currency, '').length;\n }\n }\n return 0;\n },\n updateModel: function updateModel(event, value) {\n this.d_modelValue = value;\n this.$emit('update:modelValue', value);\n },\n onInputFocus: function onInputFocus(event) {\n this.focused = true;\n if (!this.disabled && !this.readonly && this.$refs.input.$el.value !== getSelection() && this.highlightOnFocus) {\n event.target.select();\n }\n this.$emit('focus', event);\n },\n onInputBlur: function onInputBlur(event) {\n this.focused = false;\n var input = event.target;\n var newValue = this.validateValue(this.parseValue(input.value));\n this.$emit('blur', {\n originalEvent: event,\n value: input.value\n });\n input.value = this.formatValue(newValue);\n input.setAttribute('aria-valuenow', newValue);\n this.updateModel(event, newValue);\n if (!this.disabled && !this.readonly && this.highlightOnFocus) {\n clearSelection();\n }\n },\n clearTimer: function clearTimer() {\n if (this.timer) {\n clearInterval(this.timer);\n }\n },\n maxBoundry: function maxBoundry() {\n return this.d_modelValue >= this.max;\n },\n minBoundry: function minBoundry() {\n return this.d_modelValue <= this.min;\n }\n },\n computed: {\n filled: function filled() {\n return this.modelValue != null && this.modelValue.toString().length > 0;\n },\n upButtonListeners: function upButtonListeners() {\n var _this2 = this;\n return {\n mousedown: function mousedown(event) {\n return _this2.onUpButtonMouseDown(event);\n },\n mouseup: function mouseup(event) {\n return _this2.onUpButtonMouseUp(event);\n },\n mouseleave: function mouseleave(event) {\n return _this2.onUpButtonMouseLeave(event);\n },\n keydown: function keydown(event) {\n return _this2.onUpButtonKeyDown(event);\n },\n keyup: function keyup(event) {\n return _this2.onUpButtonKeyUp(event);\n }\n };\n },\n downButtonListeners: function downButtonListeners() {\n var _this3 = this;\n return {\n mousedown: function mousedown(event) {\n return _this3.onDownButtonMouseDown(event);\n },\n mouseup: function mouseup(event) {\n return _this3.onDownButtonMouseUp(event);\n },\n mouseleave: function mouseleave(event) {\n return _this3.onDownButtonMouseLeave(event);\n },\n keydown: function keydown(event) {\n return _this3.onDownButtonKeyDown(event);\n },\n keyup: function keyup(event) {\n return _this3.onDownButtonKeyUp(event);\n }\n };\n },\n formattedValue: function formattedValue() {\n var val = !this.modelValue && !this.allowEmpty ? 0 : this.modelValue;\n return this.formatValue(val);\n },\n getFormatter: function getFormatter() {\n return this.numberFormat;\n }\n },\n components: {\n InputText: InputText,\n AngleUpIcon: AngleUpIcon,\n AngleDownIcon: AngleDownIcon\n }\n};\n\nvar _hoisted_1 = [\"disabled\"];\nvar _hoisted_2 = [\"disabled\"];\nvar _hoisted_3 = [\"disabled\"];\nvar _hoisted_4 = [\"disabled\"];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n var _component_InputText = resolveComponent(\"InputText\");\n return openBlock(), createElementBlock(\"span\", mergeProps({\n \"class\": _ctx.cx('root')\n }, _ctx.ptmi('root')), [createVNode(_component_InputText, {\n ref: \"input\",\n id: _ctx.inputId,\n role: \"spinbutton\",\n \"class\": normalizeClass([_ctx.cx('pcInput'), _ctx.inputClass]),\n style: normalizeStyle(_ctx.inputStyle),\n value: $options.formattedValue,\n \"aria-valuemin\": _ctx.min,\n \"aria-valuemax\": _ctx.max,\n \"aria-valuenow\": _ctx.modelValue,\n inputmode: _ctx.mode === 'decimal' && !_ctx.minFractionDigits ? 'numeric' : 'decimal',\n disabled: _ctx.disabled,\n readonly: _ctx.readonly,\n placeholder: _ctx.placeholder,\n \"aria-labelledby\": _ctx.ariaLabelledby,\n \"aria-label\": _ctx.ariaLabel,\n invalid: _ctx.invalid,\n variant: _ctx.variant,\n onInput: $options.onUserInput,\n onKeydown: $options.onInputKeyDown,\n onKeypress: $options.onInputKeyPress,\n onPaste: $options.onPaste,\n onClick: $options.onInputClick,\n onFocus: $options.onInputFocus,\n onBlur: $options.onInputBlur,\n pt: _ctx.ptm('pcInput'),\n unstyled: _ctx.unstyled\n }, null, 8, [\"id\", \"class\", \"style\", \"value\", \"aria-valuemin\", \"aria-valuemax\", \"aria-valuenow\", \"inputmode\", \"disabled\", \"readonly\", \"placeholder\", \"aria-labelledby\", \"aria-label\", \"invalid\", \"variant\", \"onInput\", \"onKeydown\", \"onKeypress\", \"onPaste\", \"onClick\", \"onFocus\", \"onBlur\", \"pt\", \"unstyled\"]), _ctx.showButtons && _ctx.buttonLayout === 'stacked' ? (openBlock(), createElementBlock(\"span\", mergeProps({\n key: 0,\n \"class\": _ctx.cx('buttonGroup')\n }, _ctx.ptm('buttonGroup')), [renderSlot(_ctx.$slots, \"incrementbutton\", {\n listeners: $options.upButtonListeners\n }, function () {\n return [createElementVNode(\"button\", mergeProps({\n \"class\": [_ctx.cx('incrementButton'), _ctx.incrementButtonClass]\n }, toHandlers($options.upButtonListeners, true), {\n disabled: _ctx.disabled,\n tabindex: -1,\n \"aria-hidden\": \"true\",\n type: \"button\"\n }, _ctx.ptm('incrementButton')), [renderSlot(_ctx.$slots, _ctx.$slots.incrementicon ? 'incrementicon' : 'incrementbuttonicon', {}, function () {\n return [(openBlock(), createBlock(resolveDynamicComponent(_ctx.incrementIcon || _ctx.incrementButtonIcon ? 'span' : 'AngleUpIcon'), mergeProps({\n \"class\": [_ctx.incrementIcon, _ctx.incrementButtonIcon]\n }, _ctx.ptm('incrementIcon'), {\n \"data-pc-section\": \"incrementicon\"\n }), null, 16, [\"class\"]))];\n })], 16, _hoisted_1)];\n }), renderSlot(_ctx.$slots, \"decrementbutton\", {\n listeners: $options.downButtonListeners\n }, function () {\n return [createElementVNode(\"button\", mergeProps({\n \"class\": [_ctx.cx('decrementButton'), _ctx.decrementButtonClass]\n }, toHandlers($options.downButtonListeners, true), {\n disabled: _ctx.disabled,\n tabindex: -1,\n \"aria-hidden\": \"true\",\n type: \"button\"\n }, _ctx.ptm('decrementButton')), [renderSlot(_ctx.$slots, _ctx.$slots.decrementicon ? 'decrementicon' : 'decrementbuttonicon', {}, function () {\n return [(openBlock(), createBlock(resolveDynamicComponent(_ctx.decrementIcon || _ctx.decrementButtonIcon ? 'span' : 'AngleDownIcon'), mergeProps({\n \"class\": [_ctx.decrementIcon, _ctx.decrementButtonIcon]\n }, _ctx.ptm('decrementIcon'), {\n \"data-pc-section\": \"decrementicon\"\n }), null, 16, [\"class\"]))];\n })], 16, _hoisted_2)];\n })], 16)) : createCommentVNode(\"\", true), renderSlot(_ctx.$slots, \"incrementbutton\", {\n listeners: $options.upButtonListeners\n }, function () {\n return [_ctx.showButtons && _ctx.buttonLayout !== 'stacked' ? (openBlock(), createElementBlock(\"button\", mergeProps({\n key: 0,\n \"class\": [_ctx.cx('incrementButton'), _ctx.incrementButtonClass]\n }, toHandlers($options.upButtonListeners, true), {\n disabled: _ctx.disabled,\n tabindex: -1,\n \"aria-hidden\": \"true\",\n type: \"button\"\n }, _ctx.ptm('incrementButton')), [renderSlot(_ctx.$slots, _ctx.$slots.incrementicon ? 'incrementicon' : 'incrementbuttonicon', {}, function () {\n return [(openBlock(), createBlock(resolveDynamicComponent(_ctx.incrementIcon || _ctx.incrementButtonIcon ? 'span' : 'AngleUpIcon'), mergeProps({\n \"class\": [_ctx.incrementIcon, _ctx.incrementButtonIcon]\n }, _ctx.ptm('incrementIcon'), {\n \"data-pc-section\": \"incrementicon\"\n }), null, 16, [\"class\"]))];\n })], 16, _hoisted_3)) : createCommentVNode(\"\", true)];\n }), renderSlot(_ctx.$slots, \"decrementbutton\", {\n listeners: $options.downButtonListeners\n }, function () {\n return [_ctx.showButtons && _ctx.buttonLayout !== 'stacked' ? (openBlock(), createElementBlock(\"button\", mergeProps({\n key: 0,\n \"class\": [_ctx.cx('decrementButton'), _ctx.decrementButtonClass]\n }, toHandlers($options.downButtonListeners, true), {\n disabled: _ctx.disabled,\n tabindex: -1,\n \"aria-hidden\": \"true\",\n type: \"button\"\n }, _ctx.ptm('decrementButton')), [renderSlot(_ctx.$slots, _ctx.$slots.decrementicon ? 'decrementicon' : 'decrementbuttonicon', {}, function () {\n return [(openBlock(), createBlock(resolveDynamicComponent(_ctx.decrementIcon || _ctx.decrementButtonIcon ? 'span' : 'AngleDownIcon'), mergeProps({\n \"class\": [_ctx.decrementIcon, _ctx.decrementButtonIcon]\n }, _ctx.ptm('decrementIcon'), {\n \"data-pc-section\": \"decrementicon\"\n }), null, 16, [\"class\"]))];\n })], 16, _hoisted_4)) : createCommentVNode(\"\", true)];\n })], 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseIcon from '@primevue/icons/baseicon';\nimport { openBlock, createElementBlock, mergeProps, createElementVNode } from 'vue';\n\nvar script = {\n name: 'ChevronDownIcon',\n \"extends\": BaseIcon\n};\n\nvar _hoisted_1 = /*#__PURE__*/createElementVNode(\"path\", {\n d: \"M7.01744 10.398C6.91269 10.3985 6.8089 10.378 6.71215 10.3379C6.61541 10.2977 6.52766 10.2386 6.45405 10.1641L1.13907 4.84913C1.03306 4.69404 0.985221 4.5065 1.00399 4.31958C1.02276 4.13266 1.10693 3.95838 1.24166 3.82747C1.37639 3.69655 1.55301 3.61742 1.74039 3.60402C1.92777 3.59062 2.11386 3.64382 2.26584 3.75424L7.01744 8.47394L11.769 3.75424C11.9189 3.65709 12.097 3.61306 12.2748 3.62921C12.4527 3.64535 12.6199 3.72073 12.7498 3.84328C12.8797 3.96582 12.9647 4.12842 12.9912 4.30502C13.0177 4.48162 12.9841 4.662 12.8958 4.81724L7.58083 10.1322C7.50996 10.2125 7.42344 10.2775 7.32656 10.3232C7.22968 10.3689 7.12449 10.3944 7.01744 10.398Z\",\n fill: \"currentColor\"\n}, null, -1);\nvar _hoisted_2 = [_hoisted_1];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"svg\", mergeProps({\n width: \"14\",\n height: \"14\",\n viewBox: \"0 0 14 14\",\n fill: \"none\",\n xmlns: \"http://www.w3.org/2000/svg\"\n }, _ctx.pti()), _hoisted_2, 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseIcon from '@primevue/icons/baseicon';\nimport { openBlock, createElementBlock, mergeProps, createElementVNode } from 'vue';\n\nvar script = {\n name: 'TimesIcon',\n \"extends\": BaseIcon\n};\n\nvar _hoisted_1 = /*#__PURE__*/createElementVNode(\"path\", {\n d: \"M8.01186 7.00933L12.27 2.75116C12.341 2.68501 12.398 2.60524 12.4375 2.51661C12.4769 2.42798 12.4982 2.3323 12.4999 2.23529C12.5016 2.13827 12.4838 2.0419 12.4474 1.95194C12.4111 1.86197 12.357 1.78024 12.2884 1.71163C12.2198 1.64302 12.138 1.58893 12.0481 1.55259C11.9581 1.51625 11.8617 1.4984 11.7647 1.50011C11.6677 1.50182 11.572 1.52306 11.4834 1.56255C11.3948 1.60204 11.315 1.65898 11.2488 1.72997L6.99067 5.98814L2.7325 1.72997C2.59553 1.60234 2.41437 1.53286 2.22718 1.53616C2.03999 1.53946 1.8614 1.61529 1.72901 1.74767C1.59663 1.88006 1.5208 2.05865 1.5175 2.24584C1.5142 2.43303 1.58368 2.61419 1.71131 2.75116L5.96948 7.00933L1.71131 11.2675C1.576 11.403 1.5 11.5866 1.5 11.7781C1.5 11.9696 1.576 12.1532 1.71131 12.2887C1.84679 12.424 2.03043 12.5 2.2219 12.5C2.41338 12.5 2.59702 12.424 2.7325 12.2887L6.99067 8.03052L11.2488 12.2887C11.3843 12.424 11.568 12.5 11.7594 12.5C11.9509 12.5 12.1346 12.424 12.27 12.2887C12.4053 12.1532 12.4813 11.9696 12.4813 11.7781C12.4813 11.5866 12.4053 11.403 12.27 11.2675L8.01186 7.00933Z\",\n fill: \"currentColor\"\n}, null, -1);\nvar _hoisted_2 = [_hoisted_1];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"svg\", mergeProps({\n width: \"14\",\n height: \"14\",\n viewBox: \"0 0 14 14\",\n fill: \"none\",\n xmlns: \"http://www.w3.org/2000/svg\"\n }, _ctx.pti()), _hoisted_2, 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import { EventBus } from '@primeuix/utils/eventbus';\n\nvar OverlayEventBus = EventBus();\n\nexport { OverlayEventBus as default };\n//# sourceMappingURL=index.mjs.map\n","import { isClient } from '@primeuix/utils/dom';\nimport { renderSlot, openBlock, createBlock, Teleport, createCommentVNode } from 'vue';\n\nvar script = {\n name: 'Portal',\n props: {\n appendTo: {\n type: [String, Object],\n \"default\": 'body'\n },\n disabled: {\n type: Boolean,\n \"default\": false\n }\n },\n data: function data() {\n return {\n mounted: false\n };\n },\n mounted: function mounted() {\n this.mounted = isClient();\n },\n computed: {\n inline: function inline() {\n return this.disabled || this.appendTo === 'self';\n }\n }\n};\n\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return $options.inline ? renderSlot(_ctx.$slots, \"default\", {\n key: 0\n }) : $data.mounted ? (openBlock(), createBlock(Teleport, {\n key: 1,\n to: $props.appendTo\n }, [renderSlot(_ctx.$slots, \"default\")], 8, [\"to\"])) : createCommentVNode(\"\", true);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseStyle from '@primevue/core/base/style';\n\nvar theme = function theme(_ref) {\n var dt = _ref.dt;\n return \"\\n.p-select {\\n display: inline-flex;\\n cursor: pointer;\\n position: relative;\\n user-select: none;\\n background: \".concat(dt('select.background'), \";\\n border: 1px solid \").concat(dt('select.border.color'), \";\\n transition: background \").concat(dt('select.transition.duration'), \", color \").concat(dt('select.transition.duration'), \", border-color \").concat(dt('select.transition.duration'), \",\\n outline-color \").concat(dt('select.transition.duration'), \", box-shadow \").concat(dt('select.transition.duration'), \";\\n border-radius: \").concat(dt('select.border.radius'), \";\\n outline-color: transparent;\\n box-shadow: \").concat(dt('select.shadow'), \";\\n}\\n\\n.p-select:not(.p-disabled):hover {\\n border-color: \").concat(dt('select.hover.border.color'), \";\\n}\\n\\n.p-select:not(.p-disabled).p-focus {\\n border-color: \").concat(dt('select.focus.border.color'), \";\\n box-shadow: \").concat(dt('select.focus.ring.shadow'), \";\\n outline: \").concat(dt('select.focus.ring.width'), \" \").concat(dt('select.focus.ring.style'), \" \").concat(dt('select.focus.ring.color'), \";\\n outline-offset: \").concat(dt('select.focus.ring.offset'), \";\\n}\\n\\n.p-select.p-variant-filled {\\n background: \").concat(dt('select.filled.background'), \";\\n}\\n\\n.p-select.p-variant-filled.p-focus {\\n background: \").concat(dt('select.filled.focus.background'), \";\\n}\\n\\n.p-select.p-invalid {\\n border-color: \").concat(dt('select.invalid.border.color'), \";\\n}\\n\\n.p-select.p-disabled {\\n opacity: 1;\\n background: \").concat(dt('select.disabled.background'), \";\\n}\\n\\n.p-select-clear-icon {\\n position: absolute;\\n top: 50%;\\n margin-top: -0.5rem;\\n color: \").concat(dt('select.clear.icon.color'), \";\\n right: \").concat(dt('select.dropdown.width'), \";\\n}\\n\\n.p-select-dropdown {\\n display: flex;\\n align-items: center;\\n justify-content: center;\\n flex-shrink: 0;\\n background: transparent;\\n color: \").concat(dt('select.dropdown.color'), \";\\n width: \").concat(dt('select.dropdown.width'), \";\\n border-top-right-radius: \").concat(dt('select.border.radius'), \";\\n border-bottom-right-radius: \").concat(dt('select.border.radius'), \";\\n}\\n\\n.p-select-label {\\n display: block;\\n white-space: nowrap;\\n overflow: hidden;\\n flex: 1 1 auto;\\n width: 1%;\\n padding: \").concat(dt('select.padding.y'), \" \").concat(dt('select.padding.x'), \";\\n text-overflow: ellipsis;\\n cursor: pointer;\\n color: \").concat(dt('select.color'), \";\\n background: transparent;\\n border: 0 none;\\n outline: 0 none;\\n}\\n\\n.p-select-label.p-placeholder {\\n color: \").concat(dt('select.placeholder.color'), \";\\n}\\n\\n.p-select:has(.p-select-clear-icon) .p-select-label {\\n padding-right: calc(1rem + \").concat(dt('select.padding.x'), \");\\n}\\n\\n.p-select.p-disabled .p-select-label {\\n color: \").concat(dt('select.disabled.color'), \";\\n}\\n\\n.p-select-label-empty {\\n overflow: hidden;\\n opacity: 0;\\n}\\n\\ninput.p-select-label {\\n cursor: default;\\n}\\n\\n.p-select .p-select-overlay {\\n min-width: 100%;\\n}\\n\\n.p-select-overlay {\\n position: absolute;\\n top: 0;\\n left: 0;\\n background: \").concat(dt('select.overlay.background'), \";\\n color: \").concat(dt('select.overlay.color'), \";\\n border: 1px solid \").concat(dt('select.overlay.border.color'), \";\\n border-radius: \").concat(dt('select.overlay.border.radius'), \";\\n box-shadow: \").concat(dt('select.overlay.shadow'), \";\\n}\\n\\n.p-select-header {\\n padding: \").concat(dt('select.list.header.padding'), \";\\n}\\n\\n.p-select-filter {\\n width: 100%;\\n}\\n\\n.p-select-list-container {\\n overflow: auto;\\n}\\n\\n.p-select-option-group {\\n cursor: auto;\\n margin: 0;\\n padding: \").concat(dt('select.option.group.padding'), \";\\n background: \").concat(dt('select.option.group.background'), \";\\n color: \").concat(dt('select.option.group.color'), \";\\n font-weight: \").concat(dt('select.option.group.font.weight'), \";\\n}\\n\\n.p-select-list {\\n margin: 0;\\n padding: 0;\\n list-style-type: none;\\n padding: \").concat(dt('select.list.padding'), \";\\n gap: \").concat(dt('select.list.gap'), \";\\n display: flex;\\n flex-direction: column;\\n}\\n\\n.p-select-option {\\n cursor: pointer;\\n font-weight: normal;\\n white-space: nowrap;\\n position: relative;\\n overflow: hidden;\\n display: flex;\\n align-items: center;\\n padding: \").concat(dt('select.option.padding'), \";\\n border: 0 none;\\n color: \").concat(dt('select.option.color'), \";\\n background: transparent;\\n transition: background \").concat(dt('select.transition.duration'), \", color \").concat(dt('select.transition.duration'), \", border-color \").concat(dt('select.transition.duration'), \",\\n box-shadow \").concat(dt('select.transition.duration'), \", outline-color \").concat(dt('select.transition.duration'), \";\\n border-radius: \").concat(dt('select.option.border.radius'), \";\\n}\\n\\n.p-select-option:not(.p-select-option-selected):not(.p-disabled).p-focus {\\n background: \").concat(dt('select.option.focus.background'), \";\\n color: \").concat(dt('select.option.focus.color'), \";\\n}\\n\\n.p-select-option.p-select-option-selected {\\n background: \").concat(dt('select.option.selected.background'), \";\\n color: \").concat(dt('select.option.selected.color'), \";\\n}\\n\\n.p-select-option.p-select-option-selected.p-focus {\\n background: \").concat(dt('select.option.selected.focus.background'), \";\\n color: \").concat(dt('select.option.selected.focus.color'), \";\\n}\\n\\n.p-select-option-check-icon {\\n position: relative;\\n margin-inline-start: \").concat(dt('select.checkmark.gutter.start'), \";\\n margin-inline-end: \").concat(dt('select.checkmark.gutter.end'), \";\\n color: \").concat(dt('select.checkmark.color'), \";\\n}\\n\\n.p-select-empty-message {\\n padding: \").concat(dt('select.empty.message.padding'), \";\\n}\\n\\n.p-select-fluid {\\n display: flex;\\n}\\n\");\n};\nvar classes = {\n root: function root(_ref2) {\n var instance = _ref2.instance,\n props = _ref2.props,\n state = _ref2.state;\n return ['p-select p-component p-inputwrapper', {\n 'p-disabled': props.disabled,\n 'p-invalid': props.invalid,\n 'p-variant-filled': props.variant ? props.variant === 'filled' : instance.$primevue.config.inputStyle === 'filled' || instance.$primevue.config.inputVariant === 'filled',\n 'p-focus': state.focused,\n 'p-inputwrapper-filled': instance.hasSelectedOption,\n 'p-inputwrapper-focus': state.focused || state.overlayVisible,\n 'p-select-open': state.overlayVisible,\n 'p-select-fluid': props.fluid\n }];\n },\n label: function label(_ref3) {\n var instance = _ref3.instance,\n props = _ref3.props;\n return ['p-select-label', {\n 'p-placeholder': !props.editable && instance.label === props.placeholder,\n 'p-select-label-empty': !props.editable && !instance.$slots['value'] && (instance.label === 'p-emptylabel' || instance.label.length === 0)\n }];\n },\n clearIcon: 'p-select-clear-icon',\n dropdown: 'p-select-dropdown',\n loadingicon: 'p-select-loading-icon',\n dropdownIcon: 'p-select-dropdown-icon',\n overlay: 'p-select-overlay p-component',\n header: 'p-select-header',\n pcFilter: 'p-select-filter',\n listContainer: 'p-select-list-container',\n list: 'p-select-list',\n optionGroup: 'p-select-option-group',\n optionGroupLabel: 'p-select-option-group-label',\n option: function option(_ref4) {\n var instance = _ref4.instance,\n props = _ref4.props,\n state = _ref4.state,\n _option = _ref4.option,\n focusedOption = _ref4.focusedOption;\n return ['p-select-option', {\n 'p-select-option-selected': instance.isSelected(_option) && props.highlightOnSelect,\n 'p-focus': state.focusedOptionIndex === focusedOption,\n 'p-disabled': instance.isOptionDisabled(_option)\n }];\n },\n optionLabel: 'p-select-option-label',\n optionCheckIcon: 'p-select-option-check-icon',\n optionBlankIcon: 'p-select-option-blank-icon',\n emptyMessage: 'p-select-empty-message'\n};\nvar SelectStyle = BaseStyle.extend({\n name: 'select',\n theme: theme,\n classes: classes\n});\n\nexport { SelectStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import { FilterService } from '@primevue/core/api';\nimport { UniqueComponentId, ConnectedOverlayScrollHandler } from '@primevue/core/utils';\nimport { focus, isAndroid, getFirstFocusableElement, getLastFocusableElement, addStyle, relativePosition, getOuterWidth, absolutePosition, isTouchDevice, isVisible, getFocusableElements, findSingle } from '@primeuix/utils/dom';\nimport { resolveFieldData, isPrintableCharacter, isNotEmpty, equals, findLastIndex } from '@primeuix/utils/object';\nimport { ZIndex } from '@primeuix/utils/zindex';\nimport BlankIcon from '@primevue/icons/blank';\nimport CheckIcon from '@primevue/icons/check';\nimport ChevronDownIcon from '@primevue/icons/chevrondown';\nimport SearchIcon from '@primevue/icons/search';\nimport SpinnerIcon from '@primevue/icons/spinner';\nimport TimesIcon from '@primevue/icons/times';\nimport IconField from 'primevue/iconfield';\nimport InputIcon from 'primevue/inputicon';\nimport InputText from 'primevue/inputtext';\nimport OverlayEventBus from 'primevue/overlayeventbus';\nimport Portal from 'primevue/portal';\nimport Ripple from 'primevue/ripple';\nimport VirtualScroller from 'primevue/virtualscroller';\nimport BaseComponent from '@primevue/core/basecomponent';\nimport SelectStyle from 'primevue/select/style';\nimport { resolveComponent, resolveDirective, openBlock, createElementBlock, mergeProps, renderSlot, createTextVNode, toDisplayString, normalizeClass, createBlock, resolveDynamicComponent, createCommentVNode, createElementVNode, createVNode, withCtx, Transition, normalizeProps, createSlots, Fragment, renderList, withDirectives } from 'vue';\n\nvar script$1 = {\n name: 'BaseSelect',\n \"extends\": BaseComponent,\n props: {\n modelValue: null,\n options: Array,\n optionLabel: [String, Function],\n optionValue: [String, Function],\n optionDisabled: [String, Function],\n optionGroupLabel: [String, Function],\n optionGroupChildren: [String, Function],\n scrollHeight: {\n type: String,\n \"default\": '14rem'\n },\n filter: Boolean,\n filterPlaceholder: String,\n filterLocale: String,\n filterMatchMode: {\n type: String,\n \"default\": 'contains'\n },\n filterFields: {\n type: Array,\n \"default\": null\n },\n editable: Boolean,\n placeholder: {\n type: String,\n \"default\": null\n },\n variant: {\n type: String,\n \"default\": null\n },\n invalid: {\n type: Boolean,\n \"default\": false\n },\n disabled: {\n type: Boolean,\n \"default\": false\n },\n dataKey: null,\n showClear: {\n type: Boolean,\n \"default\": false\n },\n fluid: {\n type: Boolean,\n \"default\": false\n },\n inputId: {\n type: String,\n \"default\": null\n },\n inputClass: {\n type: [String, Object],\n \"default\": null\n },\n inputStyle: {\n type: Object,\n \"default\": null\n },\n labelId: {\n type: String,\n \"default\": null\n },\n labelClass: {\n type: [String, Object],\n \"default\": null\n },\n labelStyle: {\n type: Object,\n \"default\": null\n },\n panelClass: {\n type: [String, Object],\n \"default\": null\n },\n overlayStyle: {\n type: Object,\n \"default\": null\n },\n overlayClass: {\n type: [String, Object],\n \"default\": null\n },\n panelStyle: {\n type: Object,\n \"default\": null\n },\n appendTo: {\n type: [String, Object],\n \"default\": 'body'\n },\n loading: {\n type: Boolean,\n \"default\": false\n },\n clearIcon: {\n type: String,\n \"default\": undefined\n },\n dropdownIcon: {\n type: String,\n \"default\": undefined\n },\n filterIcon: {\n type: String,\n \"default\": undefined\n },\n loadingIcon: {\n type: String,\n \"default\": undefined\n },\n resetFilterOnHide: {\n type: Boolean,\n \"default\": false\n },\n resetFilterOnClear: {\n type: Boolean,\n \"default\": false\n },\n virtualScrollerOptions: {\n type: Object,\n \"default\": null\n },\n autoOptionFocus: {\n type: Boolean,\n \"default\": false\n },\n autoFilterFocus: {\n type: Boolean,\n \"default\": false\n },\n selectOnFocus: {\n type: Boolean,\n \"default\": false\n },\n focusOnHover: {\n type: Boolean,\n \"default\": true\n },\n highlightOnSelect: {\n type: Boolean,\n \"default\": true\n },\n checkmark: {\n type: Boolean,\n \"default\": false\n },\n filterMessage: {\n type: String,\n \"default\": null\n },\n selectionMessage: {\n type: String,\n \"default\": null\n },\n emptySelectionMessage: {\n type: String,\n \"default\": null\n },\n emptyFilterMessage: {\n type: String,\n \"default\": null\n },\n emptyMessage: {\n type: String,\n \"default\": null\n },\n tabindex: {\n type: Number,\n \"default\": 0\n },\n ariaLabel: {\n type: String,\n \"default\": null\n },\n ariaLabelledby: {\n type: String,\n \"default\": null\n }\n },\n style: SelectStyle,\n provide: function provide() {\n return {\n $pcSelect: this,\n $parentInstance: this\n };\n }\n};\n\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _unsupportedIterableToArray(r, a) { if (r) { if (\"string\" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return \"Object\" === t && r.constructor && (t = r.constructor.name), \"Map\" === t || \"Set\" === t ? Array.from(r) : \"Arguments\" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }\nfunction _iterableToArray(r) { if (\"undefined\" != typeof Symbol && null != r[Symbol.iterator] || null != r[\"@@iterator\"]) return Array.from(r); }\nfunction _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }\nfunction _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nvar script = {\n name: 'Select',\n \"extends\": script$1,\n inheritAttrs: false,\n emits: ['update:modelValue', 'change', 'focus', 'blur', 'before-show', 'before-hide', 'show', 'hide', 'filter'],\n outsideClickListener: null,\n scrollHandler: null,\n resizeListener: null,\n labelClickListener: null,\n overlay: null,\n list: null,\n virtualScroller: null,\n searchTimeout: null,\n searchValue: null,\n isModelValueChanged: false,\n data: function data() {\n return {\n id: this.$attrs.id,\n clicked: false,\n focused: false,\n focusedOptionIndex: -1,\n filterValue: null,\n overlayVisible: false\n };\n },\n watch: {\n '$attrs.id': function $attrsId(newValue) {\n this.id = newValue || UniqueComponentId();\n },\n modelValue: function modelValue() {\n this.isModelValueChanged = true;\n },\n options: function options() {\n this.autoUpdateModel();\n }\n },\n mounted: function mounted() {\n this.id = this.id || UniqueComponentId();\n this.autoUpdateModel();\n this.bindLabelClickListener();\n },\n updated: function updated() {\n if (this.overlayVisible && this.isModelValueChanged) {\n this.scrollInView(this.findSelectedOptionIndex());\n }\n this.isModelValueChanged = false;\n },\n beforeUnmount: function beforeUnmount() {\n this.unbindOutsideClickListener();\n this.unbindResizeListener();\n this.unbindLabelClickListener();\n if (this.scrollHandler) {\n this.scrollHandler.destroy();\n this.scrollHandler = null;\n }\n if (this.overlay) {\n ZIndex.clear(this.overlay);\n this.overlay = null;\n }\n },\n methods: {\n getOptionIndex: function getOptionIndex(index, fn) {\n return this.virtualScrollerDisabled ? index : fn && fn(index)['index'];\n },\n getOptionLabel: function getOptionLabel(option) {\n return this.optionLabel ? resolveFieldData(option, this.optionLabel) : option;\n },\n getOptionValue: function getOptionValue(option) {\n return this.optionValue ? resolveFieldData(option, this.optionValue) : option;\n },\n getOptionRenderKey: function getOptionRenderKey(option, index) {\n return (this.dataKey ? resolveFieldData(option, this.dataKey) : this.getOptionLabel(option)) + '_' + index;\n },\n getPTItemOptions: function getPTItemOptions(option, itemOptions, index, key) {\n return this.ptm(key, {\n context: {\n option: option,\n index: index,\n selected: this.isSelected(option),\n focused: this.focusedOptionIndex === this.getOptionIndex(index, itemOptions),\n disabled: this.isOptionDisabled(option)\n }\n });\n },\n isOptionDisabled: function isOptionDisabled(option) {\n return this.optionDisabled ? resolveFieldData(option, this.optionDisabled) : false;\n },\n isOptionGroup: function isOptionGroup(option) {\n return this.optionGroupLabel && option.optionGroup && option.group;\n },\n getOptionGroupLabel: function getOptionGroupLabel(optionGroup) {\n return resolveFieldData(optionGroup, this.optionGroupLabel);\n },\n getOptionGroupChildren: function getOptionGroupChildren(optionGroup) {\n return resolveFieldData(optionGroup, this.optionGroupChildren);\n },\n getAriaPosInset: function getAriaPosInset(index) {\n var _this = this;\n return (this.optionGroupLabel ? index - this.visibleOptions.slice(0, index).filter(function (option) {\n return _this.isOptionGroup(option);\n }).length : index) + 1;\n },\n show: function show(isFocus) {\n this.$emit('before-show');\n this.overlayVisible = true;\n this.focusedOptionIndex = this.focusedOptionIndex !== -1 ? this.focusedOptionIndex : this.autoOptionFocus ? this.findFirstFocusedOptionIndex() : this.editable ? -1 : this.findSelectedOptionIndex();\n isFocus && focus(this.$refs.focusInput);\n },\n hide: function hide(isFocus) {\n var _this2 = this;\n var _hide = function _hide() {\n _this2.$emit('before-hide');\n _this2.overlayVisible = false;\n _this2.clicked = false;\n _this2.focusedOptionIndex = -1;\n _this2.searchValue = '';\n _this2.resetFilterOnHide && (_this2.filterValue = null);\n isFocus && focus(_this2.$refs.focusInput);\n };\n setTimeout(function () {\n _hide();\n }, 0); // For ScreenReaders\n },\n onFocus: function onFocus(event) {\n if (this.disabled) {\n // For ScreenReaders\n return;\n }\n this.focused = true;\n if (this.overlayVisible) {\n this.focusedOptionIndex = this.focusedOptionIndex !== -1 ? this.focusedOptionIndex : this.autoOptionFocus ? this.findFirstFocusedOptionIndex() : this.editable ? -1 : this.findSelectedOptionIndex();\n this.scrollInView(this.focusedOptionIndex);\n }\n this.$emit('focus', event);\n },\n onBlur: function onBlur(event) {\n this.focused = false;\n this.focusedOptionIndex = -1;\n this.searchValue = '';\n this.$emit('blur', event);\n },\n onKeyDown: function onKeyDown(event) {\n if (this.disabled || isAndroid()) {\n event.preventDefault();\n return;\n }\n var metaKey = event.metaKey || event.ctrlKey;\n switch (event.code) {\n case 'ArrowDown':\n this.onArrowDownKey(event);\n break;\n case 'ArrowUp':\n this.onArrowUpKey(event, this.editable);\n break;\n case 'ArrowLeft':\n case 'ArrowRight':\n this.onArrowLeftKey(event, this.editable);\n break;\n case 'Home':\n this.onHomeKey(event, this.editable);\n break;\n case 'End':\n this.onEndKey(event, this.editable);\n break;\n case 'PageDown':\n this.onPageDownKey(event);\n break;\n case 'PageUp':\n this.onPageUpKey(event);\n break;\n case 'Space':\n this.onSpaceKey(event, this.editable);\n break;\n case 'Enter':\n case 'NumpadEnter':\n this.onEnterKey(event);\n break;\n case 'Escape':\n this.onEscapeKey(event);\n break;\n case 'Tab':\n this.onTabKey(event);\n break;\n case 'Backspace':\n this.onBackspaceKey(event, this.editable);\n break;\n case 'ShiftLeft':\n case 'ShiftRight':\n //NOOP\n break;\n default:\n if (!metaKey && isPrintableCharacter(event.key)) {\n !this.overlayVisible && this.show();\n !this.editable && this.searchOptions(event, event.key);\n }\n break;\n }\n this.clicked = false;\n },\n onEditableInput: function onEditableInput(event) {\n var value = event.target.value;\n this.searchValue = '';\n var matched = this.searchOptions(event, value);\n !matched && (this.focusedOptionIndex = -1);\n this.updateModel(event, value);\n !this.overlayVisible && isNotEmpty(value) && this.show();\n },\n onContainerClick: function onContainerClick(event) {\n if (this.disabled || this.loading) {\n return;\n }\n if (event.target.tagName === 'INPUT' || event.target.getAttribute('data-pc-section') === 'clearicon' || event.target.closest('[data-pc-section=\"clearicon\"]')) {\n return;\n } else if (!this.overlay || !this.overlay.contains(event.target)) {\n this.overlayVisible ? this.hide(true) : this.show(true);\n }\n this.clicked = true;\n },\n onClearClick: function onClearClick(event) {\n this.updateModel(event, null);\n this.resetFilterOnClear && (this.filterValue = null);\n },\n onFirstHiddenFocus: function onFirstHiddenFocus(event) {\n var focusableEl = event.relatedTarget === this.$refs.focusInput ? getFirstFocusableElement(this.overlay, ':not([data-p-hidden-focusable=\"true\"])') : this.$refs.focusInput;\n focus(focusableEl);\n },\n onLastHiddenFocus: function onLastHiddenFocus(event) {\n var focusableEl = event.relatedTarget === this.$refs.focusInput ? getLastFocusableElement(this.overlay, ':not([data-p-hidden-focusable=\"true\"])') : this.$refs.focusInput;\n focus(focusableEl);\n },\n onOptionSelect: function onOptionSelect(event, option) {\n var isHide = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;\n var value = this.getOptionValue(option);\n this.updateModel(event, value);\n isHide && this.hide(true);\n },\n onOptionMouseMove: function onOptionMouseMove(event, index) {\n if (this.focusOnHover) {\n this.changeFocusedOptionIndex(event, index);\n }\n },\n onFilterChange: function onFilterChange(event) {\n var value = event.target.value;\n this.filterValue = value;\n this.focusedOptionIndex = -1;\n this.$emit('filter', {\n originalEvent: event,\n value: value\n });\n !this.virtualScrollerDisabled && this.virtualScroller.scrollToIndex(0);\n },\n onFilterKeyDown: function onFilterKeyDown(event) {\n switch (event.code) {\n case 'ArrowDown':\n this.onArrowDownKey(event);\n break;\n case 'ArrowUp':\n this.onArrowUpKey(event, true);\n break;\n case 'ArrowLeft':\n case 'ArrowRight':\n this.onArrowLeftKey(event, true);\n break;\n case 'Home':\n this.onHomeKey(event, true);\n break;\n case 'End':\n this.onEndKey(event, true);\n break;\n case 'Enter':\n case 'NumpadEnter':\n this.onEnterKey(event);\n break;\n case 'Escape':\n this.onEscapeKey(event);\n break;\n case 'Tab':\n this.onTabKey(event, true);\n break;\n }\n },\n onFilterBlur: function onFilterBlur() {\n this.focusedOptionIndex = -1;\n },\n onFilterUpdated: function onFilterUpdated() {\n if (this.overlayVisible) {\n this.alignOverlay();\n }\n },\n onOverlayClick: function onOverlayClick(event) {\n OverlayEventBus.emit('overlay-click', {\n originalEvent: event,\n target: this.$el\n });\n },\n onOverlayKeyDown: function onOverlayKeyDown(event) {\n switch (event.code) {\n case 'Escape':\n this.onEscapeKey(event);\n break;\n }\n },\n onArrowDownKey: function onArrowDownKey(event) {\n if (!this.overlayVisible) {\n this.show();\n this.editable && this.changeFocusedOptionIndex(event, this.findSelectedOptionIndex());\n } else {\n var optionIndex = this.focusedOptionIndex !== -1 ? this.findNextOptionIndex(this.focusedOptionIndex) : this.clicked ? this.findFirstOptionIndex() : this.findFirstFocusedOptionIndex();\n this.changeFocusedOptionIndex(event, optionIndex);\n }\n event.preventDefault();\n },\n onArrowUpKey: function onArrowUpKey(event) {\n var pressedInInputText = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n if (event.altKey && !pressedInInputText) {\n if (this.focusedOptionIndex !== -1) {\n this.onOptionSelect(event, this.visibleOptions[this.focusedOptionIndex]);\n }\n this.overlayVisible && this.hide();\n event.preventDefault();\n } else {\n var optionIndex = this.focusedOptionIndex !== -1 ? this.findPrevOptionIndex(this.focusedOptionIndex) : this.clicked ? this.findLastOptionIndex() : this.findLastFocusedOptionIndex();\n this.changeFocusedOptionIndex(event, optionIndex);\n !this.overlayVisible && this.show();\n event.preventDefault();\n }\n },\n onArrowLeftKey: function onArrowLeftKey(event) {\n var pressedInInputText = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n pressedInInputText && (this.focusedOptionIndex = -1);\n },\n onHomeKey: function onHomeKey(event) {\n var pressedInInputText = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n if (pressedInInputText) {\n var target = event.currentTarget;\n if (event.shiftKey) {\n target.setSelectionRange(0, event.target.selectionStart);\n } else {\n target.setSelectionRange(0, 0);\n this.focusedOptionIndex = -1;\n }\n } else {\n this.changeFocusedOptionIndex(event, this.findFirstOptionIndex());\n !this.overlayVisible && this.show();\n }\n event.preventDefault();\n },\n onEndKey: function onEndKey(event) {\n var pressedInInputText = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n if (pressedInInputText) {\n var target = event.currentTarget;\n if (event.shiftKey) {\n target.setSelectionRange(event.target.selectionStart, target.value.length);\n } else {\n var len = target.value.length;\n target.setSelectionRange(len, len);\n this.focusedOptionIndex = -1;\n }\n } else {\n this.changeFocusedOptionIndex(event, this.findLastOptionIndex());\n !this.overlayVisible && this.show();\n }\n event.preventDefault();\n },\n onPageUpKey: function onPageUpKey(event) {\n this.scrollInView(0);\n event.preventDefault();\n },\n onPageDownKey: function onPageDownKey(event) {\n this.scrollInView(this.visibleOptions.length - 1);\n event.preventDefault();\n },\n onEnterKey: function onEnterKey(event) {\n if (!this.overlayVisible) {\n this.focusedOptionIndex = -1; // reset\n this.onArrowDownKey(event);\n } else {\n if (this.focusedOptionIndex !== -1) {\n this.onOptionSelect(event, this.visibleOptions[this.focusedOptionIndex]);\n }\n this.hide();\n }\n event.preventDefault();\n },\n onSpaceKey: function onSpaceKey(event) {\n var pressedInInputText = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n !pressedInInputText && this.onEnterKey(event);\n },\n onEscapeKey: function onEscapeKey(event) {\n this.overlayVisible && this.hide(true);\n event.preventDefault();\n event.stopPropagation(); //@todo will be changed next versionss\n },\n onTabKey: function onTabKey(event) {\n var pressedInInputText = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n if (!pressedInInputText) {\n if (this.overlayVisible && this.hasFocusableElements()) {\n focus(this.$refs.firstHiddenFocusableElementOnOverlay);\n event.preventDefault();\n } else {\n if (this.focusedOptionIndex !== -1) {\n this.onOptionSelect(event, this.visibleOptions[this.focusedOptionIndex]);\n }\n this.overlayVisible && this.hide(this.filter);\n }\n }\n },\n onBackspaceKey: function onBackspaceKey(event) {\n var pressedInInputText = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n if (pressedInInputText) {\n !this.overlayVisible && this.show();\n }\n },\n onOverlayEnter: function onOverlayEnter(el) {\n ZIndex.set('overlay', el, this.$primevue.config.zIndex.overlay);\n addStyle(el, {\n position: 'absolute',\n top: '0',\n left: '0'\n });\n this.alignOverlay();\n this.scrollInView();\n this.autoFilterFocus && focus(this.$refs.filterInput.$el);\n },\n onOverlayAfterEnter: function onOverlayAfterEnter() {\n this.bindOutsideClickListener();\n this.bindScrollListener();\n this.bindResizeListener();\n this.$emit('show');\n },\n onOverlayLeave: function onOverlayLeave() {\n this.unbindOutsideClickListener();\n this.unbindScrollListener();\n this.unbindResizeListener();\n this.$emit('hide');\n this.overlay = null;\n },\n onOverlayAfterLeave: function onOverlayAfterLeave(el) {\n ZIndex.clear(el);\n },\n alignOverlay: function alignOverlay() {\n if (this.appendTo === 'self') {\n relativePosition(this.overlay, this.$el);\n } else {\n this.overlay.style.minWidth = getOuterWidth(this.$el) + 'px';\n absolutePosition(this.overlay, this.$el);\n }\n },\n bindOutsideClickListener: function bindOutsideClickListener() {\n var _this3 = this;\n if (!this.outsideClickListener) {\n this.outsideClickListener = function (event) {\n if (_this3.overlayVisible && _this3.overlay && !_this3.$el.contains(event.target) && !_this3.overlay.contains(event.target)) {\n _this3.hide();\n }\n };\n document.addEventListener('click', this.outsideClickListener);\n }\n },\n unbindOutsideClickListener: function unbindOutsideClickListener() {\n if (this.outsideClickListener) {\n document.removeEventListener('click', this.outsideClickListener);\n this.outsideClickListener = null;\n }\n },\n bindScrollListener: function bindScrollListener() {\n var _this4 = this;\n if (!this.scrollHandler) {\n this.scrollHandler = new ConnectedOverlayScrollHandler(this.$refs.container, function () {\n if (_this4.overlayVisible) {\n _this4.hide();\n }\n });\n }\n this.scrollHandler.bindScrollListener();\n },\n unbindScrollListener: function unbindScrollListener() {\n if (this.scrollHandler) {\n this.scrollHandler.unbindScrollListener();\n }\n },\n bindResizeListener: function bindResizeListener() {\n var _this5 = this;\n if (!this.resizeListener) {\n this.resizeListener = function () {\n if (_this5.overlayVisible && !isTouchDevice()) {\n _this5.hide();\n }\n };\n window.addEventListener('resize', this.resizeListener);\n }\n },\n unbindResizeListener: function unbindResizeListener() {\n if (this.resizeListener) {\n window.removeEventListener('resize', this.resizeListener);\n this.resizeListener = null;\n }\n },\n bindLabelClickListener: function bindLabelClickListener() {\n var _this6 = this;\n if (!this.editable && !this.labelClickListener) {\n var label = document.querySelector(\"label[for=\\\"\".concat(this.inputId, \"\\\"]\"));\n if (label && isVisible(label)) {\n this.labelClickListener = function () {\n focus(_this6.$refs.focusInput);\n };\n label.addEventListener('click', this.labelClickListener);\n }\n }\n },\n unbindLabelClickListener: function unbindLabelClickListener() {\n if (this.labelClickListener) {\n var label = document.querySelector(\"label[for=\\\"\".concat(this.inputId, \"\\\"]\"));\n if (label && isVisible(label)) {\n label.removeEventListener('click', this.labelClickListener);\n }\n }\n },\n hasFocusableElements: function hasFocusableElements() {\n return getFocusableElements(this.overlay, ':not([data-p-hidden-focusable=\"true\"])').length > 0;\n },\n isOptionMatched: function isOptionMatched(option) {\n var _this$getOptionLabel;\n return this.isValidOption(option) && typeof this.getOptionLabel(option) === 'string' && ((_this$getOptionLabel = this.getOptionLabel(option)) === null || _this$getOptionLabel === void 0 ? void 0 : _this$getOptionLabel.toLocaleLowerCase(this.filterLocale).startsWith(this.searchValue.toLocaleLowerCase(this.filterLocale)));\n },\n isValidOption: function isValidOption(option) {\n return isNotEmpty(option) && !(this.isOptionDisabled(option) || this.isOptionGroup(option));\n },\n isValidSelectedOption: function isValidSelectedOption(option) {\n return this.isValidOption(option) && this.isSelected(option);\n },\n isSelected: function isSelected(option) {\n return this.isValidOption(option) && equals(this.modelValue, this.getOptionValue(option), this.equalityKey);\n },\n findFirstOptionIndex: function findFirstOptionIndex() {\n var _this7 = this;\n return this.visibleOptions.findIndex(function (option) {\n return _this7.isValidOption(option);\n });\n },\n findLastOptionIndex: function findLastOptionIndex() {\n var _this8 = this;\n return findLastIndex(this.visibleOptions, function (option) {\n return _this8.isValidOption(option);\n });\n },\n findNextOptionIndex: function findNextOptionIndex(index) {\n var _this9 = this;\n var matchedOptionIndex = index < this.visibleOptions.length - 1 ? this.visibleOptions.slice(index + 1).findIndex(function (option) {\n return _this9.isValidOption(option);\n }) : -1;\n return matchedOptionIndex > -1 ? matchedOptionIndex + index + 1 : index;\n },\n findPrevOptionIndex: function findPrevOptionIndex(index) {\n var _this10 = this;\n var matchedOptionIndex = index > 0 ? findLastIndex(this.visibleOptions.slice(0, index), function (option) {\n return _this10.isValidOption(option);\n }) : -1;\n return matchedOptionIndex > -1 ? matchedOptionIndex : index;\n },\n findSelectedOptionIndex: function findSelectedOptionIndex() {\n var _this11 = this;\n return this.hasSelectedOption ? this.visibleOptions.findIndex(function (option) {\n return _this11.isValidSelectedOption(option);\n }) : -1;\n },\n findFirstFocusedOptionIndex: function findFirstFocusedOptionIndex() {\n var selectedIndex = this.findSelectedOptionIndex();\n return selectedIndex < 0 ? this.findFirstOptionIndex() : selectedIndex;\n },\n findLastFocusedOptionIndex: function findLastFocusedOptionIndex() {\n var selectedIndex = this.findSelectedOptionIndex();\n return selectedIndex < 0 ? this.findLastOptionIndex() : selectedIndex;\n },\n searchOptions: function searchOptions(event, _char) {\n var _this12 = this;\n this.searchValue = (this.searchValue || '') + _char;\n var optionIndex = -1;\n var matched = false;\n if (isNotEmpty(this.searchValue)) {\n if (this.focusedOptionIndex !== -1) {\n optionIndex = this.visibleOptions.slice(this.focusedOptionIndex).findIndex(function (option) {\n return _this12.isOptionMatched(option);\n });\n optionIndex = optionIndex === -1 ? this.visibleOptions.slice(0, this.focusedOptionIndex).findIndex(function (option) {\n return _this12.isOptionMatched(option);\n }) : optionIndex + this.focusedOptionIndex;\n } else {\n optionIndex = this.visibleOptions.findIndex(function (option) {\n return _this12.isOptionMatched(option);\n });\n }\n if (optionIndex !== -1) {\n matched = true;\n }\n if (optionIndex === -1 && this.focusedOptionIndex === -1) {\n optionIndex = this.findFirstFocusedOptionIndex();\n }\n if (optionIndex !== -1) {\n this.changeFocusedOptionIndex(event, optionIndex);\n }\n }\n if (this.searchTimeout) {\n clearTimeout(this.searchTimeout);\n }\n this.searchTimeout = setTimeout(function () {\n _this12.searchValue = '';\n _this12.searchTimeout = null;\n }, 500);\n return matched;\n },\n changeFocusedOptionIndex: function changeFocusedOptionIndex(event, index) {\n if (this.focusedOptionIndex !== index) {\n this.focusedOptionIndex = index;\n this.scrollInView();\n if (this.selectOnFocus) {\n this.onOptionSelect(event, this.visibleOptions[index], false);\n }\n }\n },\n scrollInView: function scrollInView() {\n var _this13 = this;\n var index = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : -1;\n this.$nextTick(function () {\n var id = index !== -1 ? \"\".concat(_this13.id, \"_\").concat(index) : _this13.focusedOptionId;\n var element = findSingle(_this13.list, \"li[id=\\\"\".concat(id, \"\\\"]\"));\n if (element) {\n element.scrollIntoView && element.scrollIntoView({\n block: 'nearest',\n inline: 'start'\n });\n } else if (!_this13.virtualScrollerDisabled) {\n _this13.virtualScroller && _this13.virtualScroller.scrollToIndex(index !== -1 ? index : _this13.focusedOptionIndex);\n }\n });\n },\n autoUpdateModel: function autoUpdateModel() {\n if (this.selectOnFocus && this.autoOptionFocus && !this.hasSelectedOption) {\n this.focusedOptionIndex = this.findFirstFocusedOptionIndex();\n this.onOptionSelect(null, this.visibleOptions[this.focusedOptionIndex], false);\n }\n },\n updateModel: function updateModel(event, value) {\n this.$emit('update:modelValue', value);\n this.$emit('change', {\n originalEvent: event,\n value: value\n });\n },\n flatOptions: function flatOptions(options) {\n var _this14 = this;\n return (options || []).reduce(function (result, option, index) {\n result.push({\n optionGroup: option,\n group: true,\n index: index\n });\n var optionGroupChildren = _this14.getOptionGroupChildren(option);\n optionGroupChildren && optionGroupChildren.forEach(function (o) {\n return result.push(o);\n });\n return result;\n }, []);\n },\n overlayRef: function overlayRef(el) {\n this.overlay = el;\n },\n listRef: function listRef(el, contentRef) {\n this.list = el;\n contentRef && contentRef(el); // For VirtualScroller\n },\n virtualScrollerRef: function virtualScrollerRef(el) {\n this.virtualScroller = el;\n }\n },\n computed: {\n visibleOptions: function visibleOptions() {\n var _this15 = this;\n var options = this.optionGroupLabel ? this.flatOptions(this.options) : this.options || [];\n if (this.filterValue) {\n var filteredOptions = FilterService.filter(options, this.searchFields, this.filterValue, this.filterMatchMode, this.filterLocale);\n if (this.optionGroupLabel) {\n var optionGroups = this.options || [];\n var filtered = [];\n optionGroups.forEach(function (group) {\n var groupChildren = _this15.getOptionGroupChildren(group);\n var filteredItems = groupChildren.filter(function (item) {\n return filteredOptions.includes(item);\n });\n if (filteredItems.length > 0) filtered.push(_objectSpread(_objectSpread({}, group), {}, _defineProperty({}, typeof _this15.optionGroupChildren === 'string' ? _this15.optionGroupChildren : 'items', _toConsumableArray(filteredItems))));\n });\n return this.flatOptions(filtered);\n }\n return filteredOptions;\n }\n return options;\n },\n hasSelectedOption: function hasSelectedOption() {\n return isNotEmpty(this.modelValue);\n },\n label: function label() {\n var selectedOptionIndex = this.findSelectedOptionIndex();\n return selectedOptionIndex !== -1 ? this.getOptionLabel(this.visibleOptions[selectedOptionIndex]) : this.placeholder || 'p-emptylabel';\n },\n editableInputValue: function editableInputValue() {\n var selectedOptionIndex = this.findSelectedOptionIndex();\n return selectedOptionIndex !== -1 ? this.getOptionLabel(this.visibleOptions[selectedOptionIndex]) : this.modelValue || '';\n },\n equalityKey: function equalityKey() {\n return this.optionValue ? null : this.dataKey;\n },\n searchFields: function searchFields() {\n return this.filterFields || [this.optionLabel];\n },\n filterResultMessageText: function filterResultMessageText() {\n return isNotEmpty(this.visibleOptions) ? this.filterMessageText.replaceAll('{0}', this.visibleOptions.length) : this.emptyFilterMessageText;\n },\n filterMessageText: function filterMessageText() {\n return this.filterMessage || this.$primevue.config.locale.searchMessage || '';\n },\n emptyFilterMessageText: function emptyFilterMessageText() {\n return this.emptyFilterMessage || this.$primevue.config.locale.emptySearchMessage || this.$primevue.config.locale.emptyFilterMessage || '';\n },\n emptyMessageText: function emptyMessageText() {\n return this.emptyMessage || this.$primevue.config.locale.emptyMessage || '';\n },\n selectionMessageText: function selectionMessageText() {\n return this.selectionMessage || this.$primevue.config.locale.selectionMessage || '';\n },\n emptySelectionMessageText: function emptySelectionMessageText() {\n return this.emptySelectionMessage || this.$primevue.config.locale.emptySelectionMessage || '';\n },\n selectedMessageText: function selectedMessageText() {\n return this.hasSelectedOption ? this.selectionMessageText.replaceAll('{0}', '1') : this.emptySelectionMessageText;\n },\n focusedOptionId: function focusedOptionId() {\n return this.focusedOptionIndex !== -1 ? \"\".concat(this.id, \"_\").concat(this.focusedOptionIndex) : null;\n },\n ariaSetSize: function ariaSetSize() {\n var _this16 = this;\n return this.visibleOptions.filter(function (option) {\n return !_this16.isOptionGroup(option);\n }).length;\n },\n virtualScrollerDisabled: function virtualScrollerDisabled() {\n return !this.virtualScrollerOptions;\n }\n },\n directives: {\n ripple: Ripple\n },\n components: {\n InputText: InputText,\n VirtualScroller: VirtualScroller,\n Portal: Portal,\n InputIcon: InputIcon,\n IconField: IconField,\n TimesIcon: TimesIcon,\n ChevronDownIcon: ChevronDownIcon,\n SpinnerIcon: SpinnerIcon,\n SearchIcon: SearchIcon,\n CheckIcon: CheckIcon,\n BlankIcon: BlankIcon\n }\n};\n\nvar _hoisted_1 = [\"id\"];\nvar _hoisted_2 = [\"id\", \"value\", \"placeholder\", \"tabindex\", \"disabled\", \"aria-label\", \"aria-labelledby\", \"aria-expanded\", \"aria-controls\", \"aria-activedescendant\", \"aria-invalid\"];\nvar _hoisted_3 = [\"id\", \"tabindex\", \"aria-label\", \"aria-labelledby\", \"aria-expanded\", \"aria-controls\", \"aria-activedescendant\", \"aria-disabled\"];\nvar _hoisted_4 = [\"id\"];\nvar _hoisted_5 = [\"id\"];\nvar _hoisted_6 = [\"id\", \"aria-label\", \"aria-selected\", \"aria-disabled\", \"aria-setsize\", \"aria-posinset\", \"onClick\", \"onMousemove\", \"data-p-selected\", \"data-p-focused\", \"data-p-disabled\"];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n var _component_SpinnerIcon = resolveComponent(\"SpinnerIcon\");\n var _component_InputText = resolveComponent(\"InputText\");\n var _component_SearchIcon = resolveComponent(\"SearchIcon\");\n var _component_InputIcon = resolveComponent(\"InputIcon\");\n var _component_IconField = resolveComponent(\"IconField\");\n var _component_CheckIcon = resolveComponent(\"CheckIcon\");\n var _component_BlankIcon = resolveComponent(\"BlankIcon\");\n var _component_VirtualScroller = resolveComponent(\"VirtualScroller\");\n var _component_Portal = resolveComponent(\"Portal\");\n var _directive_ripple = resolveDirective(\"ripple\");\n return openBlock(), createElementBlock(\"div\", mergeProps({\n ref: \"container\",\n id: $data.id,\n \"class\": _ctx.cx('root'),\n onClick: _cache[11] || (_cache[11] = function () {\n return $options.onContainerClick && $options.onContainerClick.apply($options, arguments);\n })\n }, _ctx.ptmi('root')), [_ctx.editable ? (openBlock(), createElementBlock(\"input\", mergeProps({\n key: 0,\n ref: \"focusInput\",\n id: _ctx.labelId || _ctx.inputId,\n type: \"text\",\n \"class\": [_ctx.cx('label'), _ctx.inputClass, _ctx.labelClass],\n style: [_ctx.inputStyle, _ctx.labelStyle],\n value: $options.editableInputValue,\n placeholder: _ctx.placeholder,\n tabindex: !_ctx.disabled ? _ctx.tabindex : -1,\n disabled: _ctx.disabled,\n autocomplete: \"off\",\n role: \"combobox\",\n \"aria-label\": _ctx.ariaLabel,\n \"aria-labelledby\": _ctx.ariaLabelledby,\n \"aria-haspopup\": \"listbox\",\n \"aria-expanded\": $data.overlayVisible,\n \"aria-controls\": $data.id + '_list',\n \"aria-activedescendant\": $data.focused ? $options.focusedOptionId : undefined,\n \"aria-invalid\": _ctx.invalid || undefined,\n onFocus: _cache[0] || (_cache[0] = function () {\n return $options.onFocus && $options.onFocus.apply($options, arguments);\n }),\n onBlur: _cache[1] || (_cache[1] = function () {\n return $options.onBlur && $options.onBlur.apply($options, arguments);\n }),\n onKeydown: _cache[2] || (_cache[2] = function () {\n return $options.onKeyDown && $options.onKeyDown.apply($options, arguments);\n }),\n onInput: _cache[3] || (_cache[3] = function () {\n return $options.onEditableInput && $options.onEditableInput.apply($options, arguments);\n })\n }, _ctx.ptm('label')), null, 16, _hoisted_2)) : (openBlock(), createElementBlock(\"span\", mergeProps({\n key: 1,\n ref: \"focusInput\",\n id: _ctx.labelId || _ctx.inputId,\n \"class\": [_ctx.cx('label'), _ctx.inputClass, _ctx.labelClass],\n style: [_ctx.inputStyle, _ctx.labelStyle],\n tabindex: !_ctx.disabled ? _ctx.tabindex : -1,\n role: \"combobox\",\n \"aria-label\": _ctx.ariaLabel || ($options.label === 'p-emptylabel' ? undefined : $options.label),\n \"aria-labelledby\": _ctx.ariaLabelledby,\n \"aria-haspopup\": \"listbox\",\n \"aria-expanded\": $data.overlayVisible,\n \"aria-controls\": $data.id + '_list',\n \"aria-activedescendant\": $data.focused ? $options.focusedOptionId : undefined,\n \"aria-disabled\": _ctx.disabled,\n onFocus: _cache[4] || (_cache[4] = function () {\n return $options.onFocus && $options.onFocus.apply($options, arguments);\n }),\n onBlur: _cache[5] || (_cache[5] = function () {\n return $options.onBlur && $options.onBlur.apply($options, arguments);\n }),\n onKeydown: _cache[6] || (_cache[6] = function () {\n return $options.onKeyDown && $options.onKeyDown.apply($options, arguments);\n })\n }, _ctx.ptm('label')), [renderSlot(_ctx.$slots, \"value\", {\n value: _ctx.modelValue,\n placeholder: _ctx.placeholder\n }, function () {\n return [createTextVNode(toDisplayString($options.label === 'p-emptylabel' ? ' ' : $options.label || 'empty'), 1)];\n })], 16, _hoisted_3)), _ctx.showClear && _ctx.modelValue != null ? renderSlot(_ctx.$slots, \"clearicon\", {\n key: 2,\n \"class\": normalizeClass(_ctx.cx('clearIcon')),\n clearCallback: $options.onClearClick\n }, function () {\n return [(openBlock(), createBlock(resolveDynamicComponent(_ctx.clearIcon ? 'i' : 'TimesIcon'), mergeProps({\n ref: \"clearIcon\",\n \"class\": [_ctx.cx('clearIcon'), _ctx.clearIcon],\n onClick: $options.onClearClick\n }, _ctx.ptm('clearIcon'), {\n \"data-pc-section\": \"clearicon\"\n }), null, 16, [\"class\", \"onClick\"]))];\n }) : createCommentVNode(\"\", true), createElementVNode(\"div\", mergeProps({\n \"class\": _ctx.cx('dropdown')\n }, _ctx.ptm('dropdown')), [_ctx.loading ? renderSlot(_ctx.$slots, \"loadingicon\", {\n key: 0,\n \"class\": normalizeClass(_ctx.cx('loadingIcon'))\n }, function () {\n return [_ctx.loadingIcon ? (openBlock(), createElementBlock(\"span\", mergeProps({\n key: 0,\n \"class\": [_ctx.cx('loadingIcon'), 'pi-spin', _ctx.loadingIcon],\n \"aria-hidden\": \"true\"\n }, _ctx.ptm('loadingIcon')), null, 16)) : (openBlock(), createBlock(_component_SpinnerIcon, mergeProps({\n key: 1,\n \"class\": _ctx.cx('loadingIcon'),\n spin: \"\",\n \"aria-hidden\": \"true\"\n }, _ctx.ptm('loadingIcon')), null, 16, [\"class\"]))];\n }) : renderSlot(_ctx.$slots, \"dropdownicon\", {\n key: 1,\n \"class\": normalizeClass(_ctx.cx('dropdownIcon'))\n }, function () {\n return [(openBlock(), createBlock(resolveDynamicComponent(_ctx.dropdownIcon ? 'span' : 'ChevronDownIcon'), mergeProps({\n \"class\": [_ctx.cx('dropdownIcon'), _ctx.dropdownIcon],\n \"aria-hidden\": \"true\"\n }, _ctx.ptm('dropdownIcon')), null, 16, [\"class\"]))];\n })], 16), createVNode(_component_Portal, {\n appendTo: _ctx.appendTo\n }, {\n \"default\": withCtx(function () {\n return [createVNode(Transition, mergeProps({\n name: \"p-connected-overlay\",\n onEnter: $options.onOverlayEnter,\n onAfterEnter: $options.onOverlayAfterEnter,\n onLeave: $options.onOverlayLeave,\n onAfterLeave: $options.onOverlayAfterLeave\n }, _ctx.ptm('transition')), {\n \"default\": withCtx(function () {\n return [$data.overlayVisible ? (openBlock(), createElementBlock(\"div\", mergeProps({\n key: 0,\n ref: $options.overlayRef,\n \"class\": [_ctx.cx('overlay'), _ctx.panelClass, _ctx.overlayClass],\n style: [_ctx.panelStyle, _ctx.overlayStyle],\n onClick: _cache[9] || (_cache[9] = function () {\n return $options.onOverlayClick && $options.onOverlayClick.apply($options, arguments);\n }),\n onKeydown: _cache[10] || (_cache[10] = function () {\n return $options.onOverlayKeyDown && $options.onOverlayKeyDown.apply($options, arguments);\n })\n }, _ctx.ptm('overlay')), [createElementVNode(\"span\", mergeProps({\n ref: \"firstHiddenFocusableElementOnOverlay\",\n role: \"presentation\",\n \"aria-hidden\": \"true\",\n \"class\": \"p-hidden-accessible p-hidden-focusable\",\n tabindex: 0,\n onFocus: _cache[7] || (_cache[7] = function () {\n return $options.onFirstHiddenFocus && $options.onFirstHiddenFocus.apply($options, arguments);\n })\n }, _ctx.ptm('hiddenFirstFocusableEl'), {\n \"data-p-hidden-accessible\": true,\n \"data-p-hidden-focusable\": true\n }), null, 16), renderSlot(_ctx.$slots, \"header\", {\n value: _ctx.modelValue,\n options: $options.visibleOptions\n }), _ctx.filter ? (openBlock(), createElementBlock(\"div\", mergeProps({\n key: 0,\n \"class\": _ctx.cx('header')\n }, _ctx.ptm('header')), [createVNode(_component_IconField, mergeProps({\n unstyled: _ctx.unstyled\n }, _ctx.ptm('pcFilterContainer')), {\n \"default\": withCtx(function () {\n return [createVNode(_component_InputText, {\n ref: \"filterInput\",\n type: \"text\",\n value: $data.filterValue,\n onVnodeMounted: $options.onFilterUpdated,\n onVnodeUpdated: $options.onFilterUpdated,\n \"class\": normalizeClass(_ctx.cx('pcFilter')),\n placeholder: _ctx.filterPlaceholder,\n variant: _ctx.variant,\n unstyled: _ctx.unstyled,\n role: \"searchbox\",\n autocomplete: \"off\",\n \"aria-owns\": $data.id + '_list',\n \"aria-activedescendant\": $options.focusedOptionId,\n onKeydown: $options.onFilterKeyDown,\n onBlur: $options.onFilterBlur,\n onInput: $options.onFilterChange,\n pt: _ctx.ptm('pcFilter')\n }, null, 8, [\"value\", \"onVnodeMounted\", \"onVnodeUpdated\", \"class\", \"placeholder\", \"variant\", \"unstyled\", \"aria-owns\", \"aria-activedescendant\", \"onKeydown\", \"onBlur\", \"onInput\", \"pt\"]), createVNode(_component_InputIcon, mergeProps({\n unstyled: _ctx.unstyled\n }, _ctx.ptm('pcFilterIconContainer')), {\n \"default\": withCtx(function () {\n return [renderSlot(_ctx.$slots, \"filtericon\", {}, function () {\n return [_ctx.filterIcon ? (openBlock(), createElementBlock(\"span\", mergeProps({\n key: 0,\n \"class\": _ctx.filterIcon\n }, _ctx.ptm('filterIcon')), null, 16)) : (openBlock(), createBlock(_component_SearchIcon, normalizeProps(mergeProps({\n key: 1\n }, _ctx.ptm('filterIcon'))), null, 16))];\n })];\n }),\n _: 3\n }, 16, [\"unstyled\"])];\n }),\n _: 3\n }, 16, [\"unstyled\"]), createElementVNode(\"span\", mergeProps({\n role: \"status\",\n \"aria-live\": \"polite\",\n \"class\": \"p-hidden-accessible\"\n }, _ctx.ptm('hiddenFilterResult'), {\n \"data-p-hidden-accessible\": true\n }), toDisplayString($options.filterResultMessageText), 17)], 16)) : createCommentVNode(\"\", true), createElementVNode(\"div\", mergeProps({\n \"class\": _ctx.cx('listContainer'),\n style: {\n 'max-height': $options.virtualScrollerDisabled ? _ctx.scrollHeight : ''\n }\n }, _ctx.ptm('listContainer')), [createVNode(_component_VirtualScroller, mergeProps({\n ref: $options.virtualScrollerRef\n }, _ctx.virtualScrollerOptions, {\n items: $options.visibleOptions,\n style: {\n height: _ctx.scrollHeight\n },\n tabindex: -1,\n disabled: $options.virtualScrollerDisabled,\n pt: _ctx.ptm('virtualScroller')\n }), createSlots({\n content: withCtx(function (_ref) {\n var styleClass = _ref.styleClass,\n contentRef = _ref.contentRef,\n items = _ref.items,\n getItemOptions = _ref.getItemOptions,\n contentStyle = _ref.contentStyle,\n itemSize = _ref.itemSize;\n return [createElementVNode(\"ul\", mergeProps({\n ref: function ref(el) {\n return $options.listRef(el, contentRef);\n },\n id: $data.id + '_list',\n \"class\": [_ctx.cx('list'), styleClass],\n style: contentStyle,\n role: \"listbox\"\n }, _ctx.ptm('list')), [(openBlock(true), createElementBlock(Fragment, null, renderList(items, function (option, i) {\n return openBlock(), createElementBlock(Fragment, {\n key: $options.getOptionRenderKey(option, $options.getOptionIndex(i, getItemOptions))\n }, [$options.isOptionGroup(option) ? (openBlock(), createElementBlock(\"li\", mergeProps({\n key: 0,\n id: $data.id + '_' + $options.getOptionIndex(i, getItemOptions),\n style: {\n height: itemSize ? itemSize + 'px' : undefined\n },\n \"class\": _ctx.cx('optionGroup'),\n role: \"option\",\n ref_for: true\n }, _ctx.ptm('optionGroup')), [renderSlot(_ctx.$slots, \"optiongroup\", {\n option: option.optionGroup,\n index: $options.getOptionIndex(i, getItemOptions)\n }, function () {\n return [createElementVNode(\"span\", mergeProps({\n \"class\": _ctx.cx('optionGroupLabel'),\n ref_for: true\n }, _ctx.ptm('optionGroupLabel')), toDisplayString($options.getOptionGroupLabel(option.optionGroup)), 17)];\n })], 16, _hoisted_5)) : withDirectives((openBlock(), createElementBlock(\"li\", mergeProps({\n key: 1,\n id: $data.id + '_' + $options.getOptionIndex(i, getItemOptions),\n \"class\": _ctx.cx('option', {\n option: option,\n focusedOption: $options.getOptionIndex(i, getItemOptions)\n }),\n style: {\n height: itemSize ? itemSize + 'px' : undefined\n },\n role: \"option\",\n \"aria-label\": $options.getOptionLabel(option),\n \"aria-selected\": $options.isSelected(option),\n \"aria-disabled\": $options.isOptionDisabled(option),\n \"aria-setsize\": $options.ariaSetSize,\n \"aria-posinset\": $options.getAriaPosInset($options.getOptionIndex(i, getItemOptions)),\n onClick: function onClick($event) {\n return $options.onOptionSelect($event, option);\n },\n onMousemove: function onMousemove($event) {\n return $options.onOptionMouseMove($event, $options.getOptionIndex(i, getItemOptions));\n },\n \"data-p-selected\": $options.isSelected(option),\n \"data-p-focused\": $data.focusedOptionIndex === $options.getOptionIndex(i, getItemOptions),\n \"data-p-disabled\": $options.isOptionDisabled(option),\n ref_for: true\n }, $options.getPTItemOptions(option, getItemOptions, i, 'option')), [_ctx.checkmark ? (openBlock(), createElementBlock(Fragment, {\n key: 0\n }, [$options.isSelected(option) ? (openBlock(), createBlock(_component_CheckIcon, mergeProps({\n key: 0,\n \"class\": _ctx.cx('optionCheckIcon'),\n ref_for: true\n }, _ctx.ptm('optionCheckIcon')), null, 16, [\"class\"])) : (openBlock(), createBlock(_component_BlankIcon, mergeProps({\n key: 1,\n \"class\": _ctx.cx('optionBlankIcon'),\n ref_for: true\n }, _ctx.ptm('optionBlankIcon')), null, 16, [\"class\"]))], 64)) : createCommentVNode(\"\", true), renderSlot(_ctx.$slots, \"option\", {\n option: option,\n selected: $options.isSelected(option),\n index: $options.getOptionIndex(i, getItemOptions)\n }, function () {\n return [createElementVNode(\"span\", mergeProps({\n \"class\": _ctx.cx('optionLabel'),\n ref_for: true\n }, _ctx.ptm('optionLabel')), toDisplayString($options.getOptionLabel(option)), 17)];\n })], 16, _hoisted_6)), [[_directive_ripple]])], 64);\n }), 128)), $data.filterValue && (!items || items && items.length === 0) ? (openBlock(), createElementBlock(\"li\", mergeProps({\n key: 0,\n \"class\": _ctx.cx('emptyMessage'),\n role: \"option\"\n }, _ctx.ptm('emptyMessage'), {\n \"data-p-hidden-accessible\": true\n }), [renderSlot(_ctx.$slots, \"emptyfilter\", {}, function () {\n return [createTextVNode(toDisplayString($options.emptyFilterMessageText), 1)];\n })], 16)) : !_ctx.options || _ctx.options && _ctx.options.length === 0 ? (openBlock(), createElementBlock(\"li\", mergeProps({\n key: 1,\n \"class\": _ctx.cx('emptyMessage'),\n role: \"option\"\n }, _ctx.ptm('emptyMessage'), {\n \"data-p-hidden-accessible\": true\n }), [renderSlot(_ctx.$slots, \"empty\", {}, function () {\n return [createTextVNode(toDisplayString($options.emptyMessageText), 1)];\n })], 16)) : createCommentVNode(\"\", true)], 16, _hoisted_4)];\n }),\n _: 2\n }, [_ctx.$slots.loader ? {\n name: \"loader\",\n fn: withCtx(function (_ref2) {\n var options = _ref2.options;\n return [renderSlot(_ctx.$slots, \"loader\", {\n options: options\n })];\n }),\n key: \"0\"\n } : undefined]), 1040, [\"items\", \"style\", \"disabled\", \"pt\"])], 16), renderSlot(_ctx.$slots, \"footer\", {\n value: _ctx.modelValue,\n options: $options.visibleOptions\n }), !_ctx.options || _ctx.options && _ctx.options.length === 0 ? (openBlock(), createElementBlock(\"span\", mergeProps({\n key: 1,\n role: \"status\",\n \"aria-live\": \"polite\",\n \"class\": \"p-hidden-accessible\"\n }, _ctx.ptm('hiddenEmptyMessage'), {\n \"data-p-hidden-accessible\": true\n }), toDisplayString($options.emptyMessageText), 17)) : createCommentVNode(\"\", true), createElementVNode(\"span\", mergeProps({\n role: \"status\",\n \"aria-live\": \"polite\",\n \"class\": \"p-hidden-accessible\"\n }, _ctx.ptm('hiddenSelectedMessage'), {\n \"data-p-hidden-accessible\": true\n }), toDisplayString($options.selectedMessageText), 17), createElementVNode(\"span\", mergeProps({\n ref: \"lastHiddenFocusableElementOnOverlay\",\n role: \"presentation\",\n \"aria-hidden\": \"true\",\n \"class\": \"p-hidden-accessible p-hidden-focusable\",\n tabindex: 0,\n onFocus: _cache[8] || (_cache[8] = function () {\n return $options.onLastHiddenFocus && $options.onLastHiddenFocus.apply($options, arguments);\n })\n }, _ctx.ptm('hiddenLastFocusableEl'), {\n \"data-p-hidden-accessible\": true,\n \"data-p-hidden-focusable\": true\n }), null, 16)], 16)) : createCommentVNode(\"\", true)];\n }),\n _: 3\n }, 16, [\"onEnter\", \"onAfterEnter\", \"onLeave\", \"onAfterLeave\"])];\n }),\n _: 3\n }, 8, [\"appendTo\"])], 16, _hoisted_1);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseStyle from '@primevue/core/base/style';\n\nvar theme = function theme(_ref) {\n var dt = _ref.dt;\n return \"\\n.p-toggleswitch {\\n display: inline-block;\\n width: \".concat(dt('toggleswitch.width'), \";\\n height: \").concat(dt('toggleswitch.height'), \";\\n}\\n\\n.p-toggleswitch-input {\\n cursor: pointer;\\n appearance: none;\\n position: absolute;\\n top: 0;\\n left: 0;\\n width: 100%;\\n height: 100%;\\n padding: 0;\\n margin: 0;\\n opacity: 0;\\n z-index: 1;\\n outline: 0 none;\\n border-radius: \").concat(dt('toggleswitch.border.radius'), \";\\n}\\n\\n.p-toggleswitch-slider {\\n display: inline-block;\\n cursor: pointer;\\n width: 100%;\\n height: 100%;\\n border-width: \").concat(dt('toggleswitch.border.width'), \";\\n border-style: solid;\\n border-color: \").concat(dt('toggleswitch.border.color'), \";\\n background: \").concat(dt('toggleswitch.background'), \";\\n transition: background \").concat(dt('toggleswitch.transition.duration'), \", color \").concat(dt('toggleswitch.transition.duration'), \", border-color \").concat(dt('toggleswitch.transition.duration'), \", outline-color \").concat(dt('toggleswitch.transition.duration'), \", box-shadow \").concat(dt('toggleswitch.transition.duration'), \";\\n border-radius: \").concat(dt('toggleswitch.border.radius'), \";\\n outline-color: transparent;\\n box-shadow: \").concat(dt('toggleswitch.shadow'), \";\\n}\\n\\n.p-toggleswitch-slider:before {\\n position: absolute;\\n content: \\\"\\\";\\n top: 50%;\\n background: \").concat(dt('toggleswitch.handle.background'), \";\\n width: \").concat(dt('toggleswitch.handle.size'), \";\\n height: \").concat(dt('toggleswitch.handle.size'), \";\\n left: \").concat(dt('toggleswitch.gap'), \";\\n margin-top: calc(-1 * calc(\").concat(dt('toggleswitch.handle.size'), \" / 2));\\n border-radius: \").concat(dt('toggleswitch.handle.border.radius'), \";\\n transition: background \").concat(dt('toggleswitch.transition.duration'), \", left \").concat(dt('toggleswitch.slide.duration'), \";\\n}\\n\\n.p-toggleswitch.p-toggleswitch-checked .p-toggleswitch-slider {\\n background: \").concat(dt('toggleswitch.checked.background'), \";\\n border-color: \").concat(dt('toggleswitch.checked.border.color'), \";\\n}\\n\\n.p-toggleswitch.p-toggleswitch-checked .p-toggleswitch-slider:before {\\n background: \").concat(dt('toggleswitch.handle.checked.background'), \";\\n left: calc(\").concat(dt('toggleswitch.width'), \" - calc(\").concat(dt('toggleswitch.handle.size'), \" + \").concat(dt('toggleswitch.gap'), \"));\\n}\\n\\n.p-toggleswitch:not(.p-disabled):has(.p-toggleswitch-input:hover) .p-toggleswitch-slider {\\n background: \").concat(dt('toggleswitch.hover.background'), \";\\n border-color: \").concat(dt('toggleswitch.hover.border.color'), \";\\n}\\n\\n.p-toggleswitch:not(.p-disabled):has(.p-toggleswitch-input:hover) .p-toggleswitch-slider:before {\\n background: \").concat(dt('toggleswitch.handle.hover.background'), \";\\n}\\n\\n.p-toggleswitch:not(.p-disabled):has(.p-toggleswitch-input:hover).p-toggleswitch-checked .p-toggleswitch-slider {\\n background: \").concat(dt('toggleswitch.checked.hover.background'), \";\\n border-color: \").concat(dt('toggleswitch.checked.hover.border.color'), \";\\n}\\n\\n.p-toggleswitch:not(.p-disabled):has(.p-toggleswitch-input:hover).p-toggleswitch-checked .p-toggleswitch-slider:before {\\n background: \").concat(dt('toggleswitch.handle.checked.hover.background'), \";\\n}\\n\\n.p-toggleswitch:not(.p-disabled):has(.p-toggleswitch-input:focus-visible) .p-toggleswitch-slider {\\n box-shadow: \").concat(dt('toggleswitch.focus.ring.shadow'), \";\\n outline: \").concat(dt('toggleswitch.focus.ring.width'), \" \").concat(dt('toggleswitch.focus.ring.style'), \" \").concat(dt('toggleswitch.focus.ring.color'), \";\\n outline-offset: \").concat(dt('toggleswitch.focus.ring.offset'), \";\\n}\\n\\n.p-toggleswitch.p-invalid > .p-toggleswitch-slider {\\n border-color: \").concat(dt('toggleswitch.invalid.border.color'), \";\\n}\\n\\n.p-toggleswitch.p-disabled {\\n opacity: 1;\\n}\\n\\n.p-toggleswitch.p-disabled .p-toggleswitch-slider {\\n background: \").concat(dt('toggleswitch.disabled.background'), \";\\n}\\n\\n.p-toggleswitch.p-disabled .p-toggleswitch-slider:before {\\n background: \").concat(dt('toggleswitch.handle.disabled.background'), \";\\n}\\n\");\n};\nvar inlineStyles = {\n root: {\n position: 'relative'\n }\n};\nvar classes = {\n root: function root(_ref2) {\n var instance = _ref2.instance,\n props = _ref2.props;\n return ['p-toggleswitch p-component', {\n 'p-toggleswitch-checked': instance.checked,\n 'p-disabled': props.disabled,\n 'p-invalid': props.invalid\n }];\n },\n input: 'p-toggleswitch-input',\n slider: 'p-toggleswitch-slider'\n};\nvar ToggleSwitchStyle = BaseStyle.extend({\n name: 'toggleswitch',\n theme: theme,\n classes: classes,\n inlineStyles: inlineStyles\n});\n\nexport { ToggleSwitchStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseComponent from '@primevue/core/basecomponent';\nimport ToggleSwitchStyle from 'primevue/toggleswitch/style';\nimport { openBlock, createElementBlock, mergeProps, createElementVNode } from 'vue';\n\nvar script$1 = {\n name: 'BaseToggleSwitch',\n \"extends\": BaseComponent,\n props: {\n modelValue: {\n type: null,\n \"default\": false\n },\n trueValue: {\n type: null,\n \"default\": true\n },\n falseValue: {\n type: null,\n \"default\": false\n },\n invalid: {\n type: Boolean,\n \"default\": false\n },\n disabled: {\n type: Boolean,\n \"default\": false\n },\n readonly: {\n type: Boolean,\n \"default\": false\n },\n tabindex: {\n type: Number,\n \"default\": null\n },\n inputId: {\n type: String,\n \"default\": null\n },\n inputClass: {\n type: [String, Object],\n \"default\": null\n },\n inputStyle: {\n type: Object,\n \"default\": null\n },\n ariaLabelledby: {\n type: String,\n \"default\": null\n },\n ariaLabel: {\n type: String,\n \"default\": null\n }\n },\n style: ToggleSwitchStyle,\n provide: function provide() {\n return {\n $pcToggleSwitch: this,\n $parentInstance: this\n };\n }\n};\n\nvar script = {\n name: 'ToggleSwitch',\n \"extends\": script$1,\n inheritAttrs: false,\n emits: ['update:modelValue', 'change', 'focus', 'blur'],\n methods: {\n getPTOptions: function getPTOptions(key) {\n var _ptm = key === 'root' ? this.ptmi : this.ptm;\n return _ptm(key, {\n context: {\n checked: this.checked,\n disabled: this.disabled\n }\n });\n },\n onChange: function onChange(event) {\n if (!this.disabled && !this.readonly) {\n var newValue = this.checked ? this.falseValue : this.trueValue;\n this.$emit('update:modelValue', newValue);\n this.$emit('change', event);\n }\n },\n onFocus: function onFocus(event) {\n this.$emit('focus', event);\n },\n onBlur: function onBlur(event) {\n this.$emit('blur', event);\n }\n },\n computed: {\n checked: function checked() {\n return this.modelValue === this.trueValue;\n }\n }\n};\n\nvar _hoisted_1 = [\"data-p-checked\", \"data-p-disabled\"];\nvar _hoisted_2 = [\"id\", \"checked\", \"tabindex\", \"disabled\", \"readonly\", \"aria-checked\", \"aria-labelledby\", \"aria-label\", \"aria-invalid\"];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"div\", mergeProps({\n \"class\": _ctx.cx('root'),\n style: _ctx.sx('root')\n }, $options.getPTOptions('root'), {\n \"data-p-checked\": $options.checked,\n \"data-p-disabled\": _ctx.disabled\n }), [createElementVNode(\"input\", mergeProps({\n id: _ctx.inputId,\n type: \"checkbox\",\n role: \"switch\",\n \"class\": [_ctx.cx('input'), _ctx.inputClass],\n style: _ctx.inputStyle,\n checked: $options.checked,\n tabindex: _ctx.tabindex,\n disabled: _ctx.disabled,\n readonly: _ctx.readonly,\n \"aria-checked\": $options.checked,\n \"aria-labelledby\": _ctx.ariaLabelledby,\n \"aria-label\": _ctx.ariaLabel,\n \"aria-invalid\": _ctx.invalid || undefined,\n onFocus: _cache[0] || (_cache[0] = function () {\n return $options.onFocus && $options.onFocus.apply($options, arguments);\n }),\n onBlur: _cache[1] || (_cache[1] = function () {\n return $options.onBlur && $options.onBlur.apply($options, arguments);\n }),\n onChange: _cache[2] || (_cache[2] = function () {\n return $options.onChange && $options.onChange.apply($options, arguments);\n })\n }, $options.getPTOptions('input')), null, 16, _hoisted_2), createElementVNode(\"span\", mergeProps({\n \"class\": _ctx.cx('slider')\n }, $options.getPTOptions('slider')), null, 16)], 16, _hoisted_1);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","\r\n \r\n\r\n\r\n\r\n","import BaseStyle from '@primevue/core/base/style';\n\nvar theme = function theme(_ref) {\n var dt = _ref.dt;\n return \"\\n.p-slider {\\n position: relative;\\n background: \".concat(dt('slider.track.background'), \";\\n border-radius: \").concat(dt('slider.border.radius'), \";\\n}\\n\\n.p-slider-handle {\\n cursor: grab;\\n touch-action: none;\\n display: flex;\\n justify-content: center;\\n align-items: center;\\n height: \").concat(dt('slider.handle.height'), \";\\n width: \").concat(dt('slider.handle.width'), \";\\n background: \").concat(dt('slider.handle.background'), \";\\n border-radius: \").concat(dt('slider.handle.border.radius'), \";\\n transition: background \").concat(dt('slider.transition.duration'), \", color \").concat(dt('slider.transition.duration'), \", border-color \").concat(dt('slider.transition.duration'), \", box-shadow \").concat(dt('slider.transition.duration'), \", outline-color \").concat(dt('slider.transition.duration'), \";\\n outline-color: transparent;\\n}\\n\\n.p-slider-handle::before {\\n content: \\\"\\\";\\n width: \").concat(dt('slider.handle.content.width'), \";\\n height: \").concat(dt('slider.handle.content.height'), \";\\n display: block;\\n background: \").concat(dt('slider.handle.content.background'), \";\\n border-radius: \").concat(dt('slider.handle.content.border.radius'), \";\\n box-shadow: \").concat(dt('slider.handle.content.shadow'), \";\\n transition: background \").concat(dt('slider.transition.duration'), \";\\n}\\n\\n.p-slider:not(.p-disabled) .p-slider-handle:hover {\\n background: \").concat(dt('slider.handle.hover.background'), \";\\n}\\n\\n.p-slider:not(.p-disabled) .p-slider-handle:hover::before {\\n background: \").concat(dt('slider.handle.content.hover.background'), \";\\n}\\n\\n.p-slider-handle:focus-visible {\\n border-color: \").concat(dt('slider.handle.focus.border.color'), \";\\n box-shadow: \").concat(dt('slider.handle.focus.ring.shadow'), \";\\n outline: \").concat(dt('slider.handle.focus.ring.width'), \" \").concat(dt('slider.handle.focus.ring.style'), \" \").concat(dt('slider.handle.focus.ring.color'), \";\\n outline-offset: \").concat(dt('slider.handle.focus.ring.offset'), \";\\n}\\n\\n.p-slider-range {\\n display: block;\\n background: \").concat(dt('slider.range.background'), \";\\n border-radius: \").concat(dt('slider.border.radius'), \";\\n}\\n\\n.p-slider.p-slider-horizontal {\\n height: \").concat(dt('slider.track.size'), \";\\n}\\n\\n.p-slider-horizontal .p-slider-range {\\n top: 0;\\n left: 0;\\n height: 100%;\\n}\\n\\n.p-slider-horizontal .p-slider-handle {\\n top: 50%;\\n margin-top: calc(-1 * calc(\").concat(dt('slider.handle.height'), \" / 2));\\n margin-left: calc(-1 * calc(\").concat(dt('slider.handle.width'), \" / 2));\\n}\\n\\n.p-slider-vertical {\\n min-height: 100px;\\n width: \").concat(dt('slider.track.size'), \";\\n}\\n\\n.p-slider-vertical .p-slider-handle {\\n left: 50%;\\n margin-left: calc(-1 * calc(\").concat(dt('slider.handle.width'), \" / 2));\\n margin-bottom: calc(-1 * calc(\").concat(dt('slider.handle.height'), \" / 2));\\n}\\n\\n.p-slider-vertical .p-slider-range {\\n bottom: 0;\\n left: 0;\\n width: 100%;\\n}\\n\");\n};\nvar inlineStyles = {\n handle: {\n position: 'absolute'\n },\n range: {\n position: 'absolute'\n }\n};\nvar classes = {\n root: function root(_ref2) {\n var props = _ref2.props;\n return ['p-slider p-component', {\n 'p-disabled': props.disabled,\n 'p-slider-horizontal': props.orientation === 'horizontal',\n 'p-slider-vertical': props.orientation === 'vertical'\n }];\n },\n range: 'p-slider-range',\n handle: 'p-slider-handle'\n};\nvar SliderStyle = BaseStyle.extend({\n name: 'slider',\n theme: theme,\n classes: classes,\n inlineStyles: inlineStyles\n});\n\nexport { SliderStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import { getWindowScrollLeft, getWindowScrollTop, getAttribute } from '@primeuix/utils/dom';\nimport BaseComponent from '@primevue/core/basecomponent';\nimport SliderStyle from 'primevue/slider/style';\nimport { openBlock, createElementBlock, mergeProps, createElementVNode, createCommentVNode } from 'vue';\n\nvar script$1 = {\n name: 'BaseSlider',\n \"extends\": BaseComponent,\n props: {\n modelValue: [Number, Array],\n min: {\n type: Number,\n \"default\": 0\n },\n max: {\n type: Number,\n \"default\": 100\n },\n orientation: {\n type: String,\n \"default\": 'horizontal'\n },\n step: {\n type: Number,\n \"default\": null\n },\n range: {\n type: Boolean,\n \"default\": false\n },\n disabled: {\n type: Boolean,\n \"default\": false\n },\n tabindex: {\n type: Number,\n \"default\": 0\n },\n ariaLabelledby: {\n type: String,\n \"default\": null\n },\n ariaLabel: {\n type: String,\n \"default\": null\n }\n },\n style: SliderStyle,\n provide: function provide() {\n return {\n $pcSlider: this,\n $parentInstance: this\n };\n }\n};\n\nfunction _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _unsupportedIterableToArray(r, a) { if (r) { if (\"string\" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return \"Object\" === t && r.constructor && (t = r.constructor.name), \"Map\" === t || \"Set\" === t ? Array.from(r) : \"Arguments\" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }\nfunction _iterableToArray(r) { if (\"undefined\" != typeof Symbol && null != r[Symbol.iterator] || null != r[\"@@iterator\"]) return Array.from(r); }\nfunction _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }\nfunction _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }\nvar script = {\n name: 'Slider',\n \"extends\": script$1,\n inheritAttrs: false,\n emits: ['update:modelValue', 'change', 'slideend'],\n dragging: false,\n handleIndex: null,\n initX: null,\n initY: null,\n barWidth: null,\n barHeight: null,\n dragListener: null,\n dragEndListener: null,\n beforeUnmount: function beforeUnmount() {\n this.unbindDragListeners();\n },\n methods: {\n updateDomData: function updateDomData() {\n var rect = this.$el.getBoundingClientRect();\n this.initX = rect.left + getWindowScrollLeft();\n this.initY = rect.top + getWindowScrollTop();\n this.barWidth = this.$el.offsetWidth;\n this.barHeight = this.$el.offsetHeight;\n },\n setValue: function setValue(event) {\n var handleValue;\n var pageX = event.touches ? event.touches[0].pageX : event.pageX;\n var pageY = event.touches ? event.touches[0].pageY : event.pageY;\n if (this.orientation === 'horizontal') handleValue = (pageX - this.initX) * 100 / this.barWidth;else handleValue = (this.initY + this.barHeight - pageY) * 100 / this.barHeight;\n var newValue = (this.max - this.min) * (handleValue / 100) + this.min;\n if (this.step) {\n var oldValue = this.range ? this.value[this.handleIndex] : this.value;\n var diff = newValue - oldValue;\n if (diff < 0) newValue = oldValue + Math.ceil(newValue / this.step - oldValue / this.step) * this.step;else if (diff > 0) newValue = oldValue + Math.floor(newValue / this.step - oldValue / this.step) * this.step;\n } else {\n newValue = Math.floor(newValue);\n }\n this.updateModel(event, newValue);\n },\n updateModel: function updateModel(event, value) {\n var newValue = parseFloat(value.toFixed(10));\n var modelValue;\n if (this.range) {\n modelValue = this.value ? _toConsumableArray(this.value) : [];\n if (this.handleIndex == 0) {\n if (newValue < this.min) newValue = this.min;else if (newValue >= this.max) newValue = this.max;\n modelValue[0] = newValue;\n } else {\n if (newValue > this.max) newValue = this.max;else if (newValue <= this.min) newValue = this.min;\n modelValue[1] = newValue;\n }\n } else {\n if (newValue < this.min) newValue = this.min;else if (newValue > this.max) newValue = this.max;\n modelValue = newValue;\n }\n this.$emit('update:modelValue', modelValue);\n this.$emit('change', modelValue);\n },\n onDragStart: function onDragStart(event, index) {\n if (this.disabled) {\n return;\n }\n this.$el.setAttribute('data-p-sliding', true);\n this.dragging = true;\n this.updateDomData();\n if (this.range && this.value[0] === this.max) {\n this.handleIndex = 0;\n } else {\n this.handleIndex = index;\n }\n event.currentTarget.focus();\n event.preventDefault();\n },\n onDrag: function onDrag(event) {\n if (this.dragging) {\n this.setValue(event);\n event.preventDefault();\n }\n },\n onDragEnd: function onDragEnd(event) {\n if (this.dragging) {\n this.dragging = false;\n this.$el.setAttribute('data-p-sliding', false);\n this.$emit('slideend', {\n originalEvent: event,\n value: this.value\n });\n }\n },\n onBarClick: function onBarClick(event) {\n if (this.disabled) {\n return;\n }\n if (getAttribute(event.target, 'data-pc-section') !== 'handle') {\n this.updateDomData();\n this.setValue(event);\n }\n },\n onMouseDown: function onMouseDown(event, index) {\n this.bindDragListeners();\n this.onDragStart(event, index);\n },\n onKeyDown: function onKeyDown(event, index) {\n this.handleIndex = index;\n switch (event.code) {\n case 'ArrowDown':\n case 'ArrowLeft':\n this.decrementValue(event, index);\n event.preventDefault();\n break;\n case 'ArrowUp':\n case 'ArrowRight':\n this.incrementValue(event, index);\n event.preventDefault();\n break;\n case 'PageDown':\n this.decrementValue(event, index, true);\n event.preventDefault();\n break;\n case 'PageUp':\n this.incrementValue(event, index, true);\n event.preventDefault();\n break;\n case 'Home':\n this.updateModel(event, this.min);\n event.preventDefault();\n break;\n case 'End':\n this.updateModel(event, this.max);\n event.preventDefault();\n break;\n }\n },\n decrementValue: function decrementValue(event, index) {\n var pageKey = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;\n var newValue;\n if (this.range) {\n if (this.step) newValue = this.value[index] - this.step;else newValue = this.value[index] - 1;\n } else {\n if (this.step) newValue = this.value - this.step;else if (!this.step && pageKey) newValue = this.value - 10;else newValue = this.value - 1;\n }\n this.updateModel(event, newValue);\n event.preventDefault();\n },\n incrementValue: function incrementValue(event, index) {\n var pageKey = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;\n var newValue;\n if (this.range) {\n if (this.step) newValue = this.value[index] + this.step;else newValue = this.value[index] + 1;\n } else {\n if (this.step) newValue = this.value + this.step;else if (!this.step && pageKey) newValue = this.value + 10;else newValue = this.value + 1;\n }\n this.updateModel(event, newValue);\n event.preventDefault();\n },\n bindDragListeners: function bindDragListeners() {\n if (!this.dragListener) {\n this.dragListener = this.onDrag.bind(this);\n document.addEventListener('mousemove', this.dragListener);\n }\n if (!this.dragEndListener) {\n this.dragEndListener = this.onDragEnd.bind(this);\n document.addEventListener('mouseup', this.dragEndListener);\n }\n },\n unbindDragListeners: function unbindDragListeners() {\n if (this.dragListener) {\n document.removeEventListener('mousemove', this.dragListener);\n this.dragListener = null;\n }\n if (this.dragEndListener) {\n document.removeEventListener('mouseup', this.dragEndListener);\n this.dragEndListener = null;\n }\n }\n },\n computed: {\n value: function value() {\n var _this$modelValue3;\n if (this.range) {\n var _this$modelValue$, _this$modelValue, _this$modelValue$2, _this$modelValue2;\n return [(_this$modelValue$ = (_this$modelValue = this.modelValue) === null || _this$modelValue === void 0 ? void 0 : _this$modelValue[0]) !== null && _this$modelValue$ !== void 0 ? _this$modelValue$ : this.min, (_this$modelValue$2 = (_this$modelValue2 = this.modelValue) === null || _this$modelValue2 === void 0 ? void 0 : _this$modelValue2[1]) !== null && _this$modelValue$2 !== void 0 ? _this$modelValue$2 : this.max];\n }\n return (_this$modelValue3 = this.modelValue) !== null && _this$modelValue3 !== void 0 ? _this$modelValue3 : this.min;\n },\n horizontal: function horizontal() {\n return this.orientation === 'horizontal';\n },\n vertical: function vertical() {\n return this.orientation === 'vertical';\n },\n rangeStyle: function rangeStyle() {\n if (this.range) {\n var rangeSliderWidth = this.rangeEndPosition > this.rangeStartPosition ? this.rangeEndPosition - this.rangeStartPosition : this.rangeStartPosition - this.rangeEndPosition;\n var rangeSliderPosition = this.rangeEndPosition > this.rangeStartPosition ? this.rangeStartPosition : this.rangeEndPosition;\n if (this.horizontal) return {\n left: rangeSliderPosition + '%',\n width: rangeSliderWidth + '%'\n };else return {\n bottom: rangeSliderPosition + '%',\n height: rangeSliderWidth + '%'\n };\n } else {\n if (this.horizontal) return {\n width: this.handlePosition + '%'\n };else return {\n height: this.handlePosition + '%'\n };\n }\n },\n handleStyle: function handleStyle() {\n if (this.horizontal) return {\n left: this.handlePosition + '%'\n };else return {\n bottom: this.handlePosition + '%'\n };\n },\n handlePosition: function handlePosition() {\n if (this.value < this.min) return 0;else if (this.value > this.max) return 100;else return (this.value - this.min) * 100 / (this.max - this.min);\n },\n rangeStartPosition: function rangeStartPosition() {\n if (this.value && this.value[0]) return (this.value[0] < this.min ? 0 : this.value[0] - this.min) * 100 / (this.max - this.min);else return 0;\n },\n rangeEndPosition: function rangeEndPosition() {\n if (this.value && this.value.length === 2) return (this.value[1] > this.max ? 100 : this.value[1] - this.min) * 100 / (this.max - this.min);else return 100;\n },\n rangeStartHandleStyle: function rangeStartHandleStyle() {\n if (this.horizontal) return {\n left: this.rangeStartPosition + '%'\n };else return {\n bottom: this.rangeStartPosition + '%'\n };\n },\n rangeEndHandleStyle: function rangeEndHandleStyle() {\n if (this.horizontal) return {\n left: this.rangeEndPosition + '%'\n };else return {\n bottom: this.rangeEndPosition + '%'\n };\n }\n }\n};\n\nvar _hoisted_1 = [\"tabindex\", \"aria-valuemin\", \"aria-valuenow\", \"aria-valuemax\", \"aria-labelledby\", \"aria-label\", \"aria-orientation\"];\nvar _hoisted_2 = [\"tabindex\", \"aria-valuemin\", \"aria-valuenow\", \"aria-valuemax\", \"aria-labelledby\", \"aria-label\", \"aria-orientation\"];\nvar _hoisted_3 = [\"tabindex\", \"aria-valuemin\", \"aria-valuenow\", \"aria-valuemax\", \"aria-labelledby\", \"aria-label\", \"aria-orientation\"];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"div\", mergeProps({\n \"class\": _ctx.cx('root'),\n onClick: _cache[15] || (_cache[15] = function () {\n return $options.onBarClick && $options.onBarClick.apply($options, arguments);\n })\n }, _ctx.ptmi('root'), {\n \"data-p-sliding\": false\n }), [createElementVNode(\"span\", mergeProps({\n \"class\": _ctx.cx('range'),\n style: [_ctx.sx('range'), $options.rangeStyle]\n }, _ctx.ptm('range')), null, 16), !_ctx.range ? (openBlock(), createElementBlock(\"span\", mergeProps({\n key: 0,\n \"class\": _ctx.cx('handle'),\n style: [_ctx.sx('handle'), $options.handleStyle],\n onTouchstartPassive: _cache[0] || (_cache[0] = function ($event) {\n return $options.onDragStart($event);\n }),\n onTouchmovePassive: _cache[1] || (_cache[1] = function ($event) {\n return $options.onDrag($event);\n }),\n onTouchend: _cache[2] || (_cache[2] = function ($event) {\n return $options.onDragEnd($event);\n }),\n onMousedown: _cache[3] || (_cache[3] = function ($event) {\n return $options.onMouseDown($event);\n }),\n onKeydown: _cache[4] || (_cache[4] = function ($event) {\n return $options.onKeyDown($event);\n }),\n tabindex: _ctx.tabindex,\n role: \"slider\",\n \"aria-valuemin\": _ctx.min,\n \"aria-valuenow\": _ctx.modelValue,\n \"aria-valuemax\": _ctx.max,\n \"aria-labelledby\": _ctx.ariaLabelledby,\n \"aria-label\": _ctx.ariaLabel,\n \"aria-orientation\": _ctx.orientation\n }, _ctx.ptm('handle')), null, 16, _hoisted_1)) : createCommentVNode(\"\", true), _ctx.range ? (openBlock(), createElementBlock(\"span\", mergeProps({\n key: 1,\n \"class\": _ctx.cx('handle'),\n style: [_ctx.sx('handle'), $options.rangeStartHandleStyle],\n onTouchstartPassive: _cache[5] || (_cache[5] = function ($event) {\n return $options.onDragStart($event, 0);\n }),\n onTouchmovePassive: _cache[6] || (_cache[6] = function ($event) {\n return $options.onDrag($event);\n }),\n onTouchend: _cache[7] || (_cache[7] = function ($event) {\n return $options.onDragEnd($event);\n }),\n onMousedown: _cache[8] || (_cache[8] = function ($event) {\n return $options.onMouseDown($event, 0);\n }),\n onKeydown: _cache[9] || (_cache[9] = function ($event) {\n return $options.onKeyDown($event, 0);\n }),\n tabindex: _ctx.tabindex,\n role: \"slider\",\n \"aria-valuemin\": _ctx.min,\n \"aria-valuenow\": _ctx.modelValue ? _ctx.modelValue[0] : null,\n \"aria-valuemax\": _ctx.max,\n \"aria-labelledby\": _ctx.ariaLabelledby,\n \"aria-label\": _ctx.ariaLabel,\n \"aria-orientation\": _ctx.orientation\n }, _ctx.ptm('startHandler')), null, 16, _hoisted_2)) : createCommentVNode(\"\", true), _ctx.range ? (openBlock(), createElementBlock(\"span\", mergeProps({\n key: 2,\n \"class\": _ctx.cx('handle'),\n style: [_ctx.sx('handle'), $options.rangeEndHandleStyle],\n onTouchstartPassive: _cache[10] || (_cache[10] = function ($event) {\n return $options.onDragStart($event, 1);\n }),\n onTouchmovePassive: _cache[11] || (_cache[11] = function ($event) {\n return $options.onDrag($event);\n }),\n onTouchend: _cache[12] || (_cache[12] = function ($event) {\n return $options.onDragEnd($event);\n }),\n onMousedown: _cache[13] || (_cache[13] = function ($event) {\n return $options.onMouseDown($event, 1);\n }),\n onKeydown: _cache[14] || (_cache[14] = function ($event) {\n return $options.onKeyDown($event, 1);\n }),\n tabindex: _ctx.tabindex,\n role: \"slider\",\n \"aria-valuemin\": _ctx.min,\n \"aria-valuenow\": _ctx.modelValue ? _ctx.modelValue[1] : null,\n \"aria-valuemax\": _ctx.max,\n \"aria-labelledby\": _ctx.ariaLabelledby,\n \"aria-label\": _ctx.ariaLabel,\n \"aria-orientation\": _ctx.orientation\n }, _ctx.ptm('endHandler')), null, 16, _hoisted_3)) : createCommentVNode(\"\", true)], 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","\r\n \r\n \r\n \r\n \r\n\r\n\r\n\r\n\r\n\r\n","export function formatCamelCase(str: string): string {\r\n // Check if the string is camel case\r\n const isCamelCase = /^([A-Z][a-z]*)+$/.test(str)\r\n\r\n if (!isCamelCase) {\r\n return str // Return original string if not camel case\r\n }\r\n\r\n // Split the string into words, keeping acronyms together\r\n const words = str.split(/(?=[A-Z][a-z])|\\d+/)\r\n\r\n // Process each word\r\n const processedWords = words.map((word) => {\r\n // If the word is all uppercase and longer than one character, it's likely an acronym\r\n if (word.length > 1 && word === word.toUpperCase()) {\r\n return word // Keep acronyms as is\r\n }\r\n // For other words, ensure the first letter is capitalized\r\n return word.charAt(0).toUpperCase() + word.slice(1)\r\n })\r\n\r\n // Join the words with spaces\r\n return processedWords.join(' ')\r\n}\r\n","\r\n \r\n \r\n {{ formatCamelCase(group.label) }}\r\n \r\n \r\n {{ setting.name }}\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n\r\n\r\n\r\n\r\n\r\n","\r\n \r\n \r\n \r\n \r\n\r\n\r\n\r\n\r\n\r\n","import BaseStyle from '@primevue/core/base/style';\n\nvar theme = function theme(_ref) {\n var dt = _ref.dt;\n return \"\\n.p-card {\\n background: \".concat(dt('card.background'), \";\\n color: \").concat(dt('card.color'), \";\\n box-shadow: \").concat(dt('card.shadow'), \";\\n border-radius: \").concat(dt('card.border.radius'), \";\\n display: flex;\\n flex-direction: column;\\n}\\n\\n.p-card-caption {\\n display: flex;\\n flex-direction: column;\\n gap: \").concat(dt('card.caption.gap'), \";\\n}\\n\\n.p-card-body {\\n padding: \").concat(dt('card.body.padding'), \";\\n display: flex;\\n flex-direction: column;\\n gap: \").concat(dt('card.body.gap'), \";\\n}\\n\\n.p-card-title {\\n font-size: \").concat(dt('card.title.font.size'), \";\\n font-weight: \").concat(dt('card.title.font.weight'), \";\\n}\\n\\n.p-card-subtitle {\\n color: \").concat(dt('card.subtitle.color'), \";\\n}\\n\");\n};\nvar classes = {\n root: 'p-card p-component',\n header: 'p-card-header',\n body: 'p-card-body',\n caption: 'p-card-caption',\n title: 'p-card-title',\n subtitle: 'p-card-subtitle',\n content: 'p-card-content',\n footer: 'p-card-footer'\n};\nvar CardStyle = BaseStyle.extend({\n name: 'card',\n theme: theme,\n classes: classes\n});\n\nexport { CardStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseComponent from '@primevue/core/basecomponent';\nimport CardStyle from 'primevue/card/style';\nimport { openBlock, createElementBlock, mergeProps, renderSlot, createCommentVNode, createElementVNode } from 'vue';\n\nvar script$1 = {\n name: 'BaseCard',\n \"extends\": BaseComponent,\n style: CardStyle,\n provide: function provide() {\n return {\n $pcCard: this,\n $parentInstance: this\n };\n }\n};\n\nvar script = {\n name: 'Card',\n \"extends\": script$1,\n inheritAttrs: false\n};\n\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"div\", mergeProps({\n \"class\": _ctx.cx('root')\n }, _ctx.ptmi('root')), [_ctx.$slots.header ? (openBlock(), createElementBlock(\"div\", mergeProps({\n key: 0,\n \"class\": _ctx.cx('header')\n }, _ctx.ptm('header')), [renderSlot(_ctx.$slots, \"header\")], 16)) : createCommentVNode(\"\", true), createElementVNode(\"div\", mergeProps({\n \"class\": _ctx.cx('body')\n }, _ctx.ptm('body')), [_ctx.$slots.title || _ctx.$slots.subtitle ? (openBlock(), createElementBlock(\"div\", mergeProps({\n key: 0,\n \"class\": _ctx.cx('caption')\n }, _ctx.ptm('caption')), [_ctx.$slots.title ? (openBlock(), createElementBlock(\"div\", mergeProps({\n key: 0,\n \"class\": _ctx.cx('title')\n }, _ctx.ptm('title')), [renderSlot(_ctx.$slots, \"title\")], 16)) : createCommentVNode(\"\", true), _ctx.$slots.subtitle ? (openBlock(), createElementBlock(\"div\", mergeProps({\n key: 1,\n \"class\": _ctx.cx('subtitle')\n }, _ctx.ptm('subtitle')), [renderSlot(_ctx.$slots, \"subtitle\")], 16)) : createCommentVNode(\"\", true)], 16)) : createCommentVNode(\"\", true), createElementVNode(\"div\", mergeProps({\n \"class\": _ctx.cx('content')\n }, _ctx.ptm('content')), [renderSlot(_ctx.$slots, \"content\")], 16), _ctx.$slots.footer ? (openBlock(), createElementBlock(\"div\", mergeProps({\n key: 1,\n \"class\": _ctx.cx('footer')\n }, _ctx.ptm('footer')), [renderSlot(_ctx.$slots, \"footer\")], 16)) : createCommentVNode(\"\", true)], 16)], 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n 0\">\r\n \r\n \r\n \r\n \r\n \r\n (group)\r\n }\"\r\n />\r\n \r\n \r\n \r\n \r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","import BaseStyle from '@primevue/core/base/style';\n\nvar theme = function theme(_ref) {\n var dt = _ref.dt;\n return \"\\n.p-tag {\\n display: inline-flex;\\n align-items: center;\\n justify-content: center;\\n background: \".concat(dt('tag.primary.background'), \";\\n color: \").concat(dt('tag.primary.color'), \";\\n font-size: \").concat(dt('tag.font.size'), \";\\n font-weight: \").concat(dt('tag.font.weight'), \";\\n padding: \").concat(dt('tag.padding'), \";\\n border-radius: \").concat(dt('tag.border.radius'), \";\\n gap: \").concat(dt('tag.gap'), \";\\n}\\n\\n.p-tag-icon {\\n font-size: \").concat(dt('tag.icon.size'), \";\\n width: \").concat(dt('tag.icon.size'), \";\\n height:\").concat(dt('tag.icon.size'), \";\\n}\\n\\n.p-tag-rounded {\\n border-radius: \").concat(dt('tag.rounded.border.radius'), \";\\n}\\n\\n.p-tag-success {\\n background: \").concat(dt('tag.success.background'), \";\\n color: \").concat(dt('tag.success.color'), \";\\n}\\n\\n.p-tag-info {\\n background: \").concat(dt('tag.info.background'), \";\\n color: \").concat(dt('tag.info.color'), \";\\n}\\n\\n.p-tag-warn {\\n background: \").concat(dt('tag.warn.background'), \";\\n color: \").concat(dt('tag.warn.color'), \";\\n}\\n\\n.p-tag-danger {\\n background: \").concat(dt('tag.danger.background'), \";\\n color: \").concat(dt('tag.danger.color'), \";\\n}\\n\\n.p-tag-secondary {\\n background: \").concat(dt('tag.secondary.background'), \";\\n color: \").concat(dt('tag.secondary.color'), \";\\n}\\n\\n.p-tag-contrast {\\n background: \").concat(dt('tag.contrast.background'), \";\\n color: \").concat(dt('tag.contrast.color'), \";\\n}\\n\");\n};\nvar classes = {\n root: function root(_ref2) {\n var props = _ref2.props;\n return ['p-tag p-component', {\n 'p-tag-info': props.severity === 'info',\n 'p-tag-success': props.severity === 'success',\n 'p-tag-warn': props.severity === 'warn',\n 'p-tag-danger': props.severity === 'danger',\n 'p-tag-secondary': props.severity === 'secondary',\n 'p-tag-contrast': props.severity === 'contrast',\n 'p-tag-rounded': props.rounded\n }];\n },\n icon: 'p-tag-icon',\n label: 'p-tag-label'\n};\nvar TagStyle = BaseStyle.extend({\n name: 'tag',\n theme: theme,\n classes: classes\n});\n\nexport { TagStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseComponent from '@primevue/core/basecomponent';\nimport TagStyle from 'primevue/tag/style';\nimport { openBlock, createElementBlock, mergeProps, createBlock, resolveDynamicComponent, createCommentVNode, renderSlot, createElementVNode, toDisplayString } from 'vue';\n\nvar script$1 = {\n name: 'BaseTag',\n \"extends\": BaseComponent,\n props: {\n value: null,\n severity: null,\n rounded: Boolean,\n icon: String\n },\n style: TagStyle,\n provide: function provide() {\n return {\n $pcTag: this,\n $parentInstance: this\n };\n }\n};\n\nvar script = {\n name: 'Tag',\n \"extends\": script$1,\n inheritAttrs: false\n};\n\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"span\", mergeProps({\n \"class\": _ctx.cx('root')\n }, _ctx.ptmi('root')), [_ctx.$slots.icon ? (openBlock(), createBlock(resolveDynamicComponent(_ctx.$slots.icon), mergeProps({\n key: 0,\n \"class\": _ctx.cx('icon')\n }, _ctx.ptm('icon')), null, 16, [\"class\"])) : _ctx.icon ? (openBlock(), createElementBlock(\"span\", mergeProps({\n key: 1,\n \"class\": [_ctx.cx('icon'), _ctx.icon]\n }, _ctx.ptm('icon')), null, 16)) : createCommentVNode(\"\", true), _ctx.value != null || _ctx.$slots[\"default\"] ? renderSlot(_ctx.$slots, \"default\", {\n key: 2\n }, function () {\n return [createElementVNode(\"span\", mergeProps({\n \"class\": _ctx.cx('label')\n }, _ctx.ptm('label')), toDisplayString(_ctx.value), 17)];\n }) : createCommentVNode(\"\", true)], 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","\r\n \r\n \r\n \r\n {{ $t('settings') }}\r\n \r\n \r\n \r\n\r\n\r\n\r\n\r\n\r\n","\r\n \r\n\r\n\r\n\r\n","import { SidebarTabExtension } from '@/types/extensionTypes'\r\nimport { defineStore } from 'pinia'\r\n\r\ninterface WorkspaceState {\r\n spinner: boolean\r\n activeSidebarTab: string | null\r\n sidebarTabs: SidebarTabExtension[]\r\n}\r\n\r\nexport const useWorkspaceStore = defineStore('workspace', {\r\n state: (): WorkspaceState => ({\r\n spinner: false,\r\n activeSidebarTab: null,\r\n sidebarTabs: []\r\n }),\r\n actions: {\r\n updateActiveSidebarTab(tabId: string) {\r\n this.activeSidebarTab = tabId\r\n },\r\n registerSidebarTab(tab: SidebarTabExtension) {\r\n this.sidebarTabs = [...this.sidebarTabs, tab]\r\n },\r\n unregisterSidebarTab(id: string) {\r\n const index = this.sidebarTabs.findIndex((tab) => tab.id === id)\r\n if (index !== -1) {\r\n const tab = this.sidebarTabs[index]\r\n if (tab.type === 'custom' && tab.destroy) {\r\n tab.destroy()\r\n }\r\n const newSidebarTabs = [...this.sidebarTabs]\r\n newSidebarTabs.splice(index, 1)\r\n this.sidebarTabs = newSidebarTabs\r\n }\r\n },\r\n getSidebarTabs() {\r\n return [...this.sidebarTabs]\r\n }\r\n }\r\n})\r\n","\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n {\r\n if (el)\r\n mountCustomTab(\r\n selectedTab as CustomSidebarTabExtension,\r\n el as HTMLElement\r\n )\r\n }\r\n \"\r\n >\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","import BaseStyle from '@primevue/core/base/style';\n\nvar theme = function theme(_ref) {\n var dt = _ref.dt;\n return \"\\n.p-splitter {\\n display: flex;\\n flex-wrap: nowrap;\\n border: 1px solid \".concat(dt('splitter.border.color'), \";\\n background: \").concat(dt('splitter.background'), \";\\n border-radius: \").concat(dt('border.radius.md'), \";\\n color: \").concat(dt('splitter.color'), \";\\n}\\n\\n.p-splitter-vertical {\\n flex-direction: column;\\n}\\n\\n.p-splitter-gutter {\\n flex-grow: 0;\\n flex-shrink: 0;\\n display: flex;\\n align-items: center;\\n justify-content: center;\\n z-index: 1;\\n background: \").concat(dt('splitter.gutter.background'), \";\\n}\\n\\n.p-splitter-gutter-handle {\\n border-radius: \").concat(dt('splitter.handle.border.radius'), \";\\n background: \").concat(dt('splitter.handle.background'), \";\\n transition: outline-color \").concat(dt('splitter.transition.duration'), \", box-shadow \").concat(dt('splitter.transition.duration'), \";\\n outline-color: transparent;\\n}\\n\\n.p-splitter-gutter-handle:focus-visible {\\n box-shadow: \").concat(dt('splitter.handle.focus.ring.shadow'), \";\\n outline: \").concat(dt('splitter.handle.focus.ring.width'), \" \").concat(dt('splitter.handle.focus.ring.style'), \" \").concat(dt('splitter.handle.focus.ring.color'), \";\\n outline-offset: \").concat(dt('splitter.handle.focus.ring.offset'), \";\\n}\\n\\n.p-splitter-horizontal.p-splitter-resizing {\\n cursor: col-resize;\\n user-select: none;\\n}\\n\\n.p-splitter-vertical.p-splitter-resizing {\\n cursor: row-resize;\\n user-select: none;\\n}\\n\\n.p-splitter-horizontal > .p-splitter-gutter > .p-splitter-gutter-handle {\\n height: \").concat(dt('splitter.handle.size'), \";\\n width: 100%;\\n}\\n\\n.p-splitter-vertical > .p-splitter-gutter > .p-splitter-gutter-handle {\\n width: \").concat(dt('splitter.handle.size'), \";\\n height: 100%;\\n}\\n\\n.p-splitter-horizontal > .p-splitter-gutter {\\n cursor: col-resize;\\n}\\n\\n.p-splitter-vertical > .p-splitter-gutter {\\n cursor: row-resize;\\n}\\n\\n.p-splitterpanel {\\n flex-grow: 1;\\n overflow: hidden;\\n}\\n\\n.p-splitterpanel-nested {\\n display: flex;\\n}\\n\\n.p-splitterpanel .p-splitter {\\n flex-grow: 1;\\n border: 0 none;\\n}\\n\");\n};\nvar classes = {\n root: function root(_ref2) {\n var props = _ref2.props;\n return ['p-splitter p-component', 'p-splitter-' + props.layout];\n },\n gutter: 'p-splitter-gutter',\n gutterHandle: 'p-splitter-gutter-handle'\n};\nvar inlineStyles = {\n root: function root(_ref3) {\n var props = _ref3.props;\n return [{\n display: 'flex',\n 'flex-wrap': 'nowrap'\n }, props.layout === 'vertical' ? {\n 'flex-direction': 'column'\n } : ''];\n }\n};\nvar SplitterStyle = BaseStyle.extend({\n name: 'splitter',\n theme: theme,\n classes: classes,\n inlineStyles: inlineStyles\n});\n\nexport { SplitterStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import { getVNodeProp } from '@primevue/core/utils';\nimport { getWidth, getHeight, getOuterWidth, getOuterHeight } from '@primeuix/utils/dom';\nimport { isArray } from '@primeuix/utils/object';\nimport BaseComponent from '@primevue/core/basecomponent';\nimport SplitterStyle from 'primevue/splitter/style';\nimport { openBlock, createElementBlock, mergeProps, Fragment, renderList, createBlock, resolveDynamicComponent, createElementVNode, createCommentVNode } from 'vue';\n\nvar script$1 = {\n name: 'BaseSplitter',\n \"extends\": BaseComponent,\n props: {\n layout: {\n type: String,\n \"default\": 'horizontal'\n },\n gutterSize: {\n type: Number,\n \"default\": 4\n },\n stateKey: {\n type: String,\n \"default\": null\n },\n stateStorage: {\n type: String,\n \"default\": 'session'\n },\n step: {\n type: Number,\n \"default\": 5\n }\n },\n style: SplitterStyle,\n provide: function provide() {\n return {\n $pcSplitter: this,\n $parentInstance: this\n };\n }\n};\n\nfunction _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _unsupportedIterableToArray(r, a) { if (r) { if (\"string\" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return \"Object\" === t && r.constructor && (t = r.constructor.name), \"Map\" === t || \"Set\" === t ? Array.from(r) : \"Arguments\" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }\nfunction _iterableToArray(r) { if (\"undefined\" != typeof Symbol && null != r[Symbol.iterator] || null != r[\"@@iterator\"]) return Array.from(r); }\nfunction _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }\nfunction _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }\nvar script = {\n name: 'Splitter',\n \"extends\": script$1,\n inheritAttrs: false,\n emits: ['resizestart', 'resizeend', 'resize'],\n dragging: false,\n mouseMoveListener: null,\n mouseUpListener: null,\n touchMoveListener: null,\n touchEndListener: null,\n size: null,\n gutterElement: null,\n startPos: null,\n prevPanelElement: null,\n nextPanelElement: null,\n nextPanelSize: null,\n prevPanelSize: null,\n panelSizes: null,\n prevPanelIndex: null,\n timer: null,\n data: function data() {\n return {\n prevSize: null\n };\n },\n mounted: function mounted() {\n var _this = this;\n if (this.panels && this.panels.length) {\n var initialized = false;\n if (this.isStateful()) {\n initialized = this.restoreState();\n }\n if (!initialized) {\n var children = _toConsumableArray(this.$el.children).filter(function (child) {\n return child.getAttribute('data-pc-name') === 'splitterpanel';\n });\n var _panelSizes = [];\n this.panels.map(function (panel, i) {\n var panelInitialSize = panel.props && panel.props.size ? panel.props.size : null;\n var panelSize = panelInitialSize || 100 / _this.panels.length;\n _panelSizes[i] = panelSize;\n children[i].style.flexBasis = 'calc(' + panelSize + '% - ' + (_this.panels.length - 1) * _this.gutterSize + 'px)';\n });\n this.panelSizes = _panelSizes;\n this.prevSize = parseFloat(_panelSizes[0]).toFixed(4);\n }\n }\n },\n beforeUnmount: function beforeUnmount() {\n this.clear();\n this.unbindMouseListeners();\n },\n methods: {\n isSplitterPanel: function isSplitterPanel(child) {\n return child.type.name === 'SplitterPanel';\n },\n onResizeStart: function onResizeStart(event, index, isKeyDown) {\n this.gutterElement = event.currentTarget || event.target.parentElement;\n this.size = this.horizontal ? getWidth(this.$el) : getHeight(this.$el);\n if (!isKeyDown) {\n this.dragging = true;\n this.startPos = this.layout === 'horizontal' ? event.pageX || event.changedTouches[0].pageX : event.pageY || event.changedTouches[0].pageY;\n }\n this.prevPanelElement = this.gutterElement.previousElementSibling;\n this.nextPanelElement = this.gutterElement.nextElementSibling;\n if (isKeyDown) {\n this.prevPanelSize = this.horizontal ? getOuterWidth(this.prevPanelElement, true) : getOuterHeight(this.prevPanelElement, true);\n this.nextPanelSize = this.horizontal ? getOuterWidth(this.nextPanelElement, true) : getOuterHeight(this.nextPanelElement, true);\n } else {\n this.prevPanelSize = 100 * (this.horizontal ? getOuterWidth(this.prevPanelElement, true) : getOuterHeight(this.prevPanelElement, true)) / this.size;\n this.nextPanelSize = 100 * (this.horizontal ? getOuterWidth(this.nextPanelElement, true) : getOuterHeight(this.nextPanelElement, true)) / this.size;\n }\n this.prevPanelIndex = index;\n this.$emit('resizestart', {\n originalEvent: event,\n sizes: this.panelSizes\n });\n this.$refs.gutter[index].setAttribute('data-p-gutter-resizing', true);\n this.$el.setAttribute('data-p-resizing', true);\n },\n onResize: function onResize(event, step, isKeyDown) {\n var newPos, newPrevPanelSize, newNextPanelSize;\n if (isKeyDown) {\n if (this.horizontal) {\n newPrevPanelSize = 100 * (this.prevPanelSize + step) / this.size;\n newNextPanelSize = 100 * (this.nextPanelSize - step) / this.size;\n } else {\n newPrevPanelSize = 100 * (this.prevPanelSize - step) / this.size;\n newNextPanelSize = 100 * (this.nextPanelSize + step) / this.size;\n }\n } else {\n if (this.horizontal) newPos = event.pageX * 100 / this.size - this.startPos * 100 / this.size;else newPos = event.pageY * 100 / this.size - this.startPos * 100 / this.size;\n newPrevPanelSize = this.prevPanelSize + newPos;\n newNextPanelSize = this.nextPanelSize - newPos;\n }\n if (this.validateResize(newPrevPanelSize, newNextPanelSize)) {\n this.prevPanelElement.style.flexBasis = 'calc(' + newPrevPanelSize + '% - ' + (this.panels.length - 1) * this.gutterSize + 'px)';\n this.nextPanelElement.style.flexBasis = 'calc(' + newNextPanelSize + '% - ' + (this.panels.length - 1) * this.gutterSize + 'px)';\n this.panelSizes[this.prevPanelIndex] = newPrevPanelSize;\n this.panelSizes[this.prevPanelIndex + 1] = newNextPanelSize;\n this.prevSize = parseFloat(newPrevPanelSize).toFixed(4);\n }\n this.$emit('resize', {\n originalEvent: event,\n sizes: this.panelSizes\n });\n },\n onResizeEnd: function onResizeEnd(event) {\n if (this.isStateful()) {\n this.saveState();\n }\n this.$emit('resizeend', {\n originalEvent: event,\n sizes: this.panelSizes\n });\n this.$refs.gutter.forEach(function (gutter) {\n return gutter.setAttribute('data-p-gutter-resizing', false);\n });\n this.$el.setAttribute('data-p-resizing', false);\n this.clear();\n },\n repeat: function repeat(event, index, step) {\n this.onResizeStart(event, index, true);\n this.onResize(event, step, true);\n },\n setTimer: function setTimer(event, index, step) {\n var _this2 = this;\n if (!this.timer) {\n this.timer = setInterval(function () {\n _this2.repeat(event, index, step);\n }, 40);\n }\n },\n clearTimer: function clearTimer() {\n if (this.timer) {\n clearInterval(this.timer);\n this.timer = null;\n }\n },\n onGutterKeyUp: function onGutterKeyUp() {\n this.clearTimer();\n this.onResizeEnd();\n },\n onGutterKeyDown: function onGutterKeyDown(event, index) {\n switch (event.code) {\n case 'ArrowLeft':\n {\n if (this.layout === 'horizontal') {\n this.setTimer(event, index, this.step * -1);\n }\n event.preventDefault();\n break;\n }\n case 'ArrowRight':\n {\n if (this.layout === 'horizontal') {\n this.setTimer(event, index, this.step);\n }\n event.preventDefault();\n break;\n }\n case 'ArrowDown':\n {\n if (this.layout === 'vertical') {\n this.setTimer(event, index, this.step * -1);\n }\n event.preventDefault();\n break;\n }\n case 'ArrowUp':\n {\n if (this.layout === 'vertical') {\n this.setTimer(event, index, this.step);\n }\n event.preventDefault();\n break;\n }\n }\n },\n onGutterMouseDown: function onGutterMouseDown(event, index) {\n this.onResizeStart(event, index);\n this.bindMouseListeners();\n },\n onGutterTouchStart: function onGutterTouchStart(event, index) {\n this.onResizeStart(event, index);\n this.bindTouchListeners();\n event.preventDefault();\n },\n onGutterTouchMove: function onGutterTouchMove(event) {\n this.onResize(event);\n event.preventDefault();\n },\n onGutterTouchEnd: function onGutterTouchEnd(event) {\n this.onResizeEnd(event);\n this.unbindTouchListeners();\n event.preventDefault();\n },\n bindMouseListeners: function bindMouseListeners() {\n var _this3 = this;\n if (!this.mouseMoveListener) {\n this.mouseMoveListener = function (event) {\n return _this3.onResize(event);\n };\n document.addEventListener('mousemove', this.mouseMoveListener);\n }\n if (!this.mouseUpListener) {\n this.mouseUpListener = function (event) {\n _this3.onResizeEnd(event);\n _this3.unbindMouseListeners();\n };\n document.addEventListener('mouseup', this.mouseUpListener);\n }\n },\n bindTouchListeners: function bindTouchListeners() {\n var _this4 = this;\n if (!this.touchMoveListener) {\n this.touchMoveListener = function (event) {\n return _this4.onResize(event.changedTouches[0]);\n };\n document.addEventListener('touchmove', this.touchMoveListener);\n }\n if (!this.touchEndListener) {\n this.touchEndListener = function (event) {\n _this4.resizeEnd(event);\n _this4.unbindTouchListeners();\n };\n document.addEventListener('touchend', this.touchEndListener);\n }\n },\n validateResize: function validateResize(newPrevPanelSize, newNextPanelSize) {\n if (newPrevPanelSize > 100 || newPrevPanelSize < 0) return false;\n if (newNextPanelSize > 100 || newNextPanelSize < 0) return false;\n var prevPanelMinSize = getVNodeProp(this.panels[this.prevPanelIndex], 'minSize');\n if (this.panels[this.prevPanelIndex].props && prevPanelMinSize && prevPanelMinSize > newPrevPanelSize) {\n return false;\n }\n var newPanelMinSize = getVNodeProp(this.panels[this.prevPanelIndex + 1], 'minSize');\n if (this.panels[this.prevPanelIndex + 1].props && newPanelMinSize && newPanelMinSize > newNextPanelSize) {\n return false;\n }\n return true;\n },\n unbindMouseListeners: function unbindMouseListeners() {\n if (this.mouseMoveListener) {\n document.removeEventListener('mousemove', this.mouseMoveListener);\n this.mouseMoveListener = null;\n }\n if (this.mouseUpListener) {\n document.removeEventListener('mouseup', this.mouseUpListener);\n this.mouseUpListener = null;\n }\n },\n unbindTouchListeners: function unbindTouchListeners() {\n if (this.touchMoveListener) {\n document.removeEventListener('touchmove', this.touchMoveListener);\n this.touchMoveListener = null;\n }\n if (this.touchEndListener) {\n document.removeEventListener('touchend', this.touchEndListener);\n this.touchEndListener = null;\n }\n },\n clear: function clear() {\n this.dragging = false;\n this.size = null;\n this.startPos = null;\n this.prevPanelElement = null;\n this.nextPanelElement = null;\n this.prevPanelSize = null;\n this.nextPanelSize = null;\n this.gutterElement = null;\n this.prevPanelIndex = null;\n },\n isStateful: function isStateful() {\n return this.stateKey != null;\n },\n getStorage: function getStorage() {\n switch (this.stateStorage) {\n case 'local':\n return window.localStorage;\n case 'session':\n return window.sessionStorage;\n default:\n throw new Error(this.stateStorage + ' is not a valid value for the state storage, supported values are \"local\" and \"session\".');\n }\n },\n saveState: function saveState() {\n if (isArray(this.panelSizes)) {\n this.getStorage().setItem(this.stateKey, JSON.stringify(this.panelSizes));\n }\n },\n restoreState: function restoreState() {\n var _this5 = this;\n var storage = this.getStorage();\n var stateString = storage.getItem(this.stateKey);\n if (stateString) {\n this.panelSizes = JSON.parse(stateString);\n var children = _toConsumableArray(this.$el.children).filter(function (child) {\n return child.getAttribute('data-pc-name') === 'splitterpanel';\n });\n children.forEach(function (child, i) {\n child.style.flexBasis = 'calc(' + _this5.panelSizes[i] + '% - ' + (_this5.panels.length - 1) * _this5.gutterSize + 'px)';\n });\n return true;\n }\n return false;\n }\n },\n computed: {\n panels: function panels() {\n var _this6 = this;\n var panels = [];\n this.$slots[\"default\"]().forEach(function (child) {\n if (_this6.isSplitterPanel(child)) {\n panels.push(child);\n } else if (child.children instanceof Array) {\n child.children.forEach(function (nestedChild) {\n if (_this6.isSplitterPanel(nestedChild)) {\n panels.push(nestedChild);\n }\n });\n }\n });\n return panels;\n },\n gutterStyle: function gutterStyle() {\n if (this.horizontal) return {\n width: this.gutterSize + 'px'\n };else return {\n height: this.gutterSize + 'px'\n };\n },\n horizontal: function horizontal() {\n return this.layout === 'horizontal';\n },\n getPTOptions: function getPTOptions() {\n var _this$$parentInstance;\n return {\n context: {\n nested: (_this$$parentInstance = this.$parentInstance) === null || _this$$parentInstance === void 0 ? void 0 : _this$$parentInstance.nestedState\n }\n };\n }\n }\n};\n\nvar _hoisted_1 = [\"onMousedown\", \"onTouchstart\", \"onTouchmove\", \"onTouchend\"];\nvar _hoisted_2 = [\"aria-orientation\", \"aria-valuenow\", \"onKeydown\"];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"div\", mergeProps({\n \"class\": _ctx.cx('root'),\n style: _ctx.sx('root'),\n \"data-p-resizing\": false\n }, _ctx.ptmi('root', $options.getPTOptions)), [(openBlock(true), createElementBlock(Fragment, null, renderList($options.panels, function (panel, i) {\n return openBlock(), createElementBlock(Fragment, {\n key: i\n }, [(openBlock(), createBlock(resolveDynamicComponent(panel), {\n tabindex: \"-1\"\n })), i !== $options.panels.length - 1 ? (openBlock(), createElementBlock(\"div\", mergeProps({\n key: 0,\n ref_for: true,\n ref: \"gutter\",\n \"class\": _ctx.cx('gutter'),\n role: \"separator\",\n tabindex: \"-1\",\n onMousedown: function onMousedown($event) {\n return $options.onGutterMouseDown($event, i);\n },\n onTouchstart: function onTouchstart($event) {\n return $options.onGutterTouchStart($event, i);\n },\n onTouchmove: function onTouchmove($event) {\n return $options.onGutterTouchMove($event, i);\n },\n onTouchend: function onTouchend($event) {\n return $options.onGutterTouchEnd($event, i);\n },\n \"data-p-gutter-resizing\": false\n }, _ctx.ptm('gutter')), [createElementVNode(\"div\", mergeProps({\n \"class\": _ctx.cx('gutterHandle'),\n tabindex: \"0\",\n style: [$options.gutterStyle],\n \"aria-orientation\": _ctx.layout,\n \"aria-valuenow\": $data.prevSize,\n onKeyup: _cache[0] || (_cache[0] = function () {\n return $options.onGutterKeyUp && $options.onGutterKeyUp.apply($options, arguments);\n }),\n onKeydown: function onKeydown($event) {\n return $options.onGutterKeyDown($event, i);\n },\n ref_for: true\n }, _ctx.ptm('gutterHandle')), null, 16, _hoisted_2)], 16, _hoisted_1)) : createCommentVNode(\"\", true)], 64);\n }), 128))], 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseStyle from '@primevue/core/base/style';\n\nvar classes = {\n root: function root(_ref) {\n var instance = _ref.instance;\n return ['p-splitterpanel', {\n 'p-splitterpanel-nested': instance.isNested\n }];\n }\n};\nvar SplitterPanelStyle = BaseStyle.extend({\n name: 'splitterpanel',\n classes: classes\n});\n\nexport { SplitterPanelStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseComponent from '@primevue/core/basecomponent';\nimport SplitterPanelStyle from 'primevue/splitterpanel/style';\nimport { openBlock, createElementBlock, mergeProps, renderSlot } from 'vue';\n\nvar script$1 = {\n name: 'BaseSplitterPanel',\n \"extends\": BaseComponent,\n props: {\n size: {\n type: Number,\n \"default\": null\n },\n minSize: {\n type: Number,\n \"default\": null\n }\n },\n style: SplitterPanelStyle,\n provide: function provide() {\n return {\n $pcSplitterPanel: this,\n $parentInstance: this\n };\n }\n};\n\nvar script = {\n name: 'SplitterPanel',\n \"extends\": script$1,\n inheritAttrs: false,\n data: function data() {\n return {\n nestedState: null\n };\n },\n computed: {\n isNested: function isNested() {\n var _this = this;\n return this.$slots[\"default\"]().some(function (child) {\n _this.nestedState = child.type.name === 'Splitter' ? true : null;\n return _this.nestedState;\n });\n },\n getPTOptions: function getPTOptions() {\n return {\n context: {\n nested: this.isNested\n }\n };\n }\n }\n};\n\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"div\", mergeProps({\n ref: \"container\",\n \"class\": _ctx.cx('root')\n }, _ctx.ptmi('root', $options.getPTOptions)), [renderSlot(_ctx.$slots, \"default\")], 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","import BaseIcon from '@primevue/icons/baseicon';\nimport { openBlock, createElementBlock, mergeProps, createElementVNode } from 'vue';\n\nvar script = {\n name: 'TimesCircleIcon',\n \"extends\": BaseIcon\n};\n\nvar _hoisted_1 = /*#__PURE__*/createElementVNode(\"path\", {\n \"fill-rule\": \"evenodd\",\n \"clip-rule\": \"evenodd\",\n d: \"M7 14C5.61553 14 4.26215 13.5895 3.11101 12.8203C1.95987 12.0511 1.06266 10.9579 0.532846 9.67879C0.00303296 8.3997 -0.13559 6.99224 0.134506 5.63437C0.404603 4.2765 1.07129 3.02922 2.05026 2.05026C3.02922 1.07129 4.2765 0.404603 5.63437 0.134506C6.99224 -0.13559 8.3997 0.00303296 9.67879 0.532846C10.9579 1.06266 12.0511 1.95987 12.8203 3.11101C13.5895 4.26215 14 5.61553 14 7C14 8.85652 13.2625 10.637 11.9497 11.9497C10.637 13.2625 8.85652 14 7 14ZM7 1.16667C5.84628 1.16667 4.71846 1.50879 3.75918 2.14976C2.79989 2.79074 2.05222 3.70178 1.61071 4.76768C1.16919 5.83358 1.05367 7.00647 1.27876 8.13803C1.50384 9.26958 2.05941 10.309 2.87521 11.1248C3.69102 11.9406 4.73042 12.4962 5.86198 12.7212C6.99353 12.9463 8.16642 12.8308 9.23232 12.3893C10.2982 11.9478 11.2093 11.2001 11.8502 10.2408C12.4912 9.28154 12.8333 8.15373 12.8333 7C12.8333 5.45291 12.2188 3.96918 11.1248 2.87521C10.0308 1.78125 8.5471 1.16667 7 1.16667ZM4.66662 9.91668C4.58998 9.91704 4.51404 9.90209 4.44325 9.87271C4.37246 9.84333 4.30826 9.8001 4.2544 9.74557C4.14516 9.6362 4.0838 9.48793 4.0838 9.33335C4.0838 9.17876 4.14516 9.0305 4.2544 8.92113L6.17553 7L4.25443 5.07891C4.15139 4.96832 4.09529 4.82207 4.09796 4.67094C4.10063 4.51982 4.16185 4.37563 4.26872 4.26876C4.3756 4.16188 4.51979 4.10066 4.67091 4.09799C4.82204 4.09532 4.96829 4.15142 5.07887 4.25446L6.99997 6.17556L8.92106 4.25446C9.03164 4.15142 9.1779 4.09532 9.32903 4.09799C9.48015 4.10066 9.62434 4.16188 9.73121 4.26876C9.83809 4.37563 9.89931 4.51982 9.90198 4.67094C9.90464 4.82207 9.84855 4.96832 9.74551 5.07891L7.82441 7L9.74554 8.92113C9.85478 9.0305 9.91614 9.17876 9.91614 9.33335C9.91614 9.48793 9.85478 9.6362 9.74554 9.74557C9.69168 9.8001 9.62748 9.84333 9.55669 9.87271C9.4859 9.90209 9.40996 9.91704 9.33332 9.91668C9.25668 9.91704 9.18073 9.90209 9.10995 9.87271C9.03916 9.84333 8.97495 9.8001 8.9211 9.74557L6.99997 7.82444L5.07884 9.74557C5.02499 9.8001 4.96078 9.84333 4.88999 9.87271C4.81921 9.90209 4.74326 9.91704 4.66662 9.91668Z\",\n fill: \"currentColor\"\n}, null, -1);\nvar _hoisted_2 = [_hoisted_1];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"svg\", mergeProps({\n width: \"14\",\n height: \"14\",\n viewBox: \"0 0 14 14\",\n fill: \"none\",\n xmlns: \"http://www.w3.org/2000/svg\"\n }, _ctx.pti()), _hoisted_2, 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseStyle from '@primevue/core/base/style';\n\nvar theme = function theme(_ref) {\n var dt = _ref.dt;\n return \"\\n.p-chip {\\n display: inline-flex;\\n align-items: center;\\n background: \".concat(dt('chip.background'), \";\\n color: \").concat(dt('chip.color'), \";\\n border-radius: \").concat(dt('chip.border.radius'), \";\\n padding: \").concat(dt('chip.padding.y'), \" \").concat(dt('chip.padding.x'), \";\\n gap: \").concat(dt('chip.gap'), \";\\n}\\n\\n.p-chip-icon {\\n color: \").concat(dt('chip.icon.color'), \";\\n font-size: \").concat(dt('chip.icon.font.size'), \";\\n width: \").concat(dt('chip.icon.size'), \";\\n height: \").concat(dt('chip.icon.size'), \";\\n}\\n\\n.p-chip-image {\\n border-radius: 50%;\\n width: \").concat(dt('chip.image.width'), \";\\n height: \").concat(dt('chip.image.height'), \";\\n margin-left: calc(-1 * \").concat(dt('chip.padding.y'), \");\\n}\\n\\n.p-chip:has(.p-chip-remove-icon) {\\n padding-right: \").concat(dt('chip.padding.y'), \";\\n}\\n\\n.p-chip:has(.p-chip-image) {\\n padding-top: calc(\").concat(dt('chip.padding.y'), \" / 2);\\n padding-bottom: calc(\").concat(dt('chip.padding.y'), \" / 2);\\n}\\n\\n.p-chip-remove-icon {\\n cursor: pointer;\\n font-size: \").concat(dt('chip.remove.icon.size'), \";\\n width: \").concat(dt('chip.remove.icon.size'), \";\\n height: \").concat(dt('chip.remove.icon.size'), \";\\n color: \").concat(dt('chip.remove.icon.color'), \";\\n border-radius: 50%;\\n transition: outline-color \").concat(dt('chip.transition.duration'), \", box-shadow \").concat(dt('chip.transition.duration'), \";\\n outline-color: transparent;\\n}\\n\\n.p-chip-remove-icon:focus-visible {\\n box-shadow: \").concat(dt('chip.remove.icon.focus.ring.shadow'), \";\\n outline: \").concat(dt('chip.remove.icon.focus.ring.width'), \" \").concat(dt('chip.remove.icon.focus.ring.style'), \" \").concat(dt('chip.remove.icon.focus.ring.color'), \";\\n outline-offset: \").concat(dt('chip.remove.icon.focus.ring.offset'), \";\\n}\\n\");\n};\nvar classes = {\n root: 'p-chip p-component',\n image: 'p-chip-image',\n icon: 'p-chip-icon',\n label: 'p-chip-label',\n removeIcon: 'p-chip-remove-icon'\n};\nvar ChipStyle = BaseStyle.extend({\n name: 'chip',\n theme: theme,\n classes: classes\n});\n\nexport { ChipStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import TimesCircleIcon from '@primevue/icons/timescircle';\nimport BaseComponent from '@primevue/core/basecomponent';\nimport ChipStyle from 'primevue/chip/style';\nimport { openBlock, createElementBlock, mergeProps, renderSlot, createBlock, resolveDynamicComponent, createCommentVNode, toDisplayString } from 'vue';\n\nvar script$1 = {\n name: 'BaseChip',\n \"extends\": BaseComponent,\n props: {\n label: {\n type: String,\n \"default\": null\n },\n icon: {\n type: String,\n \"default\": null\n },\n image: {\n type: String,\n \"default\": null\n },\n removable: {\n type: Boolean,\n \"default\": false\n },\n removeIcon: {\n type: String,\n \"default\": undefined\n }\n },\n style: ChipStyle,\n provide: function provide() {\n return {\n $pcChip: this,\n $parentInstance: this\n };\n }\n};\n\nvar script = {\n name: 'Chip',\n \"extends\": script$1,\n inheritAttrs: false,\n emits: ['remove'],\n data: function data() {\n return {\n visible: true\n };\n },\n methods: {\n onKeydown: function onKeydown(event) {\n if (event.key === 'Enter' || event.key === 'Backspace') {\n this.close(event);\n }\n },\n close: function close(event) {\n this.visible = false;\n this.$emit('remove', event);\n }\n },\n components: {\n TimesCircleIcon: TimesCircleIcon\n }\n};\n\nvar _hoisted_1 = [\"aria-label\"];\nvar _hoisted_2 = [\"src\"];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return $data.visible ? (openBlock(), createElementBlock(\"div\", mergeProps({\n key: 0,\n \"class\": _ctx.cx('root'),\n \"aria-label\": _ctx.label\n }, _ctx.ptmi('root')), [renderSlot(_ctx.$slots, \"default\", {}, function () {\n return [_ctx.image ? (openBlock(), createElementBlock(\"img\", mergeProps({\n key: 0,\n src: _ctx.image\n }, _ctx.ptm('image'), {\n \"class\": _ctx.cx('image')\n }), null, 16, _hoisted_2)) : _ctx.$slots.icon ? (openBlock(), createBlock(resolveDynamicComponent(_ctx.$slots.icon), mergeProps({\n key: 1,\n \"class\": _ctx.cx('icon')\n }, _ctx.ptm('icon')), null, 16, [\"class\"])) : _ctx.icon ? (openBlock(), createElementBlock(\"span\", mergeProps({\n key: 2,\n \"class\": [_ctx.cx('icon'), _ctx.icon]\n }, _ctx.ptm('icon')), null, 16)) : createCommentVNode(\"\", true), _ctx.label ? (openBlock(), createElementBlock(\"div\", mergeProps({\n key: 3,\n \"class\": _ctx.cx('label')\n }, _ctx.ptm('label')), toDisplayString(_ctx.label), 17)) : createCommentVNode(\"\", true)];\n }), _ctx.removable ? renderSlot(_ctx.$slots, \"removeicon\", {\n key: 0,\n removeCallback: $options.close,\n keydownCallback: $options.onKeydown\n }, function () {\n return [(openBlock(), createBlock(resolveDynamicComponent(_ctx.removeIcon ? 'span' : 'TimesCircleIcon'), mergeProps({\n tabindex: \"0\",\n \"class\": [_ctx.cx('removeIcon'), _ctx.removeIcon],\n onClick: $options.close,\n onKeydown: $options.onKeydown\n }, _ctx.ptm('removeIcon')), null, 16, [\"class\", \"onClick\", \"onKeydown\"]))];\n }) : createCommentVNode(\"\", true)], 16, _hoisted_1)) : createCommentVNode(\"\", true);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import { isNotEmpty } from '@primeuix/utils/object';\nimport BaseStyle from '@primevue/core/base/style';\n\nvar theme = function theme(_ref) {\n var dt = _ref.dt;\n return \"\\n.p-autocomplete {\\n display: inline-flex;\\n}\\n\\n.p-autocomplete-loader {\\n position: absolute;\\n top: 50%;\\n margin-top: -0.5rem;\\n right: \".concat(dt('autocomplete.padding.x'), \";\\n}\\n\\n.p-autocomplete:has(.p-autocomplete-dropdown) .p-autocomplete-loader {\\n right: calc(\").concat(dt('autocomplete.dropdown.width'), \" + \").concat(dt('autocomplete.padding.x'), \");\\n}\\n\\n.p-autocomplete:has(.p-autocomplete-dropdown) .p-autocomplete-input {\\n flex: 1 1 auto;\\n width: 1%;\\n}\\n\\n.p-autocomplete:has(.p-autocomplete-dropdown) .p-autocomplete-input,\\n.p-autocomplete:has(.p-autocomplete-dropdown) .p-autocomplete-input-multiple {\\n border-top-right-radius: 0;\\n border-bottom-right-radius: 0;\\n}\\n\\n.p-autocomplete-dropdown {\\n cursor: pointer;\\n display: inline-flex;\\n cursor: pointer;\\n user-select: none;\\n align-items: center;\\n justify-content: center;\\n overflow: hidden;\\n position: relative;\\n width: \").concat(dt('autocomplete.dropdown.width'), \";\\n border-top-right-radius: \").concat(dt('autocomplete.dropdown.border.radius'), \";\\n border-bottom-right-radius: \").concat(dt('autocomplete.dropdown.border.radius'), \";\\n background: \").concat(dt('autocomplete.dropdown.background'), \";\\n border: 1px solid \").concat(dt('autocomplete.dropdown.border.color'), \";\\n border-left: 0 none;\\n color: \").concat(dt('autocomplete.dropdown.color'), \";\\n transition: background \").concat(dt('autocomplete.transition.duration'), \", color \").concat(dt('autocomplete.transition.duration'), \", border-color \").concat(dt('autocomplete.transition.duration'), \", outline-color \").concat(dt('autocomplete.transition.duration'), \", box-shadow \").concat(dt('autocomplete.transition.duration'), \";\\n outline-color: transparent;\\n}\\n\\n.p-autocomplete-dropdown:not(:disabled):hover {\\n background: \").concat(dt('autocomplete.dropdown.hover.background'), \";\\n border-color: \").concat(dt('autocomplete.dropdown.hover.border.color'), \";\\n color: \").concat(dt('autocomplete.dropdown.hover.color'), \";\\n}\\n\\n.p-autocomplete-dropdown:not(:disabled):active {\\n background: \").concat(dt('autocomplete.dropdown.active.background'), \";\\n border-color: \").concat(dt('autocomplete.dropdown.active.border.color'), \";\\n color: \").concat(dt('autocomplete.dropdown.active.color'), \";\\n}\\n\\n.p-autocomplete-dropdown:focus-visible {\\n box-shadow: \").concat(dt('autocomplete.dropdown.focus.ring.shadow'), \";\\n outline: \").concat(dt('autocomplete.dropdown.focus.ring.width'), \" \").concat(dt('autocomplete.dropdown.focus.ring.style'), \" \").concat(dt('autocomplete.dropdown.focus.ring.color'), \";\\n outline-offset: \").concat(dt('autocomplete.dropdown.focus.ring.offset'), \";\\n}\\n\\n.p-autocomplete .p-autocomplete-overlay {\\n min-width: 100%;\\n}\\n\\n.p-autocomplete-overlay {\\n position: absolute;\\n overflow: auto;\\n top: 0;\\n left: 0;\\n background: \").concat(dt('autocomplete.overlay.background'), \";\\n color: \").concat(dt('autocomplete.overlay.color'), \";\\n border: 1px solid \").concat(dt('autocomplete.overlay.border.color'), \";\\n border-radius: \").concat(dt('autocomplete.overlay.border.radius'), \";\\n box-shadow: \").concat(dt('autocomplete.overlay.shadow'), \";\\n}\\n\\n.p-autocomplete-list {\\n margin: 0;\\n padding: 0;\\n list-style-type: none;\\n display: flex;\\n flex-direction: column;\\n gap: \").concat(dt('autocomplete.list.gap'), \";\\n padding: \").concat(dt('autocomplete.list.padding'), \";\\n}\\n\\n.p-autocomplete-option {\\n cursor: pointer;\\n white-space: nowrap;\\n position: relative;\\n overflow: hidden;\\n display: flex;\\n align-items: center;\\n padding: \").concat(dt('autocomplete.option.padding'), \";\\n border: 0 none;\\n color: \").concat(dt('autocomplete.option.color'), \";\\n background: transparent;\\n transition: background \").concat(dt('autocomplete.transition.duration'), \", color \").concat(dt('autocomplete.transition.duration'), \", border-color \").concat(dt('autocomplete.transition.duration'), \";\\n border-radius: \").concat(dt('autocomplete.option.border.radius'), \";\\n}\\n\\n.p-autocomplete-option:not(.p-autocomplete-option-selected):not(.p-disabled).p-focus {\\n background: \").concat(dt('autocomplete.option.focus.background'), \";\\n color: \").concat(dt('autocomplete.option.focus.color'), \";\\n}\\n\\n.p-autocomplete-option-selected {\\n background: \").concat(dt('autocomplete.option.selected.background'), \";\\n color: \").concat(dt('autocomplete.option.selected.color'), \";\\n}\\n\\n.p-autocomplete-option-selected.p-focus {\\n background: \").concat(dt('autocomplete.option.selected.focus.background'), \";\\n color: \").concat(dt('autocomplete.option.selected.focus.color'), \";\\n}\\n\\n.p-autocomplete-option-group {\\n margin: 0;\\n padding: \").concat(dt('autocomplete.option.group.padding'), \";\\n color: \").concat(dt('autocomplete.option.group.color'), \";\\n background: \").concat(dt('autocomplete.option.group.background'), \";\\n font-weight: \").concat(dt('autocomplete.option.group.font.weight'), \";\\n}\\n\\n.p-autocomplete-input-multiple {\\n margin: 0;\\n list-style-type: none;\\n cursor: text;\\n overflow: hidden;\\n display: flex;\\n align-items: center;\\n flex-wrap: wrap;\\n padding: calc(\").concat(dt('autocomplete.padding.y'), \" / 2) \").concat(dt('autocomplete.padding.x'), \";\\n gap: calc(\").concat(dt('autocomplete.padding.y'), \" / 2);\\n color: \").concat(dt('autocomplete.color'), \";\\n background: \").concat(dt('autocomplete.background'), \";\\n border: 1px solid \").concat(dt('autocomplete.border.color'), \";\\n border-radius: \").concat(dt('autocomplete.border.radius'), \";\\n width: 100%;\\n transition: background \").concat(dt('autocomplete.transition.duration'), \", color \").concat(dt('autocomplete.transition.duration'), \", border-color \").concat(dt('autocomplete.transition.duration'), \", outline-color \").concat(dt('autocomplete.transition.duration'), \", box-shadow \").concat(dt('autocomplete.transition.duration'), \";\\n outline-color: transparent;\\n box-shadow: \").concat(dt('autocomplete.shadow'), \";\\n}\\n\\n.p-autocomplete:not(.p-disabled):hover .p-autocomplete-input-multiple {\\n border-color: \").concat(dt('autocomplete.hover.border.color'), \";\\n}\\n\\n.p-autocomplete:not(.p-disabled).p-focus .p-autocomplete-input-multiple {\\n border-color: \").concat(dt('autocomplete.focus.border.color'), \";\\n box-shadow: \").concat(dt('autocomplete.focus.ring.shadow'), \";\\n outline: \").concat(dt('autocomplete.focus.ring.width'), \" \").concat(dt('autocomplete.focus.ring.style'), \" \").concat(dt('autocomplete.focus.ring.color'), \";\\n outline-offset: \").concat(dt('autocomplete.focus.ring.offset'), \";\\n}\\n\\n.p-autocomplete.p-invalid .p-autocomplete-input-multiple {\\n border-color: \").concat(dt('autocomplete.invalid.border.color'), \";\\n}\\n\\n.p-variant-filled.p-autocomplete-input-multiple {\\n background: \").concat(dt('autocomplete.filled.background'), \";\\n}\\n\\n.p-autocomplete:not(.p-disabled).p-focus .p-variant-filled.p-autocomplete-input-multiple {\\n background: \").concat(dt('autocomplete.filled.focus.background'), \";\\n}\\n\\n.p-autocomplete.p-disabled .p-autocomplete-input-multiple {\\n opacity: 1;\\n background: \").concat(dt('autocomplete.disabled.background'), \";\\n color: \").concat(dt('autocomplete.disabled.color'), \";\\n}\\n\\n.p-autocomplete-chip.p-chip {\\n padding-top: calc(\").concat(dt('autocomplete.padding.y'), \" / 2);\\n padding-bottom: calc(\").concat(dt('autocomplete.padding.y'), \" / 2);\\n border-radius: \").concat(dt('autocomplete.chip.border.radius'), \";\\n}\\n\\n.p-autocomplete-input-multiple:has(.p-autocomplete-chip) {\\n padding-left: calc(\").concat(dt('autocomplete.padding.y'), \" / 2);\\n padding-right: calc(\").concat(dt('autocomplete.padding.y'), \" / 2);\\n}\\n\\n.p-autocomplete-chip-item.p-focus .p-autocomplete-chip {\\n background: \").concat(dt('inputchips.chip.focus.background'), \";\\n color: \").concat(dt('inputchips.chip.focus.color'), \";\\n}\\n\\n.p-autocomplete-input-chip {\\n flex: 1 1 auto;\\n display: inline-flex;\\n padding-top: calc(\").concat(dt('autocomplete.padding.y'), \" / 2);\\n padding-bottom: calc(\").concat(dt('autocomplete.padding.y'), \" / 2);\\n}\\n\\n.p-autocomplete-input-chip input {\\n border: 0 none;\\n outline: 0 none;\\n background: transparent;\\n margin: 0;\\n padding: 0;\\n box-shadow: none;\\n border-radius: 0;\\n width: 100%;\\n font-family: inherit;\\n font-feature-settings: inherit;\\n font-size: 1rem;\\n color: inherit;\\n}\\n\\n.p-autocomplete-input-chip input::placeholder {\\n color: \").concat(dt('autocomplete.placeholder.color'), \";\\n}\\n\\n.p-autocomplete-empty-message {\\n padding: \").concat(dt('autocomplete.empty.message.padding'), \";\\n}\\n\\n.p-autocomplete-fluid {\\n display: flex;\\n}\\n\\n.p-autocomplete-fluid:has(.p-autocomplete-dropdown) .p-autocomplete-input {\\n width: 1%;\\n}\\n\");\n};\nvar inlineStyles = {\n root: {\n position: 'relative'\n }\n};\nvar classes = {\n root: function root(_ref2) {\n var instance = _ref2.instance,\n props = _ref2.props;\n return ['p-autocomplete p-component p-inputwrapper', {\n 'p-disabled': props.disabled,\n 'p-invalid': props.invalid,\n 'p-focus': instance.focused,\n 'p-inputwrapper-filled': props.modelValue || isNotEmpty(instance.inputValue),\n 'p-inputwrapper-focus': instance.focused,\n 'p-autocomplete-open': instance.overlayVisible,\n 'p-autocomplete-fluid': props.fluid\n }];\n },\n pcInput: 'p-autocomplete-input',\n inputMultiple: function inputMultiple(_ref3) {\n var props = _ref3.props,\n instance = _ref3.instance;\n return ['p-autocomplete-input-multiple', {\n 'p-variant-filled': props.variant ? props.variant === 'filled' : instance.$primevue.config.inputStyle === 'filled' || instance.$primevue.config.inputVariant === 'filled'\n }];\n },\n chipItem: function chipItem(_ref4) {\n var instance = _ref4.instance,\n i = _ref4.i;\n return ['p-autocomplete-chip-item', {\n 'p-focus': instance.focusedMultipleOptionIndex === i\n }];\n },\n pcChip: 'p-autocomplete-chip',\n chipIcon: 'p-autocomplete-chip-icon',\n inputChip: 'p-autocomplete-input-chip',\n loader: 'p-autocomplete-loader',\n dropdown: 'p-autocomplete-dropdown',\n overlay: 'p-autocomplete-overlay p-component',\n list: 'p-autocomplete-list',\n optionGroup: 'p-autocomplete-option-group',\n option: function option(_ref5) {\n var instance = _ref5.instance,\n _option = _ref5.option,\n i = _ref5.i,\n getItemOptions = _ref5.getItemOptions;\n return ['p-autocomplete-option', {\n 'p-autocomplete-option-selected': instance.isSelected(_option),\n 'p-focus': instance.focusedOptionIndex === instance.getOptionIndex(i, getItemOptions),\n 'p-disabled': instance.isOptionDisabled(_option)\n }];\n },\n emptyMessage: 'p-autocomplete-empty-message'\n};\nvar AutoCompleteStyle = BaseStyle.extend({\n name: 'autocomplete',\n theme: theme,\n classes: classes,\n inlineStyles: inlineStyles\n});\n\nexport { AutoCompleteStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import { UniqueComponentId, ConnectedOverlayScrollHandler } from '@primevue/core/utils';\nimport { focus, addStyle, relativePosition, getOuterWidth, absolutePosition, isTouchDevice, findSingle } from '@primeuix/utils/dom';\nimport { resolveFieldData, isEmpty, isNotEmpty, equals, findLastIndex } from '@primeuix/utils/object';\nimport { ZIndex } from '@primeuix/utils/zindex';\nimport ChevronDownIcon from '@primevue/icons/chevrondown';\nimport SpinnerIcon from '@primevue/icons/spinner';\nimport Chip from 'primevue/chip';\nimport InputText from 'primevue/inputtext';\nimport OverlayEventBus from 'primevue/overlayeventbus';\nimport Portal from 'primevue/portal';\nimport Ripple from 'primevue/ripple';\nimport VirtualScroller from 'primevue/virtualscroller';\nimport BaseComponent from '@primevue/core/basecomponent';\nimport AutoCompleteStyle from 'primevue/autocomplete/style';\nimport { resolveComponent, resolveDirective, openBlock, createElementBlock, mergeProps, createBlock, normalizeClass, normalizeStyle, createCommentVNode, Fragment, renderList, renderSlot, createVNode, withCtx, createElementVNode, resolveDynamicComponent, toDisplayString, Transition, createSlots, createTextVNode, withDirectives } from 'vue';\n\nvar script$1 = {\n name: 'BaseAutoComplete',\n \"extends\": BaseComponent,\n props: {\n modelValue: null,\n suggestions: {\n type: Array,\n \"default\": null\n },\n optionLabel: null,\n optionDisabled: null,\n optionGroupLabel: null,\n optionGroupChildren: null,\n scrollHeight: {\n type: String,\n \"default\": '14rem'\n },\n dropdown: {\n type: Boolean,\n \"default\": false\n },\n dropdownMode: {\n type: String,\n \"default\": 'blank'\n },\n multiple: {\n type: Boolean,\n \"default\": false\n },\n loading: {\n type: Boolean,\n \"default\": false\n },\n variant: {\n type: String,\n \"default\": null\n },\n invalid: {\n type: Boolean,\n \"default\": false\n },\n disabled: {\n type: Boolean,\n \"default\": false\n },\n placeholder: {\n type: String,\n \"default\": null\n },\n dataKey: {\n type: String,\n \"default\": null\n },\n minLength: {\n type: Number,\n \"default\": 1\n },\n delay: {\n type: Number,\n \"default\": 300\n },\n appendTo: {\n type: [String, Object],\n \"default\": 'body'\n },\n forceSelection: {\n type: Boolean,\n \"default\": false\n },\n completeOnFocus: {\n type: Boolean,\n \"default\": false\n },\n inputId: {\n type: String,\n \"default\": null\n },\n inputStyle: {\n type: Object,\n \"default\": null\n },\n inputClass: {\n type: [String, Object],\n \"default\": null\n },\n panelStyle: {\n type: Object,\n \"default\": null\n },\n panelClass: {\n type: [String, Object],\n \"default\": null\n },\n overlayStyle: {\n type: Object,\n \"default\": null\n },\n overlayClass: {\n type: [String, Object],\n \"default\": null\n },\n dropdownIcon: {\n type: String,\n \"default\": null\n },\n dropdownClass: {\n type: [String, Object],\n \"default\": null\n },\n loader: {\n type: String,\n \"default\": null\n },\n loadingIcon: {\n type: String,\n \"default\": null\n },\n removeTokenIcon: {\n type: String,\n \"default\": null\n },\n chipIcon: {\n type: String,\n \"default\": null\n },\n virtualScrollerOptions: {\n type: Object,\n \"default\": null\n },\n autoOptionFocus: {\n type: Boolean,\n \"default\": false\n },\n selectOnFocus: {\n type: Boolean,\n \"default\": false\n },\n focusOnHover: {\n type: Boolean,\n \"default\": true\n },\n searchLocale: {\n type: String,\n \"default\": undefined\n },\n searchMessage: {\n type: String,\n \"default\": null\n },\n selectionMessage: {\n type: String,\n \"default\": null\n },\n emptySelectionMessage: {\n type: String,\n \"default\": null\n },\n emptySearchMessage: {\n type: String,\n \"default\": null\n },\n tabindex: {\n type: Number,\n \"default\": 0\n },\n typeahead: {\n type: Boolean,\n \"default\": true\n },\n ariaLabel: {\n type: String,\n \"default\": null\n },\n ariaLabelledby: {\n type: String,\n \"default\": null\n },\n fluid: {\n type: Boolean,\n \"default\": false\n }\n },\n style: AutoCompleteStyle,\n provide: function provide() {\n return {\n $pcAutoComplete: this,\n $parentInstance: this\n };\n }\n};\n\nfunction _typeof$1(o) { \"@babel/helpers - typeof\"; return _typeof$1 = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof$1(o); }\nfunction _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _unsupportedIterableToArray(r, a) { if (r) { if (\"string\" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return \"Object\" === t && r.constructor && (t = r.constructor.name), \"Map\" === t || \"Set\" === t ? Array.from(r) : \"Arguments\" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }\nfunction _iterableToArray(r) { if (\"undefined\" != typeof Symbol && null != r[Symbol.iterator] || null != r[\"@@iterator\"]) return Array.from(r); }\nfunction _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }\nfunction _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }\nvar script = {\n name: 'AutoComplete',\n \"extends\": script$1,\n inheritAttrs: false,\n emits: ['update:modelValue', 'change', 'focus', 'blur', 'item-select', 'item-unselect', 'option-select', 'option-unselect', 'dropdown-click', 'clear', 'complete', 'before-show', 'before-hide', 'show', 'hide'],\n outsideClickListener: null,\n resizeListener: null,\n scrollHandler: null,\n overlay: null,\n virtualScroller: null,\n searchTimeout: null,\n dirty: false,\n data: function data() {\n return {\n id: this.$attrs.id,\n clicked: false,\n focused: false,\n focusedOptionIndex: -1,\n focusedMultipleOptionIndex: -1,\n overlayVisible: false,\n searching: false\n };\n },\n watch: {\n '$attrs.id': function $attrsId(newValue) {\n this.id = newValue || UniqueComponentId();\n },\n suggestions: function suggestions() {\n if (this.searching) {\n this.show();\n this.focusedOptionIndex = this.overlayVisible && this.autoOptionFocus ? this.findFirstFocusedOptionIndex() : -1;\n this.searching = false;\n }\n this.autoUpdateModel();\n }\n },\n mounted: function mounted() {\n this.id = this.id || UniqueComponentId();\n this.autoUpdateModel();\n },\n updated: function updated() {\n if (this.overlayVisible) {\n this.alignOverlay();\n }\n },\n beforeUnmount: function beforeUnmount() {\n this.unbindOutsideClickListener();\n this.unbindResizeListener();\n if (this.scrollHandler) {\n this.scrollHandler.destroy();\n this.scrollHandler = null;\n }\n if (this.overlay) {\n ZIndex.clear(this.overlay);\n this.overlay = null;\n }\n },\n methods: {\n getOptionIndex: function getOptionIndex(index, fn) {\n return this.virtualScrollerDisabled ? index : fn && fn(index)['index'];\n },\n getOptionLabel: function getOptionLabel(option) {\n return this.optionLabel ? resolveFieldData(option, this.optionLabel) : option;\n },\n getOptionValue: function getOptionValue(option) {\n return option; // TODO: The 'optionValue' properties can be added.\n },\n getOptionRenderKey: function getOptionRenderKey(option, index) {\n return (this.dataKey ? resolveFieldData(option, this.dataKey) : this.getOptionLabel(option)) + '_' + index;\n },\n getPTOptions: function getPTOptions(option, itemOptions, index, key) {\n return this.ptm(key, {\n context: {\n selected: this.isSelected(option),\n focused: this.focusedOptionIndex === this.getOptionIndex(index, itemOptions),\n disabled: this.isOptionDisabled(option)\n }\n });\n },\n isOptionDisabled: function isOptionDisabled(option) {\n return this.optionDisabled ? resolveFieldData(option, this.optionDisabled) : false;\n },\n isOptionGroup: function isOptionGroup(option) {\n return this.optionGroupLabel && option.optionGroup && option.group;\n },\n getOptionGroupLabel: function getOptionGroupLabel(optionGroup) {\n return resolveFieldData(optionGroup, this.optionGroupLabel);\n },\n getOptionGroupChildren: function getOptionGroupChildren(optionGroup) {\n return resolveFieldData(optionGroup, this.optionGroupChildren);\n },\n getAriaPosInset: function getAriaPosInset(index) {\n var _this = this;\n return (this.optionGroupLabel ? index - this.visibleOptions.slice(0, index).filter(function (option) {\n return _this.isOptionGroup(option);\n }).length : index) + 1;\n },\n show: function show(isFocus) {\n this.$emit('before-show');\n this.dirty = true;\n this.overlayVisible = true;\n this.focusedOptionIndex = this.focusedOptionIndex !== -1 ? this.focusedOptionIndex : this.autoOptionFocus ? this.findFirstFocusedOptionIndex() : -1;\n isFocus && focus(this.multiple ? this.$refs.focusInput : this.$refs.focusInput.$el);\n },\n hide: function hide(isFocus) {\n var _this2 = this;\n var _hide = function _hide() {\n _this2.$emit('before-hide');\n _this2.dirty = isFocus;\n _this2.overlayVisible = false;\n _this2.clicked = false;\n _this2.focusedOptionIndex = -1;\n isFocus && focus(_this2.multiple ? _this2.$refs.focusInput : _this2.$refs.focusInput.$el);\n };\n setTimeout(function () {\n _hide();\n }, 0); // For ScreenReaders\n },\n onFocus: function onFocus(event) {\n if (this.disabled) {\n // For ScreenReaders\n return;\n }\n if (!this.dirty && this.completeOnFocus) {\n this.search(event, event.target.value, 'focus');\n }\n this.dirty = true;\n this.focused = true;\n if (this.overlayVisible) {\n this.focusedOptionIndex = this.focusedOptionIndex !== -1 ? this.focusedOptionIndex : this.overlayVisible && this.autoOptionFocus ? this.findFirstFocusedOptionIndex() : -1;\n this.scrollInView(this.focusedOptionIndex);\n }\n this.$emit('focus', event);\n },\n onBlur: function onBlur(event) {\n this.dirty = false;\n this.focused = false;\n this.focusedOptionIndex = -1;\n this.$emit('blur', event);\n },\n onKeyDown: function onKeyDown(event) {\n if (this.disabled) {\n event.preventDefault();\n return;\n }\n switch (event.code) {\n case 'ArrowDown':\n this.onArrowDownKey(event);\n break;\n case 'ArrowUp':\n this.onArrowUpKey(event);\n break;\n case 'ArrowLeft':\n this.onArrowLeftKey(event);\n break;\n case 'ArrowRight':\n this.onArrowRightKey(event);\n break;\n case 'Home':\n this.onHomeKey(event);\n break;\n case 'End':\n this.onEndKey(event);\n break;\n case 'PageDown':\n this.onPageDownKey(event);\n break;\n case 'PageUp':\n this.onPageUpKey(event);\n break;\n case 'Enter':\n case 'NumpadEnter':\n this.onEnterKey(event);\n break;\n case 'Escape':\n this.onEscapeKey(event);\n break;\n case 'Tab':\n this.onTabKey(event);\n break;\n case 'Backspace':\n this.onBackspaceKey(event);\n break;\n }\n this.clicked = false;\n },\n onInput: function onInput(event) {\n var _this3 = this;\n if (this.typeahead) {\n if (this.searchTimeout) {\n clearTimeout(this.searchTimeout);\n }\n var query = event.target.value;\n if (!this.multiple) {\n this.updateModel(event, query);\n }\n if (query.length === 0) {\n this.hide();\n this.$emit('clear');\n } else {\n if (query.length >= this.minLength) {\n this.focusedOptionIndex = -1;\n this.searchTimeout = setTimeout(function () {\n _this3.search(event, query, 'input');\n }, this.delay);\n } else {\n this.hide();\n }\n }\n }\n },\n onChange: function onChange(event) {\n var _this4 = this;\n if (this.forceSelection) {\n var valid = false;\n\n // when forceSelection is on, prevent called twice onOptionSelect()\n if (this.visibleOptions && !this.multiple) {\n var value = this.multiple ? this.$refs.focusInput.value : this.$refs.focusInput.$el.value;\n var matchedValue = this.visibleOptions.find(function (option) {\n return _this4.isOptionMatched(option, value || '');\n });\n if (matchedValue !== undefined) {\n valid = true;\n !this.isSelected(matchedValue) && this.onOptionSelect(event, matchedValue);\n }\n }\n if (!valid) {\n if (this.multiple) this.$refs.focusInput.value = '';else this.$refs.focusInput.$el.value = '';\n this.$emit('clear');\n !this.multiple && this.updateModel(event, null);\n }\n }\n },\n onMultipleContainerFocus: function onMultipleContainerFocus() {\n if (this.disabled) {\n // For ScreenReaders\n return;\n }\n this.focused = true;\n },\n onMultipleContainerBlur: function onMultipleContainerBlur() {\n this.focusedMultipleOptionIndex = -1;\n this.focused = false;\n },\n onMultipleContainerKeyDown: function onMultipleContainerKeyDown(event) {\n if (this.disabled) {\n event.preventDefault();\n return;\n }\n switch (event.code) {\n case 'ArrowLeft':\n this.onArrowLeftKeyOnMultiple(event);\n break;\n case 'ArrowRight':\n this.onArrowRightKeyOnMultiple(event);\n break;\n case 'Backspace':\n this.onBackspaceKeyOnMultiple(event);\n break;\n }\n },\n onContainerClick: function onContainerClick(event) {\n this.clicked = true;\n if (this.disabled || this.searching || this.loading || this.isInputClicked(event) || this.isDropdownClicked(event)) {\n return;\n }\n if (!this.overlay || !this.overlay.contains(event.target)) {\n focus(this.multiple ? this.$refs.focusInput : this.$refs.focusInput.$el);\n }\n },\n onDropdownClick: function onDropdownClick(event) {\n var query = undefined;\n if (this.overlayVisible) {\n this.hide(true);\n } else {\n focus(this.multiple ? this.$refs.focusInput : this.$refs.focusInput.$el);\n query = this.$refs.focusInput.$el.value;\n if (this.dropdownMode === 'blank') this.search(event, '', 'dropdown');else if (this.dropdownMode === 'current') this.search(event, query, 'dropdown');\n }\n this.$emit('dropdown-click', {\n originalEvent: event,\n query: query\n });\n },\n onOptionSelect: function onOptionSelect(event, option) {\n var isHide = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;\n var value = this.getOptionValue(option);\n if (this.multiple) {\n this.$refs.focusInput.value = '';\n if (!this.isSelected(option)) {\n this.updateModel(event, [].concat(_toConsumableArray(this.modelValue || []), [value]));\n }\n } else {\n this.updateModel(event, value);\n }\n this.$emit('item-select', {\n originalEvent: event,\n value: option\n });\n this.$emit('option-select', {\n originalEvent: event,\n value: option\n });\n isHide && this.hide(true);\n },\n onOptionMouseMove: function onOptionMouseMove(event, index) {\n if (this.focusOnHover) {\n this.changeFocusedOptionIndex(event, index);\n }\n },\n onOverlayClick: function onOverlayClick(event) {\n OverlayEventBus.emit('overlay-click', {\n originalEvent: event,\n target: this.$el\n });\n },\n onOverlayKeyDown: function onOverlayKeyDown(event) {\n switch (event.code) {\n case 'Escape':\n this.onEscapeKey(event);\n break;\n }\n },\n onArrowDownKey: function onArrowDownKey(event) {\n if (!this.overlayVisible) {\n return;\n }\n var optionIndex = this.focusedOptionIndex !== -1 ? this.findNextOptionIndex(this.focusedOptionIndex) : this.clicked ? this.findFirstOptionIndex() : this.findFirstFocusedOptionIndex();\n this.changeFocusedOptionIndex(event, optionIndex);\n event.preventDefault();\n },\n onArrowUpKey: function onArrowUpKey(event) {\n if (!this.overlayVisible) {\n return;\n }\n if (event.altKey) {\n if (this.focusedOptionIndex !== -1) {\n this.onOptionSelect(event, this.visibleOptions[this.focusedOptionIndex]);\n }\n this.overlayVisible && this.hide();\n event.preventDefault();\n } else {\n var optionIndex = this.focusedOptionIndex !== -1 ? this.findPrevOptionIndex(this.focusedOptionIndex) : this.clicked ? this.findLastOptionIndex() : this.findLastFocusedOptionIndex();\n this.changeFocusedOptionIndex(event, optionIndex);\n event.preventDefault();\n }\n },\n onArrowLeftKey: function onArrowLeftKey(event) {\n var target = event.currentTarget;\n this.focusedOptionIndex = -1;\n if (this.multiple) {\n if (isEmpty(target.value) && this.hasSelectedOption) {\n focus(this.$refs.multiContainer);\n this.focusedMultipleOptionIndex = this.modelValue.length;\n } else {\n event.stopPropagation(); // To prevent onArrowLeftKeyOnMultiple method\n }\n }\n },\n onArrowRightKey: function onArrowRightKey(event) {\n this.focusedOptionIndex = -1;\n this.multiple && event.stopPropagation(); // To prevent onArrowRightKeyOnMultiple method\n },\n onHomeKey: function onHomeKey(event) {\n var currentTarget = event.currentTarget;\n var len = currentTarget.value.length;\n currentTarget.setSelectionRange(0, event.shiftKey ? len : 0);\n this.focusedOptionIndex = -1;\n event.preventDefault();\n },\n onEndKey: function onEndKey(event) {\n var currentTarget = event.currentTarget;\n var len = currentTarget.value.length;\n currentTarget.setSelectionRange(event.shiftKey ? 0 : len, len);\n this.focusedOptionIndex = -1;\n event.preventDefault();\n },\n onPageUpKey: function onPageUpKey(event) {\n this.scrollInView(0);\n event.preventDefault();\n },\n onPageDownKey: function onPageDownKey(event) {\n this.scrollInView(this.visibleOptions.length - 1);\n event.preventDefault();\n },\n onEnterKey: function onEnterKey(event) {\n if (!this.typeahead) {\n if (this.multiple) {\n this.updateModel(event, [].concat(_toConsumableArray(this.modelValue || []), [event.target.value]));\n this.$refs.focusInput.value = '';\n }\n } else {\n if (!this.overlayVisible) {\n this.focusedOptionIndex = -1; // reset\n this.onArrowDownKey(event);\n } else {\n if (this.focusedOptionIndex !== -1) {\n this.onOptionSelect(event, this.visibleOptions[this.focusedOptionIndex]);\n }\n this.hide();\n }\n }\n },\n onEscapeKey: function onEscapeKey(event) {\n this.overlayVisible && this.hide(true);\n event.preventDefault();\n },\n onTabKey: function onTabKey(event) {\n if (this.focusedOptionIndex !== -1) {\n this.onOptionSelect(event, this.visibleOptions[this.focusedOptionIndex]);\n }\n this.overlayVisible && this.hide();\n },\n onBackspaceKey: function onBackspaceKey(event) {\n if (this.multiple) {\n if (isNotEmpty(this.modelValue) && !this.$refs.focusInput.value) {\n var removedValue = this.modelValue[this.modelValue.length - 1];\n var newValue = this.modelValue.slice(0, -1);\n this.$emit('update:modelValue', newValue);\n this.$emit('item-unselect', {\n originalEvent: event,\n value: removedValue\n });\n this.$emit('option-unselect', {\n originalEvent: event,\n value: removedValue\n });\n }\n event.stopPropagation(); // To prevent onBackspaceKeyOnMultiple method\n }\n },\n onArrowLeftKeyOnMultiple: function onArrowLeftKeyOnMultiple() {\n this.focusedMultipleOptionIndex = this.focusedMultipleOptionIndex < 1 ? 0 : this.focusedMultipleOptionIndex - 1;\n },\n onArrowRightKeyOnMultiple: function onArrowRightKeyOnMultiple() {\n this.focusedMultipleOptionIndex++;\n if (this.focusedMultipleOptionIndex > this.modelValue.length - 1) {\n this.focusedMultipleOptionIndex = -1;\n focus(this.$refs.focusInput);\n }\n },\n onBackspaceKeyOnMultiple: function onBackspaceKeyOnMultiple(event) {\n if (this.focusedMultipleOptionIndex !== -1) {\n this.removeOption(event, this.focusedMultipleOptionIndex);\n }\n },\n onOverlayEnter: function onOverlayEnter(el) {\n ZIndex.set('overlay', el, this.$primevue.config.zIndex.overlay);\n addStyle(el, {\n position: 'absolute',\n top: '0',\n left: '0'\n });\n this.alignOverlay();\n },\n onOverlayAfterEnter: function onOverlayAfterEnter() {\n this.bindOutsideClickListener();\n this.bindScrollListener();\n this.bindResizeListener();\n this.$emit('show');\n },\n onOverlayLeave: function onOverlayLeave() {\n this.unbindOutsideClickListener();\n this.unbindScrollListener();\n this.unbindResizeListener();\n this.$emit('hide');\n this.overlay = null;\n },\n onOverlayAfterLeave: function onOverlayAfterLeave(el) {\n ZIndex.clear(el);\n },\n alignOverlay: function alignOverlay() {\n var target = this.multiple ? this.$refs.multiContainer : this.$refs.focusInput.$el;\n if (this.appendTo === 'self') {\n relativePosition(this.overlay, target);\n } else {\n this.overlay.style.minWidth = getOuterWidth(target) + 'px';\n absolutePosition(this.overlay, target);\n }\n },\n bindOutsideClickListener: function bindOutsideClickListener() {\n var _this5 = this;\n if (!this.outsideClickListener) {\n this.outsideClickListener = function (event) {\n if (_this5.overlayVisible && _this5.overlay && _this5.isOutsideClicked(event)) {\n _this5.hide();\n }\n };\n document.addEventListener('click', this.outsideClickListener);\n }\n },\n unbindOutsideClickListener: function unbindOutsideClickListener() {\n if (this.outsideClickListener) {\n document.removeEventListener('click', this.outsideClickListener);\n this.outsideClickListener = null;\n }\n },\n bindScrollListener: function bindScrollListener() {\n var _this6 = this;\n if (!this.scrollHandler) {\n this.scrollHandler = new ConnectedOverlayScrollHandler(this.$refs.container, function () {\n if (_this6.overlayVisible) {\n _this6.hide();\n }\n });\n }\n this.scrollHandler.bindScrollListener();\n },\n unbindScrollListener: function unbindScrollListener() {\n if (this.scrollHandler) {\n this.scrollHandler.unbindScrollListener();\n }\n },\n bindResizeListener: function bindResizeListener() {\n var _this7 = this;\n if (!this.resizeListener) {\n this.resizeListener = function () {\n if (_this7.overlayVisible && !isTouchDevice()) {\n _this7.hide();\n }\n };\n window.addEventListener('resize', this.resizeListener);\n }\n },\n unbindResizeListener: function unbindResizeListener() {\n if (this.resizeListener) {\n window.removeEventListener('resize', this.resizeListener);\n this.resizeListener = null;\n }\n },\n isOutsideClicked: function isOutsideClicked(event) {\n return !this.overlay.contains(event.target) && !this.isInputClicked(event) && !this.isDropdownClicked(event);\n },\n isInputClicked: function isInputClicked(event) {\n if (this.multiple) return event.target === this.$refs.multiContainer || this.$refs.multiContainer.contains(event.target);else return event.target === this.$refs.focusInput.$el;\n },\n isDropdownClicked: function isDropdownClicked(event) {\n return this.$refs.dropdownButton ? event.target === this.$refs.dropdownButton || this.$refs.dropdownButton.contains(event.target) : false;\n },\n isOptionMatched: function isOptionMatched(option, value) {\n var _this$getOptionLabel;\n return this.isValidOption(option) && ((_this$getOptionLabel = this.getOptionLabel(option)) === null || _this$getOptionLabel === void 0 ? void 0 : _this$getOptionLabel.toLocaleLowerCase(this.searchLocale)) === value.toLocaleLowerCase(this.searchLocale);\n },\n isValidOption: function isValidOption(option) {\n return isNotEmpty(option) && !(this.isOptionDisabled(option) || this.isOptionGroup(option));\n },\n isValidSelectedOption: function isValidSelectedOption(option) {\n return this.isValidOption(option) && this.isSelected(option);\n },\n isEquals: function isEquals(value1, value2) {\n return equals(value1, value2, this.equalityKey);\n },\n isSelected: function isSelected(option) {\n var _this8 = this;\n var optionValue = this.getOptionValue(option);\n return this.multiple ? (this.modelValue || []).some(function (value) {\n return _this8.isEquals(value, optionValue);\n }) : this.isEquals(this.modelValue, this.getOptionValue(option));\n },\n findFirstOptionIndex: function findFirstOptionIndex() {\n var _this9 = this;\n return this.visibleOptions.findIndex(function (option) {\n return _this9.isValidOption(option);\n });\n },\n findLastOptionIndex: function findLastOptionIndex() {\n var _this10 = this;\n return findLastIndex(this.visibleOptions, function (option) {\n return _this10.isValidOption(option);\n });\n },\n findNextOptionIndex: function findNextOptionIndex(index) {\n var _this11 = this;\n var matchedOptionIndex = index < this.visibleOptions.length - 1 ? this.visibleOptions.slice(index + 1).findIndex(function (option) {\n return _this11.isValidOption(option);\n }) : -1;\n return matchedOptionIndex > -1 ? matchedOptionIndex + index + 1 : index;\n },\n findPrevOptionIndex: function findPrevOptionIndex(index) {\n var _this12 = this;\n var matchedOptionIndex = index > 0 ? findLastIndex(this.visibleOptions.slice(0, index), function (option) {\n return _this12.isValidOption(option);\n }) : -1;\n return matchedOptionIndex > -1 ? matchedOptionIndex : index;\n },\n findSelectedOptionIndex: function findSelectedOptionIndex() {\n var _this13 = this;\n return this.hasSelectedOption ? this.visibleOptions.findIndex(function (option) {\n return _this13.isValidSelectedOption(option);\n }) : -1;\n },\n findFirstFocusedOptionIndex: function findFirstFocusedOptionIndex() {\n var selectedIndex = this.findSelectedOptionIndex();\n return selectedIndex < 0 ? this.findFirstOptionIndex() : selectedIndex;\n },\n findLastFocusedOptionIndex: function findLastFocusedOptionIndex() {\n var selectedIndex = this.findSelectedOptionIndex();\n return selectedIndex < 0 ? this.findLastOptionIndex() : selectedIndex;\n },\n search: function search(event, query, source) {\n //allow empty string but not undefined or null\n if (query === undefined || query === null) {\n return;\n }\n\n //do not search blank values on input change\n if (source === 'input' && query.trim().length === 0) {\n return;\n }\n this.searching = true;\n this.$emit('complete', {\n originalEvent: event,\n query: query\n });\n },\n removeOption: function removeOption(event, index) {\n var _this14 = this;\n var removedOption = this.modelValue[index];\n var value = this.modelValue.filter(function (_, i) {\n return i !== index;\n }).map(function (option) {\n return _this14.getOptionValue(option);\n });\n this.updateModel(event, value);\n this.$emit('item-unselect', {\n originalEvent: event,\n value: removedOption\n });\n this.$emit('option-unselect', {\n originalEvent: event,\n value: removedOption\n });\n this.dirty = true;\n focus(this.multiple ? this.$refs.focusInput : this.$refs.focusInput.$el);\n },\n changeFocusedOptionIndex: function changeFocusedOptionIndex(event, index) {\n if (this.focusedOptionIndex !== index) {\n this.focusedOptionIndex = index;\n this.scrollInView();\n if (this.selectOnFocus) {\n this.onOptionSelect(event, this.visibleOptions[index], false);\n }\n }\n },\n scrollInView: function scrollInView() {\n var _this15 = this;\n var index = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : -1;\n this.$nextTick(function () {\n var id = index !== -1 ? \"\".concat(_this15.id, \"_\").concat(index) : _this15.focusedOptionId;\n var element = findSingle(_this15.list, \"li[id=\\\"\".concat(id, \"\\\"]\"));\n if (element) {\n element.scrollIntoView && element.scrollIntoView({\n block: 'nearest',\n inline: 'start'\n });\n } else if (!_this15.virtualScrollerDisabled) {\n _this15.virtualScroller && _this15.virtualScroller.scrollToIndex(index !== -1 ? index : _this15.focusedOptionIndex);\n }\n });\n },\n autoUpdateModel: function autoUpdateModel() {\n if (this.selectOnFocus && this.autoOptionFocus && !this.hasSelectedOption) {\n this.focusedOptionIndex = this.findFirstFocusedOptionIndex();\n this.onOptionSelect(null, this.visibleOptions[this.focusedOptionIndex], false);\n }\n },\n updateModel: function updateModel(event, value) {\n this.$emit('update:modelValue', value);\n this.$emit('change', {\n originalEvent: event,\n value: value\n });\n },\n flatOptions: function flatOptions(options) {\n var _this16 = this;\n return (options || []).reduce(function (result, option, index) {\n result.push({\n optionGroup: option,\n group: true,\n index: index\n });\n var optionGroupChildren = _this16.getOptionGroupChildren(option);\n optionGroupChildren && optionGroupChildren.forEach(function (o) {\n return result.push(o);\n });\n return result;\n }, []);\n },\n overlayRef: function overlayRef(el) {\n this.overlay = el;\n },\n listRef: function listRef(el, contentRef) {\n this.list = el;\n contentRef && contentRef(el); // For VirtualScroller\n },\n virtualScrollerRef: function virtualScrollerRef(el) {\n this.virtualScroller = el;\n }\n },\n computed: {\n visibleOptions: function visibleOptions() {\n return this.optionGroupLabel ? this.flatOptions(this.suggestions) : this.suggestions || [];\n },\n inputValue: function inputValue() {\n if (isNotEmpty(this.modelValue)) {\n if (_typeof$1(this.modelValue) === 'object') {\n var label = this.getOptionLabel(this.modelValue);\n return label != null ? label : this.modelValue;\n } else {\n return this.modelValue;\n }\n } else {\n return '';\n }\n },\n hasSelectedOption: function hasSelectedOption() {\n return isNotEmpty(this.modelValue);\n },\n equalityKey: function equalityKey() {\n return this.dataKey; // TODO: The 'optionValue' properties can be added.\n },\n searchResultMessageText: function searchResultMessageText() {\n return isNotEmpty(this.visibleOptions) && this.overlayVisible ? this.searchMessageText.replaceAll('{0}', this.visibleOptions.length) : this.emptySearchMessageText;\n },\n searchMessageText: function searchMessageText() {\n return this.searchMessage || this.$primevue.config.locale.searchMessage || '';\n },\n emptySearchMessageText: function emptySearchMessageText() {\n return this.emptySearchMessage || this.$primevue.config.locale.emptySearchMessage || '';\n },\n selectionMessageText: function selectionMessageText() {\n return this.selectionMessage || this.$primevue.config.locale.selectionMessage || '';\n },\n emptySelectionMessageText: function emptySelectionMessageText() {\n return this.emptySelectionMessage || this.$primevue.config.locale.emptySelectionMessage || '';\n },\n selectedMessageText: function selectedMessageText() {\n return this.hasSelectedOption ? this.selectionMessageText.replaceAll('{0}', this.multiple ? this.modelValue.length : '1') : this.emptySelectionMessageText;\n },\n listAriaLabel: function listAriaLabel() {\n return this.$primevue.config.locale.aria ? this.$primevue.config.locale.aria.listLabel : undefined;\n },\n focusedOptionId: function focusedOptionId() {\n return this.focusedOptionIndex !== -1 ? \"\".concat(this.id, \"_\").concat(this.focusedOptionIndex) : null;\n },\n focusedMultipleOptionId: function focusedMultipleOptionId() {\n return this.focusedMultipleOptionIndex !== -1 ? \"\".concat(this.id, \"_multiple_option_\").concat(this.focusedMultipleOptionIndex) : null;\n },\n ariaSetSize: function ariaSetSize() {\n var _this17 = this;\n return this.visibleOptions.filter(function (option) {\n return !_this17.isOptionGroup(option);\n }).length;\n },\n virtualScrollerDisabled: function virtualScrollerDisabled() {\n return !this.virtualScrollerOptions;\n },\n panelId: function panelId() {\n return this.id + '_panel';\n }\n },\n components: {\n InputText: InputText,\n VirtualScroller: VirtualScroller,\n Portal: Portal,\n ChevronDownIcon: ChevronDownIcon,\n SpinnerIcon: SpinnerIcon,\n Chip: Chip\n },\n directives: {\n ripple: Ripple\n }\n};\n\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nvar _hoisted_1 = [\"aria-activedescendant\"];\nvar _hoisted_2 = [\"id\", \"aria-label\", \"aria-setsize\", \"aria-posinset\"];\nvar _hoisted_3 = [\"id\", \"placeholder\", \"tabindex\", \"disabled\", \"aria-label\", \"aria-labelledby\", \"aria-expanded\", \"aria-controls\", \"aria-activedescendant\", \"aria-invalid\"];\nvar _hoisted_4 = [\"disabled\", \"aria-expanded\", \"aria-controls\"];\nvar _hoisted_5 = [\"id\"];\nvar _hoisted_6 = [\"id\", \"aria-label\"];\nvar _hoisted_7 = [\"id\"];\nvar _hoisted_8 = [\"id\", \"aria-label\", \"aria-selected\", \"aria-disabled\", \"aria-setsize\", \"aria-posinset\", \"onClick\", \"onMousemove\", \"data-p-selected\", \"data-p-focus\", \"data-p-disabled\"];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n var _component_InputText = resolveComponent(\"InputText\");\n var _component_Chip = resolveComponent(\"Chip\");\n var _component_SpinnerIcon = resolveComponent(\"SpinnerIcon\");\n var _component_VirtualScroller = resolveComponent(\"VirtualScroller\");\n var _component_Portal = resolveComponent(\"Portal\");\n var _directive_ripple = resolveDirective(\"ripple\");\n return openBlock(), createElementBlock(\"div\", mergeProps({\n ref: \"container\",\n \"class\": _ctx.cx('root'),\n style: _ctx.sx('root'),\n onClick: _cache[11] || (_cache[11] = function () {\n return $options.onContainerClick && $options.onContainerClick.apply($options, arguments);\n })\n }, _ctx.ptmi('root')), [!_ctx.multiple ? (openBlock(), createBlock(_component_InputText, {\n key: 0,\n ref: \"focusInput\",\n id: _ctx.inputId,\n type: \"text\",\n \"class\": normalizeClass([_ctx.cx('pcInput'), _ctx.inputClass]),\n style: normalizeStyle(_ctx.inputStyle),\n value: $options.inputValue,\n placeholder: _ctx.placeholder,\n tabindex: !_ctx.disabled ? _ctx.tabindex : -1,\n disabled: _ctx.disabled,\n invalid: _ctx.invalid,\n variant: _ctx.variant,\n autocomplete: \"off\",\n role: \"combobox\",\n \"aria-label\": _ctx.ariaLabel,\n \"aria-labelledby\": _ctx.ariaLabelledby,\n \"aria-haspopup\": \"listbox\",\n \"aria-autocomplete\": \"list\",\n \"aria-expanded\": $data.overlayVisible,\n \"aria-controls\": $options.panelId,\n \"aria-activedescendant\": $data.focused ? $options.focusedOptionId : undefined,\n onFocus: $options.onFocus,\n onBlur: $options.onBlur,\n onKeydown: $options.onKeyDown,\n onInput: $options.onInput,\n onChange: $options.onChange,\n unstyled: _ctx.unstyled,\n pt: _ctx.ptm('pcInput')\n }, null, 8, [\"id\", \"class\", \"style\", \"value\", \"placeholder\", \"tabindex\", \"disabled\", \"invalid\", \"variant\", \"aria-label\", \"aria-labelledby\", \"aria-expanded\", \"aria-controls\", \"aria-activedescendant\", \"onFocus\", \"onBlur\", \"onKeydown\", \"onInput\", \"onChange\", \"unstyled\", \"pt\"])) : createCommentVNode(\"\", true), _ctx.multiple ? (openBlock(), createElementBlock(\"ul\", mergeProps({\n key: 1,\n ref: \"multiContainer\",\n \"class\": _ctx.cx('inputMultiple'),\n tabindex: \"-1\",\n role: \"listbox\",\n \"aria-orientation\": \"horizontal\",\n \"aria-activedescendant\": $data.focused ? $options.focusedMultipleOptionId : undefined,\n onFocus: _cache[5] || (_cache[5] = function () {\n return $options.onMultipleContainerFocus && $options.onMultipleContainerFocus.apply($options, arguments);\n }),\n onBlur: _cache[6] || (_cache[6] = function () {\n return $options.onMultipleContainerBlur && $options.onMultipleContainerBlur.apply($options, arguments);\n }),\n onKeydown: _cache[7] || (_cache[7] = function () {\n return $options.onMultipleContainerKeyDown && $options.onMultipleContainerKeyDown.apply($options, arguments);\n })\n }, _ctx.ptm('inputMultiple')), [(openBlock(true), createElementBlock(Fragment, null, renderList(_ctx.modelValue, function (option, i) {\n return openBlock(), createElementBlock(\"li\", mergeProps({\n key: \"\".concat(i, \"_\").concat($options.getOptionLabel(option)),\n id: $data.id + '_multiple_option_' + i,\n \"class\": _ctx.cx('chipItem', {\n i: i\n }),\n role: \"option\",\n \"aria-label\": $options.getOptionLabel(option),\n \"aria-selected\": true,\n \"aria-setsize\": _ctx.modelValue.length,\n \"aria-posinset\": i + 1,\n ref_for: true\n }, _ctx.ptm('chipItem')), [renderSlot(_ctx.$slots, \"chip\", mergeProps({\n \"class\": _ctx.cx('pcChip'),\n value: option,\n index: i,\n removeCallback: function removeCallback(event) {\n return $options.removeOption(event, i);\n },\n ref_for: true\n }, _ctx.ptm('pcChip')), function () {\n return [createVNode(_component_Chip, {\n \"class\": normalizeClass(_ctx.cx('pcChip')),\n label: $options.getOptionLabel(option),\n removeIcon: _ctx.chipIcon || _ctx.removeTokenIcon,\n removable: \"\",\n unstyled: _ctx.unstyled,\n onRemove: function onRemove($event) {\n return $options.removeOption($event, i);\n },\n pt: _ctx.ptm('pcChip')\n }, {\n removeicon: withCtx(function () {\n return [renderSlot(_ctx.$slots, _ctx.$slots.chipicon ? 'chipicon' : 'removetokenicon', {\n \"class\": normalizeClass(_ctx.cx('chipIcon')),\n index: i,\n removeCallback: function removeCallback(event) {\n return $options.removeOption(event, i);\n }\n })];\n }),\n _: 2\n }, 1032, [\"class\", \"label\", \"removeIcon\", \"unstyled\", \"onRemove\", \"pt\"])];\n })], 16, _hoisted_2);\n }), 128)), createElementVNode(\"li\", mergeProps({\n \"class\": _ctx.cx('inputChip'),\n role: \"option\"\n }, _ctx.ptm('inputChip')), [createElementVNode(\"input\", mergeProps({\n ref: \"focusInput\",\n id: _ctx.inputId,\n type: \"text\",\n style: _ctx.inputStyle,\n \"class\": _ctx.inputClass,\n placeholder: _ctx.placeholder,\n tabindex: !_ctx.disabled ? _ctx.tabindex : -1,\n disabled: _ctx.disabled,\n autocomplete: \"off\",\n role: \"combobox\",\n \"aria-label\": _ctx.ariaLabel,\n \"aria-labelledby\": _ctx.ariaLabelledby,\n \"aria-haspopup\": \"listbox\",\n \"aria-autocomplete\": \"list\",\n \"aria-expanded\": $data.overlayVisible,\n \"aria-controls\": $data.id + '_list',\n \"aria-activedescendant\": $data.focused ? $options.focusedOptionId : undefined,\n \"aria-invalid\": _ctx.invalid || undefined,\n onFocus: _cache[0] || (_cache[0] = function () {\n return $options.onFocus && $options.onFocus.apply($options, arguments);\n }),\n onBlur: _cache[1] || (_cache[1] = function () {\n return $options.onBlur && $options.onBlur.apply($options, arguments);\n }),\n onKeydown: _cache[2] || (_cache[2] = function () {\n return $options.onKeyDown && $options.onKeyDown.apply($options, arguments);\n }),\n onInput: _cache[3] || (_cache[3] = function () {\n return $options.onInput && $options.onInput.apply($options, arguments);\n }),\n onChange: _cache[4] || (_cache[4] = function () {\n return $options.onChange && $options.onChange.apply($options, arguments);\n })\n }, _ctx.ptm('input')), null, 16, _hoisted_3)], 16)], 16, _hoisted_1)) : createCommentVNode(\"\", true), $data.searching || _ctx.loading ? renderSlot(_ctx.$slots, _ctx.$slots.loader ? 'loader' : 'loadingicon', {\n key: 2,\n \"class\": normalizeClass(_ctx.cx('loader'))\n }, function () {\n return [_ctx.loader || _ctx.loadingIcon ? (openBlock(), createElementBlock(\"i\", mergeProps({\n key: 0,\n \"class\": ['pi-spin', _ctx.cx('loader'), _ctx.loader, _ctx.loadingIcon],\n \"aria-hidden\": \"true\"\n }, _ctx.ptm('loader')), null, 16)) : (openBlock(), createBlock(_component_SpinnerIcon, mergeProps({\n key: 1,\n \"class\": _ctx.cx('loader'),\n spin: \"\",\n \"aria-hidden\": \"true\"\n }, _ctx.ptm('loader')), null, 16, [\"class\"]))];\n }) : createCommentVNode(\"\", true), renderSlot(_ctx.$slots, _ctx.$slots.dropdown ? 'dropdown' : 'dropdownbutton', {\n toggleCallback: function toggleCallback(event) {\n return $options.onDropdownClick(event);\n }\n }, function () {\n return [_ctx.dropdown ? (openBlock(), createElementBlock(\"button\", mergeProps({\n key: 0,\n ref: \"dropdownButton\",\n type: \"button\",\n \"class\": [_ctx.cx('dropdown'), _ctx.dropdownClass],\n disabled: _ctx.disabled,\n \"aria-haspopup\": \"listbox\",\n \"aria-expanded\": $data.overlayVisible,\n \"aria-controls\": $options.panelId,\n onClick: _cache[8] || (_cache[8] = function () {\n return $options.onDropdownClick && $options.onDropdownClick.apply($options, arguments);\n })\n }, _ctx.ptm('dropdown')), [renderSlot(_ctx.$slots, \"dropdownicon\", {\n \"class\": normalizeClass(_ctx.dropdownIcon)\n }, function () {\n return [(openBlock(), createBlock(resolveDynamicComponent(_ctx.dropdownIcon ? 'span' : 'ChevronDownIcon'), mergeProps({\n \"class\": _ctx.dropdownIcon\n }, _ctx.ptm('dropdownIcon')), null, 16, [\"class\"]))];\n })], 16, _hoisted_4)) : createCommentVNode(\"\", true)];\n }), createElementVNode(\"span\", mergeProps({\n role: \"status\",\n \"aria-live\": \"polite\",\n \"class\": \"p-hidden-accessible\"\n }, _ctx.ptm('hiddenSearchResult'), {\n \"data-p-hidden-accessible\": true\n }), toDisplayString($options.searchResultMessageText), 17), createVNode(_component_Portal, {\n appendTo: _ctx.appendTo\n }, {\n \"default\": withCtx(function () {\n return [createVNode(Transition, mergeProps({\n name: \"p-connected-overlay\",\n onEnter: $options.onOverlayEnter,\n onAfterEnter: $options.onOverlayAfterEnter,\n onLeave: $options.onOverlayLeave,\n onAfterLeave: $options.onOverlayAfterLeave\n }, _ctx.ptm('transition')), {\n \"default\": withCtx(function () {\n return [$data.overlayVisible ? (openBlock(), createElementBlock(\"div\", mergeProps({\n key: 0,\n ref: $options.overlayRef,\n id: $options.panelId,\n \"class\": [_ctx.cx('overlay'), _ctx.panelClass, _ctx.overlayClass],\n style: _objectSpread(_objectSpread(_objectSpread({}, _ctx.panelStyle), _ctx.overlayStyle), {}, {\n 'max-height': $options.virtualScrollerDisabled ? _ctx.scrollHeight : ''\n }),\n onClick: _cache[9] || (_cache[9] = function () {\n return $options.onOverlayClick && $options.onOverlayClick.apply($options, arguments);\n }),\n onKeydown: _cache[10] || (_cache[10] = function () {\n return $options.onOverlayKeyDown && $options.onOverlayKeyDown.apply($options, arguments);\n })\n }, _ctx.ptm('overlay')), [renderSlot(_ctx.$slots, \"header\", {\n value: _ctx.modelValue,\n suggestions: $options.visibleOptions\n }), createVNode(_component_VirtualScroller, mergeProps({\n ref: $options.virtualScrollerRef\n }, _ctx.virtualScrollerOptions, {\n style: {\n height: _ctx.scrollHeight\n },\n items: $options.visibleOptions,\n tabindex: -1,\n disabled: $options.virtualScrollerDisabled,\n pt: _ctx.ptm('virtualScroller')\n }), createSlots({\n content: withCtx(function (_ref) {\n var styleClass = _ref.styleClass,\n contentRef = _ref.contentRef,\n items = _ref.items,\n getItemOptions = _ref.getItemOptions,\n contentStyle = _ref.contentStyle,\n itemSize = _ref.itemSize;\n return [createElementVNode(\"ul\", mergeProps({\n ref: function ref(el) {\n return $options.listRef(el, contentRef);\n },\n id: $data.id + '_list',\n \"class\": [_ctx.cx('list'), styleClass],\n style: contentStyle,\n role: \"listbox\",\n \"aria-label\": $options.listAriaLabel\n }, _ctx.ptm('list')), [(openBlock(true), createElementBlock(Fragment, null, renderList(items, function (option, i) {\n return openBlock(), createElementBlock(Fragment, {\n key: $options.getOptionRenderKey(option, $options.getOptionIndex(i, getItemOptions))\n }, [$options.isOptionGroup(option) ? (openBlock(), createElementBlock(\"li\", mergeProps({\n key: 0,\n id: $data.id + '_' + $options.getOptionIndex(i, getItemOptions),\n style: {\n height: itemSize ? itemSize + 'px' : undefined\n },\n \"class\": _ctx.cx('optionGroup'),\n role: \"option\",\n ref_for: true\n }, _ctx.ptm('optionGroup')), [renderSlot(_ctx.$slots, \"optiongroup\", {\n option: option.optionGroup,\n index: $options.getOptionIndex(i, getItemOptions)\n }, function () {\n return [createTextVNode(toDisplayString($options.getOptionGroupLabel(option.optionGroup)), 1)];\n })], 16, _hoisted_7)) : withDirectives((openBlock(), createElementBlock(\"li\", mergeProps({\n key: 1,\n id: $data.id + '_' + $options.getOptionIndex(i, getItemOptions),\n style: {\n height: itemSize ? itemSize + 'px' : undefined\n },\n \"class\": _ctx.cx('option', {\n option: option,\n i: i,\n getItemOptions: getItemOptions\n }),\n role: \"option\",\n \"aria-label\": $options.getOptionLabel(option),\n \"aria-selected\": $options.isSelected(option),\n \"aria-disabled\": $options.isOptionDisabled(option),\n \"aria-setsize\": $options.ariaSetSize,\n \"aria-posinset\": $options.getAriaPosInset($options.getOptionIndex(i, getItemOptions)),\n onClick: function onClick($event) {\n return $options.onOptionSelect($event, option);\n },\n onMousemove: function onMousemove($event) {\n return $options.onOptionMouseMove($event, $options.getOptionIndex(i, getItemOptions));\n },\n \"data-p-selected\": $options.isSelected(option),\n \"data-p-focus\": $data.focusedOptionIndex === $options.getOptionIndex(i, getItemOptions),\n \"data-p-disabled\": $options.isOptionDisabled(option),\n ref_for: true\n }, $options.getPTOptions(option, getItemOptions, i, 'option')), [renderSlot(_ctx.$slots, \"option\", {\n option: option,\n index: $options.getOptionIndex(i, getItemOptions)\n }, function () {\n return [createTextVNode(toDisplayString($options.getOptionLabel(option)), 1)];\n })], 16, _hoisted_8)), [[_directive_ripple]])], 64);\n }), 128)), !items || items && items.length === 0 ? (openBlock(), createElementBlock(\"li\", mergeProps({\n key: 0,\n \"class\": _ctx.cx('emptyMessage'),\n role: \"option\"\n }, _ctx.ptm('emptyMessage')), [renderSlot(_ctx.$slots, \"empty\", {}, function () {\n return [createTextVNode(toDisplayString($options.searchResultMessageText), 1)];\n })], 16)) : createCommentVNode(\"\", true)], 16, _hoisted_6)];\n }),\n _: 2\n }, [_ctx.$slots.loader ? {\n name: \"loader\",\n fn: withCtx(function (_ref2) {\n var options = _ref2.options;\n return [renderSlot(_ctx.$slots, \"loader\", {\n options: options\n })];\n }),\n key: \"0\"\n } : undefined]), 1040, [\"style\", \"items\", \"disabled\", \"pt\"]), renderSlot(_ctx.$slots, \"footer\", {\n value: _ctx.modelValue,\n suggestions: $options.visibleOptions\n }), createElementVNode(\"span\", mergeProps({\n role: \"status\",\n \"aria-live\": \"polite\",\n \"class\": \"p-hidden-accessible\"\n }, _ctx.ptm('hiddenSelectedMessage'), {\n \"data-p-hidden-accessible\": true\n }), toDisplayString($options.selectedMessageText), 17)], 16, _hoisted_5)) : createCommentVNode(\"\", true)];\n }),\n _: 3\n }, 16, [\"onEnter\", \"onAfterEnter\", \"onLeave\", \"onAfterLeave\"])];\n }),\n _: 3\n }, 8, [\"appendTo\"])], 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","\r\n\r\n","import BaseIcon from '@primevue/icons/baseicon';\nimport { openBlock, createElementBlock, mergeProps, createElementVNode } from 'vue';\n\nvar script = {\n name: 'WindowMaximizeIcon',\n \"extends\": BaseIcon\n};\n\nvar _hoisted_1 = /*#__PURE__*/createElementVNode(\"path\", {\n \"fill-rule\": \"evenodd\",\n \"clip-rule\": \"evenodd\",\n d: \"M7 14H11.8C12.3835 14 12.9431 13.7682 13.3556 13.3556C13.7682 12.9431 14 12.3835 14 11.8V2.2C14 1.61652 13.7682 1.05694 13.3556 0.644365C12.9431 0.231785 12.3835 0 11.8 0H2.2C1.61652 0 1.05694 0.231785 0.644365 0.644365C0.231785 1.05694 0 1.61652 0 2.2V7C0 7.15913 0.063214 7.31174 0.175736 7.42426C0.288258 7.53679 0.44087 7.6 0.6 7.6C0.75913 7.6 0.911742 7.53679 1.02426 7.42426C1.13679 7.31174 1.2 7.15913 1.2 7V2.2C1.2 1.93478 1.30536 1.68043 1.49289 1.49289C1.68043 1.30536 1.93478 1.2 2.2 1.2H11.8C12.0652 1.2 12.3196 1.30536 12.5071 1.49289C12.6946 1.68043 12.8 1.93478 12.8 2.2V11.8C12.8 12.0652 12.6946 12.3196 12.5071 12.5071C12.3196 12.6946 12.0652 12.8 11.8 12.8H7C6.84087 12.8 6.68826 12.8632 6.57574 12.9757C6.46321 13.0883 6.4 13.2409 6.4 13.4C6.4 13.5591 6.46321 13.7117 6.57574 13.8243C6.68826 13.9368 6.84087 14 7 14ZM9.77805 7.42192C9.89013 7.534 10.0415 7.59788 10.2 7.59995C10.3585 7.59788 10.5099 7.534 10.622 7.42192C10.7341 7.30985 10.798 7.15844 10.8 6.99995V3.94242C10.8066 3.90505 10.8096 3.86689 10.8089 3.82843C10.8079 3.77159 10.7988 3.7157 10.7824 3.6623C10.756 3.55552 10.701 3.45698 10.622 3.37798C10.5099 3.2659 10.3585 3.20202 10.2 3.19995H7.00002C6.84089 3.19995 6.68828 3.26317 6.57576 3.37569C6.46324 3.48821 6.40002 3.64082 6.40002 3.79995C6.40002 3.95908 6.46324 4.11169 6.57576 4.22422C6.68828 4.33674 6.84089 4.39995 7.00002 4.39995H8.80006L6.19997 7.00005C6.10158 7.11005 6.04718 7.25246 6.04718 7.40005C6.04718 7.54763 6.10158 7.69004 6.19997 7.80005C6.30202 7.91645 6.44561 7.98824 6.59997 8.00005C6.75432 7.98824 6.89791 7.91645 6.99997 7.80005L9.60002 5.26841V6.99995C9.6021 7.15844 9.66598 7.30985 9.77805 7.42192ZM1.4 14H3.8C4.17066 13.9979 4.52553 13.8498 4.78763 13.5877C5.04973 13.3256 5.1979 12.9707 5.2 12.6V10.2C5.1979 9.82939 5.04973 9.47452 4.78763 9.21242C4.52553 8.95032 4.17066 8.80215 3.8 8.80005H1.4C1.02934 8.80215 0.674468 8.95032 0.412371 9.21242C0.150274 9.47452 0.00210008 9.82939 0 10.2V12.6C0.00210008 12.9707 0.150274 13.3256 0.412371 13.5877C0.674468 13.8498 1.02934 13.9979 1.4 14ZM1.25858 10.0586C1.29609 10.0211 1.34696 10 1.4 10H3.8C3.85304 10 3.90391 10.0211 3.94142 10.0586C3.97893 10.0961 4 10.147 4 10.2V12.6C4 12.6531 3.97893 12.704 3.94142 12.7415C3.90391 12.779 3.85304 12.8 3.8 12.8H1.4C1.34696 12.8 1.29609 12.779 1.25858 12.7415C1.22107 12.704 1.2 12.6531 1.2 12.6V10.2C1.2 10.147 1.22107 10.0961 1.25858 10.0586Z\",\n fill: \"currentColor\"\n}, null, -1);\nvar _hoisted_2 = [_hoisted_1];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"svg\", mergeProps({\n width: \"14\",\n height: \"14\",\n viewBox: \"0 0 14 14\",\n fill: \"none\",\n xmlns: \"http://www.w3.org/2000/svg\"\n }, _ctx.pti()), _hoisted_2, 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseIcon from '@primevue/icons/baseicon';\nimport { openBlock, createElementBlock, mergeProps, createElementVNode } from 'vue';\n\nvar script = {\n name: 'WindowMinimizeIcon',\n \"extends\": BaseIcon\n};\n\nvar _hoisted_1 = /*#__PURE__*/createElementVNode(\"path\", {\n \"fill-rule\": \"evenodd\",\n \"clip-rule\": \"evenodd\",\n d: \"M11.8 0H2.2C1.61652 0 1.05694 0.231785 0.644365 0.644365C0.231785 1.05694 0 1.61652 0 2.2V7C0 7.15913 0.063214 7.31174 0.175736 7.42426C0.288258 7.53679 0.44087 7.6 0.6 7.6C0.75913 7.6 0.911742 7.53679 1.02426 7.42426C1.13679 7.31174 1.2 7.15913 1.2 7V2.2C1.2 1.93478 1.30536 1.68043 1.49289 1.49289C1.68043 1.30536 1.93478 1.2 2.2 1.2H11.8C12.0652 1.2 12.3196 1.30536 12.5071 1.49289C12.6946 1.68043 12.8 1.93478 12.8 2.2V11.8C12.8 12.0652 12.6946 12.3196 12.5071 12.5071C12.3196 12.6946 12.0652 12.8 11.8 12.8H7C6.84087 12.8 6.68826 12.8632 6.57574 12.9757C6.46321 13.0883 6.4 13.2409 6.4 13.4C6.4 13.5591 6.46321 13.7117 6.57574 13.8243C6.68826 13.9368 6.84087 14 7 14H11.8C12.3835 14 12.9431 13.7682 13.3556 13.3556C13.7682 12.9431 14 12.3835 14 11.8V2.2C14 1.61652 13.7682 1.05694 13.3556 0.644365C12.9431 0.231785 12.3835 0 11.8 0ZM6.368 7.952C6.44137 7.98326 6.52025 7.99958 6.6 8H9.8C9.95913 8 10.1117 7.93678 10.2243 7.82426C10.3368 7.71174 10.4 7.55913 10.4 7.4C10.4 7.24087 10.3368 7.08826 10.2243 6.97574C10.1117 6.86321 9.95913 6.8 9.8 6.8H8.048L10.624 4.224C10.73 4.11026 10.7877 3.95982 10.7849 3.80438C10.7822 3.64894 10.7192 3.50063 10.6093 3.3907C10.4994 3.28077 10.3511 3.2178 10.1956 3.21506C10.0402 3.21232 9.88974 3.27002 9.776 3.376L7.2 5.952V4.2C7.2 4.04087 7.13679 3.88826 7.02426 3.77574C6.91174 3.66321 6.75913 3.6 6.6 3.6C6.44087 3.6 6.28826 3.66321 6.17574 3.77574C6.06321 3.88826 6 4.04087 6 4.2V7.4C6.00042 7.47975 6.01674 7.55862 6.048 7.632C6.07656 7.70442 6.11971 7.7702 6.17475 7.82524C6.2298 7.88029 6.29558 7.92344 6.368 7.952ZM1.4 8.80005H3.8C4.17066 8.80215 4.52553 8.95032 4.78763 9.21242C5.04973 9.47452 5.1979 9.82939 5.2 10.2V12.6C5.1979 12.9707 5.04973 13.3256 4.78763 13.5877C4.52553 13.8498 4.17066 13.9979 3.8 14H1.4C1.02934 13.9979 0.674468 13.8498 0.412371 13.5877C0.150274 13.3256 0.00210008 12.9707 0 12.6V10.2C0.00210008 9.82939 0.150274 9.47452 0.412371 9.21242C0.674468 8.95032 1.02934 8.80215 1.4 8.80005ZM3.94142 12.7415C3.97893 12.704 4 12.6531 4 12.6V10.2C4 10.147 3.97893 10.0961 3.94142 10.0586C3.90391 10.0211 3.85304 10 3.8 10H1.4C1.34696 10 1.29609 10.0211 1.25858 10.0586C1.22107 10.0961 1.2 10.147 1.2 10.2V12.6C1.2 12.6531 1.22107 12.704 1.25858 12.7415C1.29609 12.779 1.34696 12.8 1.4 12.8H3.8C3.85304 12.8 3.90391 12.779 3.94142 12.7415Z\",\n fill: \"currentColor\"\n}, null, -1);\nvar _hoisted_2 = [_hoisted_1];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"svg\", mergeProps({\n width: \"14\",\n height: \"14\",\n viewBox: \"0 0 14 14\",\n fill: \"none\",\n xmlns: \"http://www.w3.org/2000/svg\"\n }, _ctx.pti()), _hoisted_2, 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseStyle from '@primevue/core/base/style';\n\nvar FocusTrapStyle = BaseStyle.extend({\n name: 'focustrap-directive'\n});\n\nexport { FocusTrapStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import { focus, getFirstFocusableElement, getLastFocusableElement, isFocusableElement, createElement } from '@primeuix/utils/dom';\nimport { isNotEmpty } from '@primeuix/utils/object';\nimport BaseDirective from '@primevue/core/basedirective';\nimport FocusTrapStyle from 'primevue/focustrap/style';\n\nvar BaseFocusTrap = BaseDirective.extend({\n style: FocusTrapStyle\n});\n\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nvar FocusTrap = BaseFocusTrap.extend('focustrap', {\n mounted: function mounted(el, binding) {\n var _ref = binding.value || {},\n disabled = _ref.disabled;\n if (!disabled) {\n this.createHiddenFocusableElements(el, binding);\n this.bind(el, binding);\n this.autoElementFocus(el, binding);\n }\n el.setAttribute('data-pd-focustrap', true);\n this.$el = el;\n },\n updated: function updated(el, binding) {\n var _ref2 = binding.value || {},\n disabled = _ref2.disabled;\n disabled && this.unbind(el);\n },\n unmounted: function unmounted(el) {\n this.unbind(el);\n },\n methods: {\n getComputedSelector: function getComputedSelector(selector) {\n return \":not(.p-hidden-focusable):not([data-p-hidden-focusable=\\\"true\\\"])\".concat(selector !== null && selector !== void 0 ? selector : '');\n },\n bind: function bind(el, binding) {\n var _this = this;\n var _ref3 = binding.value || {},\n onFocusIn = _ref3.onFocusIn,\n onFocusOut = _ref3.onFocusOut;\n el.$_pfocustrap_mutationobserver = new MutationObserver(function (mutationList) {\n mutationList.forEach(function (mutation) {\n if (mutation.type === 'childList' && !el.contains(document.activeElement)) {\n var findNextFocusableElement = function findNextFocusableElement(_el) {\n var focusableElement = isFocusableElement(_el) ? isFocusableElement(_el, _this.getComputedSelector(el.$_pfocustrap_focusableselector)) ? _el : getFirstFocusableElement(el, _this.getComputedSelector(el.$_pfocustrap_focusableselector)) : getFirstFocusableElement(_el);\n return isNotEmpty(focusableElement) ? focusableElement : _el.nextSibling && findNextFocusableElement(_el.nextSibling);\n };\n focus(findNextFocusableElement(mutation.nextSibling));\n }\n });\n });\n el.$_pfocustrap_mutationobserver.disconnect();\n el.$_pfocustrap_mutationobserver.observe(el, {\n childList: true\n });\n el.$_pfocustrap_focusinlistener = function (event) {\n return onFocusIn && onFocusIn(event);\n };\n el.$_pfocustrap_focusoutlistener = function (event) {\n return onFocusOut && onFocusOut(event);\n };\n el.addEventListener('focusin', el.$_pfocustrap_focusinlistener);\n el.addEventListener('focusout', el.$_pfocustrap_focusoutlistener);\n },\n unbind: function unbind(el) {\n el.$_pfocustrap_mutationobserver && el.$_pfocustrap_mutationobserver.disconnect();\n el.$_pfocustrap_focusinlistener && el.removeEventListener('focusin', el.$_pfocustrap_focusinlistener) && (el.$_pfocustrap_focusinlistener = null);\n el.$_pfocustrap_focusoutlistener && el.removeEventListener('focusout', el.$_pfocustrap_focusoutlistener) && (el.$_pfocustrap_focusoutlistener = null);\n },\n autoFocus: function autoFocus(options) {\n this.autoElementFocus(this.$el, {\n value: _objectSpread(_objectSpread({}, options), {}, {\n autoFocus: true\n })\n });\n },\n autoElementFocus: function autoElementFocus(el, binding) {\n var _ref4 = binding.value || {},\n _ref4$autoFocusSelect = _ref4.autoFocusSelector,\n autoFocusSelector = _ref4$autoFocusSelect === void 0 ? '' : _ref4$autoFocusSelect,\n _ref4$firstFocusableS = _ref4.firstFocusableSelector,\n firstFocusableSelector = _ref4$firstFocusableS === void 0 ? '' : _ref4$firstFocusableS,\n _ref4$autoFocus = _ref4.autoFocus,\n autoFocus = _ref4$autoFocus === void 0 ? false : _ref4$autoFocus;\n var focusableElement = getFirstFocusableElement(el, \"[autofocus]\".concat(this.getComputedSelector(autoFocusSelector)));\n autoFocus && !focusableElement && (focusableElement = getFirstFocusableElement(el, this.getComputedSelector(firstFocusableSelector)));\n focus(focusableElement);\n },\n onFirstHiddenElementFocus: function onFirstHiddenElementFocus(event) {\n var _this$$el;\n var currentTarget = event.currentTarget,\n relatedTarget = event.relatedTarget;\n var focusableElement = relatedTarget === currentTarget.$_pfocustrap_lasthiddenfocusableelement || !((_this$$el = this.$el) !== null && _this$$el !== void 0 && _this$$el.contains(relatedTarget)) ? getFirstFocusableElement(currentTarget.parentElement, this.getComputedSelector(currentTarget.$_pfocustrap_focusableselector)) : currentTarget.$_pfocustrap_lasthiddenfocusableelement;\n focus(focusableElement);\n },\n onLastHiddenElementFocus: function onLastHiddenElementFocus(event) {\n var _this$$el2;\n var currentTarget = event.currentTarget,\n relatedTarget = event.relatedTarget;\n var focusableElement = relatedTarget === currentTarget.$_pfocustrap_firsthiddenfocusableelement || !((_this$$el2 = this.$el) !== null && _this$$el2 !== void 0 && _this$$el2.contains(relatedTarget)) ? getLastFocusableElement(currentTarget.parentElement, this.getComputedSelector(currentTarget.$_pfocustrap_focusableselector)) : currentTarget.$_pfocustrap_firsthiddenfocusableelement;\n focus(focusableElement);\n },\n createHiddenFocusableElements: function createHiddenFocusableElements(el, binding) {\n var _this2 = this;\n var _ref5 = binding.value || {},\n _ref5$tabIndex = _ref5.tabIndex,\n tabIndex = _ref5$tabIndex === void 0 ? 0 : _ref5$tabIndex,\n _ref5$firstFocusableS = _ref5.firstFocusableSelector,\n firstFocusableSelector = _ref5$firstFocusableS === void 0 ? '' : _ref5$firstFocusableS,\n _ref5$lastFocusableSe = _ref5.lastFocusableSelector,\n lastFocusableSelector = _ref5$lastFocusableSe === void 0 ? '' : _ref5$lastFocusableSe;\n var createFocusableElement = function createFocusableElement(onFocus) {\n return createElement('span', {\n \"class\": 'p-hidden-accessible p-hidden-focusable',\n tabIndex: tabIndex,\n role: 'presentation',\n 'aria-hidden': true,\n 'data-p-hidden-accessible': true,\n 'data-p-hidden-focusable': true,\n onFocus: onFocus === null || onFocus === void 0 ? void 0 : onFocus.bind(_this2)\n });\n };\n var firstFocusableElement = createFocusableElement(this.onFirstHiddenElementFocus);\n var lastFocusableElement = createFocusableElement(this.onLastHiddenElementFocus);\n firstFocusableElement.$_pfocustrap_lasthiddenfocusableelement = lastFocusableElement;\n firstFocusableElement.$_pfocustrap_focusableselector = firstFocusableSelector;\n firstFocusableElement.setAttribute('data-pc-section', 'firstfocusableelement');\n lastFocusableElement.$_pfocustrap_firsthiddenfocusableelement = firstFocusableElement;\n lastFocusableElement.$_pfocustrap_focusableselector = lastFocusableSelector;\n lastFocusableElement.setAttribute('data-pc-section', 'lastfocusableelement');\n el.prepend(firstFocusableElement);\n el.append(lastFocusableElement);\n }\n }\n});\n\nexport { FocusTrap as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseStyle from '@primevue/core/base/style';\n\nvar theme = function theme(_ref) {\n var dt = _ref.dt;\n return \"\\n.p-dialog {\\n max-height: 90%;\\n transform: scale(1);\\n border-radius: \".concat(dt('dialog.border.radius'), \";\\n box-shadow: \").concat(dt('dialog.shadow'), \";\\n background: \").concat(dt('dialog.background'), \";\\n border: 1px solid \").concat(dt('dialog.border.color'), \";\\n color: \").concat(dt('dialog.color'), \";\\n}\\n\\n.p-dialog-content {\\n overflow-y: auto;\\n padding: \").concat(dt('dialog.content.padding'), \";\\n}\\n\\n.p-dialog-header {\\n display: flex;\\n align-items: center;\\n justify-content: space-between;\\n flex-shrink: 0;\\n padding: \").concat(dt('dialog.header.padding'), \";\\n}\\n\\n.p-dialog-title {\\n font-weight: \").concat(dt('dialog.title.font.weight'), \";\\n font-size: \").concat(dt('dialog.title.font.size'), \";\\n}\\n\\n.p-dialog-footer {\\n flex-shrink: 0;\\n padding: \").concat(dt('dialog.footer.padding'), \";\\n display: flex;\\n justify-content: flex-end;\\n gap: \").concat(dt('dialog.footer.gap'), \";\\n}\\n\\n.p-dialog-header-actions {\\n display: flex;\\n align-items: center;\\n gap: \").concat(dt('dialog.header.gap'), \";\\n}\\n.p-dialog-enter-active {\\n transition: all 150ms cubic-bezier(0, 0, 0.2, 1);\\n}\\n\\n.p-dialog-leave-active {\\n transition: all 150ms cubic-bezier(0.4, 0, 0.2, 1);\\n}\\n\\n.p-dialog-enter-from,\\n.p-dialog-leave-to {\\n opacity: 0;\\n transform: scale(0.7);\\n}\\n\\n.p-dialog-top .p-dialog,\\n.p-dialog-bottom .p-dialog,\\n.p-dialog-left .p-dialog,\\n.p-dialog-right .p-dialog,\\n.p-dialog-topleft .p-dialog,\\n.p-dialog-topright .p-dialog,\\n.p-dialog-bottomleft .p-dialog,\\n.p-dialog-bottomright .p-dialog {\\n margin: 0.75rem;\\n transform: translate3d(0px, 0px, 0px);\\n}\\n\\n.p-dialog-top .p-dialog-enter-active,\\n.p-dialog-top .p-dialog-leave-active,\\n.p-dialog-bottom .p-dialog-enter-active,\\n.p-dialog-bottom .p-dialog-leave-active,\\n.p-dialog-left .p-dialog-enter-active,\\n.p-dialog-left .p-dialog-leave-active,\\n.p-dialog-right .p-dialog-enter-active,\\n.p-dialog-right .p-dialog-leave-active,\\n.p-dialog-topleft .p-dialog-enter-active,\\n.p-dialog-topleft .p-dialog-leave-active,\\n.p-dialog-topright .p-dialog-enter-active,\\n.p-dialog-topright .p-dialog-leave-active,\\n.p-dialog-bottomleft .p-dialog-enter-active,\\n.p-dialog-bottomleft .p-dialog-leave-active,\\n.p-dialog-bottomright .p-dialog-enter-active,\\n.p-dialog-bottomright .p-dialog-leave-active {\\n transition: all 0.3s ease-out;\\n}\\n\\n.p-dialog-top .p-dialog-enter-from,\\n.p-dialog-top .p-dialog-leave-to {\\n transform: translate3d(0px, -100%, 0px);\\n}\\n\\n.p-dialog-bottom .p-dialog-enter-from,\\n.p-dialog-bottom .p-dialog-leave-to {\\n transform: translate3d(0px, 100%, 0px);\\n}\\n\\n.p-dialog-left .p-dialog-enter-from,\\n.p-dialog-left .p-dialog-leave-to,\\n.p-dialog-topleft .p-dialog-enter-from,\\n.p-dialog-topleft .p-dialog-leave-to,\\n.p-dialog-bottomleft .p-dialog-enter-from,\\n.p-dialog-bottomleft .p-dialog-leave-to {\\n transform: translate3d(-100%, 0px, 0px);\\n}\\n\\n.p-dialog-right .p-dialog-enter-from,\\n.p-dialog-right .p-dialog-leave-to,\\n.p-dialog-topright .p-dialog-enter-from,\\n.p-dialog-topright .p-dialog-leave-to,\\n.p-dialog-bottomright .p-dialog-enter-from,\\n.p-dialog-bottomright .p-dialog-leave-to {\\n transform: translate3d(100%, 0px, 0px);\\n}\\n\\n.p-dialog-maximized {\\n width: 100vw !important;\\n height: 100vh !important;\\n top: 0px !important;\\n left: 0px !important;\\n max-height: 100%;\\n height: 100%;\\n border-radius: 0;\\n}\\n\\n.p-dialog-maximized .p-dialog-content {\\n flex-grow: 1;\\n}\\n\");\n};\n\n/* Position */\nvar inlineStyles = {\n mask: function mask(_ref2) {\n var position = _ref2.position,\n modal = _ref2.modal;\n return {\n position: 'fixed',\n height: '100%',\n width: '100%',\n left: 0,\n top: 0,\n display: 'flex',\n justifyContent: position === 'left' || position === 'topleft' || position === 'bottomleft' ? 'flex-start' : position === 'right' || position === 'topright' || position === 'bottomright' ? 'flex-end' : 'center',\n alignItems: position === 'top' || position === 'topleft' || position === 'topright' ? 'flex-start' : position === 'bottom' || position === 'bottomleft' || position === 'bottomright' ? 'flex-end' : 'center',\n pointerEvents: modal ? 'auto' : 'none'\n };\n },\n root: {\n display: 'flex',\n flexDirection: 'column',\n pointerEvents: 'auto'\n }\n};\nvar classes = {\n mask: function mask(_ref3) {\n var props = _ref3.props;\n var positions = ['left', 'right', 'top', 'topleft', 'topright', 'bottom', 'bottomleft', 'bottomright'];\n var pos = positions.find(function (item) {\n return item === props.position;\n });\n return ['p-dialog-mask', {\n 'p-overlay-mask p-overlay-mask-enter': props.modal\n }, pos ? \"p-dialog-\".concat(pos) : ''];\n },\n root: function root(_ref4) {\n var props = _ref4.props,\n instance = _ref4.instance;\n return ['p-dialog p-component', {\n 'p-dialog-maximized': props.maximizable && instance.maximized\n }];\n },\n header: 'p-dialog-header',\n title: 'p-dialog-title',\n headerActions: 'p-dialog-header-actions',\n pcMaximizeButton: 'p-dialog-maximize-button',\n pcCloseButton: 'p-dialog-close-button',\n content: 'p-dialog-content',\n footer: 'p-dialog-footer'\n};\nvar DialogStyle = BaseStyle.extend({\n name: 'dialog',\n theme: theme,\n classes: classes,\n inlineStyles: inlineStyles\n});\n\nexport { DialogStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import { UniqueComponentId } from '@primevue/core/utils';\nimport { addClass, focus, blockBodyScroll, unblockBodyScroll, setAttribute, addStyle, getOuterWidth, getOuterHeight, getViewport } from '@primeuix/utils/dom';\nimport { ZIndex } from '@primeuix/utils/zindex';\nimport TimesIcon from '@primevue/icons/times';\nimport WindowMaximizeIcon from '@primevue/icons/windowmaximize';\nimport WindowMinimizeIcon from '@primevue/icons/windowminimize';\nimport Button from 'primevue/button';\nimport FocusTrap from 'primevue/focustrap';\nimport Portal from 'primevue/portal';\nimport Ripple from 'primevue/ripple';\nimport { computed, resolveComponent, resolveDirective, openBlock, createBlock, withCtx, createElementBlock, mergeProps, createVNode, Transition, withDirectives, renderSlot, Fragment, normalizeClass, toDisplayString, createCommentVNode, createElementVNode, resolveDynamicComponent, createTextVNode } from 'vue';\nimport BaseComponent from '@primevue/core/basecomponent';\nimport DialogStyle from 'primevue/dialog/style';\n\nvar script$1 = {\n name: 'BaseDialog',\n \"extends\": BaseComponent,\n props: {\n header: {\n type: null,\n \"default\": null\n },\n footer: {\n type: null,\n \"default\": null\n },\n visible: {\n type: Boolean,\n \"default\": false\n },\n modal: {\n type: Boolean,\n \"default\": null\n },\n contentStyle: {\n type: null,\n \"default\": null\n },\n contentClass: {\n type: String,\n \"default\": null\n },\n contentProps: {\n type: null,\n \"default\": null\n },\n maximizable: {\n type: Boolean,\n \"default\": false\n },\n dismissableMask: {\n type: Boolean,\n \"default\": false\n },\n closable: {\n type: Boolean,\n \"default\": true\n },\n closeOnEscape: {\n type: Boolean,\n \"default\": true\n },\n showHeader: {\n type: Boolean,\n \"default\": true\n },\n blockScroll: {\n type: Boolean,\n \"default\": false\n },\n baseZIndex: {\n type: Number,\n \"default\": 0\n },\n autoZIndex: {\n type: Boolean,\n \"default\": true\n },\n position: {\n type: String,\n \"default\": 'center'\n },\n breakpoints: {\n type: Object,\n \"default\": null\n },\n draggable: {\n type: Boolean,\n \"default\": true\n },\n keepInViewport: {\n type: Boolean,\n \"default\": true\n },\n minX: {\n type: Number,\n \"default\": 0\n },\n minY: {\n type: Number,\n \"default\": 0\n },\n appendTo: {\n type: [String, Object],\n \"default\": 'body'\n },\n closeIcon: {\n type: String,\n \"default\": undefined\n },\n maximizeIcon: {\n type: String,\n \"default\": undefined\n },\n minimizeIcon: {\n type: String,\n \"default\": undefined\n },\n closeButtonProps: {\n type: Object,\n \"default\": function _default() {\n return {\n severity: 'secondary',\n text: true,\n rounded: true\n };\n }\n },\n maximizeButtonProps: {\n type: Object,\n \"default\": function _default() {\n return {\n severity: 'secondary',\n text: true,\n rounded: true\n };\n }\n },\n _instance: null\n },\n style: DialogStyle,\n provide: function provide() {\n return {\n $pcDialog: this,\n $parentInstance: this\n };\n }\n};\n\nvar script = {\n name: 'Dialog',\n \"extends\": script$1,\n inheritAttrs: false,\n emits: ['update:visible', 'show', 'hide', 'after-hide', 'maximize', 'unmaximize', 'dragend'],\n provide: function provide() {\n var _this = this;\n return {\n dialogRef: computed(function () {\n return _this._instance;\n })\n };\n },\n data: function data() {\n return {\n id: this.$attrs.id,\n containerVisible: this.visible,\n maximized: false,\n focusableMax: null,\n focusableClose: null\n };\n },\n watch: {\n '$attrs.id': function $attrsId(newValue) {\n this.id = newValue || UniqueComponentId();\n }\n },\n documentKeydownListener: null,\n container: null,\n mask: null,\n content: null,\n headerContainer: null,\n footerContainer: null,\n maximizableButton: null,\n closeButton: null,\n styleElement: null,\n dragging: null,\n documentDragListener: null,\n documentDragEndListener: null,\n lastPageX: null,\n lastPageY: null,\n updated: function updated() {\n if (this.visible) {\n this.containerVisible = this.visible;\n }\n },\n beforeUnmount: function beforeUnmount() {\n this.unbindDocumentState();\n this.unbindGlobalListeners();\n this.destroyStyle();\n if (this.mask && this.autoZIndex) {\n ZIndex.clear(this.mask);\n }\n this.container = null;\n this.mask = null;\n },\n mounted: function mounted() {\n this.id = this.id || UniqueComponentId();\n if (this.breakpoints) {\n this.createStyle();\n }\n },\n methods: {\n close: function close() {\n this.$emit('update:visible', false);\n },\n onBeforeEnter: function onBeforeEnter(el) {\n el.setAttribute(this.attributeSelector, '');\n },\n onEnter: function onEnter() {\n this.$emit('show');\n this.focus();\n this.enableDocumentSettings();\n this.bindGlobalListeners();\n if (this.autoZIndex) {\n ZIndex.set('modal', this.mask, this.baseZIndex + this.$primevue.config.zIndex.modal);\n }\n },\n onBeforeLeave: function onBeforeLeave() {\n if (this.modal) {\n !this.isUnstyled && addClass(this.mask, 'p-overlay-mask-leave');\n }\n },\n onLeave: function onLeave() {\n this.$emit('hide');\n this.focusableClose = null;\n this.focusableMax = null;\n },\n onAfterLeave: function onAfterLeave() {\n if (this.autoZIndex) {\n ZIndex.clear(this.mask);\n }\n this.containerVisible = false;\n this.unbindDocumentState();\n this.unbindGlobalListeners();\n this.$emit('after-hide');\n },\n onMaskClick: function onMaskClick(event) {\n if (this.dismissableMask && this.modal && this.mask === event.target) {\n this.close();\n }\n },\n focus: function focus$1() {\n var findFocusableElement = function findFocusableElement(container) {\n return container && container.querySelector('[autofocus]');\n };\n var focusTarget = this.$slots.footer && findFocusableElement(this.footerContainer);\n if (!focusTarget) {\n focusTarget = this.$slots.header && findFocusableElement(this.headerContainer);\n if (!focusTarget) {\n focusTarget = this.$slots[\"default\"] && findFocusableElement(this.content);\n if (!focusTarget) {\n if (this.maximizable) {\n this.focusableMax = true;\n focusTarget = this.maximizableButton;\n } else {\n this.focusableClose = true;\n focusTarget = this.closeButton;\n }\n }\n }\n }\n if (focusTarget) {\n focus(focusTarget, {\n focusVisible: true\n });\n }\n },\n maximize: function maximize(event) {\n if (this.maximized) {\n this.maximized = false;\n this.$emit('unmaximize', event);\n } else {\n this.maximized = true;\n this.$emit('maximize', event);\n }\n if (!this.modal) {\n this.maximized ? blockBodyScroll() : unblockBodyScroll();\n }\n },\n enableDocumentSettings: function enableDocumentSettings() {\n if (this.modal || !this.modal && this.blockScroll || this.maximizable && this.maximized) {\n blockBodyScroll();\n }\n },\n unbindDocumentState: function unbindDocumentState() {\n if (this.modal || !this.modal && this.blockScroll || this.maximizable && this.maximized) {\n unblockBodyScroll();\n }\n },\n onKeyDown: function onKeyDown(event) {\n if (event.code === 'Escape' && this.closeOnEscape) {\n this.close();\n }\n },\n bindDocumentKeyDownListener: function bindDocumentKeyDownListener() {\n if (!this.documentKeydownListener) {\n this.documentKeydownListener = this.onKeyDown.bind(this);\n window.document.addEventListener('keydown', this.documentKeydownListener);\n }\n },\n unbindDocumentKeyDownListener: function unbindDocumentKeyDownListener() {\n if (this.documentKeydownListener) {\n window.document.removeEventListener('keydown', this.documentKeydownListener);\n this.documentKeydownListener = null;\n }\n },\n containerRef: function containerRef(el) {\n this.container = el;\n },\n maskRef: function maskRef(el) {\n this.mask = el;\n },\n contentRef: function contentRef(el) {\n this.content = el;\n },\n headerContainerRef: function headerContainerRef(el) {\n this.headerContainer = el;\n },\n footerContainerRef: function footerContainerRef(el) {\n this.footerContainer = el;\n },\n maximizableRef: function maximizableRef(el) {\n this.maximizableButton = el ? el.$el : undefined;\n },\n closeButtonRef: function closeButtonRef(el) {\n this.closeButton = el ? el.$el : undefined;\n },\n createStyle: function createStyle() {\n if (!this.styleElement && !this.isUnstyled) {\n var _this$$primevue;\n this.styleElement = document.createElement('style');\n this.styleElement.type = 'text/css';\n setAttribute(this.styleElement, 'nonce', (_this$$primevue = this.$primevue) === null || _this$$primevue === void 0 || (_this$$primevue = _this$$primevue.config) === null || _this$$primevue === void 0 || (_this$$primevue = _this$$primevue.csp) === null || _this$$primevue === void 0 ? void 0 : _this$$primevue.nonce);\n document.head.appendChild(this.styleElement);\n var innerHTML = '';\n for (var breakpoint in this.breakpoints) {\n innerHTML += \"\\n @media screen and (max-width: \".concat(breakpoint, \") {\\n .p-dialog[\").concat(this.attributeSelector, \"] {\\n width: \").concat(this.breakpoints[breakpoint], \" !important;\\n }\\n }\\n \");\n }\n this.styleElement.innerHTML = innerHTML;\n }\n },\n destroyStyle: function destroyStyle() {\n if (this.styleElement) {\n document.head.removeChild(this.styleElement);\n this.styleElement = null;\n }\n },\n initDrag: function initDrag(event) {\n if (event.target.closest('div').getAttribute('data-pc-section') === 'headeractions') {\n return;\n }\n if (this.draggable) {\n this.dragging = true;\n this.lastPageX = event.pageX;\n this.lastPageY = event.pageY;\n this.container.style.margin = '0';\n document.body.setAttribute('data-p-unselectable-text', 'true');\n !this.isUnstyled && addStyle(document.body, {\n 'user-select': 'none'\n });\n }\n },\n bindGlobalListeners: function bindGlobalListeners() {\n if (this.draggable) {\n this.bindDocumentDragListener();\n this.bindDocumentDragEndListener();\n }\n if (this.closeOnEscape && this.closable) {\n this.bindDocumentKeyDownListener();\n }\n },\n unbindGlobalListeners: function unbindGlobalListeners() {\n this.unbindDocumentDragListener();\n this.unbindDocumentDragEndListener();\n this.unbindDocumentKeyDownListener();\n },\n bindDocumentDragListener: function bindDocumentDragListener() {\n var _this2 = this;\n this.documentDragListener = function (event) {\n if (_this2.dragging) {\n var width = getOuterWidth(_this2.container);\n var height = getOuterHeight(_this2.container);\n var deltaX = event.pageX - _this2.lastPageX;\n var deltaY = event.pageY - _this2.lastPageY;\n var offset = _this2.container.getBoundingClientRect();\n var leftPos = offset.left + deltaX;\n var topPos = offset.top + deltaY;\n var viewport = getViewport();\n var containerComputedStyle = getComputedStyle(_this2.container);\n var marginLeft = parseFloat(containerComputedStyle.marginLeft);\n var marginTop = parseFloat(containerComputedStyle.marginTop);\n _this2.container.style.position = 'fixed';\n if (_this2.keepInViewport) {\n if (leftPos >= _this2.minX && leftPos + width < viewport.width) {\n _this2.lastPageX = event.pageX;\n _this2.container.style.left = leftPos - marginLeft + 'px';\n }\n if (topPos >= _this2.minY && topPos + height < viewport.height) {\n _this2.lastPageY = event.pageY;\n _this2.container.style.top = topPos - marginTop + 'px';\n }\n } else {\n _this2.lastPageX = event.pageX;\n _this2.container.style.left = leftPos - marginLeft + 'px';\n _this2.lastPageY = event.pageY;\n _this2.container.style.top = topPos - marginTop + 'px';\n }\n }\n };\n window.document.addEventListener('mousemove', this.documentDragListener);\n },\n unbindDocumentDragListener: function unbindDocumentDragListener() {\n if (this.documentDragListener) {\n window.document.removeEventListener('mousemove', this.documentDragListener);\n this.documentDragListener = null;\n }\n },\n bindDocumentDragEndListener: function bindDocumentDragEndListener() {\n var _this3 = this;\n this.documentDragEndListener = function (event) {\n if (_this3.dragging) {\n _this3.dragging = false;\n document.body.removeAttribute('data-p-unselectable-text');\n !_this3.isUnstyled && (document.body.style['user-select'] = '');\n _this3.$emit('dragend', event);\n }\n };\n window.document.addEventListener('mouseup', this.documentDragEndListener);\n },\n unbindDocumentDragEndListener: function unbindDocumentDragEndListener() {\n if (this.documentDragEndListener) {\n window.document.removeEventListener('mouseup', this.documentDragEndListener);\n this.documentDragEndListener = null;\n }\n }\n },\n computed: {\n maximizeIconComponent: function maximizeIconComponent() {\n return this.maximized ? this.minimizeIcon ? 'span' : 'WindowMinimizeIcon' : this.maximizeIcon ? 'span' : 'WindowMaximizeIcon';\n },\n ariaLabelledById: function ariaLabelledById() {\n return this.header != null || this.$attrs['aria-labelledby'] !== null ? this.id + '_header' : null;\n },\n closeAriaLabel: function closeAriaLabel() {\n return this.$primevue.config.locale.aria ? this.$primevue.config.locale.aria.close : undefined;\n },\n attributeSelector: function attributeSelector() {\n return UniqueComponentId();\n }\n },\n directives: {\n ripple: Ripple,\n focustrap: FocusTrap\n },\n components: {\n Button: Button,\n Portal: Portal,\n WindowMinimizeIcon: WindowMinimizeIcon,\n WindowMaximizeIcon: WindowMaximizeIcon,\n TimesIcon: TimesIcon\n }\n};\n\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nvar _hoisted_1 = [\"aria-labelledby\", \"aria-modal\"];\nvar _hoisted_2 = [\"id\"];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n var _component_Button = resolveComponent(\"Button\");\n var _component_Portal = resolveComponent(\"Portal\");\n var _directive_focustrap = resolveDirective(\"focustrap\");\n return openBlock(), createBlock(_component_Portal, {\n appendTo: _ctx.appendTo\n }, {\n \"default\": withCtx(function () {\n return [$data.containerVisible ? (openBlock(), createElementBlock(\"div\", mergeProps({\n key: 0,\n ref: $options.maskRef,\n \"class\": _ctx.cx('mask'),\n style: _ctx.sx('mask', true, {\n position: _ctx.position,\n modal: _ctx.modal\n }),\n onClick: _cache[1] || (_cache[1] = function () {\n return $options.onMaskClick && $options.onMaskClick.apply($options, arguments);\n })\n }, _ctx.ptm('mask')), [createVNode(Transition, mergeProps({\n name: \"p-dialog\",\n onBeforeEnter: $options.onBeforeEnter,\n onEnter: $options.onEnter,\n onBeforeLeave: $options.onBeforeLeave,\n onLeave: $options.onLeave,\n onAfterLeave: $options.onAfterLeave,\n appear: \"\"\n }, _ctx.ptm('transition')), {\n \"default\": withCtx(function () {\n return [_ctx.visible ? withDirectives((openBlock(), createElementBlock(\"div\", mergeProps({\n key: 0,\n ref: $options.containerRef,\n \"class\": _ctx.cx('root'),\n style: _ctx.sx('root'),\n role: \"dialog\",\n \"aria-labelledby\": $options.ariaLabelledById,\n \"aria-modal\": _ctx.modal\n }, _ctx.ptmi('root')), [_ctx.$slots.container ? renderSlot(_ctx.$slots, \"container\", {\n key: 0,\n closeCallback: $options.close,\n maximizeCallback: function maximizeCallback(event) {\n return $options.maximize(event);\n }\n }) : (openBlock(), createElementBlock(Fragment, {\n key: 1\n }, [_ctx.showHeader ? (openBlock(), createElementBlock(\"div\", mergeProps({\n key: 0,\n ref: $options.headerContainerRef,\n \"class\": _ctx.cx('header'),\n onMousedown: _cache[0] || (_cache[0] = function () {\n return $options.initDrag && $options.initDrag.apply($options, arguments);\n })\n }, _ctx.ptm('header')), [renderSlot(_ctx.$slots, \"header\", {\n \"class\": normalizeClass(_ctx.cx('title'))\n }, function () {\n return [_ctx.header ? (openBlock(), createElementBlock(\"span\", mergeProps({\n key: 0,\n id: $options.ariaLabelledById,\n \"class\": _ctx.cx('title')\n }, _ctx.ptm('title')), toDisplayString(_ctx.header), 17, _hoisted_2)) : createCommentVNode(\"\", true)];\n }), createElementVNode(\"div\", mergeProps({\n \"class\": _ctx.cx('headerActions')\n }, _ctx.ptm('headerActions')), [_ctx.maximizable ? (openBlock(), createBlock(_component_Button, mergeProps({\n key: 0,\n ref: $options.maximizableRef,\n autofocus: $data.focusableMax,\n \"class\": _ctx.cx('pcMaximizeButton'),\n onClick: $options.maximize,\n tabindex: _ctx.maximizable ? '0' : '-1',\n unstyled: _ctx.unstyled\n }, _ctx.maximizeButtonProps, {\n pt: _ctx.ptm('pcMaximizeButton'),\n \"data-pc-group-section\": \"headericon\"\n }), {\n icon: withCtx(function (slotProps) {\n return [renderSlot(_ctx.$slots, \"maximizeicon\", {\n maximized: $data.maximized\n }, function () {\n return [(openBlock(), createBlock(resolveDynamicComponent($options.maximizeIconComponent), mergeProps({\n \"class\": [slotProps[\"class\"], $data.maximized ? _ctx.minimizeIcon : _ctx.maximizeIcon]\n }, _ctx.ptm('pcMaximizeButton')['icon']), null, 16, [\"class\"]))];\n })];\n }),\n _: 3\n }, 16, [\"autofocus\", \"class\", \"onClick\", \"tabindex\", \"unstyled\", \"pt\"])) : createCommentVNode(\"\", true), _ctx.closable ? (openBlock(), createBlock(_component_Button, mergeProps({\n key: 1,\n ref: $options.closeButtonRef,\n autofocus: $data.focusableClose,\n \"class\": _ctx.cx('pcCloseButton'),\n onClick: $options.close,\n \"aria-label\": $options.closeAriaLabel,\n unstyled: _ctx.unstyled\n }, _ctx.closeButtonProps, {\n pt: _ctx.ptm('pcCloseButton'),\n \"data-pc-group-section\": \"headericon\"\n }), {\n icon: withCtx(function (slotProps) {\n return [renderSlot(_ctx.$slots, \"closeicon\", {}, function () {\n return [(openBlock(), createBlock(resolveDynamicComponent(_ctx.closeIcon ? 'span' : 'TimesIcon'), mergeProps({\n \"class\": [_ctx.closeIcon, slotProps[\"class\"]]\n }, _ctx.ptm('pcCloseButton')['icon']), null, 16, [\"class\"]))];\n })];\n }),\n _: 3\n }, 16, [\"autofocus\", \"class\", \"onClick\", \"aria-label\", \"unstyled\", \"pt\"])) : createCommentVNode(\"\", true)], 16)], 16)) : createCommentVNode(\"\", true), createElementVNode(\"div\", mergeProps({\n ref: $options.contentRef,\n \"class\": [_ctx.cx('content'), _ctx.contentClass],\n style: _ctx.contentStyle\n }, _objectSpread(_objectSpread({}, _ctx.contentProps), _ctx.ptm('content'))), [renderSlot(_ctx.$slots, \"default\")], 16), _ctx.footer || _ctx.$slots.footer ? (openBlock(), createElementBlock(\"div\", mergeProps({\n key: 1,\n ref: $options.footerContainerRef,\n \"class\": _ctx.cx('footer')\n }, _ctx.ptm('footer')), [renderSlot(_ctx.$slots, \"footer\", {}, function () {\n return [createTextVNode(toDisplayString(_ctx.footer), 1)];\n })], 16)) : createCommentVNode(\"\", true)], 64))], 16, _hoisted_1)), [[_directive_focustrap, {\n disabled: !_ctx.modal\n }]]) : createCommentVNode(\"\", true)];\n }),\n _: 3\n }, 16, [\"onBeforeEnter\", \"onEnter\", \"onBeforeLeave\", \"onLeave\", \"onAfterLeave\"])], 16)) : createCommentVNode(\"\", true)];\n }),\n _: 3\n }, 8, [\"appendTo\"]);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseStyle from '@primevue/core/base/style';\n\nvar theme = function theme(_ref) {\n var dt = _ref.dt;\n return \"\\n.p-togglebutton {\\n display: inline-flex;\\n cursor: pointer;\\n user-select: none;\\n align-items: center;\\n justify-content: center;\\n overflow: hidden;\\n position: relative;\\n color: \".concat(dt('togglebutton.color'), \";\\n background: \").concat(dt('togglebutton.background'), \";\\n border: 1px solid \").concat(dt('togglebutton.border.color'), \";\\n padding: \").concat(dt('togglebutton.padding'), \";\\n font-size: 1rem;\\n font-family: inherit;\\n font-feature-settings: inherit;\\n transition: background \").concat(dt('togglebutton.transition.duration'), \", color \").concat(dt('togglebutton.transition.duration'), \", border-color \").concat(dt('togglebutton.transition.duration'), \",\\n outline-color \").concat(dt('togglebutton.transition.duration'), \", box-shadow \").concat(dt('togglebutton.transition.duration'), \";\\n border-radius: \").concat(dt('togglebutton.border.radius'), \";\\n outline-color: transparent;\\n font-weight: \").concat(dt('togglebutton.font.weight'), \";\\n}\\n\\n.p-togglebutton-content {\\n position: relative;\\n display: inline-flex;\\n align-items: center;\\n justify-content: center;\\n gap: \").concat(dt('togglebutton.gap'), \";\\n}\\n\\n.p-togglebutton-label,\\n.p-togglebutton-icon {\\n position: relative;\\n transition: none;\\n}\\n\\n.p-togglebutton::before {\\n content: \\\"\\\";\\n background: transparent;\\n transition: background \").concat(dt('togglebutton.transition.duration'), \", color \").concat(dt('togglebutton.transition.duration'), \", border-color \").concat(dt('togglebutton.transition.duration'), \",\\n outline-color \").concat(dt('togglebutton.transition.duration'), \", box-shadow \").concat(dt('togglebutton.transition.duration'), \";\\n position: absolute;\\n left: \").concat(dt('togglebutton.content.left'), \";\\n top: \").concat(dt('togglebutton.content.top'), \";\\n width: calc(100% - calc(2 * \").concat(dt('togglebutton.content.left'), \"));\\n height: calc(100% - calc(2 * \").concat(dt('togglebutton.content.top'), \"));\\n border-radius: \").concat(dt('togglebutton.border.radius'), \";\\n}\\n\\n.p-togglebutton.p-togglebutton-checked::before {\\n background: \").concat(dt('togglebutton.content.checked.background'), \";\\n box-shadow: \").concat(dt('togglebutton.content.checked.shadow'), \";\\n}\\n\\n.p-togglebutton:not(:disabled):not(.p-togglebutton-checked):hover {\\n background: \").concat(dt('togglebutton.hover.background'), \";\\n color: \").concat(dt('togglebutton.hover.color'), \";\\n}\\n\\n.p-togglebutton.p-togglebutton-checked {\\n background: \").concat(dt('togglebutton.checked.background'), \";\\n border-color: \").concat(dt('togglebutton.checked.border.color'), \";\\n color: \").concat(dt('togglebutton.checked.color'), \";\\n}\\n\\n.p-togglebutton:focus-visible {\\n box-shadow: \").concat(dt('togglebutton.focus.ring.shadow'), \";\\n outline: \").concat(dt('togglebutton.focus.ring.width'), \" \").concat(dt('togglebutton.focus.ring.style'), \" \").concat(dt('togglebutton.focus.ring.color'), \";\\n outline-offset: \").concat(dt('togglebutton.focus.ring.offset'), \";\\n}\\n\\n.p-togglebutton.p-invalid {\\n border-color: \").concat(dt('togglebutton.invalid.border.color'), \";\\n}\\n\\n.p-togglebutton:disabled {\\n opacity: 1;\\n cursor: default;\\n background: \").concat(dt('togglebutton.disabled.background'), \";\\n border-color: \").concat(dt('togglebutton.disabled.border.color'), \";\\n color: \").concat(dt('togglebutton.disabled.color'), \";\\n}\\n\\n.p-togglebutton-icon {\\n color: \").concat(dt('togglebutton.icon.color'), \";\\n}\\n\\n.p-togglebutton:not(:disabled):not(.p-togglebutton-checked):hover .p-togglebutton-icon {\\n color: \").concat(dt('togglebutton.icon.hover.color'), \";\\n}\\n\\n.p-togglebutton.p-togglebutton-checked .p-togglebutton-icon {\\n color: \").concat(dt('togglebutton.icon.checked.color'), \";\\n}\\n\\n.p-togglebutton:disabled .p-togglebutton-icon {\\n color: \").concat(dt('togglebutton.icon.disabled.color'), \";\\n}\\n\");\n};\nvar classes = {\n root: function root(_ref2) {\n var instance = _ref2.instance,\n props = _ref2.props;\n return ['p-togglebutton p-component', {\n 'p-togglebutton-checked': instance.active,\n 'p-invalid': props.invalid\n }];\n },\n content: 'p-togglebutton-content',\n icon: 'p-togglebutton-icon',\n label: 'p-togglebutton-label'\n};\nvar ToggleButtonStyle = BaseStyle.extend({\n name: 'togglebutton',\n theme: theme,\n classes: classes\n});\n\nexport { ToggleButtonStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import { isNotEmpty } from '@primeuix/utils/object';\nimport Ripple from 'primevue/ripple';\nimport BaseComponent from '@primevue/core/basecomponent';\nimport ToggleButtonStyle from 'primevue/togglebutton/style';\nimport { resolveDirective, withDirectives, openBlock, createElementBlock, mergeProps, createElementVNode, renderSlot, normalizeClass, createCommentVNode, toDisplayString } from 'vue';\n\nvar script$1 = {\n name: 'BaseToggleButton',\n \"extends\": BaseComponent,\n props: {\n modelValue: Boolean,\n onIcon: String,\n offIcon: String,\n onLabel: {\n type: String,\n \"default\": 'Yes'\n },\n offLabel: {\n type: String,\n \"default\": 'No'\n },\n iconPos: {\n type: String,\n \"default\": 'left'\n },\n invalid: {\n type: Boolean,\n \"default\": false\n },\n disabled: {\n type: Boolean,\n \"default\": false\n },\n readonly: {\n type: Boolean,\n \"default\": false\n },\n tabindex: {\n type: Number,\n \"default\": null\n },\n ariaLabelledby: {\n type: String,\n \"default\": null\n },\n ariaLabel: {\n type: String,\n \"default\": null\n }\n },\n style: ToggleButtonStyle,\n provide: function provide() {\n return {\n $pcToggleButton: this,\n $parentInstance: this\n };\n }\n};\n\nvar script = {\n name: 'ToggleButton',\n \"extends\": script$1,\n inheritAttrs: false,\n emits: ['update:modelValue', 'change'],\n methods: {\n getPTOptions: function getPTOptions(key) {\n var _ptm = key === 'root' ? this.ptmi : this.ptm;\n return _ptm(key, {\n context: {\n active: this.active,\n disabled: this.disabled\n }\n });\n },\n onChange: function onChange(event) {\n if (!this.disabled && !this.readonly) {\n this.$emit('update:modelValue', !this.modelValue);\n this.$emit('change', event);\n }\n }\n },\n computed: {\n active: function active() {\n return this.modelValue === true;\n },\n hasLabel: function hasLabel() {\n return isNotEmpty(this.onLabel) && isNotEmpty(this.offLabel);\n },\n label: function label() {\n return this.hasLabel ? this.modelValue ? this.onLabel : this.offLabel : ' ';\n }\n },\n directives: {\n ripple: Ripple\n }\n};\n\nvar _hoisted_1 = [\"tabindex\", \"disabled\", \"aria-pressed\", \"data-p-checked\", \"data-p-disabled\"];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n var _directive_ripple = resolveDirective(\"ripple\");\n return withDirectives((openBlock(), createElementBlock(\"button\", mergeProps({\n type: \"button\",\n \"class\": _ctx.cx('root'),\n tabindex: _ctx.tabindex,\n disabled: _ctx.disabled,\n \"aria-pressed\": _ctx.modelValue,\n onClick: _cache[0] || (_cache[0] = function () {\n return $options.onChange && $options.onChange.apply($options, arguments);\n })\n }, $options.getPTOptions('root'), {\n \"data-p-checked\": $options.active,\n \"data-p-disabled\": _ctx.disabled\n }), [createElementVNode(\"span\", mergeProps({\n \"class\": _ctx.cx('content')\n }, $options.getPTOptions('content')), [renderSlot(_ctx.$slots, \"default\", {}, function () {\n return [renderSlot(_ctx.$slots, \"icon\", {\n value: _ctx.modelValue,\n \"class\": normalizeClass(_ctx.cx('icon'))\n }, function () {\n return [_ctx.onIcon || _ctx.offIcon ? (openBlock(), createElementBlock(\"span\", mergeProps({\n key: 0,\n \"class\": [_ctx.cx('icon'), _ctx.modelValue ? _ctx.onIcon : _ctx.offIcon]\n }, $options.getPTOptions('icon')), null, 16)) : createCommentVNode(\"\", true)];\n }), createElementVNode(\"span\", mergeProps({\n \"class\": _ctx.cx('label')\n }, $options.getPTOptions('label')), toDisplayString($options.label), 17)];\n })], 16)], 16, _hoisted_1)), [[_directive_ripple]]);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseStyle from '@primevue/core/base/style';\n\nvar theme = function theme(_ref) {\n var dt = _ref.dt;\n return \"\\n.p-selectbutton {\\n display: inline-flex;\\n user-select: none;\\n vertical-align: bottom;\\n outline-color: transparent;\\n border-radius: \".concat(dt('selectbutton.border.radius'), \";\\n}\\n\\n.p-selectbutton .p-togglebutton {\\n border-radius: 0;\\n border-width: 1px 1px 1px 0;\\n}\\n\\n.p-selectbutton .p-togglebutton:focus-visible {\\n position: relative;\\n z-index: 1;\\n}\\n\\n.p-selectbutton .p-togglebutton:first-child {\\n border-left-width: 1px;\\n border-top-left-radius: \").concat(dt('selectbutton.border.radius'), \";\\n border-bottom-left-radius: \").concat(dt('selectbutton.border.radius'), \";\\n}\\n\\n.p-selectbutton .p-togglebutton:last-child {\\n border-top-right-radius: \").concat(dt('selectbutton.border.radius'), \";\\n border-bottom-right-radius: \").concat(dt('selectbutton.border.radius'), \";\\n}\\n\\n.p-selectbutton.p-invalid {\\n outline: 1px solid \").concat(dt('selectbutton.invalid.border.color'), \";\\n outline-offset: 0;\\n}\\n\");\n};\nvar classes = {\n root: function root(_ref2) {\n var props = _ref2.props;\n return ['p-selectbutton p-component', {\n 'p-invalid': props.invalid\n }];\n }\n};\nvar SelectButtonStyle = BaseStyle.extend({\n name: 'selectbutton',\n theme: theme,\n classes: classes\n});\n\nexport { SelectButtonStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import { resolveFieldData, equals } from '@primeuix/utils/object';\nimport Ripple from 'primevue/ripple';\nimport ToggleButton from 'primevue/togglebutton';\nimport BaseComponent from '@primevue/core/basecomponent';\nimport SelectButtonStyle from 'primevue/selectbutton/style';\nimport { resolveComponent, openBlock, createElementBlock, mergeProps, Fragment, renderList, createBlock, createSlots, withCtx, renderSlot, createElementVNode, toDisplayString } from 'vue';\n\nvar script$1 = {\n name: 'BaseSelectButton',\n \"extends\": BaseComponent,\n props: {\n modelValue: null,\n options: Array,\n optionLabel: null,\n optionValue: null,\n optionDisabled: null,\n multiple: Boolean,\n allowEmpty: {\n type: Boolean,\n \"default\": true\n },\n invalid: {\n type: Boolean,\n \"default\": false\n },\n disabled: Boolean,\n dataKey: null,\n ariaLabelledby: {\n type: String,\n \"default\": null\n }\n },\n style: SelectButtonStyle,\n provide: function provide() {\n return {\n $pcSelectButton: this,\n $parentInstance: this\n };\n }\n};\n\nfunction _createForOfIteratorHelper(r, e) { var t = \"undefined\" != typeof Symbol && r[Symbol.iterator] || r[\"@@iterator\"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e ) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError(\"Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t[\"return\"] || t[\"return\"](); } finally { if (u) throw o; } } }; }\nfunction _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _unsupportedIterableToArray(r, a) { if (r) { if (\"string\" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return \"Object\" === t && r.constructor && (t = r.constructor.name), \"Map\" === t || \"Set\" === t ? Array.from(r) : \"Arguments\" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }\nfunction _iterableToArray(r) { if (\"undefined\" != typeof Symbol && null != r[Symbol.iterator] || null != r[\"@@iterator\"]) return Array.from(r); }\nfunction _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }\nfunction _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }\nvar script = {\n name: 'SelectButton',\n \"extends\": script$1,\n inheritAttrs: false,\n emits: ['update:modelValue', 'change'],\n methods: {\n getOptionLabel: function getOptionLabel(option) {\n return this.optionLabel ? resolveFieldData(option, this.optionLabel) : option;\n },\n getOptionValue: function getOptionValue(option) {\n return this.optionValue ? resolveFieldData(option, this.optionValue) : option;\n },\n getOptionRenderKey: function getOptionRenderKey(option) {\n return this.dataKey ? resolveFieldData(option, this.dataKey) : this.getOptionLabel(option);\n },\n getPTOptions: function getPTOptions(option, key) {\n return this.ptm(key, {\n context: {\n active: this.isSelected(option),\n disabled: this.isOptionDisabled(option),\n option: option\n }\n });\n },\n isOptionDisabled: function isOptionDisabled(option) {\n return this.optionDisabled ? resolveFieldData(option, this.optionDisabled) : false;\n },\n onOptionSelect: function onOptionSelect(event, option, index) {\n var _this = this;\n if (this.disabled || this.isOptionDisabled(option)) {\n return;\n }\n var selected = this.isSelected(option);\n if (selected && !this.allowEmpty) {\n return;\n }\n var optionValue = this.getOptionValue(option);\n var newValue;\n if (this.multiple) {\n if (selected) newValue = this.modelValue.filter(function (val) {\n return !equals(val, optionValue, _this.equalityKey);\n });else newValue = this.modelValue ? [].concat(_toConsumableArray(this.modelValue), [optionValue]) : [optionValue];\n } else {\n newValue = selected ? null : optionValue;\n }\n this.focusedIndex = index;\n this.$emit('update:modelValue', newValue);\n this.$emit('change', {\n event: event,\n value: newValue\n });\n },\n isSelected: function isSelected(option) {\n var selected = false;\n var optionValue = this.getOptionValue(option);\n if (this.multiple) {\n if (this.modelValue) {\n var _iterator = _createForOfIteratorHelper(this.modelValue),\n _step;\n try {\n for (_iterator.s(); !(_step = _iterator.n()).done;) {\n var val = _step.value;\n if (equals(val, optionValue, this.equalityKey)) {\n selected = true;\n break;\n }\n }\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n }\n } else {\n selected = equals(this.modelValue, optionValue, this.equalityKey);\n }\n return selected;\n }\n },\n computed: {\n equalityKey: function equalityKey() {\n return this.optionValue ? null : this.dataKey;\n }\n },\n directives: {\n ripple: Ripple\n },\n components: {\n ToggleButton: ToggleButton\n }\n};\n\nvar _hoisted_1 = [\"aria-labelledby\"];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n var _component_ToggleButton = resolveComponent(\"ToggleButton\");\n return openBlock(), createElementBlock(\"div\", mergeProps({\n \"class\": _ctx.cx('root'),\n role: \"group\",\n \"aria-labelledby\": _ctx.ariaLabelledby\n }, _ctx.ptmi('root')), [(openBlock(true), createElementBlock(Fragment, null, renderList(_ctx.options, function (option, index) {\n return openBlock(), createBlock(_component_ToggleButton, {\n key: $options.getOptionRenderKey(option),\n modelValue: $options.isSelected(option),\n onLabel: $options.getOptionLabel(option),\n offLabel: $options.getOptionLabel(option),\n disabled: _ctx.disabled || $options.isOptionDisabled(option),\n unstyled: _ctx.unstyled,\n onChange: function onChange($event) {\n return $options.onOptionSelect($event, option, index);\n },\n pt: _ctx.ptm('pcButton')\n }, createSlots({\n _: 2\n }, [_ctx.$slots.option ? {\n name: \"default\",\n fn: withCtx(function () {\n return [renderSlot(_ctx.$slots, \"option\", {\n option: option,\n index: index\n }, function () {\n return [createElementVNode(\"span\", mergeProps({\n ref_for: true\n }, _ctx.ptm('pcButton')['label']), toDisplayString($options.getOptionLabel(option)), 17)];\n })];\n }),\n key: \"0\"\n } : undefined]), 1032, [\"modelValue\", \"onLabel\", \"offLabel\", \"disabled\", \"unstyled\", \"onChange\", \"pt\"]);\n }), 128))], 16, _hoisted_1);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","\r\n \r\n \r\n \r\n Add node filter condition\r\n \r\n \r\n \r\n updateFilterValues(event.query)\"\r\n completeOnFocus\r\n forceSelection\r\n dropdown\r\n >\r\n \r\n \r\n \r\n \r\n \r\n\r\n\r\n\r\n\r\n\r\n","\r\n \r\n {{ nodeSource.displayText }}\r\n \r\n\r\n\r\n\r\n\r\n\r\n","\r\n\r\n\r\n \r\n \r\n \r\n \r\n {{ nodeDef.display_name }}\r\n \r\n PREVIEW\r\n\r\n \r\n \r\n \r\n \r\n \r\n {{ slotInput ? slotInput.name : '' }}\r\n \r\n \r\n {{ slotOutput ? slotOutput.name : '' }}\r\n \r\n \r\n \r\n \r\n \r\n\r\n \r\n \r\n ◀\r\n {{ widgetInput.name }}\r\n \r\n \r\n {{ truncateDefaultValue(widgetInput.default) }}\r\n \r\n ▶\r\n \r\n \r\n \r\n {{ nodeDef.description }}\r\n \r\n \r\n\r\n\r\n\r\n\r\n\r\n","\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n {{ option.category.replaceAll('/', ' > ') }}\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n {{ value[0].invokeSequence.toUpperCase() }}\r\n \r\n {{ value[1] }}\r\n \r\n \r\n \r\n \r\n\r\n\r\n\r\n\r\n\r\n","import {\r\n ConnectingLink,\r\n LGraphNode,\r\n Vector2,\r\n INodeInputSlot,\r\n INodeOutputSlot,\r\n INodeSlot\r\n} from '@comfyorg/litegraph'\r\n\r\nexport class ConnectingLinkImpl implements ConnectingLink {\r\n node: LGraphNode\r\n slot: number\r\n input: INodeInputSlot | null\r\n output: INodeOutputSlot | null\r\n pos: Vector2\r\n\r\n constructor(\r\n node: LGraphNode,\r\n slot: number,\r\n input: INodeInputSlot | null,\r\n output: INodeOutputSlot | null,\r\n pos: Vector2\r\n ) {\r\n this.node = node\r\n this.slot = slot\r\n this.input = input\r\n this.output = output\r\n this.pos = pos\r\n }\r\n\r\n static createFromPlainObject(obj: ConnectingLink) {\r\n return new ConnectingLinkImpl(\r\n obj.node,\r\n obj.slot,\r\n obj.input,\r\n obj.output,\r\n obj.pos\r\n )\r\n }\r\n\r\n get type(): string | null {\r\n const result = this.input ? this.input.type : this.output.type\r\n return result === -1 ? null : result\r\n }\r\n\r\n /**\r\n * Which slot type is release and need to be reconnected.\r\n * - 'output' means we need a new node's outputs slot to connect with this link\r\n */\r\n get releaseSlotType(): 'input' | 'output' {\r\n return this.output ? 'input' : 'output'\r\n }\r\n\r\n connectTo(newNode: LGraphNode) {\r\n const newNodeSlots =\r\n this.releaseSlotType === 'output' ? newNode.outputs : newNode.inputs\r\n const newNodeSlot = newNodeSlots.findIndex(\r\n (slot: INodeSlot) => slot.type === this.type\r\n )\r\n\r\n if (newNodeSlot === -1) {\r\n console.warn(\r\n `Could not find slot with type ${this.type} on node ${newNode.title}. This should never happen`\r\n )\r\n return\r\n }\r\n\r\n if (this.releaseSlotType === 'input') {\r\n this.node.connect(this.slot, newNode, newNodeSlot)\r\n } else {\r\n newNode.connect(newNodeSlot, this.node, this.slot)\r\n }\r\n }\r\n}\r\n","\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n\r\n\r\n\r\n\r\n\r\n","\r\n \r\n {{ tooltipText }}\r\n \r\n\r\n\r\n\r\n\r\n\r\n","function _arrayWithHoles(r) {\n if (Array.isArray(r)) return r;\n}\nexport { _arrayWithHoles as default };","function _iterableToArrayLimit(r, l) {\n var t = null == r ? null : \"undefined\" != typeof Symbol && r[Symbol.iterator] || r[\"@@iterator\"];\n if (null != t) {\n var e,\n n,\n i,\n u,\n a = [],\n f = !0,\n o = !1;\n try {\n if (i = (t = t.call(r)).next, 0 === l) {\n if (Object(t) !== t) return;\n f = !1;\n } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);\n } catch (r) {\n o = !0, n = r;\n } finally {\n try {\n if (!f && null != t[\"return\"] && (u = t[\"return\"](), Object(u) !== u)) return;\n } finally {\n if (o) throw n;\n }\n }\n return a;\n }\n}\nexport { _iterableToArrayLimit as default };","function _arrayLikeToArray(r, a) {\n (null == a || a > r.length) && (a = r.length);\n for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];\n return n;\n}\nexport { _arrayLikeToArray as default };","import arrayLikeToArray from \"./arrayLikeToArray.js\";\nfunction _unsupportedIterableToArray(r, a) {\n if (r) {\n if (\"string\" == typeof r) return arrayLikeToArray(r, a);\n var t = {}.toString.call(r).slice(8, -1);\n return \"Object\" === t && r.constructor && (t = r.constructor.name), \"Map\" === t || \"Set\" === t ? Array.from(r) : \"Arguments\" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? arrayLikeToArray(r, a) : void 0;\n }\n}\nexport { _unsupportedIterableToArray as default };","function _nonIterableRest() {\n 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}\nexport { _nonIterableRest as default };","import arrayWithHoles from \"./arrayWithHoles.js\";\nimport iterableToArrayLimit from \"./iterableToArrayLimit.js\";\nimport unsupportedIterableToArray from \"./unsupportedIterableToArray.js\";\nimport nonIterableRest from \"./nonIterableRest.js\";\nfunction _slicedToArray(r, e) {\n return arrayWithHoles(r) || iterableToArrayLimit(r, e) || unsupportedIterableToArray(r, e) || nonIterableRest();\n}\nexport { _slicedToArray as default };","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.bind = void 0;\nfunction bind(target, _a) {\n var type = _a.type, listener = _a.listener, options = _a.options;\n target.addEventListener(type, listener, options);\n return function unbind() {\n target.removeEventListener(type, listener, options);\n };\n}\nexports.bind = bind;\n","\"use strict\";\nvar __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.bindAll = void 0;\nvar bind_1 = require(\"./bind\");\nfunction toOptions(value) {\n if (typeof value === 'undefined') {\n return undefined;\n }\n if (typeof value === 'boolean') {\n return {\n capture: value,\n };\n }\n return value;\n}\nfunction getBinding(original, sharedOptions) {\n if (sharedOptions == null) {\n return original;\n }\n var binding = __assign(__assign({}, original), { options: __assign(__assign({}, toOptions(sharedOptions)), toOptions(original.options)) });\n return binding;\n}\nfunction bindAll(target, bindings, sharedOptions) {\n var unbinds = bindings.map(function (original) {\n var binding = getBinding(original, sharedOptions);\n return (0, bind_1.bind)(target, binding);\n });\n return function unbindAll() {\n unbinds.forEach(function (unbind) { return unbind(); });\n };\n}\nexports.bindAll = bindAll;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.bindAll = exports.bind = void 0;\nvar bind_1 = require(\"./bind\");\nObject.defineProperty(exports, \"bind\", { enumerable: true, get: function () { return bind_1.bind; } });\nvar bind_all_1 = require(\"./bind-all\");\nObject.defineProperty(exports, \"bindAll\", { enumerable: true, get: function () { return bind_all_1.bindAll; } });\n","// pulling this into a separate file so adapter(s) that don't\n// need the honey pot can pay as little as possible for it.\nexport var honeyPotDataAttribute = 'data-pdnd-honey-pot';","import { honeyPotDataAttribute } from './honey-pot-data-attribute';\nexport function isHoneyPotElement(target) {\n return target instanceof Element && target.hasAttribute(honeyPotDataAttribute);\n}","import _slicedToArray from \"@babel/runtime/helpers/slicedToArray\";\nimport { isHoneyPotElement } from './is-honey-pot-element';\nexport function getElementFromPointWithoutHoneypot(client) {\n // eslint-disable-next-line no-restricted-syntax\n var _document$elementsFro = document.elementsFromPoint(client.x, client.y),\n _document$elementsFro2 = _slicedToArray(_document$elementsFro, 2),\n top = _document$elementsFro2[0],\n second = _document$elementsFro2[1];\n if (!top) {\n return null;\n }\n if (isHoneyPotElement(top)) {\n return second !== null && second !== void 0 ? second : null;\n }\n return top;\n}","function _typeof(o) {\n \"@babel/helpers - typeof\";\n\n return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) {\n return typeof o;\n } : function (o) {\n return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o;\n }, _typeof(o);\n}\nexport { _typeof as default };","import _typeof from \"./typeof.js\";\nfunction toPrimitive(t, r) {\n if (\"object\" != _typeof(t) || !t) return t;\n var e = t[Symbol.toPrimitive];\n if (void 0 !== e) {\n var i = e.call(t, r || \"default\");\n if (\"object\" != _typeof(i)) return i;\n throw new TypeError(\"@@toPrimitive must return a primitive value.\");\n }\n return (\"string\" === r ? String : Number)(t);\n}\nexport { toPrimitive as default };","import _typeof from \"./typeof.js\";\nimport toPrimitive from \"./toPrimitive.js\";\nfunction toPropertyKey(t) {\n var i = toPrimitive(t, \"string\");\n return \"symbol\" == _typeof(i) ? i : i + \"\";\n}\nexport { toPropertyKey as default };","import toPropertyKey from \"./toPropertyKey.js\";\nfunction _defineProperty(e, r, t) {\n return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {\n value: t,\n enumerable: !0,\n configurable: !0,\n writable: !0\n }) : e[r] = t, e;\n}\nexport { _defineProperty as default };","// Maximum possible z-index\n// https://stackoverflow.com/questions/491052/minimum-and-maximum-value-of-z-index\nexport var maxZIndex = 2147483647;","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nimport { bind, bindAll } from 'bind-event-listener';\nimport { maxZIndex } from '../util/max-z-index';\nimport { honeyPotDataAttribute } from './honey-pot-data-attribute';\nvar honeyPotSize = 2;\nvar halfHoneyPotSize = honeyPotSize / 2;\n\n/**\n * `clientX` and `clientY` can be in sub pixels (eg `2.332`)\n * However, browser hitbox testing is commonly do to the closest pixel.\n *\n * → https://issues.chromium.org/issues/40940531\n *\n * To be sure that the honey pot will be over the `client` position,\n * we `.floor()` `clientX` and`clientY` and then make it `2px` in size.\n **/\nfunction floorToClosestPixel(point) {\n return {\n x: Math.floor(point.x),\n y: Math.floor(point.y)\n };\n}\n\n/**\n * We want to make sure the honey pot sits around the users position.\n * This seemed to be the most resilient while testing.\n */\nfunction pullBackByHalfHoneyPotSize(point) {\n return {\n x: point.x - halfHoneyPotSize,\n y: point.y - halfHoneyPotSize\n };\n}\n\n/**\n * Prevent the honey pot from changing the window size.\n * This is super unlikely to occur, but just being safe.\n */\nfunction preventGoingBackwardsOffScreen(point) {\n return {\n x: Math.max(point.x, 0),\n y: Math.max(point.y, 0)\n };\n}\n\n/**\n * Prevent the honey pot from changing the window size.\n * This is super unlikely to occur, but just being safe.\n */\nfunction preventGoingForwardsOffScreen(point) {\n return {\n x: Math.min(point.x, window.innerWidth - honeyPotSize),\n y: Math.min(point.y, window.innerHeight - honeyPotSize)\n };\n}\n\n/**\n * Create a `2x2` `DOMRect` around the `client` position\n */\nfunction getHoneyPotRectFor(_ref) {\n var client = _ref.client;\n var point = preventGoingForwardsOffScreen(preventGoingBackwardsOffScreen(pullBackByHalfHoneyPotSize(floorToClosestPixel(client))));\n\n // When debugging, it is helpful to\n // make this element a bit bigger\n return DOMRect.fromRect({\n x: point.x,\n y: point.y,\n width: honeyPotSize,\n height: honeyPotSize\n });\n}\nfunction getRectStyles(_ref2) {\n var clientRect = _ref2.clientRect;\n return {\n left: \"\".concat(clientRect.left, \"px\"),\n top: \"\".concat(clientRect.top, \"px\"),\n width: \"\".concat(clientRect.width, \"px\"),\n height: \"\".concat(clientRect.height, \"px\")\n };\n}\nfunction isWithin(_ref3) {\n var client = _ref3.client,\n clientRect = _ref3.clientRect;\n return (\n // is within horizontal bounds\n client.x >= clientRect.x && client.x <= clientRect.x + clientRect.width &&\n // is within vertical bounds\n client.y >= clientRect.y && client.y <= clientRect.y + clientRect.height\n );\n}\n/**\n * The honey pot fix is designed to get around a painful bug in all browsers.\n *\n * [Overview](https://www.youtube.com/watch?v=udE9qbFTeQg)\n *\n * **Background**\n *\n * When a drag starts, browsers incorrectly think that the users pointer is\n * still depressed where the drag started. Any element that goes under this position\n * will be entered into, causing `\"mouseenter\"` events and `\":hover\"` styles to be applied.\n *\n * _This is a violation of the spec_\n *\n * > \"From the moment that the user agent is to initiate the drag-and-drop operation,\n * > until the end \tof the drag-and-drop operation, device input events\n * > (e.g. mouse and keyboard events) must be suppressed.\"\n * >\n * > - https://html.spec.whatwg.org/multipage/dnd.html#drag-and-drop-processing-model\n *\n * _Some impacts_\n *\n * - `\":hover\"` styles being applied where they shouldn't (looks messy)\n * - components such as tooltips responding to `\"mouseenter\"` can show during a drag,\n * and on an element the user isn't even over\n *\n * Bug: https://issues.chromium.org/issues/41129937\n *\n * **Honey pot fix**\n *\n * 1. Create an element where the browser thinks the depressed pointer is\n * to absorb the incorrect pointer events\n * 2. Remove that element when it is no longer needed\n */\nfunction mountHoneyPot(_ref4) {\n var initial = _ref4.initial;\n var element = document.createElement('div');\n element.setAttribute(honeyPotDataAttribute, 'true');\n\n // can shift during the drag thanks to Firefox\n var clientRect = getHoneyPotRectFor({\n client: initial\n });\n Object.assign(element.style, _objectSpread(_objectSpread({\n // Setting a background color explicitly to avoid any inherited styles.\n // Looks like this could be `opacity: 0`, but worried that _might_\n // cause the element to be ignored on some platforms.\n // When debugging, set backgroundColor to something like \"red\".\n backgroundColor: 'transparent',\n position: 'fixed',\n // Being explicit to avoid inheriting styles\n padding: 0,\n margin: 0,\n boxSizing: 'border-box'\n }, getRectStyles({\n clientRect: clientRect\n })), {}, {\n // We want this element to absorb pointer events,\n // it's kind of the whole point 😉\n pointerEvents: 'auto',\n // Want to make sure the honey pot is top of everything else.\n // Don't need to worry about native drag previews, as they will\n // have been rendered (and removed) before the honey pot is rendered\n zIndex: maxZIndex\n }));\n document.body.appendChild(element);\n\n /**\n * 🦊 In firefox we can get `\"pointermove\"` events after the drag\n * has started, which is a spec violation.\n * The final `\"pointermove\"` will reveal where the \"depressed\" position\n * is for our honey pot fix.\n */\n var unbindPointerMove = bind(window, {\n type: 'pointermove',\n listener: function listener(event) {\n var client = {\n x: event.clientX,\n y: event.clientY\n };\n clientRect = getHoneyPotRectFor({\n client: client\n });\n Object.assign(element.style, getRectStyles({\n clientRect: clientRect\n }));\n },\n // using capture so we are less likely to be impacted by event stopping\n options: {\n capture: true\n }\n });\n return function finish(_ref5) {\n var current = _ref5.current;\n // Don't need this any more\n unbindPointerMove();\n\n // If the user is hover the honey pot, we remove it\n // so that the user can continue to interact with the page normally.\n if (isWithin({\n client: current,\n clientRect: clientRect\n })) {\n element.remove();\n return;\n }\n function cleanup() {\n unbindPostDragEvents();\n element.remove();\n }\n var unbindPostDragEvents = bindAll(window, [{\n type: 'pointerdown',\n listener: cleanup\n }, {\n type: 'pointermove',\n listener: cleanup\n }, {\n type: 'focusin',\n listener: cleanup\n }, {\n type: 'focusout',\n listener: cleanup\n },\n // a 'pointerdown' should happen before 'dragstart', but just being super safe\n {\n type: 'dragstart',\n listener: cleanup\n },\n // if the user has dragged something out of the window\n // and then is dragging something back into the window\n // the first events we will see are \"dragenter\" (and then \"dragover\").\n // So if we see any of these we need to clear the post drag fix.\n {\n type: 'dragenter',\n listener: cleanup\n }, {\n type: 'dragover',\n listener: cleanup\n }\n\n // Not adding a \"wheel\" event listener, as \"wheel\" by itself does not\n // resolve the bug.\n ], {\n // Using `capture` so less likely to be impacted by other code stopping events\n capture: true\n });\n };\n}\nexport function makeHoneyPotFix() {\n var latestPointerMove = null;\n function bindEvents() {\n // For sanity, only collecting this value from when events are first bound.\n // This prevents the case where a super old \"pointermove\" could be used\n // from a prior interaction.\n latestPointerMove = null;\n return bind(window, {\n type: 'pointermove',\n listener: function listener(event) {\n latestPointerMove = {\n x: event.clientX,\n y: event.clientY\n };\n },\n // listening for pointer move in capture phase\n // so we are less likely to be impacted by events being stopped.\n options: {\n capture: true\n }\n });\n }\n function getOnPostDispatch() {\n var finish = null;\n return function onPostEvent(_ref6) {\n var eventName = _ref6.eventName,\n payload = _ref6.payload;\n // We are adding the honey pot `onDragStart` so we don't\n // impact the creation of the native drag preview.\n if (eventName === 'onDragStart') {\n var _latestPointerMove;\n var input = payload.location.initial.input;\n\n // Sometimes there will be no latest \"pointermove\" (eg iOS).\n // In which case, we use the start position of the drag.\n var initial = (_latestPointerMove = latestPointerMove) !== null && _latestPointerMove !== void 0 ? _latestPointerMove : {\n x: input.clientX,\n y: input.clientY\n };\n\n // Don't need to defensively call `finish()` as `onDrop` from\n // one interaction is guaranteed to be called before `onDragStart`\n // of the next.\n finish = mountHoneyPot({\n initial: initial\n });\n }\n if (eventName === 'onDrop') {\n var _finish;\n var _input = payload.location.current.input;\n (_finish = finish) === null || _finish === void 0 || _finish({\n current: {\n x: _input.clientX,\n y: _input.clientY\n }\n });\n finish = null;\n // this interaction is finished, we want to use\n // the latest \"pointermove\" for each interaction\n latestPointerMove = null;\n }\n };\n }\n return {\n bindEvents: bindEvents,\n getOnPostDispatch: getOnPostDispatch\n };\n}","import arrayLikeToArray from \"./arrayLikeToArray.js\";\nfunction _arrayWithoutHoles(r) {\n if (Array.isArray(r)) return arrayLikeToArray(r);\n}\nexport { _arrayWithoutHoles as default };","function _iterableToArray(r) {\n if (\"undefined\" != typeof Symbol && null != r[Symbol.iterator] || null != r[\"@@iterator\"]) return Array.from(r);\n}\nexport { _iterableToArray as default };","function _nonIterableSpread() {\n throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\nexport { _nonIterableSpread as default };","import arrayWithoutHoles from \"./arrayWithoutHoles.js\";\nimport iterableToArray from \"./iterableToArray.js\";\nimport unsupportedIterableToArray from \"./unsupportedIterableToArray.js\";\nimport nonIterableSpread from \"./nonIterableSpread.js\";\nfunction _toConsumableArray(r) {\n return arrayWithoutHoles(r) || iterableToArray(r) || unsupportedIterableToArray(r) || nonIterableSpread();\n}\nexport { _toConsumableArray as default };","/** Provide a function that you only ever want to be called a single time */\nexport function once(fn) {\n var cache = null;\n return function wrapped() {\n if (!cache) {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n var result = fn.apply(this, args);\n cache = {\n result: result\n };\n }\n return cache.result;\n };\n}","import { once } from '../public-utils/once';\n\n// using `cache` as our `isFirefox()` result will not change in a browser\n\n/**\n * Returns `true` if a `Firefox` browser\n * */\nexport var isFirefox = once(function isFirefox() {\n if (process.env.NODE_ENV === 'test') {\n return false;\n }\n return navigator.userAgent.includes('Firefox');\n});","import { once } from '../public-utils/once';\n\n// using `cache` as our `isSafari()` result will not change in a browser\n\n/**\n * Returns `true` if a `Safari` browser.\n * Returns `true` if the browser is running on iOS (they are all Safari).\n * */\nexport var isSafari = once(function isSafari() {\n if (process.env.NODE_ENV === 'test') {\n return false;\n }\n var _navigator = navigator,\n userAgent = _navigator.userAgent;\n return userAgent.includes('AppleWebKit') && !userAgent.includes('Chrome');\n});","import { bindAll } from 'bind-event-listener';\nimport { isSafari } from '../is-safari';\n\n/* For \"dragenter\" events, the browser should set `relatedTarget` to the previous element.\n * For external drag operations, our first \"dragenter\" event should have a `event.relatedTarget` of `null`.\n *\n * Unfortunately in Safari `event.relatedTarget` is *always* set to `null`\n * Safari bug: https://bugs.webkit.org/show_bug.cgi?id=242627\n * To work around this we count \"dragenter\" and \"dragleave\" events */\n\n// Using symbols for event properties so we don't clash with\n// anything on the `event` object\nvar symbols = {\n isLeavingWindow: Symbol('leaving'),\n isEnteringWindow: Symbol('entering')\n};\nexport function isEnteringWindowInSafari(_ref) {\n var dragEnter = _ref.dragEnter;\n if (!isSafari()) {\n return false;\n }\n return dragEnter.hasOwnProperty(symbols.isEnteringWindow);\n}\nexport function isLeavingWindowInSafari(_ref2) {\n var dragLeave = _ref2.dragLeave;\n if (!isSafari()) {\n return false;\n }\n return dragLeave.hasOwnProperty(symbols.isLeavingWindow);\n}\n(function fixSafari() {\n // Don't do anything when server side rendering\n if (typeof window === 'undefined') {\n return;\n }\n\n // rather than checking the userAgent for \"jsdom\" we can do this check\n // so that the check will be removed completely in production code\n if (process.env.NODE_ENV === 'test') {\n return;\n }\n if (!isSafari()) {\n return;\n }\n function getInitialState() {\n return {\n enterCount: 0,\n isOverWindow: false\n };\n }\n var state = getInitialState();\n function resetState() {\n state = getInitialState();\n }\n\n // These event listeners are bound _forever_ and _never_ removed\n // We don't bother cleaning up these event listeners (for now)\n // as this workaround is only for Safari\n\n // This is how the event count works:\n //\n // lift (+1 enterCount)\n // - dragstart(draggable) [enterCount: 0]\n // - dragenter(draggable) [enterCount: 1]\n // leaving draggable (+0 enterCount)\n // - dragenter(document.body) [enterCount: 2]\n // - dragleave(draggable) [enterCount: 1]\n // leaving window (-1 enterCount)\n // - dragleave(document.body) [enterCount: 0] {leaving the window}\n\n // Things to note:\n // - dragenter and dragleave bubble\n // - the first dragenter when entering a window might not be on `window`\n // - it could be on an element that is pressed up against the window\n // - (so we cannot rely on `event.target` values)\n\n bindAll(window, [{\n type: 'dragstart',\n listener: function listener() {\n state.enterCount = 0;\n // drag start occurs in the source window\n state.isOverWindow = true;\n // When a drag first starts it will also trigger a \"dragenter\" on the draggable element\n }\n }, {\n type: 'drop',\n listener: resetState\n }, {\n type: 'dragend',\n listener: resetState\n }, {\n type: 'dragenter',\n listener: function listener(event) {\n if (!state.isOverWindow && state.enterCount === 0) {\n // Patching the `event` object\n // The `event` object is shared with all event listeners for the event\n // @ts-expect-error: adding property to the event object\n event[symbols.isEnteringWindow] = true;\n }\n state.isOverWindow = true;\n state.enterCount++;\n }\n }, {\n type: 'dragleave',\n listener: function listener(event) {\n state.enterCount--;\n if (state.isOverWindow && state.enterCount === 0) {\n // Patching the `event` object as it is shared with all event listeners\n // The `event` object is shared with all event listeners for the event\n // @ts-expect-error: adding property to the event object\n event[symbols.isLeavingWindow] = true;\n state.isOverWindow = false;\n }\n }\n }],\n // using `capture: true` so that adding event listeners\n // in bubble phase will have the correct symbols\n {\n capture: true\n });\n})();","/**\n * Does the `EventTarget` look like a `Node` based on \"duck typing\".\n *\n * Helpful when the `Node` might be outside of the current document\n * so we cannot to an `target instanceof Node` check.\n */\nfunction isNodeLike(target) {\n return 'nodeName' in target;\n}\n\n/**\n * Is an `EventTarget` a `Node` from another `window`?\n */\nexport function isFromAnotherWindow(eventTarget) {\n return isNodeLike(eventTarget) && eventTarget.ownerDocument !== document;\n}","import { isFirefox } from '../is-firefox';\nimport { isSafari } from '../is-safari';\nimport { isLeavingWindowInSafari } from './count-events-for-safari';\nimport { isFromAnotherWindow } from './is-from-another-window';\nexport function isLeavingWindow(_ref) {\n var dragLeave = _ref.dragLeave;\n var type = dragLeave.type,\n relatedTarget = dragLeave.relatedTarget;\n if (type !== 'dragleave') {\n return false;\n }\n if (isSafari()) {\n return isLeavingWindowInSafari({\n dragLeave: dragLeave\n });\n }\n\n // Standard check: if going to `null` we are leaving the `window`\n if (relatedTarget == null) {\n return true;\n }\n\n /**\n * 🦊 Exception: `iframe` in Firefox (`125.0`)\n *\n * Case 1: parent `window` → child `iframe`\n * `dragLeave.relatedTarget` is element _inside_ the child `iframe`\n * (foreign element)\n *\n * Case 2: child `iframe` → parent `window`\n * `dragLeave.relatedTarget` is the `iframe` in the parent `window`\n * (foreign element)\n */\n\n if (isFirefox()) {\n return isFromAnotherWindow(relatedTarget);\n }\n\n /**\n * 🌏 Exception: `iframe` in Chrome (`124.0`)\n *\n * Case 1: parent `window` → child `iframe`\n * `dragLeave.relatedTarget` is the `iframe` in the parent `window`\n *\n * Case 2: child `iframe` → parent `window`\n * `dragLeave.relatedTarget` is `null` *(standard check)*\n */\n\n // Case 2\n // Using `instanceof` check as the element will be in the same `window`\n return relatedTarget instanceof HTMLIFrameElement;\n}","export function getBindingsForBrokenDrags(_ref) {\n var onDragEnd = _ref.onDragEnd;\n return [\n // ## Detecting drag ending for removed draggables\n //\n // If a draggable element is removed during a drag and the user drops:\n // 1. if over a valid drop target: we get a \"drop\" event to know the drag is finished\n // 2. if not over a valid drop target (or cancelled): we get nothing\n // The \"dragend\" event will not fire on the source draggable if it has been\n // removed from the DOM.\n // So we need to figure out if a drag operation has finished by looking at other events\n // We can do this by looking at other events\n\n // ### First detection: \"pointermove\" events\n\n // 1. \"pointermove\" events cannot fire during a drag and drop operation\n // according to the spec. So if we get a \"pointermove\" it means that\n // the drag and drop operations has finished. So if we get a \"pointermove\"\n // we know that the drag is over\n // 2. 🦊😤 Drag and drop operations are _supposed_ to suppress\n // other pointer events. However, firefox will allow a few\n // pointer event to get through after a drag starts.\n // The most I've seen is 3\n {\n type: 'pointermove',\n listener: function () {\n var callCount = 0;\n return function listener() {\n // Using 20 as it is far bigger than the most observed (3)\n if (callCount < 20) {\n callCount++;\n return;\n }\n onDragEnd();\n };\n }()\n },\n // ### Second detection: \"pointerdown\" events\n\n // If we receive this event then we know that a drag operation has finished\n // and potentially another one is about to start.\n // Note: `pointerdown` fires on all browsers / platforms before \"dragstart\"\n {\n type: 'pointerdown',\n listener: onDragEnd\n }];\n}","export function getInput(event) {\n return {\n altKey: event.altKey,\n button: event.button,\n buttons: event.buttons,\n ctrlKey: event.ctrlKey,\n metaKey: event.metaKey,\n shiftKey: event.shiftKey,\n clientX: event.clientX,\n clientY: event.clientY,\n pageX: event.pageX,\n pageY: event.pageY\n };\n}","var rafSchd = function rafSchd(fn) {\n var lastArgs = [];\n var frameId = null;\n\n var wrapperFn = function wrapperFn() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n lastArgs = args;\n\n if (frameId) {\n return;\n }\n\n frameId = requestAnimationFrame(function () {\n frameId = null;\n fn.apply(void 0, lastArgs);\n });\n };\n\n wrapperFn.cancel = function () {\n if (!frameId) {\n return;\n }\n\n cancelAnimationFrame(frameId);\n frameId = null;\n };\n\n return wrapperFn;\n};\n\nexport default rafSchd;\n","import rafSchd from 'raf-schd';\nvar scheduleOnDrag = rafSchd(function (fn) {\n return fn();\n});\nvar dragStart = function () {\n var scheduled = null;\n function schedule(fn) {\n var frameId = requestAnimationFrame(function () {\n scheduled = null;\n fn();\n });\n scheduled = {\n frameId: frameId,\n fn: fn\n };\n }\n function flush() {\n if (scheduled) {\n cancelAnimationFrame(scheduled.frameId);\n scheduled.fn();\n scheduled = null;\n }\n }\n return {\n schedule: schedule,\n flush: flush\n };\n}();\nexport function makeDispatch(_ref) {\n var source = _ref.source,\n initial = _ref.initial,\n dispatchEvent = _ref.dispatchEvent;\n var previous = {\n dropTargets: []\n };\n function safeDispatch(args) {\n dispatchEvent(args);\n previous = {\n dropTargets: args.payload.location.current.dropTargets\n };\n }\n var dispatch = {\n start: function start(_ref2) {\n var nativeSetDragImage = _ref2.nativeSetDragImage;\n // Ensuring that both `onGenerateDragPreview` and `onDragStart` get the same location.\n // We do this so that `previous` is`[]` in `onDragStart` (which is logical)\n var location = {\n current: initial,\n previous: previous,\n initial: initial\n };\n // a `onGenerateDragPreview` does _not_ add another entry for `previous`\n // onDragPreview\n safeDispatch({\n eventName: 'onGenerateDragPreview',\n payload: {\n source: source,\n location: location,\n nativeSetDragImage: nativeSetDragImage\n }\n });\n dragStart.schedule(function () {\n safeDispatch({\n eventName: 'onDragStart',\n payload: {\n source: source,\n location: location\n }\n });\n });\n },\n dragUpdate: function dragUpdate(_ref3) {\n var current = _ref3.current;\n dragStart.flush();\n scheduleOnDrag.cancel();\n safeDispatch({\n eventName: 'onDropTargetChange',\n payload: {\n source: source,\n location: {\n initial: initial,\n previous: previous,\n current: current\n }\n }\n });\n },\n drag: function drag(_ref4) {\n var current = _ref4.current;\n scheduleOnDrag(function () {\n dragStart.flush();\n var location = {\n initial: initial,\n previous: previous,\n current: current\n };\n safeDispatch({\n eventName: 'onDrag',\n payload: {\n source: source,\n location: location\n }\n });\n });\n },\n drop: function drop(_ref5) {\n var current = _ref5.current,\n updatedSourcePayload = _ref5.updatedSourcePayload;\n dragStart.flush();\n scheduleOnDrag.cancel();\n safeDispatch({\n eventName: 'onDrop',\n payload: {\n source: updatedSourcePayload !== null && updatedSourcePayload !== void 0 ? updatedSourcePayload : source,\n location: {\n current: current,\n previous: previous,\n initial: initial\n }\n }\n });\n }\n };\n return dispatch;\n}","import _toConsumableArray from \"@babel/runtime/helpers/toConsumableArray\";\nimport { bindAll } from 'bind-event-listener';\nimport { getElementFromPointWithoutHoneypot } from '../honey-pot-fix/get-element-from-point-without-honey-pot';\nimport { isHoneyPotElement } from '../honey-pot-fix/is-honey-pot-element';\nimport { isLeavingWindow } from '../util/changing-window/is-leaving-window';\nimport { getBindingsForBrokenDrags } from '../util/detect-broken-drag';\nimport { getInput } from '../util/get-input';\nimport { makeDispatch } from './dispatch-consumer-event';\nvar globalState = {\n isActive: false\n};\nfunction canStart() {\n return !globalState.isActive;\n}\nfunction getNativeSetDragImage(event) {\n if (event.dataTransfer) {\n // need to use `.bind` as `setDragImage` is required\n // to be run with `event.dataTransfer` as the \"this\" context\n return event.dataTransfer.setDragImage.bind(event.dataTransfer);\n }\n return null;\n}\nfunction hasHierarchyChanged(_ref) {\n var current = _ref.current,\n next = _ref.next;\n if (current.length !== next.length) {\n return true;\n }\n // not checking stickiness, data or dropEffect,\n // just whether the hierarchy has changed\n for (var i = 0; i < current.length; i++) {\n if (current[i].element !== next[i].element) {\n return true;\n }\n }\n return false;\n}\nfunction start(_ref2) {\n var event = _ref2.event,\n dragType = _ref2.dragType,\n getDropTargetsOver = _ref2.getDropTargetsOver,\n dispatchEvent = _ref2.dispatchEvent;\n if (!canStart()) {\n return;\n }\n var initial = getStartLocation({\n event: event,\n dragType: dragType,\n getDropTargetsOver: getDropTargetsOver\n });\n globalState.isActive = true;\n var state = {\n current: initial\n };\n\n // Setting initial drop effect for the drag\n setDropEffectOnEvent({\n event: event,\n current: initial.dropTargets\n });\n var dispatch = makeDispatch({\n source: dragType.payload,\n dispatchEvent: dispatchEvent,\n initial: initial\n });\n function updateState(next) {\n // only looking at whether hierarchy has changed to determine whether something as 'changed'\n var hasChanged = hasHierarchyChanged({\n current: state.current.dropTargets,\n next: next.dropTargets\n });\n\n // Always updating the state to include latest data, dropEffect and stickiness\n // Only updating consumers if the hierarchy has changed in some way\n // Consumers can get the latest data by using `onDrag`\n state.current = next;\n if (hasChanged) {\n dispatch.dragUpdate({\n current: state.current\n });\n }\n }\n function onUpdateEvent(event) {\n var input = getInput(event);\n\n // If we are over the honey pot, we need to get the element\n // that the user would have been over if not for the honey pot\n var target = isHoneyPotElement(event.target) ? getElementFromPointWithoutHoneypot({\n x: input.clientX,\n y: input.clientY\n }) : event.target;\n var nextDropTargets = getDropTargetsOver({\n target: target,\n input: input,\n source: dragType.payload,\n current: state.current.dropTargets\n });\n if (nextDropTargets.length) {\n // 🩸 must call `event.preventDefault()` to allow a browser drop to occur\n event.preventDefault();\n setDropEffectOnEvent({\n event: event,\n current: nextDropTargets\n });\n }\n updateState({\n dropTargets: nextDropTargets,\n input: input\n });\n }\n function cancel() {\n // The spec behaviour is that when a drag is cancelled, or when dropping on no drop targets,\n // a \"dragleave\" event is fired on the active drop target before a \"dragend\" event.\n // We are replicating that behaviour in `cancel` if there are any active drop targets to\n // ensure consistent behaviour.\n //\n // Note: When cancelling, or dropping on no drop targets, a \"dragleave\" event\n // will have already cleared the dropTargets to `[]` (as that particular \"dragleave\" has a `relatedTarget` of `null`)\n\n if (state.current.dropTargets.length) {\n updateState({\n dropTargets: [],\n input: state.current.input\n });\n }\n dispatch.drop({\n current: state.current,\n updatedSourcePayload: null\n });\n finish();\n }\n function finish() {\n globalState.isActive = false;\n unbindEvents();\n }\n var unbindEvents = bindAll(window, [{\n // 👋 Note: we are repurposing the `dragover` event as our `drag` event\n // this is because firefox does not publish pointer coordinates during\n // a `drag` event, but does for every other type of drag event\n // `dragover` fires on all elements that are being dragged over\n // Because we are binding to `window` - our `dragover` is effectively the same as a `drag`\n // 🦊😤\n type: 'dragover',\n listener: function listener(event) {\n // We need to regularly calculate the drop targets in order to allow:\n // - dynamic `canDrop()` checks\n // - rapid updating `getData()` calls to attach data in response to user input (eg for edge detection)\n // Sadly we cannot schedule inspecting changes resulting from this event\n // we need to be able to conditionally cancel the event with `event.preventDefault()`\n // to enable the correct native drop experience.\n\n // 1. check to see if anything has changed\n onUpdateEvent(event);\n\n // 2. let consumers know a move has occurred\n // This will include the latest 'input' values\n dispatch.drag({\n current: state.current\n });\n }\n }, {\n type: 'dragenter',\n listener: onUpdateEvent\n }, {\n type: 'dragleave',\n listener: function listener(event) {\n if (!isLeavingWindow({\n dragLeave: event\n })) {\n return;\n }\n\n /**\n * At this point we don't know if a drag is being cancelled,\n * or if a drag is leaving the `window`.\n *\n * Both have:\n * 1. \"dragleave\" (with `relatedTarget: null`)\n * 2. \"dragend\" (a \"dragend\" can occur when outside the `window`)\n *\n * **Clearing drop targets**\n *\n * For either case we are clearing the the drop targets\n *\n * - cancelling: we clear drop targets in `\"dragend\"` anyway\n * - leaving the `window`: we clear the drop targets (to clear stickiness)\n *\n * **Leaving the window and finishing the drag**\n *\n * _internal drags_\n *\n * - The drag continues when the user is outside the `window`\n * and can resume if the user drags back over the `window`,\n * or end when the user drops in an external `window`.\n * - We will get a `\"dragend\"`, or we can listen for other\n * events to determine the drag is finished when the user re-enters the `window`).\n *\n * _external drags_\n *\n * - We conclude the drag operation.\n * - We have no idea if the user will drag back over the `window`,\n * or if the drag ends elsewhere.\n * - We will create a new drag if the user re-enters the `window`.\n *\n * **Not updating `input`**\n *\n * 🐛 Bug[Chrome] the final `\"dragleave\"` has default input values (eg `clientX == 0`)\n * Workaround: intentionally not updating `input` in \"dragleave\"\n * rather than the users current input values\n * - [Conversation](https://twitter.com/alexandereardon/status/1642697633864241152)\n * - [Bug](https://bugs.chromium.org/p/chromium/issues/detail?id=1429937)\n **/\n\n updateState({\n input: state.current.input,\n dropTargets: []\n });\n if (dragType.startedFrom === 'external') {\n cancel();\n }\n }\n }, {\n // A \"drop\" can only happen if the browser allowed the drop\n type: 'drop',\n listener: function listener(event) {\n // Capture the final input.\n // We are capturing the final `input` for the\n // most accurate honey pot experience\n state.current = {\n dropTargets: state.current.dropTargets,\n input: getInput(event)\n };\n\n /** If there are no drop targets, then we will get\n * a \"drop\" event if:\n * - `preventUnhandled()` is being used\n * - there is an unmanaged drop target (eg another library)\n * In these cases, it's up to the consumer\n * to handle the drop if it's not over one of our drop targets\n * - `preventUnhandled()` will cancel the \"drop\"\n * - unmanaged drop targets can handle the \"drop\" how they want to\n * We won't call `event.preventDefault()` in this call path */\n\n if (!state.current.dropTargets.length) {\n cancel();\n return;\n }\n event.preventDefault();\n\n // applying the latest drop effect to the event\n setDropEffectOnEvent({\n event: event,\n current: state.current.dropTargets\n });\n dispatch.drop({\n current: state.current,\n // When dropping something native, we need to extract the latest\n // `.items` from the \"drop\" event as it is now accessible\n updatedSourcePayload: dragType.type === 'external' ? dragType.getDropPayload(event) : null\n });\n finish();\n }\n }, {\n // \"dragend\" fires when on the drag source (eg a draggable element)\n // when the drag is finished.\n // \"dragend\" will fire after \"drop\" (if there was a successful drop)\n // \"dragend\" does not fire if the draggable source has been removed during the drag\n // or for external drag sources (eg files)\n\n // This \"dragend\" listener will not fire if there was a successful drop\n // as we will have already removed the event listener\n\n type: 'dragend',\n listener: function listener(event) {\n // In firefox, the position of the \"dragend\" event can\n // be a bit different to the last \"dragover\" event.\n // Updating the input so we can get the best possible\n // information for the honey pot.\n state.current = {\n dropTargets: state.current.dropTargets,\n input: getInput(event)\n };\n cancel();\n }\n }].concat(_toConsumableArray(getBindingsForBrokenDrags({\n onDragEnd: cancel\n }))),\n // Once we have started a managed drag operation it is important that we see / own all drag events\n // We got one adoption bug pop up where some code was stopping (`event.stopPropagation()`)\n // all \"drop\" events in the bubble phase on the `document.body`.\n // This meant that we never saw the \"drop\" event.\n {\n capture: true\n });\n dispatch.start({\n nativeSetDragImage: getNativeSetDragImage(event)\n });\n}\nfunction setDropEffectOnEvent(_ref3) {\n var _current$;\n var event = _ref3.event,\n current = _ref3.current;\n // setting the `dropEffect` to be the innerMost drop targets dropEffect\n var innerMost = (_current$ = current[0]) === null || _current$ === void 0 ? void 0 : _current$.dropEffect;\n if (innerMost != null && event.dataTransfer) {\n event.dataTransfer.dropEffect = innerMost;\n }\n}\nfunction getStartLocation(_ref4) {\n var event = _ref4.event,\n dragType = _ref4.dragType,\n getDropTargetsOver = _ref4.getDropTargetsOver;\n var input = getInput(event);\n\n // When dragging from outside of the browser,\n // the drag is not being sourced from any local drop targets\n if (dragType.startedFrom === 'external') {\n return {\n input: input,\n dropTargets: []\n };\n }\n var dropTargets = getDropTargetsOver({\n input: input,\n source: dragType.payload,\n target: event.target,\n current: []\n });\n return {\n input: input,\n dropTargets: dropTargets\n };\n}\nexport var lifecycle = {\n canStart: canStart,\n start: start\n};","// Extending `Map` to allow us to link Key and Values together\n\nvar ledger = new Map();\nfunction registerUsage(_ref) {\n var typeKey = _ref.typeKey,\n mount = _ref.mount;\n var entry = ledger.get(typeKey);\n if (entry) {\n entry.usageCount++;\n return entry;\n }\n var initial = {\n typeKey: typeKey,\n unmount: mount(),\n usageCount: 1\n };\n ledger.set(typeKey, initial);\n return initial;\n}\nexport function register(args) {\n var entry = registerUsage(args);\n return function unregister() {\n entry.usageCount--;\n if (entry.usageCount > 0) {\n return;\n }\n // Only a single usage left, remove it\n entry.unmount();\n ledger.delete(args.typeKey);\n };\n}","/** Create a new combined function that will call all the provided functions */\nexport function combine() {\n for (var _len = arguments.length, fns = new Array(_len), _key = 0; _key < _len; _key++) {\n fns[_key] = arguments[_key];\n }\n return function cleanup() {\n fns.forEach(function (fn) {\n return fn();\n });\n };\n}","export function addAttribute(element, _ref) {\n var attribute = _ref.attribute,\n value = _ref.value;\n element.setAttribute(attribute, value);\n return function () {\n return element.removeAttribute(attribute);\n };\n}","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\nimport _toConsumableArray from \"@babel/runtime/helpers/toConsumableArray\";\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== \"undefined\" && o[Symbol.iterator] || o[\"@@iterator\"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === \"number\") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError(\"Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }\nimport { combine } from '../public-utils/combine';\nimport { addAttribute } from '../util/add-attribute';\nfunction copyReverse(array) {\n return array.slice(0).reverse();\n}\nexport function makeDropTarget(_ref) {\n var typeKey = _ref.typeKey,\n defaultDropEffect = _ref.defaultDropEffect;\n var registry = new WeakMap();\n var dropTargetDataAtt = \"data-drop-target-for-\".concat(typeKey);\n var dropTargetSelector = \"[\".concat(dropTargetDataAtt, \"]\");\n function addToRegistry(args) {\n registry.set(args.element, args);\n return function () {\n return registry.delete(args.element);\n };\n }\n function dropTargetForConsumers(args) {\n // Guardrail: warn if the draggable element is already registered\n if (process.env.NODE_ENV !== 'production') {\n var existing = registry.get(args.element);\n if (existing) {\n // eslint-disable-next-line no-console\n console.warn(\"You have already registered a [\".concat(typeKey, \"] dropTarget on the same element\"), {\n existing: existing,\n proposed: args\n });\n }\n if (args.element instanceof HTMLIFrameElement) {\n // eslint-disable-next-line no-console\n console.warn(\"\\n We recommend not registering elements as drop targets\\n as it can result in some strange browser event ordering.\\n \" // Removing newlines and excessive whitespace\n .replace(/\\s{2,}/g, ' ').trim());\n }\n }\n return combine(addAttribute(args.element, {\n attribute: dropTargetDataAtt,\n value: 'true'\n }), addToRegistry(args));\n }\n function getActualDropTargets(_ref2) {\n var _args$getData, _args$getData2, _args$getDropEffect, _args$getDropEffect2;\n var source = _ref2.source,\n target = _ref2.target,\n input = _ref2.input,\n _ref2$result = _ref2.result,\n result = _ref2$result === void 0 ? [] : _ref2$result;\n if (target == null) {\n return result;\n }\n if (!(target instanceof Element)) {\n // For \"text-selection\" drags, the original `target`\n // is not an `Element`, so we need to start looking from\n // the parent element\n if (target instanceof Node) {\n return getActualDropTargets({\n source: source,\n target: target.parentElement,\n input: input,\n result: result\n });\n }\n\n // not sure what we are working with,\n // so we can exit.\n return result;\n }\n var closest = target.closest(dropTargetSelector);\n\n // Cannot find anything else\n if (closest == null) {\n return result;\n }\n var args = registry.get(closest);\n\n // error: something had a dropTargetSelector but we could not\n // find a match. For now, failing silently\n if (args == null) {\n return result;\n }\n var feedback = {\n input: input,\n source: source,\n element: args.element\n };\n\n // if dropping is not allowed, skip this drop target\n // and continue looking up the DOM tree\n if (args.canDrop && !args.canDrop(feedback)) {\n return getActualDropTargets({\n source: source,\n target: args.element.parentElement,\n input: input,\n result: result\n });\n }\n\n // calculate our new record\n var data = (_args$getData = (_args$getData2 = args.getData) === null || _args$getData2 === void 0 ? void 0 : _args$getData2.call(args, feedback)) !== null && _args$getData !== void 0 ? _args$getData : {};\n var dropEffect = (_args$getDropEffect = (_args$getDropEffect2 = args.getDropEffect) === null || _args$getDropEffect2 === void 0 ? void 0 : _args$getDropEffect2.call(args, feedback)) !== null && _args$getDropEffect !== void 0 ? _args$getDropEffect : defaultDropEffect;\n var record = {\n data: data,\n element: args.element,\n dropEffect: dropEffect,\n // we are collecting _actual_ drop targets, so these are\n // being applied _not_ due to stickiness\n isActiveDueToStickiness: false\n };\n return getActualDropTargets({\n source: source,\n target: args.element.parentElement,\n input: input,\n // Using bubble ordering. Same ordering as `event.getPath()`\n result: [].concat(_toConsumableArray(result), [record])\n });\n }\n function notifyCurrent(_ref3) {\n var eventName = _ref3.eventName,\n payload = _ref3.payload;\n var _iterator = _createForOfIteratorHelper(payload.location.current.dropTargets),\n _step;\n try {\n for (_iterator.s(); !(_step = _iterator.n()).done;) {\n var _entry$eventName;\n var record = _step.value;\n var entry = registry.get(record.element);\n var _args = _objectSpread(_objectSpread({}, payload), {}, {\n self: record\n });\n entry === null || entry === void 0 || (_entry$eventName = entry[eventName]) === null || _entry$eventName === void 0 || _entry$eventName.call(entry,\n // I cannot seem to get the types right here.\n // TS doesn't seem to like that one event can need `nativeSetDragImage`\n // @ts-expect-error\n _args);\n }\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n }\n var actions = {\n onGenerateDragPreview: notifyCurrent,\n onDrag: notifyCurrent,\n onDragStart: notifyCurrent,\n onDrop: notifyCurrent,\n onDropTargetChange: function onDropTargetChange(_ref4) {\n var payload = _ref4.payload;\n var isCurrent = new Set(payload.location.current.dropTargets.map(function (record) {\n return record.element;\n }));\n var visited = new Set();\n var _iterator2 = _createForOfIteratorHelper(payload.location.previous.dropTargets),\n _step2;\n try {\n for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {\n var _entry$onDropTargetCh;\n var record = _step2.value;\n visited.add(record.element);\n var entry = registry.get(record.element);\n var isOver = isCurrent.has(record.element);\n var _args2 = _objectSpread(_objectSpread({}, payload), {}, {\n self: record\n });\n entry === null || entry === void 0 || (_entry$onDropTargetCh = entry.onDropTargetChange) === null || _entry$onDropTargetCh === void 0 || _entry$onDropTargetCh.call(entry, _args2);\n\n // if we cannot find the drop target in the current array, then it has been left\n if (!isOver) {\n var _entry$onDragLeave;\n entry === null || entry === void 0 || (_entry$onDragLeave = entry.onDragLeave) === null || _entry$onDragLeave === void 0 || _entry$onDragLeave.call(entry, _args2);\n }\n }\n } catch (err) {\n _iterator2.e(err);\n } finally {\n _iterator2.f();\n }\n var _iterator3 = _createForOfIteratorHelper(payload.location.current.dropTargets),\n _step3;\n try {\n for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {\n var _entry$onDropTargetCh2, _entry$onDragEnter;\n var _record = _step3.value;\n // already published an update to this drop target\n if (visited.has(_record.element)) {\n continue;\n }\n // at this point we have a new drop target that is being entered into\n var _args3 = _objectSpread(_objectSpread({}, payload), {}, {\n self: _record\n });\n var _entry = registry.get(_record.element);\n _entry === null || _entry === void 0 || (_entry$onDropTargetCh2 = _entry.onDropTargetChange) === null || _entry$onDropTargetCh2 === void 0 || _entry$onDropTargetCh2.call(_entry, _args3);\n _entry === null || _entry === void 0 || (_entry$onDragEnter = _entry.onDragEnter) === null || _entry$onDragEnter === void 0 || _entry$onDragEnter.call(_entry, _args3);\n }\n } catch (err) {\n _iterator3.e(err);\n } finally {\n _iterator3.f();\n }\n }\n };\n function dispatchEvent(args) {\n actions[args.eventName](args);\n }\n function getIsOver(_ref5) {\n var source = _ref5.source,\n target = _ref5.target,\n input = _ref5.input,\n current = _ref5.current;\n var actual = getActualDropTargets({\n source: source,\n target: target,\n input: input\n });\n\n // stickiness is only relevant when we have less\n // drop targets than we did before\n if (actual.length >= current.length) {\n return actual;\n }\n\n // less 'actual' drop targets than before,\n // we need to see if 'stickiness' applies\n\n // An old drop target will continue to be dropped on if:\n // 1. it has the same parent\n // 2. nothing exists in it's previous index\n\n var lastCaptureOrdered = copyReverse(current);\n var actualCaptureOrdered = copyReverse(actual);\n var resultCaptureOrdered = [];\n for (var index = 0; index < lastCaptureOrdered.length; index++) {\n var _argsForLast$getIsSti;\n var last = lastCaptureOrdered[index];\n var fresh = actualCaptureOrdered[index];\n\n // if a record is in the new index -> use that\n // it will have the latest data + dropEffect\n if (fresh != null) {\n resultCaptureOrdered.push(fresh);\n continue;\n }\n\n // At this point we have no drop target in the old spot\n // Check to see if we can use a previous sticky drop target\n\n // The \"parent\" is the one inside of `resultCaptureOrdered`\n // (the parent might be a drop target that was sticky)\n var parent = resultCaptureOrdered[index - 1];\n var lastParent = lastCaptureOrdered[index - 1];\n\n // Stickiness is based on parent relationships, so if the parent relationship has change\n // then we can stop our search\n if ((parent === null || parent === void 0 ? void 0 : parent.element) !== (lastParent === null || lastParent === void 0 ? void 0 : lastParent.element)) {\n break;\n }\n\n // We need to check whether the old drop target can still be dropped on\n\n var argsForLast = registry.get(last.element);\n\n // We cannot drop on a drop target that is no longer mounted\n if (!argsForLast) {\n break;\n }\n var feedback = {\n input: input,\n source: source,\n element: argsForLast.element\n };\n\n // We cannot drop on a drop target that no longer allows being dropped on\n if (argsForLast.canDrop && !argsForLast.canDrop(feedback)) {\n break;\n }\n\n // We cannot drop on a drop target that is no longer sticky\n if (!((_argsForLast$getIsSti = argsForLast.getIsSticky) !== null && _argsForLast$getIsSti !== void 0 && _argsForLast$getIsSti.call(argsForLast, feedback))) {\n break;\n }\n\n // Note: intentionally not recollecting `getData()` or `getDropEffect()`\n // Previous values for `data` and `dropEffect` will be borrowed\n // This is to prevent things like the 'closest edge' changing when\n // no longer over a drop target.\n // We could change our mind on this behaviour in the future\n\n resultCaptureOrdered.push(_objectSpread(_objectSpread({}, last), {}, {\n // making it clear to consumers this drop target is active due to stickiness\n isActiveDueToStickiness: true\n }));\n }\n\n // return bubble ordered result\n return copyReverse(resultCaptureOrdered);\n }\n return {\n dropTargetForConsumers: dropTargetForConsumers,\n getIsOver: getIsOver,\n dispatchEvent: dispatchEvent\n };\n}","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\nfunction _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== \"undefined\" && o[Symbol.iterator] || o[\"@@iterator\"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === \"number\") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError(\"Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nexport function makeMonitor() {\n var registry = new Set();\n var dragging = null;\n function tryAddToActive(monitor) {\n if (!dragging) {\n return;\n }\n // Monitor is allowed to monitor events if:\n // 1. It has no `canMonitor` function (default is that a monitor can listen to everything)\n // 2. `canMonitor` returns true\n if (!monitor.canMonitor || monitor.canMonitor(dragging.canMonitorArgs)) {\n dragging.active.add(monitor);\n }\n }\n function monitorForConsumers(args) {\n // We are giving each `args` a new reference so that you\n // can create multiple monitors with the same `args`.\n var entry = _objectSpread({}, args);\n registry.add(entry);\n\n // if there is an active drag we need to see if this new monitor is relevant\n tryAddToActive(entry);\n return function cleanup() {\n registry.delete(entry);\n\n // We need to stop publishing events during a drag to this monitor!\n if (dragging) {\n dragging.active.delete(entry);\n }\n };\n }\n function dispatchEvent(_ref) {\n var eventName = _ref.eventName,\n payload = _ref.payload;\n if (eventName === 'onGenerateDragPreview') {\n dragging = {\n canMonitorArgs: {\n initial: payload.location.initial,\n source: payload.source\n },\n active: new Set()\n };\n var _iterator = _createForOfIteratorHelper(registry),\n _step;\n try {\n for (_iterator.s(); !(_step = _iterator.n()).done;) {\n var monitor = _step.value;\n tryAddToActive(monitor);\n }\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n }\n\n // This should never happen.\n if (!dragging) {\n return;\n }\n\n // Creating an array from the set _before_ iterating\n // This is so that monitors added during the current event will not be called.\n // This behaviour matches native EventTargets where an event listener\n // cannot add another event listener during an active event to the same\n // event target in the same event (for us we have a single global event target)\n var active = Array.from(dragging.active);\n for (var _i = 0, _active = active; _i < _active.length; _i++) {\n var _monitor = _active[_i];\n // A monitor can be removed by another monitor during an event.\n // We need to check that the monitor is still registered before calling it\n if (dragging.active.has(_monitor)) {\n var _monitor$eventName;\n // @ts-expect-error: I cannot get this type working!\n (_monitor$eventName = _monitor[eventName]) === null || _monitor$eventName === void 0 || _monitor$eventName.call(_monitor, payload);\n }\n }\n if (eventName === 'onDrop') {\n dragging.active.clear();\n dragging = null;\n }\n }\n return {\n dispatchEvent: dispatchEvent,\n monitorForConsumers: monitorForConsumers\n };\n}","import { lifecycle } from '../ledger/lifecycle-manager';\nimport { register } from '../ledger/usage-ledger';\nimport { makeDropTarget } from './make-drop-target';\nimport { makeMonitor } from './make-monitor';\nexport function makeAdapter(_ref) {\n var typeKey = _ref.typeKey,\n mount = _ref.mount,\n dispatchEventToSource = _ref.dispatchEventToSource,\n onPostDispatch = _ref.onPostDispatch,\n defaultDropEffect = _ref.defaultDropEffect;\n var monitorAPI = makeMonitor();\n var dropTargetAPI = makeDropTarget({\n typeKey: typeKey,\n defaultDropEffect: defaultDropEffect\n });\n function dispatchEvent(args) {\n // 1. forward the event to source\n dispatchEventToSource === null || dispatchEventToSource === void 0 || dispatchEventToSource(args);\n\n // 2. forward the event to relevant dropTargets\n dropTargetAPI.dispatchEvent(args);\n\n // 3. forward event to monitors\n monitorAPI.dispatchEvent(args);\n\n // 4. post consumer dispatch (used for honey pot fix)\n onPostDispatch === null || onPostDispatch === void 0 || onPostDispatch(args);\n }\n function start(_ref2) {\n var event = _ref2.event,\n dragType = _ref2.dragType;\n lifecycle.start({\n event: event,\n dragType: dragType,\n getDropTargetsOver: dropTargetAPI.getIsOver,\n dispatchEvent: dispatchEvent\n });\n }\n function registerUsage() {\n function mountAdapter() {\n var api = {\n canStart: lifecycle.canStart,\n start: start\n };\n return mount(api);\n }\n return register({\n typeKey: typeKey,\n mount: mountAdapter\n });\n }\n return {\n registerUsage: registerUsage,\n dropTarget: dropTargetAPI.dropTargetForConsumers,\n monitor: monitorAPI.monitorForConsumers\n };\n}","import { once } from '../public-utils/once';\n\n// using `cache` as our `isAndroid()` result will not change in a browser\nexport var isAndroid = once(function isAndroid() {\n return navigator.userAgent.toLocaleLowerCase().includes('android');\n});\nexport var androidFallbackText = 'pdnd:android-fallback';","// Why we put the media types in their own files:\n//\n// - we are not putting them all in one file as not all adapters need all types\n// - we are not putting them in the external helpers as some things just need the\n// types and not the external functions code\nexport var textMediaType = 'text/plain';","// Why we put the media types in their own files:\n//\n// - we are not putting them all in one file as not all adapters need all types\n// - we are not putting them in the external helpers as some things just need the\n// types and not the external functions code\nexport var urlMediaType = 'text/uri-list';","/**\n * This key has been pulled into a separate module\n * so that the external adapter does not need to import\n * the element adapter\n */\nexport var elementAdapterNativeDataKey = 'application/vnd.pdnd';","import _slicedToArray from \"@babel/runtime/helpers/slicedToArray\";\nimport { bind } from 'bind-event-listener';\nimport { getElementFromPointWithoutHoneypot } from '../honey-pot-fix/get-element-from-point-without-honey-pot';\nimport { makeHoneyPotFix } from '../honey-pot-fix/make-honey-pot-fix';\nimport { makeAdapter } from '../make-adapter/make-adapter';\nimport { combine } from '../public-utils/combine';\nimport { addAttribute } from '../util/add-attribute';\nimport { androidFallbackText, isAndroid } from '../util/android';\nimport { getInput } from '../util/get-input';\nimport { textMediaType } from '../util/media-types/text-media-type';\nimport { urlMediaType } from '../util/media-types/url-media-type';\nimport { elementAdapterNativeDataKey } from './element-adapter-native-data-key';\nvar draggableRegistry = new WeakMap();\nfunction addToRegistry(args) {\n draggableRegistry.set(args.element, args);\n return function cleanup() {\n draggableRegistry.delete(args.element);\n };\n}\nvar honeyPotFix = makeHoneyPotFix();\nvar adapter = makeAdapter({\n typeKey: 'element',\n defaultDropEffect: 'move',\n mount: function mount(api) {\n /** Binding event listeners the `document` rather than `window` so that\n * this adapter always gets preference over the text adapter.\n * `document` is the first `EventTarget` under `window`\n * https://twitter.com/alexandereardon/status/1604658588311465985\n */\n return combine(honeyPotFix.bindEvents(), bind(document, {\n type: 'dragstart',\n listener: function listener(event) {\n var _entry$dragHandle, _entry$getInitialData, _entry$getInitialData2, _entry$dragHandle2, _entry$getInitialData3, _entry$getInitialData4;\n if (!api.canStart(event)) {\n return;\n }\n\n // If the \"dragstart\" event is cancelled, then a drag won't start\n // There will be no further drag operation events (eg no \"dragend\" event)\n if (event.defaultPrevented) {\n return;\n }\n\n // Technically `dataTransfer` can be `null` according to the types\n // But that behaviour does not seem to appear in the spec.\n // If there is not `dataTransfer`, we can assume something is wrong and not\n // start a drag\n if (!event.dataTransfer) {\n // Including this code on \"test\" and \"development\" environments:\n // - Browser tests commonly run against \"development\" builds\n // - Unit tests commonly run in \"test\"\n if (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line no-console\n console.warn(\"\\n It appears as though you have are not testing DragEvents correctly.\\n\\n - If you are unit testing, ensure you have polyfilled DragEvent.\\n - If you are browser testing, ensure you are dispatching drag events correctly.\\n\\n Please see our testing guides for more information:\\n https://atlassian.design/components/pragmatic-drag-and-drop/core-package/testing\\n \".replace(/ {2}/g, ''));\n }\n return;\n }\n\n // the closest parent that is a draggable element will be marked as\n // the `event.target` for the event\n var target = event.target;\n\n // this source is only for elements\n // Note: only HTMLElements can have the \"draggable\" attribute\n if (!(target instanceof HTMLElement)) {\n return null;\n }\n\n // see if the thing being dragged is owned by us\n var entry = draggableRegistry.get(target);\n\n // no matching element found\n // → dragging an element with `draggable=\"true\"` that is not controlled by us\n if (!entry) {\n return null;\n }\n var input = getInput(event);\n var feedback = {\n element: entry.element,\n dragHandle: (_entry$dragHandle = entry.dragHandle) !== null && _entry$dragHandle !== void 0 ? _entry$dragHandle : null,\n input: input\n };\n\n // Check: does the draggable want to allow dragging?\n if (entry.canDrag && !entry.canDrag(feedback)) {\n // cancel drag operation if we cannot drag\n event.preventDefault();\n return null;\n }\n\n // Check: is there a drag handle and is the user using it?\n if (entry.dragHandle) {\n // technically don't need this util, but just being\n // consistent with how we look up what is under the users\n // cursor.\n var over = getElementFromPointWithoutHoneypot({\n x: input.clientX,\n y: input.clientY\n });\n\n // if we are not dragging from the drag handle (or something inside the drag handle)\n // then we will cancel the active drag\n if (!entry.dragHandle.contains(over)) {\n event.preventDefault();\n return null;\n }\n }\n\n /**\n * **Goal**\n * Pass information to other applications\n *\n * **Approach**\n * Put data into the native data store\n *\n * **What about the native adapter?**\n * When the element adapter puts native data into the native data store\n * the native adapter is not triggered in the current window,\n * but a native adapter in an external window _can_ be triggered\n *\n * **Why bake this into core?**\n * This functionality could be pulled out and exposed inside of\n * `onGenerateDragPreview`. But decided to make it a part of the\n * base API as it felt like a common enough use case and ended\n * up being a similar amount of code to include this function as\n * it was to expose the hook for it\n */\n var nativeData = (_entry$getInitialData = (_entry$getInitialData2 = entry.getInitialDataForExternal) === null || _entry$getInitialData2 === void 0 ? void 0 : _entry$getInitialData2.call(entry, feedback)) !== null && _entry$getInitialData !== void 0 ? _entry$getInitialData : null;\n if (nativeData) {\n for (var _i = 0, _Object$entries = Object.entries(nativeData); _i < _Object$entries.length; _i++) {\n var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2),\n key = _Object$entries$_i[0],\n data = _Object$entries$_i[1];\n event.dataTransfer.setData(key, data !== null && data !== void 0 ? data : '');\n }\n }\n\n /**\n * 📱 For Android devices, a drag operation will not start unless\n * \"text/plain\" or \"text/uri-list\" data exists in the native data store\n * https://twitter.com/alexandereardon/status/1732189803754713424\n *\n * Tested on:\n * Device: Google Pixel 5\n * Android version: 14 (November 5, 2023)\n * Chrome version: 120.0\n */\n var types = event.dataTransfer.types;\n if (isAndroid() && !types.includes(textMediaType) && !types.includes(urlMediaType)) {\n event.dataTransfer.setData(textMediaType, androidFallbackText);\n }\n\n /**\n * 1. Must set any media type for `iOS15` to work\n * 2. We are also doing adding data so that the native adapter\n * can know that the element adapter has handled this drag\n *\n * We used to wrap this `setData()` in a `try/catch` for Firefox,\n * but it looks like that was not needed.\n *\n * Tested using: https://codesandbox.io/s/checking-firefox-throw-behaviour-on-dragstart-qt8h4f\n *\n * - ✅ Firefox@70.0 (Oct 2019) on macOS Sonoma\n * - ✅ Firefox@70.0 (Oct 2019) on macOS Big Sur\n * - ✅ Firefox@70.0 (Oct 2019) on Windows 10\n *\n * // just checking a few more combinations to be super safe\n *\n * - ✅ Chrome@78 (Oct 2019) on macOS Big Sur\n * - ✅ Chrome@78 (Oct 2019) on Windows 10\n * - ✅ Safari@14.1 on macOS Big Sur\n */\n event.dataTransfer.setData(elementAdapterNativeDataKey, '');\n var payload = {\n element: entry.element,\n dragHandle: (_entry$dragHandle2 = entry.dragHandle) !== null && _entry$dragHandle2 !== void 0 ? _entry$dragHandle2 : null,\n data: (_entry$getInitialData3 = (_entry$getInitialData4 = entry.getInitialData) === null || _entry$getInitialData4 === void 0 ? void 0 : _entry$getInitialData4.call(entry, feedback)) !== null && _entry$getInitialData3 !== void 0 ? _entry$getInitialData3 : {}\n };\n var dragType = {\n type: 'element',\n payload: payload,\n startedFrom: 'internal'\n };\n api.start({\n event: event,\n dragType: dragType\n });\n }\n }));\n },\n dispatchEventToSource: function dispatchEventToSource(_ref) {\n var _draggableRegistry$ge, _draggableRegistry$ge2;\n var eventName = _ref.eventName,\n payload = _ref.payload;\n // During a drag operation, a draggable can be:\n // - remounted with different functions\n // - removed completely\n // So we need to get the latest entry from the registry in order\n // to call the latest event functions\n\n (_draggableRegistry$ge = draggableRegistry.get(payload.source.element)) === null || _draggableRegistry$ge === void 0 || (_draggableRegistry$ge2 = _draggableRegistry$ge[eventName]) === null || _draggableRegistry$ge2 === void 0 || _draggableRegistry$ge2.call(_draggableRegistry$ge,\n // I cannot seem to get the types right here.\n // TS doesn't seem to like that one event can need `nativeSetDragImage`\n // @ts-expect-error\n payload);\n },\n onPostDispatch: honeyPotFix.getOnPostDispatch()\n});\nexport var dropTargetForElements = adapter.dropTarget;\nexport var monitorForElements = adapter.monitor;\nexport function draggable(args) {\n // Guardrail: warn if the drag handle is not contained in draggable element\n if (process.env.NODE_ENV !== 'production') {\n if (args.dragHandle && !args.element.contains(args.dragHandle)) {\n // eslint-disable-next-line no-console\n console.warn('Drag handle element must be contained in draggable element', {\n element: args.element,\n dragHandle: args.dragHandle\n });\n }\n }\n // Guardrail: warn if the draggable element is already registered\n if (process.env.NODE_ENV !== 'production') {\n var existing = draggableRegistry.get(args.element);\n if (existing) {\n // eslint-disable-next-line no-console\n console.warn('You have already registered a `draggable` on the same element', {\n existing: existing,\n proposed: args\n });\n }\n }\n return combine(\n // making the draggable register the adapter rather than drop targets\n // this is because you *must* have a draggable element to start a drag\n // but you _might_ not have any drop targets immediately\n // (You might create drop targets async)\n adapter.registerUsage(), addToRegistry(args), addAttribute(args.element, {\n attribute: 'draggable',\n value: 'true'\n }));\n}\n\n/** Common event payload for all events */\n\n/** A map containing payloads for all events */\n\n/** Common event payload for all drop target events */\n\n/** A map containing payloads for all events on drop targets */\n\n/** Arguments given to all feedback functions (eg `canDrag()`) on for a `draggable()` */\n\n/** Arguments given to all feedback functions (eg `canDrop()`) on a `dropTargetForElements()` */\n\n/** Arguments given to all monitor feedback functions (eg `canMonitor()`) for a `monitorForElements` */","\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n\r\n\r\n\r\n","import BaseIcon from '@primevue/icons/baseicon';\nimport { openBlock, createElementBlock, mergeProps, createElementVNode } from 'vue';\n\nvar script = {\n name: 'ArrowDownIcon',\n \"extends\": BaseIcon\n};\n\nvar _hoisted_1 = /*#__PURE__*/createElementVNode(\"path\", {\n \"fill-rule\": \"evenodd\",\n \"clip-rule\": \"evenodd\",\n d: \"M6.99994 14C6.91097 14.0004 6.82281 13.983 6.74064 13.9489C6.65843 13.9148 6.58387 13.8646 6.52133 13.8013L1.10198 8.38193C0.982318 8.25351 0.917175 8.08367 0.920272 7.90817C0.923368 7.73267 0.994462 7.56523 1.11858 7.44111C1.24269 7.317 1.41014 7.2459 1.58563 7.2428C1.76113 7.23971 1.93098 7.30485 2.0594 7.42451L6.32263 11.6877V0.677419C6.32263 0.497756 6.394 0.325452 6.52104 0.198411C6.64808 0.0713706 6.82039 0 7.00005 0C7.17971 0 7.35202 0.0713706 7.47906 0.198411C7.6061 0.325452 7.67747 0.497756 7.67747 0.677419V11.6877L11.9407 7.42451C12.0691 7.30485 12.2389 7.23971 12.4144 7.2428C12.5899 7.2459 12.7574 7.317 12.8815 7.44111C13.0056 7.56523 13.0767 7.73267 13.0798 7.90817C13.0829 8.08367 13.0178 8.25351 12.8981 8.38193L7.47875 13.8013C7.41621 13.8646 7.34164 13.9148 7.25944 13.9489C7.17727 13.983 7.08912 14.0004 7.00015 14C7.00012 14 7.00009 14 7.00005 14C7.00001 14 6.99998 14 6.99994 14Z\",\n fill: \"currentColor\"\n}, null, -1);\nvar _hoisted_2 = [_hoisted_1];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"svg\", mergeProps({\n width: \"14\",\n height: \"14\",\n viewBox: \"0 0 14 14\",\n fill: \"none\",\n xmlns: \"http://www.w3.org/2000/svg\"\n }, _ctx.pti()), _hoisted_2, 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseIcon from '@primevue/icons/baseicon';\nimport { openBlock, createElementBlock, mergeProps, createElementVNode } from 'vue';\n\nvar script = {\n name: 'ArrowUpIcon',\n \"extends\": BaseIcon\n};\n\nvar _hoisted_1 = /*#__PURE__*/createElementVNode(\"path\", {\n \"fill-rule\": \"evenodd\",\n \"clip-rule\": \"evenodd\",\n d: \"M6.51551 13.799C6.64205 13.9255 6.813 13.9977 6.99193 14C7.17087 13.9977 7.34182 13.9255 7.46835 13.799C7.59489 13.6725 7.66701 13.5015 7.66935 13.3226V2.31233L11.9326 6.57554C11.9951 6.63887 12.0697 6.68907 12.1519 6.72319C12.2341 6.75731 12.3223 6.77467 12.4113 6.77425C12.5003 6.77467 12.5885 6.75731 12.6707 6.72319C12.7529 6.68907 12.8274 6.63887 12.89 6.57554C13.0168 6.44853 13.0881 6.27635 13.0881 6.09683C13.0881 5.91732 13.0168 5.74514 12.89 5.61812L7.48846 0.216594C7.48274 0.210436 7.4769 0.204374 7.47094 0.198411C7.3439 0.0713707 7.1716 0 6.99193 0C6.81227 0 6.63997 0.0713707 6.51293 0.198411C6.50704 0.204296 6.50128 0.210278 6.49563 0.216354L1.09386 5.61812C0.974201 5.74654 0.909057 5.91639 0.912154 6.09189C0.91525 6.26738 0.986345 6.43483 1.11046 6.55894C1.23457 6.68306 1.40202 6.75415 1.57752 6.75725C1.75302 6.76035 1.92286 6.6952 2.05128 6.57554L6.31451 2.31231V13.3226C6.31685 13.5015 6.38898 13.6725 6.51551 13.799Z\",\n fill: \"currentColor\"\n}, null, -1);\nvar _hoisted_2 = [_hoisted_1];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"svg\", mergeProps({\n width: \"14\",\n height: \"14\",\n viewBox: \"0 0 14 14\",\n fill: \"none\",\n xmlns: \"http://www.w3.org/2000/svg\"\n }, _ctx.pti()), _hoisted_2, 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseStyle from '@primevue/core/base/style';\n\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nvar theme = function theme(_ref) {\n var dt = _ref.dt;\n return \"\\n.p-paginator {\\n display: flex;\\n align-items: center;\\n justify-content: center;\\n flex-wrap: wrap;\\n background: \".concat(dt('paginator.background'), \";\\n color: \").concat(dt('paginator.color'), \";\\n padding: \").concat(dt('paginator.padding'), \";\\n border-radius: \").concat(dt('paginator.border.radius'), \";\\n gap: \").concat(dt('paginator.gap'), \";\\n}\\n\\n.p-paginator-content {\\n display: flex;\\n align-items: center;\\n justify-content: center;\\n flex-wrap: wrap;\\n gap: \").concat(dt('paginator.gap'), \";\\n}\\n\\n.p-paginator-content-start {\\n margin-right: auto;\\n}\\n\\n.p-paginator-content-end {\\n margin-left: auto;\\n}\\n\\n.p-paginator-page,\\n.p-paginator-next,\\n.p-paginator-last,\\n.p-paginator-first,\\n.p-paginator-prev {\\n cursor: pointer;\\n display: inline-flex;\\n align-items: center;\\n justify-content: center;\\n line-height: 1;\\n user-select: none;\\n overflow: hidden;\\n position: relative;\\n background: \").concat(dt('paginator.nav.button.background'), \";\\n border: 0 none;\\n color: \").concat(dt('paginator.nav.button.color'), \";\\n min-width: \").concat(dt('paginator.nav.button.width'), \";\\n height: \").concat(dt('paginator.nav.button.height'), \";\\n transition: background \").concat(dt('paginator.transition.duration'), \", color \").concat(dt('paginator.transition.duration'), \", outline-color \").concat(dt('paginator.transition.duration'), \", box-shadow \").concat(dt('paginator.transition.duration'), \";\\n border-radius: \").concat(dt('paginator.nav.button.border.radius'), \";\\n padding: 0;\\n margin: 0;\\n}\\n\\n.p-paginator-page:focus-visible,\\n.p-paginator-next:focus-visible,\\n.p-paginator-last:focus-visible,\\n.p-paginator-first:focus-visible,\\n.p-paginator-prev:focus-visible {\\n box-shadow: \").concat(dt('paginator.nav.button.focus.ring.shadow'), \";\\n outline: \").concat(dt('paginator.nav.button.focus.ring.width'), \" \").concat(dt('paginator.nav.button.focus.ring.style'), \" \").concat(dt('paginator.nav.button.focus.ring.color'), \";\\n outline-offset: \").concat(dt('paginator.nav.button.focus.ring.offset'), \";\\n}\\n\\n.p-paginator-page:not(.p-disabled):not(.p-paginator-page-selected):hover,\\n.p-paginator-first:not(.p-disabled):hover,\\n.p-paginator-prev:not(.p-disabled):hover,\\n.p-paginator-next:not(.p-disabled):hover,\\n.p-paginator-last:not(.p-disabled):hover {\\n background: \").concat(dt('paginator.nav.button.hover.background'), \";\\n color: \").concat(dt('paginator.nav.button.hover.color'), \";\\n}\\n\\n.p-paginator-page.p-paginator-page-selected {\\n background: \").concat(dt('paginator.nav.button.selected.background'), \";\\n color: \").concat(dt('paginator.nav.button.selected.color'), \";\\n}\\n\\n.p-paginator-current {\\n color: \").concat(dt('paginator.current.page.report.color'), \";\\n}\\n\\n.p-paginator-pages {\\n display: flex;\\n align-items: center;\\n gap: \").concat(dt('paginator.gap'), \";\\n}\\n\\n.p-paginator-jtp-input .p-inputtext {\\n max-width: \").concat(dt('paginator.jump.to.page.input.max.width'), \";\\n}\\n\");\n};\nvar classes = {\n paginator: function paginator(_ref2) {\n var instance = _ref2.instance,\n key = _ref2.key;\n return ['p-paginator p-component', _defineProperty({\n 'p-paginator-default': !instance.hasBreakpoints()\n }, \"p-paginator-\".concat(key), instance.hasBreakpoints())];\n },\n content: 'p-paginator-content',\n contentStart: 'p-paginator-content-start',\n contentEnd: 'p-paginator-content-end',\n first: function first(_ref4) {\n var instance = _ref4.instance;\n return ['p-paginator-first', {\n 'p-disabled': instance.$attrs.disabled\n }];\n },\n firstIcon: 'p-paginator-first-icon',\n prev: function prev(_ref5) {\n var instance = _ref5.instance;\n return ['p-paginator-prev', {\n 'p-disabled': instance.$attrs.disabled\n }];\n },\n prevIcon: 'p-paginator-prev-icon',\n next: function next(_ref6) {\n var instance = _ref6.instance;\n return ['p-paginator-next', {\n 'p-disabled': instance.$attrs.disabled\n }];\n },\n nextIcon: 'p-paginator-next-icon',\n last: function last(_ref7) {\n var instance = _ref7.instance;\n return ['p-paginator-last', {\n 'p-disabled': instance.$attrs.disabled\n }];\n },\n lastIcon: 'p-paginator-last-icon',\n pages: 'p-paginator-pages',\n page: function page(_ref8) {\n var props = _ref8.props,\n pageLink = _ref8.pageLink;\n return ['p-paginator-page', {\n 'p-paginator-page-selected': pageLink - 1 === props.page\n }];\n },\n current: 'p-paginator-current',\n pcRowPerPageDropdown: 'p-paginator-rpp-dropdown',\n pcJumpToPageDropdown: 'p-paginator-jtp-dropdown',\n pcJumpToPageInput: 'p-paginator-jtp-input'\n};\nvar PaginatorStyle = BaseStyle.extend({\n name: 'paginator',\n theme: theme,\n classes: classes\n});\n\nexport { PaginatorStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseIcon from '@primevue/icons/baseicon';\nimport { openBlock, createElementBlock, mergeProps, createElementVNode } from 'vue';\n\nvar script = {\n name: 'AngleDoubleLeftIcon',\n \"extends\": BaseIcon\n};\n\nvar _hoisted_1 = /*#__PURE__*/createElementVNode(\"path\", {\n \"fill-rule\": \"evenodd\",\n \"clip-rule\": \"evenodd\",\n d: \"M5.71602 11.164C5.80782 11.2021 5.9063 11.2215 6.00569 11.221C6.20216 11.2301 6.39427 11.1612 6.54025 11.0294C6.68191 10.8875 6.76148 10.6953 6.76148 10.4948C6.76148 10.2943 6.68191 10.1021 6.54025 9.96024L3.51441 6.9344L6.54025 3.90855C6.624 3.76126 6.65587 3.59011 6.63076 3.42254C6.60564 3.25498 6.525 3.10069 6.40175 2.98442C6.2785 2.86815 6.11978 2.79662 5.95104 2.7813C5.78229 2.76598 5.61329 2.80776 5.47112 2.89994L1.97123 6.39983C1.82957 6.54167 1.75 6.73393 1.75 6.9344C1.75 7.13486 1.82957 7.32712 1.97123 7.46896L5.47112 10.9991C5.54096 11.0698 5.62422 11.1259 5.71602 11.164ZM11.0488 10.9689C11.1775 11.1156 11.3585 11.2061 11.5531 11.221C11.7477 11.2061 11.9288 11.1156 12.0574 10.9689C12.1815 10.8302 12.25 10.6506 12.25 10.4645C12.25 10.2785 12.1815 10.0989 12.0574 9.96024L9.03158 6.93439L12.0574 3.90855C12.1248 3.76739 12.1468 3.60881 12.1204 3.45463C12.0939 3.30045 12.0203 3.15826 11.9097 3.04765C11.7991 2.93703 11.6569 2.86343 11.5027 2.83698C11.3486 2.81053 11.19 2.83252 11.0488 2.89994L7.51865 6.36957C7.37699 6.51141 7.29742 6.70367 7.29742 6.90414C7.29742 7.1046 7.37699 7.29686 7.51865 7.4387L11.0488 10.9689Z\",\n fill: \"currentColor\"\n}, null, -1);\nvar _hoisted_2 = [_hoisted_1];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"svg\", mergeProps({\n width: \"14\",\n height: \"14\",\n viewBox: \"0 0 14 14\",\n fill: \"none\",\n xmlns: \"http://www.w3.org/2000/svg\"\n }, _ctx.pti()), _hoisted_2, 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseIcon from '@primevue/icons/baseicon';\nimport { openBlock, createElementBlock, mergeProps, createElementVNode } from 'vue';\n\nvar script = {\n name: 'AngleDoubleRightIcon',\n \"extends\": BaseIcon\n};\n\nvar _hoisted_1 = /*#__PURE__*/createElementVNode(\"path\", {\n \"fill-rule\": \"evenodd\",\n \"clip-rule\": \"evenodd\",\n d: \"M7.68757 11.1451C7.7791 11.1831 7.8773 11.2024 7.9764 11.2019C8.07769 11.1985 8.17721 11.1745 8.26886 11.1312C8.36052 11.088 8.44238 11.0265 8.50943 10.9505L12.0294 7.49085C12.1707 7.34942 12.25 7.15771 12.25 6.95782C12.25 6.75794 12.1707 6.56622 12.0294 6.42479L8.50943 2.90479C8.37014 2.82159 8.20774 2.78551 8.04633 2.80192C7.88491 2.81833 7.73309 2.88635 7.6134 2.99588C7.4937 3.10541 7.41252 3.25061 7.38189 3.40994C7.35126 3.56927 7.37282 3.73423 7.44337 3.88033L10.4605 6.89748L7.44337 9.91463C7.30212 10.0561 7.22278 10.2478 7.22278 10.4477C7.22278 10.6475 7.30212 10.8393 7.44337 10.9807C7.51301 11.0512 7.59603 11.1071 7.68757 11.1451ZM1.94207 10.9505C2.07037 11.0968 2.25089 11.1871 2.44493 11.2019C2.63898 11.1871 2.81949 11.0968 2.94779 10.9505L6.46779 7.49085C6.60905 7.34942 6.68839 7.15771 6.68839 6.95782C6.68839 6.75793 6.60905 6.56622 6.46779 6.42479L2.94779 2.90479C2.80704 2.83757 2.6489 2.81563 2.49517 2.84201C2.34143 2.86839 2.19965 2.94178 2.08936 3.05207C1.97906 3.16237 1.90567 3.30415 1.8793 3.45788C1.85292 3.61162 1.87485 3.76975 1.94207 3.9105L4.95922 6.92765L1.94207 9.9448C1.81838 10.0831 1.75 10.2621 1.75 10.4477C1.75 10.6332 1.81838 10.8122 1.94207 10.9505Z\",\n fill: \"currentColor\"\n}, null, -1);\nvar _hoisted_2 = [_hoisted_1];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"svg\", mergeProps({\n width: \"14\",\n height: \"14\",\n viewBox: \"0 0 14 14\",\n fill: \"none\",\n xmlns: \"http://www.w3.org/2000/svg\"\n }, _ctx.pti()), _hoisted_2, 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseIcon from '@primevue/icons/baseicon';\nimport { openBlock, createElementBlock, mergeProps, createElementVNode } from 'vue';\n\nvar script = {\n name: 'AngleRightIcon',\n \"extends\": BaseIcon\n};\n\nvar _hoisted_1 = /*#__PURE__*/createElementVNode(\"path\", {\n d: \"M5.25 11.1728C5.14929 11.1694 5.05033 11.1455 4.9592 11.1025C4.86806 11.0595 4.78666 10.9984 4.72 10.9228C4.57955 10.7822 4.50066 10.5916 4.50066 10.3928C4.50066 10.1941 4.57955 10.0035 4.72 9.86283L7.72 6.86283L4.72 3.86283C4.66067 3.71882 4.64765 3.55991 4.68275 3.40816C4.71785 3.25642 4.79932 3.11936 4.91585 3.01602C5.03238 2.91268 5.17819 2.84819 5.33305 2.83149C5.4879 2.81479 5.64411 2.84671 5.78 2.92283L9.28 6.42283C9.42045 6.56346 9.49934 6.75408 9.49934 6.95283C9.49934 7.15158 9.42045 7.34221 9.28 7.48283L5.78 10.9228C5.71333 10.9984 5.63193 11.0595 5.5408 11.1025C5.44966 11.1455 5.35071 11.1694 5.25 11.1728Z\",\n fill: \"currentColor\"\n}, null, -1);\nvar _hoisted_2 = [_hoisted_1];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"svg\", mergeProps({\n width: \"14\",\n height: \"14\",\n viewBox: \"0 0 14 14\",\n fill: \"none\",\n xmlns: \"http://www.w3.org/2000/svg\"\n }, _ctx.pti()), _hoisted_2, 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseIcon from '@primevue/icons/baseicon';\nimport { openBlock, createElementBlock, mergeProps, createElementVNode } from 'vue';\n\nvar script = {\n name: 'AngleLeftIcon',\n \"extends\": BaseIcon\n};\n\nvar _hoisted_1 = /*#__PURE__*/createElementVNode(\"path\", {\n d: \"M8.75 11.185C8.65146 11.1854 8.55381 11.1662 8.4628 11.1284C8.37179 11.0906 8.28924 11.0351 8.22 10.965L4.72 7.46496C4.57955 7.32433 4.50066 7.13371 4.50066 6.93496C4.50066 6.73621 4.57955 6.54558 4.72 6.40496L8.22 2.93496C8.36095 2.84357 8.52851 2.80215 8.69582 2.81733C8.86312 2.83252 9.02048 2.90344 9.14268 3.01872C9.26487 3.134 9.34483 3.28696 9.36973 3.4531C9.39463 3.61924 9.36303 3.78892 9.28 3.93496L6.28 6.93496L9.28 9.93496C9.42045 10.0756 9.49934 10.2662 9.49934 10.465C9.49934 10.6637 9.42045 10.8543 9.28 10.995C9.13526 11.1257 8.9448 11.1939 8.75 11.185Z\",\n fill: \"currentColor\"\n}, null, -1);\nvar _hoisted_2 = [_hoisted_1];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"svg\", mergeProps({\n width: \"14\",\n height: \"14\",\n viewBox: \"0 0 14 14\",\n fill: \"none\",\n xmlns: \"http://www.w3.org/2000/svg\"\n }, _ctx.pti()), _hoisted_2, 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import { UniqueComponentId } from '@primevue/core/utils';\nimport { setAttribute } from '@primeuix/utils/dom';\nimport BaseComponent from '@primevue/core/basecomponent';\nimport PaginatorStyle from 'primevue/paginator/style';\nimport { openBlock, createElementBlock, mergeProps, toDisplayString, resolveDirective, withDirectives, createBlock, resolveDynamicComponent, resolveComponent, normalizeClass, createSlots, withCtx, Fragment, renderList, createTextVNode, normalizeProps, renderSlot, createCommentVNode, createElementVNode } from 'vue';\nimport AngleDoubleLeftIcon from '@primevue/icons/angledoubleleft';\nimport Ripple from 'primevue/ripple';\nimport Select from 'primevue/select';\nimport InputNumber from 'primevue/inputnumber';\nimport AngleDoubleRightIcon from '@primevue/icons/angledoubleright';\nimport AngleRightIcon from '@primevue/icons/angleright';\nimport AngleLeftIcon from '@primevue/icons/angleleft';\n\nvar script$a = {\n name: 'BasePaginator',\n \"extends\": BaseComponent,\n props: {\n totalRecords: {\n type: Number,\n \"default\": 0\n },\n rows: {\n type: Number,\n \"default\": 0\n },\n first: {\n type: Number,\n \"default\": 0\n },\n pageLinkSize: {\n type: Number,\n \"default\": 5\n },\n rowsPerPageOptions: {\n type: Array,\n \"default\": null\n },\n template: {\n type: [Object, String],\n \"default\": 'FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink RowsPerPageDropdown'\n },\n currentPageReportTemplate: {\n type: null,\n \"default\": '({currentPage} of {totalPages})'\n },\n alwaysShow: {\n type: Boolean,\n \"default\": true\n }\n },\n style: PaginatorStyle,\n provide: function provide() {\n return {\n $pcPaginator: this,\n $parentInstance: this\n };\n }\n};\n\nvar script$9 = {\n name: 'CurrentPageReport',\n hostName: 'Paginator',\n \"extends\": BaseComponent,\n props: {\n pageCount: {\n type: Number,\n \"default\": 0\n },\n currentPage: {\n type: Number,\n \"default\": 0\n },\n page: {\n type: Number,\n \"default\": 0\n },\n first: {\n type: Number,\n \"default\": 0\n },\n rows: {\n type: Number,\n \"default\": 0\n },\n totalRecords: {\n type: Number,\n \"default\": 0\n },\n template: {\n type: String,\n \"default\": '({currentPage} of {totalPages})'\n }\n },\n computed: {\n text: function text() {\n var text = this.template.replace('{currentPage}', this.currentPage).replace('{totalPages}', this.pageCount).replace('{first}', this.pageCount > 0 ? this.first + 1 : 0).replace('{last}', Math.min(this.first + this.rows, this.totalRecords)).replace('{rows}', this.rows).replace('{totalRecords}', this.totalRecords);\n return text;\n }\n }\n};\n\nfunction render$9(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"span\", mergeProps({\n \"class\": _ctx.cx('current')\n }, _ctx.ptm('current')), toDisplayString($options.text), 17);\n}\n\nscript$9.render = render$9;\n\nvar script$8 = {\n name: 'FirstPageLink',\n hostName: 'Paginator',\n \"extends\": BaseComponent,\n props: {\n template: {\n type: Function,\n \"default\": null\n }\n },\n methods: {\n getPTOptions: function getPTOptions(key) {\n return this.ptm(key, {\n context: {\n disabled: this.$attrs.disabled\n }\n });\n }\n },\n components: {\n AngleDoubleLeftIcon: AngleDoubleLeftIcon\n },\n directives: {\n ripple: Ripple\n }\n};\n\nfunction render$8(_ctx, _cache, $props, $setup, $data, $options) {\n var _directive_ripple = resolveDirective(\"ripple\");\n return withDirectives((openBlock(), createElementBlock(\"button\", mergeProps({\n \"class\": _ctx.cx('first'),\n type: \"button\"\n }, $options.getPTOptions('first'), {\n \"data-pc-group-section\": \"pagebutton\"\n }), [(openBlock(), createBlock(resolveDynamicComponent($props.template || 'AngleDoubleLeftIcon'), mergeProps({\n \"class\": _ctx.cx('firstIcon')\n }, $options.getPTOptions('firstIcon')), null, 16, [\"class\"]))], 16)), [[_directive_ripple]]);\n}\n\nscript$8.render = render$8;\n\nvar script$7 = {\n name: 'JumpToPageDropdown',\n hostName: 'Paginator',\n \"extends\": BaseComponent,\n emits: ['page-change'],\n props: {\n page: Number,\n pageCount: Number,\n disabled: Boolean,\n templates: null\n },\n methods: {\n onChange: function onChange(value) {\n this.$emit('page-change', value);\n }\n },\n computed: {\n pageOptions: function pageOptions() {\n var opts = [];\n for (var i = 0; i < this.pageCount; i++) {\n opts.push({\n label: String(i + 1),\n value: i\n });\n }\n return opts;\n }\n },\n components: {\n JTPSelect: Select\n }\n};\n\nfunction render$7(_ctx, _cache, $props, $setup, $data, $options) {\n var _component_JTPSelect = resolveComponent(\"JTPSelect\");\n return openBlock(), createBlock(_component_JTPSelect, {\n modelValue: $props.page,\n options: $options.pageOptions,\n optionLabel: \"label\",\n optionValue: \"value\",\n \"onUpdate:modelValue\": _cache[0] || (_cache[0] = function ($event) {\n return $options.onChange($event);\n }),\n \"class\": normalizeClass(_ctx.cx('pcJumpToPageDropdown')),\n disabled: $props.disabled,\n unstyled: _ctx.unstyled,\n pt: _ctx.ptm('pcJumpToPageDropdown'),\n \"data-pc-group-section\": \"pagedropdown\"\n }, createSlots({\n _: 2\n }, [$props.templates['jumptopagedropdownicon'] ? {\n name: \"dropdownicon\",\n fn: withCtx(function (slotProps) {\n return [(openBlock(), createBlock(resolveDynamicComponent($props.templates['jumptopagedropdownicon']), {\n \"class\": normalizeClass(slotProps[\"class\"])\n }, null, 8, [\"class\"]))];\n }),\n key: \"0\"\n } : undefined]), 1032, [\"modelValue\", \"options\", \"class\", \"disabled\", \"unstyled\", \"pt\"]);\n}\n\nscript$7.render = render$7;\n\nvar script$6 = {\n name: 'JumpToPageInput',\n hostName: 'Paginator',\n \"extends\": BaseComponent,\n inheritAttrs: false,\n emits: ['page-change'],\n props: {\n page: Number,\n pageCount: Number,\n disabled: Boolean\n },\n data: function data() {\n return {\n d_page: this.page\n };\n },\n watch: {\n page: function page(newValue) {\n this.d_page = newValue;\n }\n },\n methods: {\n onChange: function onChange(value) {\n if (value !== this.page) {\n this.d_page = value;\n this.$emit('page-change', value - 1);\n }\n }\n },\n computed: {\n inputArialabel: function inputArialabel() {\n return this.$primevue.config.locale.aria ? this.$primevue.config.locale.aria.jumpToPageInputLabel : undefined;\n }\n },\n components: {\n JTPInput: InputNumber\n }\n};\n\nfunction render$6(_ctx, _cache, $props, $setup, $data, $options) {\n var _component_JTPInput = resolveComponent(\"JTPInput\");\n return openBlock(), createBlock(_component_JTPInput, {\n ref: \"jtpInput\",\n modelValue: $data.d_page,\n \"class\": normalizeClass(_ctx.cx('pcJumpToPageInput')),\n \"aria-label\": $options.inputArialabel,\n disabled: $props.disabled,\n \"onUpdate:modelValue\": $options.onChange,\n unstyled: _ctx.unstyled,\n pt: _ctx.ptm('pcJumpToPageInput')\n }, null, 8, [\"modelValue\", \"class\", \"aria-label\", \"disabled\", \"onUpdate:modelValue\", \"unstyled\", \"pt\"]);\n}\n\nscript$6.render = render$6;\n\nvar script$5 = {\n name: 'LastPageLink',\n hostName: 'Paginator',\n \"extends\": BaseComponent,\n props: {\n template: {\n type: Function,\n \"default\": null\n }\n },\n methods: {\n getPTOptions: function getPTOptions(key) {\n return this.ptm(key, {\n context: {\n disabled: this.$attrs.disabled\n }\n });\n }\n },\n components: {\n AngleDoubleRightIcon: AngleDoubleRightIcon\n },\n directives: {\n ripple: Ripple\n }\n};\n\nfunction render$5(_ctx, _cache, $props, $setup, $data, $options) {\n var _directive_ripple = resolveDirective(\"ripple\");\n return withDirectives((openBlock(), createElementBlock(\"button\", mergeProps({\n \"class\": _ctx.cx('last'),\n type: \"button\"\n }, $options.getPTOptions('last'), {\n \"data-pc-group-section\": \"pagebutton\"\n }), [(openBlock(), createBlock(resolveDynamicComponent($props.template || 'AngleDoubleRightIcon'), mergeProps({\n \"class\": _ctx.cx('lastIcon')\n }, $options.getPTOptions('lastIcon')), null, 16, [\"class\"]))], 16)), [[_directive_ripple]]);\n}\n\nscript$5.render = render$5;\n\nvar script$4 = {\n name: 'NextPageLink',\n hostName: 'Paginator',\n \"extends\": BaseComponent,\n props: {\n template: {\n type: Function,\n \"default\": null\n }\n },\n methods: {\n getPTOptions: function getPTOptions(key) {\n return this.ptm(key, {\n context: {\n disabled: this.$attrs.disabled\n }\n });\n }\n },\n components: {\n AngleRightIcon: AngleRightIcon\n },\n directives: {\n ripple: Ripple\n }\n};\n\nfunction render$4(_ctx, _cache, $props, $setup, $data, $options) {\n var _directive_ripple = resolveDirective(\"ripple\");\n return withDirectives((openBlock(), createElementBlock(\"button\", mergeProps({\n \"class\": _ctx.cx('next'),\n type: \"button\"\n }, $options.getPTOptions('next'), {\n \"data-pc-group-section\": \"pagebutton\"\n }), [(openBlock(), createBlock(resolveDynamicComponent($props.template || 'AngleRightIcon'), mergeProps({\n \"class\": _ctx.cx('nextIcon')\n }, $options.getPTOptions('nextIcon')), null, 16, [\"class\"]))], 16)), [[_directive_ripple]]);\n}\n\nscript$4.render = render$4;\n\nvar script$3 = {\n name: 'PageLinks',\n hostName: 'Paginator',\n \"extends\": BaseComponent,\n inheritAttrs: false,\n emits: ['click'],\n props: {\n value: Array,\n page: Number\n },\n methods: {\n getPTOptions: function getPTOptions(pageLink, key) {\n return this.ptm(key, {\n context: {\n active: pageLink === this.page\n }\n });\n },\n onPageLinkClick: function onPageLinkClick(event, pageLink) {\n this.$emit('click', {\n originalEvent: event,\n value: pageLink\n });\n },\n ariaPageLabel: function ariaPageLabel(value) {\n return this.$primevue.config.locale.aria ? this.$primevue.config.locale.aria.pageLabel.replace(/{page}/g, value) : undefined;\n }\n },\n directives: {\n ripple: Ripple\n }\n};\n\nvar _hoisted_1 = [\"aria-label\", \"aria-current\", \"onClick\", \"data-p-active\"];\nfunction render$3(_ctx, _cache, $props, $setup, $data, $options) {\n var _directive_ripple = resolveDirective(\"ripple\");\n return openBlock(), createElementBlock(\"span\", mergeProps({\n \"class\": _ctx.cx('pages')\n }, _ctx.ptm('pages')), [(openBlock(true), createElementBlock(Fragment, null, renderList($props.value, function (pageLink) {\n return withDirectives((openBlock(), createElementBlock(\"button\", mergeProps({\n key: pageLink,\n \"class\": _ctx.cx('page', {\n pageLink: pageLink\n }),\n type: \"button\",\n \"aria-label\": $options.ariaPageLabel(pageLink),\n \"aria-current\": pageLink - 1 === $props.page ? 'page' : undefined,\n onClick: function onClick($event) {\n return $options.onPageLinkClick($event, pageLink);\n },\n ref_for: true\n }, $options.getPTOptions(pageLink - 1, 'page'), {\n \"data-p-active\": pageLink - 1 === $props.page\n }), [createTextVNode(toDisplayString(pageLink), 1)], 16, _hoisted_1)), [[_directive_ripple]]);\n }), 128))], 16);\n}\n\nscript$3.render = render$3;\n\nvar script$2 = {\n name: 'PrevPageLink',\n hostName: 'Paginator',\n \"extends\": BaseComponent,\n props: {\n template: {\n type: Function,\n \"default\": null\n }\n },\n methods: {\n getPTOptions: function getPTOptions(key) {\n return this.ptm(key, {\n context: {\n disabled: this.$attrs.disabled\n }\n });\n }\n },\n components: {\n AngleLeftIcon: AngleLeftIcon\n },\n directives: {\n ripple: Ripple\n }\n};\n\nfunction render$2(_ctx, _cache, $props, $setup, $data, $options) {\n var _directive_ripple = resolveDirective(\"ripple\");\n return withDirectives((openBlock(), createElementBlock(\"button\", mergeProps({\n \"class\": _ctx.cx('prev'),\n type: \"button\"\n }, $options.getPTOptions('prev'), {\n \"data-pc-group-section\": \"pagebutton\"\n }), [(openBlock(), createBlock(resolveDynamicComponent($props.template || 'AngleLeftIcon'), mergeProps({\n \"class\": _ctx.cx('prevIcon')\n }, $options.getPTOptions('prevIcon')), null, 16, [\"class\"]))], 16)), [[_directive_ripple]]);\n}\n\nscript$2.render = render$2;\n\nvar script$1 = {\n name: 'RowsPerPageDropdown',\n hostName: 'Paginator',\n \"extends\": BaseComponent,\n emits: ['rows-change'],\n props: {\n options: Array,\n rows: Number,\n disabled: Boolean,\n templates: null\n },\n methods: {\n onChange: function onChange(value) {\n this.$emit('rows-change', value);\n }\n },\n computed: {\n rowsOptions: function rowsOptions() {\n var opts = [];\n if (this.options) {\n for (var i = 0; i < this.options.length; i++) {\n opts.push({\n label: String(this.options[i]),\n value: this.options[i]\n });\n }\n }\n return opts;\n }\n },\n components: {\n RPPSelect: Select\n }\n};\n\nfunction render$1(_ctx, _cache, $props, $setup, $data, $options) {\n var _component_RPPSelect = resolveComponent(\"RPPSelect\");\n return openBlock(), createBlock(_component_RPPSelect, {\n modelValue: $props.rows,\n options: $options.rowsOptions,\n optionLabel: \"label\",\n optionValue: \"value\",\n \"onUpdate:modelValue\": _cache[0] || (_cache[0] = function ($event) {\n return $options.onChange($event);\n }),\n \"class\": normalizeClass(_ctx.cx('pcRowPerPageDropdown')),\n disabled: $props.disabled,\n unstyled: _ctx.unstyled,\n pt: _ctx.ptm('pcRowPerPageDropdown'),\n \"data-pc-group-section\": \"pagedropdown\"\n }, createSlots({\n _: 2\n }, [$props.templates['rowsperpagedropdownicon'] ? {\n name: \"dropdownicon\",\n fn: withCtx(function (slotProps) {\n return [(openBlock(), createBlock(resolveDynamicComponent($props.templates['rowsperpagedropdownicon']), {\n \"class\": normalizeClass(slotProps[\"class\"])\n }, null, 8, [\"class\"]))];\n }),\n key: \"0\"\n } : undefined]), 1032, [\"modelValue\", \"options\", \"class\", \"disabled\", \"unstyled\", \"pt\"]);\n}\n\nscript$1.render = render$1;\n\nfunction _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _iterableToArray(r) { if (\"undefined\" != typeof Symbol && null != r[Symbol.iterator] || null != r[\"@@iterator\"]) return Array.from(r); }\nfunction _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }\nfunction _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _unsupportedIterableToArray(r, a) { if (r) { if (\"string\" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return \"Object\" === t && r.constructor && (t = r.constructor.name), \"Map\" === t || \"Set\" === t ? Array.from(r) : \"Arguments\" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }\nfunction _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }\nfunction _iterableToArrayLimit(r, l) { var t = null == r ? null : \"undefined\" != typeof Symbol && r[Symbol.iterator] || r[\"@@iterator\"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t[\"return\"] && (u = t[\"return\"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }\nfunction _arrayWithHoles(r) { if (Array.isArray(r)) return r; }\nvar script = {\n name: 'Paginator',\n \"extends\": script$a,\n inheritAttrs: false,\n emits: ['update:first', 'update:rows', 'page'],\n data: function data() {\n return {\n d_first: this.first,\n d_rows: this.rows\n };\n },\n watch: {\n first: function first(newValue) {\n this.d_first = newValue;\n },\n rows: function rows(newValue) {\n this.d_rows = newValue;\n },\n totalRecords: function totalRecords(newValue) {\n if (this.page > 0 && newValue && this.d_first >= newValue) {\n this.changePage(this.pageCount - 1);\n }\n }\n },\n mounted: function mounted() {\n this.setPaginatorAttribute();\n this.createStyle();\n },\n methods: {\n changePage: function changePage(p) {\n var pc = this.pageCount;\n if (p >= 0 && p < pc) {\n this.d_first = this.d_rows * p;\n var state = {\n page: p,\n first: this.d_first,\n rows: this.d_rows,\n pageCount: pc\n };\n this.$emit('update:first', this.d_first);\n this.$emit('update:rows', this.d_rows);\n this.$emit('page', state);\n }\n },\n changePageToFirst: function changePageToFirst(event) {\n if (!this.isFirstPage) {\n this.changePage(0);\n }\n event.preventDefault();\n },\n changePageToPrev: function changePageToPrev(event) {\n this.changePage(this.page - 1);\n event.preventDefault();\n },\n changePageLink: function changePageLink(event) {\n this.changePage(event.value - 1);\n event.originalEvent.preventDefault();\n },\n changePageToNext: function changePageToNext(event) {\n this.changePage(this.page + 1);\n event.preventDefault();\n },\n changePageToLast: function changePageToLast(event) {\n if (!this.isLastPage) {\n this.changePage(this.pageCount - 1);\n }\n event.preventDefault();\n },\n onRowChange: function onRowChange(value) {\n this.d_rows = value;\n this.changePage(this.page);\n },\n createStyle: function createStyle() {\n var _this = this;\n if (this.hasBreakpoints() && !this.isUnstyled) {\n var _this$$primevue;\n this.styleElement = document.createElement('style');\n this.styleElement.type = 'text/css';\n setAttribute(this.styleElement, 'nonce', (_this$$primevue = this.$primevue) === null || _this$$primevue === void 0 || (_this$$primevue = _this$$primevue.config) === null || _this$$primevue === void 0 || (_this$$primevue = _this$$primevue.csp) === null || _this$$primevue === void 0 ? void 0 : _this$$primevue.nonce);\n document.head.appendChild(this.styleElement);\n var innerHTML = '';\n var keys = Object.keys(this.template);\n var sortedBreakpoints = {};\n keys.sort(function (a, b) {\n return parseInt(a) - parseInt(b);\n }).forEach(function (key) {\n sortedBreakpoints[key] = _this.template[key];\n });\n for (var _i = 0, _Object$entries = Object.entries(Object.entries(sortedBreakpoints)); _i < _Object$entries.length; _i++) {\n var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2),\n index = _Object$entries$_i[0],\n _Object$entries$_i$ = _slicedToArray(_Object$entries$_i[1], 1),\n key = _Object$entries$_i$[0];\n var minValue = void 0,\n calculatedMinValue = void 0;\n if (key !== 'default' && typeof Object.keys(sortedBreakpoints)[index - 1] === 'string') {\n calculatedMinValue = Number(Object.keys(sortedBreakpoints)[index - 1].slice(0, -2)) + 1 + 'px';\n } else {\n calculatedMinValue = Object.keys(sortedBreakpoints)[index - 1];\n }\n minValue = Object.entries(sortedBreakpoints)[index - 1] ? \"and (min-width:\".concat(calculatedMinValue, \")\") : '';\n if (key === 'default') {\n innerHTML += \"\\n @media screen \".concat(minValue, \" {\\n .paginator[\").concat(this.attributeSelector, \"],\\n display: flex;\\n }\\n }\\n \");\n } else {\n innerHTML += \"\\n.paginator[\".concat(this.attributeSelector, \"], .p-paginator-\").concat(key, \" {\\n display: none;\\n}\\n@media screen \").concat(minValue, \" and (max-width: \").concat(key, \") {\\n .paginator[\").concat(this.attributeSelector, \"], .p-paginator-\").concat(key, \" {\\n display: flex;\\n }\\n .paginator[\").concat(this.attributeSelector, \"],\\n .p-paginator-default{\\n display: none;\\n }\\n}\\n \");\n }\n }\n this.styleElement.innerHTML = innerHTML;\n }\n },\n hasBreakpoints: function hasBreakpoints() {\n return _typeof(this.template) === 'object';\n },\n setPaginatorAttribute: function setPaginatorAttribute() {\n var _this2 = this;\n if (this.$refs.paginator && this.$refs.paginator.length >= 0) {\n _toConsumableArray(this.$refs.paginator).forEach(function (el) {\n el.setAttribute(_this2.attributeSelector, '');\n });\n }\n },\n getAriaLabel: function getAriaLabel(labelType) {\n return this.$primevue.config.locale.aria ? this.$primevue.config.locale.aria[labelType] : undefined;\n }\n },\n computed: {\n templateItems: function templateItems() {\n var keys = {};\n if (this.hasBreakpoints()) {\n keys = this.template;\n if (!keys[\"default\"]) {\n keys[\"default\"] = 'FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink RowsPerPageDropdown';\n }\n for (var item in keys) {\n keys[item] = this.template[item].split(' ').map(function (value) {\n return value.trim();\n });\n }\n return keys;\n }\n keys['default'] = this.template.split(' ').map(function (value) {\n return value.trim();\n });\n return keys;\n },\n page: function page() {\n return Math.floor(this.d_first / this.d_rows);\n },\n pageCount: function pageCount() {\n return Math.ceil(this.totalRecords / this.d_rows);\n },\n isFirstPage: function isFirstPage() {\n return this.page === 0;\n },\n isLastPage: function isLastPage() {\n return this.page === this.pageCount - 1;\n },\n calculatePageLinkBoundaries: function calculatePageLinkBoundaries() {\n var numberOfPages = this.pageCount;\n var visiblePages = Math.min(this.pageLinkSize, numberOfPages);\n\n //calculate range, keep current in middle if necessary\n var start = Math.max(0, Math.ceil(this.page - visiblePages / 2));\n var end = Math.min(numberOfPages - 1, start + visiblePages - 1);\n\n //check when approaching to last page\n var delta = this.pageLinkSize - (end - start + 1);\n start = Math.max(0, start - delta);\n return [start, end];\n },\n pageLinks: function pageLinks() {\n var pageLinks = [];\n var boundaries = this.calculatePageLinkBoundaries;\n var start = boundaries[0];\n var end = boundaries[1];\n for (var i = start; i <= end; i++) {\n pageLinks.push(i + 1);\n }\n return pageLinks;\n },\n currentState: function currentState() {\n return {\n page: this.page,\n first: this.d_first,\n rows: this.d_rows\n };\n },\n empty: function empty() {\n return this.pageCount === 0;\n },\n currentPage: function currentPage() {\n return this.pageCount > 0 ? this.page + 1 : 0;\n },\n attributeSelector: function attributeSelector() {\n return UniqueComponentId();\n }\n },\n components: {\n CurrentPageReport: script$9,\n FirstPageLink: script$8,\n LastPageLink: script$5,\n NextPageLink: script$4,\n PageLinks: script$3,\n PrevPageLink: script$2,\n RowsPerPageDropdown: script$1,\n JumpToPageDropdown: script$7,\n JumpToPageInput: script$6\n }\n};\n\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n var _component_FirstPageLink = resolveComponent(\"FirstPageLink\");\n var _component_PrevPageLink = resolveComponent(\"PrevPageLink\");\n var _component_NextPageLink = resolveComponent(\"NextPageLink\");\n var _component_LastPageLink = resolveComponent(\"LastPageLink\");\n var _component_PageLinks = resolveComponent(\"PageLinks\");\n var _component_CurrentPageReport = resolveComponent(\"CurrentPageReport\");\n var _component_RowsPerPageDropdown = resolveComponent(\"RowsPerPageDropdown\");\n var _component_JumpToPageDropdown = resolveComponent(\"JumpToPageDropdown\");\n var _component_JumpToPageInput = resolveComponent(\"JumpToPageInput\");\n return (_ctx.alwaysShow ? true : $options.pageLinks && $options.pageLinks.length > 1) ? (openBlock(), createElementBlock(\"nav\", normalizeProps(mergeProps({\n key: 0\n }, _ctx.ptmi('paginatorContainer'))), [(openBlock(true), createElementBlock(Fragment, null, renderList($options.templateItems, function (value, key) {\n return openBlock(), createElementBlock(\"div\", mergeProps({\n key: key,\n ref_for: true,\n ref: \"paginator\",\n \"class\": _ctx.cx('paginator', {\n key: key\n })\n }, _ctx.ptm('root')), [_ctx.$slots.start ? (openBlock(), createElementBlock(\"div\", mergeProps({\n key: 0,\n \"class\": _ctx.cx('contentStart'),\n ref_for: true\n }, _ctx.ptm('contentStart')), [renderSlot(_ctx.$slots, \"start\", {\n state: $options.currentState\n })], 16)) : createCommentVNode(\"\", true), createElementVNode(\"div\", mergeProps({\n \"class\": _ctx.cx('content'),\n ref_for: true\n }, _ctx.ptm('content')), [(openBlock(true), createElementBlock(Fragment, null, renderList(value, function (item) {\n return openBlock(), createElementBlock(Fragment, {\n key: item\n }, [item === 'FirstPageLink' ? (openBlock(), createBlock(_component_FirstPageLink, {\n key: 0,\n \"aria-label\": $options.getAriaLabel('firstPageLabel'),\n template: _ctx.$slots.firsticon || _ctx.$slots.firstpagelinkicon,\n onClick: _cache[0] || (_cache[0] = function ($event) {\n return $options.changePageToFirst($event);\n }),\n disabled: $options.isFirstPage || $options.empty,\n unstyled: _ctx.unstyled,\n pt: _ctx.pt\n }, null, 8, [\"aria-label\", \"template\", \"disabled\", \"unstyled\", \"pt\"])) : item === 'PrevPageLink' ? (openBlock(), createBlock(_component_PrevPageLink, {\n key: 1,\n \"aria-label\": $options.getAriaLabel('prevPageLabel'),\n template: _ctx.$slots.previcon || _ctx.$slots.prevpagelinkicon,\n onClick: _cache[1] || (_cache[1] = function ($event) {\n return $options.changePageToPrev($event);\n }),\n disabled: $options.isFirstPage || $options.empty,\n unstyled: _ctx.unstyled,\n pt: _ctx.pt\n }, null, 8, [\"aria-label\", \"template\", \"disabled\", \"unstyled\", \"pt\"])) : item === 'NextPageLink' ? (openBlock(), createBlock(_component_NextPageLink, {\n key: 2,\n \"aria-label\": $options.getAriaLabel('nextPageLabel'),\n template: _ctx.$slots.nexticon || _ctx.$slots.nextpagelinkicon,\n onClick: _cache[2] || (_cache[2] = function ($event) {\n return $options.changePageToNext($event);\n }),\n disabled: $options.isLastPage || $options.empty,\n unstyled: _ctx.unstyled,\n pt: _ctx.pt\n }, null, 8, [\"aria-label\", \"template\", \"disabled\", \"unstyled\", \"pt\"])) : item === 'LastPageLink' ? (openBlock(), createBlock(_component_LastPageLink, {\n key: 3,\n \"aria-label\": $options.getAriaLabel('lastPageLabel'),\n template: _ctx.$slots.lasticon || _ctx.$slots.lastpagelinkicon,\n onClick: _cache[3] || (_cache[3] = function ($event) {\n return $options.changePageToLast($event);\n }),\n disabled: $options.isLastPage || $options.empty,\n unstyled: _ctx.unstyled,\n pt: _ctx.pt\n }, null, 8, [\"aria-label\", \"template\", \"disabled\", \"unstyled\", \"pt\"])) : item === 'PageLinks' ? (openBlock(), createBlock(_component_PageLinks, {\n key: 4,\n \"aria-label\": $options.getAriaLabel('pageLabel'),\n value: $options.pageLinks,\n page: $options.page,\n onClick: _cache[4] || (_cache[4] = function ($event) {\n return $options.changePageLink($event);\n }),\n pt: _ctx.pt\n }, null, 8, [\"aria-label\", \"value\", \"page\", \"pt\"])) : item === 'CurrentPageReport' ? (openBlock(), createBlock(_component_CurrentPageReport, {\n key: 5,\n \"aria-live\": \"polite\",\n template: _ctx.currentPageReportTemplate,\n currentPage: $options.currentPage,\n page: $options.page,\n pageCount: $options.pageCount,\n first: $data.d_first,\n rows: $data.d_rows,\n totalRecords: _ctx.totalRecords,\n unstyled: _ctx.unstyled,\n pt: _ctx.pt\n }, null, 8, [\"template\", \"currentPage\", \"page\", \"pageCount\", \"first\", \"rows\", \"totalRecords\", \"unstyled\", \"pt\"])) : item === 'RowsPerPageDropdown' && _ctx.rowsPerPageOptions ? (openBlock(), createBlock(_component_RowsPerPageDropdown, {\n key: 6,\n \"aria-label\": $options.getAriaLabel('rowsPerPageLabel'),\n rows: $data.d_rows,\n options: _ctx.rowsPerPageOptions,\n onRowsChange: _cache[5] || (_cache[5] = function ($event) {\n return $options.onRowChange($event);\n }),\n disabled: $options.empty,\n templates: _ctx.$slots,\n unstyled: _ctx.unstyled,\n pt: _ctx.pt\n }, null, 8, [\"aria-label\", \"rows\", \"options\", \"disabled\", \"templates\", \"unstyled\", \"pt\"])) : item === 'JumpToPageDropdown' ? (openBlock(), createBlock(_component_JumpToPageDropdown, {\n key: 7,\n \"aria-label\": $options.getAriaLabel('jumpToPageDropdownLabel'),\n page: $options.page,\n pageCount: $options.pageCount,\n onPageChange: _cache[6] || (_cache[6] = function ($event) {\n return $options.changePage($event);\n }),\n disabled: $options.empty,\n templates: _ctx.$slots,\n unstyled: _ctx.unstyled,\n pt: _ctx.pt\n }, null, 8, [\"aria-label\", \"page\", \"pageCount\", \"disabled\", \"templates\", \"unstyled\", \"pt\"])) : item === 'JumpToPageInput' ? (openBlock(), createBlock(_component_JumpToPageInput, {\n key: 8,\n page: $options.currentPage,\n onPageChange: _cache[7] || (_cache[7] = function ($event) {\n return $options.changePage($event);\n }),\n disabled: $options.empty,\n unstyled: _ctx.unstyled,\n pt: _ctx.pt\n }, null, 8, [\"page\", \"disabled\", \"unstyled\", \"pt\"])) : createCommentVNode(\"\", true)], 64);\n }), 128))], 16), _ctx.$slots.end ? (openBlock(), createElementBlock(\"div\", mergeProps({\n key: 1,\n \"class\": _ctx.cx('contentEnd'),\n ref_for: true\n }, _ctx.ptm('contentEnd')), [renderSlot(_ctx.$slots, \"end\", {\n state: $options.currentState\n })], 16)) : createCommentVNode(\"\", true)], 16);\n }), 128))], 16)) : createCommentVNode(\"\", true);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseStyle from '@primevue/core/base/style';\n\nvar theme = function theme(_ref) {\n var dt = _ref.dt;\n return \"\\n.p-datatable {\\n position: relative;\\n}\\n\\n.p-datatable-table {\\n border-spacing: 0;\\n width: 100%;\\n}\\n\\n.p-datatable-scrollable > .p-datatable-table-container {\\n position: relative;\\n}\\n\\n.p-datatable-scrollable-table > .p-datatable-thead {\\n top: 0;\\n z-index: 1;\\n}\\n\\n.p-datatable-scrollable-table > .p-datatable-frozen-tbody {\\n position: sticky;\\n z-index: 1;\\n}\\n\\n.p-datatable-scrollable-table>.p-datatable-tfoot {\\n bottom: 0;\\n z-index: 1;\\n}\\n\\n.p-datatable-scrollable .p-datatable-frozen-column {\\n position: sticky;\\n background: inherit;\\n}\\n\\n.p-datatable-scrollable th.p-datatable-frozen-column {\\n z-index: 1;\\n}\\n\\n.p-datatable-scrollable > .p-datatable-table-container > .p-datatable-table > .p-datatable-thead,\\n.p-datatable-scrollable > .p-datatable-table-container > .p-virtualscroller > .p-datatable-table > .p-datatable-thead {\\n background: \".concat(dt('datatable.header.cell.background'), \";\\n}\\n\\n.p-datatable-scrollable > .p-datatable-table-container > .p-datatable-table > .p-datatable-tfoot,\\n.p-datatable-scrollable > .p-datatable-table-container > .p-virtualscroller > .p-datatable-table > .p-datatable-tfoot {\\n background: \").concat(dt('datatable.footer.cell.background'), \";\\n}\\n\\n.p-datatable-flex-scrollable {\\n display: flex;\\n flex-direction: column;\\n height: 100%;\\n}\\n\\n.p-datatable-flex-scrollable > .p-datatable-table-container {\\n display: flex;\\n flex-direction: column;\\n flex: 1;\\n height: 100%;\\n}\\n\\n.p-datatable-scrollable-table > .p-datatable-tbody > .p-datatable-row-group-header {\\n position: sticky;\\n z-index: 1;\\n}\\n\\n.p-datatable-resizable-table > .p-datatable-thead > tr > th,\\n.p-datatable-resizable-table > .p-datatable-tfoot > tr > td,\\n.p-datatable-resizable-table > .p-datatable-tbody > tr > td {\\n overflow: hidden;\\n white-space: nowrap;\\n}\\n\\n.p-datatable-resizable-table > .p-datatable-thead > tr > th.p-datatable-resizable-column:not(.p-datatable-frozen-column) {\\n background-clip: padding-box;\\n position: relative;\\n}\\n\\n.p-datatable-resizable-table-fit > .p-datatable-thead > tr > th.p-datatable-resizable-column:last-child .p-datatable-column-resizer {\\n display: none;\\n}\\n\\n.p-datatable-column-resizer {\\n display: block;\\n position: absolute;\\n top: 0;\\n right: 0;\\n margin: 0;\\n width: \").concat(dt('datatable.column.resizer.width'), \";\\n height: 100%;\\n padding: 0px;\\n cursor: col-resize;\\n border: 1px solid transparent;\\n}\\n\\n.p-datatable-column-header-content {\\n display: flex;\\n align-items: center;\\n gap: \").concat(dt('datatable.header.cell.gap'), \";\\n}\\n\\n.p-datatable-column-resize-indicator {\\n width: \").concat(dt('datatable.resize.indicator.width'), \";\\n position: absolute;\\n z-index: 10;\\n display: none;\\n background: \").concat(dt('datatable.resize.indicator.color'), \";\\n}\\n\\n.p-datatable-row-reorder-indicator-up,\\n.p-datatable-row-reorder-indicator-down {\\n position: absolute;\\n display: none;\\n}\\n\\n.p-datatable-reorderable-column,\\n.p-datatable-reorderable-row-handle {\\n cursor: move;\\n}\\n\\n.p-datatable-mask {\\n position: absolute;\\n display: flex;\\n align-items: center;\\n justify-content: center;\\n z-index: 2;\\n}\\n\\n.p-datatable-inline-filter {\\n display: flex;\\n align-items: center;\\n width: 100%;\\n gap: \").concat(dt('datatable.filter.inline.gap'), \";\\n}\\n\\n.p-datatable-inline-filter .p-datatable-filter-element-container {\\n flex: 1 1 auto;\\n width: 1%;\\n}\\n\\n.p-datatable-filter-overlay {\\n background: \").concat(dt('datatable.filter.overlay.select.background'), \";\\n color: \").concat(dt('datatable.filter.overlay.select.color'), \";\\n border: 1px solid \").concat(dt('datatable.filter.overlay.select.border.color'), \";\\n border-radius: \").concat(dt('datatable.filter.overlay.select.border.radius'), \";\\n box-shadow: \").concat(dt('datatable.filter.overlay.select.shadow'), \";\\n min-width: 12.5rem;\\n}\\n\\n.p-datatable-filter-constraint-list {\\n margin: 0;\\n list-style: none;\\n display: flex;\\n flex-direction: column;\\n padding: \").concat(dt('datatable.filter.constraint.list.padding'), \";\\n gap: \").concat(dt('datatable.filter.constraint.list.gap'), \";\\n}\\n\\n.p-datatable-filter-constraint {\\n padding: \").concat(dt('datatable.filter.constraint.padding'), \";\\n color: \").concat(dt('datatable.filter.constraint.color'), \";\\n border-radius: \").concat(dt('datatable.filter.constraint.border.radius'), \";\\n cursor: pointer;\\n transition: background \").concat(dt('datatable.transition.duration'), \", color \").concat(dt('datatable.transition.duration'), \", border-color \").concat(dt('datatable.transition.duration'), \",\\n box-shadow \").concat(dt('datatable.transition.duration'), \";\\n}\\n\\n.p-datatable-filter-constraint-selected {\\n background: \").concat(dt('datatable.filter.constraint.selected.background'), \";\\n color: \").concat(dt('datatable.filter.constraint.selected.color'), \";\\n}\\n\\n.p-datatable-filter-constraint:not(.p-datatable-filter-constraint-selected):not(.p-disabled):hover {\\n background: \").concat(dt('datatable.filter.constraint.focus.background'), \";\\n color: \").concat(dt('datatable.filter.constraint.focus.color'), \";\\n}\\n\\n.p-datatable-filter-constraint:focus-visible {\\n outline: 0 none;\\n background: \").concat(dt('datatable.filter.constraint.focus.background'), \";\\n color: \").concat(dt('datatable.filter.constraint.focus.color'), \";\\n}\\n\\n.p-datatable-filter-constraint-selected:focus-visible {\\n outline: 0 none;\\n background: \").concat(dt('datatable.filter.constraint.selected.focus.background'), \";\\n color: \").concat(dt('datatable.filter.constraint.selected.focus.color'), \";\\n}\\n\\n.p-datatable-filter-constraint-separator {\\n border-top: 1px solid \").concat(dt('datatable.filter.constraint.separator.border.color'), \";\\n}\\n\\n.p-datatable-popover-filter {\\n display: inline-flex;\\n margin-left: auto;\\n}\\n\\n.p-datatable-filter-overlay-popover {\\n background: \").concat(dt('datatable.filter.overlay.popover.background'), \";\\n color: \").concat(dt('datatable.filter.overlay.popover.color'), \";\\n border: 1px solid \").concat(dt('datatable.filter.overlay.popover.border.color'), \";\\n border-radius: \").concat(dt('datatable.filter.overlay.popover.border.radius'), \";\\n box-shadow: \").concat(dt('datatable.filter.overlay.popover.shadow'), \";\\n min-width: 12.5rem;\\n padding: \").concat(dt('datatable.filter.overlay.popover.padding'), \";\\n display: flex;\\n flex-direction: column;\\n gap: \").concat(dt('datatable.filter.overlay.popover.gap'), \";\\n}\\n\\n.p-datatable-filter-operator-dropdown {\\n width: 100%;\\n}\\n\\n.p-datatable-filter-rule-list,\\n.p-datatable-filter-rule {\\n display: flex;\\n flex-direction: column;\\n gap: \").concat(dt('datatable.filter.overlay.popover.gap'), \";\\n}\\n\\n.p-datatable-filter-rule {\\n border-bottom: 1px solid \").concat(dt('datatable.filter.rule.border.color'), \";\\n}\\n\\n.p-datatable-filter-rule:last-child {\\n border-bottom: 0 none;\\n}\\n\\n.p-datatable-filter-add-rule-button {\\n width: 100%;\\n}\\n\\n.p-datatable-filter-remove-button {\\n width: 100%;\\n}\\n\\n.p-datatable-filter-buttonbar {\\n padding: 0;\\n display: flex;\\n align-items: center;\\n justify-content: space-between;\\n}\\n\\n.p-datatable-virtualscroller-spacer {\\n display: flex;\\n}\\n\\n.p-datatable .p-virtualscroller .p-virtualscroller-loading {\\n transform: none !important;\\n min-height: 0;\\n position: sticky;\\n top: 0;\\n left: 0;\\n}\\n\\n.p-datatable-paginator-top {\\n border-color: \").concat(dt('datatable.paginator.top.border.color'), \";\\n border-style: solid;\\n border-width: \").concat(dt('datatable.paginator.top.border.width'), \";\\n}\\n\\n.p-datatable-paginator-bottom {\\n border-color: \").concat(dt('datatable.paginator.bottom.border.color'), \";\\n border-style: solid;\\n border-width: \").concat(dt('datatable.paginator.bottom.border.width'), \";\\n}\\n\\n.p-datatable-header {\\n background: \").concat(dt('datatable.header.background'), \";\\n color: \").concat(dt('datatable.header.color'), \";\\n border-color: \").concat(dt('datatable.header.border.color'), \";\\n border-style: solid;\\n border-width: \").concat(dt('datatable.header.border.width'), \";\\n padding: \").concat(dt('datatable.header.padding'), \";\\n}\\n\\n.p-datatable-footer {\\n background: \").concat(dt('datatable.footer.background'), \";\\n color: \").concat(dt('datatable.footer.color'), \";\\n border-color: \").concat(dt('datatable.footer.border.color'), \";\\n border-style: solid;\\n border-width: \").concat(dt('datatable.footer.border.width'), \";\\n padding: \").concat(dt('datatable.footer.padding'), \";\\n}\\n\\n.p-datatable-header-cell {\\n padding: \").concat(dt('datatable.header.cell.padding'), \";\\n background: \").concat(dt('datatable.header.cell.background'), \";\\n border-color: \").concat(dt('datatable.header.cell.border.color'), \";\\n border-style: solid;\\n border-width: 0 0 1px 0;\\n color: \").concat(dt('datatable.header.cell.color'), \";\\n font-weight: normal;\\n text-align: left;\\n transition: background \").concat(dt('datatable.transition.duration'), \", color \").concat(dt('datatable.transition.duration'), \", border-color \").concat(dt('datatable.transition.duration'), \",\\n outline-color \").concat(dt('datatable.transition.duration'), \", box-shadow \").concat(dt('datatable.transition.duration'), \";\\n}\\n\\n.p-datatable-column-title {\\n font-weight: \").concat(dt('datatable.column.title.font.weight'), \";\\n}\\n\\n.p-datatable-tbody > tr {\\n outline-color: transparent;\\n background: \").concat(dt('datatable.row.background'), \";\\n color: \").concat(dt('datatable.row.color'), \";\\n transition: background \").concat(dt('datatable.transition.duration'), \", color \").concat(dt('datatable.transition.duration'), \", border-color \").concat(dt('datatable.transition.duration'), \",\\n outline-color \").concat(dt('datatable.transition.duration'), \", box-shadow \").concat(dt('datatable.transition.duration'), \";\\n}\\n\\n.p-datatable-tbody > tr > td {\\n text-align: left;\\n border-color: \").concat(dt('datatable.body.cell.border.color'), \";\\n border-style: solid;\\n border-width: 0 0 1px 0;\\n padding: \").concat(dt('datatable.body.cell.padding'), \";\\n}\\n\\n.p-datatable-hoverable .p-datatable-tbody > tr:not(.p-datatable-row-selected):hover {\\n background: \").concat(dt('datatable.row.hover.background'), \";\\n color: \").concat(dt('datatable.row.hover.color'), \";\\n}\\n\\n.p-datatable-tbody > tr.p-datatable-row-selected {\\n background: \").concat(dt('datatable.row.selected.background'), \";\\n color: \").concat(dt('datatable.row.selected.color'), \";\\n}\\n\\n.p-datatable-tbody > tr:has(+ .p-datatable-row-selected) > td {\\n border-bottom-color: \").concat(dt('datatable.body.cell.selected.border.color'), \";\\n}\\n\\n.p-datatable-tbody > tr.p-datatable-row-selected > td {\\n border-bottom-color: \").concat(dt('datatable.body.cell.selected.border.color'), \";\\n}\\n\\n.p-datatable-tbody > tr:focus-visible,\\n.p-datatable-tbody > tr.p-datatable-contextmenu-row-selected {\\n box-shadow: \").concat(dt('datatable.body.cell.focus.ring.shadow'), \";\\n outline: \").concat(dt('datatable.body.cell.focus.ring.width'), \" \").concat(dt('datatable.body.cell.focus.ring.style'), \" \").concat(dt('datatable.body.cell.focus.ring.color'), \";\\n outline-offset: \").concat(dt('datatable.body.cell.focus.ring.offset'), \";\\n}\\n\\n.p-datatable-tfoot > tr > td {\\n text-align: left;\\n padding: \").concat(dt('datatable.footer.cell.padding'), \";\\n border-color: \").concat(dt('datatable.footer.cell.border.color'), \";\\n border-style: solid;\\n border-width: 0 0 1px 0;\\n color: \").concat(dt('datatable.footer.cell.color'), \";\\n background: \").concat(dt('datatable.footer.cell.background'), \";\\n}\\n\\n.p-datatable-column-footer {\\n font-weight: \").concat(dt('datatable.column.footer.font.weight'), \";\\n}\\n\\n.p-datatable-sortable-column {\\n cursor: pointer;\\n user-select: none;\\n outline-color: transparent;\\n}\\n\\n.p-datatable-column-title,\\n.p-datatable-sort-icon,\\n.p-datatable-sort-badge {\\n vertical-align: middle;\\n}\\n\\n.p-datatable-sort-icon {\\n color: \").concat(dt('datatable.sort.icon.color'), \";\\n transition: color \").concat(dt('datatable.transition.duration'), \";\\n}\\n\\n.p-datatable-sortable-column:not(.p-datatable-column-sorted):hover {\\n background: \").concat(dt('datatable.header.cell.hover.background'), \";\\n color: \").concat(dt('datatable.header.cell.hover.color'), \";\\n}\\n\\n.p-datatable-sortable-column:not(.p-datatable-column-sorted):hover .p-datatable-sort-icon {\\n color: \").concat(dt('datatable.sort.icon.hover.color'), \";\\n}\\n\\n.p-datatable-column-sorted {\\n background: \").concat(dt('datatable.header.cell.selected.background'), \";\\n color: \").concat(dt('datatable.header.cell.selected.color'), \";\\n}\\n\\n.p-datatable-column-sorted .p-datatable-sort-icon {\\n color: \").concat(dt('datatable.header.cell.selected.color'), \";\\n}\\n\\n.p-datatable-sortable-column:focus-visible {\\n box-shadow: \").concat(dt('datatable.header.cell.focus.ring.shadow'), \";\\n outline: \").concat(dt('datatable.header.cell.focus.ring.width'), \" \").concat(dt('datatable.header.cell.focus.ring.style'), \" \").concat(dt('datatable.header.cell.focus.ring.color'), \";\\n outline-offset: \").concat(dt('datatable.header.cell.focus.ring.offset'), \";\\n}\\n\\n.p-datatable-hoverable .p-datatable-selectable-row {\\n cursor: pointer;\\n}\\n\\n.p-datatable-tbody > tr.p-datatable-dragpoint-top > td {\\n box-shadow: inset 0 2px 0 0 \").concat(dt('datatable.drop.point.color'), \";\\n}\\n\\n.p-datatable-tbody > tr.p-datatable-dragpoint-bottom > td {\\n box-shadow: inset 0 -2px 0 0 \").concat(dt('datatable.drop.point.color'), \";\\n}\\n\\n.p-datatable-loading-icon {\\n font-size: \").concat(dt('datatable.loading.icon.size'), \";\\n width: \").concat(dt('datatable.loading.icon.size'), \";\\n height: \").concat(dt('datatable.loading.icon.size'), \";\\n}\\n\\n.p-datatable-gridlines .p-datatable-header {\\n border-width: 1px 1px 0 1px;\\n}\\n\\n.p-datatable-gridlines .p-datatable-footer {\\n border-width: 0 1px 1px 1px;\\n}\\n\\n.p-datatable-gridlines .p-datatable-paginator-top {\\n border-width: 1px 1px 0 1px;\\n}\\n\\n.p-datatable-gridlines .p-datatable-paginator-bottom {\\n border-width: 0 1px 1px 1px;\\n}\\n\\n.p-datatable-gridlines .p-datatable-thead > tr > th {\\n border-width: 1px 0 1px 1px;\\n}\\n\\n.p-datatable-gridlines .p-datatable-thead > tr > th:last-child {\\n border-width: 1px;\\n}\\n\\n.p-datatable-gridlines .p-datatable-tbody > tr > td {\\n border-width: 1px 0 0 1px;\\n}\\n\\n.p-datatable-gridlines .p-datatable-tbody > tr > td:last-child {\\n border-width: 1px 1px 0 1px;\\n}\\n\\np-datatable-gridlines .p-datatable-tbody > tr:last-child > td {\\n border-width: 1px 0 1px 1px;\\n}\\n\\n.p-datatable-gridlines .p-datatable-tbody > tr:last-child > td:last-child {\\n border-width: 1px;\\n}\\n\\n.p-datatable-gridlines .p-datatable-tfoot > tr > td {\\n border-width: 1px 0 1px 1px;\\n}\\n\\n.p-datatable-gridlines .p-datatable-tfoot > tr > td:last-child {\\n border-width: 1px 1px 1px 1px;\\n}\\n\\n.p-datatable.p-datatable-gridlines .p-datatable-thead + .p-datatable-tfoot > tr > td {\\n border-width: 0 0 1px 1px;\\n}\\n\\n.p-datatable.p-datatable-gridlines .p-datatable-thead + .p-datatable-tfoot > tr > td:last-child {\\n border-width: 0 1px 1px 1px;\\n}\\n\\n.p-datatable.p-datatable-gridlines:has(.p-datatable-thead):has(.p-datatable-tbody) .p-datatable-tbody > tr > td {\\n border-width: 0 0 1px 1px;\\n}\\n\\n.p-datatable.p-datatable-gridlines:has(.p-datatable-thead):has(.p-datatable-tbody) .p-datatable-tbody > tr > td:last-child {\\n border-width: 0 1px 1px 1px;\\n}\\n\\n.p-datatable.p-datatable-gridlines:has(.p-datatable-tbody):has(.p-datatable-tfoot) .p-datatable-tbody > tr:last-child > td {\\n border-width: 0 0 0 1px;\\n}\\n\\n.p-datatable.p-datatable-gridlines:has(.p-datatable-tbody):has(.p-datatable-tfoot) .p-datatable-tbody > tr:last-child > td:last-child {\\n border-width: 0 1px 0 1px;\\n}\\n\\n.p-datatable.p-datatable-striped .p-datatable-tbody > tr.p-row-odd {\\n background: \").concat(dt('datatable.row.striped.background'), \";\\n}\\n\\n.p-datatable.p-datatable-striped .p-datatable-tbody > tr.p-row-odd.p-datatable-row-selected {\\n background: \").concat(dt('datatable.row.selected.background'), \";\\n color: \").concat(dt('datatable.row.selected.color'), \";\\n}\\n\\n.p-datatable.p-datatable-sm .p-datatable-header {\\n padding: 0.375rem 0.5rem;\\n}\\n\\n.p-datatable.p-datatable-sm .p-datatable-thead > tr > th {\\n padding: 0.375rem 0.5rem;\\n}\\n\\n.p-datatable.p-datatable-sm .p-datatable-tbody > tr > td {\\n padding: 0.375rem 0.5rem;\\n}\\n\\n.p-datatable.p-datatable-sm .p-datatable-tfoot > tr > td {\\n padding: 0.375rem 0.5rem;\\n}\\n\\n.p-datatable.p-datatable-sm .p-datatable-footer {\\n padding: 0.375rem 0.5rem;\\n}\\n\\n.p-datatable.p-datatable-lg .p-datatable-header {\\n padding: 0.9375rem 1.25rem;\\n}\\n\\n.p-datatable.p-datatable-lg .p-datatable-thead > tr > th {\\n padding: 0.9375rem 1.25rem;\\n}\\n\\n.p-datatable.p-datatable-lg .p-datatable-tbody>tr>td {\\n padding: 0.9375rem 1.25rem;\\n}\\n\\n.p-datatable.p-datatable-lg .p-datatable-tfoot>tr>td {\\n padding: 0.9375rem 1.25rem;\\n}\\n\\n.p-datatable.p-datatable-lg .p-datatable-footer {\\n padding: 0.9375rem 1.25rem;\\n}\\n\\n.p-datatable-row-toggle-button {\\n display: inline-flex;\\n align-items: center;\\n justify-content: center;\\n overflow: hidden;\\n position: relative;\\n width: \").concat(dt('datatable.row.toggle.button.size'), \";\\n height: \").concat(dt('datatable.row.toggle.button.size'), \";\\n color: \").concat(dt('datatable.row.toggle.button.color'), \";\\n border: 0 none;\\n background: transparent;\\n cursor: pointer;\\n border-radius: \").concat(dt('datatable.row.toggle.button.border.radius'), \";\\n transition: background \").concat(dt('datatable.transition.duration'), \", color \").concat(dt('datatable.transition.duration'), \", border-color \").concat(dt('datatable.transition.duration'), \",\\n outline-color \").concat(dt('datatable.transition.duration'), \", box-shadow \").concat(dt('datatable.transition.duration'), \";\\n outline-color: transparent;\\n user-select: none;\\n}\\n\\n.p-datatable-row-toggle-button:enabled:hover {\\n color: \").concat(dt('datatable.row.toggle.button.hover.color'), \";\\n background: \").concat(dt('datatable.row.toggle.button.hover.background'), \";\\n}\\n\\n.p-datatable-tbody > tr.p-datatable-row-selected .p-datatable-row-toggle-button:hover {\\n background: \").concat(dt('datatable.row.toggle.button.selected.hover.background'), \";\\n \").concat(dt('datatable.row.toggle.button.selected.hover.color'), \";\\n}\\n\\n.p-datatable-row-toggle-button:focus-visible {\\n box-shadow: \").concat(dt('datatable.row.toggle.button.focus.ring.shadow'), \";\\n outline: \").concat(dt('datatable.row.toggle.button.focus.ring.width'), \" \").concat(dt('datatable.row.toggle.button.focus.ring.style'), \" \").concat(dt('datatable.row.toggle.button.focus.ring.color'), \";\\n outline-offset: \").concat(dt('datatable.row.toggle.button.focus.ring.offset'), \";\\n}\\n\");\n};\nvar classes = {\n root: function root(_ref2) {\n var props = _ref2.props;\n return ['p-datatable p-component', {\n 'p-datatable-hoverable': props.rowHover || props.selectionMode,\n 'p-datatable-resizable': props.resizableColumns,\n 'p-datatable-resizable-fit': props.resizableColumns && props.columnResizeMode === 'fit',\n 'p-datatable-scrollable': props.scrollable,\n 'p-datatable-flex-scrollable': props.scrollable && props.scrollHeight === 'flex',\n 'p-datatable-striped': props.stripedRows,\n 'p-datatable-gridlines': props.showGridlines,\n 'p-datatable-sm': props.size === 'small',\n 'p-datatable-lg': props.size === 'large'\n }];\n },\n mask: 'p-datatable-mask p-overlay-mask',\n loadingIcon: 'p-datatable-loading-icon',\n header: 'p-datatable-header',\n pcPaginator: function pcPaginator(_ref3) {\n var position = _ref3.position;\n return 'p-datatable-paginator-' + position;\n },\n tableContainer: 'p-datatable-table-container',\n table: function table(_ref4) {\n var props = _ref4.props;\n return ['p-datatable-table', {\n 'p-datatable-scrollable-table': props.scrollable,\n 'p-datatable-resizable-table': props.resizableColumns,\n 'p-datatable-resizable-table-fit': props.resizableColumns && props.columnResizeMode === 'fit'\n }];\n },\n thead: 'p-datatable-thead',\n headerCell: function headerCell(_ref5) {\n var instance = _ref5.instance,\n props = _ref5.props,\n column = _ref5.column;\n return column && !instance.columnProp(column, 'hidden') && (props.rowGroupMode !== 'subheader' || props.groupRowsBy !== instance.columnProp(column, 'field')) ? ['p-datatable-header-cell', {\n 'p-datatable-frozen-column': instance.columnProp(column, 'frozen')\n }] : ['p-datatable-header-cell', {\n 'p-datatable-sortable-column': instance.columnProp('sortable'),\n 'p-datatable-resizable-column': instance.resizableColumns,\n 'p-datatable-column-sorted': instance.isColumnSorted(),\n 'p-datatable-frozen-column': instance.columnProp('frozen'),\n 'p-datatable-reorderable-column': props.reorderableColumns\n }];\n },\n columnResizer: 'p-datatable-column-resizer',\n columnHeaderContent: 'p-datatable-column-header-content',\n columnTitle: 'p-datatable-column-title',\n columnFooter: 'p-datatable-column-footer',\n sortIcon: 'p-datatable-sort-icon',\n pcSortBadge: 'p-datatable-sort-badge',\n filter: function filter(_ref6) {\n var props = _ref6.props;\n return ['p-datatable-filter', {\n 'p-datatable-inline-filter': props.display === 'row',\n 'p-datatable-popover-filter': props.display === 'menu'\n }];\n },\n filterElementContainer: 'p-datatable-filter-element-container',\n pcColumnFilterButton: 'p-datatable-column-filter-button',\n pcColumnFilterClearButton: 'p-datatable-column-filter-clear-button',\n filterOverlay: function filterOverlay(_ref7) {\n _ref7.instance;\n var props = _ref7.props;\n return ['p-datatable-filter-overlay p-component', {\n 'p-datatable-filter-overlay-popover': props.display === 'menu'\n }];\n },\n filterConstraintList: 'p-datatable-filter-constraint-list',\n filterConstraint: function filterConstraint(_ref8) {\n var instance = _ref8.instance,\n matchMode = _ref8.matchMode;\n return ['p-datatable-filter-constraint', {\n 'p-datatable-filter-constraint-selected': matchMode && instance.isRowMatchModeSelected(matchMode.value)\n }];\n },\n filterConstraintSeparator: 'p-datatable-filter-constraint-separator',\n filterOperator: 'p-datatable-filter-operator',\n pcFilterOperatorDropdown: 'p-datatable-filter-operator-dropdown',\n filterRuleList: 'p-datatable-filter-rule-list',\n filterRule: 'p-datatable-filter-rule',\n pcFilterConstraintDropdown: 'p-datatable-filter-constraint-dropdown',\n pcFilterRemoveRuleButton: 'p-datatable-filter-remove-rule-button',\n pcFilterAddRuleButton: 'p-datatable-filter-add-rule-button',\n filterButtonbar: 'p-datatable-filter-buttonbar',\n pcFilterClearButton: 'p-datatable-filter-clear-button',\n pcFilterApplyButton: 'p-datatable-filter-apply-button',\n tbody: function tbody(_ref9) {\n var props = _ref9.props;\n return props.frozenRow ? 'p-datatable-tbody p-datatable-frozen-tbody' : 'p-datatable-tbody';\n },\n rowGroupHeader: 'p-datatable-row-group-header',\n rowToggleButton: 'p-datatable-row-toggle-button',\n rowToggleIcon: 'p-datatable-row-toggle-icon',\n row: function row(_ref10) {\n var instance = _ref10.instance,\n props = _ref10.props,\n index = _ref10.index,\n columnSelectionMode = _ref10.columnSelectionMode;\n var rowStyleClass = [];\n if (props.selectionMode) {\n rowStyleClass.push('p-datatable-selectable-row');\n }\n if (props.selection) {\n rowStyleClass.push({\n 'p-datatable-row-selected': columnSelectionMode ? instance.isSelected && instance.$parentInstance.$parentInstance.highlightOnSelect : instance.isSelected\n });\n }\n if (props.contextMenuSelection) {\n rowStyleClass.push({\n 'p-datatable-contextmenu-row-selected': instance.isSelectedWithContextMenu\n });\n }\n rowStyleClass.push(index % 2 === 0 ? 'p-row-even' : 'p-row-odd');\n return rowStyleClass;\n },\n rowExpansion: 'p-datatable-row-expansion',\n rowGroupFooter: 'p-datatable-row-group-footer',\n emptyMessage: 'p-datatable-empty-message',\n bodyCell: function bodyCell(_ref11) {\n var instance = _ref11.instance;\n return [{\n 'p-datatable-frozen-column': instance.columnProp('frozen')\n }];\n },\n reorderableRowHandle: 'p-datatable-reorderable-row-handle',\n pcRowEditorInit: 'p-datatable-row-editor-init',\n pcRowEditorSave: 'p-datatable-row-editor-save',\n pcRowEditorCancel: 'p-datatable-row-editor-cancel',\n tfoot: 'p-datatable-tfoot',\n footerCell: function footerCell(_ref12) {\n var instance = _ref12.instance;\n return [{\n 'p-datatable-frozen-column': instance.columnProp('frozen')\n }];\n },\n virtualScrollerSpacer: 'p-datatable-virtualscroller-spacer',\n footer: 'p-datatable-footer',\n columnResizeIndicator: 'p-datatable-column-resize-indicator',\n rowReorderIndicatorUp: 'p-datatable-row-reorder-indicator-up',\n rowReorderIndicatorDown: 'p-datatable-row-reorder-indicator-down'\n};\nvar inlineStyles = {\n tableContainer: {\n overflow: 'auto'\n },\n thead: {\n position: 'sticky'\n },\n tfoot: {\n position: 'sticky'\n }\n};\nvar DataTableStyle = BaseStyle.extend({\n name: 'datatable',\n theme: theme,\n classes: classes,\n inlineStyles: inlineStyles\n});\n\nexport { DataTableStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseIcon from '@primevue/icons/baseicon';\nimport { openBlock, createElementBlock, mergeProps, createElementVNode } from 'vue';\n\nvar script = {\n name: 'ChevronRightIcon',\n \"extends\": BaseIcon\n};\n\nvar _hoisted_1 = /*#__PURE__*/createElementVNode(\"path\", {\n d: \"M4.38708 13C4.28408 13.0005 4.18203 12.9804 4.08691 12.9409C3.99178 12.9014 3.9055 12.8433 3.83313 12.7701C3.68634 12.6231 3.60388 12.4238 3.60388 12.2161C3.60388 12.0084 3.68634 11.8091 3.83313 11.6622L8.50507 6.99022L3.83313 2.31827C3.69467 2.16968 3.61928 1.97313 3.62287 1.77005C3.62645 1.56698 3.70872 1.37322 3.85234 1.22959C3.99596 1.08597 4.18972 1.00371 4.3928 1.00012C4.59588 0.996539 4.79242 1.07192 4.94102 1.21039L10.1669 6.43628C10.3137 6.58325 10.3962 6.78249 10.3962 6.99022C10.3962 7.19795 10.3137 7.39718 10.1669 7.54416L4.94102 12.7701C4.86865 12.8433 4.78237 12.9014 4.68724 12.9409C4.59212 12.9804 4.49007 13.0005 4.38708 13Z\",\n fill: \"currentColor\"\n}, null, -1);\nvar _hoisted_2 = [_hoisted_1];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"svg\", mergeProps({\n width: \"14\",\n height: \"14\",\n viewBox: \"0 0 14 14\",\n fill: \"none\",\n xmlns: \"http://www.w3.org/2000/svg\"\n }, _ctx.pti()), _hoisted_2, 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseIcon from '@primevue/icons/baseicon';\nimport { openBlock, createElementBlock, mergeProps, createElementVNode } from 'vue';\n\nvar script = {\n name: 'BarsIcon',\n \"extends\": BaseIcon\n};\n\nvar _hoisted_1 = /*#__PURE__*/createElementVNode(\"path\", {\n \"fill-rule\": \"evenodd\",\n \"clip-rule\": \"evenodd\",\n d: \"M13.3226 3.6129H0.677419C0.497757 3.6129 0.325452 3.54152 0.198411 3.41448C0.0713707 3.28744 0 3.11514 0 2.93548C0 2.75581 0.0713707 2.58351 0.198411 2.45647C0.325452 2.32943 0.497757 2.25806 0.677419 2.25806H13.3226C13.5022 2.25806 13.6745 2.32943 13.8016 2.45647C13.9286 2.58351 14 2.75581 14 2.93548C14 3.11514 13.9286 3.28744 13.8016 3.41448C13.6745 3.54152 13.5022 3.6129 13.3226 3.6129ZM13.3226 7.67741H0.677419C0.497757 7.67741 0.325452 7.60604 0.198411 7.479C0.0713707 7.35196 0 7.17965 0 6.99999C0 6.82033 0.0713707 6.64802 0.198411 6.52098C0.325452 6.39394 0.497757 6.32257 0.677419 6.32257H13.3226C13.5022 6.32257 13.6745 6.39394 13.8016 6.52098C13.9286 6.64802 14 6.82033 14 6.99999C14 7.17965 13.9286 7.35196 13.8016 7.479C13.6745 7.60604 13.5022 7.67741 13.3226 7.67741ZM0.677419 11.7419H13.3226C13.5022 11.7419 13.6745 11.6706 13.8016 11.5435C13.9286 11.4165 14 11.2442 14 11.0645C14 10.8848 13.9286 10.7125 13.8016 10.5855C13.6745 10.4585 13.5022 10.3871 13.3226 10.3871H0.677419C0.497757 10.3871 0.325452 10.4585 0.198411 10.5855C0.0713707 10.7125 0 10.8848 0 11.0645C0 11.2442 0.0713707 11.4165 0.198411 11.5435C0.325452 11.6706 0.497757 11.7419 0.677419 11.7419Z\",\n fill: \"currentColor\"\n}, null, -1);\nvar _hoisted_2 = [_hoisted_1];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"svg\", mergeProps({\n width: \"14\",\n height: \"14\",\n viewBox: \"0 0 14 14\",\n fill: \"none\",\n xmlns: \"http://www.w3.org/2000/svg\"\n }, _ctx.pti()), _hoisted_2, 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseIcon from '@primevue/icons/baseicon';\nimport { openBlock, createElementBlock, mergeProps, createElementVNode } from 'vue';\n\nvar script = {\n name: 'PencilIcon',\n \"extends\": BaseIcon\n};\n\nvar _hoisted_1 = /*#__PURE__*/createElementVNode(\"path\", {\n d: \"M0.609628 13.959C0.530658 13.9599 0.452305 13.9451 0.379077 13.9156C0.305849 13.8861 0.239191 13.8424 0.18294 13.787C0.118447 13.7234 0.0688234 13.6464 0.0376166 13.5614C0.00640987 13.4765 -0.00560954 13.3857 0.00241768 13.2956L0.25679 10.1501C0.267698 10.0041 0.331934 9.86709 0.437312 9.76516L9.51265 0.705715C10.0183 0.233014 10.6911 -0.0203041 11.3835 0.00127367C12.0714 0.00660201 12.7315 0.27311 13.2298 0.746671C13.7076 1.23651 13.9824 1.88848 13.9992 2.57201C14.0159 3.25554 13.7733 3.92015 13.32 4.4327L4.23648 13.5331C4.13482 13.6342 4.0017 13.6978 3.85903 13.7133L0.667067 14L0.609628 13.959ZM1.43018 10.4696L1.25787 12.714L3.50619 12.5092L12.4502 3.56444C12.6246 3.35841 12.7361 3.10674 12.7714 2.83933C12.8067 2.57193 12.7644 2.30002 12.6495 2.05591C12.5346 1.8118 12.3519 1.60575 12.1231 1.46224C11.8943 1.31873 11.6291 1.2438 11.3589 1.24633C11.1813 1.23508 11.0033 1.25975 10.8355 1.31887C10.6677 1.37798 10.5136 1.47033 10.3824 1.59036L1.43018 10.4696Z\",\n fill: \"currentColor\"\n}, null, -1);\nvar _hoisted_2 = [_hoisted_1];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"svg\", mergeProps({\n width: \"14\",\n height: \"14\",\n viewBox: \"0 0 14 14\",\n fill: \"none\",\n xmlns: \"http://www.w3.org/2000/svg\"\n }, _ctx.pti()), _hoisted_2, 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseIcon from '@primevue/icons/baseicon';\nimport { openBlock, createElementBlock, mergeProps, createElementVNode } from 'vue';\n\nvar script = {\n name: 'MinusIcon',\n \"extends\": BaseIcon\n};\n\nvar _hoisted_1 = /*#__PURE__*/createElementVNode(\"path\", {\n d: \"M13.2222 7.77778H0.777778C0.571498 7.77778 0.373667 7.69584 0.227806 7.54998C0.0819442 7.40412 0 7.20629 0 7.00001C0 6.79373 0.0819442 6.5959 0.227806 6.45003C0.373667 6.30417 0.571498 6.22223 0.777778 6.22223H13.2222C13.4285 6.22223 13.6263 6.30417 13.7722 6.45003C13.9181 6.5959 14 6.79373 14 7.00001C14 7.20629 13.9181 7.40412 13.7722 7.54998C13.6263 7.69584 13.4285 7.77778 13.2222 7.77778Z\",\n fill: \"currentColor\"\n}, null, -1);\nvar _hoisted_2 = [_hoisted_1];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"svg\", mergeProps({\n width: \"14\",\n height: \"14\",\n viewBox: \"0 0 14 14\",\n fill: \"none\",\n xmlns: \"http://www.w3.org/2000/svg\"\n }, _ctx.pti()), _hoisted_2, 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseStyle from '@primevue/core/base/style';\n\nvar theme = function theme(_ref) {\n var dt = _ref.dt;\n return \"\\n.p-checkbox {\\n position: relative;\\n display: inline-flex;\\n user-select: none;\\n vertical-align: bottom;\\n width: \".concat(dt('checkbox.width'), \";\\n height: \").concat(dt('checkbox.height'), \";\\n}\\n\\n.p-checkbox-input {\\n cursor: pointer;\\n appearance: none;\\n position: absolute;\\n top: 0;\\n left: 0;\\n width: 100%;\\n height: 100%;\\n padding: 0;\\n margin: 0;\\n opacity: 0;\\n z-index: 1;\\n outline: 0 none;\\n border: 1px solid transparent;\\n border-radius: \").concat(dt('checkbox.border.radius'), \";\\n}\\n\\n.p-checkbox-box {\\n display: flex;\\n justify-content: center;\\n align-items: center;\\n border-radius: \").concat(dt('checkbox.border.radius'), \";\\n border: 1px solid \").concat(dt('checkbox.border.color'), \";\\n background: \").concat(dt('checkbox.background'), \";\\n width: \").concat(dt('checkbox.width'), \";\\n height: \").concat(dt('checkbox.height'), \";\\n transition: background \").concat(dt('checkbox.transition.duration'), \", color \").concat(dt('checkbox.transition.duration'), \", border-color \").concat(dt('checkbox.transition.duration'), \", box-shadow \").concat(dt('checkbox.transition.duration'), \", outline-color \").concat(dt('checkbox.transition.duration'), \";\\n outline-color: transparent;\\n box-shadow: \").concat(dt('checkbox.shadow'), \";\\n}\\n\\n.p-checkbox-icon {\\n transition-duration: \").concat(dt('checkbox.transition.duration'), \";\\n color: \").concat(dt('checkbox.icon.color'), \";\\n font-size: \").concat(dt('checkbox.icon.size'), \";\\n width: \").concat(dt('checkbox.icon.size'), \";\\n height: \").concat(dt('checkbox.icon.size'), \";\\n}\\n\\n.p-checkbox:not(.p-disabled):has(.p-checkbox-input:hover) .p-checkbox-box {\\n border-color: \").concat(dt('checkbox.hover.border.color'), \";\\n}\\n\\n.p-checkbox-checked .p-checkbox-box {\\n border-color: \").concat(dt('checkbox.checked.border.color'), \";\\n background: \").concat(dt('checkbox.checked.background'), \";\\n}\\n\\n.p-checkbox-checked .p-checkbox-icon {\\n color: \").concat(dt('checkbox.icon.checked.color'), \";\\n}\\n\\n.p-checkbox-checked:not(.p-disabled):has(.p-checkbox-input:hover) .p-checkbox-box {\\n background: \").concat(dt('checkbox.checked.hover.background'), \";\\n border-color: \").concat(dt('checkbox.checked.hover.border.color'), \";\\n}\\n\\n.p-checkbox-checked:not(.p-disabled):has(.p-checkbox-input:hover) .p-checkbox-icon {\\n color: \").concat(dt('checkbox.icon.checked.hover.color'), \";\\n}\\n\\n.p-checkbox:not(.p-disabled):has(.p-checkbox-input:focus-visible) .p-checkbox-box {\\n border-color: \").concat(dt('checkbox.focus.border.color'), \";\\n box-shadow: \").concat(dt('checkbox.focus.ring.shadow'), \";\\n outline: \").concat(dt('checkbox.focus.ring.width'), \" \").concat(dt('checkbox.focus.ring.style'), \" \").concat(dt('checkbox.focus.ring.color'), \";\\n outline-offset: \").concat(dt('checkbox.focus.ring.offset'), \";\\n}\\n\\n.p-checkbox-checked:not(.p-disabled):has(.p-checkbox-input:focus-visible) .p-checkbox-box {\\n border-color: \").concat(dt('checkbox.checked.focus.border.color'), \";\\n}\\n\\n.p-checkbox.p-invalid > .p-checkbox-box {\\n border-color: \").concat(dt('checkbox.invalid.border.color'), \";\\n}\\n\\n.p-checkbox.p-variant-filled .p-checkbox-box {\\n background: \").concat(dt('checkbox.filled.background'), \";\\n}\\n\\n.p-checkbox-checked.p-variant-filled .p-checkbox-box {\\n background: \").concat(dt('checkbox.checked.background'), \";\\n}\\n\\n.p-checkbox-checked.p-variant-filled:not(.p-disabled):has(.p-checkbox-input:hover) .p-checkbox-box {\\n background: \").concat(dt('checkbox.checked.hover.background'), \";\\n}\\n\\n.p-checkbox.p-disabled {\\n opacity: 1;\\n}\\n\\n.p-checkbox.p-disabled .p-checkbox-box {\\n background: \").concat(dt('checkbox.disabled.background'), \";\\n border-color: \").concat(dt('checkbox.checked.disabled.border.color'), \";\\n}\\n\\n.p-checkbox.p-disabled .p-checkbox-box .p-checkbox-icon {\\n color: \").concat(dt('checkbox.icon.disabled.color'), \";\\n}\\n\");\n};\nvar classes = {\n root: function root(_ref2) {\n var instance = _ref2.instance,\n props = _ref2.props;\n return ['p-checkbox p-component', {\n 'p-checkbox-checked': instance.checked,\n 'p-disabled': props.disabled,\n 'p-invalid': props.invalid,\n 'p-variant-filled': props.variant ? props.variant === 'filled' : instance.$primevue.config.inputStyle === 'filled' || instance.$primevue.config.inputVariant === 'filled'\n }];\n },\n box: 'p-checkbox-box',\n input: 'p-checkbox-input',\n icon: 'p-checkbox-icon'\n};\nvar CheckboxStyle = BaseStyle.extend({\n name: 'checkbox',\n theme: theme,\n classes: classes\n});\n\nexport { CheckboxStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import { equals, contains } from '@primeuix/utils/object';\nimport CheckIcon from '@primevue/icons/check';\nimport MinusIcon from '@primevue/icons/minus';\nimport BaseComponent from '@primevue/core/basecomponent';\nimport CheckboxStyle from 'primevue/checkbox/style';\nimport { resolveComponent, openBlock, createElementBlock, mergeProps, createElementVNode, renderSlot, normalizeClass, createBlock, createCommentVNode } from 'vue';\n\nvar script$1 = {\n name: 'BaseCheckbox',\n \"extends\": BaseComponent,\n props: {\n value: null,\n modelValue: null,\n binary: Boolean,\n name: {\n type: String,\n \"default\": null\n },\n indeterminate: {\n type: Boolean,\n \"default\": false\n },\n trueValue: {\n type: null,\n \"default\": true\n },\n falseValue: {\n type: null,\n \"default\": false\n },\n variant: {\n type: String,\n \"default\": null\n },\n invalid: {\n type: Boolean,\n \"default\": false\n },\n disabled: {\n type: Boolean,\n \"default\": false\n },\n readonly: {\n type: Boolean,\n \"default\": false\n },\n required: {\n type: Boolean,\n \"default\": false\n },\n tabindex: {\n type: Number,\n \"default\": null\n },\n inputId: {\n type: String,\n \"default\": null\n },\n inputClass: {\n type: [String, Object],\n \"default\": null\n },\n inputStyle: {\n type: Object,\n \"default\": null\n },\n ariaLabelledby: {\n type: String,\n \"default\": null\n },\n ariaLabel: {\n type: String,\n \"default\": null\n }\n },\n style: CheckboxStyle,\n provide: function provide() {\n return {\n $pcCheckbox: this,\n $parentInstance: this\n };\n }\n};\n\nfunction _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _unsupportedIterableToArray(r, a) { if (r) { if (\"string\" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return \"Object\" === t && r.constructor && (t = r.constructor.name), \"Map\" === t || \"Set\" === t ? Array.from(r) : \"Arguments\" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }\nfunction _iterableToArray(r) { if (\"undefined\" != typeof Symbol && null != r[Symbol.iterator] || null != r[\"@@iterator\"]) return Array.from(r); }\nfunction _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }\nfunction _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }\nvar script = {\n name: 'Checkbox',\n \"extends\": script$1,\n inheritAttrs: false,\n emits: ['update:modelValue', 'change', 'focus', 'blur', 'update:indeterminate'],\n data: function data() {\n return {\n d_indeterminate: this.indeterminate\n };\n },\n watch: {\n indeterminate: function indeterminate(newValue) {\n this.d_indeterminate = newValue;\n }\n },\n methods: {\n getPTOptions: function getPTOptions(key) {\n var _ptm = key === 'root' ? this.ptmi : this.ptm;\n return _ptm(key, {\n context: {\n checked: this.checked,\n disabled: this.disabled\n }\n });\n },\n onChange: function onChange(event) {\n var _this = this;\n if (!this.disabled && !this.readonly) {\n var newModelValue;\n if (this.binary) {\n newModelValue = this.d_indeterminate ? this.trueValue : this.checked ? this.falseValue : this.trueValue;\n } else {\n if (this.checked || this.d_indeterminate) newModelValue = this.modelValue.filter(function (val) {\n return !equals(val, _this.value);\n });else newModelValue = this.modelValue ? [].concat(_toConsumableArray(this.modelValue), [this.value]) : [this.value];\n }\n if (this.d_indeterminate) {\n this.d_indeterminate = false;\n this.$emit('update:indeterminate', this.d_indeterminate);\n }\n this.$emit('update:modelValue', newModelValue);\n this.$emit('change', event);\n }\n },\n onFocus: function onFocus(event) {\n this.$emit('focus', event);\n },\n onBlur: function onBlur(event) {\n this.$emit('blur', event);\n }\n },\n computed: {\n checked: function checked() {\n return this.d_indeterminate ? false : this.binary ? this.modelValue === this.trueValue : contains(this.value, this.modelValue);\n }\n },\n components: {\n CheckIcon: CheckIcon,\n MinusIcon: MinusIcon\n }\n};\n\nvar _hoisted_1 = [\"data-p-checked\", \"data-p-indeterminate\", \"data-p-disabled\"];\nvar _hoisted_2 = [\"id\", \"value\", \"name\", \"checked\", \"tabindex\", \"disabled\", \"readonly\", \"required\", \"aria-labelledby\", \"aria-label\", \"aria-invalid\", \"aria-checked\"];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n var _component_CheckIcon = resolveComponent(\"CheckIcon\");\n var _component_MinusIcon = resolveComponent(\"MinusIcon\");\n return openBlock(), createElementBlock(\"div\", mergeProps({\n \"class\": _ctx.cx('root')\n }, $options.getPTOptions('root'), {\n \"data-p-checked\": $options.checked,\n \"data-p-indeterminate\": $data.d_indeterminate || undefined,\n \"data-p-disabled\": _ctx.disabled\n }), [createElementVNode(\"input\", mergeProps({\n id: _ctx.inputId,\n type: \"checkbox\",\n \"class\": [_ctx.cx('input'), _ctx.inputClass],\n style: _ctx.inputStyle,\n value: _ctx.value,\n name: _ctx.name,\n checked: $options.checked,\n tabindex: _ctx.tabindex,\n disabled: _ctx.disabled,\n readonly: _ctx.readonly,\n required: _ctx.required,\n \"aria-labelledby\": _ctx.ariaLabelledby,\n \"aria-label\": _ctx.ariaLabel,\n \"aria-invalid\": _ctx.invalid || undefined,\n \"aria-checked\": $data.d_indeterminate ? 'mixed' : undefined,\n onFocus: _cache[0] || (_cache[0] = function () {\n return $options.onFocus && $options.onFocus.apply($options, arguments);\n }),\n onBlur: _cache[1] || (_cache[1] = function () {\n return $options.onBlur && $options.onBlur.apply($options, arguments);\n }),\n onChange: _cache[2] || (_cache[2] = function () {\n return $options.onChange && $options.onChange.apply($options, arguments);\n })\n }, $options.getPTOptions('input')), null, 16, _hoisted_2), createElementVNode(\"div\", mergeProps({\n \"class\": _ctx.cx('box')\n }, $options.getPTOptions('box')), [renderSlot(_ctx.$slots, \"icon\", {\n checked: $options.checked,\n indeterminate: $data.d_indeterminate,\n \"class\": normalizeClass(_ctx.cx('icon'))\n }, function () {\n return [$options.checked ? (openBlock(), createBlock(_component_CheckIcon, mergeProps({\n key: 0,\n \"class\": _ctx.cx('icon')\n }, $options.getPTOptions('icon')), null, 16, [\"class\"])) : $data.d_indeterminate ? (openBlock(), createBlock(_component_MinusIcon, mergeProps({\n key: 1,\n \"class\": _ctx.cx('icon')\n }, $options.getPTOptions('icon')), null, 16, [\"class\"])) : createCommentVNode(\"\", true)];\n })], 16)], 16, _hoisted_1);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseStyle from '@primevue/core/base/style';\n\nvar theme = function theme(_ref) {\n var dt = _ref.dt;\n return \"\\n.p-radiobutton {\\n position: relative;\\n display: inline-flex;\\n user-select: none;\\n vertical-align: bottom;\\n width: \".concat(dt('radiobutton.width'), \";\\n height: \").concat(dt('radiobutton.height'), \";\\n}\\n\\n.p-radiobutton-input {\\n cursor: pointer;\\n appearance: none;\\n position: absolute;\\n top: 0;\\n left: 0;\\n width: 100%;\\n height: 100%;\\n padding: 0;\\n margin: 0;\\n opacity: 0;\\n z-index: 1;\\n outline: 0 none;\\n border: 1px solid transparent;\\n border-radius: 50%;\\n}\\n\\n.p-radiobutton-box {\\n display: flex;\\n justify-content: center;\\n align-items: center;\\n border-radius: 50%;\\n border: 1px solid \").concat(dt('radiobutton.border.color'), \";\\n background: \").concat(dt('radiobutton.background'), \";\\n width: \").concat(dt('radiobutton.width'), \";\\n height: \").concat(dt('radiobutton.height'), \";\\n transition: background \").concat(dt('radiobutton.transition.duration'), \", color \").concat(dt('radiobutton.transition.duration'), \", border-color \").concat(dt('radiobutton.transition.duration'), \", box-shadow \").concat(dt('radiobutton.transition.duration'), \", outline-color \").concat(dt('radiobutton.transition.duration'), \";\\n outline-color: transparent;\\n box-shadow: \").concat(dt('radiobutton.shadow'), \";\\n}\\n\\n.p-radiobutton-icon {\\n transition-duration: \").concat(dt('radiobutton.transition.duration'), \";\\n background: transparent;\\n font-size: \").concat(dt('radiobutton.icon.size'), \";\\n width: \").concat(dt('radiobutton.icon.size'), \";\\n height: \").concat(dt('radiobutton.icon.size'), \";\\n border-radius: 50%;\\n backface-visibility: hidden;\\n transform: translateZ(0) scale(0.1);\\n}\\n\\n.p-radiobutton:not(.p-disabled):has(.p-radiobutton-input:hover) .p-radiobutton-box {\\n border-color: \").concat(dt('radiobutton.hover.border.color'), \";\\n}\\n\\n.p-radiobutton-checked .p-radiobutton-box {\\n border-color: \").concat(dt('radiobutton.checked.border.color'), \";\\n background: \").concat(dt('radiobutton.checked.background'), \";\\n}\\n\\n.p-radiobutton-checked .p-radiobutton-box .p-radiobutton-icon {\\n background: \").concat(dt('radiobutton.icon.checked.color'), \";\\n transform: translateZ(0) scale(1, 1);\\n visibility: visible;\\n}\\n\\n.p-radiobutton-checked:not(.p-disabled):has(.p-radiobutton-input:hover) .p-radiobutton-box {\\n border-color: \").concat(dt('radiobutton.checked.hover.border.color'), \";\\n background: \").concat(dt('radiobutton.checked.hover.background'), \";\\n}\\n\\n.p-radiobutton:not(.p-disabled):has(.p-radiobutton-input:hover).p-radiobutton-checked .p-radiobutton-box .p-radiobutton-icon {\\n background: \").concat(dt('radiobutton.icon.checked.hover.color'), \";\\n}\\n\\n.p-radiobutton:not(.p-disabled):has(.p-radiobutton-input:focus-visible) .p-radiobutton-box {\\n border-color: \").concat(dt('radiobutton.focus.border.color'), \";\\n box-shadow: \").concat(dt('radiobutton.focus.ring.shadow'), \";\\n outline: \").concat(dt('radiobutton.focus.ring.width'), \" \").concat(dt('radiobutton.focus.ring.style'), \" \").concat(dt('radiobutton.focus.ring.color'), \";\\n outline-offset: \").concat(dt('radiobutton.focus.ring.offset'), \";\\n}\\n\\n.p-radiobutton-checked:not(.p-disabled):has(.p-radiobutton-input:focus-visible) .p-radiobutton-box {\\n border-color: \").concat(dt('radiobutton.checked.focus.border.color'), \";\\n}\\n\\n.p-radiobutton.p-invalid > .p-radiobutton-box {\\n border-color: \").concat(dt('radiobutton.invalid.border.color'), \";\\n}\\n\\n.p-radiobutton.p-variant-filled .p-radiobutton-box {\\n background: \").concat(dt('radiobutton.filled.background'), \";\\n}\\n\\n.p-radiobutton.p-variant-filled.p-radiobutton-checked .p-radiobutton-box {\\n background: \").concat(dt('radiobutton.checked.background'), \";\\n}\\n\\n.p-radiobutton.p-variant-filled:not(.p-disabled):has(.p-radiobutton-input:hover).p-radiobutton-checked .p-radiobutton-box {\\n background: \").concat(dt('radiobutton.checked.hover.background'), \";\\n}\\n\\n.p-radiobutton.p-disabled {\\n opacity: 1;\\n}\\n\\n.p-radiobutton.p-disabled .p-radiobutton-box {\\n background: \").concat(dt('radiobutton.disabled.background'), \";\\n border-color: \").concat(dt('radiobutton.checked.disabled.border.color'), \";\\n}\\n\\n.p-radiobutton-checked.p-disabled .p-radiobutton-box .p-radiobutton-icon {\\n background: \").concat(dt('radiobutton.icon.disabled.color'), \";\\n}\\n\");\n};\nvar classes = {\n root: function root(_ref2) {\n var instance = _ref2.instance,\n props = _ref2.props;\n return ['p-radiobutton p-component', {\n 'p-radiobutton-checked': instance.checked,\n 'p-disabled': props.disabled,\n 'p-invalid': props.invalid,\n 'p-variant-filled': props.variant ? props.variant === 'filled' : instance.$primevue.config.inputStyle === 'filled' || instance.$primevue.config.inputVariant === 'filled'\n }];\n },\n box: 'p-radiobutton-box',\n input: 'p-radiobutton-input',\n icon: 'p-radiobutton-icon'\n};\nvar RadioButtonStyle = BaseStyle.extend({\n name: 'radiobutton',\n theme: theme,\n classes: classes\n});\n\nexport { RadioButtonStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import { equals } from '@primeuix/utils/object';\nimport BaseComponent from '@primevue/core/basecomponent';\nimport RadioButtonStyle from 'primevue/radiobutton/style';\nimport { openBlock, createElementBlock, mergeProps, createElementVNode } from 'vue';\n\nvar script$1 = {\n name: 'BaseRadioButton',\n \"extends\": BaseComponent,\n props: {\n value: null,\n modelValue: null,\n binary: Boolean,\n name: {\n type: String,\n \"default\": null\n },\n variant: {\n type: String,\n \"default\": null\n },\n invalid: {\n type: Boolean,\n \"default\": false\n },\n disabled: {\n type: Boolean,\n \"default\": false\n },\n readonly: {\n type: Boolean,\n \"default\": false\n },\n tabindex: {\n type: Number,\n \"default\": null\n },\n inputId: {\n type: String,\n \"default\": null\n },\n inputClass: {\n type: [String, Object],\n \"default\": null\n },\n inputStyle: {\n type: Object,\n \"default\": null\n },\n ariaLabelledby: {\n type: String,\n \"default\": null\n },\n ariaLabel: {\n type: String,\n \"default\": null\n }\n },\n style: RadioButtonStyle,\n provide: function provide() {\n return {\n $pcRadioButton: this,\n $parentInstance: this\n };\n }\n};\n\nvar script = {\n name: 'RadioButton',\n \"extends\": script$1,\n inheritAttrs: false,\n emits: ['update:modelValue', 'change', 'focus', 'blur'],\n methods: {\n getPTOptions: function getPTOptions(key) {\n var _ptm = key === 'root' ? this.ptmi : this.ptm;\n return _ptm(key, {\n context: {\n checked: this.checked,\n disabled: this.disabled\n }\n });\n },\n onChange: function onChange(event) {\n if (!this.disabled && !this.readonly) {\n var newModelValue = this.binary ? !this.checked : this.value;\n this.$emit('update:modelValue', newModelValue);\n this.$emit('change', event);\n }\n },\n onFocus: function onFocus(event) {\n this.$emit('focus', event);\n },\n onBlur: function onBlur(event) {\n this.$emit('blur', event);\n }\n },\n computed: {\n checked: function checked() {\n return this.modelValue != null && (this.binary ? !!this.modelValue : equals(this.modelValue, this.value));\n }\n }\n};\n\nvar _hoisted_1 = [\"data-p-checked\", \"data-p-disabled\"];\nvar _hoisted_2 = [\"id\", \"value\", \"name\", \"checked\", \"tabindex\", \"disabled\", \"readonly\", \"aria-labelledby\", \"aria-label\", \"aria-invalid\"];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"div\", mergeProps({\n \"class\": _ctx.cx('root')\n }, $options.getPTOptions('root'), {\n \"data-p-checked\": $options.checked,\n \"data-p-disabled\": _ctx.disabled\n }), [createElementVNode(\"input\", mergeProps({\n id: _ctx.inputId,\n type: \"radio\",\n \"class\": [_ctx.cx('input'), _ctx.inputClass],\n style: _ctx.inputStyle,\n value: _ctx.value,\n name: _ctx.name,\n checked: $options.checked,\n tabindex: _ctx.tabindex,\n disabled: _ctx.disabled,\n readonly: _ctx.readonly,\n \"aria-labelledby\": _ctx.ariaLabelledby,\n \"aria-label\": _ctx.ariaLabel,\n \"aria-invalid\": _ctx.invalid || undefined,\n onFocus: _cache[0] || (_cache[0] = function () {\n return $options.onFocus && $options.onFocus.apply($options, arguments);\n }),\n onBlur: _cache[1] || (_cache[1] = function () {\n return $options.onBlur && $options.onBlur.apply($options, arguments);\n }),\n onChange: _cache[2] || (_cache[2] = function () {\n return $options.onChange && $options.onChange.apply($options, arguments);\n })\n }, $options.getPTOptions('input')), null, 16, _hoisted_2), createElementVNode(\"div\", mergeProps({\n \"class\": _ctx.cx('box')\n }, $options.getPTOptions('box')), [createElementVNode(\"div\", mergeProps({\n \"class\": _ctx.cx('icon')\n }, $options.getPTOptions('icon')), null, 16)], 16)], 16, _hoisted_1);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseIcon from '@primevue/icons/baseicon';\nimport { openBlock, createElementBlock, mergeProps, createElementVNode } from 'vue';\n\nvar script = {\n name: 'FilterIcon',\n \"extends\": BaseIcon\n};\n\nvar _hoisted_1 = /*#__PURE__*/createElementVNode(\"path\", {\n d: \"M8.64708 14H5.35296C5.18981 13.9979 5.03395 13.9321 4.91858 13.8167C4.8032 13.7014 4.73745 13.5455 4.73531 13.3824V7L0.329431 0.98C0.259794 0.889466 0.217389 0.780968 0.20718 0.667208C0.19697 0.553448 0.219379 0.439133 0.271783 0.337647C0.324282 0.236453 0.403423 0.151519 0.500663 0.0920138C0.597903 0.0325088 0.709548 0.000692754 0.823548 0H13.1765C13.2905 0.000692754 13.4021 0.0325088 13.4994 0.0920138C13.5966 0.151519 13.6758 0.236453 13.7283 0.337647C13.7807 0.439133 13.8031 0.553448 13.7929 0.667208C13.7826 0.780968 13.7402 0.889466 13.6706 0.98L9.26472 7V13.3824C9.26259 13.5455 9.19683 13.7014 9.08146 13.8167C8.96609 13.9321 8.81022 13.9979 8.64708 14ZM5.97061 12.7647H8.02943V6.79412C8.02878 6.66289 8.07229 6.53527 8.15296 6.43177L11.9412 1.23529H2.05884L5.86355 6.43177C5.94422 6.53527 5.98773 6.66289 5.98708 6.79412L5.97061 12.7647Z\",\n fill: \"currentColor\"\n}, null, -1);\nvar _hoisted_2 = [_hoisted_1];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"svg\", mergeProps({\n width: \"14\",\n height: \"14\",\n viewBox: \"0 0 14 14\",\n fill: \"none\",\n xmlns: \"http://www.w3.org/2000/svg\"\n }, _ctx.pti()), _hoisted_2, 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseIcon from '@primevue/icons/baseicon';\nimport { openBlock, createElementBlock, mergeProps, createElementVNode } from 'vue';\n\nvar script = {\n name: 'FilterSlashIcon',\n \"extends\": BaseIcon\n};\n\nvar _hoisted_1 = /*#__PURE__*/createElementVNode(\"path\", {\n \"fill-rule\": \"evenodd\",\n \"clip-rule\": \"evenodd\",\n d: \"M13.4994 0.0920138C13.5967 0.151519 13.6758 0.236453 13.7283 0.337647C13.7807 0.439133 13.8031 0.553448 13.7929 0.667208C13.7827 0.780968 13.7403 0.889466 13.6707 0.98L11.406 4.06823C11.3099 4.19928 11.1656 4.28679 11.005 4.3115C10.8444 4.33621 10.6805 4.2961 10.5495 4.2C10.4184 4.1039 10.3309 3.95967 10.3062 3.79905C10.2815 3.63843 10.3216 3.47458 10.4177 3.34353L11.9412 1.23529H7.41184C7.24803 1.23529 7.09093 1.17022 6.97509 1.05439C6.85926 0.938558 6.79419 0.781457 6.79419 0.617647C6.79419 0.453837 6.85926 0.296736 6.97509 0.180905C7.09093 0.0650733 7.24803 0 7.41184 0H13.1765C13.2905 0.000692754 13.4022 0.0325088 13.4994 0.0920138ZM4.20008 0.181168H4.24126L13.2013 9.03411C13.3169 9.14992 13.3819 9.3069 13.3819 9.47058C13.3819 9.63426 13.3169 9.79124 13.2013 9.90705C13.1445 9.96517 13.0766 10.0112 13.0016 10.0423C12.9266 10.0735 12.846 10.0891 12.7648 10.0882C12.6836 10.0886 12.6032 10.0728 12.5283 10.0417C12.4533 10.0106 12.3853 9.96479 12.3283 9.90705L9.3142 6.92587L9.26479 6.99999V13.3823C9.26265 13.5455 9.19689 13.7014 9.08152 13.8167C8.96615 13.9321 8.81029 13.9979 8.64714 14H5.35302C5.18987 13.9979 5.03401 13.9321 4.91864 13.8167C4.80327 13.7014 4.73751 13.5455 4.73537 13.3823V6.99999L0.329492 1.02117C0.259855 0.930634 0.21745 0.822137 0.207241 0.708376C0.197031 0.594616 0.21944 0.480301 0.271844 0.378815C0.324343 0.277621 0.403484 0.192687 0.500724 0.133182C0.597964 0.073677 0.709609 0.041861 0.823609 0.0411682H3.86243C3.92448 0.0461551 3.9855 0.060022 4.04361 0.0823446C4.10037 0.10735 4.15311 0.140655 4.20008 0.181168ZM8.02949 6.79411C8.02884 6.66289 8.07235 6.53526 8.15302 6.43176L8.42478 6.05293L3.55773 1.23529H2.0589L5.84714 6.43176C5.92781 6.53526 5.97132 6.66289 5.97067 6.79411V12.7647H8.02949V6.79411Z\",\n fill: \"currentColor\"\n}, null, -1);\nvar _hoisted_2 = [_hoisted_1];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"svg\", mergeProps({\n width: \"14\",\n height: \"14\",\n viewBox: \"0 0 14 14\",\n fill: \"none\",\n xmlns: \"http://www.w3.org/2000/svg\"\n }, _ctx.pti()), _hoisted_2, 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseIcon from '@primevue/icons/baseicon';\nimport { openBlock, createElementBlock, mergeProps, createElementVNode } from 'vue';\n\nvar script = {\n name: 'PlusIcon',\n \"extends\": BaseIcon\n};\n\nvar _hoisted_1 = /*#__PURE__*/createElementVNode(\"path\", {\n d: \"M7.67742 6.32258V0.677419C7.67742 0.497757 7.60605 0.325452 7.47901 0.198411C7.35197 0.0713707 7.17966 0 7 0C6.82034 0 6.64803 0.0713707 6.52099 0.198411C6.39395 0.325452 6.32258 0.497757 6.32258 0.677419V6.32258H0.677419C0.497757 6.32258 0.325452 6.39395 0.198411 6.52099C0.0713707 6.64803 0 6.82034 0 7C0 7.17966 0.0713707 7.35197 0.198411 7.47901C0.325452 7.60605 0.497757 7.67742 0.677419 7.67742H6.32258V13.3226C6.32492 13.5015 6.39704 13.6725 6.52358 13.799C6.65012 13.9255 6.82106 13.9977 7 14C7.17966 14 7.35197 13.9286 7.47901 13.8016C7.60605 13.6745 7.67742 13.5022 7.67742 13.3226V7.67742H13.3226C13.5022 7.67742 13.6745 7.60605 13.8016 7.47901C13.9286 7.35197 14 7.17966 14 7C13.9977 6.82106 13.9255 6.65012 13.799 6.52358C13.6725 6.39704 13.5015 6.32492 13.3226 6.32258H7.67742Z\",\n fill: \"currentColor\"\n}, null, -1);\nvar _hoisted_2 = [_hoisted_1];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"svg\", mergeProps({\n width: \"14\",\n height: \"14\",\n viewBox: \"0 0 14 14\",\n fill: \"none\",\n xmlns: \"http://www.w3.org/2000/svg\"\n }, _ctx.pti()), _hoisted_2, 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseIcon from '@primevue/icons/baseicon';\nimport { openBlock, createElementBlock, mergeProps, createElementVNode } from 'vue';\n\nvar script = {\n name: 'TrashIcon',\n \"extends\": BaseIcon\n};\n\nvar _hoisted_1 = /*#__PURE__*/createElementVNode(\"path\", {\n \"fill-rule\": \"evenodd\",\n \"clip-rule\": \"evenodd\",\n d: \"M3.44802 13.9955H10.552C10.8056 14.0129 11.06 13.9797 11.3006 13.898C11.5412 13.8163 11.7632 13.6877 11.9537 13.5196C12.1442 13.3515 12.2995 13.1473 12.4104 12.9188C12.5213 12.6903 12.5858 12.442 12.6 12.1884V4.36041H13.4C13.5591 4.36041 13.7117 4.29722 13.8243 4.18476C13.9368 4.07229 14 3.91976 14 3.76071C14 3.60166 13.9368 3.44912 13.8243 3.33666C13.7117 3.22419 13.5591 3.16101 13.4 3.16101H12.0537C12.0203 3.1557 11.9863 3.15299 11.952 3.15299C11.9178 3.15299 11.8838 3.1557 11.8503 3.16101H11.2285C11.2421 3.10893 11.2487 3.05513 11.248 3.00106V1.80966C11.2171 1.30262 10.9871 0.828306 10.608 0.48989C10.229 0.151475 9.73159 -0.0236625 9.22402 0.00257442H4.77602C4.27251 -0.0171866 3.78126 0.160868 3.40746 0.498617C3.03365 0.836366 2.807 1.30697 2.77602 1.80966V3.00106C2.77602 3.0556 2.78346 3.10936 2.79776 3.16101H0.6C0.521207 3.16101 0.443185 3.17652 0.37039 3.20666C0.297595 3.2368 0.231451 3.28097 0.175736 3.33666C0.120021 3.39235 0.0758251 3.45846 0.0456722 3.53121C0.0155194 3.60397 0 3.68196 0 3.76071C0 3.83946 0.0155194 3.91744 0.0456722 3.9902C0.0758251 4.06296 0.120021 4.12907 0.175736 4.18476C0.231451 4.24045 0.297595 4.28462 0.37039 4.31476C0.443185 4.3449 0.521207 4.36041 0.6 4.36041H1.40002V12.1884C1.41426 12.442 1.47871 12.6903 1.58965 12.9188C1.7006 13.1473 1.85582 13.3515 2.04633 13.5196C2.23683 13.6877 2.45882 13.8163 2.69944 13.898C2.94005 13.9797 3.1945 14.0129 3.44802 13.9955ZM2.60002 4.36041H11.304V12.1884C11.304 12.5163 10.952 12.7961 10.504 12.7961H3.40002C2.97602 12.7961 2.60002 12.5163 2.60002 12.1884V4.36041ZM3.95429 3.16101C3.96859 3.10936 3.97602 3.0556 3.97602 3.00106V1.80966C3.97602 1.48183 4.33602 1.20197 4.77602 1.20197H9.24802C9.66403 1.20197 10.048 1.48183 10.048 1.80966V3.00106C10.0473 3.05515 10.054 3.10896 10.0678 3.16101H3.95429ZM5.57571 10.997C5.41731 10.995 5.26597 10.9311 5.15395 10.8191C5.04193 10.7071 4.97808 10.5558 4.97601 10.3973V6.77517C4.97601 6.61612 5.0392 6.46359 5.15166 6.35112C5.26413 6.23866 5.41666 6.17548 5.57571 6.17548C5.73476 6.17548 5.8873 6.23866 5.99976 6.35112C6.11223 6.46359 6.17541 6.61612 6.17541 6.77517V10.3894C6.17647 10.4688 6.16174 10.5476 6.13208 10.6213C6.10241 10.695 6.05841 10.762 6.00261 10.8186C5.94682 10.8751 5.88035 10.92 5.80707 10.9506C5.73378 10.9813 5.65514 10.9971 5.57571 10.997ZM7.99968 10.8214C8.11215 10.9339 8.26468 10.997 8.42373 10.997C8.58351 10.9949 8.73604 10.93 8.84828 10.8163C8.96052 10.7025 9.02345 10.5491 9.02343 10.3894V6.77517C9.02343 6.61612 8.96025 6.46359 8.84778 6.35112C8.73532 6.23866 8.58278 6.17548 8.42373 6.17548C8.26468 6.17548 8.11215 6.23866 7.99968 6.35112C7.88722 6.46359 7.82404 6.61612 7.82404 6.77517V10.3973C7.82404 10.5564 7.88722 10.7089 7.99968 10.8214Z\",\n fill: \"currentColor\"\n}, null, -1);\nvar _hoisted_2 = [_hoisted_1];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"svg\", mergeProps({\n width: \"14\",\n height: \"14\",\n viewBox: \"0 0 14 14\",\n fill: \"none\",\n xmlns: \"http://www.w3.org/2000/svg\"\n }, _ctx.pti()), _hoisted_2, 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseIcon from '@primevue/icons/baseicon';\nimport { openBlock, createElementBlock, mergeProps, createElementVNode } from 'vue';\n\nvar script = {\n name: 'SortAltIcon',\n \"extends\": BaseIcon\n};\n\nvar _hoisted_1 = /*#__PURE__*/createElementVNode(\"path\", {\n d: \"M5.64515 3.61291C5.47353 3.61291 5.30192 3.54968 5.16644 3.4142L3.38708 1.63484L1.60773 3.4142C1.34579 3.67613 0.912244 3.67613 0.650309 3.4142C0.388374 3.15226 0.388374 2.71871 0.650309 2.45678L2.90837 0.198712C3.17031 -0.0632236 3.60386 -0.0632236 3.86579 0.198712L6.12386 2.45678C6.38579 2.71871 6.38579 3.15226 6.12386 3.4142C5.98837 3.54968 5.81676 3.61291 5.64515 3.61291Z\",\n fill: \"currentColor\"\n}, null, -1);\nvar _hoisted_2 = /*#__PURE__*/createElementVNode(\"path\", {\n d: \"M3.38714 14C3.01681 14 2.70972 13.6929 2.70972 13.3226V0.677419C2.70972 0.307097 3.01681 0 3.38714 0C3.75746 0 4.06456 0.307097 4.06456 0.677419V13.3226C4.06456 13.6929 3.75746 14 3.38714 14Z\",\n fill: \"currentColor\"\n}, null, -1);\nvar _hoisted_3 = /*#__PURE__*/createElementVNode(\"path\", {\n d: \"M10.6129 14C10.4413 14 10.2697 13.9368 10.1342 13.8013L7.87611 11.5432C7.61418 11.2813 7.61418 10.8477 7.87611 10.5858C8.13805 10.3239 8.5716 10.3239 8.83353 10.5858L10.6129 12.3652L12.3922 10.5858C12.6542 10.3239 13.0877 10.3239 13.3497 10.5858C13.6116 10.8477 13.6116 11.2813 13.3497 11.5432L11.0916 13.8013C10.9561 13.9368 10.7845 14 10.6129 14Z\",\n fill: \"currentColor\"\n}, null, -1);\nvar _hoisted_4 = /*#__PURE__*/createElementVNode(\"path\", {\n d: \"M10.6129 14C10.2426 14 9.93552 13.6929 9.93552 13.3226V0.677419C9.93552 0.307097 10.2426 0 10.6129 0C10.9833 0 11.2904 0.307097 11.2904 0.677419V13.3226C11.2904 13.6929 10.9832 14 10.6129 14Z\",\n fill: \"currentColor\"\n}, null, -1);\nvar _hoisted_5 = [_hoisted_1, _hoisted_2, _hoisted_3, _hoisted_4];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"svg\", mergeProps({\n width: \"14\",\n height: \"14\",\n viewBox: \"0 0 14 14\",\n fill: \"none\",\n xmlns: \"http://www.w3.org/2000/svg\"\n }, _ctx.pti()), _hoisted_5, 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseIcon from '@primevue/icons/baseicon';\nimport { openBlock, createElementBlock, mergeProps, createElementVNode } from 'vue';\n\nvar script = {\n name: 'SortAmountDownIcon',\n \"extends\": BaseIcon\n};\n\nvar _hoisted_1 = /*#__PURE__*/createElementVNode(\"path\", {\n d: \"M4.93953 10.5858L3.83759 11.6877V0.677419C3.83759 0.307097 3.53049 0 3.16017 0C2.78985 0 2.48275 0.307097 2.48275 0.677419V11.6877L1.38082 10.5858C1.11888 10.3239 0.685331 10.3239 0.423396 10.5858C0.16146 10.8477 0.16146 11.2813 0.423396 11.5432L2.68146 13.8013C2.74469 13.8645 2.81694 13.9097 2.89823 13.9458C2.97952 13.9819 3.06985 14 3.16017 14C3.25049 14 3.33178 13.9819 3.42211 13.9458C3.5034 13.9097 3.57565 13.8645 3.63888 13.8013L5.89694 11.5432C6.15888 11.2813 6.15888 10.8477 5.89694 10.5858C5.63501 10.3239 5.20146 10.3239 4.93953 10.5858ZM13.0957 0H7.22468C6.85436 0 6.54726 0.307097 6.54726 0.677419C6.54726 1.04774 6.85436 1.35484 7.22468 1.35484H13.0957C13.466 1.35484 13.7731 1.04774 13.7731 0.677419C13.7731 0.307097 13.466 0 13.0957 0ZM7.22468 5.41935H9.48275C9.85307 5.41935 10.1602 5.72645 10.1602 6.09677C10.1602 6.4671 9.85307 6.77419 9.48275 6.77419H7.22468C6.85436 6.77419 6.54726 6.4671 6.54726 6.09677C6.54726 5.72645 6.85436 5.41935 7.22468 5.41935ZM7.6763 8.12903H7.22468C6.85436 8.12903 6.54726 8.43613 6.54726 8.80645C6.54726 9.17677 6.85436 9.48387 7.22468 9.48387H7.6763C8.04662 9.48387 8.35372 9.17677 8.35372 8.80645C8.35372 8.43613 8.04662 8.12903 7.6763 8.12903ZM7.22468 2.70968H11.2892C11.6595 2.70968 11.9666 3.01677 11.9666 3.3871C11.9666 3.75742 11.6595 4.06452 11.2892 4.06452H7.22468C6.85436 4.06452 6.54726 3.75742 6.54726 3.3871C6.54726 3.01677 6.85436 2.70968 7.22468 2.70968Z\",\n fill: \"currentColor\"\n}, null, -1);\nvar _hoisted_2 = [_hoisted_1];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"svg\", mergeProps({\n width: \"14\",\n height: \"14\",\n viewBox: \"0 0 14 14\",\n fill: \"none\",\n xmlns: \"http://www.w3.org/2000/svg\"\n }, _ctx.pti()), _hoisted_2, 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseIcon from '@primevue/icons/baseicon';\nimport { openBlock, createElementBlock, mergeProps, createElementVNode } from 'vue';\n\nvar script = {\n name: 'SortAmountUpAltIcon',\n \"extends\": BaseIcon\n};\n\nvar _hoisted_1 = /*#__PURE__*/createElementVNode(\"path\", {\n d: \"M3.63435 0.19871C3.57113 0.135484 3.49887 0.0903226 3.41758 0.0541935C3.255 -0.0180645 3.06532 -0.0180645 2.90274 0.0541935C2.82145 0.0903226 2.74919 0.135484 2.68597 0.19871L0.427901 2.45677C0.165965 2.71871 0.165965 3.15226 0.427901 3.41419C0.689836 3.67613 1.12338 3.67613 1.38532 3.41419L2.48726 2.31226V13.3226C2.48726 13.6929 2.79435 14 3.16467 14C3.535 14 3.84209 13.6929 3.84209 13.3226V2.31226L4.94403 3.41419C5.07951 3.54968 5.25113 3.6129 5.42274 3.6129C5.59435 3.6129 5.76597 3.54968 5.90145 3.41419C6.16338 3.15226 6.16338 2.71871 5.90145 2.45677L3.64338 0.19871H3.63435ZM13.7685 13.3226C13.7685 12.9523 13.4615 12.6452 13.0911 12.6452H7.22016C6.84984 12.6452 6.54274 12.9523 6.54274 13.3226C6.54274 13.6929 6.84984 14 7.22016 14H13.0911C13.4615 14 13.7685 13.6929 13.7685 13.3226ZM7.22016 8.58064C6.84984 8.58064 6.54274 8.27355 6.54274 7.90323C6.54274 7.5329 6.84984 7.22581 7.22016 7.22581H9.47823C9.84855 7.22581 10.1556 7.5329 10.1556 7.90323C10.1556 8.27355 9.84855 8.58064 9.47823 8.58064H7.22016ZM7.22016 5.87097H7.67177C8.0421 5.87097 8.34919 5.56387 8.34919 5.19355C8.34919 4.82323 8.0421 4.51613 7.67177 4.51613H7.22016C6.84984 4.51613 6.54274 4.82323 6.54274 5.19355C6.54274 5.56387 6.84984 5.87097 7.22016 5.87097ZM11.2847 11.2903H7.22016C6.84984 11.2903 6.54274 10.9832 6.54274 10.6129C6.54274 10.2426 6.84984 9.93548 7.22016 9.93548H11.2847C11.655 9.93548 11.9621 10.2426 11.9621 10.6129C11.9621 10.9832 11.655 11.2903 11.2847 11.2903Z\",\n fill: \"currentColor\"\n}, null, -1);\nvar _hoisted_2 = [_hoisted_1];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"svg\", mergeProps({\n width: \"14\",\n height: \"14\",\n viewBox: \"0 0 14 14\",\n fill: \"none\",\n xmlns: \"http://www.w3.org/2000/svg\"\n }, _ctx.pti()), _hoisted_2, 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import { FilterOperator, FilterService, FilterMatchMode } from '@primevue/core/api';\nimport { getVNodeProp, UniqueComponentId, HelperSet, ConnectedOverlayScrollHandler } from '@primevue/core/utils';\nimport { getFirstFocusableElement, invokeElementMethod, getAttribute, getNextElementSibling, getOuterWidth, getPreviousElementSibling, getOuterHeight, focus, addStyle, absolutePosition, isTouchDevice, getIndex, isClickable, clearSelection, findSingle, find, exportCSV, getOffset, getHiddenElementOuterWidth, getHiddenElementOuterHeight, getWindowScrollTop, removeClass, addClass, setAttribute } from '@primeuix/utils/dom';\nimport { resolveFieldData, equals, isNotEmpty, localeComparator, sort, findIndexInList, reorderArray, isEmpty } from '@primeuix/utils/object';\nimport ArrowDownIcon from '@primevue/icons/arrowdown';\nimport ArrowUpIcon from '@primevue/icons/arrowup';\nimport SpinnerIcon from '@primevue/icons/spinner';\nimport Paginator from 'primevue/paginator';\nimport VirtualScroller from 'primevue/virtualscroller';\nimport BaseComponent from '@primevue/core/basecomponent';\nimport DataTableStyle from 'primevue/datatable/style';\nimport ChevronDownIcon from '@primevue/icons/chevrondown';\nimport ChevronRightIcon from '@primevue/icons/chevronright';\nimport { mergeProps, resolveComponent, openBlock, createBlock, withCtx, resolveDynamicComponent, normalizeClass, createCommentVNode, resolveDirective, createElementBlock, Fragment, withDirectives, createTextVNode, toDisplayString, createElementVNode, withModifiers, renderList, createVNode, Transition, withKeys, normalizeProps, renderSlot, createSlots } from 'vue';\nimport BarsIcon from '@primevue/icons/bars';\nimport CheckIcon from '@primevue/icons/check';\nimport PencilIcon from '@primevue/icons/pencil';\nimport TimesIcon from '@primevue/icons/times';\nimport Button from 'primevue/button';\nimport OverlayEventBus from 'primevue/overlayeventbus';\nimport Ripple from 'primevue/ripple';\nimport Checkbox from 'primevue/checkbox';\nimport RadioButton from 'primevue/radiobutton';\nimport { ZIndex } from '@primeuix/utils/zindex';\nimport FilterIcon from '@primevue/icons/filter';\nimport FilterSlashIcon from '@primevue/icons/filterslash';\nimport PlusIcon from '@primevue/icons/plus';\nimport TrashIcon from '@primevue/icons/trash';\nimport FocusTrap from 'primevue/focustrap';\nimport Portal from 'primevue/portal';\nimport Select from 'primevue/select';\nimport SortAltIcon from '@primevue/icons/sortalt';\nimport SortAmountDownIcon from '@primevue/icons/sortamountdown';\nimport SortAmountUpAltIcon from '@primevue/icons/sortamountupalt';\nimport Badge from 'primevue/badge';\n\nvar script$c = {\n name: 'BaseDataTable',\n \"extends\": BaseComponent,\n props: {\n value: {\n type: Array,\n \"default\": null\n },\n dataKey: {\n type: [String, Function],\n \"default\": null\n },\n rows: {\n type: Number,\n \"default\": 0\n },\n first: {\n type: Number,\n \"default\": 0\n },\n totalRecords: {\n type: Number,\n \"default\": 0\n },\n paginator: {\n type: Boolean,\n \"default\": false\n },\n paginatorPosition: {\n type: String,\n \"default\": 'bottom'\n },\n alwaysShowPaginator: {\n type: Boolean,\n \"default\": true\n },\n paginatorTemplate: {\n type: [Object, String],\n \"default\": 'FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink RowsPerPageDropdown'\n },\n pageLinkSize: {\n type: Number,\n \"default\": 5\n },\n rowsPerPageOptions: {\n type: Array,\n \"default\": null\n },\n currentPageReportTemplate: {\n type: String,\n \"default\": '({currentPage} of {totalPages})'\n },\n lazy: {\n type: Boolean,\n \"default\": false\n },\n loading: {\n type: Boolean,\n \"default\": false\n },\n loadingIcon: {\n type: String,\n \"default\": undefined\n },\n sortField: {\n type: [String, Function],\n \"default\": null\n },\n sortOrder: {\n type: Number,\n \"default\": null\n },\n defaultSortOrder: {\n type: Number,\n \"default\": 1\n },\n nullSortOrder: {\n type: Number,\n \"default\": 1\n },\n multiSortMeta: {\n type: Array,\n \"default\": null\n },\n sortMode: {\n type: String,\n \"default\": 'single'\n },\n removableSort: {\n type: Boolean,\n \"default\": false\n },\n filters: {\n type: Object,\n \"default\": null\n },\n filterDisplay: {\n type: String,\n \"default\": null\n },\n globalFilterFields: {\n type: Array,\n \"default\": null\n },\n filterLocale: {\n type: String,\n \"default\": undefined\n },\n selection: {\n type: [Array, Object],\n \"default\": null\n },\n selectionMode: {\n type: String,\n \"default\": null\n },\n compareSelectionBy: {\n type: String,\n \"default\": 'deepEquals'\n },\n metaKeySelection: {\n type: Boolean,\n \"default\": false\n },\n contextMenu: {\n type: Boolean,\n \"default\": false\n },\n contextMenuSelection: {\n type: Object,\n \"default\": null\n },\n selectAll: {\n type: Boolean,\n \"default\": null\n },\n rowHover: {\n type: Boolean,\n \"default\": false\n },\n csvSeparator: {\n type: String,\n \"default\": ','\n },\n exportFilename: {\n type: String,\n \"default\": 'download'\n },\n exportFunction: {\n type: Function,\n \"default\": null\n },\n resizableColumns: {\n type: Boolean,\n \"default\": false\n },\n columnResizeMode: {\n type: String,\n \"default\": 'fit'\n },\n reorderableColumns: {\n type: Boolean,\n \"default\": false\n },\n expandedRows: {\n type: [Array, Object],\n \"default\": null\n },\n expandedRowIcon: {\n type: String,\n \"default\": undefined\n },\n collapsedRowIcon: {\n type: String,\n \"default\": undefined\n },\n rowGroupMode: {\n type: String,\n \"default\": null\n },\n groupRowsBy: {\n type: [Array, String, Function],\n \"default\": null\n },\n expandableRowGroups: {\n type: Boolean,\n \"default\": false\n },\n expandedRowGroups: {\n type: Array,\n \"default\": null\n },\n stateStorage: {\n type: String,\n \"default\": 'session'\n },\n stateKey: {\n type: String,\n \"default\": null\n },\n editMode: {\n type: String,\n \"default\": null\n },\n editingRows: {\n type: Array,\n \"default\": null\n },\n rowClass: {\n type: Function,\n \"default\": null\n },\n rowStyle: {\n type: Function,\n \"default\": null\n },\n scrollable: {\n type: Boolean,\n \"default\": false\n },\n virtualScrollerOptions: {\n type: Object,\n \"default\": null\n },\n scrollHeight: {\n type: String,\n \"default\": null\n },\n frozenValue: {\n type: Array,\n \"default\": null\n },\n breakpoint: {\n type: String,\n \"default\": '960px'\n },\n showGridlines: {\n type: Boolean,\n \"default\": false\n },\n stripedRows: {\n type: Boolean,\n \"default\": false\n },\n highlightOnSelect: {\n type: Boolean,\n \"default\": false\n },\n size: {\n type: String,\n \"default\": null\n },\n tableStyle: {\n type: null,\n \"default\": null\n },\n tableClass: {\n type: [String, Object],\n \"default\": null\n },\n tableProps: {\n type: Object,\n \"default\": null\n },\n filterInputProps: {\n type: null,\n \"default\": null\n },\n filterButtonProps: {\n type: Object,\n \"default\": function _default() {\n return {\n filter: {\n severity: 'secondary',\n text: true,\n rounded: true\n },\n inline: {\n clear: {\n severity: 'secondary',\n text: true,\n rounded: true\n }\n },\n popover: {\n addRule: {\n severity: 'info',\n text: true,\n size: 'small'\n },\n removeRule: {\n severity: 'danger',\n text: true,\n size: 'small'\n },\n apply: {\n size: 'small'\n },\n clear: {\n outlined: true,\n size: 'small'\n }\n }\n };\n }\n },\n editButtonProps: {\n type: Object,\n \"default\": function _default() {\n return {\n init: {\n severity: 'secondary',\n text: true,\n rounded: true\n },\n save: {\n severity: 'secondary',\n text: true,\n rounded: true\n },\n cancel: {\n severity: 'secondary',\n text: true,\n rounded: true\n }\n };\n }\n }\n },\n style: DataTableStyle,\n provide: function provide() {\n return {\n $pcDataTable: this,\n $parentInstance: this\n };\n }\n};\n\nvar script$b = {\n name: 'RowCheckbox',\n hostName: 'DataTable',\n \"extends\": BaseComponent,\n emits: ['change'],\n props: {\n value: null,\n checked: null,\n column: null,\n rowCheckboxIconTemplate: {\n type: Function,\n \"default\": null\n },\n index: {\n type: Number,\n \"default\": null\n }\n },\n methods: {\n getColumnPT: function getColumnPT(key) {\n var columnMetaData = {\n props: this.column.props,\n parent: {\n instance: this,\n props: this.$props,\n state: this.$data\n },\n context: {\n index: this.index,\n checked: this.checked,\n disabled: this.$attrs.disabled\n }\n };\n return mergeProps(this.ptm(\"column.\".concat(key), {\n column: columnMetaData\n }), this.ptm(\"column.\".concat(key), columnMetaData), this.ptmo(this.getColumnProp(), key, columnMetaData));\n },\n getColumnProp: function getColumnProp() {\n return this.column.props && this.column.props.pt ? this.column.props.pt : undefined; //@todo:\n },\n onChange: function onChange(event) {\n if (!this.$attrs.disabled) {\n this.$emit('change', {\n originalEvent: event,\n data: this.value\n });\n }\n }\n },\n computed: {\n checkboxAriaLabel: function checkboxAriaLabel() {\n return this.$primevue.config.locale.aria ? this.checked ? this.$primevue.config.locale.aria.selectRow : this.$primevue.config.locale.aria.unselectRow : undefined;\n }\n },\n components: {\n CheckIcon: CheckIcon,\n Checkbox: Checkbox\n }\n};\n\nfunction render$b(_ctx, _cache, $props, $setup, $data, $options) {\n var _component_CheckIcon = resolveComponent(\"CheckIcon\");\n var _component_Checkbox = resolveComponent(\"Checkbox\");\n return openBlock(), createBlock(_component_Checkbox, {\n modelValue: $props.checked,\n binary: true,\n disabled: _ctx.$attrs.disabled,\n \"aria-label\": $options.checkboxAriaLabel,\n onChange: $options.onChange,\n unstyled: _ctx.unstyled,\n pt: $options.getColumnPT('pcRowCheckbox')\n }, {\n icon: withCtx(function (slotProps) {\n return [$props.rowCheckboxIconTemplate ? (openBlock(), createBlock(resolveDynamicComponent($props.rowCheckboxIconTemplate), {\n key: 0,\n checked: slotProps.checked,\n \"class\": normalizeClass(slotProps[\"class\"])\n }, null, 8, [\"checked\", \"class\"])) : !$props.rowCheckboxIconTemplate && slotProps.checked ? (openBlock(), createBlock(_component_CheckIcon, mergeProps({\n key: 1,\n \"class\": slotProps[\"class\"]\n }, $options.getColumnPT('pcRowCheckbox.icon')), null, 16, [\"class\"])) : createCommentVNode(\"\", true)];\n }),\n _: 1\n }, 8, [\"modelValue\", \"disabled\", \"aria-label\", \"onChange\", \"unstyled\", \"pt\"]);\n}\n\nscript$b.render = render$b;\n\nvar script$a = {\n name: 'RowRadioButton',\n hostName: 'DataTable',\n \"extends\": BaseComponent,\n emits: ['change'],\n props: {\n value: null,\n checked: null,\n name: null,\n column: null,\n index: {\n type: Number,\n \"default\": null\n }\n },\n methods: {\n getColumnPT: function getColumnPT(key) {\n var columnMetaData = {\n props: this.column.props,\n parent: {\n instance: this,\n props: this.$props,\n state: this.$data\n },\n context: {\n index: this.index,\n checked: this.checked,\n disabled: this.$attrs.disabled\n }\n };\n return mergeProps(this.ptm(\"column.\".concat(key), {\n column: columnMetaData\n }), this.ptm(\"column.\".concat(key), columnMetaData), this.ptmo(this.getColumnProp(), key, columnMetaData));\n },\n getColumnProp: function getColumnProp() {\n return this.column.props && this.column.props.pt ? this.column.props.pt : undefined; //@todo:\n },\n onChange: function onChange(event) {\n if (!this.$attrs.disabled) {\n this.$emit('change', {\n originalEvent: event,\n data: this.value\n });\n }\n }\n },\n components: {\n RadioButton: RadioButton\n }\n};\n\nfunction render$a(_ctx, _cache, $props, $setup, $data, $options) {\n var _component_RadioButton = resolveComponent(\"RadioButton\");\n return openBlock(), createBlock(_component_RadioButton, {\n modelValue: $props.checked,\n binary: true,\n disabled: _ctx.$attrs.disabled,\n name: $props.name,\n onChange: $options.onChange,\n unstyled: _ctx.unstyled,\n pt: $options.getColumnPT('pcRowRadiobutton')\n }, null, 8, [\"modelValue\", \"disabled\", \"name\", \"onChange\", \"unstyled\", \"pt\"]);\n}\n\nscript$a.render = render$a;\n\nvar script$9 = {\n name: 'BodyCell',\n hostName: 'DataTable',\n \"extends\": BaseComponent,\n emits: ['cell-edit-init', 'cell-edit-complete', 'cell-edit-cancel', 'row-edit-init', 'row-edit-save', 'row-edit-cancel', 'row-toggle', 'radio-change', 'checkbox-change', 'editing-meta-change'],\n props: {\n rowData: {\n type: Object,\n \"default\": null\n },\n column: {\n type: Object,\n \"default\": null\n },\n frozenRow: {\n type: Boolean,\n \"default\": false\n },\n rowIndex: {\n type: Number,\n \"default\": null\n },\n index: {\n type: Number,\n \"default\": null\n },\n isRowExpanded: {\n type: Boolean,\n \"default\": false\n },\n selected: {\n type: Boolean,\n \"default\": false\n },\n editing: {\n type: Boolean,\n \"default\": false\n },\n editingMeta: {\n type: Object,\n \"default\": null\n },\n editMode: {\n type: String,\n \"default\": null\n },\n virtualScrollerContentProps: {\n type: Object,\n \"default\": null\n },\n ariaControls: {\n type: String,\n \"default\": null\n },\n name: {\n type: String,\n \"default\": null\n },\n expandedRowIcon: {\n type: String,\n \"default\": null\n },\n collapsedRowIcon: {\n type: String,\n \"default\": null\n },\n editButtonProps: {\n type: Object,\n \"default\": null\n }\n },\n documentEditListener: null,\n selfClick: false,\n overlayEventListener: null,\n data: function data() {\n return {\n d_editing: this.editing,\n styleObject: {}\n };\n },\n watch: {\n editing: function editing(newValue) {\n this.d_editing = newValue;\n },\n '$data.d_editing': function $dataD_editing(newValue) {\n this.$emit('editing-meta-change', {\n data: this.rowData,\n field: this.field || \"field_\".concat(this.index),\n index: this.rowIndex,\n editing: newValue\n });\n }\n },\n mounted: function mounted() {\n if (this.columnProp('frozen')) {\n this.updateStickyPosition();\n }\n },\n updated: function updated() {\n var _this = this;\n if (this.columnProp('frozen')) {\n this.updateStickyPosition();\n }\n if (this.d_editing && (this.editMode === 'cell' || this.editMode === 'row' && this.columnProp('rowEditor'))) {\n setTimeout(function () {\n var focusableEl = getFirstFocusableElement(_this.$el);\n focusableEl && focusableEl.focus();\n }, 1);\n }\n },\n beforeUnmount: function beforeUnmount() {\n if (this.overlayEventListener) {\n OverlayEventBus.off('overlay-click', this.overlayEventListener);\n this.overlayEventListener = null;\n }\n },\n methods: {\n columnProp: function columnProp(prop) {\n return getVNodeProp(this.column, prop);\n },\n getColumnPT: function getColumnPT(key) {\n var _this$$parentInstance, _this$$parentInstance2;\n var columnMetaData = {\n props: this.column.props,\n parent: {\n instance: this,\n props: this.$props,\n state: this.$data\n },\n context: {\n index: this.index,\n size: (_this$$parentInstance = this.$parentInstance) === null || _this$$parentInstance === void 0 || (_this$$parentInstance = _this$$parentInstance.$parentInstance) === null || _this$$parentInstance === void 0 ? void 0 : _this$$parentInstance.size,\n showGridlines: (_this$$parentInstance2 = this.$parentInstance) === null || _this$$parentInstance2 === void 0 || (_this$$parentInstance2 = _this$$parentInstance2.$parentInstance) === null || _this$$parentInstance2 === void 0 ? void 0 : _this$$parentInstance2.showGridlines\n }\n };\n return mergeProps(this.ptm(\"column.\".concat(key), {\n column: columnMetaData\n }), this.ptm(\"column.\".concat(key), columnMetaData), this.ptmo(this.getColumnProp(), key, columnMetaData));\n },\n getColumnProp: function getColumnProp() {\n return this.column.props && this.column.props.pt ? this.column.props.pt : undefined;\n },\n resolveFieldData: function resolveFieldData$1() {\n return resolveFieldData(this.rowData, this.field);\n },\n toggleRow: function toggleRow(event) {\n this.$emit('row-toggle', {\n originalEvent: event,\n data: this.rowData\n });\n },\n toggleRowWithRadio: function toggleRowWithRadio(event, index) {\n this.$emit('radio-change', {\n originalEvent: event.originalEvent,\n index: index,\n data: event.data\n });\n },\n toggleRowWithCheckbox: function toggleRowWithCheckbox(event, index) {\n this.$emit('checkbox-change', {\n originalEvent: event.originalEvent,\n index: index,\n data: event.data\n });\n },\n isEditable: function isEditable() {\n return this.column.children && this.column.children.editor != null;\n },\n bindDocumentEditListener: function bindDocumentEditListener() {\n var _this2 = this;\n if (!this.documentEditListener) {\n this.documentEditListener = function (event) {\n if (!_this2.selfClick) {\n _this2.completeEdit(event, 'outside');\n }\n _this2.selfClick = false;\n };\n document.addEventListener('click', this.documentEditListener);\n }\n },\n unbindDocumentEditListener: function unbindDocumentEditListener() {\n if (this.documentEditListener) {\n document.removeEventListener('click', this.documentEditListener);\n this.documentEditListener = null;\n this.selfClick = false;\n }\n },\n switchCellToViewMode: function switchCellToViewMode() {\n this.d_editing = false;\n this.unbindDocumentEditListener();\n OverlayEventBus.off('overlay-click', this.overlayEventListener);\n this.overlayEventListener = null;\n },\n onClick: function onClick(event) {\n var _this3 = this;\n if (this.editMode === 'cell' && this.isEditable()) {\n this.selfClick = true;\n if (!this.d_editing) {\n this.d_editing = true;\n this.bindDocumentEditListener();\n this.$emit('cell-edit-init', {\n originalEvent: event,\n data: this.rowData,\n field: this.field,\n index: this.rowIndex\n });\n this.overlayEventListener = function (e) {\n if (_this3.$el && _this3.$el.contains(e.target)) {\n _this3.selfClick = true;\n }\n };\n OverlayEventBus.on('overlay-click', this.overlayEventListener);\n }\n }\n },\n completeEdit: function completeEdit(event, type) {\n var completeEvent = {\n originalEvent: event,\n data: this.rowData,\n newData: this.editingRowData,\n value: this.rowData[this.field],\n newValue: this.editingRowData[this.field],\n field: this.field,\n index: this.rowIndex,\n type: type,\n defaultPrevented: false,\n preventDefault: function preventDefault() {\n this.defaultPrevented = true;\n }\n };\n this.$emit('cell-edit-complete', completeEvent);\n if (!completeEvent.defaultPrevented) {\n this.switchCellToViewMode();\n }\n },\n onKeyDown: function onKeyDown(event) {\n if (this.editMode === 'cell') {\n switch (event.code) {\n case 'Enter':\n case 'NumpadEnter':\n this.completeEdit(event, 'enter');\n break;\n case 'Escape':\n this.switchCellToViewMode();\n this.$emit('cell-edit-cancel', {\n originalEvent: event,\n data: this.rowData,\n field: this.field,\n index: this.rowIndex\n });\n break;\n case 'Tab':\n this.completeEdit(event, 'tab');\n if (event.shiftKey) this.moveToPreviousCell(event);else this.moveToNextCell(event);\n break;\n }\n }\n },\n moveToPreviousCell: function moveToPreviousCell(event) {\n var currentCell = this.findCell(event.target);\n var targetCell = this.findPreviousEditableColumn(currentCell);\n if (targetCell) {\n invokeElementMethod(targetCell, 'click');\n event.preventDefault();\n }\n },\n moveToNextCell: function moveToNextCell(event) {\n var currentCell = this.findCell(event.target);\n var targetCell = this.findNextEditableColumn(currentCell);\n if (targetCell) {\n invokeElementMethod(targetCell, 'click');\n event.preventDefault();\n }\n },\n findCell: function findCell(element) {\n if (element) {\n var cell = element;\n while (cell && !getAttribute(cell, 'data-p-cell-editing')) {\n cell = cell.parentElement;\n }\n return cell;\n } else {\n return null;\n }\n },\n findPreviousEditableColumn: function findPreviousEditableColumn(cell) {\n var prevCell = cell.previousElementSibling;\n if (!prevCell) {\n var previousRow = cell.parentElement.previousElementSibling;\n if (previousRow) {\n prevCell = previousRow.lastElementChild;\n }\n }\n if (prevCell) {\n if (getAttribute(prevCell, 'data-p-editable-column')) return prevCell;else return this.findPreviousEditableColumn(prevCell);\n } else {\n return null;\n }\n },\n findNextEditableColumn: function findNextEditableColumn(cell) {\n var nextCell = cell.nextElementSibling;\n if (!nextCell) {\n var nextRow = cell.parentElement.nextElementSibling;\n if (nextRow) {\n nextCell = nextRow.firstElementChild;\n }\n }\n if (nextCell) {\n if (getAttribute(nextCell, 'data-p-editable-column')) return nextCell;else return this.findNextEditableColumn(nextCell);\n } else {\n return null;\n }\n },\n onRowEditInit: function onRowEditInit(event) {\n this.$emit('row-edit-init', {\n originalEvent: event,\n data: this.rowData,\n newData: this.editingRowData,\n field: this.field,\n index: this.rowIndex\n });\n },\n onRowEditSave: function onRowEditSave(event) {\n this.$emit('row-edit-save', {\n originalEvent: event,\n data: this.rowData,\n newData: this.editingRowData,\n field: this.field,\n index: this.rowIndex\n });\n },\n onRowEditCancel: function onRowEditCancel(event) {\n this.$emit('row-edit-cancel', {\n originalEvent: event,\n data: this.rowData,\n newData: this.editingRowData,\n field: this.field,\n index: this.rowIndex\n });\n },\n editorInitCallback: function editorInitCallback(event) {\n this.$emit('row-edit-init', {\n originalEvent: event,\n data: this.rowData,\n newData: this.editingRowData,\n field: this.field,\n index: this.rowIndex\n });\n },\n editorSaveCallback: function editorSaveCallback(event) {\n if (this.editMode === 'row') {\n this.$emit('row-edit-save', {\n originalEvent: event,\n data: this.rowData,\n newData: this.editingRowData,\n field: this.field,\n index: this.rowIndex\n });\n } else {\n this.completeEdit(event, 'enter');\n }\n },\n editorCancelCallback: function editorCancelCallback(event) {\n if (this.editMode === 'row') {\n this.$emit('row-edit-cancel', {\n originalEvent: event,\n data: this.rowData,\n newData: this.editingRowData,\n field: this.field,\n index: this.rowIndex\n });\n } else {\n this.switchCellToViewMode();\n this.$emit('cell-edit-cancel', {\n originalEvent: event,\n data: this.rowData,\n field: this.field,\n index: this.rowIndex\n });\n }\n },\n updateStickyPosition: function updateStickyPosition() {\n if (this.columnProp('frozen')) {\n var align = this.columnProp('alignFrozen');\n if (align === 'right') {\n var right = 0;\n var next = getNextElementSibling(this.$el, '[data-p-frozen-column=\"true\"]');\n if (next) {\n right = getOuterWidth(next) + parseFloat(next.style.right || 0);\n }\n this.styleObject.right = right + 'px';\n } else {\n var left = 0;\n var prev = getPreviousElementSibling(this.$el, '[data-p-frozen-column=\"true\"]');\n if (prev) {\n left = getOuterWidth(prev) + parseFloat(prev.style.left || 0);\n }\n this.styleObject.left = left + 'px';\n }\n }\n },\n getVirtualScrollerProp: function getVirtualScrollerProp(option) {\n return this.virtualScrollerContentProps ? this.virtualScrollerContentProps[option] : null;\n }\n },\n computed: {\n editingRowData: function editingRowData() {\n return this.editingMeta[this.rowIndex] ? this.editingMeta[this.rowIndex].data : this.rowData;\n },\n field: function field() {\n return this.columnProp('field');\n },\n containerClass: function containerClass() {\n return [this.columnProp('bodyClass'), this.columnProp('class'), this.cx('bodyCell')];\n },\n containerStyle: function containerStyle() {\n var bodyStyle = this.columnProp('bodyStyle');\n var columnStyle = this.columnProp('style');\n return this.columnProp('frozen') ? [columnStyle, bodyStyle, this.styleObject] : [columnStyle, bodyStyle];\n },\n loading: function loading() {\n return this.getVirtualScrollerProp('loading');\n },\n loadingOptions: function loadingOptions() {\n var getLoaderOptions = this.getVirtualScrollerProp('getLoaderOptions');\n return getLoaderOptions && getLoaderOptions(this.rowIndex, {\n cellIndex: this.index,\n cellFirst: this.index === 0,\n cellLast: this.index === this.getVirtualScrollerProp('columns').length - 1,\n cellEven: this.index % 2 === 0,\n cellOdd: this.index % 2 !== 0,\n column: this.column,\n field: this.field\n });\n },\n expandButtonAriaLabel: function expandButtonAriaLabel() {\n return this.$primevue.config.locale.aria ? this.isRowExpanded ? this.$primevue.config.locale.aria.expandRow : this.$primevue.config.locale.aria.collapseRow : undefined;\n },\n initButtonAriaLabel: function initButtonAriaLabel() {\n return this.$primevue.config.locale.aria ? this.$primevue.config.locale.aria.editRow : undefined;\n },\n saveButtonAriaLabel: function saveButtonAriaLabel() {\n return this.$primevue.config.locale.aria ? this.$primevue.config.locale.aria.saveEdit : undefined;\n },\n cancelButtonAriaLabel: function cancelButtonAriaLabel() {\n return this.$primevue.config.locale.aria ? this.$primevue.config.locale.aria.cancelEdit : undefined;\n }\n },\n components: {\n DTRadioButton: script$a,\n DTCheckbox: script$b,\n Button: Button,\n ChevronDownIcon: ChevronDownIcon,\n ChevronRightIcon: ChevronRightIcon,\n BarsIcon: BarsIcon,\n PencilIcon: PencilIcon,\n CheckIcon: CheckIcon,\n TimesIcon: TimesIcon\n },\n directives: {\n ripple: Ripple\n }\n};\n\nfunction _typeof$a(o) { \"@babel/helpers - typeof\"; return _typeof$a = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof$a(o); }\nfunction ownKeys$a(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread$a(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$a(Object(t), !0).forEach(function (r) { _defineProperty$a(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$a(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty$a(e, r, t) { return (r = _toPropertyKey$a(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }\nfunction _toPropertyKey$a(t) { var i = _toPrimitive$a(t, \"string\"); return \"symbol\" == _typeof$a(i) ? i : i + \"\"; }\nfunction _toPrimitive$a(t, r) { if (\"object\" != _typeof$a(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof$a(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nvar _hoisted_1$4 = [\"colspan\", \"rowspan\", \"data-p-selection-column\", \"data-p-editable-column\", \"data-p-cell-editing\", \"data-p-frozen-column\"];\nvar _hoisted_2$2 = [\"aria-expanded\", \"aria-controls\", \"aria-label\"];\nfunction render$9(_ctx, _cache, $props, $setup, $data, $options) {\n var _component_DTRadioButton = resolveComponent(\"DTRadioButton\");\n var _component_DTCheckbox = resolveComponent(\"DTCheckbox\");\n var _component_BarsIcon = resolveComponent(\"BarsIcon\");\n var _component_ChevronDownIcon = resolveComponent(\"ChevronDownIcon\");\n var _component_ChevronRightIcon = resolveComponent(\"ChevronRightIcon\");\n var _component_Button = resolveComponent(\"Button\");\n var _directive_ripple = resolveDirective(\"ripple\");\n return $options.loading ? (openBlock(), createElementBlock(\"td\", mergeProps({\n key: 0,\n style: $options.containerStyle,\n \"class\": $options.containerClass,\n role: \"cell\"\n }, _objectSpread$a(_objectSpread$a({}, $options.getColumnPT('root')), $options.getColumnPT('bodyCell'))), [(openBlock(), createBlock(resolveDynamicComponent($props.column.children.loading), {\n data: $props.rowData,\n column: $props.column,\n field: $options.field,\n index: $props.rowIndex,\n frozenRow: $props.frozenRow,\n loadingOptions: $options.loadingOptions\n }, null, 8, [\"data\", \"column\", \"field\", \"index\", \"frozenRow\", \"loadingOptions\"]))], 16)) : (openBlock(), createElementBlock(\"td\", mergeProps({\n key: 1,\n style: $options.containerStyle,\n \"class\": $options.containerClass,\n colspan: $options.columnProp('colspan'),\n rowspan: $options.columnProp('rowspan'),\n onClick: _cache[3] || (_cache[3] = function () {\n return $options.onClick && $options.onClick.apply($options, arguments);\n }),\n onKeydown: _cache[4] || (_cache[4] = function () {\n return $options.onKeyDown && $options.onKeyDown.apply($options, arguments);\n }),\n role: \"cell\"\n }, _objectSpread$a(_objectSpread$a({}, $options.getColumnPT('root')), $options.getColumnPT('bodyCell')), {\n \"data-p-selection-column\": $options.columnProp('selectionMode') != null,\n \"data-p-editable-column\": $options.isEditable(),\n \"data-p-cell-editing\": $data.d_editing,\n \"data-p-frozen-column\": $options.columnProp('frozen')\n }), [$props.column.children && $props.column.children.body && !$data.d_editing ? (openBlock(), createBlock(resolveDynamicComponent($props.column.children.body), {\n key: 0,\n data: $props.rowData,\n column: $props.column,\n field: $options.field,\n index: $props.rowIndex,\n frozenRow: $props.frozenRow,\n editorInitCallback: $options.editorInitCallback,\n rowTogglerCallback: $options.toggleRow\n }, null, 8, [\"data\", \"column\", \"field\", \"index\", \"frozenRow\", \"editorInitCallback\", \"rowTogglerCallback\"])) : $props.column.children && $props.column.children.editor && $data.d_editing ? (openBlock(), createBlock(resolveDynamicComponent($props.column.children.editor), {\n key: 1,\n data: $options.editingRowData,\n column: $props.column,\n field: $options.field,\n index: $props.rowIndex,\n frozenRow: $props.frozenRow,\n editorSaveCallback: $options.editorSaveCallback,\n editorCancelCallback: $options.editorCancelCallback\n }, null, 8, [\"data\", \"column\", \"field\", \"index\", \"frozenRow\", \"editorSaveCallback\", \"editorCancelCallback\"])) : $props.column.children && $props.column.children.body && !$props.column.children.editor && $data.d_editing ? (openBlock(), createBlock(resolveDynamicComponent($props.column.children.body), {\n key: 2,\n data: $options.editingRowData,\n column: $props.column,\n field: $options.field,\n index: $props.rowIndex,\n frozenRow: $props.frozenRow\n }, null, 8, [\"data\", \"column\", \"field\", \"index\", \"frozenRow\"])) : $options.columnProp('selectionMode') ? (openBlock(), createElementBlock(Fragment, {\n key: 3\n }, [$options.columnProp('selectionMode') === 'single' ? (openBlock(), createBlock(_component_DTRadioButton, {\n key: 0,\n value: $props.rowData,\n name: $props.name,\n checked: $props.selected,\n onChange: _cache[0] || (_cache[0] = function ($event) {\n return $options.toggleRowWithRadio($event, $props.rowIndex);\n }),\n column: $props.column,\n index: $props.index,\n unstyled: _ctx.unstyled,\n pt: _ctx.pt\n }, null, 8, [\"value\", \"name\", \"checked\", \"column\", \"index\", \"unstyled\", \"pt\"])) : $options.columnProp('selectionMode') === 'multiple' ? (openBlock(), createBlock(_component_DTCheckbox, {\n key: 1,\n value: $props.rowData,\n checked: $props.selected,\n rowCheckboxIconTemplate: $props.column.children && $props.column.children.rowcheckboxicon,\n \"aria-selected\": $props.selected ? true : undefined,\n onChange: _cache[1] || (_cache[1] = function ($event) {\n return $options.toggleRowWithCheckbox($event, $props.rowIndex);\n }),\n column: $props.column,\n index: $props.index,\n unstyled: _ctx.unstyled,\n pt: _ctx.pt\n }, null, 8, [\"value\", \"checked\", \"rowCheckboxIconTemplate\", \"aria-selected\", \"column\", \"index\", \"unstyled\", \"pt\"])) : createCommentVNode(\"\", true)], 64)) : $options.columnProp('rowReorder') ? (openBlock(), createElementBlock(Fragment, {\n key: 4\n }, [$props.column.children && $props.column.children.rowreordericon ? (openBlock(), createBlock(resolveDynamicComponent($props.column.children.rowreordericon), {\n key: 0,\n \"class\": normalizeClass(_ctx.cx('reorderableRowHandle'))\n }, null, 8, [\"class\"])) : $options.columnProp('rowReorderIcon') ? (openBlock(), createElementBlock(\"i\", mergeProps({\n key: 1,\n \"class\": [_ctx.cx('reorderableRowHandle'), $options.columnProp('rowReorderIcon')]\n }, $options.getColumnPT('reorderableRowHandle')), null, 16)) : (openBlock(), createBlock(_component_BarsIcon, mergeProps({\n key: 2,\n \"class\": _ctx.cx('reorderableRowHandle')\n }, $options.getColumnPT('reorderableRowHandle')), null, 16, [\"class\"]))], 64)) : $options.columnProp('expander') ? withDirectives((openBlock(), createElementBlock(\"button\", mergeProps({\n key: 5,\n \"class\": _ctx.cx('rowToggleButton'),\n type: \"button\",\n \"aria-expanded\": $props.isRowExpanded,\n \"aria-controls\": $props.ariaControls,\n \"aria-label\": $options.expandButtonAriaLabel,\n onClick: _cache[2] || (_cache[2] = function () {\n return $options.toggleRow && $options.toggleRow.apply($options, arguments);\n })\n }, $options.getColumnPT('rowToggleButton'), {\n \"data-pc-group-section\": \"rowactionbutton\"\n }), [$props.column.children && $props.column.children.rowtogglericon ? (openBlock(), createBlock(resolveDynamicComponent($props.column.children.rowtogglericon), {\n key: 0,\n \"class\": normalizeClass(_ctx.cx('rowToggleIcon')),\n rowExpanded: $props.isRowExpanded\n }, null, 8, [\"class\", \"rowExpanded\"])) : (openBlock(), createElementBlock(Fragment, {\n key: 1\n }, [$props.isRowExpanded && $props.expandedRowIcon ? (openBlock(), createElementBlock(\"span\", {\n key: 0,\n \"class\": normalizeClass([_ctx.cx('rowToggleIcon'), $props.expandedRowIcon])\n }, null, 2)) : $props.isRowExpanded && !$props.expandedRowIcon ? (openBlock(), createBlock(_component_ChevronDownIcon, mergeProps({\n key: 1,\n \"class\": _ctx.cx('rowToggleIcon')\n }, $options.getColumnPT('rowToggleIcon')), null, 16, [\"class\"])) : !$props.isRowExpanded && $props.collapsedRowIcon ? (openBlock(), createElementBlock(\"span\", {\n key: 2,\n \"class\": normalizeClass([_ctx.cx('rowToggleIcon'), $props.collapsedRowIcon])\n }, null, 2)) : !$props.isRowExpanded && !$props.collapsedRowIcon ? (openBlock(), createBlock(_component_ChevronRightIcon, mergeProps({\n key: 3,\n \"class\": _ctx.cx('rowToggleIcon')\n }, $options.getColumnPT('rowToggleIcon')), null, 16, [\"class\"])) : createCommentVNode(\"\", true)], 64))], 16, _hoisted_2$2)), [[_directive_ripple]]) : $props.editMode === 'row' && $options.columnProp('rowEditor') ? (openBlock(), createElementBlock(Fragment, {\n key: 6\n }, [!$data.d_editing ? (openBlock(), createBlock(_component_Button, mergeProps({\n key: 0,\n \"class\": _ctx.cx('pcRowEditorInit'),\n \"aria-label\": $options.initButtonAriaLabel,\n unstyled: _ctx.unstyled,\n onClick: $options.onRowEditInit\n }, _objectSpread$a(_objectSpread$a({}, $options.getColumnPT('pcRowEditorInit')), $props.editButtonProps.init), {\n \"data-pc-group-section\": \"rowactionbutton\"\n }), {\n icon: withCtx(function (slotProps) {\n return [(openBlock(), createBlock(resolveDynamicComponent($props.column.children && $props.column.children.roweditoriniticon || 'PencilIcon'), mergeProps({\n \"class\": slotProps[\"class\"]\n }, $options.getColumnPT('pcRowEditorInit')['icon']), null, 16, [\"class\"]))];\n }),\n _: 1\n }, 16, [\"class\", \"aria-label\", \"unstyled\", \"onClick\"])) : createCommentVNode(\"\", true), $data.d_editing ? (openBlock(), createBlock(_component_Button, mergeProps({\n key: 1,\n \"class\": _ctx.cx('pcRowEditorSave'),\n \"aria-label\": $options.saveButtonAriaLabel,\n unstyled: _ctx.unstyled,\n onClick: $options.onRowEditSave\n }, _objectSpread$a(_objectSpread$a({}, $options.getColumnPT('pcRowEditorSave')), $props.editButtonProps.save), {\n \"data-pc-group-section\": \"rowactionbutton\"\n }), {\n icon: withCtx(function (slotProps) {\n return [(openBlock(), createBlock(resolveDynamicComponent($props.column.children && $props.column.children.roweditorsaveicon || 'CheckIcon'), mergeProps({\n \"class\": slotProps[\"class\"]\n }, $options.getColumnPT('pcRowEditorSave')['icon']), null, 16, [\"class\"]))];\n }),\n _: 1\n }, 16, [\"class\", \"aria-label\", \"unstyled\", \"onClick\"])) : createCommentVNode(\"\", true), $data.d_editing ? (openBlock(), createBlock(_component_Button, mergeProps({\n key: 2,\n \"class\": _ctx.cx('pcRowEditorCancel'),\n \"aria-label\": $options.cancelButtonAriaLabel,\n unstyled: _ctx.unstyled,\n onClick: $options.onRowEditCancel\n }, _objectSpread$a(_objectSpread$a({}, $options.getColumnPT('pcRowEditorCancel')), $props.editButtonProps.cancel), {\n \"data-pc-group-section\": \"rowactionbutton\"\n }), {\n icon: withCtx(function (slotProps) {\n return [(openBlock(), createBlock(resolveDynamicComponent($props.column.children && $props.column.children.roweditorcancelicon || 'TimesIcon'), mergeProps({\n \"class\": slotProps[\"class\"]\n }, $options.getColumnPT('pcRowEditorCancel')['icon']), null, 16, [\"class\"]))];\n }),\n _: 1\n }, 16, [\"class\", \"aria-label\", \"unstyled\", \"onClick\"])) : createCommentVNode(\"\", true)], 64)) : (openBlock(), createElementBlock(Fragment, {\n key: 7\n }, [createTextVNode(toDisplayString($options.resolveFieldData()), 1)], 64))], 16, _hoisted_1$4));\n}\n\nscript$9.render = render$9;\n\nfunction _typeof$9(o) { \"@babel/helpers - typeof\"; return _typeof$9 = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof$9(o); }\nfunction _createForOfIteratorHelper$2(r, e) { var t = \"undefined\" != typeof Symbol && r[Symbol.iterator] || r[\"@@iterator\"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray$2(r)) || e ) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError(\"Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t[\"return\"] || t[\"return\"](); } finally { if (u) throw o; } } }; }\nfunction _unsupportedIterableToArray$2(r, a) { if (r) { if (\"string\" == typeof r) return _arrayLikeToArray$2(r, a); var t = {}.toString.call(r).slice(8, -1); return \"Object\" === t && r.constructor && (t = r.constructor.name), \"Map\" === t || \"Set\" === t ? Array.from(r) : \"Arguments\" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray$2(r, a) : void 0; } }\nfunction _arrayLikeToArray$2(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }\nfunction ownKeys$9(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread$9(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$9(Object(t), !0).forEach(function (r) { _defineProperty$9(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$9(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty$9(e, r, t) { return (r = _toPropertyKey$9(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }\nfunction _toPropertyKey$9(t) { var i = _toPrimitive$9(t, \"string\"); return \"symbol\" == _typeof$9(i) ? i : i + \"\"; }\nfunction _toPrimitive$9(t, r) { if (\"object\" != _typeof$9(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof$9(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nvar script$8 = {\n name: 'BodyRow',\n hostName: 'DataTable',\n \"extends\": BaseComponent,\n emits: ['rowgroup-toggle', 'row-click', 'row-dblclick', 'row-rightclick', 'row-touchend', 'row-keydown', 'row-mousedown', 'row-dragstart', 'row-dragover', 'row-dragleave', 'row-dragend', 'row-drop', 'row-toggle', 'radio-change', 'checkbox-change', 'cell-edit-init', 'cell-edit-complete', 'cell-edit-cancel', 'row-edit-init', 'row-edit-save', 'row-edit-cancel', 'editing-meta-change'],\n props: {\n rowData: {\n type: Object,\n \"default\": null\n },\n index: {\n type: Number,\n \"default\": 0\n },\n value: {\n type: Array,\n \"default\": null\n },\n columns: {\n type: null,\n \"default\": null\n },\n frozenRow: {\n type: Boolean,\n \"default\": false\n },\n empty: {\n type: Boolean,\n \"default\": false\n },\n rowGroupMode: {\n type: String,\n \"default\": null\n },\n groupRowsBy: {\n type: [Array, String, Function],\n \"default\": null\n },\n expandableRowGroups: {\n type: Boolean,\n \"default\": false\n },\n expandedRowGroups: {\n type: Array,\n \"default\": null\n },\n first: {\n type: Number,\n \"default\": 0\n },\n dataKey: {\n type: [String, Function],\n \"default\": null\n },\n expandedRowIcon: {\n type: String,\n \"default\": null\n },\n collapsedRowIcon: {\n type: String,\n \"default\": null\n },\n expandedRows: {\n type: [Array, Object],\n \"default\": null\n },\n selection: {\n type: [Array, Object],\n \"default\": null\n },\n selectionKeys: {\n type: null,\n \"default\": null\n },\n selectionMode: {\n type: String,\n \"default\": null\n },\n contextMenu: {\n type: Boolean,\n \"default\": false\n },\n contextMenuSelection: {\n type: Object,\n \"default\": null\n },\n rowClass: {\n type: null,\n \"default\": null\n },\n rowStyle: {\n type: null,\n \"default\": null\n },\n rowGroupHeaderStyle: {\n type: null,\n \"default\": null\n },\n editMode: {\n type: String,\n \"default\": null\n },\n compareSelectionBy: {\n type: String,\n \"default\": 'deepEquals'\n },\n editingRows: {\n type: Array,\n \"default\": null\n },\n editingRowKeys: {\n type: null,\n \"default\": null\n },\n editingMeta: {\n type: Object,\n \"default\": null\n },\n templates: {\n type: null,\n \"default\": null\n },\n scrollable: {\n type: Boolean,\n \"default\": false\n },\n editButtonProps: {\n type: Object,\n \"default\": null\n },\n virtualScrollerContentProps: {\n type: Object,\n \"default\": null\n },\n isVirtualScrollerDisabled: {\n type: Boolean,\n \"default\": false\n },\n expandedRowId: {\n type: String,\n \"default\": null\n },\n nameAttributeSelector: {\n type: String,\n \"default\": null\n }\n },\n data: function data() {\n return {\n d_rowExpanded: false\n };\n },\n watch: {\n expandedRows: {\n deep: true,\n immediate: true,\n handler: function handler(newValue) {\n var _this = this;\n this.d_rowExpanded = this.dataKey ? (newValue === null || newValue === void 0 ? void 0 : newValue[resolveFieldData(this.rowData, this.dataKey)]) !== undefined : newValue === null || newValue === void 0 ? void 0 : newValue.some(function (d) {\n return _this.equals(_this.rowData, d);\n });\n }\n }\n },\n methods: {\n columnProp: function columnProp(col, prop) {\n return getVNodeProp(col, prop);\n },\n //@todo - update this method\n getColumnPT: function getColumnPT(key) {\n var columnMetaData = {\n parent: {\n instance: this,\n props: this.$props,\n state: this.$data\n }\n };\n return mergeProps(this.ptm(\"column.\".concat(key), {\n column: columnMetaData\n }), this.ptm(\"column.\".concat(key), columnMetaData), this.ptmo(this.columnProp({}, 'pt'), key, columnMetaData));\n },\n //@todo - update this method\n getBodyRowPTOptions: function getBodyRowPTOptions(key) {\n var _this$$parentInstance;\n var datatable = (_this$$parentInstance = this.$parentInstance) === null || _this$$parentInstance === void 0 ? void 0 : _this$$parentInstance.$parentInstance;\n return this.ptm(key, {\n context: {\n index: this.rowIndex,\n selectable: (datatable === null || datatable === void 0 ? void 0 : datatable.rowHover) || (datatable === null || datatable === void 0 ? void 0 : datatable.selectionMode),\n selected: this.isSelected,\n stripedRows: (datatable === null || datatable === void 0 ? void 0 : datatable.stripedRows) || false\n }\n });\n },\n shouldRenderBodyCell: function shouldRenderBodyCell(column) {\n var isHidden = this.columnProp(column, 'hidden');\n if (this.rowGroupMode && !isHidden) {\n var field = this.columnProp(column, 'field');\n if (this.rowGroupMode === 'subheader') {\n return this.groupRowsBy !== field;\n } else if (this.rowGroupMode === 'rowspan') {\n if (this.isGrouped(column)) {\n var prevRowData = this.value[this.rowIndex - 1];\n if (prevRowData) {\n var currentRowFieldData = resolveFieldData(this.value[this.rowIndex], field);\n var previousRowFieldData = resolveFieldData(prevRowData, field);\n return currentRowFieldData !== previousRowFieldData;\n } else {\n return true;\n }\n } else {\n return true;\n }\n }\n } else {\n return !isHidden;\n }\n },\n calculateRowGroupSize: function calculateRowGroupSize(column) {\n if (this.isGrouped(column)) {\n var index = this.rowIndex;\n var field = this.columnProp(column, 'field');\n var currentRowFieldData = resolveFieldData(this.value[index], field);\n var nextRowFieldData = currentRowFieldData;\n var groupRowSpan = 0;\n while (currentRowFieldData === nextRowFieldData) {\n groupRowSpan++;\n var nextRowData = this.value[++index];\n if (nextRowData) {\n nextRowFieldData = resolveFieldData(nextRowData, field);\n } else {\n break;\n }\n }\n return groupRowSpan === 1 ? null : groupRowSpan;\n } else {\n return null;\n }\n },\n isGrouped: function isGrouped(column) {\n var field = this.columnProp(column, 'field');\n if (this.groupRowsBy && field) {\n if (Array.isArray(this.groupRowsBy)) return this.groupRowsBy.indexOf(field) > -1;else return this.groupRowsBy === field;\n } else {\n return false;\n }\n },\n findIndexInSelection: function findIndexInSelection(data) {\n return this.findIndex(data, this.selection);\n },\n findIndex: function findIndex(data, collection) {\n var index = -1;\n if (collection && collection.length) {\n for (var i = 0; i < collection.length; i++) {\n if (this.equals(data, collection[i])) {\n index = i;\n break;\n }\n }\n }\n return index;\n },\n equals: function equals$1(data1, data2) {\n return this.compareSelectionBy === 'equals' ? data1 === data2 : equals(data1, data2, this.dataKey);\n },\n onRowGroupToggle: function onRowGroupToggle(event) {\n this.$emit('rowgroup-toggle', {\n originalEvent: event,\n data: this.rowData\n });\n },\n onRowClick: function onRowClick(event) {\n this.$emit('row-click', {\n originalEvent: event,\n data: this.rowData,\n index: this.rowIndex\n });\n },\n onRowDblClick: function onRowDblClick(event) {\n this.$emit('row-dblclick', {\n originalEvent: event,\n data: this.rowData,\n index: this.rowIndex\n });\n },\n onRowRightClick: function onRowRightClick(event) {\n this.$emit('row-rightclick', {\n originalEvent: event,\n data: this.rowData,\n index: this.rowIndex\n });\n },\n onRowTouchEnd: function onRowTouchEnd(event) {\n this.$emit('row-touchend', event);\n },\n onRowKeyDown: function onRowKeyDown(event) {\n this.$emit('row-keydown', {\n originalEvent: event,\n data: this.rowData,\n index: this.rowIndex\n });\n },\n onRowMouseDown: function onRowMouseDown(event) {\n this.$emit('row-mousedown', event);\n },\n onRowDragStart: function onRowDragStart(event) {\n this.$emit('row-dragstart', {\n originalEvent: event,\n index: this.rowIndex\n });\n },\n onRowDragOver: function onRowDragOver(event) {\n this.$emit('row-dragover', {\n originalEvent: event,\n index: this.rowIndex\n });\n },\n onRowDragLeave: function onRowDragLeave(event) {\n this.$emit('row-dragleave', event);\n },\n onRowDragEnd: function onRowDragEnd(event) {\n this.$emit('row-dragend', event);\n },\n onRowDrop: function onRowDrop(event) {\n this.$emit('row-drop', event);\n },\n onRowToggle: function onRowToggle(event) {\n this.d_rowExpanded = !this.d_rowExpanded;\n this.$emit('row-toggle', _objectSpread$9(_objectSpread$9({}, event), {}, {\n expanded: this.d_rowExpanded\n }));\n },\n onRadioChange: function onRadioChange(event) {\n this.$emit('radio-change', event);\n },\n onCheckboxChange: function onCheckboxChange(event) {\n this.$emit('checkbox-change', event);\n },\n onCellEditInit: function onCellEditInit(event) {\n this.$emit('cell-edit-init', event);\n },\n onCellEditComplete: function onCellEditComplete(event) {\n this.$emit('cell-edit-complete', event);\n },\n onCellEditCancel: function onCellEditCancel(event) {\n this.$emit('cell-edit-cancel', event);\n },\n onRowEditInit: function onRowEditInit(event) {\n this.$emit('row-edit-init', event);\n },\n onRowEditSave: function onRowEditSave(event) {\n this.$emit('row-edit-save', event);\n },\n onRowEditCancel: function onRowEditCancel(event) {\n this.$emit('row-edit-cancel', event);\n },\n onEditingMetaChange: function onEditingMetaChange(event) {\n this.$emit('editing-meta-change', event);\n },\n getVirtualScrollerProp: function getVirtualScrollerProp(option, options) {\n options = options || this.virtualScrollerContentProps;\n return options ? options[option] : null;\n }\n },\n computed: {\n rowIndex: function rowIndex() {\n var getItemOptions = this.getVirtualScrollerProp('getItemOptions');\n return getItemOptions ? getItemOptions(this.index).index : this.index;\n },\n rowStyles: function rowStyles() {\n var _this$rowStyle;\n return (_this$rowStyle = this.rowStyle) === null || _this$rowStyle === void 0 ? void 0 : _this$rowStyle.call(this, this.rowData);\n },\n rowClasses: function rowClasses() {\n var rowStyleClass = [];\n var columnSelectionMode = null;\n if (this.rowClass) {\n var rowClassValue = this.rowClass(this.rowData);\n if (rowClassValue) {\n rowStyleClass.push(rowClassValue);\n }\n }\n if (this.columns) {\n var _iterator = _createForOfIteratorHelper$2(this.columns),\n _step;\n try {\n for (_iterator.s(); !(_step = _iterator.n()).done;) {\n var col = _step.value;\n var _selectionMode = this.columnProp(col, 'selectionMode');\n if (isNotEmpty(_selectionMode)) {\n columnSelectionMode = _selectionMode;\n break;\n }\n }\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n }\n return [this.cx('row', {\n rowData: this.rowData,\n index: this.rowIndex,\n columnSelectionMode: columnSelectionMode\n }), rowStyleClass];\n },\n rowTabindex: function rowTabindex() {\n if (this.selection === null && (this.selectionMode === 'single' || this.selectionMode === 'multiple')) {\n return this.rowIndex === 0 ? 0 : -1;\n }\n return -1;\n },\n isRowEditing: function isRowEditing() {\n if (this.rowData && this.editingRows) {\n if (this.dataKey) return this.editingRowKeys ? this.editingRowKeys[resolveFieldData(this.rowData, this.dataKey)] !== undefined : false;else return this.findIndex(this.rowData, this.editingRows) > -1;\n }\n return false;\n },\n isRowGroupExpanded: function isRowGroupExpanded() {\n if (this.expandableRowGroups && this.expandedRowGroups) {\n var groupFieldValue = resolveFieldData(this.rowData, this.groupRowsBy);\n return this.expandedRowGroups.indexOf(groupFieldValue) > -1;\n }\n return false;\n },\n isSelected: function isSelected() {\n if (this.rowData && this.selection) {\n if (this.dataKey) {\n return this.selectionKeys ? this.selectionKeys[resolveFieldData(this.rowData, this.dataKey)] !== undefined : false;\n } else {\n if (this.selection instanceof Array) return this.findIndexInSelection(this.rowData) > -1;else return this.equals(this.rowData, this.selection);\n }\n }\n return false;\n },\n isSelectedWithContextMenu: function isSelectedWithContextMenu() {\n if (this.rowData && this.contextMenuSelection) {\n return this.equals(this.rowData, this.contextMenuSelection, this.dataKey);\n }\n return false;\n },\n shouldRenderRowGroupHeader: function shouldRenderRowGroupHeader() {\n var currentRowFieldData = resolveFieldData(this.rowData, this.groupRowsBy);\n var prevRowData = this.value[this.rowIndex - 1];\n if (prevRowData) {\n var previousRowFieldData = resolveFieldData(prevRowData, this.groupRowsBy);\n return currentRowFieldData !== previousRowFieldData;\n } else {\n return true;\n }\n },\n shouldRenderRowGroupFooter: function shouldRenderRowGroupFooter() {\n if (this.expandableRowGroups && !this.isRowGroupExpanded) {\n return false;\n } else {\n var currentRowFieldData = resolveFieldData(this.rowData, this.groupRowsBy);\n var nextRowData = this.value[this.rowIndex + 1];\n if (nextRowData) {\n var nextRowFieldData = resolveFieldData(nextRowData, this.groupRowsBy);\n return currentRowFieldData !== nextRowFieldData;\n } else {\n return true;\n }\n }\n },\n columnsLength: function columnsLength() {\n var _this2 = this;\n if (this.columns) {\n var hiddenColLength = 0;\n this.columns.forEach(function (column) {\n if (_this2.columnProp(column, 'selectionMode') === 'single') hiddenColLength--;\n if (_this2.columnProp(column, 'hidden')) hiddenColLength++;\n });\n return this.columns.length - hiddenColLength;\n }\n return 0;\n }\n },\n components: {\n DTBodyCell: script$9,\n ChevronDownIcon: ChevronDownIcon,\n ChevronRightIcon: ChevronRightIcon\n }\n};\n\nfunction _typeof$8(o) { \"@babel/helpers - typeof\"; return _typeof$8 = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof$8(o); }\nfunction ownKeys$8(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread$8(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$8(Object(t), !0).forEach(function (r) { _defineProperty$8(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$8(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty$8(e, r, t) { return (r = _toPropertyKey$8(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }\nfunction _toPropertyKey$8(t) { var i = _toPrimitive$8(t, \"string\"); return \"symbol\" == _typeof$8(i) ? i : i + \"\"; }\nfunction _toPrimitive$8(t, r) { if (\"object\" != _typeof$8(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof$8(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nvar _hoisted_1$3 = [\"colspan\"];\nvar _hoisted_2$1 = [\"tabindex\", \"aria-selected\", \"data-p-index\", \"data-p-selectable-row\", \"data-p-selected\", \"data-p-selected-contextmenu\"];\nvar _hoisted_3 = [\"id\"];\nvar _hoisted_4 = [\"colspan\"];\nvar _hoisted_5 = [\"colspan\"];\nvar _hoisted_6 = [\"colspan\"];\nfunction render$8(_ctx, _cache, $props, $setup, $data, $options) {\n var _component_ChevronDownIcon = resolveComponent(\"ChevronDownIcon\");\n var _component_ChevronRightIcon = resolveComponent(\"ChevronRightIcon\");\n var _component_DTBodyCell = resolveComponent(\"DTBodyCell\");\n return !$props.empty ? (openBlock(), createElementBlock(Fragment, {\n key: 0\n }, [$props.templates['groupheader'] && $props.rowGroupMode === 'subheader' && $options.shouldRenderRowGroupHeader ? (openBlock(), createElementBlock(\"tr\", mergeProps({\n key: 0,\n \"class\": _ctx.cx('rowGroupHeader'),\n style: $props.rowGroupHeaderStyle,\n role: \"row\"\n }, _ctx.ptm('rowGroupHeader')), [createElementVNode(\"td\", mergeProps({\n colspan: $options.columnsLength - 1\n }, _objectSpread$8(_objectSpread$8({}, $options.getColumnPT('bodycell')), _ctx.ptm('rowGroupHeaderCell'))), [$props.expandableRowGroups ? (openBlock(), createElementBlock(\"button\", mergeProps({\n key: 0,\n \"class\": _ctx.cx('rowToggleButton'),\n onClick: _cache[0] || (_cache[0] = function () {\n return $options.onRowGroupToggle && $options.onRowGroupToggle.apply($options, arguments);\n }),\n type: \"button\"\n }, _ctx.ptm('rowToggleButton')), [$props.templates['rowtoggleicon'] || $props.templates['rowgrouptogglericon'] ? (openBlock(), createBlock(resolveDynamicComponent($props.templates['rowtoggleicon'] || $props.templates['rowgrouptogglericon']), {\n key: 0,\n expanded: $options.isRowGroupExpanded\n }, null, 8, [\"expanded\"])) : (openBlock(), createElementBlock(Fragment, {\n key: 1\n }, [$options.isRowGroupExpanded && $props.expandedRowIcon ? (openBlock(), createElementBlock(\"span\", mergeProps({\n key: 0,\n \"class\": [_ctx.cx('rowToggleIcon'), $props.expandedRowIcon]\n }, _ctx.ptm('rowToggleIcon')), null, 16)) : $options.isRowGroupExpanded && !$props.expandedRowIcon ? (openBlock(), createBlock(_component_ChevronDownIcon, mergeProps({\n key: 1,\n \"class\": _ctx.cx('rowToggleIcon')\n }, _ctx.ptm('rowToggleIcon')), null, 16, [\"class\"])) : !$options.isRowGroupExpanded && $props.collapsedRowIcon ? (openBlock(), createElementBlock(\"span\", mergeProps({\n key: 2,\n \"class\": [_ctx.cx('rowToggleIcon'), $props.collapsedRowIcon]\n }, _ctx.ptm('rowToggleIcon')), null, 16)) : !$options.isRowGroupExpanded && !$props.collapsedRowIcon ? (openBlock(), createBlock(_component_ChevronRightIcon, mergeProps({\n key: 3,\n \"class\": _ctx.cx('rowToggleIcon')\n }, _ctx.ptm('rowToggleIcon')), null, 16, [\"class\"])) : createCommentVNode(\"\", true)], 64))], 16)) : createCommentVNode(\"\", true), (openBlock(), createBlock(resolveDynamicComponent($props.templates['groupheader']), {\n data: $props.rowData,\n index: $options.rowIndex\n }, null, 8, [\"data\", \"index\"]))], 16, _hoisted_1$3)], 16)) : createCommentVNode(\"\", true), ($props.expandableRowGroups ? $options.isRowGroupExpanded : true) ? (openBlock(), createElementBlock(\"tr\", mergeProps({\n key: 1,\n \"class\": $options.rowClasses,\n style: $options.rowStyles,\n tabindex: $options.rowTabindex,\n role: \"row\",\n \"aria-selected\": $props.selectionMode ? $options.isSelected : null,\n onClick: _cache[1] || (_cache[1] = function () {\n return $options.onRowClick && $options.onRowClick.apply($options, arguments);\n }),\n onDblclick: _cache[2] || (_cache[2] = function () {\n return $options.onRowDblClick && $options.onRowDblClick.apply($options, arguments);\n }),\n onContextmenu: _cache[3] || (_cache[3] = function () {\n return $options.onRowRightClick && $options.onRowRightClick.apply($options, arguments);\n }),\n onTouchend: _cache[4] || (_cache[4] = function () {\n return $options.onRowTouchEnd && $options.onRowTouchEnd.apply($options, arguments);\n }),\n onKeydown: _cache[5] || (_cache[5] = withModifiers(function () {\n return $options.onRowKeyDown && $options.onRowKeyDown.apply($options, arguments);\n }, [\"self\"])),\n onMousedown: _cache[6] || (_cache[6] = function () {\n return $options.onRowMouseDown && $options.onRowMouseDown.apply($options, arguments);\n }),\n onDragstart: _cache[7] || (_cache[7] = function () {\n return $options.onRowDragStart && $options.onRowDragStart.apply($options, arguments);\n }),\n onDragover: _cache[8] || (_cache[8] = function () {\n return $options.onRowDragOver && $options.onRowDragOver.apply($options, arguments);\n }),\n onDragleave: _cache[9] || (_cache[9] = function () {\n return $options.onRowDragLeave && $options.onRowDragLeave.apply($options, arguments);\n }),\n onDragend: _cache[10] || (_cache[10] = function () {\n return $options.onRowDragEnd && $options.onRowDragEnd.apply($options, arguments);\n }),\n onDrop: _cache[11] || (_cache[11] = function () {\n return $options.onRowDrop && $options.onRowDrop.apply($options, arguments);\n })\n }, $options.getBodyRowPTOptions('bodyRow'), {\n \"data-p-index\": $options.rowIndex,\n \"data-p-selectable-row\": $props.selectionMode ? true : false,\n \"data-p-selected\": $props.selection && $options.isSelected,\n \"data-p-selected-contextmenu\": $props.contextMenuSelection && $options.isSelectedWithContextMenu\n }), [(openBlock(true), createElementBlock(Fragment, null, renderList($props.columns, function (col, i) {\n return openBlock(), createElementBlock(Fragment, null, [$options.shouldRenderBodyCell(col) ? (openBlock(), createBlock(_component_DTBodyCell, {\n key: $options.columnProp(col, 'columnKey') || $options.columnProp(col, 'field') || i,\n rowData: $props.rowData,\n column: col,\n rowIndex: $options.rowIndex,\n index: i,\n selected: $options.isSelected,\n frozenRow: $props.frozenRow,\n rowspan: $props.rowGroupMode === 'rowspan' ? $options.calculateRowGroupSize(col) : null,\n editMode: $props.editMode,\n editing: $props.editMode === 'row' && $options.isRowEditing,\n editingMeta: $props.editingMeta,\n virtualScrollerContentProps: $props.virtualScrollerContentProps,\n ariaControls: $props.expandedRowId + '_' + $options.rowIndex + '_expansion',\n name: $props.nameAttributeSelector,\n isRowExpanded: $data.d_rowExpanded,\n expandedRowIcon: $props.expandedRowIcon,\n collapsedRowIcon: $props.collapsedRowIcon,\n editButtonProps: $props.editButtonProps,\n onRadioChange: $options.onRadioChange,\n onCheckboxChange: $options.onCheckboxChange,\n onRowToggle: $options.onRowToggle,\n onCellEditInit: $options.onCellEditInit,\n onCellEditComplete: $options.onCellEditComplete,\n onCellEditCancel: $options.onCellEditCancel,\n onRowEditInit: $options.onRowEditInit,\n onRowEditSave: $options.onRowEditSave,\n onRowEditCancel: $options.onRowEditCancel,\n onEditingMetaChange: $options.onEditingMetaChange,\n unstyled: _ctx.unstyled,\n pt: _ctx.pt\n }, null, 8, [\"rowData\", \"column\", \"rowIndex\", \"index\", \"selected\", \"frozenRow\", \"rowspan\", \"editMode\", \"editing\", \"editingMeta\", \"virtualScrollerContentProps\", \"ariaControls\", \"name\", \"isRowExpanded\", \"expandedRowIcon\", \"collapsedRowIcon\", \"editButtonProps\", \"onRadioChange\", \"onCheckboxChange\", \"onRowToggle\", \"onCellEditInit\", \"onCellEditComplete\", \"onCellEditCancel\", \"onRowEditInit\", \"onRowEditSave\", \"onRowEditCancel\", \"onEditingMetaChange\", \"unstyled\", \"pt\"])) : createCommentVNode(\"\", true)], 64);\n }), 256))], 16, _hoisted_2$1)) : createCommentVNode(\"\", true), $props.templates['expansion'] && $props.expandedRows && $data.d_rowExpanded ? (openBlock(), createElementBlock(\"tr\", mergeProps({\n key: 2,\n id: $props.expandedRowId + '_' + $options.rowIndex + '_expansion',\n \"class\": _ctx.cx('rowExpansion'),\n role: \"row\"\n }, _ctx.ptm('rowExpansion')), [createElementVNode(\"td\", mergeProps({\n colspan: $options.columnsLength\n }, _objectSpread$8(_objectSpread$8({}, $options.getColumnPT('bodycell')), _ctx.ptm('rowExpansionCell'))), [(openBlock(), createBlock(resolveDynamicComponent($props.templates['expansion']), {\n data: $props.rowData,\n index: $options.rowIndex\n }, null, 8, [\"data\", \"index\"]))], 16, _hoisted_4)], 16, _hoisted_3)) : createCommentVNode(\"\", true), $props.templates['groupfooter'] && $props.rowGroupMode === 'subheader' && $options.shouldRenderRowGroupFooter ? (openBlock(), createElementBlock(\"tr\", mergeProps({\n key: 3,\n \"class\": _ctx.cx('rowGroupFooter'),\n role: \"row\"\n }, _ctx.ptm('rowGroupFooter')), [createElementVNode(\"td\", mergeProps({\n colspan: $options.columnsLength - 1\n }, _objectSpread$8(_objectSpread$8({}, $options.getColumnPT('bodycell')), _ctx.ptm('rowGroupFooterCell'))), [(openBlock(), createBlock(resolveDynamicComponent($props.templates['groupfooter']), {\n data: $props.rowData,\n index: $options.rowIndex\n }, null, 8, [\"data\", \"index\"]))], 16, _hoisted_5)], 16)) : createCommentVNode(\"\", true)], 64)) : (openBlock(), createElementBlock(\"tr\", mergeProps({\n key: 1,\n \"class\": _ctx.cx('emptyMessage'),\n role: \"row\"\n }, _ctx.ptm('emptyMessage')), [createElementVNode(\"td\", mergeProps({\n colspan: $options.columnsLength\n }, _objectSpread$8(_objectSpread$8({}, $options.getColumnPT('bodycell')), _ctx.ptm('emptyMessageCell'))), [$props.templates.empty ? (openBlock(), createBlock(resolveDynamicComponent($props.templates.empty), {\n key: 0\n })) : createCommentVNode(\"\", true)], 16, _hoisted_6)], 16));\n}\n\nscript$8.render = render$8;\n\nvar script$7 = {\n name: 'TableBody',\n hostName: 'DataTable',\n \"extends\": BaseComponent,\n emits: ['rowgroup-toggle', 'row-click', 'row-dblclick', 'row-rightclick', 'row-touchend', 'row-keydown', 'row-mousedown', 'row-dragstart', 'row-dragover', 'row-dragleave', 'row-dragend', 'row-drop', 'row-toggle', 'radio-change', 'checkbox-change', 'cell-edit-init', 'cell-edit-complete', 'cell-edit-cancel', 'row-edit-init', 'row-edit-save', 'row-edit-cancel', 'editing-meta-change'],\n props: {\n value: {\n type: Array,\n \"default\": null\n },\n columns: {\n type: null,\n \"default\": null\n },\n frozenRow: {\n type: Boolean,\n \"default\": false\n },\n empty: {\n type: Boolean,\n \"default\": false\n },\n rowGroupMode: {\n type: String,\n \"default\": null\n },\n groupRowsBy: {\n type: [Array, String, Function],\n \"default\": null\n },\n expandableRowGroups: {\n type: Boolean,\n \"default\": false\n },\n expandedRowGroups: {\n type: Array,\n \"default\": null\n },\n first: {\n type: Number,\n \"default\": 0\n },\n dataKey: {\n type: [String, Function],\n \"default\": null\n },\n expandedRowIcon: {\n type: String,\n \"default\": null\n },\n collapsedRowIcon: {\n type: String,\n \"default\": null\n },\n expandedRows: {\n type: [Array, Object],\n \"default\": null\n },\n selection: {\n type: [Array, Object],\n \"default\": null\n },\n selectionKeys: {\n type: null,\n \"default\": null\n },\n selectionMode: {\n type: String,\n \"default\": null\n },\n contextMenu: {\n type: Boolean,\n \"default\": false\n },\n contextMenuSelection: {\n type: Object,\n \"default\": null\n },\n rowClass: {\n type: null,\n \"default\": null\n },\n rowStyle: {\n type: null,\n \"default\": null\n },\n editMode: {\n type: String,\n \"default\": null\n },\n compareSelectionBy: {\n type: String,\n \"default\": 'deepEquals'\n },\n editingRows: {\n type: Array,\n \"default\": null\n },\n editingRowKeys: {\n type: null,\n \"default\": null\n },\n editingMeta: {\n type: Object,\n \"default\": null\n },\n templates: {\n type: null,\n \"default\": null\n },\n scrollable: {\n type: Boolean,\n \"default\": false\n },\n editButtonProps: {\n type: Object,\n \"default\": null\n },\n virtualScrollerContentProps: {\n type: Object,\n \"default\": null\n },\n isVirtualScrollerDisabled: {\n type: Boolean,\n \"default\": false\n }\n },\n data: function data() {\n return {\n rowGroupHeaderStyleObject: {}\n };\n },\n mounted: function mounted() {\n if (this.frozenRow) {\n this.updateFrozenRowStickyPosition();\n }\n if (this.scrollable && this.rowGroupMode === 'subheader') {\n this.updateFrozenRowGroupHeaderStickyPosition();\n }\n },\n updated: function updated() {\n if (this.frozenRow) {\n this.updateFrozenRowStickyPosition();\n }\n if (this.scrollable && this.rowGroupMode === 'subheader') {\n this.updateFrozenRowGroupHeaderStickyPosition();\n }\n },\n methods: {\n getRowKey: function getRowKey(rowData, rowIndex) {\n return this.dataKey ? resolveFieldData(rowData, this.dataKey) : rowIndex;\n },\n updateFrozenRowStickyPosition: function updateFrozenRowStickyPosition() {\n this.$el.style.top = getOuterHeight(this.$el.previousElementSibling) + 'px';\n },\n updateFrozenRowGroupHeaderStickyPosition: function updateFrozenRowGroupHeaderStickyPosition() {\n var tableHeaderHeight = getOuterHeight(this.$el.previousElementSibling);\n this.rowGroupHeaderStyleObject.top = tableHeaderHeight + 'px';\n },\n getVirtualScrollerProp: function getVirtualScrollerProp(option, options) {\n options = options || this.virtualScrollerContentProps;\n return options ? options[option] : null;\n },\n bodyRef: function bodyRef(el) {\n // For VirtualScroller\n var contentRef = this.getVirtualScrollerProp('contentRef');\n contentRef && contentRef(el);\n }\n },\n computed: {\n rowGroupHeaderStyle: function rowGroupHeaderStyle() {\n if (this.scrollable) {\n return {\n top: this.rowGroupHeaderStyleObject.top\n };\n }\n return null;\n },\n bodyContentStyle: function bodyContentStyle() {\n return this.getVirtualScrollerProp('contentStyle');\n },\n ptmTBodyOptions: function ptmTBodyOptions() {\n var _this$$parentInstance;\n return {\n context: {\n scrollable: (_this$$parentInstance = this.$parentInstance) === null || _this$$parentInstance === void 0 || (_this$$parentInstance = _this$$parentInstance.$parentInstance) === null || _this$$parentInstance === void 0 ? void 0 : _this$$parentInstance.scrollable\n }\n };\n },\n expandedRowId: function expandedRowId() {\n return UniqueComponentId();\n },\n nameAttributeSelector: function nameAttributeSelector() {\n return UniqueComponentId();\n }\n },\n components: {\n DTBodyRow: script$8\n }\n};\n\nfunction render$7(_ctx, _cache, $props, $setup, $data, $options) {\n var _component_DTBodyRow = resolveComponent(\"DTBodyRow\");\n return openBlock(), createElementBlock(\"tbody\", mergeProps({\n ref: $options.bodyRef,\n \"class\": _ctx.cx('tbody'),\n role: \"rowgroup\",\n style: $options.bodyContentStyle\n }, _ctx.ptm('tbody', $options.ptmTBodyOptions)), [!$props.empty ? (openBlock(true), createElementBlock(Fragment, {\n key: 0\n }, renderList($props.value, function (rowData, rowIndex) {\n return openBlock(), createBlock(_component_DTBodyRow, {\n key: $options.getRowKey(rowData, rowIndex),\n rowData: rowData,\n index: rowIndex,\n value: $props.value,\n columns: $props.columns,\n frozenRow: $props.frozenRow,\n empty: $props.empty,\n first: $props.first,\n dataKey: $props.dataKey,\n selection: $props.selection,\n selectionKeys: $props.selectionKeys,\n selectionMode: $props.selectionMode,\n contextMenu: $props.contextMenu,\n contextMenuSelection: $props.contextMenuSelection,\n rowGroupMode: $props.rowGroupMode,\n groupRowsBy: $props.groupRowsBy,\n expandableRowGroups: $props.expandableRowGroups,\n rowClass: $props.rowClass,\n rowStyle: $props.rowStyle,\n editMode: $props.editMode,\n compareSelectionBy: $props.compareSelectionBy,\n scrollable: $props.scrollable,\n expandedRowIcon: $props.expandedRowIcon,\n collapsedRowIcon: $props.collapsedRowIcon,\n expandedRows: $props.expandedRows,\n expandedRowGroups: $props.expandedRowGroups,\n editingRows: $props.editingRows,\n editingRowKeys: $props.editingRowKeys,\n templates: $props.templates,\n editButtonProps: $props.editButtonProps,\n virtualScrollerContentProps: $props.virtualScrollerContentProps,\n isVirtualScrollerDisabled: $props.isVirtualScrollerDisabled,\n editingMeta: $props.editingMeta,\n rowGroupHeaderStyle: $options.rowGroupHeaderStyle,\n expandedRowId: $options.expandedRowId,\n nameAttributeSelector: $options.nameAttributeSelector,\n onRowgroupToggle: _cache[0] || (_cache[0] = function ($event) {\n return _ctx.$emit('rowgroup-toggle', $event);\n }),\n onRowClick: _cache[1] || (_cache[1] = function ($event) {\n return _ctx.$emit('row-click', $event);\n }),\n onRowDblclick: _cache[2] || (_cache[2] = function ($event) {\n return _ctx.$emit('row-dblclick', $event);\n }),\n onRowRightclick: _cache[3] || (_cache[3] = function ($event) {\n return _ctx.$emit('row-rightclick', $event);\n }),\n onRowTouchend: _cache[4] || (_cache[4] = function ($event) {\n return _ctx.$emit('row-touchend', $event);\n }),\n onRowKeydown: _cache[5] || (_cache[5] = function ($event) {\n return _ctx.$emit('row-keydown', $event);\n }),\n onRowMousedown: _cache[6] || (_cache[6] = function ($event) {\n return _ctx.$emit('row-mousedown', $event);\n }),\n onRowDragstart: _cache[7] || (_cache[7] = function ($event) {\n return _ctx.$emit('row-dragstart', $event);\n }),\n onRowDragover: _cache[8] || (_cache[8] = function ($event) {\n return _ctx.$emit('row-dragover', $event);\n }),\n onRowDragleave: _cache[9] || (_cache[9] = function ($event) {\n return _ctx.$emit('row-dragleave', $event);\n }),\n onRowDragend: _cache[10] || (_cache[10] = function ($event) {\n return _ctx.$emit('row-dragend', $event);\n }),\n onRowDrop: _cache[11] || (_cache[11] = function ($event) {\n return _ctx.$emit('row-drop', $event);\n }),\n onRowToggle: _cache[12] || (_cache[12] = function ($event) {\n return _ctx.$emit('row-toggle', $event);\n }),\n onRadioChange: _cache[13] || (_cache[13] = function ($event) {\n return _ctx.$emit('radio-change', $event);\n }),\n onCheckboxChange: _cache[14] || (_cache[14] = function ($event) {\n return _ctx.$emit('checkbox-change', $event);\n }),\n onCellEditInit: _cache[15] || (_cache[15] = function ($event) {\n return _ctx.$emit('cell-edit-init', $event);\n }),\n onCellEditComplete: _cache[16] || (_cache[16] = function ($event) {\n return _ctx.$emit('cell-edit-complete', $event);\n }),\n onCellEditCancel: _cache[17] || (_cache[17] = function ($event) {\n return _ctx.$emit('cell-edit-cancel', $event);\n }),\n onRowEditInit: _cache[18] || (_cache[18] = function ($event) {\n return _ctx.$emit('row-edit-init', $event);\n }),\n onRowEditSave: _cache[19] || (_cache[19] = function ($event) {\n return _ctx.$emit('row-edit-save', $event);\n }),\n onRowEditCancel: _cache[20] || (_cache[20] = function ($event) {\n return _ctx.$emit('row-edit-cancel', $event);\n }),\n onEditingMetaChange: _cache[21] || (_cache[21] = function ($event) {\n return _ctx.$emit('editing-meta-change', $event);\n }),\n unstyled: _ctx.unstyled,\n pt: _ctx.pt\n }, null, 8, [\"rowData\", \"index\", \"value\", \"columns\", \"frozenRow\", \"empty\", \"first\", \"dataKey\", \"selection\", \"selectionKeys\", \"selectionMode\", \"contextMenu\", \"contextMenuSelection\", \"rowGroupMode\", \"groupRowsBy\", \"expandableRowGroups\", \"rowClass\", \"rowStyle\", \"editMode\", \"compareSelectionBy\", \"scrollable\", \"expandedRowIcon\", \"collapsedRowIcon\", \"expandedRows\", \"expandedRowGroups\", \"editingRows\", \"editingRowKeys\", \"templates\", \"editButtonProps\", \"virtualScrollerContentProps\", \"isVirtualScrollerDisabled\", \"editingMeta\", \"rowGroupHeaderStyle\", \"expandedRowId\", \"nameAttributeSelector\", \"unstyled\", \"pt\"]);\n }), 128)) : (openBlock(), createBlock(_component_DTBodyRow, {\n key: 1,\n empty: $props.empty,\n columns: $props.columns,\n templates: $props.templates\n }, null, 8, [\"empty\", \"columns\", \"templates\"]))], 16);\n}\n\nscript$7.render = render$7;\n\nvar script$6 = {\n name: 'FooterCell',\n hostName: 'DataTable',\n \"extends\": BaseComponent,\n props: {\n column: {\n type: Object,\n \"default\": null\n },\n index: {\n type: Number,\n \"default\": null\n }\n },\n data: function data() {\n return {\n styleObject: {}\n };\n },\n mounted: function mounted() {\n if (this.columnProp('frozen')) {\n this.updateStickyPosition();\n }\n },\n updated: function updated() {\n if (this.columnProp('frozen')) {\n this.updateStickyPosition();\n }\n },\n methods: {\n columnProp: function columnProp(prop) {\n return getVNodeProp(this.column, prop);\n },\n getColumnPT: function getColumnPT(key) {\n var _this$$parentInstance, _this$$parentInstance2;\n var columnMetaData = {\n props: this.column.props,\n parent: {\n instance: this,\n props: this.$props,\n state: this.$data\n },\n context: {\n index: this.index,\n size: (_this$$parentInstance = this.$parentInstance) === null || _this$$parentInstance === void 0 || (_this$$parentInstance = _this$$parentInstance.$parentInstance) === null || _this$$parentInstance === void 0 ? void 0 : _this$$parentInstance.size,\n showGridlines: ((_this$$parentInstance2 = this.$parentInstance) === null || _this$$parentInstance2 === void 0 || (_this$$parentInstance2 = _this$$parentInstance2.$parentInstance) === null || _this$$parentInstance2 === void 0 ? void 0 : _this$$parentInstance2.showGridlines) || false\n }\n };\n return mergeProps(this.ptm(\"column.\".concat(key), {\n column: columnMetaData\n }), this.ptm(\"column.\".concat(key), columnMetaData), this.ptmo(this.getColumnProp(), key, columnMetaData));\n },\n getColumnProp: function getColumnProp() {\n return this.column.props && this.column.props.pt ? this.column.props.pt : undefined;\n },\n updateStickyPosition: function updateStickyPosition() {\n if (this.columnProp('frozen')) {\n var align = this.columnProp('alignFrozen');\n if (align === 'right') {\n var right = 0;\n var next = getNextElementSibling(this.$el, '[data-p-frozen-column=\"true\"]');\n if (next) {\n right = getOuterWidth(next) + parseFloat(next.style.right || 0);\n }\n this.styleObject.right = right + 'px';\n } else {\n var left = 0;\n var prev = getPreviousElementSibling(this.$el, '[data-p-frozen-column=\"true\"]');\n if (prev) {\n left = getOuterWidth(prev) + parseFloat(prev.style.left || 0);\n }\n this.styleObject.left = left + 'px';\n }\n }\n }\n },\n computed: {\n containerClass: function containerClass() {\n return [this.columnProp('footerClass'), this.columnProp('class'), this.cx('footerCell')];\n },\n containerStyle: function containerStyle() {\n var bodyStyle = this.columnProp('footerStyle');\n var columnStyle = this.columnProp('style');\n return this.columnProp('frozen') ? [columnStyle, bodyStyle, this.styleObject] : [columnStyle, bodyStyle];\n }\n }\n};\n\nfunction _typeof$7(o) { \"@babel/helpers - typeof\"; return _typeof$7 = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof$7(o); }\nfunction ownKeys$7(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread$7(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$7(Object(t), !0).forEach(function (r) { _defineProperty$7(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$7(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty$7(e, r, t) { return (r = _toPropertyKey$7(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }\nfunction _toPropertyKey$7(t) { var i = _toPrimitive$7(t, \"string\"); return \"symbol\" == _typeof$7(i) ? i : i + \"\"; }\nfunction _toPrimitive$7(t, r) { if (\"object\" != _typeof$7(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof$7(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nvar _hoisted_1$2 = [\"colspan\", \"rowspan\", \"data-p-frozen-column\"];\nfunction render$6(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"td\", mergeProps({\n style: $options.containerStyle,\n \"class\": $options.containerClass,\n role: \"cell\",\n colspan: $options.columnProp('colspan'),\n rowspan: $options.columnProp('rowspan')\n }, _objectSpread$7(_objectSpread$7({}, $options.getColumnPT('root')), $options.getColumnPT('footerCell')), {\n \"data-p-frozen-column\": $options.columnProp('frozen')\n }), [$props.column.children && $props.column.children.footer ? (openBlock(), createBlock(resolveDynamicComponent($props.column.children.footer), {\n key: 0,\n column: $props.column\n }, null, 8, [\"column\"])) : createCommentVNode(\"\", true), $options.columnProp('footer') ? (openBlock(), createElementBlock(\"span\", mergeProps({\n key: 1,\n \"class\": _ctx.cx('columnFooter')\n }, $options.getColumnPT('columnFooter')), toDisplayString($options.columnProp('footer')), 17)) : createCommentVNode(\"\", true)], 16, _hoisted_1$2);\n}\n\nscript$6.render = render$6;\n\nfunction _createForOfIteratorHelper$1(r, e) { var t = \"undefined\" != typeof Symbol && r[Symbol.iterator] || r[\"@@iterator\"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray$1(r)) || e ) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError(\"Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t[\"return\"] || t[\"return\"](); } finally { if (u) throw o; } } }; }\nfunction _unsupportedIterableToArray$1(r, a) { if (r) { if (\"string\" == typeof r) return _arrayLikeToArray$1(r, a); var t = {}.toString.call(r).slice(8, -1); return \"Object\" === t && r.constructor && (t = r.constructor.name), \"Map\" === t || \"Set\" === t ? Array.from(r) : \"Arguments\" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray$1(r, a) : void 0; } }\nfunction _arrayLikeToArray$1(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }\nvar script$5 = {\n name: 'TableFooter',\n hostName: 'DataTable',\n \"extends\": BaseComponent,\n props: {\n columnGroup: {\n type: null,\n \"default\": null\n },\n columns: {\n type: Object,\n \"default\": null\n }\n },\n provide: function provide() {\n return {\n $rows: this.d_footerRows,\n $columns: this.d_footerColumns\n };\n },\n data: function data() {\n return {\n d_footerRows: new HelperSet({\n type: 'Row'\n }),\n d_footerColumns: new HelperSet({\n type: 'Column'\n })\n };\n },\n beforeUnmount: function beforeUnmount() {\n this.d_footerRows.clear();\n this.d_footerColumns.clear();\n },\n methods: {\n columnProp: function columnProp(col, prop) {\n return getVNodeProp(col, prop);\n },\n getColumnGroupPT: function getColumnGroupPT(key) {\n var columnGroupMetaData = {\n props: this.getColumnGroupProps(),\n parent: {\n instance: this,\n props: this.$props,\n state: this.$data\n },\n context: {\n type: 'footer',\n scrollable: this.ptmTFootOptions.context.scrollable\n }\n };\n return mergeProps(this.ptm(\"columnGroup.\".concat(key), {\n columnGroup: columnGroupMetaData\n }), this.ptm(\"columnGroup.\".concat(key), columnGroupMetaData), this.ptmo(this.getColumnGroupProps(), key, columnGroupMetaData));\n },\n getColumnGroupProps: function getColumnGroupProps() {\n return this.columnGroup && this.columnGroup.props && this.columnGroup.props.pt ? this.columnGroup.props.pt : undefined; //@todo\n },\n getRowPT: function getRowPT(row, key, index) {\n var rowMetaData = {\n props: row.props,\n parent: {\n instance: this,\n props: this.$props,\n state: this.$data\n },\n context: {\n index: index\n }\n };\n return mergeProps(this.ptm(\"row.\".concat(key), {\n row: rowMetaData\n }), this.ptm(\"row.\".concat(key), rowMetaData), this.ptmo(this.getRowProp(row), key, rowMetaData));\n },\n getRowProp: function getRowProp(row) {\n return row.props && row.props.pt ? row.props.pt : undefined; //@todo\n },\n getFooterRows: function getFooterRows() {\n var _this$d_footerRows;\n return (_this$d_footerRows = this.d_footerRows) === null || _this$d_footerRows === void 0 ? void 0 : _this$d_footerRows.get(this.columnGroup, this.columnGroup.children);\n },\n getFooterColumns: function getFooterColumns(row) {\n var _this$d_footerColumns;\n return (_this$d_footerColumns = this.d_footerColumns) === null || _this$d_footerColumns === void 0 ? void 0 : _this$d_footerColumns.get(row, row.children);\n }\n },\n computed: {\n hasFooter: function hasFooter() {\n var hasFooter = false;\n if (this.columnGroup) {\n hasFooter = true;\n } else if (this.columns) {\n var _iterator = _createForOfIteratorHelper$1(this.columns),\n _step;\n try {\n for (_iterator.s(); !(_step = _iterator.n()).done;) {\n var col = _step.value;\n if (this.columnProp(col, 'footer') || col.children && col.children.footer) {\n hasFooter = true;\n break;\n }\n }\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n }\n return hasFooter;\n },\n ptmTFootOptions: function ptmTFootOptions() {\n var _this$$parentInstance;\n return {\n context: {\n scrollable: (_this$$parentInstance = this.$parentInstance) === null || _this$$parentInstance === void 0 || (_this$$parentInstance = _this$$parentInstance.$parentInstance) === null || _this$$parentInstance === void 0 ? void 0 : _this$$parentInstance.scrollable\n }\n };\n }\n },\n components: {\n DTFooterCell: script$6\n }\n};\n\nfunction _typeof$6(o) { \"@babel/helpers - typeof\"; return _typeof$6 = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof$6(o); }\nfunction ownKeys$6(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread$6(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$6(Object(t), !0).forEach(function (r) { _defineProperty$6(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$6(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty$6(e, r, t) { return (r = _toPropertyKey$6(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }\nfunction _toPropertyKey$6(t) { var i = _toPrimitive$6(t, \"string\"); return \"symbol\" == _typeof$6(i) ? i : i + \"\"; }\nfunction _toPrimitive$6(t, r) { if (\"object\" != _typeof$6(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof$6(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nfunction render$5(_ctx, _cache, $props, $setup, $data, $options) {\n var _component_DTFooterCell = resolveComponent(\"DTFooterCell\");\n return $options.hasFooter ? (openBlock(), createElementBlock(\"tfoot\", mergeProps({\n key: 0,\n \"class\": _ctx.cx('tfoot'),\n style: _ctx.sx('tfoot'),\n role: \"rowgroup\"\n }, $props.columnGroup ? _objectSpread$6(_objectSpread$6({}, _ctx.ptm('tfoot', $options.ptmTFootOptions)), $options.getColumnGroupPT('root')) : _ctx.ptm('tfoot', $options.ptmTFootOptions), {\n \"data-pc-section\": \"tfoot\"\n }), [!$props.columnGroup ? (openBlock(), createElementBlock(\"tr\", mergeProps({\n key: 0,\n role: \"row\"\n }, _ctx.ptm('footerRow')), [(openBlock(true), createElementBlock(Fragment, null, renderList($props.columns, function (col, i) {\n return openBlock(), createElementBlock(Fragment, {\n key: $options.columnProp(col, 'columnKey') || $options.columnProp(col, 'field') || i\n }, [!$options.columnProp(col, 'hidden') ? (openBlock(), createBlock(_component_DTFooterCell, {\n key: 0,\n column: col,\n pt: _ctx.pt\n }, null, 8, [\"column\", \"pt\"])) : createCommentVNode(\"\", true)], 64);\n }), 128))], 16)) : (openBlock(true), createElementBlock(Fragment, {\n key: 1\n }, renderList($options.getFooterRows(), function (row, i) {\n return openBlock(), createElementBlock(\"tr\", mergeProps({\n key: i,\n role: \"row\",\n ref_for: true\n }, _objectSpread$6(_objectSpread$6({}, _ctx.ptm('footerRow')), $options.getRowPT(row, 'root', i))), [(openBlock(true), createElementBlock(Fragment, null, renderList($options.getFooterColumns(row), function (col, j) {\n return openBlock(), createElementBlock(Fragment, {\n key: $options.columnProp(col, 'columnKey') || $options.columnProp(col, 'field') || j\n }, [!$options.columnProp(col, 'hidden') ? (openBlock(), createBlock(_component_DTFooterCell, {\n key: 0,\n column: col,\n index: i,\n pt: _ctx.pt\n }, null, 8, [\"column\", \"index\", \"pt\"])) : createCommentVNode(\"\", true)], 64);\n }), 128))], 16);\n }), 128))], 16)) : createCommentVNode(\"\", true);\n}\n\nscript$5.render = render$5;\n\nfunction _typeof$5(o) { \"@babel/helpers - typeof\"; return _typeof$5 = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof$5(o); }\nfunction ownKeys$5(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread$5(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$5(Object(t), !0).forEach(function (r) { _defineProperty$5(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$5(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty$5(e, r, t) { return (r = _toPropertyKey$5(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }\nfunction _toPropertyKey$5(t) { var i = _toPrimitive$5(t, \"string\"); return \"symbol\" == _typeof$5(i) ? i : i + \"\"; }\nfunction _toPrimitive$5(t, r) { if (\"object\" != _typeof$5(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof$5(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nvar script$4 = {\n name: 'ColumnFilter',\n hostName: 'DataTable',\n \"extends\": BaseComponent,\n emits: ['filter-change', 'filter-apply', 'operator-change', 'matchmode-change', 'constraint-add', 'constraint-remove', 'filter-clear', 'apply-click'],\n props: {\n field: {\n type: String,\n \"default\": null\n },\n type: {\n type: String,\n \"default\": 'text'\n },\n display: {\n type: String,\n \"default\": null\n },\n showMenu: {\n type: Boolean,\n \"default\": true\n },\n matchMode: {\n type: String,\n \"default\": null\n },\n showOperator: {\n type: Boolean,\n \"default\": true\n },\n showClearButton: {\n type: Boolean,\n \"default\": true\n },\n showApplyButton: {\n type: Boolean,\n \"default\": true\n },\n showMatchModes: {\n type: Boolean,\n \"default\": true\n },\n showAddButton: {\n type: Boolean,\n \"default\": true\n },\n matchModeOptions: {\n type: Array,\n \"default\": null\n },\n maxConstraints: {\n type: Number,\n \"default\": 2\n },\n filterElement: {\n type: Function,\n \"default\": null\n },\n filterHeaderTemplate: {\n type: Function,\n \"default\": null\n },\n filterFooterTemplate: {\n type: Function,\n \"default\": null\n },\n filterClearTemplate: {\n type: Function,\n \"default\": null\n },\n filterApplyTemplate: {\n type: Function,\n \"default\": null\n },\n filterIconTemplate: {\n type: Function,\n \"default\": null\n },\n filterAddIconTemplate: {\n type: Function,\n \"default\": null\n },\n filterRemoveIconTemplate: {\n type: Function,\n \"default\": null\n },\n filterClearIconTemplate: {\n type: Function,\n \"default\": null\n },\n filters: {\n type: Object,\n \"default\": null\n },\n filtersStore: {\n type: Object,\n \"default\": null\n },\n filterMenuClass: {\n type: String,\n \"default\": null\n },\n filterMenuStyle: {\n type: null,\n \"default\": null\n },\n filterInputProps: {\n type: null,\n \"default\": null\n },\n filterButtonProps: {\n type: null,\n \"default\": null\n },\n column: null\n },\n data: function data() {\n return {\n id: this.$attrs.id,\n overlayVisible: false,\n defaultMatchMode: null,\n defaultOperator: null\n };\n },\n watch: {\n '$attrs.id': function $attrsId(newValue) {\n this.id = newValue || UniqueComponentId();\n }\n },\n overlay: null,\n selfClick: false,\n overlayEventListener: null,\n beforeUnmount: function beforeUnmount() {\n if (this.overlayEventListener) {\n OverlayEventBus.off('overlay-click', this.overlayEventListener);\n this.overlayEventListener = null;\n }\n if (this.overlay) {\n ZIndex.clear(this.overlay);\n this.onOverlayHide();\n }\n },\n mounted: function mounted() {\n this.id = this.id || UniqueComponentId();\n if (this.filters && this.filters[this.field]) {\n var fieldFilters = this.filters[this.field];\n if (fieldFilters.operator) {\n this.defaultMatchMode = fieldFilters.constraints[0].matchMode;\n this.defaultOperator = fieldFilters.operator;\n } else {\n this.defaultMatchMode = this.filters[this.field].matchMode;\n }\n }\n },\n methods: {\n getColumnPT: function getColumnPT(key, params) {\n var columnMetaData = _objectSpread$5({\n props: this.column.props,\n parent: {\n instance: this,\n props: this.$props,\n state: this.$data\n }\n }, params);\n return mergeProps(this.ptm(\"column.\".concat(key), {\n column: columnMetaData\n }), this.ptm(\"column.\".concat(key), columnMetaData), this.ptmo(this.getColumnProp(), key, columnMetaData));\n },\n getColumnProp: function getColumnProp() {\n return this.column.props && this.column.props.pt ? this.column.props.pt : undefined;\n },\n ptmFilterConstraintOptions: function ptmFilterConstraintOptions(matchMode) {\n return {\n context: {\n highlighted: matchMode && this.isRowMatchModeSelected(matchMode.value)\n }\n };\n },\n clearFilter: function clearFilter() {\n var _filters = _objectSpread$5({}, this.filters);\n if (_filters[this.field].operator) {\n _filters[this.field].constraints.splice(1);\n _filters[this.field].operator = this.defaultOperator;\n _filters[this.field].constraints[0] = {\n value: null,\n matchMode: this.defaultMatchMode\n };\n } else {\n _filters[this.field].value = null;\n _filters[this.field].matchMode = this.defaultMatchMode;\n }\n this.$emit('filter-clear');\n this.$emit('filter-change', _filters);\n this.$emit('filter-apply');\n this.hide();\n },\n applyFilter: function applyFilter() {\n this.$emit('apply-click', {\n field: this.field,\n constraints: this.filters[this.field]\n });\n this.$emit('filter-apply');\n this.hide();\n },\n hasFilter: function hasFilter() {\n if (this.filtersStore) {\n var fieldFilter = this.filtersStore[this.field];\n if (fieldFilter) {\n if (fieldFilter.operator) return !this.isFilterBlank(fieldFilter.constraints[0].value);else return !this.isFilterBlank(fieldFilter.value);\n }\n }\n return false;\n },\n hasRowFilter: function hasRowFilter() {\n return this.filters[this.field] && !this.isFilterBlank(this.filters[this.field].value);\n },\n isFilterBlank: function isFilterBlank(filter) {\n if (filter !== null && filter !== undefined) {\n if (typeof filter === 'string' && filter.trim().length == 0 || filter instanceof Array && filter.length == 0) return true;else return false;\n }\n return true;\n },\n toggleMenu: function toggleMenu(event) {\n this.overlayVisible = !this.overlayVisible;\n event.preventDefault();\n },\n onToggleButtonKeyDown: function onToggleButtonKeyDown(event) {\n switch (event.code) {\n case 'Enter':\n case 'NumpadEnter':\n case 'Space':\n this.toggleMenu(event);\n break;\n case 'Escape':\n this.overlayVisible = false;\n break;\n }\n },\n onRowMatchModeChange: function onRowMatchModeChange(matchMode) {\n var _filters = _objectSpread$5({}, this.filters);\n _filters[this.field].matchMode = matchMode;\n this.$emit('matchmode-change', {\n field: this.field,\n matchMode: matchMode\n });\n this.$emit('filter-change', _filters);\n this.$emit('filter-apply');\n this.hide();\n },\n onRowMatchModeKeyDown: function onRowMatchModeKeyDown(event) {\n var item = event.target;\n switch (event.code) {\n case 'ArrowDown':\n var nextItem = this.findNextItem(item);\n if (nextItem) {\n item.removeAttribute('tabindex');\n nextItem.tabIndex = '0';\n nextItem.focus();\n }\n event.preventDefault();\n break;\n case 'ArrowUp':\n var prevItem = this.findPrevItem(item);\n if (prevItem) {\n item.removeAttribute('tabindex');\n prevItem.tabIndex = '0';\n prevItem.focus();\n }\n event.preventDefault();\n break;\n }\n },\n isRowMatchModeSelected: function isRowMatchModeSelected(matchMode) {\n return this.filters[this.field].matchMode === matchMode;\n },\n onOperatorChange: function onOperatorChange(value) {\n var _filters = _objectSpread$5({}, this.filters);\n _filters[this.field].operator = value;\n this.$emit('filter-change', _filters);\n this.$emit('operator-change', {\n field: this.field,\n operator: value\n });\n if (!this.showApplyButton) {\n this.$emit('filter-apply');\n }\n },\n onMenuMatchModeChange: function onMenuMatchModeChange(value, index) {\n var _filters = _objectSpread$5({}, this.filters);\n _filters[this.field].constraints[index].matchMode = value;\n this.$emit('matchmode-change', {\n field: this.field,\n matchMode: value,\n index: index\n });\n if (!this.showApplyButton) {\n this.$emit('filter-apply');\n }\n },\n addConstraint: function addConstraint() {\n var _filters = _objectSpread$5({}, this.filters);\n var newConstraint = {\n value: null,\n matchMode: this.defaultMatchMode\n };\n _filters[this.field].constraints.push(newConstraint);\n this.$emit('constraint-add', {\n field: this.field,\n constraing: newConstraint\n });\n this.$emit('filter-change', _filters);\n if (!this.showApplyButton) {\n this.$emit('filter-apply');\n }\n },\n removeConstraint: function removeConstraint(index) {\n var _filters = _objectSpread$5({}, this.filters);\n var removedConstraint = _filters[this.field].constraints.splice(index, 1);\n this.$emit('constraint-remove', {\n field: this.field,\n constraing: removedConstraint\n });\n this.$emit('filter-change', _filters);\n if (!this.showApplyButton) {\n this.$emit('filter-apply');\n }\n },\n filterCallback: function filterCallback() {\n this.$emit('filter-apply');\n },\n findNextItem: function findNextItem(item) {\n var nextItem = item.nextElementSibling;\n if (nextItem) return getAttribute(nextItem, 'data-pc-section') === 'filterconstraintseparator' ? this.findNextItem(nextItem) : nextItem;else return item.parentElement.firstElementChild;\n },\n findPrevItem: function findPrevItem(item) {\n var prevItem = item.previousElementSibling;\n if (prevItem) return getAttribute(prevItem, 'data-pc-section') === 'filterconstraintseparator' ? this.findPrevItem(prevItem) : prevItem;else return item.parentElement.lastElementChild;\n },\n hide: function hide() {\n this.overlayVisible = false;\n this.showMenuButton && focus(this.$refs.icon.$el);\n },\n onContentClick: function onContentClick(event) {\n this.selfClick = true;\n OverlayEventBus.emit('overlay-click', {\n originalEvent: event,\n target: this.overlay\n });\n },\n onContentMouseDown: function onContentMouseDown() {\n this.selfClick = true;\n },\n onOverlayEnter: function onOverlayEnter(el) {\n var _this = this;\n if (this.filterMenuStyle) {\n addStyle(this.overlay, this.filterMenuStyle);\n }\n ZIndex.set('overlay', el, this.$primevue.config.zIndex.overlay);\n addStyle(el, {\n position: 'absolute',\n top: '0',\n left: '0'\n });\n absolutePosition(this.overlay, this.$refs.icon.$el);\n this.bindOutsideClickListener();\n this.bindScrollListener();\n this.bindResizeListener();\n this.overlayEventListener = function (e) {\n if (!_this.isOutsideClicked(e.target)) {\n _this.selfClick = true;\n }\n };\n OverlayEventBus.on('overlay-click', this.overlayEventListener);\n },\n onOverlayAfterEnter: function onOverlayAfterEnter() {\n var _this$overlay;\n (_this$overlay = this.overlay) === null || _this$overlay === void 0 || (_this$overlay = _this$overlay.$focustrap) === null || _this$overlay === void 0 || _this$overlay.autoFocus();\n },\n onOverlayLeave: function onOverlayLeave() {\n this.onOverlayHide();\n },\n onOverlayAfterLeave: function onOverlayAfterLeave(el) {\n ZIndex.clear(el);\n },\n onOverlayHide: function onOverlayHide() {\n this.unbindOutsideClickListener();\n this.unbindResizeListener();\n this.unbindScrollListener();\n this.overlay = null;\n OverlayEventBus.off('overlay-click', this.overlayEventListener);\n this.overlayEventListener = null;\n },\n overlayRef: function overlayRef(el) {\n this.overlay = el;\n },\n isOutsideClicked: function isOutsideClicked(target) {\n return !this.isTargetClicked(target) && this.overlay && !(this.overlay.isSameNode(target) || this.overlay.contains(target));\n },\n isTargetClicked: function isTargetClicked(target) {\n return this.$refs.icon && (this.$refs.icon.$el.isSameNode(target) || this.$refs.icon.$el.contains(target));\n },\n bindOutsideClickListener: function bindOutsideClickListener() {\n var _this2 = this;\n if (!this.outsideClickListener) {\n this.outsideClickListener = function (event) {\n if (_this2.overlayVisible && !_this2.selfClick && _this2.isOutsideClicked(event.target)) {\n _this2.overlayVisible = false;\n }\n _this2.selfClick = false;\n };\n document.addEventListener('click', this.outsideClickListener);\n }\n },\n unbindOutsideClickListener: function unbindOutsideClickListener() {\n if (this.outsideClickListener) {\n document.removeEventListener('click', this.outsideClickListener);\n this.outsideClickListener = null;\n this.selfClick = false;\n }\n },\n bindScrollListener: function bindScrollListener() {\n var _this3 = this;\n if (!this.scrollHandler) {\n this.scrollHandler = new ConnectedOverlayScrollHandler(this.$refs.icon.$el, function () {\n if (_this3.overlayVisible) {\n _this3.hide();\n }\n });\n }\n this.scrollHandler.bindScrollListener();\n },\n unbindScrollListener: function unbindScrollListener() {\n if (this.scrollHandler) {\n this.scrollHandler.unbindScrollListener();\n }\n },\n bindResizeListener: function bindResizeListener() {\n var _this4 = this;\n if (!this.resizeListener) {\n this.resizeListener = function () {\n if (_this4.overlayVisible && !isTouchDevice()) {\n _this4.hide();\n }\n };\n window.addEventListener('resize', this.resizeListener);\n }\n },\n unbindResizeListener: function unbindResizeListener() {\n if (this.resizeListener) {\n window.removeEventListener('resize', this.resizeListener);\n this.resizeListener = null;\n }\n }\n },\n computed: {\n showMenuButton: function showMenuButton() {\n return this.showMenu && (this.display === 'row' ? this.type !== 'boolean' : true);\n },\n overlayId: function overlayId() {\n return this.id + '_overlay';\n },\n matchModes: function matchModes() {\n var _this5 = this;\n return this.matchModeOptions || this.$primevue.config.filterMatchModeOptions[this.type].map(function (key) {\n return {\n label: _this5.$primevue.config.locale[key],\n value: key\n };\n });\n },\n isShowMatchModes: function isShowMatchModes() {\n return this.type !== 'boolean' && this.showMatchModes && this.matchModes;\n },\n operatorOptions: function operatorOptions() {\n return [{\n label: this.$primevue.config.locale.matchAll,\n value: FilterOperator.AND\n }, {\n label: this.$primevue.config.locale.matchAny,\n value: FilterOperator.OR\n }];\n },\n noFilterLabel: function noFilterLabel() {\n return this.$primevue.config.locale ? this.$primevue.config.locale.noFilter : undefined;\n },\n isShowOperator: function isShowOperator() {\n return this.showOperator && this.filters[this.field].operator;\n },\n operator: function operator() {\n return this.filters[this.field].operator;\n },\n fieldConstraints: function fieldConstraints() {\n return this.filters[this.field].constraints || [this.filters[this.field]];\n },\n showRemoveIcon: function showRemoveIcon() {\n return this.fieldConstraints.length > 1;\n },\n removeRuleButtonLabel: function removeRuleButtonLabel() {\n return this.$primevue.config.locale ? this.$primevue.config.locale.removeRule : undefined;\n },\n addRuleButtonLabel: function addRuleButtonLabel() {\n return this.$primevue.config.locale ? this.$primevue.config.locale.addRule : undefined;\n },\n isShowAddConstraint: function isShowAddConstraint() {\n return this.showAddButton && this.filters[this.field].operator && this.fieldConstraints && this.fieldConstraints.length < this.maxConstraints;\n },\n clearButtonLabel: function clearButtonLabel() {\n return this.$primevue.config.locale ? this.$primevue.config.locale.clear : undefined;\n },\n applyButtonLabel: function applyButtonLabel() {\n return this.$primevue.config.locale ? this.$primevue.config.locale.apply : undefined;\n },\n columnFilterButtonAriaLabel: function columnFilterButtonAriaLabel() {\n return this.$primevue.config.locale ? this.overlayVisible ? this.$primevue.config.locale.showFilterMenu : this.$primevue.config.locale.hideFilterMenu : undefined;\n },\n filterOperatorAriaLabel: function filterOperatorAriaLabel() {\n return this.$primevue.config.locale ? this.$primevue.config.locale.filterOperator : undefined;\n },\n filterRuleAriaLabel: function filterRuleAriaLabel() {\n return this.$primevue.config.locale ? this.$primevue.config.locale.filterConstraint : undefined;\n },\n ptmHeaderFilterClearParams: function ptmHeaderFilterClearParams() {\n return {\n context: {\n hidden: this.hasRowFilter()\n }\n };\n },\n ptmFilterMenuParams: function ptmFilterMenuParams() {\n return {\n context: {\n overlayVisible: this.overlayVisible,\n active: this.hasFilter()\n }\n };\n }\n },\n components: {\n Select: Select,\n Button: Button,\n Portal: Portal,\n FilterSlashIcon: FilterSlashIcon,\n FilterIcon: FilterIcon,\n TrashIcon: TrashIcon,\n PlusIcon: PlusIcon\n },\n directives: {\n focustrap: FocusTrap\n }\n};\n\nfunction _typeof$4(o) { \"@babel/helpers - typeof\"; return _typeof$4 = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof$4(o); }\nfunction ownKeys$4(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread$4(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$4(Object(t), !0).forEach(function (r) { _defineProperty$4(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$4(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty$4(e, r, t) { return (r = _toPropertyKey$4(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }\nfunction _toPropertyKey$4(t) { var i = _toPrimitive$4(t, \"string\"); return \"symbol\" == _typeof$4(i) ? i : i + \"\"; }\nfunction _toPrimitive$4(t, r) { if (\"object\" != _typeof$4(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof$4(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nvar _hoisted_1$1 = [\"id\", \"aria-modal\"];\nvar _hoisted_2 = [\"onClick\", \"onKeydown\", \"tabindex\"];\nfunction render$4(_ctx, _cache, $props, $setup, $data, $options) {\n var _component_Button = resolveComponent(\"Button\");\n var _component_Select = resolveComponent(\"Select\");\n var _component_Portal = resolveComponent(\"Portal\");\n var _directive_focustrap = resolveDirective(\"focustrap\");\n return openBlock(), createElementBlock(\"div\", mergeProps({\n \"class\": _ctx.cx('filter')\n }, $options.getColumnPT('filter')), [$props.display === 'row' ? (openBlock(), createElementBlock(\"div\", mergeProps({\n key: 0,\n \"class\": _ctx.cx('filterElementContainer')\n }, _objectSpread$4(_objectSpread$4({}, $props.filterInputProps), $options.getColumnPT('filterElementContainer'))), [(openBlock(), createBlock(resolveDynamicComponent($props.filterElement), {\n field: $props.field,\n filterModel: $props.filters[$props.field],\n filterCallback: $options.filterCallback\n }, null, 8, [\"field\", \"filterModel\", \"filterCallback\"]))], 16)) : createCommentVNode(\"\", true), $options.showMenuButton ? (openBlock(), createBlock(_component_Button, mergeProps({\n key: 1,\n ref: \"icon\",\n \"aria-label\": $options.columnFilterButtonAriaLabel,\n \"aria-haspopup\": \"true\",\n \"aria-expanded\": $data.overlayVisible,\n \"aria-controls\": $options.overlayId,\n \"class\": _ctx.cx('pcColumnFilterButton'),\n unstyled: _ctx.unstyled,\n onClick: _cache[0] || (_cache[0] = function ($event) {\n return $options.toggleMenu($event);\n }),\n onKeydown: _cache[1] || (_cache[1] = function ($event) {\n return $options.onToggleButtonKeyDown($event);\n })\n }, _objectSpread$4(_objectSpread$4({}, $options.getColumnPT('pcColumnFilterButton', $options.ptmFilterMenuParams)), $props.filterButtonProps.filter)), {\n icon: withCtx(function (slotProps) {\n return [(openBlock(), createBlock(resolveDynamicComponent($props.filterIconTemplate || 'FilterIcon'), mergeProps({\n \"class\": slotProps[\"class\"]\n }, $options.getColumnPT('filterMenuIcon')), null, 16, [\"class\"]))];\n }),\n _: 1\n }, 16, [\"aria-label\", \"aria-expanded\", \"aria-controls\", \"class\", \"unstyled\"])) : createCommentVNode(\"\", true), $props.showClearButton && $props.display === 'row' && $options.hasRowFilter() ? (openBlock(), createBlock(_component_Button, mergeProps({\n key: 2,\n \"class\": _ctx.cx('pcColumnFilterClearButton'),\n unstyled: _ctx.unstyled,\n onClick: _cache[2] || (_cache[2] = function ($event) {\n return $options.clearFilter();\n })\n }, _objectSpread$4(_objectSpread$4({}, $options.getColumnPT('pcColumnFilterClearButton', $options.ptmHeaderFilterClearParams)), $props.filterButtonProps.inline.clear)), {\n icon: withCtx(function (slotProps) {\n return [(openBlock(), createBlock(resolveDynamicComponent($props.filterClearIconTemplate || 'FilterSlashIcon'), mergeProps({\n \"class\": slotProps[\"class\"]\n }, $options.getColumnPT('filterClearIcon')), null, 16, [\"class\"]))];\n }),\n _: 1\n }, 16, [\"class\", \"unstyled\"])) : createCommentVNode(\"\", true), createVNode(_component_Portal, null, {\n \"default\": withCtx(function () {\n return [createVNode(Transition, mergeProps({\n name: \"p-connected-overlay\",\n onEnter: $options.onOverlayEnter,\n onAfterEnter: $options.onOverlayAfterEnter,\n onLeave: $options.onOverlayLeave,\n onAfterLeave: $options.onOverlayAfterLeave\n }, $options.getColumnPT('transition')), {\n \"default\": withCtx(function () {\n return [$data.overlayVisible ? withDirectives((openBlock(), createElementBlock(\"div\", mergeProps({\n key: 0,\n ref: $options.overlayRef,\n id: $options.overlayId,\n \"aria-modal\": $data.overlayVisible,\n role: \"dialog\",\n \"class\": [_ctx.cx('filterOverlay'), $props.filterMenuClass],\n onKeydown: _cache[10] || (_cache[10] = withKeys(function () {\n return $options.hide && $options.hide.apply($options, arguments);\n }, [\"escape\"])),\n onClick: _cache[11] || (_cache[11] = function () {\n return $options.onContentClick && $options.onContentClick.apply($options, arguments);\n }),\n onMousedown: _cache[12] || (_cache[12] = function () {\n return $options.onContentMouseDown && $options.onContentMouseDown.apply($options, arguments);\n })\n }, $options.getColumnPT('filterOverlay')), [(openBlock(), createBlock(resolveDynamicComponent($props.filterHeaderTemplate), {\n field: $props.field,\n filterModel: $props.filters[$props.field],\n filterCallback: $options.filterCallback\n }, null, 8, [\"field\", \"filterModel\", \"filterCallback\"])), $props.display === 'row' ? (openBlock(), createElementBlock(\"ul\", mergeProps({\n key: 0,\n \"class\": _ctx.cx('filterConstraintList')\n }, $options.getColumnPT('filterConstraintList')), [(openBlock(true), createElementBlock(Fragment, null, renderList($options.matchModes, function (matchMode, i) {\n return openBlock(), createElementBlock(\"li\", mergeProps({\n key: matchMode.label,\n \"class\": _ctx.cx('filterConstraint', {\n matchMode: matchMode\n }),\n onClick: function onClick($event) {\n return $options.onRowMatchModeChange(matchMode.value);\n },\n onKeydown: [_cache[3] || (_cache[3] = function ($event) {\n return $options.onRowMatchModeKeyDown($event);\n }), withKeys(withModifiers(function ($event) {\n return $options.onRowMatchModeChange(matchMode.value);\n }, [\"prevent\"]), [\"enter\"])],\n tabindex: i === 0 ? '0' : null,\n ref_for: true\n }, $options.getColumnPT('filterConstraint', $options.ptmFilterConstraintOptions(matchMode))), toDisplayString(matchMode.label), 17, _hoisted_2);\n }), 128)), createElementVNode(\"li\", mergeProps({\n \"class\": _ctx.cx('filterConstraintSeparator')\n }, $options.getColumnPT('filterConstraintSeparator')), null, 16), createElementVNode(\"li\", mergeProps({\n \"class\": _ctx.cx('filterConstraint'),\n onClick: _cache[4] || (_cache[4] = function ($event) {\n return $options.clearFilter();\n }),\n onKeydown: [_cache[5] || (_cache[5] = function ($event) {\n return $options.onRowMatchModeKeyDown($event);\n }), _cache[6] || (_cache[6] = withKeys(function ($event) {\n return _ctx.onRowClearItemClick();\n }, [\"enter\"]))]\n }, $options.getColumnPT('filterConstraint')), toDisplayString($options.noFilterLabel), 17)], 16)) : (openBlock(), createElementBlock(Fragment, {\n key: 1\n }, [$options.isShowOperator ? (openBlock(), createElementBlock(\"div\", mergeProps({\n key: 0,\n \"class\": _ctx.cx('filterOperator')\n }, $options.getColumnPT('filterOperator')), [createVNode(_component_Select, {\n options: $options.operatorOptions,\n modelValue: $options.operator,\n \"aria-label\": $options.filterOperatorAriaLabel,\n \"class\": normalizeClass(_ctx.cx('pcFilterOperatorDropdown')),\n optionLabel: \"label\",\n optionValue: \"value\",\n \"onUpdate:modelValue\": _cache[7] || (_cache[7] = function ($event) {\n return $options.onOperatorChange($event);\n }),\n unstyled: _ctx.unstyled,\n pt: $options.getColumnPT('pcFilterOperatorDropdown')\n }, null, 8, [\"options\", \"modelValue\", \"aria-label\", \"class\", \"unstyled\", \"pt\"])], 16)) : createCommentVNode(\"\", true), createElementVNode(\"div\", mergeProps({\n \"class\": _ctx.cx('filterRuleList')\n }, $options.getColumnPT('filterRuleList')), [(openBlock(true), createElementBlock(Fragment, null, renderList($options.fieldConstraints, function (fieldConstraint, i) {\n return openBlock(), createElementBlock(\"div\", mergeProps({\n key: i,\n \"class\": _ctx.cx('filterRule'),\n ref_for: true\n }, $options.getColumnPT('filterRule')), [$options.isShowMatchModes ? (openBlock(), createBlock(_component_Select, {\n key: 0,\n options: $options.matchModes,\n modelValue: fieldConstraint.matchMode,\n \"class\": normalizeClass(_ctx.cx('pcFilterConstraintDropdown')),\n optionLabel: \"label\",\n optionValue: \"value\",\n \"aria-label\": $options.filterRuleAriaLabel,\n \"onUpdate:modelValue\": function onUpdateModelValue($event) {\n return $options.onMenuMatchModeChange($event, i);\n },\n unstyled: _ctx.unstyled,\n pt: $options.getColumnPT('pcFilterConstraintDropdown')\n }, null, 8, [\"options\", \"modelValue\", \"class\", \"aria-label\", \"onUpdate:modelValue\", \"unstyled\", \"pt\"])) : createCommentVNode(\"\", true), $props.display === 'menu' ? (openBlock(), createBlock(resolveDynamicComponent($props.filterElement), {\n key: 1,\n field: $props.field,\n filterModel: fieldConstraint,\n filterCallback: $options.filterCallback,\n applyFilter: $options.applyFilter\n }, null, 8, [\"field\", \"filterModel\", \"filterCallback\", \"applyFilter\"])) : createCommentVNode(\"\", true), $options.showRemoveIcon ? (openBlock(), createElementBlock(\"div\", mergeProps({\n key: 2,\n ref_for: true\n }, $options.getColumnPT('filterRemove')), [createVNode(_component_Button, mergeProps({\n type: \"button\",\n \"class\": _ctx.cx('pcFilterRemoveRuleButton'),\n onClick: function onClick($event) {\n return $options.removeConstraint(i);\n },\n label: $options.removeRuleButtonLabel,\n unstyled: _ctx.unstyled,\n ref_for: true\n }, $props.filterButtonProps.popover.removeRule, {\n pt: $options.getColumnPT('pcFilterRemoveRuleButton')\n }), {\n icon: withCtx(function (iconProps) {\n return [(openBlock(), createBlock(resolveDynamicComponent($props.filterRemoveIconTemplate || 'TrashIcon'), mergeProps({\n \"class\": iconProps[\"class\"],\n ref_for: true\n }, $options.getColumnPT('pcFilterRemoveRuleButton')['icon']), null, 16, [\"class\"]))];\n }),\n _: 2\n }, 1040, [\"class\", \"onClick\", \"label\", \"unstyled\", \"pt\"])], 16)) : createCommentVNode(\"\", true)], 16);\n }), 128))], 16), $options.isShowAddConstraint ? (openBlock(), createElementBlock(\"div\", normalizeProps(mergeProps({\n key: 1\n }, $options.getColumnPT('filterAddButtonContainer'))), [createVNode(_component_Button, mergeProps({\n type: \"button\",\n label: $options.addRuleButtonLabel,\n iconPos: \"left\",\n \"class\": _ctx.cx('pcFilterAddRuleButton'),\n onClick: _cache[8] || (_cache[8] = function ($event) {\n return $options.addConstraint();\n }),\n unstyled: _ctx.unstyled\n }, $props.filterButtonProps.popover.addRule, {\n pt: $options.getColumnPT('pcFilterAddRuleButton')\n }), {\n icon: withCtx(function (iconProps) {\n return [(openBlock(), createBlock(resolveDynamicComponent($props.filterAddIconTemplate || 'PlusIcon'), mergeProps({\n \"class\": iconProps[\"class\"]\n }, $options.getColumnPT('pcFilterAddRuleButton')['icon']), null, 16, [\"class\"]))];\n }),\n _: 1\n }, 16, [\"label\", \"class\", \"unstyled\", \"pt\"])], 16)) : createCommentVNode(\"\", true), createElementVNode(\"div\", mergeProps({\n \"class\": _ctx.cx('filterButtonbar')\n }, $options.getColumnPT('filterButtonbar')), [!$props.filterClearTemplate && $props.showClearButton ? (openBlock(), createBlock(_component_Button, mergeProps({\n key: 0,\n type: \"button\",\n \"class\": _ctx.cx('pcFilterClearButton'),\n label: $options.clearButtonLabel,\n onClick: $options.clearFilter,\n unstyled: _ctx.unstyled\n }, $props.filterButtonProps.popover.clear, {\n pt: $options.getColumnPT('pcFilterClearButton')\n }), null, 16, [\"class\", \"label\", \"onClick\", \"unstyled\", \"pt\"])) : (openBlock(), createBlock(resolveDynamicComponent($props.filterClearTemplate), {\n key: 1,\n field: $props.field,\n filterModel: $props.filters[$props.field],\n filterCallback: $options.clearFilter\n }, null, 8, [\"field\", \"filterModel\", \"filterCallback\"])), $props.showApplyButton ? (openBlock(), createElementBlock(Fragment, {\n key: 2\n }, [!$props.filterApplyTemplate ? (openBlock(), createBlock(_component_Button, mergeProps({\n key: 0,\n type: \"button\",\n \"class\": _ctx.cx('pcFilterApplyButton'),\n label: $options.applyButtonLabel,\n onClick: _cache[9] || (_cache[9] = function ($event) {\n return $options.applyFilter();\n }),\n unstyled: _ctx.unstyled\n }, $props.filterButtonProps.popover.apply, {\n pt: $options.getColumnPT('pcFilterApplyButton')\n }), null, 16, [\"class\", \"label\", \"unstyled\", \"pt\"])) : (openBlock(), createBlock(resolveDynamicComponent($props.filterApplyTemplate), {\n key: 1,\n field: $props.field,\n filterModel: $props.filters[$props.field],\n filterCallback: $options.applyFilter\n }, null, 8, [\"field\", \"filterModel\", \"filterCallback\"]))], 64)) : createCommentVNode(\"\", true)], 16)], 64)), (openBlock(), createBlock(resolveDynamicComponent($props.filterFooterTemplate), {\n field: $props.field,\n filterModel: $props.filters[$props.field],\n filterCallback: $options.filterCallback\n }, null, 8, [\"field\", \"filterModel\", \"filterCallback\"]))], 16, _hoisted_1$1)), [[_directive_focustrap]]) : createCommentVNode(\"\", true)];\n }),\n _: 1\n }, 16, [\"onEnter\", \"onAfterEnter\", \"onLeave\", \"onAfterLeave\"])];\n }),\n _: 1\n })], 16);\n}\n\nscript$4.render = render$4;\n\nvar script$3 = {\n name: 'HeaderCheckbox',\n hostName: 'DataTable',\n \"extends\": BaseComponent,\n emits: ['change'],\n props: {\n checked: null,\n disabled: null,\n column: null,\n headerCheckboxIconTemplate: {\n type: Function,\n \"default\": null\n }\n },\n methods: {\n getColumnPT: function getColumnPT(key) {\n var columnMetaData = {\n props: this.column.props,\n parent: {\n instance: this,\n props: this.$props,\n state: this.$data\n },\n context: {\n checked: this.checked,\n disabled: this.disabled\n }\n };\n return mergeProps(this.ptm(\"column.\".concat(key), {\n column: columnMetaData\n }), this.ptm(\"column.\".concat(key), columnMetaData), this.ptmo(this.getColumnProp(), key, columnMetaData));\n },\n getColumnProp: function getColumnProp() {\n return this.column.props && this.column.props.pt ? this.column.props.pt : undefined; //@todo:\n },\n onChange: function onChange(event) {\n this.$emit('change', {\n originalEvent: event,\n checked: !this.checked\n });\n }\n },\n computed: {\n headerCheckboxAriaLabel: function headerCheckboxAriaLabel() {\n return this.$primevue.config.locale.aria ? this.checked ? this.$primevue.config.locale.aria.selectAll : this.$primevue.config.locale.aria.unselectAll : undefined;\n }\n },\n components: {\n CheckIcon: CheckIcon,\n Checkbox: Checkbox\n }\n};\n\nfunction render$3(_ctx, _cache, $props, $setup, $data, $options) {\n var _component_CheckIcon = resolveComponent(\"CheckIcon\");\n var _component_Checkbox = resolveComponent(\"Checkbox\");\n return openBlock(), createBlock(_component_Checkbox, {\n modelValue: $props.checked,\n binary: true,\n disabled: $props.disabled,\n \"aria-label\": $options.headerCheckboxAriaLabel,\n onChange: $options.onChange,\n pt: $options.getColumnPT('pcHeaderCheckbox')\n }, {\n icon: withCtx(function (slotProps) {\n return [$props.headerCheckboxIconTemplate ? (openBlock(), createBlock(resolveDynamicComponent($props.headerCheckboxIconTemplate), {\n key: 0,\n checked: slotProps.checked,\n \"class\": normalizeClass(slotProps[\"class\"])\n }, null, 8, [\"checked\", \"class\"])) : !$props.headerCheckboxIconTemplate && slotProps.checked ? (openBlock(), createBlock(_component_CheckIcon, mergeProps({\n key: 1,\n \"class\": slotProps[\"class\"]\n }, $options.getColumnPT('pcHeaderCheckbox.icon')), null, 16, [\"class\"])) : createCommentVNode(\"\", true)];\n }),\n _: 1\n }, 8, [\"modelValue\", \"disabled\", \"aria-label\", \"onChange\", \"pt\"]);\n}\n\nscript$3.render = render$3;\n\nvar script$2 = {\n name: 'HeaderCell',\n hostName: 'DataTable',\n \"extends\": BaseComponent,\n emits: ['column-click', 'column-mousedown', 'column-dragstart', 'column-dragover', 'column-dragleave', 'column-drop', 'column-resizestart', 'checkbox-change', 'filter-change', 'filter-apply', 'operator-change', 'matchmode-change', 'constraint-add', 'constraint-remove', 'filter-clear', 'apply-click'],\n props: {\n column: {\n type: Object,\n \"default\": null\n },\n index: {\n type: Number,\n \"default\": null\n },\n resizableColumns: {\n type: Boolean,\n \"default\": false\n },\n groupRowsBy: {\n type: [Array, String, Function],\n \"default\": null\n },\n sortMode: {\n type: String,\n \"default\": 'single'\n },\n groupRowSortField: {\n type: [String, Function],\n \"default\": null\n },\n sortField: {\n type: [String, Function],\n \"default\": null\n },\n sortOrder: {\n type: Number,\n \"default\": null\n },\n multiSortMeta: {\n type: Array,\n \"default\": null\n },\n allRowsSelected: {\n type: Boolean,\n \"default\": false\n },\n empty: {\n type: Boolean,\n \"default\": false\n },\n filterDisplay: {\n type: String,\n \"default\": null\n },\n filters: {\n type: Object,\n \"default\": null\n },\n filtersStore: {\n type: Object,\n \"default\": null\n },\n filterColumn: {\n type: Boolean,\n \"default\": false\n },\n reorderableColumns: {\n type: Boolean,\n \"default\": false\n },\n filterInputProps: {\n type: null,\n \"default\": null\n },\n filterButtonProps: {\n type: null,\n \"default\": null\n }\n },\n data: function data() {\n return {\n styleObject: {}\n };\n },\n mounted: function mounted() {\n if (this.columnProp('frozen')) {\n this.updateStickyPosition();\n }\n },\n updated: function updated() {\n if (this.columnProp('frozen')) {\n this.updateStickyPosition();\n }\n },\n methods: {\n columnProp: function columnProp(prop) {\n return getVNodeProp(this.column, prop);\n },\n getColumnPT: function getColumnPT(key) {\n var _this$$parentInstance, _this$$parentInstance2;\n var columnMetaData = {\n props: this.column.props,\n parent: {\n instance: this,\n props: this.$props,\n state: this.$data\n },\n context: {\n index: this.index,\n sortable: this.columnProp('sortable') === '' || this.columnProp('sortable'),\n sorted: this.isColumnSorted(),\n resizable: this.resizableColumns,\n size: (_this$$parentInstance = this.$parentInstance) === null || _this$$parentInstance === void 0 || (_this$$parentInstance = _this$$parentInstance.$parentInstance) === null || _this$$parentInstance === void 0 ? void 0 : _this$$parentInstance.size,\n showGridlines: ((_this$$parentInstance2 = this.$parentInstance) === null || _this$$parentInstance2 === void 0 || (_this$$parentInstance2 = _this$$parentInstance2.$parentInstance) === null || _this$$parentInstance2 === void 0 ? void 0 : _this$$parentInstance2.showGridlines) || false\n }\n };\n return mergeProps(this.ptm(\"column.\".concat(key), {\n column: columnMetaData\n }), this.ptm(\"column.\".concat(key), columnMetaData), this.ptmo(this.getColumnProp(), key, columnMetaData));\n },\n getColumnProp: function getColumnProp() {\n return this.column.props && this.column.props.pt ? this.column.props.pt : undefined; //@todo:\n },\n onClick: function onClick(event) {\n this.$emit('column-click', {\n originalEvent: event,\n column: this.column\n });\n },\n onKeyDown: function onKeyDown(event) {\n if ((event.code === 'Enter' || event.code === 'NumpadEnter' || event.code === 'Space') && event.currentTarget.nodeName === 'TH' && getAttribute(event.currentTarget, 'data-p-sortable-column')) {\n this.$emit('column-click', {\n originalEvent: event,\n column: this.column\n });\n event.preventDefault();\n }\n },\n onMouseDown: function onMouseDown(event) {\n this.$emit('column-mousedown', {\n originalEvent: event,\n column: this.column\n });\n },\n onDragStart: function onDragStart(event) {\n this.$emit('column-dragstart', {\n originalEvent: event,\n column: this.column\n });\n },\n onDragOver: function onDragOver(event) {\n this.$emit('column-dragover', {\n originalEvent: event,\n column: this.column\n });\n },\n onDragLeave: function onDragLeave(event) {\n this.$emit('column-dragleave', {\n originalEvent: event,\n column: this.column\n });\n },\n onDrop: function onDrop(event) {\n this.$emit('column-drop', {\n originalEvent: event,\n column: this.column\n });\n },\n onResizeStart: function onResizeStart(event) {\n this.$emit('column-resizestart', event);\n },\n getMultiSortMetaIndex: function getMultiSortMetaIndex() {\n var _this = this;\n return this.multiSortMeta.findIndex(function (meta) {\n return meta.field === _this.columnProp('field') || meta.field === _this.columnProp('sortField');\n });\n },\n getBadgeValue: function getBadgeValue() {\n var index = this.getMultiSortMetaIndex();\n return this.groupRowsBy && this.groupRowsBy === this.groupRowSortField && index > -1 ? index : index + 1;\n },\n isMultiSorted: function isMultiSorted() {\n return this.sortMode === 'multiple' && this.columnProp('sortable') && this.getMultiSortMetaIndex() > -1;\n },\n isColumnSorted: function isColumnSorted() {\n return this.sortMode === 'single' ? this.sortField && (this.sortField === this.columnProp('field') || this.sortField === this.columnProp('sortField')) : this.isMultiSorted();\n },\n updateStickyPosition: function updateStickyPosition() {\n if (this.columnProp('frozen')) {\n var align = this.columnProp('alignFrozen');\n if (align === 'right') {\n var right = 0;\n var next = getNextElementSibling(this.$el, '[data-p-frozen-column=\"true\"]');\n if (next) {\n right = getOuterWidth(next) + parseFloat(next.style.right || 0);\n }\n this.styleObject.right = right + 'px';\n } else {\n var left = 0;\n var prev = getPreviousElementSibling(this.$el, '[data-p-frozen-column=\"true\"]');\n if (prev) {\n left = getOuterWidth(prev) + parseFloat(prev.style.left || 0);\n }\n this.styleObject.left = left + 'px';\n }\n var filterRow = this.$el.parentElement.nextElementSibling;\n if (filterRow) {\n var index = getIndex(this.$el);\n if (filterRow.children[index]) {\n filterRow.children[index].style.left = this.styleObject.left;\n filterRow.children[index].style.right = this.styleObject.right;\n }\n }\n }\n },\n onHeaderCheckboxChange: function onHeaderCheckboxChange(event) {\n this.$emit('checkbox-change', event);\n }\n },\n computed: {\n containerClass: function containerClass() {\n return [this.cx('headerCell'), this.filterColumn ? this.columnProp('filterHeaderClass') : this.columnProp('headerClass'), this.columnProp('class')];\n },\n containerStyle: function containerStyle() {\n var headerStyle = this.filterColumn ? this.columnProp('filterHeaderStyle') : this.columnProp('headerStyle');\n var columnStyle = this.columnProp('style');\n return this.columnProp('frozen') ? [columnStyle, headerStyle, this.styleObject] : [columnStyle, headerStyle];\n },\n sortState: function sortState() {\n var sorted = false;\n var sortOrder = null;\n if (this.sortMode === 'single') {\n sorted = this.sortField && (this.sortField === this.columnProp('field') || this.sortField === this.columnProp('sortField'));\n sortOrder = sorted ? this.sortOrder : 0;\n } else if (this.sortMode === 'multiple') {\n var metaIndex = this.getMultiSortMetaIndex();\n if (metaIndex > -1) {\n sorted = true;\n sortOrder = this.multiSortMeta[metaIndex].order;\n }\n }\n return {\n sorted: sorted,\n sortOrder: sortOrder\n };\n },\n sortableColumnIcon: function sortableColumnIcon() {\n var _this$sortState = this.sortState,\n sorted = _this$sortState.sorted,\n sortOrder = _this$sortState.sortOrder;\n if (!sorted) return SortAltIcon;else if (sorted && sortOrder > 0) return SortAmountUpAltIcon;else if (sorted && sortOrder < 0) return SortAmountDownIcon;\n return null;\n },\n ariaSort: function ariaSort() {\n if (this.columnProp('sortable')) {\n var _this$sortState2 = this.sortState,\n sorted = _this$sortState2.sorted,\n sortOrder = _this$sortState2.sortOrder;\n if (sorted && sortOrder < 0) return 'descending';else if (sorted && sortOrder > 0) return 'ascending';else return 'none';\n } else {\n return null;\n }\n }\n },\n components: {\n Badge: Badge,\n DTHeaderCheckbox: script$3,\n DTColumnFilter: script$4,\n SortAltIcon: SortAltIcon,\n SortAmountUpAltIcon: SortAmountUpAltIcon,\n SortAmountDownIcon: SortAmountDownIcon\n }\n};\n\nfunction _typeof$3(o) { \"@babel/helpers - typeof\"; return _typeof$3 = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof$3(o); }\nfunction ownKeys$3(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread$3(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$3(Object(t), !0).forEach(function (r) { _defineProperty$3(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$3(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty$3(e, r, t) { return (r = _toPropertyKey$3(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }\nfunction _toPropertyKey$3(t) { var i = _toPrimitive$3(t, \"string\"); return \"symbol\" == _typeof$3(i) ? i : i + \"\"; }\nfunction _toPrimitive$3(t, r) { if (\"object\" != _typeof$3(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof$3(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nvar _hoisted_1 = [\"tabindex\", \"colspan\", \"rowspan\", \"aria-sort\", \"data-p-sortable-column\", \"data-p-resizable-column\", \"data-p-sorted\", \"data-p-filter-column\", \"data-p-frozen-column\", \"data-p-reorderable-column\"];\nfunction render$2(_ctx, _cache, $props, $setup, $data, $options) {\n var _component_Badge = resolveComponent(\"Badge\");\n var _component_DTHeaderCheckbox = resolveComponent(\"DTHeaderCheckbox\");\n var _component_DTColumnFilter = resolveComponent(\"DTColumnFilter\");\n return openBlock(), createElementBlock(\"th\", mergeProps({\n style: $options.containerStyle,\n \"class\": $options.containerClass,\n tabindex: $options.columnProp('sortable') ? '0' : null,\n role: \"columnheader\",\n colspan: $options.columnProp('colspan'),\n rowspan: $options.columnProp('rowspan'),\n \"aria-sort\": $options.ariaSort,\n onClick: _cache[8] || (_cache[8] = function () {\n return $options.onClick && $options.onClick.apply($options, arguments);\n }),\n onKeydown: _cache[9] || (_cache[9] = function () {\n return $options.onKeyDown && $options.onKeyDown.apply($options, arguments);\n }),\n onMousedown: _cache[10] || (_cache[10] = function () {\n return $options.onMouseDown && $options.onMouseDown.apply($options, arguments);\n }),\n onDragstart: _cache[11] || (_cache[11] = function () {\n return $options.onDragStart && $options.onDragStart.apply($options, arguments);\n }),\n onDragover: _cache[12] || (_cache[12] = function () {\n return $options.onDragOver && $options.onDragOver.apply($options, arguments);\n }),\n onDragleave: _cache[13] || (_cache[13] = function () {\n return $options.onDragLeave && $options.onDragLeave.apply($options, arguments);\n }),\n onDrop: _cache[14] || (_cache[14] = function () {\n return $options.onDrop && $options.onDrop.apply($options, arguments);\n })\n }, _objectSpread$3(_objectSpread$3({}, $options.getColumnPT('root')), $options.getColumnPT('headerCell')), {\n \"data-p-sortable-column\": $options.columnProp('sortable'),\n \"data-p-resizable-column\": $props.resizableColumns,\n \"data-p-sorted\": $options.isColumnSorted(),\n \"data-p-filter-column\": $props.filterColumn,\n \"data-p-frozen-column\": $options.columnProp('frozen'),\n \"data-p-reorderable-column\": $props.reorderableColumns\n }), [$props.resizableColumns && !$options.columnProp('frozen') ? (openBlock(), createElementBlock(\"span\", mergeProps({\n key: 0,\n \"class\": _ctx.cx('columnResizer'),\n onMousedown: _cache[0] || (_cache[0] = function () {\n return $options.onResizeStart && $options.onResizeStart.apply($options, arguments);\n })\n }, $options.getColumnPT('columnResizer')), null, 16)) : createCommentVNode(\"\", true), createElementVNode(\"div\", mergeProps({\n \"class\": _ctx.cx('columnHeaderContent')\n }, $options.getColumnPT('columnHeaderContent')), [$props.column.children && $props.column.children.header ? (openBlock(), createBlock(resolveDynamicComponent($props.column.children.header), {\n key: 0,\n column: $props.column\n }, null, 8, [\"column\"])) : createCommentVNode(\"\", true), $options.columnProp('header') ? (openBlock(), createElementBlock(\"span\", mergeProps({\n key: 1,\n \"class\": _ctx.cx('columnTitle')\n }, $options.getColumnPT('columnTitle')), toDisplayString($options.columnProp('header')), 17)) : createCommentVNode(\"\", true), $options.columnProp('sortable') ? (openBlock(), createElementBlock(\"span\", normalizeProps(mergeProps({\n key: 2\n }, $options.getColumnPT('sort'))), [(openBlock(), createBlock(resolveDynamicComponent($props.column.children && $props.column.children.sorticon || $options.sortableColumnIcon), mergeProps({\n sorted: $options.sortState.sorted,\n sortOrder: $options.sortState.sortOrder,\n \"class\": _ctx.cx('sortIcon')\n }, $options.getColumnPT('sorticon')), null, 16, [\"sorted\", \"sortOrder\", \"class\"]))], 16)) : createCommentVNode(\"\", true), $options.isMultiSorted() ? (openBlock(), createBlock(_component_Badge, mergeProps({\n key: 3,\n \"class\": _ctx.cx('pcSortBadge')\n }, $options.getColumnPT('pcSortBadge'), {\n value: $options.getBadgeValue(),\n size: \"small\"\n }), null, 16, [\"class\", \"value\"])) : createCommentVNode(\"\", true), $options.columnProp('selectionMode') === 'multiple' && $props.filterDisplay !== 'row' ? (openBlock(), createBlock(_component_DTHeaderCheckbox, {\n key: 4,\n checked: $props.allRowsSelected,\n onChange: $options.onHeaderCheckboxChange,\n disabled: $props.empty,\n headerCheckboxIconTemplate: $props.column.children && $props.column.children.headercheckboxicon,\n column: $props.column,\n unstyled: _ctx.unstyled,\n pt: _ctx.pt\n }, null, 8, [\"checked\", \"onChange\", \"disabled\", \"headerCheckboxIconTemplate\", \"column\", \"unstyled\", \"pt\"])) : createCommentVNode(\"\", true), $props.filterDisplay === 'menu' && $props.column.children && $props.column.children.filter ? (openBlock(), createBlock(_component_DTColumnFilter, {\n key: 5,\n field: $options.columnProp('filterField') || $options.columnProp('field'),\n type: $options.columnProp('dataType'),\n display: \"menu\",\n showMenu: $options.columnProp('showFilterMenu'),\n filterElement: $props.column.children && $props.column.children.filter,\n filterHeaderTemplate: $props.column.children && $props.column.children.filterheader,\n filterFooterTemplate: $props.column.children && $props.column.children.filterfooter,\n filterClearTemplate: $props.column.children && $props.column.children.filterclear,\n filterApplyTemplate: $props.column.children && $props.column.children.filterapply,\n filterIconTemplate: $props.column.children && $props.column.children.filtericon,\n filterAddIconTemplate: $props.column.children && $props.column.children.filteraddicon,\n filterRemoveIconTemplate: $props.column.children && $props.column.children.filterremoveicon,\n filterClearIconTemplate: $props.column.children && $props.column.children.filterclearicon,\n filters: $props.filters,\n filtersStore: $props.filtersStore,\n filterInputProps: $props.filterInputProps,\n filterButtonProps: $props.filterButtonProps,\n onFilterChange: _cache[1] || (_cache[1] = function ($event) {\n return _ctx.$emit('filter-change', $event);\n }),\n onFilterApply: _cache[2] || (_cache[2] = function ($event) {\n return _ctx.$emit('filter-apply');\n }),\n filterMenuStyle: $options.columnProp('filterMenuStyle'),\n filterMenuClass: $options.columnProp('filterMenuClass'),\n showOperator: $options.columnProp('showFilterOperator'),\n showClearButton: $options.columnProp('showClearButton'),\n showApplyButton: $options.columnProp('showApplyButton'),\n showMatchModes: $options.columnProp('showFilterMatchModes'),\n showAddButton: $options.columnProp('showAddButton'),\n matchModeOptions: $options.columnProp('filterMatchModeOptions'),\n maxConstraints: $options.columnProp('maxConstraints'),\n onOperatorChange: _cache[3] || (_cache[3] = function ($event) {\n return _ctx.$emit('operator-change', $event);\n }),\n onMatchmodeChange: _cache[4] || (_cache[4] = function ($event) {\n return _ctx.$emit('matchmode-change', $event);\n }),\n onConstraintAdd: _cache[5] || (_cache[5] = function ($event) {\n return _ctx.$emit('constraint-add', $event);\n }),\n onConstraintRemove: _cache[6] || (_cache[6] = function ($event) {\n return _ctx.$emit('constraint-remove', $event);\n }),\n onApplyClick: _cache[7] || (_cache[7] = function ($event) {\n return _ctx.$emit('apply-click', $event);\n }),\n column: $props.column,\n unstyled: _ctx.unstyled,\n pt: _ctx.pt\n }, null, 8, [\"field\", \"type\", \"showMenu\", \"filterElement\", \"filterHeaderTemplate\", \"filterFooterTemplate\", \"filterClearTemplate\", \"filterApplyTemplate\", \"filterIconTemplate\", \"filterAddIconTemplate\", \"filterRemoveIconTemplate\", \"filterClearIconTemplate\", \"filters\", \"filtersStore\", \"filterInputProps\", \"filterButtonProps\", \"filterMenuStyle\", \"filterMenuClass\", \"showOperator\", \"showClearButton\", \"showApplyButton\", \"showMatchModes\", \"showAddButton\", \"matchModeOptions\", \"maxConstraints\", \"column\", \"unstyled\", \"pt\"])) : createCommentVNode(\"\", true)], 16)], 16, _hoisted_1);\n}\n\nscript$2.render = render$2;\n\nvar script$1 = {\n name: 'TableHeader',\n hostName: 'DataTable',\n \"extends\": BaseComponent,\n emits: ['column-click', 'column-mousedown', 'column-dragstart', 'column-dragover', 'column-dragleave', 'column-drop', 'column-resizestart', 'checkbox-change', 'filter-change', 'filter-apply', 'operator-change', 'matchmode-change', 'constraint-add', 'constraint-remove', 'filter-clear', 'apply-click'],\n props: {\n columnGroup: {\n type: null,\n \"default\": null\n },\n columns: {\n type: null,\n \"default\": null\n },\n rowGroupMode: {\n type: String,\n \"default\": null\n },\n groupRowsBy: {\n type: [Array, String, Function],\n \"default\": null\n },\n resizableColumns: {\n type: Boolean,\n \"default\": false\n },\n allRowsSelected: {\n type: Boolean,\n \"default\": false\n },\n empty: {\n type: Boolean,\n \"default\": false\n },\n sortMode: {\n type: String,\n \"default\": 'single'\n },\n groupRowSortField: {\n type: [String, Function],\n \"default\": null\n },\n sortField: {\n type: [String, Function],\n \"default\": null\n },\n sortOrder: {\n type: Number,\n \"default\": null\n },\n multiSortMeta: {\n type: Array,\n \"default\": null\n },\n filterDisplay: {\n type: String,\n \"default\": null\n },\n filters: {\n type: Object,\n \"default\": null\n },\n filtersStore: {\n type: Object,\n \"default\": null\n },\n reorderableColumns: {\n type: Boolean,\n \"default\": false\n },\n first: {\n type: Number,\n \"default\": 0\n },\n filterInputProps: {\n type: null,\n \"default\": null\n },\n filterButtonProps: {\n type: null,\n \"default\": null\n }\n },\n provide: function provide() {\n return {\n $rows: this.d_headerRows,\n $columns: this.d_headerColumns\n };\n },\n data: function data() {\n return {\n d_headerRows: new HelperSet({\n type: 'Row'\n }),\n d_headerColumns: new HelperSet({\n type: 'Column'\n })\n };\n },\n beforeUnmount: function beforeUnmount() {\n this.d_headerRows.clear();\n this.d_headerColumns.clear();\n },\n methods: {\n columnProp: function columnProp(col, prop) {\n return getVNodeProp(col, prop);\n },\n getColumnGroupPT: function getColumnGroupPT(key) {\n var _this$$parentInstance;\n var columnGroupMetaData = {\n props: this.getColumnGroupProps(),\n parent: {\n instance: this,\n props: this.$props,\n state: this.$data\n },\n context: {\n type: 'header',\n scrollable: (_this$$parentInstance = this.$parentInstance) === null || _this$$parentInstance === void 0 || (_this$$parentInstance = _this$$parentInstance.$parentInstance) === null || _this$$parentInstance === void 0 ? void 0 : _this$$parentInstance.scrollable\n }\n };\n return mergeProps(this.ptm(\"columnGroup.\".concat(key), {\n columnGroup: columnGroupMetaData\n }), this.ptm(\"columnGroup.\".concat(key), columnGroupMetaData), this.ptmo(this.getColumnGroupProps(), key, columnGroupMetaData));\n },\n getColumnGroupProps: function getColumnGroupProps() {\n return this.columnGroup && this.columnGroup.props && this.columnGroup.props.pt ? this.columnGroup.props.pt : undefined; //@todo\n },\n getRowPT: function getRowPT(row, key, index) {\n var rowMetaData = {\n props: row.props,\n parent: {\n instance: this,\n props: this.$props,\n state: this.$data\n },\n context: {\n index: index\n }\n };\n return mergeProps(this.ptm(\"row.\".concat(key), {\n row: rowMetaData\n }), this.ptm(\"row.\".concat(key), rowMetaData), this.ptmo(this.getRowProp(row), key, rowMetaData));\n },\n getRowProp: function getRowProp(row) {\n return row.props && row.props.pt ? row.props.pt : undefined; //@todo\n },\n getColumnPT: function getColumnPT(column, key, index) {\n var columnMetaData = {\n props: column.props,\n parent: {\n instance: this,\n props: this.$props,\n state: this.$data\n },\n context: {\n index: index\n }\n };\n return mergeProps(this.ptm(\"column.\".concat(key), {\n column: columnMetaData\n }), this.ptm(\"column.\".concat(key), columnMetaData), this.ptmo(this.getColumnProp(column), key, columnMetaData));\n },\n getColumnProp: function getColumnProp(column) {\n return column.props && column.props.pt ? column.props.pt : undefined; //@todo\n },\n getFilterColumnHeaderClass: function getFilterColumnHeaderClass(column) {\n return [this.cx('headerCell', {\n column: column\n }), this.columnProp(column, 'filterHeaderClass'), this.columnProp(column, 'class')];\n },\n getFilterColumnHeaderStyle: function getFilterColumnHeaderStyle(column) {\n return [this.columnProp(column, 'filterHeaderStyle'), this.columnProp(column, 'style')];\n },\n getHeaderRows: function getHeaderRows() {\n var _this$d_headerRows;\n return (_this$d_headerRows = this.d_headerRows) === null || _this$d_headerRows === void 0 ? void 0 : _this$d_headerRows.get(this.columnGroup, this.columnGroup.children);\n },\n getHeaderColumns: function getHeaderColumns(row) {\n var _this$d_headerColumns;\n return (_this$d_headerColumns = this.d_headerColumns) === null || _this$d_headerColumns === void 0 ? void 0 : _this$d_headerColumns.get(row, row.children);\n }\n },\n computed: {\n ptmTHeadOptions: function ptmTHeadOptions() {\n var _this$$parentInstance2;\n return {\n context: {\n scrollable: (_this$$parentInstance2 = this.$parentInstance) === null || _this$$parentInstance2 === void 0 || (_this$$parentInstance2 = _this$$parentInstance2.$parentInstance) === null || _this$$parentInstance2 === void 0 ? void 0 : _this$$parentInstance2.scrollable\n }\n };\n }\n },\n components: {\n DTHeaderCell: script$2,\n DTHeaderCheckbox: script$3,\n DTColumnFilter: script$4\n }\n};\n\nfunction _typeof$2(o) { \"@babel/helpers - typeof\"; return _typeof$2 = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof$2(o); }\nfunction ownKeys$2(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread$2(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$2(Object(t), !0).forEach(function (r) { _defineProperty$2(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$2(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty$2(e, r, t) { return (r = _toPropertyKey$2(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }\nfunction _toPropertyKey$2(t) { var i = _toPrimitive$2(t, \"string\"); return \"symbol\" == _typeof$2(i) ? i : i + \"\"; }\nfunction _toPrimitive$2(t, r) { if (\"object\" != _typeof$2(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof$2(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nfunction render$1(_ctx, _cache, $props, $setup, $data, $options) {\n var _component_DTHeaderCell = resolveComponent(\"DTHeaderCell\");\n var _component_DTHeaderCheckbox = resolveComponent(\"DTHeaderCheckbox\");\n var _component_DTColumnFilter = resolveComponent(\"DTColumnFilter\");\n return openBlock(), createElementBlock(\"thead\", mergeProps({\n \"class\": _ctx.cx('thead'),\n style: _ctx.sx('thead'),\n role: \"rowgroup\"\n }, $props.columnGroup ? _objectSpread$2(_objectSpread$2({}, _ctx.ptm('thead', $options.ptmTHeadOptions)), $options.getColumnGroupPT('root')) : _ctx.ptm('thead', $options.ptmTHeadOptions), {\n \"data-pc-section\": \"thead\"\n }), [!$props.columnGroup ? (openBlock(), createElementBlock(Fragment, {\n key: 0\n }, [createElementVNode(\"tr\", mergeProps({\n role: \"row\"\n }, _ctx.ptm('headerRow')), [(openBlock(true), createElementBlock(Fragment, null, renderList($props.columns, function (col, i) {\n return openBlock(), createElementBlock(Fragment, {\n key: $options.columnProp(col, 'columnKey') || $options.columnProp(col, 'field') || i\n }, [!$options.columnProp(col, 'hidden') && ($props.rowGroupMode !== 'subheader' || $props.groupRowsBy !== $options.columnProp(col, 'field')) ? (openBlock(), createBlock(_component_DTHeaderCell, {\n key: 0,\n column: col,\n index: i,\n onColumnClick: _cache[0] || (_cache[0] = function ($event) {\n return _ctx.$emit('column-click', $event);\n }),\n onColumnMousedown: _cache[1] || (_cache[1] = function ($event) {\n return _ctx.$emit('column-mousedown', $event);\n }),\n onColumnDragstart: _cache[2] || (_cache[2] = function ($event) {\n return _ctx.$emit('column-dragstart', $event);\n }),\n onColumnDragover: _cache[3] || (_cache[3] = function ($event) {\n return _ctx.$emit('column-dragover', $event);\n }),\n onColumnDragleave: _cache[4] || (_cache[4] = function ($event) {\n return _ctx.$emit('column-dragleave', $event);\n }),\n onColumnDrop: _cache[5] || (_cache[5] = function ($event) {\n return _ctx.$emit('column-drop', $event);\n }),\n groupRowsBy: $props.groupRowsBy,\n groupRowSortField: $props.groupRowSortField,\n reorderableColumns: $props.reorderableColumns,\n resizableColumns: $props.resizableColumns,\n onColumnResizestart: _cache[6] || (_cache[6] = function ($event) {\n return _ctx.$emit('column-resizestart', $event);\n }),\n sortMode: $props.sortMode,\n sortField: $props.sortField,\n sortOrder: $props.sortOrder,\n multiSortMeta: $props.multiSortMeta,\n allRowsSelected: $props.allRowsSelected,\n empty: $props.empty,\n onCheckboxChange: _cache[7] || (_cache[7] = function ($event) {\n return _ctx.$emit('checkbox-change', $event);\n }),\n filters: $props.filters,\n filterDisplay: $props.filterDisplay,\n filtersStore: $props.filtersStore,\n filterInputProps: $props.filterInputProps,\n filterButtonProps: $props.filterButtonProps,\n first: $props.first,\n onFilterChange: _cache[8] || (_cache[8] = function ($event) {\n return _ctx.$emit('filter-change', $event);\n }),\n onFilterApply: _cache[9] || (_cache[9] = function ($event) {\n return _ctx.$emit('filter-apply');\n }),\n onOperatorChange: _cache[10] || (_cache[10] = function ($event) {\n return _ctx.$emit('operator-change', $event);\n }),\n onMatchmodeChange: _cache[11] || (_cache[11] = function ($event) {\n return _ctx.$emit('matchmode-change', $event);\n }),\n onConstraintAdd: _cache[12] || (_cache[12] = function ($event) {\n return _ctx.$emit('constraint-add', $event);\n }),\n onConstraintRemove: _cache[13] || (_cache[13] = function ($event) {\n return _ctx.$emit('constraint-remove', $event);\n }),\n onApplyClick: _cache[14] || (_cache[14] = function ($event) {\n return _ctx.$emit('apply-click', $event);\n }),\n unstyled: _ctx.unstyled,\n pt: _ctx.pt\n }, null, 8, [\"column\", \"index\", \"groupRowsBy\", \"groupRowSortField\", \"reorderableColumns\", \"resizableColumns\", \"sortMode\", \"sortField\", \"sortOrder\", \"multiSortMeta\", \"allRowsSelected\", \"empty\", \"filters\", \"filterDisplay\", \"filtersStore\", \"filterInputProps\", \"filterButtonProps\", \"first\", \"unstyled\", \"pt\"])) : createCommentVNode(\"\", true)], 64);\n }), 128))], 16), $props.filterDisplay === 'row' ? (openBlock(), createElementBlock(\"tr\", mergeProps({\n key: 0,\n role: \"row\"\n }, _ctx.ptm('headerRow')), [(openBlock(true), createElementBlock(Fragment, null, renderList($props.columns, function (col, i) {\n return openBlock(), createElementBlock(Fragment, {\n key: $options.columnProp(col, 'columnKey') || $options.columnProp(col, 'field') || i\n }, [!$options.columnProp(col, 'hidden') && ($props.rowGroupMode !== 'subheader' || $props.groupRowsBy !== $options.columnProp(col, 'field')) ? (openBlock(), createElementBlock(\"th\", mergeProps({\n key: 0,\n style: $options.getFilterColumnHeaderStyle(col),\n \"class\": $options.getFilterColumnHeaderClass(col),\n ref_for: true\n }, _objectSpread$2(_objectSpread$2({}, $options.getColumnPT(col, 'root', i)), $options.getColumnPT(col, 'headerCell', i))), [$options.columnProp(col, 'selectionMode') === 'multiple' ? (openBlock(), createBlock(_component_DTHeaderCheckbox, {\n key: 0,\n checked: $props.allRowsSelected,\n disabled: $props.empty,\n onChange: _cache[15] || (_cache[15] = function ($event) {\n return _ctx.$emit('checkbox-change', $event);\n }),\n column: col,\n unstyled: _ctx.unstyled,\n pt: _ctx.pt\n }, null, 8, [\"checked\", \"disabled\", \"column\", \"unstyled\", \"pt\"])) : createCommentVNode(\"\", true), col.children && col.children.filter ? (openBlock(), createBlock(_component_DTColumnFilter, {\n key: 1,\n field: $options.columnProp(col, 'filterField') || $options.columnProp(col, 'field'),\n type: $options.columnProp(col, 'dataType'),\n display: \"row\",\n showMenu: $options.columnProp(col, 'showFilterMenu'),\n filterElement: col.children && col.children.filter,\n filterHeaderTemplate: col.children && col.children.filterheader,\n filterFooterTemplate: col.children && col.children.filterfooter,\n filterClearTemplate: col.children && col.children.filterclear,\n filterApplyTemplate: col.children && col.children.filterapply,\n filterIconTemplate: col.children && col.children.filtericon,\n filterAddIconTemplate: col.children && col.children.filteraddicon,\n filterRemoveIconTemplate: col.children && col.children.filterremoveicon,\n filterClearIconTemplate: col.children && col.children.filterclearicon,\n filters: $props.filters,\n filtersStore: $props.filtersStore,\n filterInputProps: $props.filterInputProps,\n filterButtonProps: $props.filterButtonProps,\n onFilterChange: _cache[16] || (_cache[16] = function ($event) {\n return _ctx.$emit('filter-change', $event);\n }),\n onFilterApply: _cache[17] || (_cache[17] = function ($event) {\n return _ctx.$emit('filter-apply');\n }),\n filterMenuStyle: $options.columnProp(col, 'filterMenuStyle'),\n filterMenuClass: $options.columnProp(col, 'filterMenuClass'),\n showOperator: $options.columnProp(col, 'showFilterOperator'),\n showClearButton: $options.columnProp(col, 'showClearButton'),\n showApplyButton: $options.columnProp(col, 'showApplyButton'),\n showMatchModes: $options.columnProp(col, 'showFilterMatchModes'),\n showAddButton: $options.columnProp(col, 'showAddButton'),\n matchModeOptions: $options.columnProp(col, 'filterMatchModeOptions'),\n maxConstraints: $options.columnProp(col, 'maxConstraints'),\n onOperatorChange: _cache[18] || (_cache[18] = function ($event) {\n return _ctx.$emit('operator-change', $event);\n }),\n onMatchmodeChange: _cache[19] || (_cache[19] = function ($event) {\n return _ctx.$emit('matchmode-change', $event);\n }),\n onConstraintAdd: _cache[20] || (_cache[20] = function ($event) {\n return _ctx.$emit('constraint-add', $event);\n }),\n onConstraintRemove: _cache[21] || (_cache[21] = function ($event) {\n return _ctx.$emit('constraint-remove', $event);\n }),\n onApplyClick: _cache[22] || (_cache[22] = function ($event) {\n return _ctx.$emit('apply-click', $event);\n }),\n column: col,\n unstyled: _ctx.unstyled,\n pt: _ctx.pt\n }, null, 8, [\"field\", \"type\", \"showMenu\", \"filterElement\", \"filterHeaderTemplate\", \"filterFooterTemplate\", \"filterClearTemplate\", \"filterApplyTemplate\", \"filterIconTemplate\", \"filterAddIconTemplate\", \"filterRemoveIconTemplate\", \"filterClearIconTemplate\", \"filters\", \"filtersStore\", \"filterInputProps\", \"filterButtonProps\", \"filterMenuStyle\", \"filterMenuClass\", \"showOperator\", \"showClearButton\", \"showApplyButton\", \"showMatchModes\", \"showAddButton\", \"matchModeOptions\", \"maxConstraints\", \"column\", \"unstyled\", \"pt\"])) : createCommentVNode(\"\", true)], 16)) : createCommentVNode(\"\", true)], 64);\n }), 128))], 16)) : createCommentVNode(\"\", true)], 64)) : (openBlock(true), createElementBlock(Fragment, {\n key: 1\n }, renderList($options.getHeaderRows(), function (row, i) {\n return openBlock(), createElementBlock(\"tr\", mergeProps({\n key: i,\n role: \"row\",\n ref_for: true\n }, _objectSpread$2(_objectSpread$2({}, _ctx.ptm('headerRow')), $options.getRowPT(row, 'root', i))), [(openBlock(true), createElementBlock(Fragment, null, renderList($options.getHeaderColumns(row), function (col, j) {\n return openBlock(), createElementBlock(Fragment, {\n key: $options.columnProp(col, 'columnKey') || $options.columnProp(col, 'field') || j\n }, [!$options.columnProp(col, 'hidden') && ($props.rowGroupMode !== 'subheader' || $props.groupRowsBy !== $options.columnProp(col, 'field')) && typeof col.children !== 'string' ? (openBlock(), createBlock(_component_DTHeaderCell, {\n key: 0,\n column: col,\n onColumnClick: _cache[23] || (_cache[23] = function ($event) {\n return _ctx.$emit('column-click', $event);\n }),\n onColumnMousedown: _cache[24] || (_cache[24] = function ($event) {\n return _ctx.$emit('column-mousedown', $event);\n }),\n groupRowsBy: $props.groupRowsBy,\n groupRowSortField: $props.groupRowSortField,\n sortMode: $props.sortMode,\n sortField: $props.sortField,\n sortOrder: $props.sortOrder,\n multiSortMeta: $props.multiSortMeta,\n allRowsSelected: $props.allRowsSelected,\n empty: $props.empty,\n onCheckboxChange: _cache[25] || (_cache[25] = function ($event) {\n return _ctx.$emit('checkbox-change', $event);\n }),\n filters: $props.filters,\n filterDisplay: $props.filterDisplay,\n filtersStore: $props.filtersStore,\n onFilterChange: _cache[26] || (_cache[26] = function ($event) {\n return _ctx.$emit('filter-change', $event);\n }),\n onFilterApply: _cache[27] || (_cache[27] = function ($event) {\n return _ctx.$emit('filter-apply');\n }),\n onOperatorChange: _cache[28] || (_cache[28] = function ($event) {\n return _ctx.$emit('operator-change', $event);\n }),\n onMatchmodeChange: _cache[29] || (_cache[29] = function ($event) {\n return _ctx.$emit('matchmode-change', $event);\n }),\n onConstraintAdd: _cache[30] || (_cache[30] = function ($event) {\n return _ctx.$emit('constraint-add', $event);\n }),\n onConstraintRemove: _cache[31] || (_cache[31] = function ($event) {\n return _ctx.$emit('constraint-remove', $event);\n }),\n onApplyClick: _cache[32] || (_cache[32] = function ($event) {\n return _ctx.$emit('apply-click', $event);\n }),\n unstyled: _ctx.unstyled,\n pt: _ctx.pt\n }, null, 8, [\"column\", \"groupRowsBy\", \"groupRowSortField\", \"sortMode\", \"sortField\", \"sortOrder\", \"multiSortMeta\", \"allRowsSelected\", \"empty\", \"filters\", \"filterDisplay\", \"filtersStore\", \"unstyled\", \"pt\"])) : createCommentVNode(\"\", true)], 64);\n }), 128))], 16);\n }), 128))], 16);\n}\n\nscript$1.render = render$1;\n\nfunction _typeof$1(o) { \"@babel/helpers - typeof\"; return _typeof$1 = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof$1(o); }\nvar _excluded = [\"expanded\"];\nfunction _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], t.indexOf(o) >= 0 || {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }\nfunction _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (e.indexOf(n) >= 0) continue; t[n] = r[n]; } return t; }\nfunction ownKeys$1(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread$1(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$1(Object(t), !0).forEach(function (r) { _defineProperty$1(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$1(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty$1(e, r, t) { return (r = _toPropertyKey$1(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }\nfunction _toPropertyKey$1(t) { var i = _toPrimitive$1(t, \"string\"); return \"symbol\" == _typeof$1(i) ? i : i + \"\"; }\nfunction _toPrimitive$1(t, r) { if (\"object\" != _typeof$1(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof$1(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nfunction _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }\nfunction _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _iterableToArrayLimit(r, l) { var t = null == r ? null : \"undefined\" != typeof Symbol && r[Symbol.iterator] || r[\"@@iterator\"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) ; else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t[\"return\"] && (u = t[\"return\"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }\nfunction _arrayWithHoles(r) { if (Array.isArray(r)) return r; }\nfunction _createForOfIteratorHelper(r, e) { var t = \"undefined\" != typeof Symbol && r[Symbol.iterator] || r[\"@@iterator\"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e ) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError(\"Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t[\"return\"] || t[\"return\"](); } finally { if (u) throw o; } } }; }\nfunction _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _unsupportedIterableToArray(r, a) { if (r) { if (\"string\" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return \"Object\" === t && r.constructor && (t = r.constructor.name), \"Map\" === t || \"Set\" === t ? Array.from(r) : \"Arguments\" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }\nfunction _iterableToArray(r) { if (\"undefined\" != typeof Symbol && null != r[Symbol.iterator] || null != r[\"@@iterator\"]) return Array.from(r); }\nfunction _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }\nfunction _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }\nvar script = {\n name: 'DataTable',\n \"extends\": script$c,\n inheritAttrs: false,\n emits: ['value-change', 'update:first', 'update:rows', 'page', 'update:sortField', 'update:sortOrder', 'update:multiSortMeta', 'sort', 'filter', 'row-click', 'row-dblclick', 'update:selection', 'row-select', 'row-unselect', 'update:contextMenuSelection', 'row-contextmenu', 'row-unselect-all', 'row-select-all', 'select-all-change', 'column-resize-end', 'column-reorder', 'row-reorder', 'update:expandedRows', 'row-collapse', 'row-expand', 'update:expandedRowGroups', 'rowgroup-collapse', 'rowgroup-expand', 'update:filters', 'state-restore', 'state-save', 'cell-edit-init', 'cell-edit-complete', 'cell-edit-cancel', 'update:editingRows', 'row-edit-init', 'row-edit-save', 'row-edit-cancel'],\n provide: function provide() {\n return {\n $columns: this.d_columns,\n $columnGroups: this.d_columnGroups\n };\n },\n data: function data() {\n return {\n d_first: this.first,\n d_rows: this.rows,\n d_sortField: this.sortField,\n d_sortOrder: this.sortOrder,\n d_nullSortOrder: this.nullSortOrder,\n d_multiSortMeta: this.multiSortMeta ? _toConsumableArray(this.multiSortMeta) : [],\n d_groupRowsSortMeta: null,\n d_selectionKeys: null,\n d_columnOrder: null,\n d_editingRowKeys: null,\n d_editingMeta: {},\n d_filters: this.cloneFilters(this.filters),\n d_columns: new HelperSet({\n type: 'Column'\n }),\n d_columnGroups: new HelperSet({\n type: 'ColumnGroup'\n })\n };\n },\n rowTouched: false,\n anchorRowIndex: null,\n rangeRowIndex: null,\n documentColumnResizeListener: null,\n documentColumnResizeEndListener: null,\n lastResizeHelperX: null,\n resizeColumnElement: null,\n columnResizing: false,\n colReorderIconWidth: null,\n colReorderIconHeight: null,\n draggedColumn: null,\n draggedColumnElement: null,\n draggedRowIndex: null,\n droppedRowIndex: null,\n rowDragging: null,\n columnWidthsState: null,\n tableWidthState: null,\n columnWidthsRestored: false,\n watch: {\n first: function first(newValue) {\n this.d_first = newValue;\n },\n rows: function rows(newValue) {\n this.d_rows = newValue;\n },\n sortField: function sortField(newValue) {\n this.d_sortField = newValue;\n },\n sortOrder: function sortOrder(newValue) {\n this.d_sortOrder = newValue;\n },\n nullSortOrder: function nullSortOrder(newValue) {\n this.d_nullSortOrder = newValue;\n },\n multiSortMeta: function multiSortMeta(newValue) {\n this.d_multiSortMeta = newValue;\n },\n selection: {\n immediate: true,\n handler: function handler(newValue) {\n if (this.dataKey) {\n this.updateSelectionKeys(newValue);\n }\n }\n },\n editingRows: {\n immediate: true,\n handler: function handler(newValue) {\n if (this.dataKey) {\n this.updateEditingRowKeys(newValue);\n }\n }\n },\n filters: {\n deep: true,\n handler: function handler(newValue) {\n this.d_filters = this.cloneFilters(newValue);\n }\n }\n },\n mounted: function mounted() {\n this.$el.setAttribute(this.attributeSelector, '');\n if (this.isStateful()) {\n this.restoreState();\n this.resizableColumns && this.restoreColumnWidths();\n }\n if (this.editMode === 'row' && this.dataKey && !this.d_editingRowKeys) {\n this.updateEditingRowKeys(this.editingRows);\n }\n },\n beforeUnmount: function beforeUnmount() {\n this.unbindColumnResizeEvents();\n this.destroyStyleElement();\n this.d_columns.clear();\n this.d_columnGroups.clear();\n },\n updated: function updated() {\n if (this.isStateful()) {\n this.saveState();\n }\n if (this.editMode === 'row' && this.dataKey && !this.d_editingRowKeys) {\n this.updateEditingRowKeys(this.editingRows);\n }\n },\n methods: {\n columnProp: function columnProp(col, prop) {\n return getVNodeProp(col, prop);\n },\n onPage: function onPage(event) {\n var _this = this;\n this.clearEditingMetaData();\n this.d_first = event.first;\n this.d_rows = event.rows;\n var pageEvent = this.createLazyLoadEvent(event);\n pageEvent.pageCount = event.pageCount;\n pageEvent.page = event.page;\n this.$emit('update:first', this.d_first);\n this.$emit('update:rows', this.d_rows);\n this.$emit('page', pageEvent);\n this.$nextTick(function () {\n _this.$emit('value-change', _this.processedData);\n });\n },\n onColumnHeaderClick: function onColumnHeaderClick(e) {\n var _this2 = this;\n var event = e.originalEvent;\n var column = e.column;\n if (this.columnProp(column, 'sortable')) {\n var targetNode = event.target;\n var columnField = this.columnProp(column, 'sortField') || this.columnProp(column, 'field');\n if (getAttribute(targetNode, 'data-p-sortable-column') === true || getAttribute(targetNode, 'data-pc-section') === 'columntitle' || getAttribute(targetNode, 'data-pc-section') === 'columnheadercontent' || getAttribute(targetNode, 'data-pc-section') === 'sorticon' || getAttribute(targetNode.parentElement, 'data-pc-section') === 'sorticon' || getAttribute(targetNode.parentElement.parentElement, 'data-pc-section') === 'sorticon' || targetNode.closest('[data-p-sortable-column=\"true\"]') && !targetNode.closest('[data-pc-section=\"columnfilterbutton\"]') && !isClickable(event.target)) {\n clearSelection();\n if (this.sortMode === 'single') {\n if (this.d_sortField === columnField) {\n if (this.removableSort && this.d_sortOrder * -1 === this.defaultSortOrder) {\n this.d_sortOrder = null;\n this.d_sortField = null;\n } else {\n this.d_sortOrder = this.d_sortOrder * -1;\n }\n } else {\n this.d_sortOrder = this.defaultSortOrder;\n this.d_sortField = columnField;\n }\n this.$emit('update:sortField', this.d_sortField);\n this.$emit('update:sortOrder', this.d_sortOrder);\n this.resetPage();\n } else if (this.sortMode === 'multiple') {\n var metaKey = event.metaKey || event.ctrlKey;\n if (!metaKey) {\n this.d_multiSortMeta = this.d_multiSortMeta.filter(function (meta) {\n return meta.field === columnField;\n });\n }\n this.addMultiSortField(columnField);\n this.$emit('update:multiSortMeta', this.d_multiSortMeta);\n }\n this.$emit('sort', this.createLazyLoadEvent(event));\n this.$nextTick(function () {\n _this2.$emit('value-change', _this2.processedData);\n });\n }\n }\n },\n sortSingle: function sortSingle(value) {\n var _this3 = this;\n this.clearEditingMetaData();\n if (this.groupRowsBy && this.groupRowsBy === this.sortField) {\n this.d_multiSortMeta = [{\n field: this.sortField,\n order: this.sortOrder || this.defaultSortOrder\n }, {\n field: this.d_sortField,\n order: this.d_sortOrder\n }];\n return this.sortMultiple(value);\n }\n var data = _toConsumableArray(value);\n var resolvedFieldData = new Map();\n var _iterator = _createForOfIteratorHelper(data),\n _step;\n try {\n for (_iterator.s(); !(_step = _iterator.n()).done;) {\n var item = _step.value;\n resolvedFieldData.set(item, resolveFieldData(item, this.d_sortField));\n }\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n var comparer = localeComparator();\n data.sort(function (data1, data2) {\n var value1 = resolvedFieldData.get(data1);\n var value2 = resolvedFieldData.get(data2);\n return sort(value1, value2, _this3.d_sortOrder, comparer, _this3.d_nullSortOrder);\n });\n return data;\n },\n sortMultiple: function sortMultiple(value) {\n var _this4 = this;\n this.clearEditingMetaData();\n if (this.groupRowsBy && (this.d_groupRowsSortMeta || this.d_multiSortMeta.length && this.groupRowsBy === this.d_multiSortMeta[0].field)) {\n var firstSortMeta = this.d_multiSortMeta[0];\n !this.d_groupRowsSortMeta && (this.d_groupRowsSortMeta = firstSortMeta);\n if (firstSortMeta.field !== this.d_groupRowsSortMeta.field) {\n this.d_multiSortMeta = [this.d_groupRowsSortMeta].concat(_toConsumableArray(this.d_multiSortMeta));\n }\n }\n var data = _toConsumableArray(value);\n data.sort(function (data1, data2) {\n return _this4.multisortField(data1, data2, 0);\n });\n return data;\n },\n multisortField: function multisortField(data1, data2, index) {\n var value1 = resolveFieldData(data1, this.d_multiSortMeta[index].field);\n var value2 = resolveFieldData(data2, this.d_multiSortMeta[index].field);\n var comparer = localeComparator();\n if (value1 === value2) {\n return this.d_multiSortMeta.length - 1 > index ? this.multisortField(data1, data2, index + 1) : 0;\n }\n return sort(value1, value2, this.d_multiSortMeta[index].order, comparer, this.d_nullSortOrder);\n },\n addMultiSortField: function addMultiSortField(field) {\n var index = this.d_multiSortMeta.findIndex(function (meta) {\n return meta.field === field;\n });\n if (index >= 0) {\n if (this.removableSort && this.d_multiSortMeta[index].order * -1 === this.defaultSortOrder) this.d_multiSortMeta.splice(index, 1);else this.d_multiSortMeta[index] = {\n field: field,\n order: this.d_multiSortMeta[index].order * -1\n };\n } else {\n this.d_multiSortMeta.push({\n field: field,\n order: this.defaultSortOrder\n });\n }\n this.d_multiSortMeta = _toConsumableArray(this.d_multiSortMeta);\n },\n getActiveFilters: function getActiveFilters(filters) {\n var removeEmptyFilters = function removeEmptyFilters(_ref) {\n var _ref2 = _slicedToArray(_ref, 2),\n key = _ref2[0],\n value = _ref2[1];\n if (value.constraints) {\n var filteredConstraints = value.constraints.filter(function (constraint) {\n return constraint.value !== null;\n });\n if (filteredConstraints.length > 0) {\n return [key, _objectSpread$1(_objectSpread$1({}, value), {}, {\n constraints: filteredConstraints\n })];\n }\n } else if (value.value !== null) {\n return [key, value];\n }\n return undefined;\n };\n var filterValidEntries = function filterValidEntries(entry) {\n return entry !== undefined;\n };\n var entries = Object.entries(filters).map(removeEmptyFilters).filter(filterValidEntries);\n return Object.fromEntries(entries);\n },\n filter: function filter(data) {\n var _this5 = this;\n if (!data) {\n return;\n }\n this.clearEditingMetaData();\n var activeFilters = this.getActiveFilters(this.filters);\n var globalFilterFieldsArray;\n if (activeFilters['global']) {\n globalFilterFieldsArray = this.globalFilterFields || this.columns.map(function (col) {\n return _this5.columnProp(col, 'filterField') || _this5.columnProp(col, 'field');\n });\n }\n var filteredValue = [];\n for (var i = 0; i < data.length; i++) {\n var localMatch = true;\n var globalMatch = false;\n var localFiltered = false;\n for (var prop in activeFilters) {\n if (Object.prototype.hasOwnProperty.call(activeFilters, prop) && prop !== 'global') {\n localFiltered = true;\n var filterField = prop;\n var filterMeta = activeFilters[filterField];\n if (filterMeta.operator) {\n var _iterator2 = _createForOfIteratorHelper(filterMeta.constraints),\n _step2;\n try {\n for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {\n var filterConstraint = _step2.value;\n localMatch = this.executeLocalFilter(filterField, data[i], filterConstraint);\n if (filterMeta.operator === FilterOperator.OR && localMatch || filterMeta.operator === FilterOperator.AND && !localMatch) {\n break;\n }\n }\n } catch (err) {\n _iterator2.e(err);\n } finally {\n _iterator2.f();\n }\n } else {\n localMatch = this.executeLocalFilter(filterField, data[i], filterMeta);\n }\n if (!localMatch) {\n break;\n }\n }\n }\n if (localMatch && activeFilters['global'] && !globalMatch && globalFilterFieldsArray) {\n for (var j = 0; j < globalFilterFieldsArray.length; j++) {\n var globalFilterField = globalFilterFieldsArray[j];\n globalMatch = FilterService.filters[activeFilters['global'].matchMode || FilterMatchMode.CONTAINS](resolveFieldData(data[i], globalFilterField), activeFilters['global'].value, this.filterLocale);\n if (globalMatch) {\n break;\n }\n }\n }\n var matches = void 0;\n if (activeFilters['global']) {\n matches = localFiltered ? localFiltered && localMatch && globalMatch : globalMatch;\n } else {\n matches = localFiltered && localMatch;\n }\n if (matches) {\n filteredValue.push(data[i]);\n }\n }\n if (filteredValue.length === this.value.length || Object.keys(activeFilters).length == 0) {\n filteredValue = data;\n }\n var filterEvent = this.createLazyLoadEvent();\n filterEvent.filteredValue = filteredValue;\n this.$emit('filter', filterEvent);\n this.$nextTick(function () {\n _this5.$emit('value-change', _this5.processedData);\n });\n return filteredValue;\n },\n executeLocalFilter: function executeLocalFilter(field, rowData, filterMeta) {\n var filterValue = filterMeta.value;\n var filterMatchMode = filterMeta.matchMode || FilterMatchMode.STARTS_WITH;\n var dataFieldValue = resolveFieldData(rowData, field);\n var filterConstraint = FilterService.filters[filterMatchMode];\n return filterConstraint(dataFieldValue, filterValue, this.filterLocale);\n },\n onRowClick: function onRowClick(e) {\n var event = e.originalEvent;\n var body = this.$refs.bodyRef && this.$refs.bodyRef.$el;\n var focusedItem = findSingle(body, 'tr[data-p-selectable-row=\"true\"][tabindex=\"0\"]');\n if (isClickable(event.target)) {\n return;\n }\n this.$emit('row-click', e);\n if (this.selectionMode) {\n var rowData = e.data;\n var rowIndex = this.d_first + e.index;\n if (this.isMultipleSelectionMode() && event.shiftKey && this.anchorRowIndex != null) {\n clearSelection();\n this.rangeRowIndex = rowIndex;\n this.selectRange(event);\n } else {\n var selected = this.isSelected(rowData);\n var metaSelection = this.rowTouched ? false : this.metaKeySelection;\n this.anchorRowIndex = rowIndex;\n this.rangeRowIndex = rowIndex;\n if (metaSelection) {\n var metaKey = event.metaKey || event.ctrlKey;\n if (selected && metaKey) {\n if (this.isSingleSelectionMode()) {\n this.$emit('update:selection', null);\n } else {\n var selectionIndex = this.findIndexInSelection(rowData);\n var _selection = this.selection.filter(function (val, i) {\n return i != selectionIndex;\n });\n this.$emit('update:selection', _selection);\n }\n this.$emit('row-unselect', {\n originalEvent: event,\n data: rowData,\n index: rowIndex,\n type: 'row'\n });\n } else {\n if (this.isSingleSelectionMode()) {\n this.$emit('update:selection', rowData);\n } else if (this.isMultipleSelectionMode()) {\n var _selection2 = metaKey ? this.selection || [] : [];\n _selection2 = [].concat(_toConsumableArray(_selection2), [rowData]);\n this.$emit('update:selection', _selection2);\n }\n this.$emit('row-select', {\n originalEvent: event,\n data: rowData,\n index: rowIndex,\n type: 'row'\n });\n }\n } else {\n if (this.selectionMode === 'single') {\n if (selected) {\n this.$emit('update:selection', null);\n this.$emit('row-unselect', {\n originalEvent: event,\n data: rowData,\n index: rowIndex,\n type: 'row'\n });\n } else {\n this.$emit('update:selection', rowData);\n this.$emit('row-select', {\n originalEvent: event,\n data: rowData,\n index: rowIndex,\n type: 'row'\n });\n }\n } else if (this.selectionMode === 'multiple') {\n if (selected) {\n var _selectionIndex = this.findIndexInSelection(rowData);\n var _selection3 = this.selection.filter(function (val, i) {\n return i != _selectionIndex;\n });\n this.$emit('update:selection', _selection3);\n this.$emit('row-unselect', {\n originalEvent: event,\n data: rowData,\n index: rowIndex,\n type: 'row'\n });\n } else {\n var _selection4 = this.selection ? [].concat(_toConsumableArray(this.selection), [rowData]) : [rowData];\n this.$emit('update:selection', _selection4);\n this.$emit('row-select', {\n originalEvent: event,\n data: rowData,\n index: rowIndex,\n type: 'row'\n });\n }\n }\n }\n }\n }\n this.rowTouched = false;\n if (focusedItem) {\n var _event$target, _event$target2, _event$target3;\n if (((_event$target = event.target) === null || _event$target === void 0 ? void 0 : _event$target.getAttribute('data-pc-section')) === 'rowtoggleicon' || ((_event$target2 = event.target) === null || _event$target2 === void 0 || (_event$target2 = _event$target2.parentElement) === null || _event$target2 === void 0 ? void 0 : _event$target2.getAttribute('data-pc-section')) === 'rowtoggleicon') return;\n var targetRow = (_event$target3 = event.target) === null || _event$target3 === void 0 ? void 0 : _event$target3.closest('tr[data-p-selectable-row=\"true\"]');\n focusedItem.tabIndex = '-1';\n targetRow.tabIndex = '0';\n }\n },\n onRowDblClick: function onRowDblClick(e) {\n var event = e.originalEvent;\n if (isClickable(event.target)) {\n return;\n }\n this.$emit('row-dblclick', e);\n },\n onRowRightClick: function onRowRightClick(event) {\n if (this.contextMenu) {\n clearSelection();\n event.originalEvent.target.focus();\n }\n this.$emit('update:contextMenuSelection', event.data);\n this.$emit('row-contextmenu', event);\n },\n onRowTouchEnd: function onRowTouchEnd() {\n this.rowTouched = true;\n },\n onRowKeyDown: function onRowKeyDown(e, slotProps) {\n var event = e.originalEvent;\n var rowData = e.data;\n var rowIndex = e.index;\n var metaKey = event.metaKey || event.ctrlKey;\n if (this.selectionMode) {\n var row = event.target;\n switch (event.code) {\n case 'ArrowDown':\n this.onArrowDownKey(event, row, rowIndex, slotProps);\n break;\n case 'ArrowUp':\n this.onArrowUpKey(event, row, rowIndex, slotProps);\n break;\n case 'Home':\n this.onHomeKey(event, row, rowIndex, slotProps);\n break;\n case 'End':\n this.onEndKey(event, row, rowIndex, slotProps);\n break;\n case 'Enter':\n case 'NumpadEnter':\n this.onEnterKey(event, rowData, rowIndex);\n break;\n case 'Space':\n this.onSpaceKey(event, rowData, rowIndex, slotProps);\n break;\n case 'Tab':\n this.onTabKey(event, rowIndex);\n break;\n default:\n if (event.code === 'KeyA' && metaKey && this.isMultipleSelectionMode()) {\n var data = this.dataToRender(slotProps.rows);\n this.$emit('update:selection', data);\n }\n event.preventDefault();\n break;\n }\n }\n },\n onArrowDownKey: function onArrowDownKey(event, row, rowIndex, slotProps) {\n var nextRow = this.findNextSelectableRow(row);\n nextRow && this.focusRowChange(row, nextRow);\n if (event.shiftKey) {\n var data = this.dataToRender(slotProps.rows);\n var nextRowIndex = rowIndex + 1 >= data.length ? data.length - 1 : rowIndex + 1;\n this.onRowClick({\n originalEvent: event,\n data: data[nextRowIndex],\n index: nextRowIndex\n });\n }\n event.preventDefault();\n },\n onArrowUpKey: function onArrowUpKey(event, row, rowIndex, slotProps) {\n var prevRow = this.findPrevSelectableRow(row);\n prevRow && this.focusRowChange(row, prevRow);\n if (event.shiftKey) {\n var data = this.dataToRender(slotProps.rows);\n var prevRowIndex = rowIndex - 1 <= 0 ? 0 : rowIndex - 1;\n this.onRowClick({\n originalEvent: event,\n data: data[prevRowIndex],\n index: prevRowIndex\n });\n }\n event.preventDefault();\n },\n onHomeKey: function onHomeKey(event, row, rowIndex, slotProps) {\n var firstRow = this.findFirstSelectableRow();\n firstRow && this.focusRowChange(row, firstRow);\n if (event.ctrlKey && event.shiftKey) {\n var data = this.dataToRender(slotProps.rows);\n this.$emit('update:selection', data.slice(0, rowIndex + 1));\n }\n event.preventDefault();\n },\n onEndKey: function onEndKey(event, row, rowIndex, slotProps) {\n var lastRow = this.findLastSelectableRow();\n lastRow && this.focusRowChange(row, lastRow);\n if (event.ctrlKey && event.shiftKey) {\n var data = this.dataToRender(slotProps.rows);\n this.$emit('update:selection', data.slice(rowIndex, data.length));\n }\n event.preventDefault();\n },\n onEnterKey: function onEnterKey(event, rowData, rowIndex) {\n this.onRowClick({\n originalEvent: event,\n data: rowData,\n index: rowIndex\n });\n event.preventDefault();\n },\n onSpaceKey: function onSpaceKey(event, rowData, rowIndex, slotProps) {\n this.onEnterKey(event, rowData, rowIndex);\n if (event.shiftKey && this.selection !== null) {\n var data = this.dataToRender(slotProps.rows);\n var index;\n if (this.selection.length > 0) {\n var firstSelectedRowIndex, lastSelectedRowIndex;\n firstSelectedRowIndex = findIndexInList(this.selection[0], data);\n lastSelectedRowIndex = findIndexInList(this.selection[this.selection.length - 1], data);\n index = rowIndex <= firstSelectedRowIndex ? lastSelectedRowIndex : firstSelectedRowIndex;\n } else {\n index = findIndexInList(this.selection, data);\n }\n var _selection = index !== rowIndex ? data.slice(Math.min(index, rowIndex), Math.max(index, rowIndex) + 1) : rowData;\n this.$emit('update:selection', _selection);\n }\n },\n onTabKey: function onTabKey(event, rowIndex) {\n var body = this.$refs.bodyRef && this.$refs.bodyRef.$el;\n var rows = find(body, 'tr[data-p-selectable-row=\"true\"]');\n if (event.code === 'Tab' && rows && rows.length > 0) {\n var firstSelectedRow = findSingle(body, 'tr[data-p-selected=\"true\"]');\n var focusedItem = findSingle(body, 'tr[data-p-selectable-row=\"true\"][tabindex=\"0\"]');\n if (firstSelectedRow) {\n firstSelectedRow.tabIndex = '0';\n focusedItem && focusedItem !== firstSelectedRow && (focusedItem.tabIndex = '-1');\n } else {\n rows[0].tabIndex = '0';\n focusedItem !== rows[0] && (rows[rowIndex].tabIndex = '-1');\n }\n }\n },\n findNextSelectableRow: function findNextSelectableRow(row) {\n var nextRow = row.nextElementSibling;\n if (nextRow) {\n if (getAttribute(nextRow, 'data-p-selectable-row') === true) return nextRow;else return this.findNextSelectableRow(nextRow);\n } else {\n return null;\n }\n },\n findPrevSelectableRow: function findPrevSelectableRow(row) {\n var prevRow = row.previousElementSibling;\n if (prevRow) {\n if (getAttribute(prevRow, 'data-p-selectable-row') === true) return prevRow;else return this.findPrevSelectableRow(prevRow);\n } else {\n return null;\n }\n },\n findFirstSelectableRow: function findFirstSelectableRow() {\n var firstRow = findSingle(this.$refs.table, 'tr[data-p-selectable-row=\"true\"]');\n return firstRow;\n },\n findLastSelectableRow: function findLastSelectableRow() {\n var rows = find(this.$refs.table, 'tr[data-p-selectable-row=\"true\"]');\n return rows ? rows[rows.length - 1] : null;\n },\n focusRowChange: function focusRowChange(firstFocusableRow, currentFocusedRow) {\n firstFocusableRow.tabIndex = '-1';\n currentFocusedRow.tabIndex = '0';\n focus(currentFocusedRow);\n },\n toggleRowWithRadio: function toggleRowWithRadio(event) {\n var rowData = event.data;\n if (this.isSelected(rowData)) {\n this.$emit('update:selection', null);\n this.$emit('row-unselect', {\n originalEvent: event.originalEvent,\n data: rowData,\n index: event.index,\n type: 'radiobutton'\n });\n } else {\n this.$emit('update:selection', rowData);\n this.$emit('row-select', {\n originalEvent: event.originalEvent,\n data: rowData,\n index: event.index,\n type: 'radiobutton'\n });\n }\n },\n toggleRowWithCheckbox: function toggleRowWithCheckbox(event) {\n var rowData = event.data;\n if (this.isSelected(rowData)) {\n var selectionIndex = this.findIndexInSelection(rowData);\n var _selection = this.selection.filter(function (val, i) {\n return i != selectionIndex;\n });\n this.$emit('update:selection', _selection);\n this.$emit('row-unselect', {\n originalEvent: event.originalEvent,\n data: rowData,\n index: event.index,\n type: 'checkbox'\n });\n } else {\n var _selection5 = this.selection ? _toConsumableArray(this.selection) : [];\n _selection5 = [].concat(_toConsumableArray(_selection5), [rowData]);\n this.$emit('update:selection', _selection5);\n this.$emit('row-select', {\n originalEvent: event.originalEvent,\n data: rowData,\n index: event.index,\n type: 'checkbox'\n });\n }\n },\n toggleRowsWithCheckbox: function toggleRowsWithCheckbox(event) {\n if (this.selectAll !== null) {\n this.$emit('select-all-change', event);\n } else {\n var originalEvent = event.originalEvent,\n checked = event.checked;\n var _selection = [];\n if (checked) {\n _selection = this.frozenValue ? [].concat(_toConsumableArray(this.frozenValue), _toConsumableArray(this.processedData)) : this.processedData;\n this.$emit('row-select-all', {\n originalEvent: originalEvent,\n data: _selection\n });\n } else {\n this.$emit('row-unselect-all', {\n originalEvent: originalEvent\n });\n }\n this.$emit('update:selection', _selection);\n }\n },\n isSingleSelectionMode: function isSingleSelectionMode() {\n return this.selectionMode === 'single';\n },\n isMultipleSelectionMode: function isMultipleSelectionMode() {\n return this.selectionMode === 'multiple';\n },\n isSelected: function isSelected(rowData) {\n if (rowData && this.selection) {\n if (this.dataKey) {\n return this.d_selectionKeys ? this.d_selectionKeys[resolveFieldData(rowData, this.dataKey)] !== undefined : false;\n } else {\n if (this.selection instanceof Array) return this.findIndexInSelection(rowData) > -1;else return this.equals(rowData, this.selection);\n }\n }\n return false;\n },\n findIndexInSelection: function findIndexInSelection(rowData) {\n return this.findIndex(rowData, this.selection);\n },\n findIndex: function findIndex(rowData, collection) {\n var index = -1;\n if (collection && collection.length) {\n for (var i = 0; i < collection.length; i++) {\n if (this.equals(rowData, collection[i])) {\n index = i;\n break;\n }\n }\n }\n return index;\n },\n updateSelectionKeys: function updateSelectionKeys(selection) {\n this.d_selectionKeys = {};\n if (Array.isArray(selection)) {\n var _iterator3 = _createForOfIteratorHelper(selection),\n _step3;\n try {\n for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {\n var data = _step3.value;\n this.d_selectionKeys[String(resolveFieldData(data, this.dataKey))] = 1;\n }\n } catch (err) {\n _iterator3.e(err);\n } finally {\n _iterator3.f();\n }\n } else {\n this.d_selectionKeys[String(resolveFieldData(selection, this.dataKey))] = 1;\n }\n },\n updateEditingRowKeys: function updateEditingRowKeys(editingRows) {\n if (editingRows && editingRows.length) {\n this.d_editingRowKeys = {};\n var _iterator4 = _createForOfIteratorHelper(editingRows),\n _step4;\n try {\n for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {\n var data = _step4.value;\n this.d_editingRowKeys[String(resolveFieldData(data, this.dataKey))] = 1;\n }\n } catch (err) {\n _iterator4.e(err);\n } finally {\n _iterator4.f();\n }\n } else {\n this.d_editingRowKeys = null;\n }\n },\n equals: function equals$1(data1, data2) {\n return this.compareSelectionBy === 'equals' ? data1 === data2 : equals(data1, data2, this.dataKey);\n },\n selectRange: function selectRange(event) {\n var rangeStart, rangeEnd;\n if (this.rangeRowIndex > this.anchorRowIndex) {\n rangeStart = this.anchorRowIndex;\n rangeEnd = this.rangeRowIndex;\n } else if (this.rangeRowIndex < this.anchorRowIndex) {\n rangeStart = this.rangeRowIndex;\n rangeEnd = this.anchorRowIndex;\n } else {\n rangeStart = this.rangeRowIndex;\n rangeEnd = this.rangeRowIndex;\n }\n if (this.lazy && this.paginator) {\n rangeStart -= this.first;\n rangeEnd -= this.first;\n }\n var value = this.processedData;\n var _selection = [];\n for (var i = rangeStart; i <= rangeEnd; i++) {\n var rangeRowData = value[i];\n _selection.push(rangeRowData);\n this.$emit('row-select', {\n originalEvent: event,\n data: rangeRowData,\n type: 'row'\n });\n }\n this.$emit('update:selection', _selection);\n },\n exportCSV: function exportCSV$1(options, data) {\n var _this6 = this;\n var csv = \"\\uFEFF\";\n if (!data) {\n data = this.processedData;\n if (options && options.selectionOnly) data = this.selection || [];else if (this.frozenValue) data = data ? [].concat(_toConsumableArray(this.frozenValue), _toConsumableArray(data)) : this.frozenValue;\n }\n\n //headers\n var headerInitiated = false;\n for (var i = 0; i < this.columns.length; i++) {\n var column = this.columns[i];\n if (this.columnProp(column, 'exportable') !== false && this.columnProp(column, 'field')) {\n if (headerInitiated) csv += this.csvSeparator;else headerInitiated = true;\n csv += '\"' + (this.columnProp(column, 'exportHeader') || this.columnProp(column, 'header') || this.columnProp(column, 'field')) + '\"';\n }\n }\n\n //body\n if (data) {\n data.forEach(function (record) {\n csv += '\\n';\n var rowInitiated = false;\n for (var _i = 0; _i < _this6.columns.length; _i++) {\n var _column = _this6.columns[_i];\n if (_this6.columnProp(_column, 'exportable') !== false && _this6.columnProp(_column, 'field')) {\n if (rowInitiated) csv += _this6.csvSeparator;else rowInitiated = true;\n var cellData = resolveFieldData(record, _this6.columnProp(_column, 'field'));\n if (cellData != null) {\n if (_this6.exportFunction) {\n cellData = _this6.exportFunction({\n data: cellData,\n field: _this6.columnProp(_column, 'field')\n });\n } else cellData = String(cellData).replace(/\"/g, '\"\"');\n } else cellData = '';\n csv += '\"' + cellData + '\"';\n }\n }\n });\n }\n\n //footers\n var footerInitiated = false;\n for (var _i2 = 0; _i2 < this.columns.length; _i2++) {\n var _column2 = this.columns[_i2];\n if (_i2 === 0) csv += '\\n';\n if (this.columnProp(_column2, 'exportable') !== false && this.columnProp(_column2, 'exportFooter')) {\n if (footerInitiated) csv += this.csvSeparator;else footerInitiated = true;\n csv += '\"' + (this.columnProp(_column2, 'exportFooter') || this.columnProp(_column2, 'footer') || this.columnProp(_column2, 'field')) + '\"';\n }\n }\n exportCSV(csv, this.exportFilename);\n },\n resetPage: function resetPage() {\n this.d_first = 0;\n this.$emit('update:first', this.d_first);\n },\n onColumnResizeStart: function onColumnResizeStart(event) {\n var containerLeft = getOffset(this.$el).left;\n this.resizeColumnElement = event.target.parentElement;\n this.columnResizing = true;\n this.lastResizeHelperX = event.pageX - containerLeft + this.$el.scrollLeft;\n this.bindColumnResizeEvents();\n },\n onColumnResize: function onColumnResize(event) {\n var containerLeft = getOffset(this.$el).left;\n this.$el.setAttribute('data-p-unselectable-text', 'true');\n !this.isUnstyled && addStyle(this.$el, {\n 'user-select': 'none'\n });\n this.$refs.resizeHelper.style.height = this.$el.offsetHeight + 'px';\n this.$refs.resizeHelper.style.top = 0 + 'px';\n this.$refs.resizeHelper.style.left = event.pageX - containerLeft + this.$el.scrollLeft + 'px';\n this.$refs.resizeHelper.style.display = 'block';\n },\n onColumnResizeEnd: function onColumnResizeEnd() {\n var delta = this.$refs.resizeHelper.offsetLeft - this.lastResizeHelperX;\n var columnWidth = this.resizeColumnElement.offsetWidth;\n var newColumnWidth = columnWidth + delta;\n var minWidth = this.resizeColumnElement.style.minWidth || 15;\n if (columnWidth + delta > parseInt(minWidth, 10)) {\n if (this.columnResizeMode === 'fit') {\n var nextColumn = this.resizeColumnElement.nextElementSibling;\n var nextColumnWidth = nextColumn.offsetWidth - delta;\n if (newColumnWidth > 15 && nextColumnWidth > 15) {\n this.resizeTableCells(newColumnWidth, nextColumnWidth);\n }\n } else if (this.columnResizeMode === 'expand') {\n var tableWidth = this.$refs.table.offsetWidth + delta + 'px';\n var updateTableWidth = function updateTableWidth(el) {\n !!el && (el.style.width = el.style.minWidth = tableWidth);\n };\n\n // Reasoning: resize table cells before updating the table width so that it can use existing computed cell widths and adjust only the one column.\n this.resizeTableCells(newColumnWidth);\n updateTableWidth(this.$refs.table);\n if (!this.virtualScrollerDisabled) {\n var body = this.$refs.bodyRef && this.$refs.bodyRef.$el;\n var frozenBody = this.$refs.frozenBodyRef && this.$refs.frozenBodyRef.$el;\n updateTableWidth(body);\n updateTableWidth(frozenBody);\n }\n }\n this.$emit('column-resize-end', {\n element: this.resizeColumnElement,\n delta: delta\n });\n }\n this.$refs.resizeHelper.style.display = 'none';\n this.resizeColumn = null;\n this.$el.removeAttribute('data-p-unselectable-text');\n !this.isUnstyled && (this.$el.style['user-select'] = '');\n this.unbindColumnResizeEvents();\n if (this.isStateful()) {\n this.saveState();\n }\n },\n resizeTableCells: function resizeTableCells(newColumnWidth, nextColumnWidth) {\n var colIndex = getIndex(this.resizeColumnElement);\n var widths = [];\n var headers = find(this.$refs.table, 'thead[data-pc-section=\"thead\"] > tr > th');\n headers.forEach(function (header) {\n return widths.push(getOuterWidth(header));\n });\n this.destroyStyleElement();\n this.createStyleElement();\n var innerHTML = '';\n var selector = \"[data-pc-name=\\\"datatable\\\"][\".concat(this.attributeSelector, \"] > [data-pc-section=\\\"tablecontainer\\\"] \").concat(this.virtualScrollerDisabled ? '' : '> [data-pc-name=\"virtualscroller\"]', \" > table[data-pc-section=\\\"table\\\"]\");\n widths.forEach(function (width, index) {\n var colWidth = index === colIndex ? newColumnWidth : nextColumnWidth && index === colIndex + 1 ? nextColumnWidth : width;\n var style = \"width: \".concat(colWidth, \"px !important; max-width: \").concat(colWidth, \"px !important\");\n innerHTML += \"\\n \".concat(selector, \" > thead[data-pc-section=\\\"thead\\\"] > tr > th:nth-child(\").concat(index + 1, \"),\\n \").concat(selector, \" > tbody[data-pc-section=\\\"tbody\\\"] > tr > td:nth-child(\").concat(index + 1, \"),\\n \").concat(selector, \" > tfoot[data-pc-section=\\\"tfoot\\\"] > tr > td:nth-child(\").concat(index + 1, \") {\\n \").concat(style, \"\\n }\\n \");\n });\n this.styleElement.innerHTML = innerHTML;\n },\n bindColumnResizeEvents: function bindColumnResizeEvents() {\n var _this7 = this;\n if (!this.documentColumnResizeListener) {\n this.documentColumnResizeListener = document.addEventListener('mousemove', function () {\n if (_this7.columnResizing) {\n _this7.onColumnResize(event);\n }\n });\n }\n if (!this.documentColumnResizeEndListener) {\n this.documentColumnResizeEndListener = document.addEventListener('mouseup', function () {\n if (_this7.columnResizing) {\n _this7.columnResizing = false;\n _this7.onColumnResizeEnd();\n }\n });\n }\n },\n unbindColumnResizeEvents: function unbindColumnResizeEvents() {\n if (this.documentColumnResizeListener) {\n document.removeEventListener('document', this.documentColumnResizeListener);\n this.documentColumnResizeListener = null;\n }\n if (this.documentColumnResizeEndListener) {\n document.removeEventListener('document', this.documentColumnResizeEndListener);\n this.documentColumnResizeEndListener = null;\n }\n },\n onColumnHeaderMouseDown: function onColumnHeaderMouseDown(e) {\n var event = e.originalEvent;\n var column = e.column;\n if (this.reorderableColumns && this.columnProp(column, 'reorderableColumn') !== false) {\n if (event.target.nodeName === 'INPUT' || event.target.nodeName === 'TEXTAREA' || getAttribute(event.target, '[data-pc-section=\"columnresizer\"]')) event.currentTarget.draggable = false;else event.currentTarget.draggable = true;\n }\n },\n onColumnHeaderDragStart: function onColumnHeaderDragStart(e) {\n var event = e.originalEvent,\n column = e.column;\n if (this.columnResizing) {\n event.preventDefault();\n return;\n }\n this.colReorderIconWidth = getHiddenElementOuterWidth(this.$refs.reorderIndicatorUp);\n this.colReorderIconHeight = getHiddenElementOuterHeight(this.$refs.reorderIndicatorUp);\n this.draggedColumn = column;\n this.draggedColumnElement = this.findParentHeader(event.target);\n event.dataTransfer.setData('text', 'b'); // Firefox requires this to make dragging possible\n },\n onColumnHeaderDragOver: function onColumnHeaderDragOver(e) {\n var event = e.originalEvent,\n column = e.column;\n var dropHeader = this.findParentHeader(event.target);\n if (this.reorderableColumns && this.draggedColumnElement && dropHeader && !this.columnProp(column, 'frozen')) {\n event.preventDefault();\n var containerOffset = getOffset(this.$el);\n var dropHeaderOffset = getOffset(dropHeader);\n if (this.draggedColumnElement !== dropHeader) {\n var targetLeft = dropHeaderOffset.left - containerOffset.left;\n var columnCenter = dropHeaderOffset.left + dropHeader.offsetWidth / 2;\n this.$refs.reorderIndicatorUp.style.top = dropHeaderOffset.top - containerOffset.top - (this.colReorderIconHeight - 1) + 'px';\n this.$refs.reorderIndicatorDown.style.top = dropHeaderOffset.top - containerOffset.top + dropHeader.offsetHeight + 'px';\n if (event.pageX > columnCenter) {\n this.$refs.reorderIndicatorUp.style.left = targetLeft + dropHeader.offsetWidth - Math.ceil(this.colReorderIconWidth / 2) + 'px';\n this.$refs.reorderIndicatorDown.style.left = targetLeft + dropHeader.offsetWidth - Math.ceil(this.colReorderIconWidth / 2) + 'px';\n this.dropPosition = 1;\n } else {\n this.$refs.reorderIndicatorUp.style.left = targetLeft - Math.ceil(this.colReorderIconWidth / 2) + 'px';\n this.$refs.reorderIndicatorDown.style.left = targetLeft - Math.ceil(this.colReorderIconWidth / 2) + 'px';\n this.dropPosition = -1;\n }\n this.$refs.reorderIndicatorUp.style.display = 'block';\n this.$refs.reorderIndicatorDown.style.display = 'block';\n }\n }\n },\n onColumnHeaderDragLeave: function onColumnHeaderDragLeave(e) {\n var event = e.originalEvent;\n if (this.reorderableColumns && this.draggedColumnElement) {\n event.preventDefault();\n this.$refs.reorderIndicatorUp.style.display = 'none';\n this.$refs.reorderIndicatorDown.style.display = 'none';\n }\n },\n onColumnHeaderDrop: function onColumnHeaderDrop(e) {\n var _this8 = this;\n var event = e.originalEvent,\n column = e.column;\n event.preventDefault();\n if (this.draggedColumnElement) {\n var dragIndex = getIndex(this.draggedColumnElement);\n var dropIndex = getIndex(this.findParentHeader(event.target));\n var allowDrop = dragIndex !== dropIndex;\n if (allowDrop && (dropIndex - dragIndex === 1 && this.dropPosition === -1 || dropIndex - dragIndex === -1 && this.dropPosition === 1)) {\n allowDrop = false;\n }\n if (allowDrop) {\n var isSameColumn = function isSameColumn(col1, col2) {\n return _this8.columnProp(col1, 'columnKey') || _this8.columnProp(col2, 'columnKey') ? _this8.columnProp(col1, 'columnKey') === _this8.columnProp(col2, 'columnKey') : _this8.columnProp(col1, 'field') === _this8.columnProp(col2, 'field');\n };\n var dragColIndex = this.columns.findIndex(function (child) {\n return isSameColumn(child, _this8.draggedColumn);\n });\n var dropColIndex = this.columns.findIndex(function (child) {\n return isSameColumn(child, column);\n });\n var widths = [];\n var headers = find(this.$el, 'thead[data-pc-section=\"thead\"] > tr > th');\n headers.forEach(function (header) {\n return widths.push(getOuterWidth(header));\n });\n var movedItem = widths.find(function (_, index) {\n return index === dragColIndex;\n });\n var remainingItems = widths.filter(function (_, index) {\n return index !== dragColIndex;\n });\n var reorderedWidths = [].concat(_toConsumableArray(remainingItems.slice(0, dropColIndex)), [movedItem], _toConsumableArray(remainingItems.slice(dropColIndex)));\n this.addColumnWidthStyles(reorderedWidths);\n if (dropColIndex < dragColIndex && this.dropPosition === 1) {\n dropColIndex++;\n }\n if (dropColIndex > dragColIndex && this.dropPosition === -1) {\n dropColIndex--;\n }\n reorderArray(this.columns, dragColIndex, dropColIndex);\n this.updateReorderableColumns();\n this.$emit('column-reorder', {\n originalEvent: event,\n dragIndex: dragColIndex,\n dropIndex: dropColIndex\n });\n }\n this.$refs.reorderIndicatorUp.style.display = 'none';\n this.$refs.reorderIndicatorDown.style.display = 'none';\n this.draggedColumnElement.draggable = false;\n this.draggedColumnElement = null;\n this.draggedColumn = null;\n this.dropPosition = null;\n }\n },\n findParentHeader: function findParentHeader(element) {\n if (element.nodeName === 'TH') {\n return element;\n } else {\n var parent = element.parentElement;\n while (parent.nodeName !== 'TH') {\n parent = parent.parentElement;\n if (!parent) break;\n }\n return parent;\n }\n },\n findColumnByKey: function findColumnByKey(columns, key) {\n if (columns && columns.length) {\n for (var i = 0; i < columns.length; i++) {\n var column = columns[i];\n if (this.columnProp(column, 'columnKey') === key || this.columnProp(column, 'field') === key) {\n return column;\n }\n }\n }\n return null;\n },\n onRowMouseDown: function onRowMouseDown(event) {\n if (getAttribute(event.target, 'data-pc-section') === 'reorderablerowhandle' || getAttribute(event.target.parentElement, 'data-pc-section') === 'reorderablerowhandle') event.currentTarget.draggable = true;else event.currentTarget.draggable = false;\n },\n onRowDragStart: function onRowDragStart(e) {\n var event = e.originalEvent;\n var index = e.index;\n this.rowDragging = true;\n this.draggedRowIndex = index;\n event.dataTransfer.setData('text', 'b'); // For firefox\n },\n onRowDragOver: function onRowDragOver(e) {\n var event = e.originalEvent;\n var index = e.index;\n if (this.rowDragging && this.draggedRowIndex !== index) {\n var rowElement = event.currentTarget;\n var rowY = getOffset(rowElement).top + getWindowScrollTop();\n var pageY = event.pageY;\n var rowMidY = rowY + getOuterHeight(rowElement) / 2;\n var prevRowElement = rowElement.previousElementSibling;\n if (pageY < rowMidY) {\n rowElement.setAttribute('data-p-datatable-dragpoint-bottom', 'false');\n !this.isUnstyled && removeClass(rowElement, 'p-datatable-dragpoint-bottom');\n this.droppedRowIndex = index;\n if (prevRowElement) {\n prevRowElement.setAttribute('data-p-datatable-dragpoint-bottom', 'true');\n !this.isUnstyled && addClass(prevRowElement, 'p-datatable-dragpoint-bottom');\n } else {\n rowElement.setAttribute('data-p-datatable-dragpoint-top', 'true');\n !this.isUnstyled && addClass(rowElement, 'p-datatable-dragpoint-top');\n }\n } else {\n if (prevRowElement) {\n prevRowElement.setAttribute('data-p-datatable-dragpoint-bottom', 'false');\n !this.isUnstyled && removeClass(prevRowElement, 'p-datatable-dragpoint-bottom');\n } else {\n rowElement.setAttribute('data-p-datatable-dragpoint-top', 'true');\n !this.isUnstyled && addClass(rowElement, 'p-datatable-dragpoint-top');\n }\n this.droppedRowIndex = index + 1;\n rowElement.setAttribute('data-p-datatable-dragpoint-bottom', 'true');\n !this.isUnstyled && addClass(rowElement, 'p-datatable-dragpoint-bottom');\n }\n event.preventDefault();\n }\n },\n onRowDragLeave: function onRowDragLeave(event) {\n var rowElement = event.currentTarget;\n var prevRowElement = rowElement.previousElementSibling;\n if (prevRowElement) {\n prevRowElement.setAttribute('data-p-datatable-dragpoint-bottom', 'false');\n !this.isUnstyled && removeClass(prevRowElement, 'p-datatable-dragpoint-bottom');\n }\n rowElement.setAttribute('data-p-datatable-dragpoint-bottom', 'false');\n !this.isUnstyled && removeClass(rowElement, 'p-datatable-dragpoint-bottom');\n rowElement.setAttribute('data-p-datatable-dragpoint-top', 'false');\n !this.isUnstyled && removeClass(rowElement, 'p-datatable-dragpoint-top');\n },\n onRowDragEnd: function onRowDragEnd(event) {\n this.rowDragging = false;\n this.draggedRowIndex = null;\n this.droppedRowIndex = null;\n event.currentTarget.draggable = false;\n },\n onRowDrop: function onRowDrop(event) {\n if (this.droppedRowIndex != null) {\n var dropIndex = this.draggedRowIndex > this.droppedRowIndex ? this.droppedRowIndex : this.droppedRowIndex === 0 ? 0 : this.droppedRowIndex - 1;\n var processedData = _toConsumableArray(this.processedData);\n reorderArray(processedData, this.draggedRowIndex + this.d_first, dropIndex + this.d_first);\n this.$emit('row-reorder', {\n originalEvent: event,\n dragIndex: this.draggedRowIndex,\n dropIndex: dropIndex,\n value: processedData\n });\n }\n\n //cleanup\n this.onRowDragLeave(event);\n this.onRowDragEnd(event);\n event.preventDefault();\n },\n toggleRow: function toggleRow(event) {\n var _this9 = this;\n var expanded = event.expanded,\n rest = _objectWithoutProperties(event, _excluded);\n var rowData = event.data;\n var expandedRows;\n if (this.dataKey) {\n var value = resolveFieldData(rowData, this.dataKey);\n expandedRows = this.expandedRows ? _objectSpread$1({}, this.expandedRows) : {};\n expanded ? expandedRows[value] = true : delete expandedRows[value];\n } else {\n expandedRows = this.expandedRows ? _toConsumableArray(this.expandedRows) : [];\n expanded ? expandedRows.push(rowData) : expandedRows = expandedRows.filter(function (d) {\n return !_this9.equals(rowData, d);\n });\n }\n this.$emit('update:expandedRows', expandedRows);\n expanded ? this.$emit('row-expand', rest) : this.$emit('row-collapse', rest);\n },\n toggleRowGroup: function toggleRowGroup(e) {\n var event = e.originalEvent;\n var data = e.data;\n var groupFieldValue = resolveFieldData(data, this.groupRowsBy);\n var _expandedRowGroups = this.expandedRowGroups ? _toConsumableArray(this.expandedRowGroups) : [];\n if (this.isRowGroupExpanded(data)) {\n _expandedRowGroups = _expandedRowGroups.filter(function (group) {\n return group !== groupFieldValue;\n });\n this.$emit('update:expandedRowGroups', _expandedRowGroups);\n this.$emit('rowgroup-collapse', {\n originalEvent: event,\n data: groupFieldValue\n });\n } else {\n _expandedRowGroups.push(groupFieldValue);\n this.$emit('update:expandedRowGroups', _expandedRowGroups);\n this.$emit('rowgroup-expand', {\n originalEvent: event,\n data: groupFieldValue\n });\n }\n },\n isRowGroupExpanded: function isRowGroupExpanded(rowData) {\n if (this.expandableRowGroups && this.expandedRowGroups) {\n var groupFieldValue = resolveFieldData(rowData, this.groupRowsBy);\n return this.expandedRowGroups.indexOf(groupFieldValue) > -1;\n }\n return false;\n },\n isStateful: function isStateful() {\n return this.stateKey != null;\n },\n getStorage: function getStorage() {\n switch (this.stateStorage) {\n case 'local':\n return window.localStorage;\n case 'session':\n return window.sessionStorage;\n default:\n throw new Error(this.stateStorage + ' is not a valid value for the state storage, supported values are \"local\" and \"session\".');\n }\n },\n saveState: function saveState() {\n var storage = this.getStorage();\n var state = {};\n if (this.paginator) {\n state.first = this.d_first;\n state.rows = this.d_rows;\n }\n if (this.d_sortField) {\n state.sortField = this.d_sortField;\n state.sortOrder = this.d_sortOrder;\n }\n if (this.d_multiSortMeta) {\n state.multiSortMeta = this.d_multiSortMeta;\n }\n if (this.hasFilters) {\n state.filters = this.filters;\n }\n if (this.resizableColumns) {\n this.saveColumnWidths(state);\n }\n if (this.reorderableColumns) {\n state.columnOrder = this.d_columnOrder;\n }\n if (this.expandedRows) {\n state.expandedRows = this.expandedRows;\n }\n if (this.expandedRowGroups) {\n state.expandedRowGroups = this.expandedRowGroups;\n }\n if (this.selection) {\n state.selection = this.selection;\n state.selectionKeys = this.d_selectionKeys;\n }\n if (Object.keys(state).length) {\n storage.setItem(this.stateKey, JSON.stringify(state));\n }\n this.$emit('state-save', state);\n },\n restoreState: function restoreState() {\n var storage = this.getStorage();\n var stateString = storage.getItem(this.stateKey);\n var dateFormat = /\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}.\\d{3}Z/;\n var reviver = function reviver(key, value) {\n if (typeof value === 'string' && dateFormat.test(value)) {\n return new Date(value);\n }\n return value;\n };\n if (stateString) {\n var restoredState = JSON.parse(stateString, reviver);\n if (this.paginator) {\n this.d_first = restoredState.first;\n this.d_rows = restoredState.rows;\n }\n if (restoredState.sortField) {\n this.d_sortField = restoredState.sortField;\n this.d_sortOrder = restoredState.sortOrder;\n }\n if (restoredState.multiSortMeta) {\n this.d_multiSortMeta = restoredState.multiSortMeta;\n }\n if (restoredState.filters) {\n this.$emit('update:filters', restoredState.filters);\n }\n if (this.resizableColumns) {\n this.columnWidthsState = restoredState.columnWidths;\n this.tableWidthState = restoredState.tableWidth;\n }\n if (this.reorderableColumns) {\n this.d_columnOrder = restoredState.columnOrder;\n }\n if (restoredState.expandedRows) {\n this.$emit('update:expandedRows', restoredState.expandedRows);\n }\n if (restoredState.expandedRowGroups) {\n this.$emit('update:expandedRowGroups', restoredState.expandedRowGroups);\n }\n if (restoredState.selection) {\n this.d_selectionKeys = restoredState.d_selectionKeys;\n this.$emit('update:selection', restoredState.selection);\n }\n this.$emit('state-restore', restoredState);\n }\n },\n saveColumnWidths: function saveColumnWidths(state) {\n var widths = [];\n var headers = find(this.$el, 'thead[data-pc-section=\"thead\"] > tr > th');\n headers.forEach(function (header) {\n return widths.push(getOuterWidth(header));\n });\n state.columnWidths = widths.join(',');\n if (this.columnResizeMode === 'expand') {\n state.tableWidth = getOuterWidth(this.$refs.table) + 'px';\n }\n },\n addColumnWidthStyles: function addColumnWidthStyles(widths) {\n this.createStyleElement();\n var innerHTML = '';\n var selector = \"[data-pc-name=\\\"datatable\\\"][\".concat(this.attributeSelector, \"] > [data-pc-section=\\\"tablecontainer\\\"] \").concat(this.virtualScrollerDisabled ? '' : '> [data-pc-name=\"virtualscroller\"]', \" > table[data-pc-section=\\\"table\\\"]\");\n widths.forEach(function (width, index) {\n var style = \"width: \".concat(width, \"px !important; max-width: \").concat(width, \"px !important\");\n innerHTML += \"\\n \".concat(selector, \" > thead[data-pc-section=\\\"thead\\\"] > tr > th:nth-child(\").concat(index + 1, \"),\\n \").concat(selector, \" > tbody[data-pc-section=\\\"tbody\\\"] > tr > td:nth-child(\").concat(index + 1, \"),\\n \").concat(selector, \" > tfoot[data-pc-section=\\\"tfoot\\\"] > tr > td:nth-child(\").concat(index + 1, \") {\\n \").concat(style, \"\\n }\\n \");\n });\n this.styleElement.innerHTML = innerHTML;\n },\n restoreColumnWidths: function restoreColumnWidths() {\n if (this.columnWidthsState) {\n var widths = this.columnWidthsState.split(',');\n if (this.columnResizeMode === 'expand' && this.tableWidthState) {\n this.$refs.table.style.width = this.tableWidthState;\n this.$refs.table.style.minWidth = this.tableWidthState;\n }\n if (isNotEmpty(widths)) {\n this.addColumnWidthStyles(widths);\n }\n }\n },\n onCellEditInit: function onCellEditInit(event) {\n this.$emit('cell-edit-init', event);\n },\n onCellEditComplete: function onCellEditComplete(event) {\n this.$emit('cell-edit-complete', event);\n },\n onCellEditCancel: function onCellEditCancel(event) {\n this.$emit('cell-edit-cancel', event);\n },\n onRowEditInit: function onRowEditInit(event) {\n var _editingRows = this.editingRows ? _toConsumableArray(this.editingRows) : [];\n _editingRows.push(event.data);\n this.$emit('update:editingRows', _editingRows);\n this.$emit('row-edit-init', event);\n },\n onRowEditSave: function onRowEditSave(event) {\n var _editingRows = _toConsumableArray(this.editingRows);\n _editingRows.splice(this.findIndex(event.data, _editingRows), 1);\n this.$emit('update:editingRows', _editingRows);\n this.$emit('row-edit-save', event);\n },\n onRowEditCancel: function onRowEditCancel(event) {\n var _editingRows = _toConsumableArray(this.editingRows);\n _editingRows.splice(this.findIndex(event.data, _editingRows), 1);\n this.$emit('update:editingRows', _editingRows);\n this.$emit('row-edit-cancel', event);\n },\n onEditingMetaChange: function onEditingMetaChange(event) {\n var data = event.data,\n field = event.field,\n index = event.index,\n editing = event.editing;\n var editingMeta = _objectSpread$1({}, this.d_editingMeta);\n var meta = editingMeta[index];\n if (editing) {\n !meta && (meta = editingMeta[index] = {\n data: _objectSpread$1({}, data),\n fields: []\n });\n meta['fields'].push(field);\n } else if (meta) {\n var fields = meta['fields'].filter(function (f) {\n return f !== field;\n });\n !fields.length ? delete editingMeta[index] : meta['fields'] = fields;\n }\n this.d_editingMeta = editingMeta;\n },\n clearEditingMetaData: function clearEditingMetaData() {\n if (this.editMode) {\n this.d_editingMeta = {};\n }\n },\n createLazyLoadEvent: function createLazyLoadEvent(event) {\n return {\n originalEvent: event,\n first: this.d_first,\n rows: this.d_rows,\n sortField: this.d_sortField,\n sortOrder: this.d_sortOrder,\n multiSortMeta: this.d_multiSortMeta,\n filters: this.d_filters\n };\n },\n hasGlobalFilter: function hasGlobalFilter() {\n return this.filters && Object.prototype.hasOwnProperty.call(this.filters, 'global');\n },\n onFilterChange: function onFilterChange(filters) {\n this.d_filters = filters;\n },\n onFilterApply: function onFilterApply() {\n this.d_first = 0;\n this.$emit('update:first', this.d_first);\n this.$emit('update:filters', this.d_filters);\n if (this.lazy) {\n this.$emit('filter', this.createLazyLoadEvent());\n }\n },\n cloneFilters: function cloneFilters() {\n var cloned = {};\n if (this.filters) {\n Object.entries(this.filters).forEach(function (_ref3) {\n var _ref4 = _slicedToArray(_ref3, 2),\n prop = _ref4[0],\n value = _ref4[1];\n cloned[prop] = value.operator ? {\n operator: value.operator,\n constraints: value.constraints.map(function (constraint) {\n return _objectSpread$1({}, constraint);\n })\n } : _objectSpread$1({}, value);\n });\n }\n return cloned;\n },\n updateReorderableColumns: function updateReorderableColumns() {\n var _this10 = this;\n var columnOrder = [];\n this.columns.forEach(function (col) {\n return columnOrder.push(_this10.columnProp(col, 'columnKey') || _this10.columnProp(col, 'field'));\n });\n this.d_columnOrder = columnOrder;\n },\n createStyleElement: function createStyleElement() {\n var _this$$primevue;\n this.styleElement = document.createElement('style');\n this.styleElement.type = 'text/css';\n setAttribute(this.styleElement, 'nonce', (_this$$primevue = this.$primevue) === null || _this$$primevue === void 0 || (_this$$primevue = _this$$primevue.config) === null || _this$$primevue === void 0 || (_this$$primevue = _this$$primevue.csp) === null || _this$$primevue === void 0 ? void 0 : _this$$primevue.nonce);\n document.head.appendChild(this.styleElement);\n },\n destroyStyleElement: function destroyStyleElement() {\n if (this.styleElement) {\n document.head.removeChild(this.styleElement);\n this.styleElement = null;\n }\n },\n dataToRender: function dataToRender(data) {\n var _data = data || this.processedData;\n if (_data && this.paginator) {\n var first = this.lazy ? 0 : this.d_first;\n return _data.slice(first, first + this.d_rows);\n }\n return _data;\n },\n getVirtualScrollerRef: function getVirtualScrollerRef() {\n return this.$refs.virtualScroller;\n },\n hasSpacerStyle: function hasSpacerStyle(style) {\n return isNotEmpty(style);\n }\n },\n computed: {\n columns: function columns() {\n var cols = this.d_columns.get(this);\n if (this.reorderableColumns && this.d_columnOrder) {\n var orderedColumns = [];\n var _iterator5 = _createForOfIteratorHelper(this.d_columnOrder),\n _step5;\n try {\n for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {\n var columnKey = _step5.value;\n var column = this.findColumnByKey(cols, columnKey);\n if (column && !this.columnProp(column, 'hidden')) {\n orderedColumns.push(column);\n }\n }\n } catch (err) {\n _iterator5.e(err);\n } finally {\n _iterator5.f();\n }\n return [].concat(orderedColumns, _toConsumableArray(cols.filter(function (item) {\n return orderedColumns.indexOf(item) < 0;\n })));\n }\n return cols;\n },\n columnGroups: function columnGroups() {\n return this.d_columnGroups.get(this);\n },\n headerColumnGroup: function headerColumnGroup() {\n var _this$columnGroups,\n _this11 = this;\n return (_this$columnGroups = this.columnGroups) === null || _this$columnGroups === void 0 ? void 0 : _this$columnGroups.find(function (group) {\n return _this11.columnProp(group, 'type') === 'header';\n });\n },\n footerColumnGroup: function footerColumnGroup() {\n var _this$columnGroups2,\n _this12 = this;\n return (_this$columnGroups2 = this.columnGroups) === null || _this$columnGroups2 === void 0 ? void 0 : _this$columnGroups2.find(function (group) {\n return _this12.columnProp(group, 'type') === 'footer';\n });\n },\n hasFilters: function hasFilters() {\n return this.filters && Object.keys(this.filters).length > 0 && this.filters.constructor === Object;\n },\n processedData: function processedData() {\n var _this$virtualScroller;\n var data = this.value || [];\n if (!this.lazy && !((_this$virtualScroller = this.virtualScrollerOptions) !== null && _this$virtualScroller !== void 0 && _this$virtualScroller.lazy)) {\n if (data && data.length) {\n if (this.hasFilters) {\n data = this.filter(data);\n }\n if (this.sorted) {\n if (this.sortMode === 'single') data = this.sortSingle(data);else if (this.sortMode === 'multiple') data = this.sortMultiple(data);\n }\n }\n }\n return data;\n },\n totalRecordsLength: function totalRecordsLength() {\n if (this.lazy) {\n return this.totalRecords;\n } else {\n var data = this.processedData;\n return data ? data.length : 0;\n }\n },\n empty: function empty() {\n var data = this.processedData;\n return !data || data.length === 0;\n },\n paginatorTop: function paginatorTop() {\n return this.paginator && (this.paginatorPosition !== 'bottom' || this.paginatorPosition === 'both');\n },\n paginatorBottom: function paginatorBottom() {\n return this.paginator && (this.paginatorPosition !== 'top' || this.paginatorPosition === 'both');\n },\n sorted: function sorted() {\n return this.d_sortField || this.d_multiSortMeta && this.d_multiSortMeta.length > 0;\n },\n allRowsSelected: function allRowsSelected() {\n var _this13 = this;\n if (this.selectAll !== null) {\n return this.selectAll;\n } else {\n var val = this.frozenValue ? [].concat(_toConsumableArray(this.frozenValue), _toConsumableArray(this.processedData)) : this.processedData;\n return isNotEmpty(val) && this.selection && Array.isArray(this.selection) && val.every(function (v) {\n return _this13.selection.some(function (s) {\n return _this13.equals(s, v);\n });\n });\n }\n },\n attributeSelector: function attributeSelector() {\n return UniqueComponentId();\n },\n groupRowSortField: function groupRowSortField() {\n return this.sortMode === 'single' ? this.sortField : this.d_groupRowsSortMeta ? this.d_groupRowsSortMeta.field : null;\n },\n headerFilterButtonProps: function headerFilterButtonProps() {\n return _objectSpread$1(_objectSpread$1({\n filter: {\n severity: 'secondary',\n text: true,\n rounded: true\n }\n }, this.filterButtonProps), {}, {\n inline: _objectSpread$1({\n clear: {\n severity: 'secondary',\n text: true,\n rounded: true\n }\n }, this.filterButtonProps.inline),\n popover: _objectSpread$1({\n addRule: {\n severity: 'info',\n text: true,\n size: 'small'\n },\n removeRule: {\n severity: 'danger',\n text: true,\n size: 'small'\n },\n apply: {\n size: 'small'\n },\n clear: {\n outlined: true,\n size: 'small'\n }\n }, this.filterButtonProps.popover)\n });\n },\n rowEditButtonProps: function rowEditButtonProps() {\n return _objectSpread$1(_objectSpread$1({}, {\n init: {\n severity: 'secondary',\n text: true,\n rounded: true\n },\n save: {\n severity: 'secondary',\n text: true,\n rounded: true\n },\n cancel: {\n severity: 'secondary',\n text: true,\n rounded: true\n }\n }), this.editButtonProps);\n },\n virtualScrollerDisabled: function virtualScrollerDisabled() {\n return isEmpty(this.virtualScrollerOptions) || !this.scrollable;\n }\n },\n components: {\n DTPaginator: Paginator,\n DTTableHeader: script$1,\n DTTableBody: script$7,\n DTTableFooter: script$5,\n DTVirtualScroller: VirtualScroller,\n ArrowDownIcon: ArrowDownIcon,\n ArrowUpIcon: ArrowUpIcon,\n SpinnerIcon: SpinnerIcon\n }\n};\n\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n var _component_SpinnerIcon = resolveComponent(\"SpinnerIcon\");\n var _component_DTPaginator = resolveComponent(\"DTPaginator\");\n var _component_DTTableHeader = resolveComponent(\"DTTableHeader\");\n var _component_DTTableBody = resolveComponent(\"DTTableBody\");\n var _component_DTTableFooter = resolveComponent(\"DTTableFooter\");\n var _component_DTVirtualScroller = resolveComponent(\"DTVirtualScroller\");\n return openBlock(), createElementBlock(\"div\", mergeProps({\n \"class\": _ctx.cx('root'),\n \"data-scrollselectors\": \".p-datatable-wrapper\"\n }, _ctx.ptmi('root')), [renderSlot(_ctx.$slots, \"default\"), _ctx.loading ? (openBlock(), createElementBlock(\"div\", mergeProps({\n key: 0,\n \"class\": _ctx.cx('mask')\n }, _ctx.ptm('mask')), [_ctx.$slots.loading ? renderSlot(_ctx.$slots, \"loading\", {\n key: 0\n }) : (openBlock(), createElementBlock(Fragment, {\n key: 1\n }, [_ctx.$slots.loadingicon ? (openBlock(), createBlock(resolveDynamicComponent(_ctx.$slots.loadingicon), {\n key: 0,\n \"class\": normalizeClass(_ctx.cx('loadingIcon'))\n }, null, 8, [\"class\"])) : _ctx.loadingIcon ? (openBlock(), createElementBlock(\"i\", mergeProps({\n key: 1,\n \"class\": [_ctx.cx('loadingIcon'), 'pi-spin', _ctx.loadingIcon]\n }, _ctx.ptm('loadingIcon')), null, 16)) : (openBlock(), createBlock(_component_SpinnerIcon, mergeProps({\n key: 2,\n spin: \"\",\n \"class\": _ctx.cx('loadingIcon')\n }, _ctx.ptm('loadingIcon')), null, 16, [\"class\"]))], 64))], 16)) : createCommentVNode(\"\", true), _ctx.$slots.header ? (openBlock(), createElementBlock(\"div\", mergeProps({\n key: 1,\n \"class\": _ctx.cx('header')\n }, _ctx.ptm('header')), [renderSlot(_ctx.$slots, \"header\")], 16)) : createCommentVNode(\"\", true), $options.paginatorTop ? (openBlock(), createBlock(_component_DTPaginator, {\n key: 2,\n rows: $data.d_rows,\n first: $data.d_first,\n totalRecords: $options.totalRecordsLength,\n pageLinkSize: _ctx.pageLinkSize,\n template: _ctx.paginatorTemplate,\n rowsPerPageOptions: _ctx.rowsPerPageOptions,\n currentPageReportTemplate: _ctx.currentPageReportTemplate,\n \"class\": normalizeClass(_ctx.cx('pcPaginator', {\n position: 'top'\n })),\n onPage: _cache[0] || (_cache[0] = function ($event) {\n return $options.onPage($event);\n }),\n alwaysShow: _ctx.alwaysShowPaginator,\n unstyled: _ctx.unstyled,\n pt: _ctx.ptm('pcPaginator')\n }, createSlots({\n _: 2\n }, [_ctx.$slots.paginatorstart ? {\n name: \"start\",\n fn: withCtx(function () {\n return [renderSlot(_ctx.$slots, \"paginatorstart\")];\n }),\n key: \"0\"\n } : undefined, _ctx.$slots.paginatorend ? {\n name: \"end\",\n fn: withCtx(function () {\n return [renderSlot(_ctx.$slots, \"paginatorend\")];\n }),\n key: \"1\"\n } : undefined, _ctx.$slots.paginatorfirstpagelinkicon ? {\n name: \"firstpagelinkicon\",\n fn: withCtx(function (slotProps) {\n return [renderSlot(_ctx.$slots, \"paginatorfirstpagelinkicon\", {\n \"class\": normalizeClass(slotProps[\"class\"])\n })];\n }),\n key: \"2\"\n } : undefined, _ctx.$slots.paginatorprevpagelinkicon ? {\n name: \"prevpagelinkicon\",\n fn: withCtx(function (slotProps) {\n return [renderSlot(_ctx.$slots, \"paginatorprevpagelinkicon\", {\n \"class\": normalizeClass(slotProps[\"class\"])\n })];\n }),\n key: \"3\"\n } : undefined, _ctx.$slots.paginatornextpagelinkicon ? {\n name: \"nextpagelinkicon\",\n fn: withCtx(function (slotProps) {\n return [renderSlot(_ctx.$slots, \"paginatornextpagelinkicon\", {\n \"class\": normalizeClass(slotProps[\"class\"])\n })];\n }),\n key: \"4\"\n } : undefined, _ctx.$slots.paginatorlastpagelinkicon ? {\n name: \"lastpagelinkicon\",\n fn: withCtx(function (slotProps) {\n return [renderSlot(_ctx.$slots, \"paginatorlastpagelinkicon\", {\n \"class\": normalizeClass(slotProps[\"class\"])\n })];\n }),\n key: \"5\"\n } : undefined, _ctx.$slots.paginatorjumptopagedropdownicon ? {\n name: \"jumptopagedropdownicon\",\n fn: withCtx(function (slotProps) {\n return [renderSlot(_ctx.$slots, \"paginatorjumptopagedropdownicon\", {\n \"class\": normalizeClass(slotProps[\"class\"])\n })];\n }),\n key: \"6\"\n } : undefined, _ctx.$slots.paginatorrowsperpagedropdownicon ? {\n name: \"rowsperpagedropdownicon\",\n fn: withCtx(function (slotProps) {\n return [renderSlot(_ctx.$slots, \"paginatorrowsperpagedropdownicon\", {\n \"class\": normalizeClass(slotProps[\"class\"])\n })];\n }),\n key: \"7\"\n } : undefined]), 1032, [\"rows\", \"first\", \"totalRecords\", \"pageLinkSize\", \"template\", \"rowsPerPageOptions\", \"currentPageReportTemplate\", \"class\", \"alwaysShow\", \"unstyled\", \"pt\"])) : createCommentVNode(\"\", true), createElementVNode(\"div\", mergeProps({\n \"class\": _ctx.cx('tableContainer'),\n style: [_ctx.sx('tableContainer'), {\n maxHeight: $options.virtualScrollerDisabled ? _ctx.scrollHeight : ''\n }]\n }, _ctx.ptm('tableContainer')), [createVNode(_component_DTVirtualScroller, mergeProps({\n ref: \"virtualScroller\"\n }, _ctx.virtualScrollerOptions, {\n items: $options.processedData,\n columns: $options.columns,\n style: _ctx.scrollHeight !== 'flex' ? {\n height: _ctx.scrollHeight\n } : undefined,\n scrollHeight: _ctx.scrollHeight !== 'flex' ? undefined : '100%',\n disabled: $options.virtualScrollerDisabled,\n loaderDisabled: \"\",\n inline: \"\",\n autoSize: \"\",\n showSpacer: false,\n pt: _ctx.ptm('virtualScroller')\n }), {\n content: withCtx(function (slotProps) {\n return [createElementVNode(\"table\", mergeProps({\n ref: \"table\",\n role: \"table\",\n \"class\": [_ctx.cx('table'), _ctx.tableClass],\n style: [_ctx.tableStyle, slotProps.spacerStyle]\n }, _objectSpread(_objectSpread({}, _ctx.tableProps), _ctx.ptm('table'))), [createVNode(_component_DTTableHeader, {\n columnGroup: $options.headerColumnGroup,\n columns: slotProps.columns,\n rowGroupMode: _ctx.rowGroupMode,\n groupRowsBy: _ctx.groupRowsBy,\n groupRowSortField: $options.groupRowSortField,\n reorderableColumns: _ctx.reorderableColumns,\n resizableColumns: _ctx.resizableColumns,\n allRowsSelected: $options.allRowsSelected,\n empty: $options.empty,\n sortMode: _ctx.sortMode,\n sortField: $data.d_sortField,\n sortOrder: $data.d_sortOrder,\n multiSortMeta: $data.d_multiSortMeta,\n filters: $data.d_filters,\n filtersStore: _ctx.filters,\n filterDisplay: _ctx.filterDisplay,\n filterButtonProps: $options.headerFilterButtonProps,\n filterInputProps: _ctx.filterInputProps,\n first: $data.d_first,\n onColumnClick: _cache[1] || (_cache[1] = function ($event) {\n return $options.onColumnHeaderClick($event);\n }),\n onColumnMousedown: _cache[2] || (_cache[2] = function ($event) {\n return $options.onColumnHeaderMouseDown($event);\n }),\n onFilterChange: $options.onFilterChange,\n onFilterApply: $options.onFilterApply,\n onColumnDragstart: _cache[3] || (_cache[3] = function ($event) {\n return $options.onColumnHeaderDragStart($event);\n }),\n onColumnDragover: _cache[4] || (_cache[4] = function ($event) {\n return $options.onColumnHeaderDragOver($event);\n }),\n onColumnDragleave: _cache[5] || (_cache[5] = function ($event) {\n return $options.onColumnHeaderDragLeave($event);\n }),\n onColumnDrop: _cache[6] || (_cache[6] = function ($event) {\n return $options.onColumnHeaderDrop($event);\n }),\n onColumnResizestart: _cache[7] || (_cache[7] = function ($event) {\n return $options.onColumnResizeStart($event);\n }),\n onCheckboxChange: _cache[8] || (_cache[8] = function ($event) {\n return $options.toggleRowsWithCheckbox($event);\n }),\n unstyled: _ctx.unstyled,\n pt: _ctx.pt\n }, null, 8, [\"columnGroup\", \"columns\", \"rowGroupMode\", \"groupRowsBy\", \"groupRowSortField\", \"reorderableColumns\", \"resizableColumns\", \"allRowsSelected\", \"empty\", \"sortMode\", \"sortField\", \"sortOrder\", \"multiSortMeta\", \"filters\", \"filtersStore\", \"filterDisplay\", \"filterButtonProps\", \"filterInputProps\", \"first\", \"onFilterChange\", \"onFilterApply\", \"unstyled\", \"pt\"]), _ctx.frozenValue ? (openBlock(), createBlock(_component_DTTableBody, {\n key: 0,\n ref: \"frozenBodyRef\",\n value: _ctx.frozenValue,\n frozenRow: true,\n columns: slotProps.columns,\n first: $data.d_first,\n dataKey: _ctx.dataKey,\n selection: _ctx.selection,\n selectionKeys: $data.d_selectionKeys,\n selectionMode: _ctx.selectionMode,\n contextMenu: _ctx.contextMenu,\n contextMenuSelection: _ctx.contextMenuSelection,\n rowGroupMode: _ctx.rowGroupMode,\n groupRowsBy: _ctx.groupRowsBy,\n expandableRowGroups: _ctx.expandableRowGroups,\n rowClass: _ctx.rowClass,\n rowStyle: _ctx.rowStyle,\n editMode: _ctx.editMode,\n compareSelectionBy: _ctx.compareSelectionBy,\n scrollable: _ctx.scrollable,\n expandedRowIcon: _ctx.expandedRowIcon,\n collapsedRowIcon: _ctx.collapsedRowIcon,\n expandedRows: _ctx.expandedRows,\n expandedRowGroups: _ctx.expandedRowGroups,\n editingRows: _ctx.editingRows,\n editingRowKeys: $data.d_editingRowKeys,\n templates: _ctx.$slots,\n editButtonProps: $options.rowEditButtonProps,\n isVirtualScrollerDisabled: true,\n onRowgroupToggle: $options.toggleRowGroup,\n onRowClick: _cache[9] || (_cache[9] = function ($event) {\n return $options.onRowClick($event);\n }),\n onRowDblclick: _cache[10] || (_cache[10] = function ($event) {\n return $options.onRowDblClick($event);\n }),\n onRowRightclick: _cache[11] || (_cache[11] = function ($event) {\n return $options.onRowRightClick($event);\n }),\n onRowTouchend: $options.onRowTouchEnd,\n onRowKeydown: $options.onRowKeyDown,\n onRowMousedown: $options.onRowMouseDown,\n onRowDragstart: _cache[12] || (_cache[12] = function ($event) {\n return $options.onRowDragStart($event);\n }),\n onRowDragover: _cache[13] || (_cache[13] = function ($event) {\n return $options.onRowDragOver($event);\n }),\n onRowDragleave: _cache[14] || (_cache[14] = function ($event) {\n return $options.onRowDragLeave($event);\n }),\n onRowDragend: _cache[15] || (_cache[15] = function ($event) {\n return $options.onRowDragEnd($event);\n }),\n onRowDrop: _cache[16] || (_cache[16] = function ($event) {\n return $options.onRowDrop($event);\n }),\n onRowToggle: _cache[17] || (_cache[17] = function ($event) {\n return $options.toggleRow($event);\n }),\n onRadioChange: _cache[18] || (_cache[18] = function ($event) {\n return $options.toggleRowWithRadio($event);\n }),\n onCheckboxChange: _cache[19] || (_cache[19] = function ($event) {\n return $options.toggleRowWithCheckbox($event);\n }),\n onCellEditInit: _cache[20] || (_cache[20] = function ($event) {\n return $options.onCellEditInit($event);\n }),\n onCellEditComplete: _cache[21] || (_cache[21] = function ($event) {\n return $options.onCellEditComplete($event);\n }),\n onCellEditCancel: _cache[22] || (_cache[22] = function ($event) {\n return $options.onCellEditCancel($event);\n }),\n onRowEditInit: _cache[23] || (_cache[23] = function ($event) {\n return $options.onRowEditInit($event);\n }),\n onRowEditSave: _cache[24] || (_cache[24] = function ($event) {\n return $options.onRowEditSave($event);\n }),\n onRowEditCancel: _cache[25] || (_cache[25] = function ($event) {\n return $options.onRowEditCancel($event);\n }),\n editingMeta: $data.d_editingMeta,\n onEditingMetaChange: $options.onEditingMetaChange,\n unstyled: _ctx.unstyled,\n pt: _ctx.pt\n }, null, 8, [\"value\", \"columns\", \"first\", \"dataKey\", \"selection\", \"selectionKeys\", \"selectionMode\", \"contextMenu\", \"contextMenuSelection\", \"rowGroupMode\", \"groupRowsBy\", \"expandableRowGroups\", \"rowClass\", \"rowStyle\", \"editMode\", \"compareSelectionBy\", \"scrollable\", \"expandedRowIcon\", \"collapsedRowIcon\", \"expandedRows\", \"expandedRowGroups\", \"editingRows\", \"editingRowKeys\", \"templates\", \"editButtonProps\", \"onRowgroupToggle\", \"onRowTouchend\", \"onRowKeydown\", \"onRowMousedown\", \"editingMeta\", \"onEditingMetaChange\", \"unstyled\", \"pt\"])) : createCommentVNode(\"\", true), createVNode(_component_DTTableBody, {\n ref: \"bodyRef\",\n value: $options.dataToRender(slotProps.rows),\n \"class\": normalizeClass(slotProps.styleClass),\n columns: slotProps.columns,\n empty: $options.empty,\n first: $data.d_first,\n dataKey: _ctx.dataKey,\n selection: _ctx.selection,\n selectionKeys: $data.d_selectionKeys,\n selectionMode: _ctx.selectionMode,\n contextMenu: _ctx.contextMenu,\n contextMenuSelection: _ctx.contextMenuSelection,\n rowGroupMode: _ctx.rowGroupMode,\n groupRowsBy: _ctx.groupRowsBy,\n expandableRowGroups: _ctx.expandableRowGroups,\n rowClass: _ctx.rowClass,\n rowStyle: _ctx.rowStyle,\n editMode: _ctx.editMode,\n compareSelectionBy: _ctx.compareSelectionBy,\n scrollable: _ctx.scrollable,\n expandedRowIcon: _ctx.expandedRowIcon,\n collapsedRowIcon: _ctx.collapsedRowIcon,\n expandedRows: _ctx.expandedRows,\n expandedRowGroups: _ctx.expandedRowGroups,\n editingRows: _ctx.editingRows,\n editingRowKeys: $data.d_editingRowKeys,\n templates: _ctx.$slots,\n editButtonProps: $options.rowEditButtonProps,\n virtualScrollerContentProps: slotProps,\n isVirtualScrollerDisabled: $options.virtualScrollerDisabled,\n onRowgroupToggle: $options.toggleRowGroup,\n onRowClick: _cache[26] || (_cache[26] = function ($event) {\n return $options.onRowClick($event);\n }),\n onRowDblclick: _cache[27] || (_cache[27] = function ($event) {\n return $options.onRowDblClick($event);\n }),\n onRowRightclick: _cache[28] || (_cache[28] = function ($event) {\n return $options.onRowRightClick($event);\n }),\n onRowTouchend: $options.onRowTouchEnd,\n onRowKeydown: function onRowKeydown($event) {\n return $options.onRowKeyDown($event, slotProps);\n },\n onRowMousedown: $options.onRowMouseDown,\n onRowDragstart: _cache[29] || (_cache[29] = function ($event) {\n return $options.onRowDragStart($event);\n }),\n onRowDragover: _cache[30] || (_cache[30] = function ($event) {\n return $options.onRowDragOver($event);\n }),\n onRowDragleave: _cache[31] || (_cache[31] = function ($event) {\n return $options.onRowDragLeave($event);\n }),\n onRowDragend: _cache[32] || (_cache[32] = function ($event) {\n return $options.onRowDragEnd($event);\n }),\n onRowDrop: _cache[33] || (_cache[33] = function ($event) {\n return $options.onRowDrop($event);\n }),\n onRowToggle: _cache[34] || (_cache[34] = function ($event) {\n return $options.toggleRow($event);\n }),\n onRadioChange: _cache[35] || (_cache[35] = function ($event) {\n return $options.toggleRowWithRadio($event);\n }),\n onCheckboxChange: _cache[36] || (_cache[36] = function ($event) {\n return $options.toggleRowWithCheckbox($event);\n }),\n onCellEditInit: _cache[37] || (_cache[37] = function ($event) {\n return $options.onCellEditInit($event);\n }),\n onCellEditComplete: _cache[38] || (_cache[38] = function ($event) {\n return $options.onCellEditComplete($event);\n }),\n onCellEditCancel: _cache[39] || (_cache[39] = function ($event) {\n return $options.onCellEditCancel($event);\n }),\n onRowEditInit: _cache[40] || (_cache[40] = function ($event) {\n return $options.onRowEditInit($event);\n }),\n onRowEditSave: _cache[41] || (_cache[41] = function ($event) {\n return $options.onRowEditSave($event);\n }),\n onRowEditCancel: _cache[42] || (_cache[42] = function ($event) {\n return $options.onRowEditCancel($event);\n }),\n editingMeta: $data.d_editingMeta,\n onEditingMetaChange: $options.onEditingMetaChange,\n unstyled: _ctx.unstyled,\n pt: _ctx.pt\n }, null, 8, [\"value\", \"class\", \"columns\", \"empty\", \"first\", \"dataKey\", \"selection\", \"selectionKeys\", \"selectionMode\", \"contextMenu\", \"contextMenuSelection\", \"rowGroupMode\", \"groupRowsBy\", \"expandableRowGroups\", \"rowClass\", \"rowStyle\", \"editMode\", \"compareSelectionBy\", \"scrollable\", \"expandedRowIcon\", \"collapsedRowIcon\", \"expandedRows\", \"expandedRowGroups\", \"editingRows\", \"editingRowKeys\", \"templates\", \"editButtonProps\", \"virtualScrollerContentProps\", \"isVirtualScrollerDisabled\", \"onRowgroupToggle\", \"onRowTouchend\", \"onRowKeydown\", \"onRowMousedown\", \"editingMeta\", \"onEditingMetaChange\", \"unstyled\", \"pt\"]), $options.hasSpacerStyle(slotProps.spacerStyle) ? (openBlock(), createElementBlock(\"tbody\", mergeProps({\n key: 1,\n \"class\": _ctx.cx('virtualScrollerSpacer'),\n style: {\n height: \"calc(\".concat(slotProps.spacerStyle.height, \" - \").concat(slotProps.rows.length * slotProps.itemSize, \"px)\")\n }\n }, _ctx.ptm('virtualScrollerSpacer')), null, 16)) : createCommentVNode(\"\", true), createVNode(_component_DTTableFooter, {\n columnGroup: $options.footerColumnGroup,\n columns: slotProps.columns,\n pt: _ctx.pt\n }, null, 8, [\"columnGroup\", \"columns\", \"pt\"])], 16)];\n }),\n _: 1\n }, 16, [\"items\", \"columns\", \"style\", \"scrollHeight\", \"disabled\", \"pt\"])], 16), $options.paginatorBottom ? (openBlock(), createBlock(_component_DTPaginator, {\n key: 3,\n rows: $data.d_rows,\n first: $data.d_first,\n totalRecords: $options.totalRecordsLength,\n pageLinkSize: _ctx.pageLinkSize,\n template: _ctx.paginatorTemplate,\n rowsPerPageOptions: _ctx.rowsPerPageOptions,\n currentPageReportTemplate: _ctx.currentPageReportTemplate,\n \"class\": normalizeClass(_ctx.cx('pcPaginator', {\n position: 'bottom'\n })),\n onPage: _cache[43] || (_cache[43] = function ($event) {\n return $options.onPage($event);\n }),\n alwaysShow: _ctx.alwaysShowPaginator,\n unstyled: _ctx.unstyled,\n pt: _ctx.ptm('pcPaginator')\n }, createSlots({\n _: 2\n }, [_ctx.$slots.paginatorstart ? {\n name: \"start\",\n fn: withCtx(function () {\n return [renderSlot(_ctx.$slots, \"paginatorstart\")];\n }),\n key: \"0\"\n } : undefined, _ctx.$slots.paginatorend ? {\n name: \"end\",\n fn: withCtx(function () {\n return [renderSlot(_ctx.$slots, \"paginatorend\")];\n }),\n key: \"1\"\n } : undefined, _ctx.$slots.paginatorfirstpagelinkicon ? {\n name: \"firstpagelinkicon\",\n fn: withCtx(function (slotProps) {\n return [renderSlot(_ctx.$slots, \"paginatorfirstpagelinkicon\", {\n \"class\": normalizeClass(slotProps[\"class\"])\n })];\n }),\n key: \"2\"\n } : undefined, _ctx.$slots.paginatorprevpagelinkicon ? {\n name: \"prevpagelinkicon\",\n fn: withCtx(function (slotProps) {\n return [renderSlot(_ctx.$slots, \"paginatorprevpagelinkicon\", {\n \"class\": normalizeClass(slotProps[\"class\"])\n })];\n }),\n key: \"3\"\n } : undefined, _ctx.$slots.paginatornextpagelinkicon ? {\n name: \"nextpagelinkicon\",\n fn: withCtx(function (slotProps) {\n return [renderSlot(_ctx.$slots, \"paginatornextpagelinkicon\", {\n \"class\": normalizeClass(slotProps[\"class\"])\n })];\n }),\n key: \"4\"\n } : undefined, _ctx.$slots.paginatorlastpagelinkicon ? {\n name: \"lastpagelinkicon\",\n fn: withCtx(function (slotProps) {\n return [renderSlot(_ctx.$slots, \"paginatorlastpagelinkicon\", {\n \"class\": normalizeClass(slotProps[\"class\"])\n })];\n }),\n key: \"5\"\n } : undefined, _ctx.$slots.paginatorjumptopagedropdownicon ? {\n name: \"jumptopagedropdownicon\",\n fn: withCtx(function (slotProps) {\n return [renderSlot(_ctx.$slots, \"paginatorjumptopagedropdownicon\", {\n \"class\": normalizeClass(slotProps[\"class\"])\n })];\n }),\n key: \"6\"\n } : undefined, _ctx.$slots.paginatorrowsperpagedropdownicon ? {\n name: \"rowsperpagedropdownicon\",\n fn: withCtx(function (slotProps) {\n return [renderSlot(_ctx.$slots, \"paginatorrowsperpagedropdownicon\", {\n \"class\": normalizeClass(slotProps[\"class\"])\n })];\n }),\n key: \"7\"\n } : undefined]), 1032, [\"rows\", \"first\", \"totalRecords\", \"pageLinkSize\", \"template\", \"rowsPerPageOptions\", \"currentPageReportTemplate\", \"class\", \"alwaysShow\", \"unstyled\", \"pt\"])) : createCommentVNode(\"\", true), _ctx.$slots.footer ? (openBlock(), createElementBlock(\"div\", mergeProps({\n key: 4,\n \"class\": _ctx.cx('footer')\n }, _ctx.ptm('footer')), [renderSlot(_ctx.$slots, \"footer\")], 16)) : createCommentVNode(\"\", true), createElementVNode(\"div\", mergeProps({\n ref: \"resizeHelper\",\n \"class\": _ctx.cx('columnResizeIndicator'),\n style: {\n \"display\": \"none\"\n }\n }, _ctx.ptm('columnResizeIndicator')), null, 16), _ctx.reorderableColumns ? (openBlock(), createElementBlock(\"span\", mergeProps({\n key: 5,\n ref: \"reorderIndicatorUp\",\n \"class\": _ctx.cx('rowReorderIndicatorUp'),\n style: {\n \"position\": \"absolute\",\n \"display\": \"none\"\n }\n }, _ctx.ptm('rowReorderIndicatorUp')), [(openBlock(), createBlock(resolveDynamicComponent(_ctx.$slots.rowreorderindicatorupicon || _ctx.$slots.reorderindicatorupicon || 'ArrowDownIcon')))], 16)) : createCommentVNode(\"\", true), _ctx.reorderableColumns ? (openBlock(), createElementBlock(\"span\", mergeProps({\n key: 6,\n ref: \"reorderIndicatorDown\",\n \"class\": _ctx.cx('rowReorderIndicatorDown'),\n style: {\n \"position\": \"absolute\",\n \"display\": \"none\"\n }\n }, _ctx.ptm('rowReorderIndicatorDown')), [(openBlock(), createBlock(resolveDynamicComponent(_ctx.$slots.rowreorderindicatordownicon || _ctx.$slots.reorderindicatordownicon || 'ArrowUpIcon')))], 16)) : createCommentVNode(\"\", true)], 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseStyle from '@primevue/core/base/style';\n\nvar ColumnStyle = BaseStyle.extend({\n name: 'column'\n});\n\nexport { ColumnStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseComponent from '@primevue/core/basecomponent';\nimport ColumnStyle from 'primevue/column/style';\n\nvar script$1 = {\n name: 'BaseColumn',\n \"extends\": BaseComponent,\n props: {\n columnKey: {\n type: null,\n \"default\": null\n },\n field: {\n type: [String, Function],\n \"default\": null\n },\n sortField: {\n type: [String, Function],\n \"default\": null\n },\n filterField: {\n type: [String, Function],\n \"default\": null\n },\n dataType: {\n type: String,\n \"default\": 'text'\n },\n sortable: {\n type: Boolean,\n \"default\": false\n },\n header: {\n type: null,\n \"default\": null\n },\n footer: {\n type: null,\n \"default\": null\n },\n style: {\n type: null,\n \"default\": null\n },\n \"class\": {\n type: String,\n \"default\": null\n },\n headerStyle: {\n type: null,\n \"default\": null\n },\n headerClass: {\n type: String,\n \"default\": null\n },\n bodyStyle: {\n type: null,\n \"default\": null\n },\n bodyClass: {\n type: String,\n \"default\": null\n },\n footerStyle: {\n type: null,\n \"default\": null\n },\n footerClass: {\n type: String,\n \"default\": null\n },\n showFilterMenu: {\n type: Boolean,\n \"default\": true\n },\n showFilterOperator: {\n type: Boolean,\n \"default\": true\n },\n showClearButton: {\n type: Boolean,\n \"default\": true\n },\n showApplyButton: {\n type: Boolean,\n \"default\": true\n },\n showFilterMatchModes: {\n type: Boolean,\n \"default\": true\n },\n showAddButton: {\n type: Boolean,\n \"default\": true\n },\n filterMatchModeOptions: {\n type: Array,\n \"default\": null\n },\n maxConstraints: {\n type: Number,\n \"default\": 2\n },\n excludeGlobalFilter: {\n type: Boolean,\n \"default\": false\n },\n filterHeaderClass: {\n type: String,\n \"default\": null\n },\n filterHeaderStyle: {\n type: null,\n \"default\": null\n },\n filterMenuClass: {\n type: String,\n \"default\": null\n },\n filterMenuStyle: {\n type: null,\n \"default\": null\n },\n selectionMode: {\n type: String,\n \"default\": null\n },\n expander: {\n type: Boolean,\n \"default\": false\n },\n colspan: {\n type: Number,\n \"default\": null\n },\n rowspan: {\n type: Number,\n \"default\": null\n },\n rowReorder: {\n type: Boolean,\n \"default\": false\n },\n rowReorderIcon: {\n type: String,\n \"default\": undefined\n },\n reorderableColumn: {\n type: Boolean,\n \"default\": true\n },\n rowEditor: {\n type: Boolean,\n \"default\": false\n },\n frozen: {\n type: Boolean,\n \"default\": false\n },\n alignFrozen: {\n type: String,\n \"default\": 'left'\n },\n exportable: {\n type: Boolean,\n \"default\": true\n },\n exportHeader: {\n type: String,\n \"default\": null\n },\n exportFooter: {\n type: String,\n \"default\": null\n },\n filterMatchMode: {\n type: String,\n \"default\": null\n },\n hidden: {\n type: Boolean,\n \"default\": false\n }\n },\n style: ColumnStyle,\n provide: function provide() {\n return {\n $pcColumn: this,\n $parentInstance: this\n };\n }\n};\n\nvar script = {\n name: 'Column',\n \"extends\": script$1,\n inheritAttrs: false,\n inject: ['$columns'],\n mounted: function mounted() {\n var _this$$columns;\n (_this$$columns = this.$columns) === null || _this$$columns === void 0 || _this$$columns.add(this.$);\n },\n unmounted: function unmounted() {\n var _this$$columns2;\n (_this$$columns2 = this.$columns) === null || _this$$columns2 === void 0 || _this$$columns2[\"delete\"](this.$);\n },\n render: function render() {\n return null;\n }\n};\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseStyle from '@primevue/core/base/style';\n\nvar theme = function theme(_ref) {\n var dt = _ref.dt;\n return \"\\n.p-confirmpopup {\\n position: absolute;\\n margin-top: \".concat(dt('confirmpopup.gutter'), \";\\n top: 0;\\n left: 0;\\n background: \").concat(dt('confirmpopup.background'), \";\\n color: \").concat(dt('confirmpopup.color'), \";\\n border: 1px solid \").concat(dt('confirmpopup.border.color'), \";\\n border-radius: \").concat(dt('confirmpopup.border.radius'), \";\\n box-shadow: \").concat(dt('confirmpopup.shadow'), \";\\n}\\n\\n.p-confirmpopup-content {\\n display: flex;\\n align-items: center;\\n padding: \").concat(dt('confirmpopup.content.padding'), \";\\n gap: \").concat(dt('confirmpopup.content.gap'), \";\\n}\\n\\n.p-confirmpopup-icon {\\n font-size: \").concat(dt('confirmpopup.icon.size'), \";\\n width: \").concat(dt('confirmpopup.icon.size'), \";\\n height: \").concat(dt('confirmpopup.icon.size'), \";\\n color: \").concat(dt('confirmpopup.icon.color'), \";\\n}\\n\\n.p-confirmpopup-footer {\\n display: flex;\\n justify-content: flex-end;\\n gap: \").concat(dt('confirmpopup.footer.gap'), \";\\n padding: \").concat(dt('confirmpopup.footer.padding'), \";\\n}\\n\\n.p-confirmpopup-footer button {\\n width: auto;\\n}\\n\\n.p-confirmpopup-footer button:last-child {\\n margin: 0;\\n}\\n\\n.p-confirmpopup-flipped {\\n margin-top: calc(\").concat(dt('confirmpopup.gutter'), \" * -1);\\n margin-bottom: \").concat(dt('confirmpopup.gutter'), \";\\n}\\n\\n.p-confirmpopup-enter-from {\\n opacity: 0;\\n transform: scaleY(0.8);\\n}\\n\\n.p-confirmpopup-leave-to {\\n opacity: 0;\\n}\\n\\n.p-confirmpopup-enter-active {\\n transition: transform 0.12s cubic-bezier(0, 0, 0.2, 1), opacity 0.12s cubic-bezier(0, 0, 0.2, 1);\\n}\\n\\n.p-confirmpopup-leave-active {\\n transition: opacity 0.1s linear;\\n}\\n\\n.p-confirmpopup:after,\\n.p-confirmpopup:before {\\n bottom: 100%;\\n left: \").concat(dt('confirmpopup.arrow.offset'), \";\\n content: \\\" \\\";\\n height: 0;\\n width: 0;\\n position: absolute;\\n pointer-events: none;\\n}\\n\\n.p-confirmpopup:after {\\n border-width: calc(\").concat(dt('confirmpopup.gutter'), \" - 2px);\\n margin-left: calc(-1 * (\").concat(dt('confirmpopup.gutter'), \" - 2px));\\n border-style: solid;\\n border-color: transparent;\\n border-bottom-color: \").concat(dt('confirmpopup.background'), \";\\n}\\n\\n.p-confirmpopup:before {\\n border-width: \").concat(dt('confirmpopup.gutter'), \";\\n margin-left: calc(-1 * \").concat(dt('confirmpopup.gutter'), \");\\n border-style: solid;\\n border-color: transparent;\\n border-bottom-color: \").concat(dt('confirmpopup.border.color'), \";\\n}\\n\\n.p-confirmpopup-flipped:after,\\n.p-confirmpopup-flipped:before {\\n bottom: auto;\\n top: 100%;\\n}\\n\\n.p-confirmpopup-flipped:after {\\n border-bottom-color: transparent;\\n border-top-color: \").concat(dt('confirmpopup.background'), \";\\n}\\n\\n.p-confirmpopup-flipped:before {\\n border-bottom-color: transparent;\\n border-top-color: \").concat(dt('confirmpopup.border.color'), \";\\n}\\n\");\n};\nvar classes = {\n root: 'p-confirmpopup p-component',\n content: 'p-confirmpopup-content',\n icon: 'p-confirmpopup-icon',\n message: 'p-confirmpopup-message',\n footer: 'p-confirmpopup-footer',\n pcRejectButton: 'p-confirmpopup-reject-button',\n pcAcceptButton: 'p-confirmpopup-accept-button'\n};\nvar ConfirmPopupStyle = BaseStyle.extend({\n name: 'confirmpopup',\n theme: theme,\n classes: classes\n});\n\nexport { ConfirmPopupStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import { ConnectedOverlayScrollHandler } from '@primevue/core/utils';\nimport { focus, absolutePosition, getOffset, addClass, isTouchDevice } from '@primeuix/utils/dom';\nimport { ZIndex } from '@primeuix/utils/zindex';\nimport { $dt } from '@primeuix/styled';\nimport Button from 'primevue/button';\nimport ConfirmationEventBus from 'primevue/confirmationeventbus';\nimport FocusTrap from 'primevue/focustrap';\nimport OverlayEventBus from 'primevue/overlayeventbus';\nimport Portal from 'primevue/portal';\nimport BaseComponent from '@primevue/core/basecomponent';\nimport ConfirmPopupStyle from 'primevue/confirmpopup/style';\nimport { resolveComponent, resolveDirective, openBlock, createBlock, withCtx, createVNode, Transition, mergeProps, withDirectives, createElementBlock, renderSlot, Fragment, resolveDynamicComponent, normalizeClass, createCommentVNode, createElementVNode, toDisplayString, createSlots } from 'vue';\n\nvar script$1 = {\n name: 'BaseConfirmPopup',\n \"extends\": BaseComponent,\n props: {\n group: String\n },\n style: ConfirmPopupStyle,\n provide: function provide() {\n return {\n $pcConfirmPopup: this,\n $parentInstance: this\n };\n }\n};\n\nvar script = {\n name: 'ConfirmPopup',\n \"extends\": script$1,\n inheritAttrs: false,\n data: function data() {\n return {\n visible: false,\n confirmation: null,\n autoFocusAccept: null,\n autoFocusReject: null\n };\n },\n target: null,\n outsideClickListener: null,\n scrollHandler: null,\n resizeListener: null,\n container: null,\n confirmListener: null,\n closeListener: null,\n mounted: function mounted() {\n var _this = this;\n this.confirmListener = function (options) {\n if (!options) {\n return;\n }\n if (options.group === _this.group) {\n _this.confirmation = options;\n _this.target = options.target;\n if (_this.confirmation.onShow) {\n _this.confirmation.onShow();\n }\n _this.visible = true;\n }\n };\n this.closeListener = function () {\n _this.visible = false;\n _this.confirmation = null;\n };\n ConfirmationEventBus.on('confirm', this.confirmListener);\n ConfirmationEventBus.on('close', this.closeListener);\n },\n beforeUnmount: function beforeUnmount() {\n ConfirmationEventBus.off('confirm', this.confirmListener);\n ConfirmationEventBus.off('close', this.closeListener);\n this.unbindOutsideClickListener();\n if (this.scrollHandler) {\n this.scrollHandler.destroy();\n this.scrollHandler = null;\n }\n this.unbindResizeListener();\n if (this.container) {\n ZIndex.clear(this.container);\n this.container = null;\n }\n this.target = null;\n this.confirmation = null;\n },\n methods: {\n accept: function accept() {\n if (this.confirmation.accept) {\n this.confirmation.accept();\n }\n this.visible = false;\n },\n reject: function reject() {\n if (this.confirmation.reject) {\n this.confirmation.reject();\n }\n this.visible = false;\n },\n onHide: function onHide() {\n if (this.confirmation.onHide) {\n this.confirmation.onHide();\n }\n this.visible = false;\n },\n onAcceptKeydown: function onAcceptKeydown(event) {\n if (event.code === 'Space' || event.code === 'Enter' || event.code === 'NumpadEnter') {\n this.accept();\n focus(this.target);\n event.preventDefault();\n }\n },\n onRejectKeydown: function onRejectKeydown(event) {\n if (event.code === 'Space' || event.code === 'Enter' || event.code === 'NumpadEnter') {\n this.reject();\n focus(this.target);\n event.preventDefault();\n }\n },\n onEnter: function onEnter(el) {\n this.autoFocusAccept = this.confirmation.defaultFocus === undefined || this.confirmation.defaultFocus === 'accept' ? true : false;\n this.autoFocusReject = this.confirmation.defaultFocus === 'reject' ? true : false;\n this.bindOutsideClickListener();\n this.bindScrollListener();\n this.bindResizeListener();\n ZIndex.set('overlay', el, this.$primevue.config.zIndex.overlay);\n },\n onAfterEnter: function onAfterEnter() {\n this.focus();\n },\n onLeave: function onLeave() {\n this.autoFocusAccept = null;\n this.autoFocusReject = null;\n this.unbindOutsideClickListener();\n this.unbindScrollListener();\n this.unbindResizeListener();\n },\n onAfterLeave: function onAfterLeave(el) {\n ZIndex.clear(el);\n },\n alignOverlay: function alignOverlay() {\n absolutePosition(this.container, this.target, false);\n var containerOffset = getOffset(this.container);\n var targetOffset = getOffset(this.target);\n var arrowLeft = 0;\n if (containerOffset.left < targetOffset.left) {\n arrowLeft = targetOffset.left - containerOffset.left;\n }\n this.container.style.setProperty($dt('overlay.arrow.left').name, \"\".concat(arrowLeft, \"px\"));\n if (containerOffset.top < targetOffset.top) {\n this.container.setAttribute('data-p-confirmpopup-flipped', 'true');\n !this.isUnstyled && addClass(this.container, 'p-confirmpopup-flipped');\n }\n },\n bindOutsideClickListener: function bindOutsideClickListener() {\n var _this2 = this;\n if (!this.outsideClickListener) {\n this.outsideClickListener = function (event) {\n if (_this2.visible && _this2.container && !_this2.container.contains(event.target) && !_this2.isTargetClicked(event)) {\n if (_this2.confirmation.onHide) {\n _this2.confirmation.onHide();\n }\n _this2.visible = false;\n } else {\n _this2.alignOverlay();\n }\n };\n document.addEventListener('click', this.outsideClickListener);\n }\n },\n unbindOutsideClickListener: function unbindOutsideClickListener() {\n if (this.outsideClickListener) {\n document.removeEventListener('click', this.outsideClickListener);\n this.outsideClickListener = null;\n }\n },\n bindScrollListener: function bindScrollListener() {\n var _this3 = this;\n if (!this.scrollHandler) {\n this.scrollHandler = new ConnectedOverlayScrollHandler(this.target, function () {\n if (_this3.visible) {\n _this3.visible = false;\n }\n });\n }\n this.scrollHandler.bindScrollListener();\n },\n unbindScrollListener: function unbindScrollListener() {\n if (this.scrollHandler) {\n this.scrollHandler.unbindScrollListener();\n }\n },\n bindResizeListener: function bindResizeListener() {\n var _this4 = this;\n if (!this.resizeListener) {\n this.resizeListener = function () {\n if (_this4.visible && !isTouchDevice()) {\n _this4.visible = false;\n }\n };\n window.addEventListener('resize', this.resizeListener);\n }\n },\n unbindResizeListener: function unbindResizeListener() {\n if (this.resizeListener) {\n window.removeEventListener('resize', this.resizeListener);\n this.resizeListener = null;\n }\n },\n focus: function focus() {\n var focusTarget = this.container.querySelector('[autofocus]');\n if (focusTarget) {\n focusTarget.focus({\n preventScroll: true\n }); // Firefox requires preventScroll\n }\n },\n isTargetClicked: function isTargetClicked(event) {\n return this.target && (this.target === event.target || this.target.contains(event.target));\n },\n containerRef: function containerRef(el) {\n this.container = el;\n },\n onOverlayClick: function onOverlayClick(event) {\n OverlayEventBus.emit('overlay-click', {\n originalEvent: event,\n target: this.target\n });\n },\n onOverlayKeydown: function onOverlayKeydown(event) {\n if (event.code === 'Escape') {\n ConfirmationEventBus.emit('close', this.closeListener);\n focus(this.target);\n }\n },\n getCXOptions: function getCXOptions(icon, iconProps) {\n return {\n contenxt: {\n icon: icon,\n iconClass: iconProps[\"class\"]\n }\n };\n }\n },\n computed: {\n message: function message() {\n return this.confirmation ? this.confirmation.message : null;\n },\n acceptLabel: function acceptLabel() {\n if (this.confirmation) {\n var confirmation = this.confirmation;\n return confirmation.acceptLabel ? confirmation.acceptLabel : confirmation.acceptProps ? confirmation.acceptProps.label || this.$primevue.config.locale.accept : null;\n }\n return null;\n },\n rejectLabel: function rejectLabel() {\n if (this.confirmation) {\n var confirmation = this.confirmation;\n return confirmation.rejectLabel ? confirmation.rejectLabel : confirmation.rejectProps ? confirmation.rejectProps.label || this.$primevue.config.locale.reject : null;\n }\n return null;\n },\n acceptIcon: function acceptIcon() {\n var _this$confirmation;\n return this.confirmation ? this.confirmation.acceptIcon : (_this$confirmation = this.confirmation) !== null && _this$confirmation !== void 0 && _this$confirmation.acceptProps ? this.confirmation.acceptProps.icon : null;\n },\n rejectIcon: function rejectIcon() {\n var _this$confirmation2;\n return this.confirmation ? this.confirmation.rejectIcon : (_this$confirmation2 = this.confirmation) !== null && _this$confirmation2 !== void 0 && _this$confirmation2.rejectProps ? this.confirmation.rejectProps.icon : null;\n }\n },\n components: {\n Button: Button,\n Portal: Portal\n },\n directives: {\n focustrap: FocusTrap\n }\n};\n\nvar _hoisted_1 = [\"aria-modal\"];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n var _component_Button = resolveComponent(\"Button\");\n var _component_Portal = resolveComponent(\"Portal\");\n var _directive_focustrap = resolveDirective(\"focustrap\");\n return openBlock(), createBlock(_component_Portal, null, {\n \"default\": withCtx(function () {\n return [createVNode(Transition, mergeProps({\n name: \"p-confirmpopup\",\n onEnter: $options.onEnter,\n onAfterEnter: $options.onAfterEnter,\n onLeave: $options.onLeave,\n onAfterLeave: $options.onAfterLeave\n }, _ctx.ptm('transition')), {\n \"default\": withCtx(function () {\n var _$data$confirmation$r, _$data$confirmation$r2, _$data$confirmation$a;\n return [$data.visible ? withDirectives((openBlock(), createElementBlock(\"div\", mergeProps({\n key: 0,\n ref: $options.containerRef,\n role: \"alertdialog\",\n \"class\": _ctx.cx('root'),\n \"aria-modal\": $data.visible,\n onClick: _cache[2] || (_cache[2] = function () {\n return $options.onOverlayClick && $options.onOverlayClick.apply($options, arguments);\n }),\n onKeydown: _cache[3] || (_cache[3] = function () {\n return $options.onOverlayKeydown && $options.onOverlayKeydown.apply($options, arguments);\n })\n }, _ctx.ptmi('root')), [_ctx.$slots.container ? renderSlot(_ctx.$slots, \"container\", {\n key: 0,\n message: $data.confirmation,\n acceptCallback: $options.accept,\n rejectCallback: $options.reject\n }) : (openBlock(), createElementBlock(Fragment, {\n key: 1\n }, [!_ctx.$slots.message ? (openBlock(), createElementBlock(\"div\", mergeProps({\n key: 0,\n \"class\": _ctx.cx('content')\n }, _ctx.ptm('content')), [renderSlot(_ctx.$slots, \"icon\", {}, function () {\n return [_ctx.$slots.icon ? (openBlock(), createBlock(resolveDynamicComponent(_ctx.$slots.icon), {\n key: 0,\n \"class\": normalizeClass(_ctx.cx('icon'))\n }, null, 8, [\"class\"])) : $data.confirmation.icon ? (openBlock(), createElementBlock(\"span\", mergeProps({\n key: 1,\n \"class\": [$data.confirmation.icon, _ctx.cx('icon')]\n }, _ctx.ptm('icon')), null, 16)) : createCommentVNode(\"\", true)];\n }), createElementVNode(\"span\", mergeProps({\n \"class\": _ctx.cx('message')\n }, _ctx.ptm('message')), toDisplayString($data.confirmation.message), 17)], 16)) : (openBlock(), createBlock(resolveDynamicComponent(_ctx.$slots.message), {\n key: 1,\n message: $data.confirmation\n }, null, 8, [\"message\"])), createElementVNode(\"div\", mergeProps({\n \"class\": _ctx.cx('footer')\n }, _ctx.ptm('footer')), [createVNode(_component_Button, mergeProps({\n \"class\": [_ctx.cx('pcRejectButton'), $data.confirmation.rejectClass],\n autofocus: $data.autoFocusReject,\n unstyled: _ctx.unstyled,\n size: ((_$data$confirmation$r = $data.confirmation.rejectProps) === null || _$data$confirmation$r === void 0 ? void 0 : _$data$confirmation$r.size) || 'small',\n text: ((_$data$confirmation$r2 = $data.confirmation.rejectProps) === null || _$data$confirmation$r2 === void 0 ? void 0 : _$data$confirmation$r2.text) || false,\n onClick: _cache[0] || (_cache[0] = function ($event) {\n return $options.reject();\n }),\n onKeydown: $options.onRejectKeydown\n }, $data.confirmation.rejectProps, {\n label: $options.rejectLabel,\n pt: _ctx.ptm('pcRejectButton')\n }), createSlots({\n _: 2\n }, [$options.rejectIcon || _ctx.$slots.rejecticon ? {\n name: \"icon\",\n fn: withCtx(function (iconProps) {\n return [renderSlot(_ctx.$slots, \"rejecticon\", {}, function () {\n return [createElementVNode(\"span\", mergeProps({\n \"class\": [$options.rejectIcon, iconProps[\"class\"]]\n }, _ctx.ptm('pcRejectButton')['icon'], {\n \"data-pc-section\": \"rejectbuttonicon\"\n }), null, 16)];\n })];\n }),\n key: \"0\"\n } : undefined]), 1040, [\"class\", \"autofocus\", \"unstyled\", \"size\", \"text\", \"onKeydown\", \"label\", \"pt\"]), createVNode(_component_Button, mergeProps({\n \"class\": [_ctx.cx('pcAcceptButton'), $data.confirmation.acceptClass],\n autofocus: $data.autoFocusAccept,\n unstyled: _ctx.unstyled,\n size: ((_$data$confirmation$a = $data.confirmation.acceptProps) === null || _$data$confirmation$a === void 0 ? void 0 : _$data$confirmation$a.size) || 'small',\n onClick: _cache[1] || (_cache[1] = function ($event) {\n return $options.accept();\n }),\n onKeydown: $options.onAcceptKeydown\n }, $data.confirmation.acceptProps, {\n label: $options.acceptLabel,\n pt: _ctx.ptm('pcAcceptButton')\n }), createSlots({\n _: 2\n }, [$options.acceptIcon || _ctx.$slots.accepticon ? {\n name: \"icon\",\n fn: withCtx(function (iconProps) {\n return [renderSlot(_ctx.$slots, \"accepticon\", {}, function () {\n return [createElementVNode(\"span\", mergeProps({\n \"class\": [$options.acceptIcon, iconProps[\"class\"]]\n }, _ctx.ptm('pcAcceptButton')['icon'], {\n \"data-pc-section\": \"acceptbuttonicon\"\n }), null, 16)];\n })];\n }),\n key: \"0\"\n } : undefined]), 1040, [\"class\", \"autofocus\", \"unstyled\", \"size\", \"onKeydown\", \"label\", \"pt\"])], 16)], 64))], 16, _hoisted_1)), [[_directive_focustrap]]) : createCommentVNode(\"\", true)];\n }),\n _: 3\n }, 16, [\"onEnter\", \"onAfterEnter\", \"onLeave\", \"onAfterLeave\"])];\n }),\n _: 3\n });\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseStyle from '@primevue/core/base/style';\n\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nvar theme = function theme(_ref) {\n var dt = _ref.dt;\n return \"\\n.p-toast {\\n width: \".concat(dt('toast.width'), \";\\n white-space: pre-line;\\n word-break: break-word;\\n}\\n\\n.p-toast-message {\\n margin: 0 0 1rem 0;\\n}\\n\\n.p-toast-message-icon {\\n flex-shrink: 0;\\n font-size: \").concat(dt('toast.icon.size'), \";\\n width: \").concat(dt('toast.icon.size'), \";\\n height: \").concat(dt('toast.icon.size'), \";\\n}\\n\\n.p-toast-message-content {\\n display: flex;\\n align-items: flex-start;\\n padding: \").concat(dt('toast.content.padding'), \";\\n gap: \").concat(dt('toast.content.gap'), \";\\n}\\n\\n.p-toast-message-text {\\n flex: 1 1 auto;\\n display: flex;\\n flex-direction: column;\\n gap: \").concat(dt('toast.text.gap'), \";\\n}\\n\\n.p-toast-summary {\\n font-weight: \").concat(dt('toast.summary.font.weight'), \";\\n font-size: \").concat(dt('toast.summary.font.size'), \";\\n}\\n\\n.p-toast-detail {\\n font-weight: \").concat(dt('toast.detail.font.weight'), \";\\n font-size: \").concat(dt('toast.detail.font.size'), \";\\n}\\n\\n.p-toast-close-button {\\n display: flex;\\n align-items: center;\\n justify-content: center;\\n overflow: hidden;\\n position: relative;\\n cursor: pointer;\\n background: transparent;\\n transition: background \").concat(dt('toast.transition.duration'), \", color \").concat(dt('toast.transition.duration'), \", outline-color \").concat(dt('toast.transition.duration'), \", box-shadow \").concat(dt('toast.transition.duration'), \";\\n outline-color: transparent;\\n color: inherit;\\n width: \").concat(dt('toast.close.button.width'), \";\\n height: \").concat(dt('toast.close.button.height'), \";\\n border-radius: \").concat(dt('toast.close.button.border.radius'), \";\\n margin: -25% 0 0 0;\\n right: -25%;\\n padding: 0;\\n border: none;\\n user-select: none;\\n}\\n\\n.p-toast-message-info,\\n.p-toast-message-success,\\n.p-toast-message-warn,\\n.p-toast-message-error,\\n.p-toast-message-secondary,\\n.p-toast-message-contrast {\\n border-width: \").concat(dt('toast.border.width'), \";\\n border-style: solid;\\n backdrop-filter: blur(\").concat(dt('toast.blur'), \");\\n border-radius: \").concat(dt('toast.border.radius'), \";\\n}\\n\\n.p-toast-close-icon {\\n font-size: \").concat(dt('toast.close.icon.size'), \";\\n width: \").concat(dt('toast.close.icon.size'), \";\\n height: \").concat(dt('toast.close.icon.size'), \";\\n}\\n\\n.p-toast-close-button:focus-visible {\\n outline-width: \").concat(dt('focus.ring.width'), \";\\n outline-style: \").concat(dt('focus.ring.style'), \";\\n outline-offset: \").concat(dt('focus.ring.offset'), \";\\n}\\n\\n.p-toast-message-info {\\n background: \").concat(dt('toast.info.background'), \";\\n border-color: \").concat(dt('toast.info.border.color'), \";\\n color: \").concat(dt('toast.info.color'), \";\\n box-shadow: \").concat(dt('toast.info.shadow'), \";\\n}\\n\\n.p-toast-message-info .p-toast-detail {\\n color: \").concat(dt('toast.info.detail.color'), \";\\n}\\n\\n.p-toast-message-info .p-toast-close-button:focus-visible {\\n outline-color: \").concat(dt('toast.info.close.button.focus.ring.color'), \";\\n box-shadow: \").concat(dt('toast.info.close.button.focus.ring.shadow'), \";\\n}\\n\\n.p-toast-message-info .p-toast-close-button:hover {\\n background: \").concat(dt('toast.info.close.button.hover.background'), \";\\n}\\n\\n.p-toast-message-success {\\n background: \").concat(dt('toast.success.background'), \";\\n border-color: \").concat(dt('toast.success.border.color'), \";\\n color: \").concat(dt('toast.success.color'), \";\\n box-shadow: \").concat(dt('toast.success.shadow'), \";\\n}\\n\\n.p-toast-message-success .p-toast-detail {\\n color: \").concat(dt('toast.success.detail.color'), \";\\n}\\n\\n.p-toast-message-success .p-toast-close-button:focus-visible {\\n outline-color: \").concat(dt('toast.success.close.button.focus.ring.color'), \";\\n box-shadow: \").concat(dt('toast.success.close.button.focus.ring.shadow'), \";\\n}\\n\\n.p-toast-message-success .p-toast-close-button:hover {\\n background: \").concat(dt('toast.success.close.button.hover.background'), \";\\n}\\n\\n.p-toast-message-warn {\\n background: \").concat(dt('toast.warn.background'), \";\\n border-color: \").concat(dt('toast.warn.border.color'), \";\\n color: \").concat(dt('toast.warn.color'), \";\\n box-shadow: \").concat(dt('toast.warn.shadow'), \";\\n}\\n\\n.p-toast-message-warn .p-toast-detail {\\n color: \").concat(dt('toast.warn.detail.color'), \";\\n}\\n\\n.p-toast-message-warn .p-toast-close-button:focus-visible {\\n outline-color: \").concat(dt('toast.warn.close.button.focus.ring.color'), \";\\n box-shadow: \").concat(dt('toast.warn.close.button.focus.ring.shadow'), \";\\n}\\n\\n.p-toast-message-warn .p-toast-close-button:hover {\\n background: \").concat(dt('toast.warn.close.button.hover.background'), \";\\n}\\n\\n.p-toast-message-error {\\n background: \").concat(dt('toast.error.background'), \";\\n border-color: \").concat(dt('toast.error.border.color'), \";\\n color: \").concat(dt('toast.error.color'), \";\\n box-shadow: \").concat(dt('toast.error.shadow'), \";\\n}\\n\\n.p-toast-message-error .p-toast-detail {\\n color: \").concat(dt('toast.error.detail.color'), \";\\n}\\n\\n.p-toast-message-error .p-toast-close-button:focus-visible {\\n outline-color: \").concat(dt('toast.error.close.button.focus.ring.color'), \";\\n box-shadow: \").concat(dt('toast.error.close.button.focus.ring.shadow'), \";\\n}\\n\\n.p-toast-message-error .p-toast-close-button:hover {\\n background: \").concat(dt('toast.error.close.button.hover.background'), \";\\n}\\n\\n.p-toast-message-secondary {\\n background: \").concat(dt('toast.secondary.background'), \";\\n border-color: \").concat(dt('toast.secondary.border.color'), \";\\n color: \").concat(dt('toast.secondary.color'), \";\\n box-shadow: \").concat(dt('toast.secondary.shadow'), \";\\n}\\n\\n.p-toast-message-secondary .p-toast-detail {\\n color: \").concat(dt('toast.secondary.detail.color'), \";\\n}\\n\\n.p-toast-message-secondary .p-toast-close-button:focus-visible {\\n outline-color: \").concat(dt('toast.secondary.close.button.focus.ring.color'), \";\\n box-shadow: \").concat(dt('toast.secondary.close.button.focus.ring.shadow'), \";\\n}\\n\\n.p-toast-message-secondary .p-toast-close-button:hover {\\n background: \").concat(dt('toast.secondary.close.button.hover.background'), \";\\n}\\n\\n.p-toast-message-contrast {\\n background: \").concat(dt('toast.contrast.background'), \";\\n border-color: \").concat(dt('toast.contrast.border.color'), \";\\n color: \").concat(dt('toast.contrast.color'), \";\\n box-shadow: \").concat(dt('toast.contrast.shadow'), \";\\n}\\n\\n.p-toast-message-contrast .p-toast-detail {\\n color: \").concat(dt('toast.contrast.detail.color'), \";\\n}\\n\\n.p-toast-message-contrast .p-toast-close-button:focus-visible {\\n outline-color: \").concat(dt('toast.contrast.close.button.focus.ring.color'), \";\\n box-shadow: \").concat(dt('toast.contrast.close.button.focus.ring.shadow'), \";\\n}\\n\\n.p-toast-message-contrast .p-toast-close-button:hover {\\n background: \").concat(dt('toast.contrast.close.button.hover.background'), \";\\n}\\n\\n.p-toast-top-center {\\n transform: translateX(-50%);\\n}\\n\\n.p-toast-bottom-center {\\n transform: translateX(-50%);\\n}\\n\\n.p-toast-center {\\n min-width: 20vw;\\n transform: translate(-50%, -50%);\\n}\\n\\n.p-toast-message-enter-from {\\n opacity: 0;\\n transform: translateY(50%);\\n}\\n\\n.p-toast-message-leave-from {\\n max-height: 1000px;\\n}\\n\\n.p-toast .p-toast-message.p-toast-message-leave-to {\\n max-height: 0;\\n opacity: 0;\\n margin-bottom: 0;\\n overflow: hidden;\\n}\\n\\n.p-toast-message-enter-active {\\n transition: transform 0.3s, opacity 0.3s;\\n}\\n\\n.p-toast-message-leave-active {\\n transition: max-height 0.45s cubic-bezier(0, 1, 0, 1), opacity 0.3s, margin-bottom 0.3s;\\n}\\n\");\n};\n\n// Position\nvar inlineStyles = {\n root: function root(_ref2) {\n var position = _ref2.position;\n return {\n position: 'fixed',\n top: position === 'top-right' || position === 'top-left' || position === 'top-center' ? '20px' : position === 'center' ? '50%' : null,\n right: (position === 'top-right' || position === 'bottom-right') && '20px',\n bottom: (position === 'bottom-left' || position === 'bottom-right' || position === 'bottom-center') && '20px',\n left: position === 'top-left' || position === 'bottom-left' ? '20px' : position === 'center' || position === 'top-center' || position === 'bottom-center' ? '50%' : null\n };\n }\n};\nvar classes = {\n root: function root(_ref3) {\n var props = _ref3.props;\n return ['p-toast p-component p-toast-' + props.position];\n },\n message: function message(_ref4) {\n var props = _ref4.props;\n return ['p-toast-message', {\n 'p-toast-message-info': props.message.severity === 'info' || props.message.severity === undefined,\n 'p-toast-message-warn': props.message.severity === 'warn',\n 'p-toast-message-error': props.message.severity === 'error',\n 'p-toast-message-success': props.message.severity === 'success',\n 'p-toast-message-secondary': props.message.severity === 'secondary',\n 'p-toast-message-contrast': props.message.severity === 'contrast'\n }];\n },\n messageContent: 'p-toast-message-content',\n messageIcon: function messageIcon(_ref5) {\n var props = _ref5.props;\n return ['p-toast-message-icon', _defineProperty(_defineProperty(_defineProperty(_defineProperty({}, props.infoIcon, props.message.severity === 'info'), props.warnIcon, props.message.severity === 'warn'), props.errorIcon, props.message.severity === 'error'), props.successIcon, props.message.severity === 'success')];\n },\n messageText: 'p-toast-message-text',\n summary: 'p-toast-summary',\n detail: 'p-toast-detail',\n closeButton: 'p-toast-close-button',\n closeIcon: 'p-toast-close-icon'\n};\nvar ToastStyle = BaseStyle.extend({\n name: 'toast',\n theme: theme,\n classes: classes,\n inlineStyles: inlineStyles\n});\n\nexport { ToastStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseIcon from '@primevue/icons/baseicon';\nimport { openBlock, createElementBlock, mergeProps, createElementVNode } from 'vue';\n\nvar script = {\n name: 'ExclamationTriangleIcon',\n \"extends\": BaseIcon\n};\n\nvar _hoisted_1 = /*#__PURE__*/createElementVNode(\"path\", {\n d: \"M13.4018 13.1893H0.598161C0.49329 13.189 0.390283 13.1615 0.299143 13.1097C0.208003 13.0578 0.131826 12.9832 0.0780112 12.8932C0.0268539 12.8015 0 12.6982 0 12.5931C0 12.4881 0.0268539 12.3848 0.0780112 12.293L6.47985 1.08982C6.53679 1.00399 6.61408 0.933574 6.70484 0.884867C6.7956 0.836159 6.897 0.810669 7 0.810669C7.103 0.810669 7.2044 0.836159 7.29516 0.884867C7.38592 0.933574 7.46321 1.00399 7.52015 1.08982L13.922 12.293C13.9731 12.3848 14 12.4881 14 12.5931C14 12.6982 13.9731 12.8015 13.922 12.8932C13.8682 12.9832 13.792 13.0578 13.7009 13.1097C13.6097 13.1615 13.5067 13.189 13.4018 13.1893ZM1.63046 11.989H12.3695L7 2.59425L1.63046 11.989Z\",\n fill: \"currentColor\"\n}, null, -1);\nvar _hoisted_2 = /*#__PURE__*/createElementVNode(\"path\", {\n d: \"M6.99996 8.78801C6.84143 8.78594 6.68997 8.72204 6.57787 8.60993C6.46576 8.49782 6.40186 8.34637 6.39979 8.18784V5.38703C6.39979 5.22786 6.46302 5.0752 6.57557 4.96265C6.68813 4.85009 6.84078 4.78686 6.99996 4.78686C7.15914 4.78686 7.31179 4.85009 7.42435 4.96265C7.5369 5.0752 7.60013 5.22786 7.60013 5.38703V8.18784C7.59806 8.34637 7.53416 8.49782 7.42205 8.60993C7.30995 8.72204 7.15849 8.78594 6.99996 8.78801Z\",\n fill: \"currentColor\"\n}, null, -1);\nvar _hoisted_3 = /*#__PURE__*/createElementVNode(\"path\", {\n d: \"M6.99996 11.1887C6.84143 11.1866 6.68997 11.1227 6.57787 11.0106C6.46576 10.8985 6.40186 10.7471 6.39979 10.5885V10.1884C6.39979 10.0292 6.46302 9.87658 6.57557 9.76403C6.68813 9.65147 6.84078 9.58824 6.99996 9.58824C7.15914 9.58824 7.31179 9.65147 7.42435 9.76403C7.5369 9.87658 7.60013 10.0292 7.60013 10.1884V10.5885C7.59806 10.7471 7.53416 10.8985 7.42205 11.0106C7.30995 11.1227 7.15849 11.1866 6.99996 11.1887Z\",\n fill: \"currentColor\"\n}, null, -1);\nvar _hoisted_4 = [_hoisted_1, _hoisted_2, _hoisted_3];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"svg\", mergeProps({\n width: \"14\",\n height: \"14\",\n viewBox: \"0 0 14 14\",\n fill: \"none\",\n xmlns: \"http://www.w3.org/2000/svg\"\n }, _ctx.pti()), _hoisted_4, 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseIcon from '@primevue/icons/baseicon';\nimport { openBlock, createElementBlock, mergeProps, createElementVNode } from 'vue';\n\nvar script = {\n name: 'InfoCircleIcon',\n \"extends\": BaseIcon\n};\n\nvar _hoisted_1 = /*#__PURE__*/createElementVNode(\"path\", {\n \"fill-rule\": \"evenodd\",\n \"clip-rule\": \"evenodd\",\n d: \"M3.11101 12.8203C4.26215 13.5895 5.61553 14 7 14C8.85652 14 10.637 13.2625 11.9497 11.9497C13.2625 10.637 14 8.85652 14 7C14 5.61553 13.5895 4.26215 12.8203 3.11101C12.0511 1.95987 10.9579 1.06266 9.67879 0.532846C8.3997 0.00303296 6.99224 -0.13559 5.63437 0.134506C4.2765 0.404603 3.02922 1.07129 2.05026 2.05026C1.07129 3.02922 0.404603 4.2765 0.134506 5.63437C-0.13559 6.99224 0.00303296 8.3997 0.532846 9.67879C1.06266 10.9579 1.95987 12.0511 3.11101 12.8203ZM3.75918 2.14976C4.71846 1.50879 5.84628 1.16667 7 1.16667C8.5471 1.16667 10.0308 1.78125 11.1248 2.87521C12.2188 3.96918 12.8333 5.45291 12.8333 7C12.8333 8.15373 12.4912 9.28154 11.8502 10.2408C11.2093 11.2001 10.2982 11.9478 9.23232 12.3893C8.16642 12.8308 6.99353 12.9463 5.86198 12.7212C4.73042 12.4962 3.69102 11.9406 2.87521 11.1248C2.05941 10.309 1.50384 9.26958 1.27876 8.13803C1.05367 7.00647 1.16919 5.83358 1.61071 4.76768C2.05222 3.70178 2.79989 2.79074 3.75918 2.14976ZM7.00002 4.8611C6.84594 4.85908 6.69873 4.79698 6.58977 4.68801C6.48081 4.57905 6.4187 4.43185 6.41669 4.27776V3.88888C6.41669 3.73417 6.47815 3.58579 6.58754 3.4764C6.69694 3.367 6.84531 3.30554 7.00002 3.30554C7.15473 3.30554 7.3031 3.367 7.4125 3.4764C7.52189 3.58579 7.58335 3.73417 7.58335 3.88888V4.27776C7.58134 4.43185 7.51923 4.57905 7.41027 4.68801C7.30131 4.79698 7.1541 4.85908 7.00002 4.8611ZM7.00002 10.6945C6.84594 10.6925 6.69873 10.6304 6.58977 10.5214C6.48081 10.4124 6.4187 10.2652 6.41669 10.1111V6.22225C6.41669 6.06754 6.47815 5.91917 6.58754 5.80977C6.69694 5.70037 6.84531 5.63892 7.00002 5.63892C7.15473 5.63892 7.3031 5.70037 7.4125 5.80977C7.52189 5.91917 7.58335 6.06754 7.58335 6.22225V10.1111C7.58134 10.2652 7.51923 10.4124 7.41027 10.5214C7.30131 10.6304 7.1541 10.6925 7.00002 10.6945Z\",\n fill: \"currentColor\"\n}, null, -1);\nvar _hoisted_2 = [_hoisted_1];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"svg\", mergeProps({\n width: \"14\",\n height: \"14\",\n viewBox: \"0 0 14 14\",\n fill: \"none\",\n xmlns: \"http://www.w3.org/2000/svg\"\n }, _ctx.pti()), _hoisted_2, 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import { UniqueComponentId } from '@primevue/core/utils';\nimport { setAttribute } from '@primeuix/utils/dom';\nimport { isEmpty } from '@primeuix/utils/object';\nimport { ZIndex } from '@primeuix/utils/zindex';\nimport Portal from 'primevue/portal';\nimport ToastEventBus from 'primevue/toasteventbus';\nimport BaseComponent from '@primevue/core/basecomponent';\nimport ToastStyle from 'primevue/toast/style';\nimport CheckIcon from '@primevue/icons/check';\nimport ExclamationTriangleIcon from '@primevue/icons/exclamationtriangle';\nimport InfoCircleIcon from '@primevue/icons/infocircle';\nimport TimesIcon from '@primevue/icons/times';\nimport TimesCircleIcon from '@primevue/icons/timescircle';\nimport Ripple from 'primevue/ripple';\nimport { resolveDirective, openBlock, createElementBlock, mergeProps, createBlock, resolveDynamicComponent, Fragment, createElementVNode, toDisplayString, normalizeProps, withDirectives, createCommentVNode, resolveComponent, withCtx, createVNode, TransitionGroup, renderList } from 'vue';\n\nvar script$2 = {\n name: 'BaseToast',\n \"extends\": BaseComponent,\n props: {\n group: {\n type: String,\n \"default\": null\n },\n position: {\n type: String,\n \"default\": 'top-right'\n },\n autoZIndex: {\n type: Boolean,\n \"default\": true\n },\n baseZIndex: {\n type: Number,\n \"default\": 0\n },\n breakpoints: {\n type: Object,\n \"default\": null\n },\n closeIcon: {\n type: String,\n \"default\": undefined\n },\n infoIcon: {\n type: String,\n \"default\": undefined\n },\n warnIcon: {\n type: String,\n \"default\": undefined\n },\n errorIcon: {\n type: String,\n \"default\": undefined\n },\n successIcon: {\n type: String,\n \"default\": undefined\n },\n closeButtonProps: {\n type: null,\n \"default\": null\n }\n },\n style: ToastStyle,\n provide: function provide() {\n return {\n $pcToast: this,\n $parentInstance: this\n };\n }\n};\n\nvar script$1 = {\n name: 'ToastMessage',\n hostName: 'Toast',\n \"extends\": BaseComponent,\n emits: ['close'],\n closeTimeout: null,\n props: {\n message: {\n type: null,\n \"default\": null\n },\n templates: {\n type: Object,\n \"default\": null\n },\n closeIcon: {\n type: String,\n \"default\": null\n },\n infoIcon: {\n type: String,\n \"default\": null\n },\n warnIcon: {\n type: String,\n \"default\": null\n },\n errorIcon: {\n type: String,\n \"default\": null\n },\n successIcon: {\n type: String,\n \"default\": null\n },\n closeButtonProps: {\n type: null,\n \"default\": null\n }\n },\n mounted: function mounted() {\n var _this = this;\n if (this.message.life) {\n this.closeTimeout = setTimeout(function () {\n _this.close({\n message: _this.message,\n type: 'life-end'\n });\n }, this.message.life);\n }\n },\n beforeUnmount: function beforeUnmount() {\n this.clearCloseTimeout();\n },\n methods: {\n close: function close(params) {\n this.$emit('close', params);\n },\n onCloseClick: function onCloseClick() {\n this.clearCloseTimeout();\n this.close({\n message: this.message,\n type: 'close'\n });\n },\n clearCloseTimeout: function clearCloseTimeout() {\n if (this.closeTimeout) {\n clearTimeout(this.closeTimeout);\n this.closeTimeout = null;\n }\n }\n },\n computed: {\n iconComponent: function iconComponent() {\n return {\n info: !this.infoIcon && InfoCircleIcon,\n success: !this.successIcon && CheckIcon,\n warn: !this.warnIcon && ExclamationTriangleIcon,\n error: !this.errorIcon && TimesCircleIcon\n }[this.message.severity];\n },\n closeAriaLabel: function closeAriaLabel() {\n return this.$primevue.config.locale.aria ? this.$primevue.config.locale.aria.close : undefined;\n }\n },\n components: {\n TimesIcon: TimesIcon,\n InfoCircleIcon: InfoCircleIcon,\n CheckIcon: CheckIcon,\n ExclamationTriangleIcon: ExclamationTriangleIcon,\n TimesCircleIcon: TimesCircleIcon\n },\n directives: {\n ripple: Ripple\n }\n};\n\nfunction _typeof$1(o) { \"@babel/helpers - typeof\"; return _typeof$1 = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof$1(o); }\nfunction ownKeys$1(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread$1(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$1(Object(t), !0).forEach(function (r) { _defineProperty$1(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$1(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty$1(e, r, t) { return (r = _toPropertyKey$1(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }\nfunction _toPropertyKey$1(t) { var i = _toPrimitive$1(t, \"string\"); return \"symbol\" == _typeof$1(i) ? i : i + \"\"; }\nfunction _toPrimitive$1(t, r) { if (\"object\" != _typeof$1(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof$1(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nvar _hoisted_1 = [\"aria-label\"];\nfunction render$1(_ctx, _cache, $props, $setup, $data, $options) {\n var _directive_ripple = resolveDirective(\"ripple\");\n return openBlock(), createElementBlock(\"div\", mergeProps({\n \"class\": [_ctx.cx('message'), $props.message.styleClass],\n role: \"alert\",\n \"aria-live\": \"assertive\",\n \"aria-atomic\": \"true\"\n }, _ctx.ptm('message')), [$props.templates.container ? (openBlock(), createBlock(resolveDynamicComponent($props.templates.container), {\n key: 0,\n message: $props.message,\n closeCallback: $options.onCloseClick\n }, null, 8, [\"message\", \"closeCallback\"])) : (openBlock(), createElementBlock(\"div\", mergeProps({\n key: 1,\n \"class\": [_ctx.cx('messageContent'), $props.message.contentStyleClass]\n }, _ctx.ptm('messageContent')), [!$props.templates.message ? (openBlock(), createElementBlock(Fragment, {\n key: 0\n }, [(openBlock(), createBlock(resolveDynamicComponent($props.templates.messageicon ? $props.templates.messageicon : $props.templates.icon ? $props.templates.icon : $options.iconComponent && $options.iconComponent.name ? $options.iconComponent : 'span'), mergeProps({\n \"class\": _ctx.cx('messageIcon')\n }, _ctx.ptm('messageIcon')), null, 16, [\"class\"])), createElementVNode(\"div\", mergeProps({\n \"class\": _ctx.cx('messageText')\n }, _ctx.ptm('messageText')), [createElementVNode(\"span\", mergeProps({\n \"class\": _ctx.cx('summary')\n }, _ctx.ptm('summary')), toDisplayString($props.message.summary), 17), createElementVNode(\"div\", mergeProps({\n \"class\": _ctx.cx('detail')\n }, _ctx.ptm('detail')), toDisplayString($props.message.detail), 17)], 16)], 64)) : (openBlock(), createBlock(resolveDynamicComponent($props.templates.message), {\n key: 1,\n message: $props.message\n }, null, 8, [\"message\"])), $props.message.closable !== false ? (openBlock(), createElementBlock(\"div\", normalizeProps(mergeProps({\n key: 2\n }, _ctx.ptm('buttonContainer'))), [withDirectives((openBlock(), createElementBlock(\"button\", mergeProps({\n \"class\": _ctx.cx('closeButton'),\n type: \"button\",\n \"aria-label\": $options.closeAriaLabel,\n onClick: _cache[0] || (_cache[0] = function () {\n return $options.onCloseClick && $options.onCloseClick.apply($options, arguments);\n }),\n autofocus: \"\"\n }, _objectSpread$1(_objectSpread$1({}, $props.closeButtonProps), _ctx.ptm('closeButton'))), [(openBlock(), createBlock(resolveDynamicComponent($props.templates.closeicon || 'TimesIcon'), mergeProps({\n \"class\": [_ctx.cx('closeIcon'), $props.closeIcon]\n }, _ctx.ptm('closeIcon')), null, 16, [\"class\"]))], 16, _hoisted_1)), [[_directive_ripple]])], 16)) : createCommentVNode(\"\", true)], 16))], 16);\n}\n\nscript$1.render = render$1;\n\nfunction _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _unsupportedIterableToArray(r, a) { if (r) { if (\"string\" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return \"Object\" === t && r.constructor && (t = r.constructor.name), \"Map\" === t || \"Set\" === t ? Array.from(r) : \"Arguments\" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }\nfunction _iterableToArray(r) { if (\"undefined\" != typeof Symbol && null != r[Symbol.iterator] || null != r[\"@@iterator\"]) return Array.from(r); }\nfunction _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }\nfunction _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }\nvar messageIdx = 0;\nvar script = {\n name: 'Toast',\n \"extends\": script$2,\n inheritAttrs: false,\n emits: ['close', 'life-end'],\n data: function data() {\n return {\n messages: []\n };\n },\n styleElement: null,\n mounted: function mounted() {\n ToastEventBus.on('add', this.onAdd);\n ToastEventBus.on('remove', this.onRemove);\n ToastEventBus.on('remove-group', this.onRemoveGroup);\n ToastEventBus.on('remove-all-groups', this.onRemoveAllGroups);\n if (this.breakpoints) {\n this.createStyle();\n }\n },\n beforeUnmount: function beforeUnmount() {\n this.destroyStyle();\n if (this.$refs.container && this.autoZIndex) {\n ZIndex.clear(this.$refs.container);\n }\n ToastEventBus.off('add', this.onAdd);\n ToastEventBus.off('remove', this.onRemove);\n ToastEventBus.off('remove-group', this.onRemoveGroup);\n ToastEventBus.off('remove-all-groups', this.onRemoveAllGroups);\n },\n methods: {\n add: function add(message) {\n if (message.id == null) {\n message.id = messageIdx++;\n }\n this.messages = [].concat(_toConsumableArray(this.messages), [message]);\n },\n remove: function remove(params) {\n var index = this.messages.findIndex(function (m) {\n return m.id === params.message.id;\n });\n if (index !== -1) {\n this.messages.splice(index, 1);\n this.$emit(params.type, {\n message: params.message\n });\n }\n },\n onAdd: function onAdd(message) {\n if (this.group == message.group) {\n this.add(message);\n }\n },\n onRemove: function onRemove(message) {\n this.remove({\n message: message,\n type: 'close'\n });\n },\n onRemoveGroup: function onRemoveGroup(group) {\n if (this.group === group) {\n this.messages = [];\n }\n },\n onRemoveAllGroups: function onRemoveAllGroups() {\n this.messages = [];\n },\n onEnter: function onEnter() {\n this.$refs.container.setAttribute(this.attributeSelector, '');\n if (this.autoZIndex) {\n ZIndex.set('modal', this.$refs.container, this.baseZIndex || this.$primevue.config.zIndex.modal);\n }\n },\n onLeave: function onLeave() {\n var _this = this;\n if (this.$refs.container && this.autoZIndex && isEmpty(this.messages)) {\n setTimeout(function () {\n ZIndex.clear(_this.$refs.container);\n }, 200);\n }\n },\n createStyle: function createStyle() {\n if (!this.styleElement && !this.isUnstyled) {\n var _this$$primevue;\n this.styleElement = document.createElement('style');\n this.styleElement.type = 'text/css';\n setAttribute(this.styleElement, 'nonce', (_this$$primevue = this.$primevue) === null || _this$$primevue === void 0 || (_this$$primevue = _this$$primevue.config) === null || _this$$primevue === void 0 || (_this$$primevue = _this$$primevue.csp) === null || _this$$primevue === void 0 ? void 0 : _this$$primevue.nonce);\n document.head.appendChild(this.styleElement);\n var innerHTML = '';\n for (var breakpoint in this.breakpoints) {\n var breakpointStyle = '';\n for (var styleProp in this.breakpoints[breakpoint]) {\n breakpointStyle += styleProp + ':' + this.breakpoints[breakpoint][styleProp] + '!important;';\n }\n innerHTML += \"\\n @media screen and (max-width: \".concat(breakpoint, \") {\\n .p-toast[\").concat(this.attributeSelector, \"] {\\n \").concat(breakpointStyle, \"\\n }\\n }\\n \");\n }\n this.styleElement.innerHTML = innerHTML;\n }\n },\n destroyStyle: function destroyStyle() {\n if (this.styleElement) {\n document.head.removeChild(this.styleElement);\n this.styleElement = null;\n }\n }\n },\n computed: {\n attributeSelector: function attributeSelector() {\n return UniqueComponentId();\n }\n },\n components: {\n ToastMessage: script$1,\n Portal: Portal\n }\n};\n\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n var _component_ToastMessage = resolveComponent(\"ToastMessage\");\n var _component_Portal = resolveComponent(\"Portal\");\n return openBlock(), createBlock(_component_Portal, null, {\n \"default\": withCtx(function () {\n return [createElementVNode(\"div\", mergeProps({\n ref: \"container\",\n \"class\": _ctx.cx('root'),\n style: _ctx.sx('root', true, {\n position: _ctx.position\n })\n }, _ctx.ptmi('root')), [createVNode(TransitionGroup, mergeProps({\n name: \"p-toast-message\",\n tag: \"div\",\n onEnter: $options.onEnter,\n onLeave: $options.onLeave\n }, _objectSpread({}, _ctx.ptm('transition'))), {\n \"default\": withCtx(function () {\n return [(openBlock(true), createElementBlock(Fragment, null, renderList($data.messages, function (msg) {\n return openBlock(), createBlock(_component_ToastMessage, {\n key: msg.id,\n message: msg,\n templates: _ctx.$slots,\n closeIcon: _ctx.closeIcon,\n infoIcon: _ctx.infoIcon,\n warnIcon: _ctx.warnIcon,\n errorIcon: _ctx.errorIcon,\n successIcon: _ctx.successIcon,\n closeButtonProps: _ctx.closeButtonProps,\n onClose: _cache[0] || (_cache[0] = function ($event) {\n return $options.remove($event);\n }),\n pt: _ctx.pt\n }, null, 8, [\"message\", \"templates\", \"closeIcon\", \"infoIcon\", \"warnIcon\", \"errorIcon\", \"successIcon\", \"closeButtonProps\", \"pt\"]);\n }), 128))];\n }),\n _: 1\n }, 16, [\"onEnter\", \"onLeave\"])], 16)];\n }),\n _: 1\n });\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","import { api } from '@/scripts/api'\r\nimport { app } from '@/scripts/app'\r\nimport {\r\n validateTaskItem,\r\n TaskItem,\r\n TaskType,\r\n TaskPrompt,\r\n TaskStatus,\r\n TaskOutput,\r\n StatusWsMessageStatus\r\n} from '@/types/apiTypes'\r\nimport { plainToClass } from 'class-transformer'\r\nimport _ from 'lodash'\r\nimport { defineStore } from 'pinia'\r\nimport { toRaw } from 'vue'\r\n\r\n// Task type used in the API.\r\nexport type APITaskType = 'queue' | 'history'\r\n\r\nexport enum TaskItemDisplayStatus {\r\n Running = 'Running',\r\n Pending = 'Pending',\r\n Completed = 'Completed',\r\n Failed = 'Failed',\r\n Cancelled = 'Cancelled'\r\n}\r\n\r\nexport class TaskItemImpl {\r\n taskType: TaskType\r\n prompt: TaskPrompt\r\n status?: TaskStatus\r\n outputs?: TaskOutput\r\n\r\n get apiTaskType(): APITaskType {\r\n switch (this.taskType) {\r\n case 'Running':\r\n case 'Pending':\r\n return 'queue'\r\n case 'History':\r\n return 'history'\r\n }\r\n }\r\n\r\n get queueIndex() {\r\n return this.prompt[0]\r\n }\r\n\r\n get promptId() {\r\n return this.prompt[1]\r\n }\r\n\r\n get promptInputs() {\r\n return this.prompt[2]\r\n }\r\n\r\n get extraData() {\r\n return this.prompt[3]\r\n }\r\n\r\n get outputsToExecute() {\r\n return this.prompt[4]\r\n }\r\n\r\n get extraPngInfo() {\r\n return this.extraData.extra_pnginfo\r\n }\r\n\r\n get clientId() {\r\n return this.extraData.client_id\r\n }\r\n\r\n get workflow() {\r\n return this.extraPngInfo.workflow\r\n }\r\n\r\n get messages() {\r\n return this.status?.messages || []\r\n }\r\n\r\n get interrupted() {\r\n return _.some(\r\n this.messages,\r\n (message) => message[0] === 'execution_interrupted'\r\n )\r\n }\r\n\r\n get isHistory() {\r\n return this.taskType === 'History'\r\n }\r\n\r\n get isRunning() {\r\n return this.taskType === 'Running'\r\n }\r\n\r\n get displayStatus(): TaskItemDisplayStatus {\r\n switch (this.taskType) {\r\n case 'Running':\r\n return TaskItemDisplayStatus.Running\r\n case 'Pending':\r\n return TaskItemDisplayStatus.Pending\r\n case 'History':\r\n switch (this.status!.status_str) {\r\n case 'success':\r\n return TaskItemDisplayStatus.Completed\r\n case 'error':\r\n return this.interrupted\r\n ? TaskItemDisplayStatus.Cancelled\r\n : TaskItemDisplayStatus.Failed\r\n }\r\n }\r\n }\r\n\r\n get executionStartTimestamp() {\r\n const message = this.messages.find(\r\n (message) => message[0] === 'execution_start'\r\n )\r\n return message ? message[1].timestamp : undefined\r\n }\r\n\r\n get executionEndTimestamp() {\r\n const messages = this.messages.filter((message) =>\r\n [\r\n 'execution_success',\r\n 'execution_interrupted',\r\n 'execution_error'\r\n ].includes(message[0])\r\n )\r\n if (!messages.length) {\r\n return undefined\r\n }\r\n return _.max(messages.map((message) => message[1].timestamp))\r\n }\r\n\r\n get executionTime() {\r\n if (!this.executionStartTimestamp || !this.executionEndTimestamp) {\r\n return undefined\r\n }\r\n return this.executionEndTimestamp - this.executionStartTimestamp\r\n }\r\n\r\n get executionTimeInSeconds() {\r\n return this.executionTime !== undefined\r\n ? this.executionTime / 1000\r\n : undefined\r\n }\r\n\r\n public async loadWorkflow() {\r\n await app.loadGraphData(toRaw(this.workflow))\r\n if (this.outputs) {\r\n app.nodeOutputs = toRaw(this.outputs)\r\n }\r\n }\r\n}\r\n\r\ninterface State {\r\n runningTasks: TaskItemImpl[]\r\n pendingTasks: TaskItemImpl[]\r\n historyTasks: TaskItemImpl[]\r\n maxHistoryItems: number\r\n}\r\n\r\nexport const useQueueStore = defineStore('queue', {\r\n state: (): State => ({\r\n runningTasks: [],\r\n pendingTasks: [],\r\n historyTasks: [],\r\n maxHistoryItems: 64\r\n }),\r\n getters: {\r\n tasks(state) {\r\n return [\r\n ...state.pendingTasks,\r\n ...state.runningTasks,\r\n ...state.historyTasks\r\n ]\r\n },\r\n lastHistoryQueueIndex(state) {\r\n return state.historyTasks.length ? state.historyTasks[0].queueIndex : -1\r\n }\r\n },\r\n actions: {\r\n // Fetch the queue data from the API\r\n async update() {\r\n const [queue, history] = await Promise.all([\r\n api.getQueue(),\r\n api.getHistory(this.maxHistoryItems)\r\n ])\r\n\r\n const toClassAll = (tasks: TaskItem[]): TaskItemImpl[] =>\r\n tasks\r\n .map((task) => validateTaskItem(task))\r\n .filter((result) => result.success)\r\n .map((result) => plainToClass(TaskItemImpl, result.data))\r\n // Desc order to show the latest tasks first\r\n .sort((a, b) => b.queueIndex - a.queueIndex)\r\n\r\n this.runningTasks = toClassAll(queue.Running)\r\n this.pendingTasks = toClassAll(queue.Pending)\r\n\r\n // Process history items\r\n const allIndex = new Set(\r\n history.History.map((item: TaskItem) => item.prompt[0])\r\n )\r\n const newHistoryItems = toClassAll(\r\n history.History.filter(\r\n (item) => item.prompt[0] > this.lastHistoryQueueIndex\r\n )\r\n )\r\n const existingHistoryItems = this.historyTasks.filter(\r\n (item: TaskItemImpl) => allIndex.has(item.queueIndex)\r\n )\r\n this.historyTasks = [...newHistoryItems, ...existingHistoryItems]\r\n .slice(0, this.maxHistoryItems)\r\n .sort((a, b) => b.queueIndex - a.queueIndex)\r\n },\r\n async clear() {\r\n await Promise.all(\r\n ['queue', 'history'].map((type) => api.clearItems(type))\r\n )\r\n await this.update()\r\n },\r\n async delete(task: TaskItemImpl) {\r\n await api.deleteItem(task.apiTaskType, task.promptId)\r\n await this.update()\r\n }\r\n }\r\n})\r\n\r\nexport const useQueuePendingTaskCountStore = defineStore(\r\n 'queuePendingTaskCount',\r\n {\r\n state: () => ({\r\n count: 0\r\n }),\r\n actions: {\r\n update(e: CustomEvent) {\r\n this.count = e.detail?.exec_info?.queue_remaining || 0\r\n }\r\n }\r\n }\r\n)\r\n","\r\n 0\"\r\n :value=\"tasks\"\r\n dataKey=\"promptId\"\r\n class=\"queue-table\"\r\n >\r\n \r\n \r\n \r\n {{ data.displayStatus.toUpperCase() }}\r\n \r\n \r\n \r\n \r\n \r\n \r\n {{ formatTime(data.executionTimeInSeconds) }}\r\n \r\n \r\n \r\n \r\n ...\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","/*!\n * shared v9.13.1\n * (c) 2024 kazuya kawaguchi\n * Released under the MIT License.\n */\n/**\n * Original Utilities\n * written by kazuya kawaguchi\n */\nconst inBrowser = typeof window !== 'undefined';\nlet mark;\nlet measure;\nif ((process.env.NODE_ENV !== 'production')) {\n const perf = inBrowser && window.performance;\n if (perf &&\n perf.mark &&\n perf.measure &&\n perf.clearMarks &&\n // @ts-ignore browser compat\n perf.clearMeasures) {\n mark = (tag) => {\n perf.mark(tag);\n };\n measure = (name, startTag, endTag) => {\n perf.measure(name, startTag, endTag);\n perf.clearMarks(startTag);\n perf.clearMarks(endTag);\n };\n }\n}\nconst RE_ARGS = /\\{([0-9a-zA-Z]+)\\}/g;\n/* eslint-disable */\nfunction format(message, ...args) {\n if (args.length === 1 && isObject(args[0])) {\n args = args[0];\n }\n if (!args || !args.hasOwnProperty) {\n args = {};\n }\n return message.replace(RE_ARGS, (match, identifier) => {\n return args.hasOwnProperty(identifier) ? args[identifier] : '';\n });\n}\nconst makeSymbol = (name, shareable = false) => !shareable ? Symbol(name) : Symbol.for(name);\nconst generateFormatCacheKey = (locale, key, source) => friendlyJSONstringify({ l: locale, k: key, s: source });\nconst friendlyJSONstringify = (json) => JSON.stringify(json)\n .replace(/\\u2028/g, '\\\\u2028')\n .replace(/\\u2029/g, '\\\\u2029')\n .replace(/\\u0027/g, '\\\\u0027');\nconst isNumber = (val) => typeof val === 'number' && isFinite(val);\nconst isDate = (val) => toTypeString(val) === '[object Date]';\nconst isRegExp = (val) => toTypeString(val) === '[object RegExp]';\nconst isEmptyObject = (val) => isPlainObject(val) && Object.keys(val).length === 0;\nconst assign = Object.assign;\nlet _globalThis;\nconst getGlobalThis = () => {\n // prettier-ignore\n return (_globalThis ||\n (_globalThis =\n typeof globalThis !== 'undefined'\n ? globalThis\n : typeof self !== 'undefined'\n ? self\n : typeof window !== 'undefined'\n ? window\n : typeof global !== 'undefined'\n ? global\n : {}));\n};\nfunction escapeHtml(rawText) {\n return rawText\n .replace(//g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''');\n}\nconst hasOwnProperty = Object.prototype.hasOwnProperty;\nfunction hasOwn(obj, key) {\n return hasOwnProperty.call(obj, key);\n}\n/* eslint-enable */\n/**\n * Useful Utilities By Evan you\n * Modified by kazuya kawaguchi\n * MIT License\n * https://github.com/vuejs/vue-next/blob/master/packages/shared/src/index.ts\n * https://github.com/vuejs/vue-next/blob/master/packages/shared/src/codeframe.ts\n */\nconst isArray = Array.isArray;\nconst isFunction = (val) => typeof val === 'function';\nconst isString = (val) => typeof val === 'string';\nconst isBoolean = (val) => typeof val === 'boolean';\nconst isSymbol = (val) => typeof val === 'symbol';\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst isObject = (val) => val !== null && typeof val === 'object';\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst isPromise = (val) => {\n return isObject(val) && isFunction(val.then) && isFunction(val.catch);\n};\nconst objectToString = Object.prototype.toString;\nconst toTypeString = (value) => objectToString.call(value);\nconst isPlainObject = (val) => {\n if (!isObject(val))\n return false;\n const proto = Object.getPrototypeOf(val);\n return proto === null || proto.constructor === Object;\n};\n// for converting list and named values to displayed strings.\nconst toDisplayString = (val) => {\n return val == null\n ? ''\n : isArray(val) || (isPlainObject(val) && val.toString === objectToString)\n ? JSON.stringify(val, null, 2)\n : String(val);\n};\nfunction join(items, separator = '') {\n return items.reduce((str, item, index) => (index === 0 ? str + item : str + separator + item), '');\n}\nconst RANGE = 2;\nfunction generateCodeFrame(source, start = 0, end = source.length) {\n const lines = source.split(/\\r?\\n/);\n let count = 0;\n const res = [];\n for (let i = 0; i < lines.length; i++) {\n count += lines[i].length + 1;\n if (count >= start) {\n for (let j = i - RANGE; j <= i + RANGE || end > count; j++) {\n if (j < 0 || j >= lines.length)\n continue;\n const line = j + 1;\n res.push(`${line}${' '.repeat(3 - String(line).length)}| ${lines[j]}`);\n const lineLength = lines[j].length;\n if (j === i) {\n // push underline\n const pad = start - (count - lineLength) + 1;\n const length = Math.max(1, end > count ? lineLength - pad : end - start);\n res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));\n }\n else if (j > i) {\n if (end > count) {\n const length = Math.max(Math.min(end - count, lineLength), 1);\n res.push(` | ` + '^'.repeat(length));\n }\n count += lineLength + 1;\n }\n }\n break;\n }\n }\n return res.join('\\n');\n}\nfunction incrementer(code) {\n let current = code;\n return () => ++current;\n}\n\nfunction warn(msg, err) {\n if (typeof console !== 'undefined') {\n console.warn(`[intlify] ` + msg);\n /* istanbul ignore if */\n if (err) {\n console.warn(err.stack);\n }\n }\n}\nconst hasWarned = {};\nfunction warnOnce(msg) {\n if (!hasWarned[msg]) {\n hasWarned[msg] = true;\n warn(msg);\n }\n}\n\n/**\n * Event emitter, forked from the below:\n * - original repository url: https://github.com/developit/mitt\n * - code url: https://github.com/developit/mitt/blob/master/src/index.ts\n * - author: Jason Miller (https://github.com/developit)\n * - license: MIT\n */\n/**\n * Create a event emitter\n *\n * @returns An event emitter\n */\nfunction createEmitter() {\n const events = new Map();\n const emitter = {\n events,\n on(event, handler) {\n const handlers = events.get(event);\n const added = handlers && handlers.push(handler);\n if (!added) {\n events.set(event, [handler]);\n }\n },\n off(event, handler) {\n const handlers = events.get(event);\n if (handlers) {\n handlers.splice(handlers.indexOf(handler) >>> 0, 1);\n }\n },\n emit(event, payload) {\n (events.get(event) || [])\n .slice()\n .map(handler => handler(payload));\n (events.get('*') || [])\n .slice()\n .map(handler => handler(event, payload));\n }\n };\n return emitter;\n}\n\nconst isNotObjectOrIsArray = (val) => !isObject(val) || isArray(val);\n// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\nfunction deepCopy(src, des) {\n // src and des should both be objects, and none of them can be a array\n if (isNotObjectOrIsArray(src) || isNotObjectOrIsArray(des)) {\n throw new Error('Invalid value');\n }\n const stack = [{ src, des }];\n while (stack.length) {\n const { src, des } = stack.pop();\n Object.keys(src).forEach(key => {\n if (isNotObjectOrIsArray(src[key]) || isNotObjectOrIsArray(des[key])) {\n // replace with src[key] when:\n // src[key] or des[key] is not an object, or\n // src[key] or des[key] is an array\n des[key] = src[key];\n }\n else {\n // src[key] and des[key] are both objects, merge them\n stack.push({ src: src[key], des: des[key] });\n }\n });\n }\n}\n\nexport { assign, createEmitter, deepCopy, escapeHtml, format, friendlyJSONstringify, generateCodeFrame, generateFormatCacheKey, getGlobalThis, hasOwn, inBrowser, incrementer, isArray, isBoolean, isDate, isEmptyObject, isFunction, isNumber, isObject, isPlainObject, isPromise, isRegExp, isString, isSymbol, join, makeSymbol, mark, measure, objectToString, toDisplayString, toTypeString, warn, warnOnce };\n","/*!\n * message-compiler v9.13.1\n * (c) 2024 kazuya kawaguchi\n * Released under the MIT License.\n */\nconst LOCATION_STUB = {\n start: { line: 1, column: 1, offset: 0 },\n end: { line: 1, column: 1, offset: 0 }\n};\nfunction createPosition(line, column, offset) {\n return { line, column, offset };\n}\nfunction createLocation(start, end, source) {\n const loc = { start, end };\n if (source != null) {\n loc.source = source;\n }\n return loc;\n}\n\n/**\n * Original Utilities\n * written by kazuya kawaguchi\n */\nconst RE_ARGS = /\\{([0-9a-zA-Z]+)\\}/g;\n/* eslint-disable */\nfunction format(message, ...args) {\n if (args.length === 1 && isObject(args[0])) {\n args = args[0];\n }\n if (!args || !args.hasOwnProperty) {\n args = {};\n }\n return message.replace(RE_ARGS, (match, identifier) => {\n return args.hasOwnProperty(identifier) ? args[identifier] : '';\n });\n}\nconst assign = Object.assign;\nconst isString = (val) => typeof val === 'string';\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst isObject = (val) => val !== null && typeof val === 'object';\nfunction join(items, separator = '') {\n return items.reduce((str, item, index) => (index === 0 ? str + item : str + separator + item), '');\n}\n\nconst CompileWarnCodes = {\n USE_MODULO_SYNTAX: 1,\n __EXTEND_POINT__: 2\n};\n/** @internal */\nconst warnMessages = {\n [CompileWarnCodes.USE_MODULO_SYNTAX]: `Use modulo before '{{0}}'.`\n};\nfunction createCompileWarn(code, loc, ...args) {\n const msg = format(warnMessages[code] || '', ...(args || [])) ;\n const message = { message: String(msg), code };\n if (loc) {\n message.location = loc;\n }\n return message;\n}\n\nconst CompileErrorCodes = {\n // tokenizer error codes\n EXPECTED_TOKEN: 1,\n INVALID_TOKEN_IN_PLACEHOLDER: 2,\n UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER: 3,\n UNKNOWN_ESCAPE_SEQUENCE: 4,\n INVALID_UNICODE_ESCAPE_SEQUENCE: 5,\n UNBALANCED_CLOSING_BRACE: 6,\n UNTERMINATED_CLOSING_BRACE: 7,\n EMPTY_PLACEHOLDER: 8,\n NOT_ALLOW_NEST_PLACEHOLDER: 9,\n INVALID_LINKED_FORMAT: 10,\n // parser error codes\n MUST_HAVE_MESSAGES_IN_PLURAL: 11,\n UNEXPECTED_EMPTY_LINKED_MODIFIER: 12,\n UNEXPECTED_EMPTY_LINKED_KEY: 13,\n UNEXPECTED_LEXICAL_ANALYSIS: 14,\n // generator error codes\n UNHANDLED_CODEGEN_NODE_TYPE: 15,\n // minifier error codes\n UNHANDLED_MINIFIER_NODE_TYPE: 16,\n // Special value for higher-order compilers to pick up the last code\n // to avoid collision of error codes. This should always be kept as the last\n // item.\n __EXTEND_POINT__: 17\n};\n/** @internal */\nconst errorMessages = {\n // tokenizer error messages\n [CompileErrorCodes.EXPECTED_TOKEN]: `Expected token: '{0}'`,\n [CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER]: `Invalid token in placeholder: '{0}'`,\n [CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER]: `Unterminated single quote in placeholder`,\n [CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE]: `Unknown escape sequence: \\\\{0}`,\n [CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE]: `Invalid unicode escape sequence: {0}`,\n [CompileErrorCodes.UNBALANCED_CLOSING_BRACE]: `Unbalanced closing brace`,\n [CompileErrorCodes.UNTERMINATED_CLOSING_BRACE]: `Unterminated closing brace`,\n [CompileErrorCodes.EMPTY_PLACEHOLDER]: `Empty placeholder`,\n [CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER]: `Not allowed nest placeholder`,\n [CompileErrorCodes.INVALID_LINKED_FORMAT]: `Invalid linked format`,\n // parser error messages\n [CompileErrorCodes.MUST_HAVE_MESSAGES_IN_PLURAL]: `Plural must have messages`,\n [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_MODIFIER]: `Unexpected empty linked modifier`,\n [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_KEY]: `Unexpected empty linked key`,\n [CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS]: `Unexpected lexical analysis in token: '{0}'`,\n // generator error messages\n [CompileErrorCodes.UNHANDLED_CODEGEN_NODE_TYPE]: `unhandled codegen node type: '{0}'`,\n // minimizer error messages\n [CompileErrorCodes.UNHANDLED_MINIFIER_NODE_TYPE]: `unhandled mimifier node type: '{0}'`\n};\nfunction createCompileError(code, loc, options = {}) {\n const { domain, messages, args } = options;\n const msg = format((messages || errorMessages)[code] || '', ...(args || []))\n ;\n const error = new SyntaxError(String(msg));\n error.code = code;\n if (loc) {\n error.location = loc;\n }\n error.domain = domain;\n return error;\n}\n/** @internal */\nfunction defaultOnError(error) {\n throw error;\n}\n\n// eslint-disable-next-line no-useless-escape\nconst RE_HTML_TAG = /<\\/?[\\w\\s=\"/.':;#-\\/]+>/;\nconst detectHtmlTag = (source) => RE_HTML_TAG.test(source);\n\nconst CHAR_SP = ' ';\nconst CHAR_CR = '\\r';\nconst CHAR_LF = '\\n';\nconst CHAR_LS = String.fromCharCode(0x2028);\nconst CHAR_PS = String.fromCharCode(0x2029);\nfunction createScanner(str) {\n const _buf = str;\n let _index = 0;\n let _line = 1;\n let _column = 1;\n let _peekOffset = 0;\n const isCRLF = (index) => _buf[index] === CHAR_CR && _buf[index + 1] === CHAR_LF;\n const isLF = (index) => _buf[index] === CHAR_LF;\n const isPS = (index) => _buf[index] === CHAR_PS;\n const isLS = (index) => _buf[index] === CHAR_LS;\n const isLineEnd = (index) => isCRLF(index) || isLF(index) || isPS(index) || isLS(index);\n const index = () => _index;\n const line = () => _line;\n const column = () => _column;\n const peekOffset = () => _peekOffset;\n const charAt = (offset) => isCRLF(offset) || isPS(offset) || isLS(offset) ? CHAR_LF : _buf[offset];\n const currentChar = () => charAt(_index);\n const currentPeek = () => charAt(_index + _peekOffset);\n function next() {\n _peekOffset = 0;\n if (isLineEnd(_index)) {\n _line++;\n _column = 0;\n }\n if (isCRLF(_index)) {\n _index++;\n }\n _index++;\n _column++;\n return _buf[_index];\n }\n function peek() {\n if (isCRLF(_index + _peekOffset)) {\n _peekOffset++;\n }\n _peekOffset++;\n return _buf[_index + _peekOffset];\n }\n function reset() {\n _index = 0;\n _line = 1;\n _column = 1;\n _peekOffset = 0;\n }\n function resetPeek(offset = 0) {\n _peekOffset = offset;\n }\n function skipToPeek() {\n const target = _index + _peekOffset;\n // eslint-disable-next-line no-unmodified-loop-condition\n while (target !== _index) {\n next();\n }\n _peekOffset = 0;\n }\n return {\n index,\n line,\n column,\n peekOffset,\n charAt,\n currentChar,\n currentPeek,\n next,\n peek,\n reset,\n resetPeek,\n skipToPeek\n };\n}\n\nconst EOF = undefined;\nconst DOT = '.';\nconst LITERAL_DELIMITER = \"'\";\nconst ERROR_DOMAIN$3 = 'tokenizer';\nfunction createTokenizer(source, options = {}) {\n const location = options.location !== false;\n const _scnr = createScanner(source);\n const currentOffset = () => _scnr.index();\n const currentPosition = () => createPosition(_scnr.line(), _scnr.column(), _scnr.index());\n const _initLoc = currentPosition();\n const _initOffset = currentOffset();\n const _context = {\n currentType: 14 /* TokenTypes.EOF */,\n offset: _initOffset,\n startLoc: _initLoc,\n endLoc: _initLoc,\n lastType: 14 /* TokenTypes.EOF */,\n lastOffset: _initOffset,\n lastStartLoc: _initLoc,\n lastEndLoc: _initLoc,\n braceNest: 0,\n inLinked: false,\n text: ''\n };\n const context = () => _context;\n const { onError } = options;\n function emitError(code, pos, offset, ...args) {\n const ctx = context();\n pos.column += offset;\n pos.offset += offset;\n if (onError) {\n const loc = location ? createLocation(ctx.startLoc, pos) : null;\n const err = createCompileError(code, loc, {\n domain: ERROR_DOMAIN$3,\n args\n });\n onError(err);\n }\n }\n function getToken(context, type, value) {\n context.endLoc = currentPosition();\n context.currentType = type;\n const token = { type };\n if (location) {\n token.loc = createLocation(context.startLoc, context.endLoc);\n }\n if (value != null) {\n token.value = value;\n }\n return token;\n }\n const getEndToken = (context) => getToken(context, 14 /* TokenTypes.EOF */);\n function eat(scnr, ch) {\n if (scnr.currentChar() === ch) {\n scnr.next();\n return ch;\n }\n else {\n emitError(CompileErrorCodes.EXPECTED_TOKEN, currentPosition(), 0, ch);\n return '';\n }\n }\n function peekSpaces(scnr) {\n let buf = '';\n while (scnr.currentPeek() === CHAR_SP || scnr.currentPeek() === CHAR_LF) {\n buf += scnr.currentPeek();\n scnr.peek();\n }\n return buf;\n }\n function skipSpaces(scnr) {\n const buf = peekSpaces(scnr);\n scnr.skipToPeek();\n return buf;\n }\n function isIdentifierStart(ch) {\n if (ch === EOF) {\n return false;\n }\n const cc = ch.charCodeAt(0);\n return ((cc >= 97 && cc <= 122) || // a-z\n (cc >= 65 && cc <= 90) || // A-Z\n cc === 95 // _\n );\n }\n function isNumberStart(ch) {\n if (ch === EOF) {\n return false;\n }\n const cc = ch.charCodeAt(0);\n return cc >= 48 && cc <= 57; // 0-9\n }\n function isNamedIdentifierStart(scnr, context) {\n const { currentType } = context;\n if (currentType !== 2 /* TokenTypes.BraceLeft */) {\n return false;\n }\n peekSpaces(scnr);\n const ret = isIdentifierStart(scnr.currentPeek());\n scnr.resetPeek();\n return ret;\n }\n function isListIdentifierStart(scnr, context) {\n const { currentType } = context;\n if (currentType !== 2 /* TokenTypes.BraceLeft */) {\n return false;\n }\n peekSpaces(scnr);\n const ch = scnr.currentPeek() === '-' ? scnr.peek() : scnr.currentPeek();\n const ret = isNumberStart(ch);\n scnr.resetPeek();\n return ret;\n }\n function isLiteralStart(scnr, context) {\n const { currentType } = context;\n if (currentType !== 2 /* TokenTypes.BraceLeft */) {\n return false;\n }\n peekSpaces(scnr);\n const ret = scnr.currentPeek() === LITERAL_DELIMITER;\n scnr.resetPeek();\n return ret;\n }\n function isLinkedDotStart(scnr, context) {\n const { currentType } = context;\n if (currentType !== 8 /* TokenTypes.LinkedAlias */) {\n return false;\n }\n peekSpaces(scnr);\n const ret = scnr.currentPeek() === \".\" /* TokenChars.LinkedDot */;\n scnr.resetPeek();\n return ret;\n }\n function isLinkedModifierStart(scnr, context) {\n const { currentType } = context;\n if (currentType !== 9 /* TokenTypes.LinkedDot */) {\n return false;\n }\n peekSpaces(scnr);\n const ret = isIdentifierStart(scnr.currentPeek());\n scnr.resetPeek();\n return ret;\n }\n function isLinkedDelimiterStart(scnr, context) {\n const { currentType } = context;\n if (!(currentType === 8 /* TokenTypes.LinkedAlias */ ||\n currentType === 12 /* TokenTypes.LinkedModifier */)) {\n return false;\n }\n peekSpaces(scnr);\n const ret = scnr.currentPeek() === \":\" /* TokenChars.LinkedDelimiter */;\n scnr.resetPeek();\n return ret;\n }\n function isLinkedReferStart(scnr, context) {\n const { currentType } = context;\n if (currentType !== 10 /* TokenTypes.LinkedDelimiter */) {\n return false;\n }\n const fn = () => {\n const ch = scnr.currentPeek();\n if (ch === \"{\" /* TokenChars.BraceLeft */) {\n return isIdentifierStart(scnr.peek());\n }\n else if (ch === \"@\" /* TokenChars.LinkedAlias */ ||\n ch === \"%\" /* TokenChars.Modulo */ ||\n ch === \"|\" /* TokenChars.Pipe */ ||\n ch === \":\" /* TokenChars.LinkedDelimiter */ ||\n ch === \".\" /* TokenChars.LinkedDot */ ||\n ch === CHAR_SP ||\n !ch) {\n return false;\n }\n else if (ch === CHAR_LF) {\n scnr.peek();\n return fn();\n }\n else {\n // other characters\n return isTextStart(scnr, false);\n }\n };\n const ret = fn();\n scnr.resetPeek();\n return ret;\n }\n function isPluralStart(scnr) {\n peekSpaces(scnr);\n const ret = scnr.currentPeek() === \"|\" /* TokenChars.Pipe */;\n scnr.resetPeek();\n return ret;\n }\n function detectModuloStart(scnr) {\n const spaces = peekSpaces(scnr);\n const ret = scnr.currentPeek() === \"%\" /* TokenChars.Modulo */ &&\n scnr.peek() === \"{\" /* TokenChars.BraceLeft */;\n scnr.resetPeek();\n return {\n isModulo: ret,\n hasSpace: spaces.length > 0\n };\n }\n function isTextStart(scnr, reset = true) {\n const fn = (hasSpace = false, prev = '', detectModulo = false) => {\n const ch = scnr.currentPeek();\n if (ch === \"{\" /* TokenChars.BraceLeft */) {\n return prev === \"%\" /* TokenChars.Modulo */ ? false : hasSpace;\n }\n else if (ch === \"@\" /* TokenChars.LinkedAlias */ || !ch) {\n return prev === \"%\" /* TokenChars.Modulo */ ? true : hasSpace;\n }\n else if (ch === \"%\" /* TokenChars.Modulo */) {\n scnr.peek();\n return fn(hasSpace, \"%\" /* TokenChars.Modulo */, true);\n }\n else if (ch === \"|\" /* TokenChars.Pipe */) {\n return prev === \"%\" /* TokenChars.Modulo */ || detectModulo\n ? true\n : !(prev === CHAR_SP || prev === CHAR_LF);\n }\n else if (ch === CHAR_SP) {\n scnr.peek();\n return fn(true, CHAR_SP, detectModulo);\n }\n else if (ch === CHAR_LF) {\n scnr.peek();\n return fn(true, CHAR_LF, detectModulo);\n }\n else {\n return true;\n }\n };\n const ret = fn();\n reset && scnr.resetPeek();\n return ret;\n }\n function takeChar(scnr, fn) {\n const ch = scnr.currentChar();\n if (ch === EOF) {\n return EOF;\n }\n if (fn(ch)) {\n scnr.next();\n return ch;\n }\n return null;\n }\n function isIdentifier(ch) {\n const cc = ch.charCodeAt(0);\n return ((cc >= 97 && cc <= 122) || // a-z\n (cc >= 65 && cc <= 90) || // A-Z\n (cc >= 48 && cc <= 57) || // 0-9\n cc === 95 || // _\n cc === 36 // $\n );\n }\n function takeIdentifierChar(scnr) {\n return takeChar(scnr, isIdentifier);\n }\n function isNamedIdentifier(ch) {\n const cc = ch.charCodeAt(0);\n return ((cc >= 97 && cc <= 122) || // a-z\n (cc >= 65 && cc <= 90) || // A-Z\n (cc >= 48 && cc <= 57) || // 0-9\n cc === 95 || // _\n cc === 36 || // $\n cc === 45 // -\n );\n }\n function takeNamedIdentifierChar(scnr) {\n return takeChar(scnr, isNamedIdentifier);\n }\n function isDigit(ch) {\n const cc = ch.charCodeAt(0);\n return cc >= 48 && cc <= 57; // 0-9\n }\n function takeDigit(scnr) {\n return takeChar(scnr, isDigit);\n }\n function isHexDigit(ch) {\n const cc = ch.charCodeAt(0);\n return ((cc >= 48 && cc <= 57) || // 0-9\n (cc >= 65 && cc <= 70) || // A-F\n (cc >= 97 && cc <= 102)); // a-f\n }\n function takeHexDigit(scnr) {\n return takeChar(scnr, isHexDigit);\n }\n function getDigits(scnr) {\n let ch = '';\n let num = '';\n while ((ch = takeDigit(scnr))) {\n num += ch;\n }\n return num;\n }\n function readModulo(scnr) {\n skipSpaces(scnr);\n const ch = scnr.currentChar();\n if (ch !== \"%\" /* TokenChars.Modulo */) {\n emitError(CompileErrorCodes.EXPECTED_TOKEN, currentPosition(), 0, ch);\n }\n scnr.next();\n return \"%\" /* TokenChars.Modulo */;\n }\n function readText(scnr) {\n let buf = '';\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const ch = scnr.currentChar();\n if (ch === \"{\" /* TokenChars.BraceLeft */ ||\n ch === \"}\" /* TokenChars.BraceRight */ ||\n ch === \"@\" /* TokenChars.LinkedAlias */ ||\n ch === \"|\" /* TokenChars.Pipe */ ||\n !ch) {\n break;\n }\n else if (ch === \"%\" /* TokenChars.Modulo */) {\n if (isTextStart(scnr)) {\n buf += ch;\n scnr.next();\n }\n else {\n break;\n }\n }\n else if (ch === CHAR_SP || ch === CHAR_LF) {\n if (isTextStart(scnr)) {\n buf += ch;\n scnr.next();\n }\n else if (isPluralStart(scnr)) {\n break;\n }\n else {\n buf += ch;\n scnr.next();\n }\n }\n else {\n buf += ch;\n scnr.next();\n }\n }\n return buf;\n }\n function readNamedIdentifier(scnr) {\n skipSpaces(scnr);\n let ch = '';\n let name = '';\n while ((ch = takeNamedIdentifierChar(scnr))) {\n name += ch;\n }\n if (scnr.currentChar() === EOF) {\n emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);\n }\n return name;\n }\n function readListIdentifier(scnr) {\n skipSpaces(scnr);\n let value = '';\n if (scnr.currentChar() === '-') {\n scnr.next();\n value += `-${getDigits(scnr)}`;\n }\n else {\n value += getDigits(scnr);\n }\n if (scnr.currentChar() === EOF) {\n emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);\n }\n return value;\n }\n function isLiteral(ch) {\n return ch !== LITERAL_DELIMITER && ch !== CHAR_LF;\n }\n function readLiteral(scnr) {\n skipSpaces(scnr);\n // eslint-disable-next-line no-useless-escape\n eat(scnr, `\\'`);\n let ch = '';\n let literal = '';\n while ((ch = takeChar(scnr, isLiteral))) {\n if (ch === '\\\\') {\n literal += readEscapeSequence(scnr);\n }\n else {\n literal += ch;\n }\n }\n const current = scnr.currentChar();\n if (current === CHAR_LF || current === EOF) {\n emitError(CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER, currentPosition(), 0);\n // TODO: Is it correct really?\n if (current === CHAR_LF) {\n scnr.next();\n // eslint-disable-next-line no-useless-escape\n eat(scnr, `\\'`);\n }\n return literal;\n }\n // eslint-disable-next-line no-useless-escape\n eat(scnr, `\\'`);\n return literal;\n }\n function readEscapeSequence(scnr) {\n const ch = scnr.currentChar();\n switch (ch) {\n case '\\\\':\n case `\\'`: // eslint-disable-line no-useless-escape\n scnr.next();\n return `\\\\${ch}`;\n case 'u':\n return readUnicodeEscapeSequence(scnr, ch, 4);\n case 'U':\n return readUnicodeEscapeSequence(scnr, ch, 6);\n default:\n emitError(CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE, currentPosition(), 0, ch);\n return '';\n }\n }\n function readUnicodeEscapeSequence(scnr, unicode, digits) {\n eat(scnr, unicode);\n let sequence = '';\n for (let i = 0; i < digits; i++) {\n const ch = takeHexDigit(scnr);\n if (!ch) {\n emitError(CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE, currentPosition(), 0, `\\\\${unicode}${sequence}${scnr.currentChar()}`);\n break;\n }\n sequence += ch;\n }\n return `\\\\${unicode}${sequence}`;\n }\n function isInvalidIdentifier(ch) {\n return (ch !== \"{\" /* TokenChars.BraceLeft */ &&\n ch !== \"}\" /* TokenChars.BraceRight */ &&\n ch !== CHAR_SP &&\n ch !== CHAR_LF);\n }\n function readInvalidIdentifier(scnr) {\n skipSpaces(scnr);\n let ch = '';\n let identifiers = '';\n while ((ch = takeChar(scnr, isInvalidIdentifier))) {\n identifiers += ch;\n }\n return identifiers;\n }\n function readLinkedModifier(scnr) {\n let ch = '';\n let name = '';\n while ((ch = takeIdentifierChar(scnr))) {\n name += ch;\n }\n return name;\n }\n function readLinkedRefer(scnr) {\n const fn = (buf) => {\n const ch = scnr.currentChar();\n if (ch === \"{\" /* TokenChars.BraceLeft */ ||\n ch === \"%\" /* TokenChars.Modulo */ ||\n ch === \"@\" /* TokenChars.LinkedAlias */ ||\n ch === \"|\" /* TokenChars.Pipe */ ||\n ch === \"(\" /* TokenChars.ParenLeft */ ||\n ch === \")\" /* TokenChars.ParenRight */ ||\n !ch) {\n return buf;\n }\n else if (ch === CHAR_SP) {\n return buf;\n }\n else if (ch === CHAR_LF || ch === DOT) {\n buf += ch;\n scnr.next();\n return fn(buf);\n }\n else {\n buf += ch;\n scnr.next();\n return fn(buf);\n }\n };\n return fn('');\n }\n function readPlural(scnr) {\n skipSpaces(scnr);\n const plural = eat(scnr, \"|\" /* TokenChars.Pipe */);\n skipSpaces(scnr);\n return plural;\n }\n // TODO: We need refactoring of token parsing ...\n function readTokenInPlaceholder(scnr, context) {\n let token = null;\n const ch = scnr.currentChar();\n switch (ch) {\n case \"{\" /* TokenChars.BraceLeft */:\n if (context.braceNest >= 1) {\n emitError(CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER, currentPosition(), 0);\n }\n scnr.next();\n token = getToken(context, 2 /* TokenTypes.BraceLeft */, \"{\" /* TokenChars.BraceLeft */);\n skipSpaces(scnr);\n context.braceNest++;\n return token;\n case \"}\" /* TokenChars.BraceRight */:\n if (context.braceNest > 0 &&\n context.currentType === 2 /* TokenTypes.BraceLeft */) {\n emitError(CompileErrorCodes.EMPTY_PLACEHOLDER, currentPosition(), 0);\n }\n scnr.next();\n token = getToken(context, 3 /* TokenTypes.BraceRight */, \"}\" /* TokenChars.BraceRight */);\n context.braceNest--;\n context.braceNest > 0 && skipSpaces(scnr);\n if (context.inLinked && context.braceNest === 0) {\n context.inLinked = false;\n }\n return token;\n case \"@\" /* TokenChars.LinkedAlias */:\n if (context.braceNest > 0) {\n emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);\n }\n token = readTokenInLinked(scnr, context) || getEndToken(context);\n context.braceNest = 0;\n return token;\n default: {\n let validNamedIdentifier = true;\n let validListIdentifier = true;\n let validLiteral = true;\n if (isPluralStart(scnr)) {\n if (context.braceNest > 0) {\n emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);\n }\n token = getToken(context, 1 /* TokenTypes.Pipe */, readPlural(scnr));\n // reset\n context.braceNest = 0;\n context.inLinked = false;\n return token;\n }\n if (context.braceNest > 0 &&\n (context.currentType === 5 /* TokenTypes.Named */ ||\n context.currentType === 6 /* TokenTypes.List */ ||\n context.currentType === 7 /* TokenTypes.Literal */)) {\n emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);\n context.braceNest = 0;\n return readToken(scnr, context);\n }\n if ((validNamedIdentifier = isNamedIdentifierStart(scnr, context))) {\n token = getToken(context, 5 /* TokenTypes.Named */, readNamedIdentifier(scnr));\n skipSpaces(scnr);\n return token;\n }\n if ((validListIdentifier = isListIdentifierStart(scnr, context))) {\n token = getToken(context, 6 /* TokenTypes.List */, readListIdentifier(scnr));\n skipSpaces(scnr);\n return token;\n }\n if ((validLiteral = isLiteralStart(scnr, context))) {\n token = getToken(context, 7 /* TokenTypes.Literal */, readLiteral(scnr));\n skipSpaces(scnr);\n return token;\n }\n if (!validNamedIdentifier && !validListIdentifier && !validLiteral) {\n // TODO: we should be re-designed invalid cases, when we will extend message syntax near the future ...\n token = getToken(context, 13 /* TokenTypes.InvalidPlace */, readInvalidIdentifier(scnr));\n emitError(CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER, currentPosition(), 0, token.value);\n skipSpaces(scnr);\n return token;\n }\n break;\n }\n }\n return token;\n }\n // TODO: We need refactoring of token parsing ...\n function readTokenInLinked(scnr, context) {\n const { currentType } = context;\n let token = null;\n const ch = scnr.currentChar();\n if ((currentType === 8 /* TokenTypes.LinkedAlias */ ||\n currentType === 9 /* TokenTypes.LinkedDot */ ||\n currentType === 12 /* TokenTypes.LinkedModifier */ ||\n currentType === 10 /* TokenTypes.LinkedDelimiter */) &&\n (ch === CHAR_LF || ch === CHAR_SP)) {\n emitError(CompileErrorCodes.INVALID_LINKED_FORMAT, currentPosition(), 0);\n }\n switch (ch) {\n case \"@\" /* TokenChars.LinkedAlias */:\n scnr.next();\n token = getToken(context, 8 /* TokenTypes.LinkedAlias */, \"@\" /* TokenChars.LinkedAlias */);\n context.inLinked = true;\n return token;\n case \".\" /* TokenChars.LinkedDot */:\n skipSpaces(scnr);\n scnr.next();\n return getToken(context, 9 /* TokenTypes.LinkedDot */, \".\" /* TokenChars.LinkedDot */);\n case \":\" /* TokenChars.LinkedDelimiter */:\n skipSpaces(scnr);\n scnr.next();\n return getToken(context, 10 /* TokenTypes.LinkedDelimiter */, \":\" /* TokenChars.LinkedDelimiter */);\n default:\n if (isPluralStart(scnr)) {\n token = getToken(context, 1 /* TokenTypes.Pipe */, readPlural(scnr));\n // reset\n context.braceNest = 0;\n context.inLinked = false;\n return token;\n }\n if (isLinkedDotStart(scnr, context) ||\n isLinkedDelimiterStart(scnr, context)) {\n skipSpaces(scnr);\n return readTokenInLinked(scnr, context);\n }\n if (isLinkedModifierStart(scnr, context)) {\n skipSpaces(scnr);\n return getToken(context, 12 /* TokenTypes.LinkedModifier */, readLinkedModifier(scnr));\n }\n if (isLinkedReferStart(scnr, context)) {\n skipSpaces(scnr);\n if (ch === \"{\" /* TokenChars.BraceLeft */) {\n // scan the placeholder\n return readTokenInPlaceholder(scnr, context) || token;\n }\n else {\n return getToken(context, 11 /* TokenTypes.LinkedKey */, readLinkedRefer(scnr));\n }\n }\n if (currentType === 8 /* TokenTypes.LinkedAlias */) {\n emitError(CompileErrorCodes.INVALID_LINKED_FORMAT, currentPosition(), 0);\n }\n context.braceNest = 0;\n context.inLinked = false;\n return readToken(scnr, context);\n }\n }\n // TODO: We need refactoring of token parsing ...\n function readToken(scnr, context) {\n let token = { type: 14 /* TokenTypes.EOF */ };\n if (context.braceNest > 0) {\n return readTokenInPlaceholder(scnr, context) || getEndToken(context);\n }\n if (context.inLinked) {\n return readTokenInLinked(scnr, context) || getEndToken(context);\n }\n const ch = scnr.currentChar();\n switch (ch) {\n case \"{\" /* TokenChars.BraceLeft */:\n return readTokenInPlaceholder(scnr, context) || getEndToken(context);\n case \"}\" /* TokenChars.BraceRight */:\n emitError(CompileErrorCodes.UNBALANCED_CLOSING_BRACE, currentPosition(), 0);\n scnr.next();\n return getToken(context, 3 /* TokenTypes.BraceRight */, \"}\" /* TokenChars.BraceRight */);\n case \"@\" /* TokenChars.LinkedAlias */:\n return readTokenInLinked(scnr, context) || getEndToken(context);\n default: {\n if (isPluralStart(scnr)) {\n token = getToken(context, 1 /* TokenTypes.Pipe */, readPlural(scnr));\n // reset\n context.braceNest = 0;\n context.inLinked = false;\n return token;\n }\n const { isModulo, hasSpace } = detectModuloStart(scnr);\n if (isModulo) {\n return hasSpace\n ? getToken(context, 0 /* TokenTypes.Text */, readText(scnr))\n : getToken(context, 4 /* TokenTypes.Modulo */, readModulo(scnr));\n }\n if (isTextStart(scnr)) {\n return getToken(context, 0 /* TokenTypes.Text */, readText(scnr));\n }\n break;\n }\n }\n return token;\n }\n function nextToken() {\n const { currentType, offset, startLoc, endLoc } = _context;\n _context.lastType = currentType;\n _context.lastOffset = offset;\n _context.lastStartLoc = startLoc;\n _context.lastEndLoc = endLoc;\n _context.offset = currentOffset();\n _context.startLoc = currentPosition();\n if (_scnr.currentChar() === EOF) {\n return getToken(_context, 14 /* TokenTypes.EOF */);\n }\n return readToken(_scnr, _context);\n }\n return {\n nextToken,\n currentOffset,\n currentPosition,\n context\n };\n}\n\nconst ERROR_DOMAIN$2 = 'parser';\n// Backslash backslash, backslash quote, uHHHH, UHHHHHH.\nconst KNOWN_ESCAPES = /(?:\\\\\\\\|\\\\'|\\\\u([0-9a-fA-F]{4})|\\\\U([0-9a-fA-F]{6}))/g;\nfunction fromEscapeSequence(match, codePoint4, codePoint6) {\n switch (match) {\n case `\\\\\\\\`:\n return `\\\\`;\n // eslint-disable-next-line no-useless-escape\n case `\\\\\\'`:\n // eslint-disable-next-line no-useless-escape\n return `\\'`;\n default: {\n const codePoint = parseInt(codePoint4 || codePoint6, 16);\n if (codePoint <= 0xd7ff || codePoint >= 0xe000) {\n return String.fromCodePoint(codePoint);\n }\n // invalid ...\n // Replace them with U+FFFD REPLACEMENT CHARACTER.\n return '�';\n }\n }\n}\nfunction createParser(options = {}) {\n const location = options.location !== false;\n const { onError, onWarn } = options;\n function emitError(tokenzer, code, start, offset, ...args) {\n const end = tokenzer.currentPosition();\n end.offset += offset;\n end.column += offset;\n if (onError) {\n const loc = location ? createLocation(start, end) : null;\n const err = createCompileError(code, loc, {\n domain: ERROR_DOMAIN$2,\n args\n });\n onError(err);\n }\n }\n function emitWarn(tokenzer, code, start, offset, ...args) {\n const end = tokenzer.currentPosition();\n end.offset += offset;\n end.column += offset;\n if (onWarn) {\n const loc = location ? createLocation(start, end) : null;\n onWarn(createCompileWarn(code, loc, args));\n }\n }\n function startNode(type, offset, loc) {\n const node = { type };\n if (location) {\n node.start = offset;\n node.end = offset;\n node.loc = { start: loc, end: loc };\n }\n return node;\n }\n function endNode(node, offset, pos, type) {\n if (type) {\n node.type = type;\n }\n if (location) {\n node.end = offset;\n if (node.loc) {\n node.loc.end = pos;\n }\n }\n }\n function parseText(tokenizer, value) {\n const context = tokenizer.context();\n const node = startNode(3 /* NodeTypes.Text */, context.offset, context.startLoc);\n node.value = value;\n endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());\n return node;\n }\n function parseList(tokenizer, index) {\n const context = tokenizer.context();\n const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc\n const node = startNode(5 /* NodeTypes.List */, offset, loc);\n node.index = parseInt(index, 10);\n tokenizer.nextToken(); // skip brach right\n endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());\n return node;\n }\n function parseNamed(tokenizer, key, modulo) {\n const context = tokenizer.context();\n const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc\n const node = startNode(4 /* NodeTypes.Named */, offset, loc);\n node.key = key;\n if (modulo === true) {\n node.modulo = true;\n }\n tokenizer.nextToken(); // skip brach right\n endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());\n return node;\n }\n function parseLiteral(tokenizer, value) {\n const context = tokenizer.context();\n const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc\n const node = startNode(9 /* NodeTypes.Literal */, offset, loc);\n node.value = value.replace(KNOWN_ESCAPES, fromEscapeSequence);\n tokenizer.nextToken(); // skip brach right\n endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());\n return node;\n }\n function parseLinkedModifier(tokenizer) {\n const token = tokenizer.nextToken();\n const context = tokenizer.context();\n const { lastOffset: offset, lastStartLoc: loc } = context; // get linked dot loc\n const node = startNode(8 /* NodeTypes.LinkedModifier */, offset, loc);\n if (token.type !== 12 /* TokenTypes.LinkedModifier */) {\n // empty modifier\n emitError(tokenizer, CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_MODIFIER, context.lastStartLoc, 0);\n node.value = '';\n endNode(node, offset, loc);\n return {\n nextConsumeToken: token,\n node\n };\n }\n // check token\n if (token.value == null) {\n emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));\n }\n node.value = token.value || '';\n endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());\n return {\n node\n };\n }\n function parseLinkedKey(tokenizer, value) {\n const context = tokenizer.context();\n const node = startNode(7 /* NodeTypes.LinkedKey */, context.offset, context.startLoc);\n node.value = value;\n endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());\n return node;\n }\n function parseLinked(tokenizer) {\n const context = tokenizer.context();\n const linkedNode = startNode(6 /* NodeTypes.Linked */, context.offset, context.startLoc);\n let token = tokenizer.nextToken();\n if (token.type === 9 /* TokenTypes.LinkedDot */) {\n const parsed = parseLinkedModifier(tokenizer);\n linkedNode.modifier = parsed.node;\n token = parsed.nextConsumeToken || tokenizer.nextToken();\n }\n // asset check token\n if (token.type !== 10 /* TokenTypes.LinkedDelimiter */) {\n emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));\n }\n token = tokenizer.nextToken();\n // skip brace left\n if (token.type === 2 /* TokenTypes.BraceLeft */) {\n token = tokenizer.nextToken();\n }\n switch (token.type) {\n case 11 /* TokenTypes.LinkedKey */:\n if (token.value == null) {\n emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));\n }\n linkedNode.key = parseLinkedKey(tokenizer, token.value || '');\n break;\n case 5 /* TokenTypes.Named */:\n if (token.value == null) {\n emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));\n }\n linkedNode.key = parseNamed(tokenizer, token.value || '');\n break;\n case 6 /* TokenTypes.List */:\n if (token.value == null) {\n emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));\n }\n linkedNode.key = parseList(tokenizer, token.value || '');\n break;\n case 7 /* TokenTypes.Literal */:\n if (token.value == null) {\n emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));\n }\n linkedNode.key = parseLiteral(tokenizer, token.value || '');\n break;\n default: {\n // empty key\n emitError(tokenizer, CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_KEY, context.lastStartLoc, 0);\n const nextContext = tokenizer.context();\n const emptyLinkedKeyNode = startNode(7 /* NodeTypes.LinkedKey */, nextContext.offset, nextContext.startLoc);\n emptyLinkedKeyNode.value = '';\n endNode(emptyLinkedKeyNode, nextContext.offset, nextContext.startLoc);\n linkedNode.key = emptyLinkedKeyNode;\n endNode(linkedNode, nextContext.offset, nextContext.startLoc);\n return {\n nextConsumeToken: token,\n node: linkedNode\n };\n }\n }\n endNode(linkedNode, tokenizer.currentOffset(), tokenizer.currentPosition());\n return {\n node: linkedNode\n };\n }\n function parseMessage(tokenizer) {\n const context = tokenizer.context();\n const startOffset = context.currentType === 1 /* TokenTypes.Pipe */\n ? tokenizer.currentOffset()\n : context.offset;\n const startLoc = context.currentType === 1 /* TokenTypes.Pipe */\n ? context.endLoc\n : context.startLoc;\n const node = startNode(2 /* NodeTypes.Message */, startOffset, startLoc);\n node.items = [];\n let nextToken = null;\n let modulo = null;\n do {\n const token = nextToken || tokenizer.nextToken();\n nextToken = null;\n switch (token.type) {\n case 0 /* TokenTypes.Text */:\n if (token.value == null) {\n emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));\n }\n node.items.push(parseText(tokenizer, token.value || ''));\n break;\n case 6 /* TokenTypes.List */:\n if (token.value == null) {\n emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));\n }\n node.items.push(parseList(tokenizer, token.value || ''));\n break;\n case 4 /* TokenTypes.Modulo */:\n modulo = true;\n break;\n case 5 /* TokenTypes.Named */:\n if (token.value == null) {\n emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));\n }\n node.items.push(parseNamed(tokenizer, token.value || '', !!modulo));\n if (modulo) {\n emitWarn(tokenizer, CompileWarnCodes.USE_MODULO_SYNTAX, context.lastStartLoc, 0, getTokenCaption(token));\n modulo = null;\n }\n break;\n case 7 /* TokenTypes.Literal */:\n if (token.value == null) {\n emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));\n }\n node.items.push(parseLiteral(tokenizer, token.value || ''));\n break;\n case 8 /* TokenTypes.LinkedAlias */: {\n const parsed = parseLinked(tokenizer);\n node.items.push(parsed.node);\n nextToken = parsed.nextConsumeToken || null;\n break;\n }\n }\n } while (context.currentType !== 14 /* TokenTypes.EOF */ &&\n context.currentType !== 1 /* TokenTypes.Pipe */);\n // adjust message node loc\n const endOffset = context.currentType === 1 /* TokenTypes.Pipe */\n ? context.lastOffset\n : tokenizer.currentOffset();\n const endLoc = context.currentType === 1 /* TokenTypes.Pipe */\n ? context.lastEndLoc\n : tokenizer.currentPosition();\n endNode(node, endOffset, endLoc);\n return node;\n }\n function parsePlural(tokenizer, offset, loc, msgNode) {\n const context = tokenizer.context();\n let hasEmptyMessage = msgNode.items.length === 0;\n const node = startNode(1 /* NodeTypes.Plural */, offset, loc);\n node.cases = [];\n node.cases.push(msgNode);\n do {\n const msg = parseMessage(tokenizer);\n if (!hasEmptyMessage) {\n hasEmptyMessage = msg.items.length === 0;\n }\n node.cases.push(msg);\n } while (context.currentType !== 14 /* TokenTypes.EOF */);\n if (hasEmptyMessage) {\n emitError(tokenizer, CompileErrorCodes.MUST_HAVE_MESSAGES_IN_PLURAL, loc, 0);\n }\n endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());\n return node;\n }\n function parseResource(tokenizer) {\n const context = tokenizer.context();\n const { offset, startLoc } = context;\n const msgNode = parseMessage(tokenizer);\n if (context.currentType === 14 /* TokenTypes.EOF */) {\n return msgNode;\n }\n else {\n return parsePlural(tokenizer, offset, startLoc, msgNode);\n }\n }\n function parse(source) {\n const tokenizer = createTokenizer(source, assign({}, options));\n const context = tokenizer.context();\n const node = startNode(0 /* NodeTypes.Resource */, context.offset, context.startLoc);\n if (location && node.loc) {\n node.loc.source = source;\n }\n node.body = parseResource(tokenizer);\n if (options.onCacheKey) {\n node.cacheKey = options.onCacheKey(source);\n }\n // assert whether achieved to EOF\n if (context.currentType !== 14 /* TokenTypes.EOF */) {\n emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, source[context.offset] || '');\n }\n endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());\n return node;\n }\n return { parse };\n}\nfunction getTokenCaption(token) {\n if (token.type === 14 /* TokenTypes.EOF */) {\n return 'EOF';\n }\n const name = (token.value || '').replace(/\\r?\\n/gu, '\\\\n');\n return name.length > 10 ? name.slice(0, 9) + '…' : name;\n}\n\nfunction createTransformer(ast, options = {} // eslint-disable-line\n) {\n const _context = {\n ast,\n helpers: new Set()\n };\n const context = () => _context;\n const helper = (name) => {\n _context.helpers.add(name);\n return name;\n };\n return { context, helper };\n}\nfunction traverseNodes(nodes, transformer) {\n for (let i = 0; i < nodes.length; i++) {\n traverseNode(nodes[i], transformer);\n }\n}\nfunction traverseNode(node, transformer) {\n // TODO: if we need pre-hook of transform, should be implemented to here\n switch (node.type) {\n case 1 /* NodeTypes.Plural */:\n traverseNodes(node.cases, transformer);\n transformer.helper(\"plural\" /* HelperNameMap.PLURAL */);\n break;\n case 2 /* NodeTypes.Message */:\n traverseNodes(node.items, transformer);\n break;\n case 6 /* NodeTypes.Linked */: {\n const linked = node;\n traverseNode(linked.key, transformer);\n transformer.helper(\"linked\" /* HelperNameMap.LINKED */);\n transformer.helper(\"type\" /* HelperNameMap.TYPE */);\n break;\n }\n case 5 /* NodeTypes.List */:\n transformer.helper(\"interpolate\" /* HelperNameMap.INTERPOLATE */);\n transformer.helper(\"list\" /* HelperNameMap.LIST */);\n break;\n case 4 /* NodeTypes.Named */:\n transformer.helper(\"interpolate\" /* HelperNameMap.INTERPOLATE */);\n transformer.helper(\"named\" /* HelperNameMap.NAMED */);\n break;\n }\n // TODO: if we need post-hook of transform, should be implemented to here\n}\n// transform AST\nfunction transform(ast, options = {} // eslint-disable-line\n) {\n const transformer = createTransformer(ast);\n transformer.helper(\"normalize\" /* HelperNameMap.NORMALIZE */);\n // traverse\n ast.body && traverseNode(ast.body, transformer);\n // set meta information\n const context = transformer.context();\n ast.helpers = Array.from(context.helpers);\n}\n\nfunction optimize(ast) {\n const body = ast.body;\n if (body.type === 2 /* NodeTypes.Message */) {\n optimizeMessageNode(body);\n }\n else {\n body.cases.forEach(c => optimizeMessageNode(c));\n }\n return ast;\n}\nfunction optimizeMessageNode(message) {\n if (message.items.length === 1) {\n const item = message.items[0];\n if (item.type === 3 /* NodeTypes.Text */ || item.type === 9 /* NodeTypes.Literal */) {\n message.static = item.value;\n delete item.value; // optimization for size\n }\n }\n else {\n const values = [];\n for (let i = 0; i < message.items.length; i++) {\n const item = message.items[i];\n if (!(item.type === 3 /* NodeTypes.Text */ || item.type === 9 /* NodeTypes.Literal */)) {\n break;\n }\n if (item.value == null) {\n break;\n }\n values.push(item.value);\n }\n if (values.length === message.items.length) {\n message.static = join(values);\n for (let i = 0; i < message.items.length; i++) {\n const item = message.items[i];\n if (item.type === 3 /* NodeTypes.Text */ || item.type === 9 /* NodeTypes.Literal */) {\n delete item.value; // optimization for size\n }\n }\n }\n }\n}\n\nconst ERROR_DOMAIN$1 = 'minifier';\n/* eslint-disable @typescript-eslint/no-explicit-any */\nfunction minify(node) {\n node.t = node.type;\n switch (node.type) {\n case 0 /* NodeTypes.Resource */: {\n const resource = node;\n minify(resource.body);\n resource.b = resource.body;\n delete resource.body;\n break;\n }\n case 1 /* NodeTypes.Plural */: {\n const plural = node;\n const cases = plural.cases;\n for (let i = 0; i < cases.length; i++) {\n minify(cases[i]);\n }\n plural.c = cases;\n delete plural.cases;\n break;\n }\n case 2 /* NodeTypes.Message */: {\n const message = node;\n const items = message.items;\n for (let i = 0; i < items.length; i++) {\n minify(items[i]);\n }\n message.i = items;\n delete message.items;\n if (message.static) {\n message.s = message.static;\n delete message.static;\n }\n break;\n }\n case 3 /* NodeTypes.Text */:\n case 9 /* NodeTypes.Literal */:\n case 8 /* NodeTypes.LinkedModifier */:\n case 7 /* NodeTypes.LinkedKey */: {\n const valueNode = node;\n if (valueNode.value) {\n valueNode.v = valueNode.value;\n delete valueNode.value;\n }\n break;\n }\n case 6 /* NodeTypes.Linked */: {\n const linked = node;\n minify(linked.key);\n linked.k = linked.key;\n delete linked.key;\n if (linked.modifier) {\n minify(linked.modifier);\n linked.m = linked.modifier;\n delete linked.modifier;\n }\n break;\n }\n case 5 /* NodeTypes.List */: {\n const list = node;\n list.i = list.index;\n delete list.index;\n break;\n }\n case 4 /* NodeTypes.Named */: {\n const named = node;\n named.k = named.key;\n delete named.key;\n break;\n }\n default:\n {\n throw createCompileError(CompileErrorCodes.UNHANDLED_MINIFIER_NODE_TYPE, null, {\n domain: ERROR_DOMAIN$1,\n args: [node.type]\n });\n }\n }\n delete node.type;\n}\n/* eslint-enable @typescript-eslint/no-explicit-any */\n\n// eslint-disable-next-line @typescript-eslint/triple-slash-reference\n/// \nconst ERROR_DOMAIN = 'parser';\nfunction createCodeGenerator(ast, options) {\n const { sourceMap, filename, breakLineCode, needIndent: _needIndent } = options;\n const location = options.location !== false;\n const _context = {\n filename,\n code: '',\n column: 1,\n line: 1,\n offset: 0,\n map: undefined,\n breakLineCode,\n needIndent: _needIndent,\n indentLevel: 0\n };\n if (location && ast.loc) {\n _context.source = ast.loc.source;\n }\n const context = () => _context;\n function push(code, node) {\n _context.code += code;\n }\n function _newline(n, withBreakLine = true) {\n const _breakLineCode = withBreakLine ? breakLineCode : '';\n push(_needIndent ? _breakLineCode + ` `.repeat(n) : _breakLineCode);\n }\n function indent(withNewLine = true) {\n const level = ++_context.indentLevel;\n withNewLine && _newline(level);\n }\n function deindent(withNewLine = true) {\n const level = --_context.indentLevel;\n withNewLine && _newline(level);\n }\n function newline() {\n _newline(_context.indentLevel);\n }\n const helper = (key) => `_${key}`;\n const needIndent = () => _context.needIndent;\n return {\n context,\n push,\n indent,\n deindent,\n newline,\n helper,\n needIndent\n };\n}\nfunction generateLinkedNode(generator, node) {\n const { helper } = generator;\n generator.push(`${helper(\"linked\" /* HelperNameMap.LINKED */)}(`);\n generateNode(generator, node.key);\n if (node.modifier) {\n generator.push(`, `);\n generateNode(generator, node.modifier);\n generator.push(`, _type`);\n }\n else {\n generator.push(`, undefined, _type`);\n }\n generator.push(`)`);\n}\nfunction generateMessageNode(generator, node) {\n const { helper, needIndent } = generator;\n generator.push(`${helper(\"normalize\" /* HelperNameMap.NORMALIZE */)}([`);\n generator.indent(needIndent());\n const length = node.items.length;\n for (let i = 0; i < length; i++) {\n generateNode(generator, node.items[i]);\n if (i === length - 1) {\n break;\n }\n generator.push(', ');\n }\n generator.deindent(needIndent());\n generator.push('])');\n}\nfunction generatePluralNode(generator, node) {\n const { helper, needIndent } = generator;\n if (node.cases.length > 1) {\n generator.push(`${helper(\"plural\" /* HelperNameMap.PLURAL */)}([`);\n generator.indent(needIndent());\n const length = node.cases.length;\n for (let i = 0; i < length; i++) {\n generateNode(generator, node.cases[i]);\n if (i === length - 1) {\n break;\n }\n generator.push(', ');\n }\n generator.deindent(needIndent());\n generator.push(`])`);\n }\n}\nfunction generateResource(generator, node) {\n if (node.body) {\n generateNode(generator, node.body);\n }\n else {\n generator.push('null');\n }\n}\nfunction generateNode(generator, node) {\n const { helper } = generator;\n switch (node.type) {\n case 0 /* NodeTypes.Resource */:\n generateResource(generator, node);\n break;\n case 1 /* NodeTypes.Plural */:\n generatePluralNode(generator, node);\n break;\n case 2 /* NodeTypes.Message */:\n generateMessageNode(generator, node);\n break;\n case 6 /* NodeTypes.Linked */:\n generateLinkedNode(generator, node);\n break;\n case 8 /* NodeTypes.LinkedModifier */:\n generator.push(JSON.stringify(node.value), node);\n break;\n case 7 /* NodeTypes.LinkedKey */:\n generator.push(JSON.stringify(node.value), node);\n break;\n case 5 /* NodeTypes.List */:\n generator.push(`${helper(\"interpolate\" /* HelperNameMap.INTERPOLATE */)}(${helper(\"list\" /* HelperNameMap.LIST */)}(${node.index}))`, node);\n break;\n case 4 /* NodeTypes.Named */:\n generator.push(`${helper(\"interpolate\" /* HelperNameMap.INTERPOLATE */)}(${helper(\"named\" /* HelperNameMap.NAMED */)}(${JSON.stringify(node.key)}))`, node);\n break;\n case 9 /* NodeTypes.Literal */:\n generator.push(JSON.stringify(node.value), node);\n break;\n case 3 /* NodeTypes.Text */:\n generator.push(JSON.stringify(node.value), node);\n break;\n default:\n {\n throw createCompileError(CompileErrorCodes.UNHANDLED_CODEGEN_NODE_TYPE, null, {\n domain: ERROR_DOMAIN,\n args: [node.type]\n });\n }\n }\n}\n// generate code from AST\nconst generate = (ast, options = {} // eslint-disable-line\n) => {\n const mode = isString(options.mode) ? options.mode : 'normal';\n const filename = isString(options.filename)\n ? options.filename\n : 'message.intl';\n const sourceMap = !!options.sourceMap;\n // prettier-ignore\n const breakLineCode = options.breakLineCode != null\n ? options.breakLineCode\n : mode === 'arrow'\n ? ';'\n : '\\n';\n const needIndent = options.needIndent ? options.needIndent : mode !== 'arrow';\n const helpers = ast.helpers || [];\n const generator = createCodeGenerator(ast, {\n mode,\n filename,\n sourceMap,\n breakLineCode,\n needIndent\n });\n generator.push(mode === 'normal' ? `function __msg__ (ctx) {` : `(ctx) => {`);\n generator.indent(needIndent);\n if (helpers.length > 0) {\n generator.push(`const { ${join(helpers.map(s => `${s}: _${s}`), ', ')} } = ctx`);\n generator.newline();\n }\n generator.push(`return `);\n generateNode(generator, ast);\n generator.deindent(needIndent);\n generator.push(`}`);\n delete ast.helpers;\n const { code, map } = generator.context();\n return {\n ast,\n code,\n map: map ? map.toJSON() : undefined // eslint-disable-line @typescript-eslint/no-explicit-any\n };\n};\n\nfunction baseCompile(source, options = {}) {\n const assignedOptions = assign({}, options);\n const jit = !!assignedOptions.jit;\n const enalbeMinify = !!assignedOptions.minify;\n const enambeOptimize = assignedOptions.optimize == null ? true : assignedOptions.optimize;\n // parse source codes\n const parser = createParser(assignedOptions);\n const ast = parser.parse(source);\n if (!jit) {\n // transform ASTs\n transform(ast, assignedOptions);\n // generate javascript codes\n return generate(ast, assignedOptions);\n }\n else {\n // optimize ASTs\n enambeOptimize && optimize(ast);\n // minimize ASTs\n enalbeMinify && minify(ast);\n // In JIT mode, no ast transform, no code generation.\n return { ast, code: '' };\n }\n}\n\nexport { CompileErrorCodes, CompileWarnCodes, ERROR_DOMAIN$2 as ERROR_DOMAIN, LOCATION_STUB, baseCompile, createCompileError, createCompileWarn, createLocation, createParser, createPosition, defaultOnError, detectHtmlTag, errorMessages, warnMessages };\n","/*!\n * core-base v9.13.1\n * (c) 2024 kazuya kawaguchi\n * Released under the MIT License.\n */\nimport { getGlobalThis, isObject, isFunction, isString, isNumber, isPlainObject, assign, join, toDisplayString, isArray, incrementer, format as format$1, isPromise, isBoolean, warn, isRegExp, warnOnce, escapeHtml, inBrowser, mark, measure, isEmptyObject, generateCodeFrame, generateFormatCacheKey, isDate } from '@intlify/shared';\nimport { CompileWarnCodes, CompileErrorCodes, createCompileError, detectHtmlTag, defaultOnError, baseCompile as baseCompile$1 } from '@intlify/message-compiler';\nexport { CompileErrorCodes, createCompileError } from '@intlify/message-compiler';\n\n/**\n * This is only called in esm-bundler builds.\n * istanbul-ignore-next\n */\nfunction initFeatureFlags() {\n if (typeof __INTLIFY_PROD_DEVTOOLS__ !== 'boolean') {\n getGlobalThis().__INTLIFY_PROD_DEVTOOLS__ = false;\n }\n if (typeof __INTLIFY_JIT_COMPILATION__ !== 'boolean') {\n getGlobalThis().__INTLIFY_JIT_COMPILATION__ = false;\n }\n if (typeof __INTLIFY_DROP_MESSAGE_COMPILER__ !== 'boolean') {\n getGlobalThis().__INTLIFY_DROP_MESSAGE_COMPILER__ = false;\n }\n}\n\nconst pathStateMachine = [];\npathStateMachine[0 /* States.BEFORE_PATH */] = {\n [\"w\" /* PathCharTypes.WORKSPACE */]: [0 /* States.BEFORE_PATH */],\n [\"i\" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],\n [\"[\" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],\n [\"o\" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]\n};\npathStateMachine[1 /* States.IN_PATH */] = {\n [\"w\" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */],\n [\".\" /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */],\n [\"[\" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],\n [\"o\" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]\n};\npathStateMachine[2 /* States.BEFORE_IDENT */] = {\n [\"w\" /* PathCharTypes.WORKSPACE */]: [2 /* States.BEFORE_IDENT */],\n [\"i\" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],\n [\"0\" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */]\n};\npathStateMachine[3 /* States.IN_IDENT */] = {\n [\"i\" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],\n [\"0\" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],\n [\"w\" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */, 1 /* Actions.PUSH */],\n [\".\" /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */, 1 /* Actions.PUSH */],\n [\"[\" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */, 1 /* Actions.PUSH */],\n [\"o\" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */, 1 /* Actions.PUSH */]\n};\npathStateMachine[4 /* States.IN_SUB_PATH */] = {\n [\"'\" /* PathCharTypes.SINGLE_QUOTE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */],\n [\"\\\"\" /* PathCharTypes.DOUBLE_QUOTE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */],\n [\"[\" /* PathCharTypes.LEFT_BRACKET */]: [\n 4 /* States.IN_SUB_PATH */,\n 2 /* Actions.INC_SUB_PATH_DEPTH */\n ],\n [\"]\" /* PathCharTypes.RIGHT_BRACKET */]: [1 /* States.IN_PATH */, 3 /* Actions.PUSH_SUB_PATH */],\n [\"o\" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,\n [\"l\" /* PathCharTypes.ELSE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */]\n};\npathStateMachine[5 /* States.IN_SINGLE_QUOTE */] = {\n [\"'\" /* PathCharTypes.SINGLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],\n [\"o\" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,\n [\"l\" /* PathCharTypes.ELSE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */]\n};\npathStateMachine[6 /* States.IN_DOUBLE_QUOTE */] = {\n [\"\\\"\" /* PathCharTypes.DOUBLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],\n [\"o\" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,\n [\"l\" /* PathCharTypes.ELSE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */]\n};\n/**\n * Check if an expression is a literal value.\n */\nconst literalValueRE = /^\\s?(?:true|false|-?[\\d.]+|'[^']*'|\"[^\"]*\")\\s?$/;\nfunction isLiteral(exp) {\n return literalValueRE.test(exp);\n}\n/**\n * Strip quotes from a string\n */\nfunction stripQuotes(str) {\n const a = str.charCodeAt(0);\n const b = str.charCodeAt(str.length - 1);\n return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str;\n}\n/**\n * Determine the type of a character in a keypath.\n */\nfunction getPathCharType(ch) {\n if (ch === undefined || ch === null) {\n return \"o\" /* PathCharTypes.END_OF_FAIL */;\n }\n const code = ch.charCodeAt(0);\n switch (code) {\n case 0x5b: // [\n case 0x5d: // ]\n case 0x2e: // .\n case 0x22: // \"\n case 0x27: // '\n return ch;\n case 0x5f: // _\n case 0x24: // $\n case 0x2d: // -\n return \"i\" /* PathCharTypes.IDENT */;\n case 0x09: // Tab (HT)\n case 0x0a: // Newline (LF)\n case 0x0d: // Return (CR)\n case 0xa0: // No-break space (NBSP)\n case 0xfeff: // Byte Order Mark (BOM)\n case 0x2028: // Line Separator (LS)\n case 0x2029: // Paragraph Separator (PS)\n return \"w\" /* PathCharTypes.WORKSPACE */;\n }\n return \"i\" /* PathCharTypes.IDENT */;\n}\n/**\n * Format a subPath, return its plain form if it is\n * a literal string or number. Otherwise prepend the\n * dynamic indicator (*).\n */\nfunction formatSubPath(path) {\n const trimmed = path.trim();\n // invalid leading 0\n if (path.charAt(0) === '0' && isNaN(parseInt(path))) {\n return false;\n }\n return isLiteral(trimmed)\n ? stripQuotes(trimmed)\n : \"*\" /* PathCharTypes.ASTARISK */ + trimmed;\n}\n/**\n * Parse a string path into an array of segments\n */\nfunction parse(path) {\n const keys = [];\n let index = -1;\n let mode = 0 /* States.BEFORE_PATH */;\n let subPathDepth = 0;\n let c;\n let key; // eslint-disable-line\n let newChar;\n let type;\n let transition;\n let action;\n let typeMap;\n const actions = [];\n actions[0 /* Actions.APPEND */] = () => {\n if (key === undefined) {\n key = newChar;\n }\n else {\n key += newChar;\n }\n };\n actions[1 /* Actions.PUSH */] = () => {\n if (key !== undefined) {\n keys.push(key);\n key = undefined;\n }\n };\n actions[2 /* Actions.INC_SUB_PATH_DEPTH */] = () => {\n actions[0 /* Actions.APPEND */]();\n subPathDepth++;\n };\n actions[3 /* Actions.PUSH_SUB_PATH */] = () => {\n if (subPathDepth > 0) {\n subPathDepth--;\n mode = 4 /* States.IN_SUB_PATH */;\n actions[0 /* Actions.APPEND */]();\n }\n else {\n subPathDepth = 0;\n if (key === undefined) {\n return false;\n }\n key = formatSubPath(key);\n if (key === false) {\n return false;\n }\n else {\n actions[1 /* Actions.PUSH */]();\n }\n }\n };\n function maybeUnescapeQuote() {\n const nextChar = path[index + 1];\n if ((mode === 5 /* States.IN_SINGLE_QUOTE */ &&\n nextChar === \"'\" /* PathCharTypes.SINGLE_QUOTE */) ||\n (mode === 6 /* States.IN_DOUBLE_QUOTE */ &&\n nextChar === \"\\\"\" /* PathCharTypes.DOUBLE_QUOTE */)) {\n index++;\n newChar = '\\\\' + nextChar;\n actions[0 /* Actions.APPEND */]();\n return true;\n }\n }\n while (mode !== null) {\n index++;\n c = path[index];\n if (c === '\\\\' && maybeUnescapeQuote()) {\n continue;\n }\n type = getPathCharType(c);\n typeMap = pathStateMachine[mode];\n transition = typeMap[type] || typeMap[\"l\" /* PathCharTypes.ELSE */] || 8 /* States.ERROR */;\n // check parse error\n if (transition === 8 /* States.ERROR */) {\n return;\n }\n mode = transition[0];\n if (transition[1] !== undefined) {\n action = actions[transition[1]];\n if (action) {\n newChar = c;\n if (action() === false) {\n return;\n }\n }\n }\n // check parse finish\n if (mode === 7 /* States.AFTER_PATH */) {\n return keys;\n }\n }\n}\n// path token cache\nconst cache = new Map();\n/**\n * key-value message resolver\n *\n * @remarks\n * Resolves messages with the key-value structure. Note that messages with a hierarchical structure such as objects cannot be resolved\n *\n * @param obj - A target object to be resolved with path\n * @param path - A {@link Path | path} to resolve the value of message\n *\n * @returns A resolved {@link PathValue | path value}\n *\n * @VueI18nGeneral\n */\nfunction resolveWithKeyValue(obj, path) {\n return isObject(obj) ? obj[path] : null;\n}\n/**\n * message resolver\n *\n * @remarks\n * Resolves messages. messages with a hierarchical structure such as objects can be resolved. This resolver is used in VueI18n as default.\n *\n * @param obj - A target object to be resolved with path\n * @param path - A {@link Path | path} to resolve the value of message\n *\n * @returns A resolved {@link PathValue | path value}\n *\n * @VueI18nGeneral\n */\nfunction resolveValue(obj, path) {\n // check object\n if (!isObject(obj)) {\n return null;\n }\n // parse path\n let hit = cache.get(path);\n if (!hit) {\n hit = parse(path);\n if (hit) {\n cache.set(path, hit);\n }\n }\n // check hit\n if (!hit) {\n return null;\n }\n // resolve path value\n const len = hit.length;\n let last = obj;\n let i = 0;\n while (i < len) {\n const val = last[hit[i]];\n if (val === undefined) {\n return null;\n }\n if (isFunction(last)) {\n return null;\n }\n last = val;\n i++;\n }\n return last;\n}\n\nconst DEFAULT_MODIFIER = (str) => str;\nconst DEFAULT_MESSAGE = (ctx) => ''; // eslint-disable-line\nconst DEFAULT_MESSAGE_DATA_TYPE = 'text';\nconst DEFAULT_NORMALIZE = (values) => values.length === 0 ? '' : join(values);\nconst DEFAULT_INTERPOLATE = toDisplayString;\nfunction pluralDefault(choice, choicesLength) {\n choice = Math.abs(choice);\n if (choicesLength === 2) {\n // prettier-ignore\n return choice\n ? choice > 1\n ? 1\n : 0\n : 1;\n }\n return choice ? Math.min(choice, 2) : 0;\n}\nfunction getPluralIndex(options) {\n // prettier-ignore\n const index = isNumber(options.pluralIndex)\n ? options.pluralIndex\n : -1;\n // prettier-ignore\n return options.named && (isNumber(options.named.count) || isNumber(options.named.n))\n ? isNumber(options.named.count)\n ? options.named.count\n : isNumber(options.named.n)\n ? options.named.n\n : index\n : index;\n}\nfunction normalizeNamed(pluralIndex, props) {\n if (!props.count) {\n props.count = pluralIndex;\n }\n if (!props.n) {\n props.n = pluralIndex;\n }\n}\nfunction createMessageContext(options = {}) {\n const locale = options.locale;\n const pluralIndex = getPluralIndex(options);\n const pluralRule = isObject(options.pluralRules) &&\n isString(locale) &&\n isFunction(options.pluralRules[locale])\n ? options.pluralRules[locale]\n : pluralDefault;\n const orgPluralRule = isObject(options.pluralRules) &&\n isString(locale) &&\n isFunction(options.pluralRules[locale])\n ? pluralDefault\n : undefined;\n const plural = (messages) => {\n return messages[pluralRule(pluralIndex, messages.length, orgPluralRule)];\n };\n const _list = options.list || [];\n const list = (index) => _list[index];\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const _named = options.named || {};\n isNumber(options.pluralIndex) && normalizeNamed(pluralIndex, _named);\n const named = (key) => _named[key];\n function message(key) {\n // prettier-ignore\n const msg = isFunction(options.messages)\n ? options.messages(key)\n : isObject(options.messages)\n ? options.messages[key]\n : false;\n return !msg\n ? options.parent\n ? options.parent.message(key) // resolve from parent messages\n : DEFAULT_MESSAGE\n : msg;\n }\n const _modifier = (name) => options.modifiers\n ? options.modifiers[name]\n : DEFAULT_MODIFIER;\n const normalize = isPlainObject(options.processor) && isFunction(options.processor.normalize)\n ? options.processor.normalize\n : DEFAULT_NORMALIZE;\n const interpolate = isPlainObject(options.processor) &&\n isFunction(options.processor.interpolate)\n ? options.processor.interpolate\n : DEFAULT_INTERPOLATE;\n const type = isPlainObject(options.processor) && isString(options.processor.type)\n ? options.processor.type\n : DEFAULT_MESSAGE_DATA_TYPE;\n const linked = (key, ...args) => {\n const [arg1, arg2] = args;\n let type = 'text';\n let modifier = '';\n if (args.length === 1) {\n if (isObject(arg1)) {\n modifier = arg1.modifier || modifier;\n type = arg1.type || type;\n }\n else if (isString(arg1)) {\n modifier = arg1 || modifier;\n }\n }\n else if (args.length === 2) {\n if (isString(arg1)) {\n modifier = arg1 || modifier;\n }\n if (isString(arg2)) {\n type = arg2 || type;\n }\n }\n const ret = message(key)(ctx);\n const msg = \n // The message in vnode resolved with linked are returned as an array by processor.nomalize\n type === 'vnode' && isArray(ret) && modifier\n ? ret[0]\n : ret;\n return modifier ? _modifier(modifier)(msg, type) : msg;\n };\n const ctx = {\n [\"list\" /* HelperNameMap.LIST */]: list,\n [\"named\" /* HelperNameMap.NAMED */]: named,\n [\"plural\" /* HelperNameMap.PLURAL */]: plural,\n [\"linked\" /* HelperNameMap.LINKED */]: linked,\n [\"message\" /* HelperNameMap.MESSAGE */]: message,\n [\"type\" /* HelperNameMap.TYPE */]: type,\n [\"interpolate\" /* HelperNameMap.INTERPOLATE */]: interpolate,\n [\"normalize\" /* HelperNameMap.NORMALIZE */]: normalize,\n [\"values\" /* HelperNameMap.VALUES */]: assign({}, _list, _named)\n };\n return ctx;\n}\n\nlet devtools = null;\nfunction setDevToolsHook(hook) {\n devtools = hook;\n}\nfunction getDevToolsHook() {\n return devtools;\n}\nfunction initI18nDevTools(i18n, version, meta) {\n // TODO: queue if devtools is undefined\n devtools &&\n devtools.emit(\"i18n:init\" /* IntlifyDevToolsHooks.I18nInit */, {\n timestamp: Date.now(),\n i18n,\n version,\n meta\n });\n}\nconst translateDevTools = /* #__PURE__*/ createDevToolsHook(\"function:translate\" /* IntlifyDevToolsHooks.FunctionTranslate */);\nfunction createDevToolsHook(hook) {\n return (payloads) => devtools && devtools.emit(hook, payloads);\n}\n\nconst code$1 = CompileWarnCodes.__EXTEND_POINT__;\nconst inc$1 = incrementer(code$1);\nconst CoreWarnCodes = {\n NOT_FOUND_KEY: code$1, // 2\n FALLBACK_TO_TRANSLATE: inc$1(), // 3\n CANNOT_FORMAT_NUMBER: inc$1(), // 4\n FALLBACK_TO_NUMBER_FORMAT: inc$1(), // 5\n CANNOT_FORMAT_DATE: inc$1(), // 6\n FALLBACK_TO_DATE_FORMAT: inc$1(), // 7\n EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER: inc$1(), // 8\n __EXTEND_POINT__: inc$1() // 9\n};\n/** @internal */\nconst warnMessages = {\n [CoreWarnCodes.NOT_FOUND_KEY]: `Not found '{key}' key in '{locale}' locale messages.`,\n [CoreWarnCodes.FALLBACK_TO_TRANSLATE]: `Fall back to translate '{key}' key with '{target}' locale.`,\n [CoreWarnCodes.CANNOT_FORMAT_NUMBER]: `Cannot format a number value due to not supported Intl.NumberFormat.`,\n [CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT]: `Fall back to number format '{key}' key with '{target}' locale.`,\n [CoreWarnCodes.CANNOT_FORMAT_DATE]: `Cannot format a date value due to not supported Intl.DateTimeFormat.`,\n [CoreWarnCodes.FALLBACK_TO_DATE_FORMAT]: `Fall back to datetime format '{key}' key with '{target}' locale.`,\n [CoreWarnCodes.EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER]: `This project is using Custom Message Compiler, which is an experimental feature. It may receive breaking changes or be removed in the future.`\n};\nfunction getWarnMessage(code, ...args) {\n return format$1(warnMessages[code], ...args);\n}\n\nconst code = CompileErrorCodes.__EXTEND_POINT__;\nconst inc = incrementer(code);\nconst CoreErrorCodes = {\n INVALID_ARGUMENT: code, // 17\n INVALID_DATE_ARGUMENT: inc(), // 18\n INVALID_ISO_DATE_ARGUMENT: inc(), // 19\n NOT_SUPPORT_NON_STRING_MESSAGE: inc(), // 20\n NOT_SUPPORT_LOCALE_PROMISE_VALUE: inc(), // 21\n NOT_SUPPORT_LOCALE_ASYNC_FUNCTION: inc(), // 22\n NOT_SUPPORT_LOCALE_TYPE: inc(), // 23\n __EXTEND_POINT__: inc() // 24\n};\nfunction createCoreError(code) {\n return createCompileError(code, null, (process.env.NODE_ENV !== 'production') ? { messages: errorMessages } : undefined);\n}\n/** @internal */\nconst errorMessages = {\n [CoreErrorCodes.INVALID_ARGUMENT]: 'Invalid arguments',\n [CoreErrorCodes.INVALID_DATE_ARGUMENT]: 'The date provided is an invalid Date object.' +\n 'Make sure your Date represents a valid date.',\n [CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT]: 'The argument provided is not a valid ISO date string',\n [CoreErrorCodes.NOT_SUPPORT_NON_STRING_MESSAGE]: 'Not support non-string message',\n [CoreErrorCodes.NOT_SUPPORT_LOCALE_PROMISE_VALUE]: 'cannot support promise value',\n [CoreErrorCodes.NOT_SUPPORT_LOCALE_ASYNC_FUNCTION]: 'cannot support async function',\n [CoreErrorCodes.NOT_SUPPORT_LOCALE_TYPE]: 'cannot support locale type'\n};\n\n/** @internal */\nfunction getLocale(context, options) {\n return options.locale != null\n ? resolveLocale(options.locale)\n : resolveLocale(context.locale);\n}\nlet _resolveLocale;\n/** @internal */\nfunction resolveLocale(locale) {\n if (isString(locale)) {\n return locale;\n }\n else {\n if (isFunction(locale)) {\n if (locale.resolvedOnce && _resolveLocale != null) {\n return _resolveLocale;\n }\n else if (locale.constructor.name === 'Function') {\n const resolve = locale();\n if (isPromise(resolve)) {\n throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_PROMISE_VALUE);\n }\n return (_resolveLocale = resolve);\n }\n else {\n throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_ASYNC_FUNCTION);\n }\n }\n else {\n throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_TYPE);\n }\n }\n}\n/**\n * Fallback with simple implemenation\n *\n * @remarks\n * A fallback locale function implemented with a simple fallback algorithm.\n *\n * Basically, it returns the value as specified in the `fallbackLocale` props, and is processed with the fallback inside intlify.\n *\n * @param ctx - A {@link CoreContext | context}\n * @param fallback - A {@link FallbackLocale | fallback locale}\n * @param start - A starting {@link Locale | locale}\n *\n * @returns Fallback locales\n *\n * @VueI18nGeneral\n */\nfunction fallbackWithSimple(ctx, fallback, start // eslint-disable-line @typescript-eslint/no-unused-vars\n) {\n // prettier-ignore\n return [...new Set([\n start,\n ...(isArray(fallback)\n ? fallback\n : isObject(fallback)\n ? Object.keys(fallback)\n : isString(fallback)\n ? [fallback]\n : [start])\n ])];\n}\n/**\n * Fallback with locale chain\n *\n * @remarks\n * A fallback locale function implemented with a fallback chain algorithm. It's used in VueI18n as default.\n *\n * @param ctx - A {@link CoreContext | context}\n * @param fallback - A {@link FallbackLocale | fallback locale}\n * @param start - A starting {@link Locale | locale}\n *\n * @returns Fallback locales\n *\n * @VueI18nSee [Fallbacking](../guide/essentials/fallback)\n *\n * @VueI18nGeneral\n */\nfunction fallbackWithLocaleChain(ctx, fallback, start) {\n const startLocale = isString(start) ? start : DEFAULT_LOCALE;\n const context = ctx;\n if (!context.__localeChainCache) {\n context.__localeChainCache = new Map();\n }\n let chain = context.__localeChainCache.get(startLocale);\n if (!chain) {\n chain = [];\n // first block defined by start\n let block = [start];\n // while any intervening block found\n while (isArray(block)) {\n block = appendBlockToChain(chain, block, fallback);\n }\n // prettier-ignore\n // last block defined by default\n const defaults = isArray(fallback) || !isPlainObject(fallback)\n ? fallback\n : fallback['default']\n ? fallback['default']\n : null;\n // convert defaults to array\n block = isString(defaults) ? [defaults] : defaults;\n if (isArray(block)) {\n appendBlockToChain(chain, block, false);\n }\n context.__localeChainCache.set(startLocale, chain);\n }\n return chain;\n}\nfunction appendBlockToChain(chain, block, blocks) {\n let follow = true;\n for (let i = 0; i < block.length && isBoolean(follow); i++) {\n const locale = block[i];\n if (isString(locale)) {\n follow = appendLocaleToChain(chain, block[i], blocks);\n }\n }\n return follow;\n}\nfunction appendLocaleToChain(chain, locale, blocks) {\n let follow;\n const tokens = locale.split('-');\n do {\n const target = tokens.join('-');\n follow = appendItemToChain(chain, target, blocks);\n tokens.splice(-1, 1);\n } while (tokens.length && follow === true);\n return follow;\n}\nfunction appendItemToChain(chain, target, blocks) {\n let follow = false;\n if (!chain.includes(target)) {\n follow = true;\n if (target) {\n follow = target[target.length - 1] !== '!';\n const locale = target.replace(/!/g, '');\n chain.push(locale);\n if ((isArray(blocks) || isPlainObject(blocks)) &&\n blocks[locale] // eslint-disable-line @typescript-eslint/no-explicit-any\n ) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n follow = blocks[locale];\n }\n }\n }\n return follow;\n}\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/**\n * Intlify core-base version\n * @internal\n */\nconst VERSION = '9.13.1';\nconst NOT_REOSLVED = -1;\nconst DEFAULT_LOCALE = 'en-US';\nconst MISSING_RESOLVE_VALUE = '';\nconst capitalize = (str) => `${str.charAt(0).toLocaleUpperCase()}${str.substr(1)}`;\nfunction getDefaultLinkedModifiers() {\n return {\n upper: (val, type) => {\n // prettier-ignore\n return type === 'text' && isString(val)\n ? val.toUpperCase()\n : type === 'vnode' && isObject(val) && '__v_isVNode' in val\n ? val.children.toUpperCase()\n : val;\n },\n lower: (val, type) => {\n // prettier-ignore\n return type === 'text' && isString(val)\n ? val.toLowerCase()\n : type === 'vnode' && isObject(val) && '__v_isVNode' in val\n ? val.children.toLowerCase()\n : val;\n },\n capitalize: (val, type) => {\n // prettier-ignore\n return (type === 'text' && isString(val)\n ? capitalize(val)\n : type === 'vnode' && isObject(val) && '__v_isVNode' in val\n ? capitalize(val.children)\n : val);\n }\n };\n}\nlet _compiler;\nfunction registerMessageCompiler(compiler) {\n _compiler = compiler;\n}\nlet _resolver;\n/**\n * Register the message resolver\n *\n * @param resolver - A {@link MessageResolver} function\n *\n * @VueI18nGeneral\n */\nfunction registerMessageResolver(resolver) {\n _resolver = resolver;\n}\nlet _fallbacker;\n/**\n * Register the locale fallbacker\n *\n * @param fallbacker - A {@link LocaleFallbacker} function\n *\n * @VueI18nGeneral\n */\nfunction registerLocaleFallbacker(fallbacker) {\n _fallbacker = fallbacker;\n}\n// Additional Meta for Intlify DevTools\nlet _additionalMeta = null;\n/* #__NO_SIDE_EFFECTS__ */\nconst setAdditionalMeta = (meta) => {\n _additionalMeta = meta;\n};\n/* #__NO_SIDE_EFFECTS__ */\nconst getAdditionalMeta = () => _additionalMeta;\nlet _fallbackContext = null;\nconst setFallbackContext = (context) => {\n _fallbackContext = context;\n};\nconst getFallbackContext = () => _fallbackContext;\n// ID for CoreContext\nlet _cid = 0;\nfunction createCoreContext(options = {}) {\n // setup options\n const onWarn = isFunction(options.onWarn) ? options.onWarn : warn;\n const version = isString(options.version) ? options.version : VERSION;\n const locale = isString(options.locale) || isFunction(options.locale)\n ? options.locale\n : DEFAULT_LOCALE;\n const _locale = isFunction(locale) ? DEFAULT_LOCALE : locale;\n const fallbackLocale = isArray(options.fallbackLocale) ||\n isPlainObject(options.fallbackLocale) ||\n isString(options.fallbackLocale) ||\n options.fallbackLocale === false\n ? options.fallbackLocale\n : _locale;\n const messages = isPlainObject(options.messages)\n ? options.messages\n : { [_locale]: {} };\n const datetimeFormats = isPlainObject(options.datetimeFormats)\n ? options.datetimeFormats\n : { [_locale]: {} }\n ;\n const numberFormats = isPlainObject(options.numberFormats)\n ? options.numberFormats\n : { [_locale]: {} }\n ;\n const modifiers = assign({}, options.modifiers || {}, getDefaultLinkedModifiers());\n const pluralRules = options.pluralRules || {};\n const missing = isFunction(options.missing) ? options.missing : null;\n const missingWarn = isBoolean(options.missingWarn) || isRegExp(options.missingWarn)\n ? options.missingWarn\n : true;\n const fallbackWarn = isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)\n ? options.fallbackWarn\n : true;\n const fallbackFormat = !!options.fallbackFormat;\n const unresolving = !!options.unresolving;\n const postTranslation = isFunction(options.postTranslation)\n ? options.postTranslation\n : null;\n const processor = isPlainObject(options.processor) ? options.processor : null;\n const warnHtmlMessage = isBoolean(options.warnHtmlMessage)\n ? options.warnHtmlMessage\n : true;\n const escapeParameter = !!options.escapeParameter;\n const messageCompiler = isFunction(options.messageCompiler)\n ? options.messageCompiler\n : _compiler;\n if ((process.env.NODE_ENV !== 'production') &&\n !false &&\n !false &&\n isFunction(options.messageCompiler)) {\n warnOnce(getWarnMessage(CoreWarnCodes.EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER));\n }\n const messageResolver = isFunction(options.messageResolver)\n ? options.messageResolver\n : _resolver || resolveWithKeyValue;\n const localeFallbacker = isFunction(options.localeFallbacker)\n ? options.localeFallbacker\n : _fallbacker || fallbackWithSimple;\n const fallbackContext = isObject(options.fallbackContext)\n ? options.fallbackContext\n : undefined;\n // setup internal options\n const internalOptions = options;\n const __datetimeFormatters = isObject(internalOptions.__datetimeFormatters)\n ? internalOptions.__datetimeFormatters\n : new Map()\n ;\n const __numberFormatters = isObject(internalOptions.__numberFormatters)\n ? internalOptions.__numberFormatters\n : new Map()\n ;\n const __meta = isObject(internalOptions.__meta) ? internalOptions.__meta : {};\n _cid++;\n const context = {\n version,\n cid: _cid,\n locale,\n fallbackLocale,\n messages,\n modifiers,\n pluralRules,\n missing,\n missingWarn,\n fallbackWarn,\n fallbackFormat,\n unresolving,\n postTranslation,\n processor,\n warnHtmlMessage,\n escapeParameter,\n messageCompiler,\n messageResolver,\n localeFallbacker,\n fallbackContext,\n onWarn,\n __meta\n };\n {\n context.datetimeFormats = datetimeFormats;\n context.numberFormats = numberFormats;\n context.__datetimeFormatters = __datetimeFormatters;\n context.__numberFormatters = __numberFormatters;\n }\n // for vue-devtools timeline event\n if ((process.env.NODE_ENV !== 'production')) {\n context.__v_emitter =\n internalOptions.__v_emitter != null\n ? internalOptions.__v_emitter\n : undefined;\n }\n // NOTE: experimental !!\n if ((process.env.NODE_ENV !== 'production') || __INTLIFY_PROD_DEVTOOLS__) {\n initI18nDevTools(context, version, __meta);\n }\n return context;\n}\n/** @internal */\nfunction isTranslateFallbackWarn(fallback, key) {\n return fallback instanceof RegExp ? fallback.test(key) : fallback;\n}\n/** @internal */\nfunction isTranslateMissingWarn(missing, key) {\n return missing instanceof RegExp ? missing.test(key) : missing;\n}\n/** @internal */\nfunction handleMissing(context, key, locale, missingWarn, type) {\n const { missing, onWarn } = context;\n // for vue-devtools timeline event\n if ((process.env.NODE_ENV !== 'production')) {\n const emitter = context.__v_emitter;\n if (emitter) {\n emitter.emit(\"missing\" /* VueDevToolsTimelineEvents.MISSING */, {\n locale,\n key,\n type,\n groupId: `${type}:${key}`\n });\n }\n }\n if (missing !== null) {\n const ret = missing(context, locale, key, type);\n return isString(ret) ? ret : key;\n }\n else {\n if ((process.env.NODE_ENV !== 'production') && isTranslateMissingWarn(missingWarn, key)) {\n onWarn(getWarnMessage(CoreWarnCodes.NOT_FOUND_KEY, { key, locale }));\n }\n return key;\n }\n}\n/** @internal */\nfunction updateFallbackLocale(ctx, locale, fallback) {\n const context = ctx;\n context.__localeChainCache = new Map();\n ctx.localeFallbacker(ctx, fallback, locale);\n}\n/** @internal */\nfunction isAlmostSameLocale(locale, compareLocale) {\n if (locale === compareLocale)\n return false;\n return locale.split('-')[0] === compareLocale.split('-')[0];\n}\n/** @internal */\nfunction isImplicitFallback(targetLocale, locales) {\n const index = locales.indexOf(targetLocale);\n if (index === -1) {\n return false;\n }\n for (let i = index + 1; i < locales.length; i++) {\n if (isAlmostSameLocale(targetLocale, locales[i])) {\n return true;\n }\n }\n return false;\n}\n/* eslint-enable @typescript-eslint/no-explicit-any */\n\nfunction format(ast) {\n const msg = (ctx) => formatParts(ctx, ast);\n return msg;\n}\nfunction formatParts(ctx, ast) {\n const body = ast.b || ast.body;\n if ((body.t || body.type) === 1 /* NodeTypes.Plural */) {\n const plural = body;\n const cases = plural.c || plural.cases;\n return ctx.plural(cases.reduce((messages, c) => [\n ...messages,\n formatMessageParts(ctx, c)\n ], []));\n }\n else {\n return formatMessageParts(ctx, body);\n }\n}\nfunction formatMessageParts(ctx, node) {\n const _static = node.s || node.static;\n if (_static) {\n return ctx.type === 'text'\n ? _static\n : ctx.normalize([_static]);\n }\n else {\n const messages = (node.i || node.items).reduce((acm, c) => [...acm, formatMessagePart(ctx, c)], []);\n return ctx.normalize(messages);\n }\n}\nfunction formatMessagePart(ctx, node) {\n const type = node.t || node.type;\n switch (type) {\n case 3 /* NodeTypes.Text */: {\n const text = node;\n return (text.v || text.value);\n }\n case 9 /* NodeTypes.Literal */: {\n const literal = node;\n return (literal.v || literal.value);\n }\n case 4 /* NodeTypes.Named */: {\n const named = node;\n return ctx.interpolate(ctx.named(named.k || named.key));\n }\n case 5 /* NodeTypes.List */: {\n const list = node;\n return ctx.interpolate(ctx.list(list.i != null ? list.i : list.index));\n }\n case 6 /* NodeTypes.Linked */: {\n const linked = node;\n const modifier = linked.m || linked.modifier;\n return ctx.linked(formatMessagePart(ctx, linked.k || linked.key), modifier ? formatMessagePart(ctx, modifier) : undefined, ctx.type);\n }\n case 7 /* NodeTypes.LinkedKey */: {\n const linkedKey = node;\n return (linkedKey.v || linkedKey.value);\n }\n case 8 /* NodeTypes.LinkedModifier */: {\n const linkedModifier = node;\n return (linkedModifier.v || linkedModifier.value);\n }\n default:\n throw new Error(`unhandled node type on format message part: ${type}`);\n }\n}\n\nconst WARN_MESSAGE = `Detected HTML in '{source}' message. Recommend not using HTML messages to avoid XSS.`;\nfunction checkHtmlMessage(source, warnHtmlMessage) {\n if (warnHtmlMessage && detectHtmlTag(source)) {\n warn(format$1(WARN_MESSAGE, { source }));\n }\n}\nconst defaultOnCacheKey = (message) => message;\nlet compileCache = Object.create(null);\nfunction onCompileWarn(_warn) {\n if (_warn.code === CompileWarnCodes.USE_MODULO_SYNTAX) {\n warn(`The use of named interpolation with modulo syntax is deprecated. ` +\n `It will be removed in v10.\\n` +\n `reference: https://vue-i18n.intlify.dev/guide/essentials/syntax#rails-i18n-format \\n` +\n `(message compiler warning message: ${_warn.message})`);\n }\n}\nfunction clearCompileCache() {\n compileCache = Object.create(null);\n}\nconst isMessageAST = (val) => isObject(val) &&\n (val.t === 0 || val.type === 0) &&\n ('b' in val || 'body' in val);\nfunction baseCompile(message, options = {}) {\n // error detecting on compile\n let detectError = false;\n const onError = options.onError || defaultOnError;\n options.onError = (err) => {\n detectError = true;\n onError(err);\n };\n // compile with mesasge-compiler\n return { ...baseCompile$1(message, options), detectError };\n}\n/* #__NO_SIDE_EFFECTS__ */\nconst compileToFunction = (message, context) => {\n if (!isString(message)) {\n throw createCoreError(CoreErrorCodes.NOT_SUPPORT_NON_STRING_MESSAGE);\n }\n // set onWarn\n if ((process.env.NODE_ENV !== 'production')) {\n context.onWarn = onCompileWarn;\n }\n {\n // check HTML message\n const warnHtmlMessage = isBoolean(context.warnHtmlMessage)\n ? context.warnHtmlMessage\n : true;\n (process.env.NODE_ENV !== 'production') && checkHtmlMessage(message, warnHtmlMessage);\n // check caches\n const onCacheKey = context.onCacheKey || defaultOnCacheKey;\n const cacheKey = onCacheKey(message);\n const cached = compileCache[cacheKey];\n if (cached) {\n return cached;\n }\n // compile\n const { code, detectError } = baseCompile(message, context);\n // evaluate function\n const msg = new Function(`return ${code}`)();\n // if occurred compile error, don't cache\n return !detectError\n ? (compileCache[cacheKey] = msg)\n : msg;\n }\n};\nfunction compile(message, context) {\n // set onWarn\n if ((process.env.NODE_ENV !== 'production')) {\n context.onWarn = onCompileWarn;\n }\n if (((__INTLIFY_JIT_COMPILATION__ && !__INTLIFY_DROP_MESSAGE_COMPILER__)) &&\n isString(message)) {\n // check HTML message\n const warnHtmlMessage = isBoolean(context.warnHtmlMessage)\n ? context.warnHtmlMessage\n : true;\n (process.env.NODE_ENV !== 'production') && checkHtmlMessage(message, warnHtmlMessage);\n // check caches\n const onCacheKey = context.onCacheKey || defaultOnCacheKey;\n const cacheKey = onCacheKey(message);\n const cached = compileCache[cacheKey];\n if (cached) {\n return cached;\n }\n // compile with JIT mode\n const { ast, detectError } = baseCompile(message, {\n ...context,\n location: (process.env.NODE_ENV !== 'production'),\n jit: true\n });\n // compose message function from AST\n const msg = format(ast);\n // if occurred compile error, don't cache\n return !detectError\n ? (compileCache[cacheKey] = msg)\n : msg;\n }\n else {\n if ((process.env.NODE_ENV !== 'production') && !isMessageAST(message)) {\n warn(`the message that is resolve with key '${context.key}' is not supported for jit compilation`);\n return (() => message);\n }\n // AST case (passed from bundler)\n const cacheKey = message.cacheKey;\n if (cacheKey) {\n const cached = compileCache[cacheKey];\n if (cached) {\n return cached;\n }\n // compose message function from message (AST)\n return (compileCache[cacheKey] =\n format(message));\n }\n else {\n return format(message);\n }\n }\n}\n\nconst NOOP_MESSAGE_FUNCTION = () => '';\nconst isMessageFunction = (val) => isFunction(val);\n// implementation of `translate` function\nfunction translate(context, ...args) {\n const { fallbackFormat, postTranslation, unresolving, messageCompiler, fallbackLocale, messages } = context;\n const [key, options] = parseTranslateArgs(...args);\n const missingWarn = isBoolean(options.missingWarn)\n ? options.missingWarn\n : context.missingWarn;\n const fallbackWarn = isBoolean(options.fallbackWarn)\n ? options.fallbackWarn\n : context.fallbackWarn;\n const escapeParameter = isBoolean(options.escapeParameter)\n ? options.escapeParameter\n : context.escapeParameter;\n const resolvedMessage = !!options.resolvedMessage;\n // prettier-ignore\n const defaultMsgOrKey = isString(options.default) || isBoolean(options.default) // default by function option\n ? !isBoolean(options.default)\n ? options.default\n : (!messageCompiler ? () => key : key)\n : fallbackFormat // default by `fallbackFormat` option\n ? (!messageCompiler ? () => key : key)\n : '';\n const enableDefaultMsg = fallbackFormat || defaultMsgOrKey !== '';\n const locale = getLocale(context, options);\n // escape params\n escapeParameter && escapeParams(options);\n // resolve message format\n // eslint-disable-next-line prefer-const\n let [formatScope, targetLocale, message] = !resolvedMessage\n ? resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn)\n : [\n key,\n locale,\n messages[locale] || {}\n ];\n // NOTE:\n // Fix to work around `ssrTransfrom` bug in Vite.\n // https://github.com/vitejs/vite/issues/4306\n // To get around this, use temporary variables.\n // https://github.com/nuxt/framework/issues/1461#issuecomment-954606243\n let format = formatScope;\n // if you use default message, set it as message format!\n let cacheBaseKey = key;\n if (!resolvedMessage &&\n !(isString(format) ||\n isMessageAST(format) ||\n isMessageFunction(format))) {\n if (enableDefaultMsg) {\n format = defaultMsgOrKey;\n cacheBaseKey = format;\n }\n }\n // checking message format and target locale\n if (!resolvedMessage &&\n (!(isString(format) ||\n isMessageAST(format) ||\n isMessageFunction(format)) ||\n !isString(targetLocale))) {\n return unresolving ? NOT_REOSLVED : key;\n }\n // TODO: refactor\n if ((process.env.NODE_ENV !== 'production') && isString(format) && context.messageCompiler == null) {\n warn(`The message format compilation is not supported in this build. ` +\n `Because message compiler isn't included. ` +\n `You need to pre-compilation all message format. ` +\n `So translate function return '${key}'.`);\n return key;\n }\n // setup compile error detecting\n let occurred = false;\n const onError = () => {\n occurred = true;\n };\n // compile message format\n const msg = !isMessageFunction(format)\n ? compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, onError)\n : format;\n // if occurred compile error, return the message format\n if (occurred) {\n return format;\n }\n // evaluate message with context\n const ctxOptions = getMessageContextOptions(context, targetLocale, message, options);\n const msgContext = createMessageContext(ctxOptions);\n const messaged = evaluateMessage(context, msg, msgContext);\n // if use post translation option, proceed it with handler\n const ret = postTranslation\n ? postTranslation(messaged, key)\n : messaged;\n // NOTE: experimental !!\n if ((process.env.NODE_ENV !== 'production') || __INTLIFY_PROD_DEVTOOLS__) {\n // prettier-ignore\n const payloads = {\n timestamp: Date.now(),\n key: isString(key)\n ? key\n : isMessageFunction(format)\n ? format.key\n : '',\n locale: targetLocale || (isMessageFunction(format)\n ? format.locale\n : ''),\n format: isString(format)\n ? format\n : isMessageFunction(format)\n ? format.source\n : '',\n message: ret\n };\n payloads.meta = assign({}, context.__meta, getAdditionalMeta() || {});\n translateDevTools(payloads);\n }\n return ret;\n}\nfunction escapeParams(options) {\n if (isArray(options.list)) {\n options.list = options.list.map(item => isString(item) ? escapeHtml(item) : item);\n }\n else if (isObject(options.named)) {\n Object.keys(options.named).forEach(key => {\n if (isString(options.named[key])) {\n options.named[key] = escapeHtml(options.named[key]);\n }\n });\n }\n}\nfunction resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn) {\n const { messages, onWarn, messageResolver: resolveValue, localeFallbacker } = context;\n const locales = localeFallbacker(context, fallbackLocale, locale); // eslint-disable-line @typescript-eslint/no-explicit-any\n let message = {};\n let targetLocale;\n let format = null;\n let from = locale;\n let to = null;\n const type = 'translate';\n for (let i = 0; i < locales.length; i++) {\n targetLocale = to = locales[i];\n if ((process.env.NODE_ENV !== 'production') &&\n locale !== targetLocale &&\n !isAlmostSameLocale(locale, targetLocale) &&\n isTranslateFallbackWarn(fallbackWarn, key)) {\n onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_TRANSLATE, {\n key,\n target: targetLocale\n }));\n }\n // for vue-devtools timeline event\n if ((process.env.NODE_ENV !== 'production') && locale !== targetLocale) {\n const emitter = context.__v_emitter;\n if (emitter) {\n emitter.emit(\"fallback\" /* VueDevToolsTimelineEvents.FALBACK */, {\n type,\n key,\n from,\n to,\n groupId: `${type}:${key}`\n });\n }\n }\n message =\n messages[targetLocale] || {};\n // for vue-devtools timeline event\n let start = null;\n let startTag;\n let endTag;\n if ((process.env.NODE_ENV !== 'production') && inBrowser) {\n start = window.performance.now();\n startTag = 'intlify-message-resolve-start';\n endTag = 'intlify-message-resolve-end';\n mark && mark(startTag);\n }\n if ((format = resolveValue(message, key)) === null) {\n // if null, resolve with object key path\n format = message[key]; // eslint-disable-line @typescript-eslint/no-explicit-any\n }\n // for vue-devtools timeline event\n if ((process.env.NODE_ENV !== 'production') && inBrowser) {\n const end = window.performance.now();\n const emitter = context.__v_emitter;\n if (emitter && start && format) {\n emitter.emit(\"message-resolve\" /* VueDevToolsTimelineEvents.MESSAGE_RESOLVE */, {\n type: \"message-resolve\" /* VueDevToolsTimelineEvents.MESSAGE_RESOLVE */,\n key,\n message: format,\n time: end - start,\n groupId: `${type}:${key}`\n });\n }\n if (startTag && endTag && mark && measure) {\n mark(endTag);\n measure('intlify message resolve', startTag, endTag);\n }\n }\n if (isString(format) || isMessageAST(format) || isMessageFunction(format)) {\n break;\n }\n if (!isImplicitFallback(targetLocale, locales)) {\n const missingRet = handleMissing(context, // eslint-disable-line @typescript-eslint/no-explicit-any\n key, targetLocale, missingWarn, type);\n if (missingRet !== key) {\n format = missingRet;\n }\n }\n from = to;\n }\n return [format, targetLocale, message];\n}\nfunction compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, onError) {\n const { messageCompiler, warnHtmlMessage } = context;\n if (isMessageFunction(format)) {\n const msg = format;\n msg.locale = msg.locale || targetLocale;\n msg.key = msg.key || key;\n return msg;\n }\n if (messageCompiler == null) {\n const msg = (() => format);\n msg.locale = targetLocale;\n msg.key = key;\n return msg;\n }\n // for vue-devtools timeline event\n let start = null;\n let startTag;\n let endTag;\n if ((process.env.NODE_ENV !== 'production') && inBrowser) {\n start = window.performance.now();\n startTag = 'intlify-message-compilation-start';\n endTag = 'intlify-message-compilation-end';\n mark && mark(startTag);\n }\n const msg = messageCompiler(format, getCompileContext(context, targetLocale, cacheBaseKey, format, warnHtmlMessage, onError));\n // for vue-devtools timeline event\n if ((process.env.NODE_ENV !== 'production') && inBrowser) {\n const end = window.performance.now();\n const emitter = context.__v_emitter;\n if (emitter && start) {\n emitter.emit(\"message-compilation\" /* VueDevToolsTimelineEvents.MESSAGE_COMPILATION */, {\n type: \"message-compilation\" /* VueDevToolsTimelineEvents.MESSAGE_COMPILATION */,\n message: format,\n time: end - start,\n groupId: `${'translate'}:${key}`\n });\n }\n if (startTag && endTag && mark && measure) {\n mark(endTag);\n measure('intlify message compilation', startTag, endTag);\n }\n }\n msg.locale = targetLocale;\n msg.key = key;\n msg.source = format;\n return msg;\n}\nfunction evaluateMessage(context, msg, msgCtx) {\n // for vue-devtools timeline event\n let start = null;\n let startTag;\n let endTag;\n if ((process.env.NODE_ENV !== 'production') && inBrowser) {\n start = window.performance.now();\n startTag = 'intlify-message-evaluation-start';\n endTag = 'intlify-message-evaluation-end';\n mark && mark(startTag);\n }\n const messaged = msg(msgCtx);\n // for vue-devtools timeline event\n if ((process.env.NODE_ENV !== 'production') && inBrowser) {\n const end = window.performance.now();\n const emitter = context.__v_emitter;\n if (emitter && start) {\n emitter.emit(\"message-evaluation\" /* VueDevToolsTimelineEvents.MESSAGE_EVALUATION */, {\n type: \"message-evaluation\" /* VueDevToolsTimelineEvents.MESSAGE_EVALUATION */,\n value: messaged,\n time: end - start,\n groupId: `${'translate'}:${msg.key}`\n });\n }\n if (startTag && endTag && mark && measure) {\n mark(endTag);\n measure('intlify message evaluation', startTag, endTag);\n }\n }\n return messaged;\n}\n/** @internal */\nfunction parseTranslateArgs(...args) {\n const [arg1, arg2, arg3] = args;\n const options = {};\n if (!isString(arg1) &&\n !isNumber(arg1) &&\n !isMessageFunction(arg1) &&\n !isMessageAST(arg1)) {\n throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);\n }\n // prettier-ignore\n const key = isNumber(arg1)\n ? String(arg1)\n : isMessageFunction(arg1)\n ? arg1\n : arg1;\n if (isNumber(arg2)) {\n options.plural = arg2;\n }\n else if (isString(arg2)) {\n options.default = arg2;\n }\n else if (isPlainObject(arg2) && !isEmptyObject(arg2)) {\n options.named = arg2;\n }\n else if (isArray(arg2)) {\n options.list = arg2;\n }\n if (isNumber(arg3)) {\n options.plural = arg3;\n }\n else if (isString(arg3)) {\n options.default = arg3;\n }\n else if (isPlainObject(arg3)) {\n assign(options, arg3);\n }\n return [key, options];\n}\nfunction getCompileContext(context, locale, key, source, warnHtmlMessage, onError) {\n return {\n locale,\n key,\n warnHtmlMessage,\n onError: (err) => {\n onError && onError(err);\n if ((process.env.NODE_ENV !== 'production')) {\n const _source = getSourceForCodeFrame(source);\n const message = `Message compilation error: ${err.message}`;\n const codeFrame = err.location &&\n _source &&\n generateCodeFrame(_source, err.location.start.offset, err.location.end.offset);\n const emitter = context.__v_emitter;\n if (emitter && _source) {\n emitter.emit(\"compile-error\" /* VueDevToolsTimelineEvents.COMPILE_ERROR */, {\n message: _source,\n error: err.message,\n start: err.location && err.location.start.offset,\n end: err.location && err.location.end.offset,\n groupId: `${'translate'}:${key}`\n });\n }\n console.error(codeFrame ? `${message}\\n${codeFrame}` : message);\n }\n else {\n throw err;\n }\n },\n onCacheKey: (source) => generateFormatCacheKey(locale, key, source)\n };\n}\nfunction getSourceForCodeFrame(source) {\n if (isString(source)) {\n return source;\n }\n else {\n if (source.loc && source.loc.source) {\n return source.loc.source;\n }\n }\n}\nfunction getMessageContextOptions(context, locale, message, options) {\n const { modifiers, pluralRules, messageResolver: resolveValue, fallbackLocale, fallbackWarn, missingWarn, fallbackContext } = context;\n const resolveMessage = (key) => {\n let val = resolveValue(message, key);\n // fallback to root context\n if (val == null && fallbackContext) {\n const [, , message] = resolveMessageFormat(fallbackContext, key, locale, fallbackLocale, fallbackWarn, missingWarn);\n val = resolveValue(message, key);\n }\n if (isString(val) || isMessageAST(val)) {\n let occurred = false;\n const onError = () => {\n occurred = true;\n };\n const msg = compileMessageFormat(context, key, locale, val, key, onError);\n return !occurred\n ? msg\n : NOOP_MESSAGE_FUNCTION;\n }\n else if (isMessageFunction(val)) {\n return val;\n }\n else {\n // TODO: should be implemented warning message\n return NOOP_MESSAGE_FUNCTION;\n }\n };\n const ctxOptions = {\n locale,\n modifiers,\n pluralRules,\n messages: resolveMessage\n };\n if (context.processor) {\n ctxOptions.processor = context.processor;\n }\n if (options.list) {\n ctxOptions.list = options.list;\n }\n if (options.named) {\n ctxOptions.named = options.named;\n }\n if (isNumber(options.plural)) {\n ctxOptions.pluralIndex = options.plural;\n }\n return ctxOptions;\n}\n\nconst intlDefined = typeof Intl !== 'undefined';\nconst Availabilities = {\n dateTimeFormat: intlDefined && typeof Intl.DateTimeFormat !== 'undefined',\n numberFormat: intlDefined && typeof Intl.NumberFormat !== 'undefined'\n};\n\n// implementation of `datetime` function\nfunction datetime(context, ...args) {\n const { datetimeFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;\n const { __datetimeFormatters } = context;\n if ((process.env.NODE_ENV !== 'production') && !Availabilities.dateTimeFormat) {\n onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_DATE));\n return MISSING_RESOLVE_VALUE;\n }\n const [key, value, options, overrides] = parseDateTimeArgs(...args);\n const missingWarn = isBoolean(options.missingWarn)\n ? options.missingWarn\n : context.missingWarn;\n const fallbackWarn = isBoolean(options.fallbackWarn)\n ? options.fallbackWarn\n : context.fallbackWarn;\n const part = !!options.part;\n const locale = getLocale(context, options);\n const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any\n fallbackLocale, locale);\n if (!isString(key) || key === '') {\n return new Intl.DateTimeFormat(locale, overrides).format(value);\n }\n // resolve format\n let datetimeFormat = {};\n let targetLocale;\n let format = null;\n let from = locale;\n let to = null;\n const type = 'datetime format';\n for (let i = 0; i < locales.length; i++) {\n targetLocale = to = locales[i];\n if ((process.env.NODE_ENV !== 'production') &&\n locale !== targetLocale &&\n isTranslateFallbackWarn(fallbackWarn, key)) {\n onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_DATE_FORMAT, {\n key,\n target: targetLocale\n }));\n }\n // for vue-devtools timeline event\n if ((process.env.NODE_ENV !== 'production') && locale !== targetLocale) {\n const emitter = context.__v_emitter;\n if (emitter) {\n emitter.emit(\"fallback\" /* VueDevToolsTimelineEvents.FALBACK */, {\n type,\n key,\n from,\n to,\n groupId: `${type}:${key}`\n });\n }\n }\n datetimeFormat =\n datetimeFormats[targetLocale] || {};\n format = datetimeFormat[key];\n if (isPlainObject(format))\n break;\n handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any\n from = to;\n }\n // checking format and target locale\n if (!isPlainObject(format) || !isString(targetLocale)) {\n return unresolving ? NOT_REOSLVED : key;\n }\n let id = `${targetLocale}__${key}`;\n if (!isEmptyObject(overrides)) {\n id = `${id}__${JSON.stringify(overrides)}`;\n }\n let formatter = __datetimeFormatters.get(id);\n if (!formatter) {\n formatter = new Intl.DateTimeFormat(targetLocale, assign({}, format, overrides));\n __datetimeFormatters.set(id, formatter);\n }\n return !part ? formatter.format(value) : formatter.formatToParts(value);\n}\n/** @internal */\nconst DATETIME_FORMAT_OPTIONS_KEYS = [\n 'localeMatcher',\n 'weekday',\n 'era',\n 'year',\n 'month',\n 'day',\n 'hour',\n 'minute',\n 'second',\n 'timeZoneName',\n 'formatMatcher',\n 'hour12',\n 'timeZone',\n 'dateStyle',\n 'timeStyle',\n 'calendar',\n 'dayPeriod',\n 'numberingSystem',\n 'hourCycle',\n 'fractionalSecondDigits'\n];\n/** @internal */\nfunction parseDateTimeArgs(...args) {\n const [arg1, arg2, arg3, arg4] = args;\n const options = {};\n let overrides = {};\n let value;\n if (isString(arg1)) {\n // Only allow ISO strings - other date formats are often supported,\n // but may cause different results in different browsers.\n const matches = arg1.match(/(\\d{4}-\\d{2}-\\d{2})(T|\\s)?(.*)/);\n if (!matches) {\n throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);\n }\n // Some browsers can not parse the iso datetime separated by space,\n // this is a compromise solution by replace the 'T'/' ' with 'T'\n const dateTime = matches[3]\n ? matches[3].trim().startsWith('T')\n ? `${matches[1].trim()}${matches[3].trim()}`\n : `${matches[1].trim()}T${matches[3].trim()}`\n : matches[1].trim();\n value = new Date(dateTime);\n try {\n // This will fail if the date is not valid\n value.toISOString();\n }\n catch (e) {\n throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);\n }\n }\n else if (isDate(arg1)) {\n if (isNaN(arg1.getTime())) {\n throw createCoreError(CoreErrorCodes.INVALID_DATE_ARGUMENT);\n }\n value = arg1;\n }\n else if (isNumber(arg1)) {\n value = arg1;\n }\n else {\n throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);\n }\n if (isString(arg2)) {\n options.key = arg2;\n }\n else if (isPlainObject(arg2)) {\n Object.keys(arg2).forEach(key => {\n if (DATETIME_FORMAT_OPTIONS_KEYS.includes(key)) {\n overrides[key] = arg2[key];\n }\n else {\n options[key] = arg2[key];\n }\n });\n }\n if (isString(arg3)) {\n options.locale = arg3;\n }\n else if (isPlainObject(arg3)) {\n overrides = arg3;\n }\n if (isPlainObject(arg4)) {\n overrides = arg4;\n }\n return [options.key || '', value, options, overrides];\n}\n/** @internal */\nfunction clearDateTimeFormat(ctx, locale, format) {\n const context = ctx;\n for (const key in format) {\n const id = `${locale}__${key}`;\n if (!context.__datetimeFormatters.has(id)) {\n continue;\n }\n context.__datetimeFormatters.delete(id);\n }\n}\n\n// implementation of `number` function\nfunction number(context, ...args) {\n const { numberFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;\n const { __numberFormatters } = context;\n if ((process.env.NODE_ENV !== 'production') && !Availabilities.numberFormat) {\n onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_NUMBER));\n return MISSING_RESOLVE_VALUE;\n }\n const [key, value, options, overrides] = parseNumberArgs(...args);\n const missingWarn = isBoolean(options.missingWarn)\n ? options.missingWarn\n : context.missingWarn;\n const fallbackWarn = isBoolean(options.fallbackWarn)\n ? options.fallbackWarn\n : context.fallbackWarn;\n const part = !!options.part;\n const locale = getLocale(context, options);\n const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any\n fallbackLocale, locale);\n if (!isString(key) || key === '') {\n return new Intl.NumberFormat(locale, overrides).format(value);\n }\n // resolve format\n let numberFormat = {};\n let targetLocale;\n let format = null;\n let from = locale;\n let to = null;\n const type = 'number format';\n for (let i = 0; i < locales.length; i++) {\n targetLocale = to = locales[i];\n if ((process.env.NODE_ENV !== 'production') &&\n locale !== targetLocale &&\n isTranslateFallbackWarn(fallbackWarn, key)) {\n onWarn(getWarnMessage(CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT, {\n key,\n target: targetLocale\n }));\n }\n // for vue-devtools timeline event\n if ((process.env.NODE_ENV !== 'production') && locale !== targetLocale) {\n const emitter = context.__v_emitter;\n if (emitter) {\n emitter.emit(\"fallback\" /* VueDevToolsTimelineEvents.FALBACK */, {\n type,\n key,\n from,\n to,\n groupId: `${type}:${key}`\n });\n }\n }\n numberFormat =\n numberFormats[targetLocale] || {};\n format = numberFormat[key];\n if (isPlainObject(format))\n break;\n handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any\n from = to;\n }\n // checking format and target locale\n if (!isPlainObject(format) || !isString(targetLocale)) {\n return unresolving ? NOT_REOSLVED : key;\n }\n let id = `${targetLocale}__${key}`;\n if (!isEmptyObject(overrides)) {\n id = `${id}__${JSON.stringify(overrides)}`;\n }\n let formatter = __numberFormatters.get(id);\n if (!formatter) {\n formatter = new Intl.NumberFormat(targetLocale, assign({}, format, overrides));\n __numberFormatters.set(id, formatter);\n }\n return !part ? formatter.format(value) : formatter.formatToParts(value);\n}\n/** @internal */\nconst NUMBER_FORMAT_OPTIONS_KEYS = [\n 'localeMatcher',\n 'style',\n 'currency',\n 'currencyDisplay',\n 'currencySign',\n 'useGrouping',\n 'minimumIntegerDigits',\n 'minimumFractionDigits',\n 'maximumFractionDigits',\n 'minimumSignificantDigits',\n 'maximumSignificantDigits',\n 'compactDisplay',\n 'notation',\n 'signDisplay',\n 'unit',\n 'unitDisplay',\n 'roundingMode',\n 'roundingPriority',\n 'roundingIncrement',\n 'trailingZeroDisplay'\n];\n/** @internal */\nfunction parseNumberArgs(...args) {\n const [arg1, arg2, arg3, arg4] = args;\n const options = {};\n let overrides = {};\n if (!isNumber(arg1)) {\n throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);\n }\n const value = arg1;\n if (isString(arg2)) {\n options.key = arg2;\n }\n else if (isPlainObject(arg2)) {\n Object.keys(arg2).forEach(key => {\n if (NUMBER_FORMAT_OPTIONS_KEYS.includes(key)) {\n overrides[key] = arg2[key];\n }\n else {\n options[key] = arg2[key];\n }\n });\n }\n if (isString(arg3)) {\n options.locale = arg3;\n }\n else if (isPlainObject(arg3)) {\n overrides = arg3;\n }\n if (isPlainObject(arg4)) {\n overrides = arg4;\n }\n return [options.key || '', value, options, overrides];\n}\n/** @internal */\nfunction clearNumberFormat(ctx, locale, format) {\n const context = ctx;\n for (const key in format) {\n const id = `${locale}__${key}`;\n if (!context.__numberFormatters.has(id)) {\n continue;\n }\n context.__numberFormatters.delete(id);\n }\n}\n\n{\n initFeatureFlags();\n}\n\nexport { CoreErrorCodes, CoreWarnCodes, DATETIME_FORMAT_OPTIONS_KEYS, DEFAULT_LOCALE, DEFAULT_MESSAGE_DATA_TYPE, MISSING_RESOLVE_VALUE, NOT_REOSLVED, NUMBER_FORMAT_OPTIONS_KEYS, VERSION, clearCompileCache, clearDateTimeFormat, clearNumberFormat, compile, compileToFunction, createCoreContext, createCoreError, createMessageContext, datetime, fallbackWithLocaleChain, fallbackWithSimple, getAdditionalMeta, getDevToolsHook, getFallbackContext, getLocale, getWarnMessage, handleMissing, initI18nDevTools, isAlmostSameLocale, isImplicitFallback, isMessageAST, isMessageFunction, isTranslateFallbackWarn, isTranslateMissingWarn, number, parse, parseDateTimeArgs, parseNumberArgs, parseTranslateArgs, registerLocaleFallbacker, registerMessageCompiler, registerMessageResolver, resolveLocale, resolveValue, resolveWithKeyValue, setAdditionalMeta, setDevToolsHook, setFallbackContext, translate, translateDevTools, updateFallbackLocale };\n","/*!\n * vue-i18n v9.13.1\n * (c) 2024 kazuya kawaguchi\n * Released under the MIT License.\n */\nimport { getGlobalThis, incrementer, format, makeSymbol, isPlainObject, isArray, deepCopy, isString, hasOwn, isObject, warn, warnOnce, isBoolean, isRegExp, isFunction, inBrowser, assign, isNumber, createEmitter, isEmptyObject } from '@intlify/shared';\nimport { CoreWarnCodes, CoreErrorCodes, createCompileError, DEFAULT_LOCALE, updateFallbackLocale, setFallbackContext, createCoreContext, clearDateTimeFormat, clearNumberFormat, setAdditionalMeta, getFallbackContext, NOT_REOSLVED, isTranslateFallbackWarn, isTranslateMissingWarn, parseTranslateArgs, translate, MISSING_RESOLVE_VALUE, parseDateTimeArgs, datetime, parseNumberArgs, number, isMessageAST, isMessageFunction, fallbackWithLocaleChain, NUMBER_FORMAT_OPTIONS_KEYS, DATETIME_FORMAT_OPTIONS_KEYS, registerMessageCompiler, compile, compileToFunction, registerMessageResolver, resolveValue, registerLocaleFallbacker, setDevToolsHook } from '@intlify/core-base';\nimport { createVNode, Text, computed, watch, getCurrentInstance, ref, shallowRef, Fragment, defineComponent, h, effectScope, inject, onMounted, onUnmounted, onBeforeMount, isRef } from 'vue';\nimport { setupDevtoolsPlugin } from '@vue/devtools-api';\n\n/**\n * Vue I18n Version\n *\n * @remarks\n * Semver format. Same format as the package.json `version` field.\n *\n * @VueI18nGeneral\n */\nconst VERSION = '9.13.1';\n/**\n * This is only called in esm-bundler builds.\n * istanbul-ignore-next\n */\nfunction initFeatureFlags() {\n if (typeof __VUE_I18N_FULL_INSTALL__ !== 'boolean') {\n getGlobalThis().__VUE_I18N_FULL_INSTALL__ = true;\n }\n if (typeof __VUE_I18N_LEGACY_API__ !== 'boolean') {\n getGlobalThis().__VUE_I18N_LEGACY_API__ = true;\n }\n if (typeof __INTLIFY_JIT_COMPILATION__ !== 'boolean') {\n getGlobalThis().__INTLIFY_JIT_COMPILATION__ = false;\n }\n if (typeof __INTLIFY_DROP_MESSAGE_COMPILER__ !== 'boolean') {\n getGlobalThis().__INTLIFY_DROP_MESSAGE_COMPILER__ = false;\n }\n if (typeof __INTLIFY_PROD_DEVTOOLS__ !== 'boolean') {\n getGlobalThis().__INTLIFY_PROD_DEVTOOLS__ = false;\n }\n}\n\nconst code$1 = CoreWarnCodes.__EXTEND_POINT__;\nconst inc$1 = incrementer(code$1);\nconst I18nWarnCodes = {\n FALLBACK_TO_ROOT: code$1, // 9\n NOT_SUPPORTED_PRESERVE: inc$1(), // 10\n NOT_SUPPORTED_FORMATTER: inc$1(), // 11\n NOT_SUPPORTED_PRESERVE_DIRECTIVE: inc$1(), // 12\n NOT_SUPPORTED_GET_CHOICE_INDEX: inc$1(), // 13\n COMPONENT_NAME_LEGACY_COMPATIBLE: inc$1(), // 14\n NOT_FOUND_PARENT_SCOPE: inc$1(), // 15\n IGNORE_OBJ_FLATTEN: inc$1(), // 16\n NOTICE_DROP_ALLOW_COMPOSITION: inc$1(), // 17\n NOTICE_DROP_TRANSLATE_EXIST_COMPATIBLE_FLAG: inc$1() // 18\n};\nconst warnMessages = {\n [I18nWarnCodes.FALLBACK_TO_ROOT]: `Fall back to {type} '{key}' with root locale.`,\n [I18nWarnCodes.NOT_SUPPORTED_PRESERVE]: `Not supported 'preserve'.`,\n [I18nWarnCodes.NOT_SUPPORTED_FORMATTER]: `Not supported 'formatter'.`,\n [I18nWarnCodes.NOT_SUPPORTED_PRESERVE_DIRECTIVE]: `Not supported 'preserveDirectiveContent'.`,\n [I18nWarnCodes.NOT_SUPPORTED_GET_CHOICE_INDEX]: `Not supported 'getChoiceIndex'.`,\n [I18nWarnCodes.COMPONENT_NAME_LEGACY_COMPATIBLE]: `Component name legacy compatible: '{name}' -> 'i18n'`,\n [I18nWarnCodes.NOT_FOUND_PARENT_SCOPE]: `Not found parent scope. use the global scope.`,\n [I18nWarnCodes.IGNORE_OBJ_FLATTEN]: `Ignore object flatten: '{key}' key has an string value`,\n [I18nWarnCodes.NOTICE_DROP_ALLOW_COMPOSITION]: `'allowComposition' option will be dropped in the next major version. For more information, please see 👉 https://tinyurl.com/2p97mcze`,\n [I18nWarnCodes.NOTICE_DROP_TRANSLATE_EXIST_COMPATIBLE_FLAG]: `'translateExistCompatible' option will be dropped in the next major version.`\n};\nfunction getWarnMessage(code, ...args) {\n return format(warnMessages[code], ...args);\n}\n\nconst code = CoreErrorCodes.__EXTEND_POINT__;\nconst inc = incrementer(code);\nconst I18nErrorCodes = {\n // composer module errors\n UNEXPECTED_RETURN_TYPE: code, // 24\n // legacy module errors\n INVALID_ARGUMENT: inc(), // 25\n // i18n module errors\n MUST_BE_CALL_SETUP_TOP: inc(), // 26\n NOT_INSTALLED: inc(), // 27\n NOT_AVAILABLE_IN_LEGACY_MODE: inc(), // 28\n // directive module errors\n REQUIRED_VALUE: inc(), // 29\n INVALID_VALUE: inc(), // 30\n // vue-devtools errors\n CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN: inc(), // 31\n NOT_INSTALLED_WITH_PROVIDE: inc(), // 32\n // unexpected error\n UNEXPECTED_ERROR: inc(), // 33\n // not compatible legacy vue-i18n constructor\n NOT_COMPATIBLE_LEGACY_VUE_I18N: inc(), // 34\n // bridge support vue 2.x only\n BRIDGE_SUPPORT_VUE_2_ONLY: inc(), // 35\n // need to define `i18n` option in `allowComposition: true` and `useScope: 'local' at `useI18n``\n MUST_DEFINE_I18N_OPTION_IN_ALLOW_COMPOSITION: inc(), // 36\n // Not available Compostion API in Legacy API mode. Please make sure that the legacy API mode is working properly\n NOT_AVAILABLE_COMPOSITION_IN_LEGACY: inc(), // 37\n // for enhancement\n __EXTEND_POINT__: inc() // 38\n};\nfunction createI18nError(code, ...args) {\n return createCompileError(code, null, (process.env.NODE_ENV !== 'production') ? { messages: errorMessages, args } : undefined);\n}\nconst errorMessages = {\n [I18nErrorCodes.UNEXPECTED_RETURN_TYPE]: 'Unexpected return type in composer',\n [I18nErrorCodes.INVALID_ARGUMENT]: 'Invalid argument',\n [I18nErrorCodes.MUST_BE_CALL_SETUP_TOP]: 'Must be called at the top of a `setup` function',\n [I18nErrorCodes.NOT_INSTALLED]: 'Need to install with `app.use` function',\n [I18nErrorCodes.UNEXPECTED_ERROR]: 'Unexpected error',\n [I18nErrorCodes.NOT_AVAILABLE_IN_LEGACY_MODE]: 'Not available in legacy mode',\n [I18nErrorCodes.REQUIRED_VALUE]: `Required in value: {0}`,\n [I18nErrorCodes.INVALID_VALUE]: `Invalid value`,\n [I18nErrorCodes.CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN]: `Cannot setup vue-devtools plugin`,\n [I18nErrorCodes.NOT_INSTALLED_WITH_PROVIDE]: 'Need to install with `provide` function',\n [I18nErrorCodes.NOT_COMPATIBLE_LEGACY_VUE_I18N]: 'Not compatible legacy VueI18n.',\n [I18nErrorCodes.BRIDGE_SUPPORT_VUE_2_ONLY]: 'vue-i18n-bridge support Vue 2.x only',\n [I18nErrorCodes.MUST_DEFINE_I18N_OPTION_IN_ALLOW_COMPOSITION]: 'Must define ‘i18n’ option or custom block in Composition API with using local scope in Legacy API mode',\n [I18nErrorCodes.NOT_AVAILABLE_COMPOSITION_IN_LEGACY]: 'Not available Compostion API in Legacy API mode. Please make sure that the legacy API mode is working properly'\n};\n\nconst TranslateVNodeSymbol = \n/* #__PURE__*/ makeSymbol('__translateVNode');\nconst DatetimePartsSymbol = /* #__PURE__*/ makeSymbol('__datetimeParts');\nconst NumberPartsSymbol = /* #__PURE__*/ makeSymbol('__numberParts');\nconst EnableEmitter = /* #__PURE__*/ makeSymbol('__enableEmitter');\nconst DisableEmitter = /* #__PURE__*/ makeSymbol('__disableEmitter');\nconst SetPluralRulesSymbol = makeSymbol('__setPluralRules');\nmakeSymbol('__intlifyMeta');\nconst InejctWithOptionSymbol = \n/* #__PURE__*/ makeSymbol('__injectWithOption');\nconst DisposeSymbol = /* #__PURE__*/ makeSymbol('__dispose');\nconst __VUE_I18N_BRIDGE__ = '__VUE_I18N_BRIDGE__';\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/**\n * Transform flat json in obj to normal json in obj\n */\nfunction handleFlatJson(obj) {\n // check obj\n if (!isObject(obj)) {\n return obj;\n }\n for (const key in obj) {\n // check key\n if (!hasOwn(obj, key)) {\n continue;\n }\n // handle for normal json\n if (!key.includes('.')) {\n // recursive process value if value is also a object\n if (isObject(obj[key])) {\n handleFlatJson(obj[key]);\n }\n }\n // handle for flat json, transform to normal json\n else {\n // go to the last object\n const subKeys = key.split('.');\n const lastIndex = subKeys.length - 1;\n let currentObj = obj;\n let hasStringValue = false;\n for (let i = 0; i < lastIndex; i++) {\n if (!(subKeys[i] in currentObj)) {\n currentObj[subKeys[i]] = {};\n }\n if (!isObject(currentObj[subKeys[i]])) {\n (process.env.NODE_ENV !== 'production') &&\n warn(getWarnMessage(I18nWarnCodes.IGNORE_OBJ_FLATTEN, {\n key: subKeys[i]\n }));\n hasStringValue = true;\n break;\n }\n currentObj = currentObj[subKeys[i]];\n }\n // update last object value, delete old property\n if (!hasStringValue) {\n currentObj[subKeys[lastIndex]] = obj[key];\n delete obj[key];\n }\n // recursive process value if value is also a object\n if (isObject(currentObj[subKeys[lastIndex]])) {\n handleFlatJson(currentObj[subKeys[lastIndex]]);\n }\n }\n }\n return obj;\n}\nfunction getLocaleMessages(locale, options) {\n const { messages, __i18n, messageResolver, flatJson } = options;\n // prettier-ignore\n const ret = (isPlainObject(messages)\n ? messages\n : isArray(__i18n)\n ? {}\n : { [locale]: {} });\n // merge locale messages of i18n custom block\n if (isArray(__i18n)) {\n __i18n.forEach(custom => {\n if ('locale' in custom && 'resource' in custom) {\n const { locale, resource } = custom;\n if (locale) {\n ret[locale] = ret[locale] || {};\n deepCopy(resource, ret[locale]);\n }\n else {\n deepCopy(resource, ret);\n }\n }\n else {\n isString(custom) && deepCopy(JSON.parse(custom), ret);\n }\n });\n }\n // handle messages for flat json\n if (messageResolver == null && flatJson) {\n for (const key in ret) {\n if (hasOwn(ret, key)) {\n handleFlatJson(ret[key]);\n }\n }\n }\n return ret;\n}\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getComponentOptions(instance) {\n return instance.type ;\n}\nfunction adjustI18nResources(gl, options, componentOptions // eslint-disable-line @typescript-eslint/no-explicit-any\n) {\n let messages = isObject(options.messages) ? options.messages : {};\n if ('__i18nGlobal' in componentOptions) {\n messages = getLocaleMessages(gl.locale.value, {\n messages,\n __i18n: componentOptions.__i18nGlobal\n });\n }\n // merge locale messages\n const locales = Object.keys(messages);\n if (locales.length) {\n locales.forEach(locale => {\n gl.mergeLocaleMessage(locale, messages[locale]);\n });\n }\n {\n // merge datetime formats\n if (isObject(options.datetimeFormats)) {\n const locales = Object.keys(options.datetimeFormats);\n if (locales.length) {\n locales.forEach(locale => {\n gl.mergeDateTimeFormat(locale, options.datetimeFormats[locale]);\n });\n }\n }\n // merge number formats\n if (isObject(options.numberFormats)) {\n const locales = Object.keys(options.numberFormats);\n if (locales.length) {\n locales.forEach(locale => {\n gl.mergeNumberFormat(locale, options.numberFormats[locale]);\n });\n }\n }\n }\n}\nfunction createTextNode(key) {\n return createVNode(Text, null, key, 0)\n ;\n}\n/* eslint-enable @typescript-eslint/no-explicit-any */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n// extend VNode interface\nconst DEVTOOLS_META = '__INTLIFY_META__';\nconst NOOP_RETURN_ARRAY = () => [];\nconst NOOP_RETURN_FALSE = () => false;\nlet composerID = 0;\nfunction defineCoreMissingHandler(missing) {\n return ((ctx, locale, key, type) => {\n return missing(locale, key, getCurrentInstance() || undefined, type);\n });\n}\n// for Intlify DevTools\n/* #__NO_SIDE_EFFECTS__ */\nconst getMetaInfo = () => {\n const instance = getCurrentInstance();\n let meta = null; // eslint-disable-line @typescript-eslint/no-explicit-any\n return instance && (meta = getComponentOptions(instance)[DEVTOOLS_META])\n ? { [DEVTOOLS_META]: meta } // eslint-disable-line @typescript-eslint/no-explicit-any\n : null;\n};\n/**\n * Create composer interface factory\n *\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nfunction createComposer(options = {}, VueI18nLegacy) {\n const { __root, __injectWithOption } = options;\n const _isGlobal = __root === undefined;\n const flatJson = options.flatJson;\n const _ref = inBrowser ? ref : shallowRef;\n const translateExistCompatible = !!options.translateExistCompatible;\n if ((process.env.NODE_ENV !== 'production')) {\n if (translateExistCompatible && !false) {\n warnOnce(getWarnMessage(I18nWarnCodes.NOTICE_DROP_TRANSLATE_EXIST_COMPATIBLE_FLAG));\n }\n }\n let _inheritLocale = isBoolean(options.inheritLocale)\n ? options.inheritLocale\n : true;\n const _locale = _ref(\n // prettier-ignore\n __root && _inheritLocale\n ? __root.locale.value\n : isString(options.locale)\n ? options.locale\n : DEFAULT_LOCALE);\n const _fallbackLocale = _ref(\n // prettier-ignore\n __root && _inheritLocale\n ? __root.fallbackLocale.value\n : isString(options.fallbackLocale) ||\n isArray(options.fallbackLocale) ||\n isPlainObject(options.fallbackLocale) ||\n options.fallbackLocale === false\n ? options.fallbackLocale\n : _locale.value);\n const _messages = _ref(getLocaleMessages(_locale.value, options));\n // prettier-ignore\n const _datetimeFormats = _ref(isPlainObject(options.datetimeFormats)\n ? options.datetimeFormats\n : { [_locale.value]: {} })\n ;\n // prettier-ignore\n const _numberFormats = _ref(isPlainObject(options.numberFormats)\n ? options.numberFormats\n : { [_locale.value]: {} })\n ;\n // warning suppress options\n // prettier-ignore\n let _missingWarn = __root\n ? __root.missingWarn\n : isBoolean(options.missingWarn) || isRegExp(options.missingWarn)\n ? options.missingWarn\n : true;\n // prettier-ignore\n let _fallbackWarn = __root\n ? __root.fallbackWarn\n : isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)\n ? options.fallbackWarn\n : true;\n // prettier-ignore\n let _fallbackRoot = __root\n ? __root.fallbackRoot\n : isBoolean(options.fallbackRoot)\n ? options.fallbackRoot\n : true;\n // configure fall back to root\n let _fallbackFormat = !!options.fallbackFormat;\n // runtime missing\n let _missing = isFunction(options.missing) ? options.missing : null;\n let _runtimeMissing = isFunction(options.missing)\n ? defineCoreMissingHandler(options.missing)\n : null;\n // postTranslation handler\n let _postTranslation = isFunction(options.postTranslation)\n ? options.postTranslation\n : null;\n // prettier-ignore\n let _warnHtmlMessage = __root\n ? __root.warnHtmlMessage\n : isBoolean(options.warnHtmlMessage)\n ? options.warnHtmlMessage\n : true;\n let _escapeParameter = !!options.escapeParameter;\n // custom linked modifiers\n // prettier-ignore\n const _modifiers = __root\n ? __root.modifiers\n : isPlainObject(options.modifiers)\n ? options.modifiers\n : {};\n // pluralRules\n let _pluralRules = options.pluralRules || (__root && __root.pluralRules);\n // runtime context\n // eslint-disable-next-line prefer-const\n let _context;\n const getCoreContext = () => {\n _isGlobal && setFallbackContext(null);\n const ctxOptions = {\n version: VERSION,\n locale: _locale.value,\n fallbackLocale: _fallbackLocale.value,\n messages: _messages.value,\n modifiers: _modifiers,\n pluralRules: _pluralRules,\n missing: _runtimeMissing === null ? undefined : _runtimeMissing,\n missingWarn: _missingWarn,\n fallbackWarn: _fallbackWarn,\n fallbackFormat: _fallbackFormat,\n unresolving: true,\n postTranslation: _postTranslation === null ? undefined : _postTranslation,\n warnHtmlMessage: _warnHtmlMessage,\n escapeParameter: _escapeParameter,\n messageResolver: options.messageResolver,\n messageCompiler: options.messageCompiler,\n __meta: { framework: 'vue' }\n };\n {\n ctxOptions.datetimeFormats = _datetimeFormats.value;\n ctxOptions.numberFormats = _numberFormats.value;\n ctxOptions.__datetimeFormatters = isPlainObject(_context)\n ? _context.__datetimeFormatters\n : undefined;\n ctxOptions.__numberFormatters = isPlainObject(_context)\n ? _context.__numberFormatters\n : undefined;\n }\n if ((process.env.NODE_ENV !== 'production')) {\n ctxOptions.__v_emitter = isPlainObject(_context)\n ? _context.__v_emitter\n : undefined;\n }\n const ctx = createCoreContext(ctxOptions);\n _isGlobal && setFallbackContext(ctx);\n return ctx;\n };\n _context = getCoreContext();\n updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);\n // track reactivity\n function trackReactivityValues() {\n return [\n _locale.value,\n _fallbackLocale.value,\n _messages.value,\n _datetimeFormats.value,\n _numberFormats.value\n ]\n ;\n }\n // locale\n const locale = computed({\n get: () => _locale.value,\n set: val => {\n _locale.value = val;\n _context.locale = _locale.value;\n }\n });\n // fallbackLocale\n const fallbackLocale = computed({\n get: () => _fallbackLocale.value,\n set: val => {\n _fallbackLocale.value = val;\n _context.fallbackLocale = _fallbackLocale.value;\n updateFallbackLocale(_context, _locale.value, val);\n }\n });\n // messages\n const messages = computed(() => _messages.value);\n // datetimeFormats\n const datetimeFormats = /* #__PURE__*/ computed(() => _datetimeFormats.value);\n // numberFormats\n const numberFormats = /* #__PURE__*/ computed(() => _numberFormats.value);\n // getPostTranslationHandler\n function getPostTranslationHandler() {\n return isFunction(_postTranslation) ? _postTranslation : null;\n }\n // setPostTranslationHandler\n function setPostTranslationHandler(handler) {\n _postTranslation = handler;\n _context.postTranslation = handler;\n }\n // getMissingHandler\n function getMissingHandler() {\n return _missing;\n }\n // setMissingHandler\n function setMissingHandler(handler) {\n if (handler !== null) {\n _runtimeMissing = defineCoreMissingHandler(handler);\n }\n _missing = handler;\n _context.missing = _runtimeMissing;\n }\n function isResolvedTranslateMessage(type, arg // eslint-disable-line @typescript-eslint/no-explicit-any\n ) {\n return type !== 'translate' || !arg.resolvedMessage;\n }\n const wrapWithDeps = (fn, argumentParser, warnType, fallbackSuccess, fallbackFail, successCondition) => {\n trackReactivityValues(); // track reactive dependency\n // NOTE: experimental !!\n let ret;\n try {\n if ((process.env.NODE_ENV !== 'production') || __INTLIFY_PROD_DEVTOOLS__) {\n setAdditionalMeta(getMetaInfo());\n }\n if (!_isGlobal) {\n _context.fallbackContext = __root\n ? getFallbackContext()\n : undefined;\n }\n ret = fn(_context);\n }\n finally {\n if ((process.env.NODE_ENV !== 'production') || __INTLIFY_PROD_DEVTOOLS__) {\n setAdditionalMeta(null);\n }\n if (!_isGlobal) {\n _context.fallbackContext = undefined;\n }\n }\n if ((warnType !== 'translate exists' && // for not `te` (e.g `t`)\n isNumber(ret) &&\n ret === NOT_REOSLVED) ||\n (warnType === 'translate exists' && !ret) // for `te`\n ) {\n const [key, arg2] = argumentParser();\n if ((process.env.NODE_ENV !== 'production') &&\n __root &&\n isString(key) &&\n isResolvedTranslateMessage(warnType, arg2)) {\n if (_fallbackRoot &&\n (isTranslateFallbackWarn(_fallbackWarn, key) ||\n isTranslateMissingWarn(_missingWarn, key))) {\n warn(getWarnMessage(I18nWarnCodes.FALLBACK_TO_ROOT, {\n key,\n type: warnType\n }));\n }\n // for vue-devtools timeline event\n if ((process.env.NODE_ENV !== 'production')) {\n const { __v_emitter: emitter } = _context;\n if (emitter && _fallbackRoot) {\n emitter.emit(\"fallback\" /* VueDevToolsTimelineEvents.FALBACK */, {\n type: warnType,\n key,\n to: 'global',\n groupId: `${warnType}:${key}`\n });\n }\n }\n }\n return __root && _fallbackRoot\n ? fallbackSuccess(__root)\n : fallbackFail(key);\n }\n else if (successCondition(ret)) {\n return ret;\n }\n else {\n /* istanbul ignore next */\n throw createI18nError(I18nErrorCodes.UNEXPECTED_RETURN_TYPE);\n }\n };\n // t\n function t(...args) {\n return wrapWithDeps(context => Reflect.apply(translate, null, [context, ...args]), () => parseTranslateArgs(...args), 'translate', root => Reflect.apply(root.t, root, [...args]), key => key, val => isString(val));\n }\n // rt\n function rt(...args) {\n const [arg1, arg2, arg3] = args;\n if (arg3 && !isObject(arg3)) {\n throw createI18nError(I18nErrorCodes.INVALID_ARGUMENT);\n }\n return t(...[arg1, arg2, assign({ resolvedMessage: true }, arg3 || {})]);\n }\n // d\n function d(...args) {\n return wrapWithDeps(context => Reflect.apply(datetime, null, [context, ...args]), () => parseDateTimeArgs(...args), 'datetime format', root => Reflect.apply(root.d, root, [...args]), () => MISSING_RESOLVE_VALUE, val => isString(val));\n }\n // n\n function n(...args) {\n return wrapWithDeps(context => Reflect.apply(number, null, [context, ...args]), () => parseNumberArgs(...args), 'number format', root => Reflect.apply(root.n, root, [...args]), () => MISSING_RESOLVE_VALUE, val => isString(val));\n }\n // for custom processor\n function normalize(values) {\n return values.map(val => isString(val) || isNumber(val) || isBoolean(val)\n ? createTextNode(String(val))\n : val);\n }\n const interpolate = (val) => val;\n const processor = {\n normalize,\n interpolate,\n type: 'vnode'\n };\n // translateVNode, using for `i18n-t` component\n function translateVNode(...args) {\n return wrapWithDeps(context => {\n let ret;\n const _context = context;\n try {\n _context.processor = processor;\n ret = Reflect.apply(translate, null, [_context, ...args]);\n }\n finally {\n _context.processor = null;\n }\n return ret;\n }, () => parseTranslateArgs(...args), 'translate', \n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n root => root[TranslateVNodeSymbol](...args), key => [createTextNode(key)], val => isArray(val));\n }\n // numberParts, using for `i18n-n` component\n function numberParts(...args) {\n return wrapWithDeps(context => Reflect.apply(number, null, [context, ...args]), () => parseNumberArgs(...args), 'number format', \n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n root => root[NumberPartsSymbol](...args), NOOP_RETURN_ARRAY, val => isString(val) || isArray(val));\n }\n // datetimeParts, using for `i18n-d` component\n function datetimeParts(...args) {\n return wrapWithDeps(context => Reflect.apply(datetime, null, [context, ...args]), () => parseDateTimeArgs(...args), 'datetime format', \n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n root => root[DatetimePartsSymbol](...args), NOOP_RETURN_ARRAY, val => isString(val) || isArray(val));\n }\n function setPluralRules(rules) {\n _pluralRules = rules;\n _context.pluralRules = _pluralRules;\n }\n // te\n function te(key, locale) {\n return wrapWithDeps(() => {\n if (!key) {\n return false;\n }\n const targetLocale = isString(locale) ? locale : _locale.value;\n const message = getLocaleMessage(targetLocale);\n const resolved = _context.messageResolver(message, key);\n return !translateExistCompatible\n ? isMessageAST(resolved) ||\n isMessageFunction(resolved) ||\n isString(resolved)\n : resolved != null;\n }, () => [key], 'translate exists', root => {\n return Reflect.apply(root.te, root, [key, locale]);\n }, NOOP_RETURN_FALSE, val => isBoolean(val));\n }\n function resolveMessages(key) {\n let messages = null;\n const locales = fallbackWithLocaleChain(_context, _fallbackLocale.value, _locale.value);\n for (let i = 0; i < locales.length; i++) {\n const targetLocaleMessages = _messages.value[locales[i]] || {};\n const messageValue = _context.messageResolver(targetLocaleMessages, key);\n if (messageValue != null) {\n messages = messageValue;\n break;\n }\n }\n return messages;\n }\n // tm\n function tm(key) {\n const messages = resolveMessages(key);\n // prettier-ignore\n return messages != null\n ? messages\n : __root\n ? __root.tm(key) || {}\n : {};\n }\n // getLocaleMessage\n function getLocaleMessage(locale) {\n return (_messages.value[locale] || {});\n }\n // setLocaleMessage\n function setLocaleMessage(locale, message) {\n if (flatJson) {\n const _message = { [locale]: message };\n for (const key in _message) {\n if (hasOwn(_message, key)) {\n handleFlatJson(_message[key]);\n }\n }\n message = _message[locale];\n }\n _messages.value[locale] = message;\n _context.messages = _messages.value;\n }\n // mergeLocaleMessage\n function mergeLocaleMessage(locale, message) {\n _messages.value[locale] = _messages.value[locale] || {};\n const _message = { [locale]: message };\n if (flatJson) {\n for (const key in _message) {\n if (hasOwn(_message, key)) {\n handleFlatJson(_message[key]);\n }\n }\n }\n message = _message[locale];\n deepCopy(message, _messages.value[locale]);\n _context.messages = _messages.value;\n }\n // getDateTimeFormat\n function getDateTimeFormat(locale) {\n return _datetimeFormats.value[locale] || {};\n }\n // setDateTimeFormat\n function setDateTimeFormat(locale, format) {\n _datetimeFormats.value[locale] = format;\n _context.datetimeFormats = _datetimeFormats.value;\n clearDateTimeFormat(_context, locale, format);\n }\n // mergeDateTimeFormat\n function mergeDateTimeFormat(locale, format) {\n _datetimeFormats.value[locale] = assign(_datetimeFormats.value[locale] || {}, format);\n _context.datetimeFormats = _datetimeFormats.value;\n clearDateTimeFormat(_context, locale, format);\n }\n // getNumberFormat\n function getNumberFormat(locale) {\n return _numberFormats.value[locale] || {};\n }\n // setNumberFormat\n function setNumberFormat(locale, format) {\n _numberFormats.value[locale] = format;\n _context.numberFormats = _numberFormats.value;\n clearNumberFormat(_context, locale, format);\n }\n // mergeNumberFormat\n function mergeNumberFormat(locale, format) {\n _numberFormats.value[locale] = assign(_numberFormats.value[locale] || {}, format);\n _context.numberFormats = _numberFormats.value;\n clearNumberFormat(_context, locale, format);\n }\n // for debug\n composerID++;\n // watch root locale & fallbackLocale\n if (__root && inBrowser) {\n watch(__root.locale, (val) => {\n if (_inheritLocale) {\n _locale.value = val;\n _context.locale = val;\n updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);\n }\n });\n watch(__root.fallbackLocale, (val) => {\n if (_inheritLocale) {\n _fallbackLocale.value = val;\n _context.fallbackLocale = val;\n updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);\n }\n });\n }\n // define basic composition API!\n const composer = {\n id: composerID,\n locale,\n fallbackLocale,\n get inheritLocale() {\n return _inheritLocale;\n },\n set inheritLocale(val) {\n _inheritLocale = val;\n if (val && __root) {\n _locale.value = __root.locale.value;\n _fallbackLocale.value = __root.fallbackLocale.value;\n updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);\n }\n },\n get availableLocales() {\n return Object.keys(_messages.value).sort();\n },\n messages,\n get modifiers() {\n return _modifiers;\n },\n get pluralRules() {\n return _pluralRules || {};\n },\n get isGlobal() {\n return _isGlobal;\n },\n get missingWarn() {\n return _missingWarn;\n },\n set missingWarn(val) {\n _missingWarn = val;\n _context.missingWarn = _missingWarn;\n },\n get fallbackWarn() {\n return _fallbackWarn;\n },\n set fallbackWarn(val) {\n _fallbackWarn = val;\n _context.fallbackWarn = _fallbackWarn;\n },\n get fallbackRoot() {\n return _fallbackRoot;\n },\n set fallbackRoot(val) {\n _fallbackRoot = val;\n },\n get fallbackFormat() {\n return _fallbackFormat;\n },\n set fallbackFormat(val) {\n _fallbackFormat = val;\n _context.fallbackFormat = _fallbackFormat;\n },\n get warnHtmlMessage() {\n return _warnHtmlMessage;\n },\n set warnHtmlMessage(val) {\n _warnHtmlMessage = val;\n _context.warnHtmlMessage = val;\n },\n get escapeParameter() {\n return _escapeParameter;\n },\n set escapeParameter(val) {\n _escapeParameter = val;\n _context.escapeParameter = val;\n },\n t,\n getLocaleMessage,\n setLocaleMessage,\n mergeLocaleMessage,\n getPostTranslationHandler,\n setPostTranslationHandler,\n getMissingHandler,\n setMissingHandler,\n [SetPluralRulesSymbol]: setPluralRules\n };\n {\n composer.datetimeFormats = datetimeFormats;\n composer.numberFormats = numberFormats;\n composer.rt = rt;\n composer.te = te;\n composer.tm = tm;\n composer.d = d;\n composer.n = n;\n composer.getDateTimeFormat = getDateTimeFormat;\n composer.setDateTimeFormat = setDateTimeFormat;\n composer.mergeDateTimeFormat = mergeDateTimeFormat;\n composer.getNumberFormat = getNumberFormat;\n composer.setNumberFormat = setNumberFormat;\n composer.mergeNumberFormat = mergeNumberFormat;\n composer[InejctWithOptionSymbol] = __injectWithOption;\n composer[TranslateVNodeSymbol] = translateVNode;\n composer[DatetimePartsSymbol] = datetimeParts;\n composer[NumberPartsSymbol] = numberParts;\n }\n // for vue-devtools timeline event\n if ((process.env.NODE_ENV !== 'production')) {\n composer[EnableEmitter] = (emitter) => {\n _context.__v_emitter = emitter;\n };\n composer[DisableEmitter] = () => {\n _context.__v_emitter = undefined;\n };\n }\n return composer;\n}\n/* eslint-enable @typescript-eslint/no-explicit-any */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/**\n * Convert to I18n Composer Options from VueI18n Options\n *\n * @internal\n */\nfunction convertComposerOptions(options) {\n const locale = isString(options.locale) ? options.locale : DEFAULT_LOCALE;\n const fallbackLocale = isString(options.fallbackLocale) ||\n isArray(options.fallbackLocale) ||\n isPlainObject(options.fallbackLocale) ||\n options.fallbackLocale === false\n ? options.fallbackLocale\n : locale;\n const missing = isFunction(options.missing) ? options.missing : undefined;\n const missingWarn = isBoolean(options.silentTranslationWarn) ||\n isRegExp(options.silentTranslationWarn)\n ? !options.silentTranslationWarn\n : true;\n const fallbackWarn = isBoolean(options.silentFallbackWarn) ||\n isRegExp(options.silentFallbackWarn)\n ? !options.silentFallbackWarn\n : true;\n const fallbackRoot = isBoolean(options.fallbackRoot)\n ? options.fallbackRoot\n : true;\n const fallbackFormat = !!options.formatFallbackMessages;\n const modifiers = isPlainObject(options.modifiers) ? options.modifiers : {};\n const pluralizationRules = options.pluralizationRules;\n const postTranslation = isFunction(options.postTranslation)\n ? options.postTranslation\n : undefined;\n const warnHtmlMessage = isString(options.warnHtmlInMessage)\n ? options.warnHtmlInMessage !== 'off'\n : true;\n const escapeParameter = !!options.escapeParameterHtml;\n const inheritLocale = isBoolean(options.sync) ? options.sync : true;\n if ((process.env.NODE_ENV !== 'production') && options.formatter) {\n warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_FORMATTER));\n }\n if ((process.env.NODE_ENV !== 'production') && options.preserveDirectiveContent) {\n warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_PRESERVE_DIRECTIVE));\n }\n let messages = options.messages;\n if (isPlainObject(options.sharedMessages)) {\n const sharedMessages = options.sharedMessages;\n const locales = Object.keys(sharedMessages);\n messages = locales.reduce((messages, locale) => {\n const message = messages[locale] || (messages[locale] = {});\n assign(message, sharedMessages[locale]);\n return messages;\n }, (messages || {}));\n }\n const { __i18n, __root, __injectWithOption } = options;\n const datetimeFormats = options.datetimeFormats;\n const numberFormats = options.numberFormats;\n const flatJson = options.flatJson;\n const translateExistCompatible = options\n .translateExistCompatible;\n return {\n locale,\n fallbackLocale,\n messages,\n flatJson,\n datetimeFormats,\n numberFormats,\n missing,\n missingWarn,\n fallbackWarn,\n fallbackRoot,\n fallbackFormat,\n modifiers,\n pluralRules: pluralizationRules,\n postTranslation,\n warnHtmlMessage,\n escapeParameter,\n messageResolver: options.messageResolver,\n inheritLocale,\n translateExistCompatible,\n __i18n,\n __root,\n __injectWithOption\n };\n}\n/**\n * create VueI18n interface factory\n *\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nfunction createVueI18n(options = {}, VueI18nLegacy) {\n {\n const composer = createComposer(convertComposerOptions(options));\n const { __extender } = options;\n // defines VueI18n\n const vueI18n = {\n // id\n id: composer.id,\n // locale\n get locale() {\n return composer.locale.value;\n },\n set locale(val) {\n composer.locale.value = val;\n },\n // fallbackLocale\n get fallbackLocale() {\n return composer.fallbackLocale.value;\n },\n set fallbackLocale(val) {\n composer.fallbackLocale.value = val;\n },\n // messages\n get messages() {\n return composer.messages.value;\n },\n // datetimeFormats\n get datetimeFormats() {\n return composer.datetimeFormats.value;\n },\n // numberFormats\n get numberFormats() {\n return composer.numberFormats.value;\n },\n // availableLocales\n get availableLocales() {\n return composer.availableLocales;\n },\n // formatter\n get formatter() {\n (process.env.NODE_ENV !== 'production') && warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_FORMATTER));\n // dummy\n return {\n interpolate() {\n return [];\n }\n };\n },\n set formatter(val) {\n (process.env.NODE_ENV !== 'production') && warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_FORMATTER));\n },\n // missing\n get missing() {\n return composer.getMissingHandler();\n },\n set missing(handler) {\n composer.setMissingHandler(handler);\n },\n // silentTranslationWarn\n get silentTranslationWarn() {\n return isBoolean(composer.missingWarn)\n ? !composer.missingWarn\n : composer.missingWarn;\n },\n set silentTranslationWarn(val) {\n composer.missingWarn = isBoolean(val) ? !val : val;\n },\n // silentFallbackWarn\n get silentFallbackWarn() {\n return isBoolean(composer.fallbackWarn)\n ? !composer.fallbackWarn\n : composer.fallbackWarn;\n },\n set silentFallbackWarn(val) {\n composer.fallbackWarn = isBoolean(val) ? !val : val;\n },\n // modifiers\n get modifiers() {\n return composer.modifiers;\n },\n // formatFallbackMessages\n get formatFallbackMessages() {\n return composer.fallbackFormat;\n },\n set formatFallbackMessages(val) {\n composer.fallbackFormat = val;\n },\n // postTranslation\n get postTranslation() {\n return composer.getPostTranslationHandler();\n },\n set postTranslation(handler) {\n composer.setPostTranslationHandler(handler);\n },\n // sync\n get sync() {\n return composer.inheritLocale;\n },\n set sync(val) {\n composer.inheritLocale = val;\n },\n // warnInHtmlMessage\n get warnHtmlInMessage() {\n return composer.warnHtmlMessage ? 'warn' : 'off';\n },\n set warnHtmlInMessage(val) {\n composer.warnHtmlMessage = val !== 'off';\n },\n // escapeParameterHtml\n get escapeParameterHtml() {\n return composer.escapeParameter;\n },\n set escapeParameterHtml(val) {\n composer.escapeParameter = val;\n },\n // preserveDirectiveContent\n get preserveDirectiveContent() {\n (process.env.NODE_ENV !== 'production') &&\n warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_PRESERVE_DIRECTIVE));\n return true;\n },\n set preserveDirectiveContent(val) {\n (process.env.NODE_ENV !== 'production') &&\n warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_PRESERVE_DIRECTIVE));\n },\n // pluralizationRules\n get pluralizationRules() {\n return composer.pluralRules || {};\n },\n // for internal\n __composer: composer,\n // t\n t(...args) {\n const [arg1, arg2, arg3] = args;\n const options = {};\n let list = null;\n let named = null;\n if (!isString(arg1)) {\n throw createI18nError(I18nErrorCodes.INVALID_ARGUMENT);\n }\n const key = arg1;\n if (isString(arg2)) {\n options.locale = arg2;\n }\n else if (isArray(arg2)) {\n list = arg2;\n }\n else if (isPlainObject(arg2)) {\n named = arg2;\n }\n if (isArray(arg3)) {\n list = arg3;\n }\n else if (isPlainObject(arg3)) {\n named = arg3;\n }\n // return composer.t(key, (list || named || {}) as any, options)\n return Reflect.apply(composer.t, composer, [\n key,\n (list || named || {}),\n options\n ]);\n },\n rt(...args) {\n return Reflect.apply(composer.rt, composer, [...args]);\n },\n // tc\n tc(...args) {\n const [arg1, arg2, arg3] = args;\n const options = { plural: 1 };\n let list = null;\n let named = null;\n if (!isString(arg1)) {\n throw createI18nError(I18nErrorCodes.INVALID_ARGUMENT);\n }\n const key = arg1;\n if (isString(arg2)) {\n options.locale = arg2;\n }\n else if (isNumber(arg2)) {\n options.plural = arg2;\n }\n else if (isArray(arg2)) {\n list = arg2;\n }\n else if (isPlainObject(arg2)) {\n named = arg2;\n }\n if (isString(arg3)) {\n options.locale = arg3;\n }\n else if (isArray(arg3)) {\n list = arg3;\n }\n else if (isPlainObject(arg3)) {\n named = arg3;\n }\n // return composer.t(key, (list || named || {}) as any, options)\n return Reflect.apply(composer.t, composer, [\n key,\n (list || named || {}),\n options\n ]);\n },\n // te\n te(key, locale) {\n return composer.te(key, locale);\n },\n // tm\n tm(key) {\n return composer.tm(key);\n },\n // getLocaleMessage\n getLocaleMessage(locale) {\n return composer.getLocaleMessage(locale);\n },\n // setLocaleMessage\n setLocaleMessage(locale, message) {\n composer.setLocaleMessage(locale, message);\n },\n // mergeLocaleMessage\n mergeLocaleMessage(locale, message) {\n composer.mergeLocaleMessage(locale, message);\n },\n // d\n d(...args) {\n return Reflect.apply(composer.d, composer, [...args]);\n },\n // getDateTimeFormat\n getDateTimeFormat(locale) {\n return composer.getDateTimeFormat(locale);\n },\n // setDateTimeFormat\n setDateTimeFormat(locale, format) {\n composer.setDateTimeFormat(locale, format);\n },\n // mergeDateTimeFormat\n mergeDateTimeFormat(locale, format) {\n composer.mergeDateTimeFormat(locale, format);\n },\n // n\n n(...args) {\n return Reflect.apply(composer.n, composer, [...args]);\n },\n // getNumberFormat\n getNumberFormat(locale) {\n return composer.getNumberFormat(locale);\n },\n // setNumberFormat\n setNumberFormat(locale, format) {\n composer.setNumberFormat(locale, format);\n },\n // mergeNumberFormat\n mergeNumberFormat(locale, format) {\n composer.mergeNumberFormat(locale, format);\n },\n // getChoiceIndex\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n getChoiceIndex(choice, choicesLength) {\n (process.env.NODE_ENV !== 'production') &&\n warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_GET_CHOICE_INDEX));\n return -1;\n }\n };\n vueI18n.__extender = __extender;\n // for vue-devtools timeline event\n if ((process.env.NODE_ENV !== 'production')) {\n vueI18n.__enableEmitter = (emitter) => {\n const __composer = composer;\n __composer[EnableEmitter] && __composer[EnableEmitter](emitter);\n };\n vueI18n.__disableEmitter = () => {\n const __composer = composer;\n __composer[DisableEmitter] && __composer[DisableEmitter]();\n };\n }\n return vueI18n;\n }\n}\n/* eslint-enable @typescript-eslint/no-explicit-any */\n\nconst baseFormatProps = {\n tag: {\n type: [String, Object]\n },\n locale: {\n type: String\n },\n scope: {\n type: String,\n // NOTE: avoid https://github.com/microsoft/rushstack/issues/1050\n validator: (val /* ComponentI18nScope */) => val === 'parent' || val === 'global',\n default: 'parent' /* ComponentI18nScope */\n },\n i18n: {\n type: Object\n }\n};\n\nfunction getInterpolateArg(\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\n{ slots }, // SetupContext,\nkeys) {\n if (keys.length === 1 && keys[0] === 'default') {\n // default slot with list\n const ret = slots.default ? slots.default() : [];\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return ret.reduce((slot, current) => {\n return [\n ...slot,\n // prettier-ignore\n ...(current.type === Fragment ? current.children : [current]\n )\n ];\n }, []);\n }\n else {\n // named slots\n return keys.reduce((arg, key) => {\n const slot = slots[key];\n if (slot) {\n arg[key] = slot();\n }\n return arg;\n }, {});\n }\n}\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getFragmentableTag(tag) {\n return Fragment ;\n}\n\nconst TranslationImpl = /*#__PURE__*/ defineComponent({\n /* eslint-disable */\n name: 'i18n-t',\n props: assign({\n keypath: {\n type: String,\n required: true\n },\n plural: {\n type: [Number, String],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n validator: (val) => isNumber(val) || !isNaN(val)\n }\n }, baseFormatProps),\n /* eslint-enable */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n setup(props, context) {\n const { slots, attrs } = context;\n // NOTE: avoid https://github.com/microsoft/rushstack/issues/1050\n const i18n = props.i18n ||\n useI18n({\n useScope: props.scope,\n __useComponent: true\n });\n return () => {\n const keys = Object.keys(slots).filter(key => key !== '_');\n const options = {};\n if (props.locale) {\n options.locale = props.locale;\n }\n if (props.plural !== undefined) {\n options.plural = isString(props.plural) ? +props.plural : props.plural;\n }\n const arg = getInterpolateArg(context, keys);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const children = i18n[TranslateVNodeSymbol](props.keypath, arg, options);\n const assignedAttrs = assign({}, attrs);\n const tag = isString(props.tag) || isObject(props.tag)\n ? props.tag\n : getFragmentableTag();\n return h(tag, assignedAttrs, children);\n };\n }\n});\n/**\n * export the public type for h/tsx inference\n * also to avoid inline import() in generated d.ts files\n */\n/**\n * Translation Component\n *\n * @remarks\n * See the following items for property about details\n *\n * @VueI18nSee [TranslationProps](component#translationprops)\n * @VueI18nSee [BaseFormatProps](component#baseformatprops)\n * @VueI18nSee [Component Interpolation](../guide/advanced/component)\n *\n * @example\n * ```html\n * \n * \n * \n * {{ $t('tos') }}\n * \n * \n * \n * ```\n * ```js\n * import { createApp } from 'vue'\n * import { createI18n } from 'vue-i18n'\n *\n * const messages = {\n * en: {\n * tos: 'Term of Service',\n * term: 'I accept xxx {0}.'\n * },\n * ja: {\n * tos: '利用規約',\n * term: '私は xxx の{0}に同意します。'\n * }\n * }\n *\n * const i18n = createI18n({\n * locale: 'en',\n * messages\n * })\n *\n * const app = createApp({\n * data: {\n * url: '/term'\n * }\n * }).use(i18n).mount('#app')\n * ```\n *\n * @VueI18nComponent\n */\nconst Translation = TranslationImpl;\nconst I18nT = Translation;\n\nfunction isVNode(target) {\n return isArray(target) && !isString(target[0]);\n}\nfunction renderFormatter(props, context, slotKeys, partFormatter) {\n const { slots, attrs } = context;\n return () => {\n const options = { part: true };\n let overrides = {};\n if (props.locale) {\n options.locale = props.locale;\n }\n if (isString(props.format)) {\n options.key = props.format;\n }\n else if (isObject(props.format)) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if (isString(props.format.key)) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n options.key = props.format.key;\n }\n // Filter out number format options only\n overrides = Object.keys(props.format).reduce((options, prop) => {\n return slotKeys.includes(prop)\n ? assign({}, options, { [prop]: props.format[prop] }) // eslint-disable-line @typescript-eslint/no-explicit-any\n : options;\n }, {});\n }\n const parts = partFormatter(...[props.value, options, overrides]);\n let children = [options.key];\n if (isArray(parts)) {\n children = parts.map((part, index) => {\n const slot = slots[part.type];\n const node = slot\n ? slot({ [part.type]: part.value, index, parts })\n : [part.value];\n if (isVNode(node)) {\n node[0].key = `${part.type}-${index}`;\n }\n return node;\n });\n }\n else if (isString(parts)) {\n children = [parts];\n }\n const assignedAttrs = assign({}, attrs);\n const tag = isString(props.tag) || isObject(props.tag)\n ? props.tag\n : getFragmentableTag();\n return h(tag, assignedAttrs, children);\n };\n}\n\nconst NumberFormatImpl = /*#__PURE__*/ defineComponent({\n /* eslint-disable */\n name: 'i18n-n',\n props: assign({\n value: {\n type: Number,\n required: true\n },\n format: {\n type: [String, Object]\n }\n }, baseFormatProps),\n /* eslint-enable */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n setup(props, context) {\n const i18n = props.i18n ||\n useI18n({\n useScope: props.scope,\n __useComponent: true\n });\n return renderFormatter(props, context, NUMBER_FORMAT_OPTIONS_KEYS, (...args) => \n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n i18n[NumberPartsSymbol](...args));\n }\n});\n/**\n * export the public type for h/tsx inference\n * also to avoid inline import() in generated d.ts files\n */\n/**\n * Number Format Component\n *\n * @remarks\n * See the following items for property about details\n *\n * @VueI18nSee [FormattableProps](component#formattableprops)\n * @VueI18nSee [BaseFormatProps](component#baseformatprops)\n * @VueI18nSee [Custom Formatting](../guide/essentials/number#custom-formatting)\n *\n * @VueI18nDanger\n * Not supported IE, due to no support `Intl.NumberFormat#formatToParts` in [IE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/formatToParts)\n *\n * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-numberformat)\n *\n * @VueI18nComponent\n */\nconst NumberFormat = NumberFormatImpl;\nconst I18nN = NumberFormat;\n\nconst DatetimeFormatImpl = /* #__PURE__*/ defineComponent({\n /* eslint-disable */\n name: 'i18n-d',\n props: assign({\n value: {\n type: [Number, Date],\n required: true\n },\n format: {\n type: [String, Object]\n }\n }, baseFormatProps),\n /* eslint-enable */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n setup(props, context) {\n const i18n = props.i18n ||\n useI18n({\n useScope: props.scope,\n __useComponent: true\n });\n return renderFormatter(props, context, DATETIME_FORMAT_OPTIONS_KEYS, (...args) => \n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n i18n[DatetimePartsSymbol](...args));\n }\n});\n/**\n * Datetime Format Component\n *\n * @remarks\n * See the following items for property about details\n *\n * @VueI18nSee [FormattableProps](component#formattableprops)\n * @VueI18nSee [BaseFormatProps](component#baseformatprops)\n * @VueI18nSee [Custom Formatting](../guide/essentials/datetime#custom-formatting)\n *\n * @VueI18nDanger\n * Not supported IE, due to no support `Intl.DateTimeFormat#formatToParts` in [IE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/formatToParts)\n *\n * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-datetimeformat)\n *\n * @VueI18nComponent\n */\nconst DatetimeFormat = DatetimeFormatImpl;\nconst I18nD = DatetimeFormat;\n\nfunction getComposer$2(i18n, instance) {\n const i18nInternal = i18n;\n if (i18n.mode === 'composition') {\n return (i18nInternal.__getInstance(instance) || i18n.global);\n }\n else {\n const vueI18n = i18nInternal.__getInstance(instance);\n return vueI18n != null\n ? vueI18n.__composer\n : i18n.global.__composer;\n }\n}\nfunction vTDirective(i18n) {\n const _process = (binding) => {\n const { instance, modifiers, value } = binding;\n /* istanbul ignore if */\n if (!instance || !instance.$) {\n throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);\n }\n const composer = getComposer$2(i18n, instance.$);\n if ((process.env.NODE_ENV !== 'production') && modifiers.preserve) {\n warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_PRESERVE));\n }\n const parsedValue = parseValue(value);\n return [\n Reflect.apply(composer.t, composer, [...makeParams(parsedValue)]),\n composer\n ];\n };\n const register = (el, binding) => {\n const [textContent, composer] = _process(binding);\n if (inBrowser && i18n.global === composer) {\n // global scope only\n el.__i18nWatcher = watch(composer.locale, () => {\n binding.instance && binding.instance.$forceUpdate();\n });\n }\n el.__composer = composer;\n el.textContent = textContent;\n };\n const unregister = (el) => {\n if (inBrowser && el.__i18nWatcher) {\n el.__i18nWatcher();\n el.__i18nWatcher = undefined;\n delete el.__i18nWatcher;\n }\n if (el.__composer) {\n el.__composer = undefined;\n delete el.__composer;\n }\n };\n const update = (el, { value }) => {\n if (el.__composer) {\n const composer = el.__composer;\n const parsedValue = parseValue(value);\n el.textContent = Reflect.apply(composer.t, composer, [\n ...makeParams(parsedValue)\n ]);\n }\n };\n const getSSRProps = (binding) => {\n const [textContent] = _process(binding);\n return { textContent };\n };\n return {\n created: register,\n unmounted: unregister,\n beforeUpdate: update,\n getSSRProps\n };\n}\nfunction parseValue(value) {\n if (isString(value)) {\n return { path: value };\n }\n else if (isPlainObject(value)) {\n if (!('path' in value)) {\n throw createI18nError(I18nErrorCodes.REQUIRED_VALUE, 'path');\n }\n return value;\n }\n else {\n throw createI18nError(I18nErrorCodes.INVALID_VALUE);\n }\n}\nfunction makeParams(value) {\n const { path, locale, args, choice, plural } = value;\n const options = {};\n const named = args || {};\n if (isString(locale)) {\n options.locale = locale;\n }\n if (isNumber(choice)) {\n options.plural = choice;\n }\n if (isNumber(plural)) {\n options.plural = plural;\n }\n return [path, named, options];\n}\n\nfunction apply(app, i18n, ...options) {\n const pluginOptions = isPlainObject(options[0])\n ? options[0]\n : {};\n const useI18nComponentName = !!pluginOptions.useI18nComponentName;\n const globalInstall = isBoolean(pluginOptions.globalInstall)\n ? pluginOptions.globalInstall\n : true;\n if ((process.env.NODE_ENV !== 'production') && globalInstall && useI18nComponentName) {\n warn(getWarnMessage(I18nWarnCodes.COMPONENT_NAME_LEGACY_COMPATIBLE, {\n name: Translation.name\n }));\n }\n if (globalInstall) {\n [!useI18nComponentName ? Translation.name : 'i18n', 'I18nT'].forEach(name => app.component(name, Translation));\n [NumberFormat.name, 'I18nN'].forEach(name => app.component(name, NumberFormat));\n [DatetimeFormat.name, 'I18nD'].forEach(name => app.component(name, DatetimeFormat));\n }\n // install directive\n {\n app.directive('t', vTDirective(i18n));\n }\n}\n\nconst VueDevToolsLabels = {\n [\"vue-devtools-plugin-vue-i18n\" /* VueDevToolsIDs.PLUGIN */]: 'Vue I18n devtools',\n [\"vue-i18n-resource-inspector\" /* VueDevToolsIDs.CUSTOM_INSPECTOR */]: 'I18n Resources',\n [\"vue-i18n-timeline\" /* VueDevToolsIDs.TIMELINE */]: 'Vue I18n'\n};\nconst VueDevToolsPlaceholders = {\n [\"vue-i18n-resource-inspector\" /* VueDevToolsIDs.CUSTOM_INSPECTOR */]: 'Search for scopes ...'\n};\nconst VueDevToolsTimelineColors = {\n [\"vue-i18n-timeline\" /* VueDevToolsIDs.TIMELINE */]: 0xffcd19\n};\n\nconst VUE_I18N_COMPONENT_TYPES = 'vue-i18n: composer properties';\nlet devtoolsApi;\nasync function enableDevTools(app, i18n) {\n return new Promise((resolve, reject) => {\n try {\n setupDevtoolsPlugin({\n id: \"vue-devtools-plugin-vue-i18n\" /* VueDevToolsIDs.PLUGIN */,\n label: VueDevToolsLabels[\"vue-devtools-plugin-vue-i18n\" /* VueDevToolsIDs.PLUGIN */],\n packageName: 'vue-i18n',\n homepage: 'https://vue-i18n.intlify.dev',\n logo: 'https://vue-i18n.intlify.dev/vue-i18n-devtools-logo.png',\n componentStateTypes: [VUE_I18N_COMPONENT_TYPES],\n app: app // eslint-disable-line @typescript-eslint/no-explicit-any\n }, api => {\n devtoolsApi = api;\n api.on.visitComponentTree(({ componentInstance, treeNode }) => {\n updateComponentTreeTags(componentInstance, treeNode, i18n);\n });\n api.on.inspectComponent(({ componentInstance, instanceData }) => {\n if (componentInstance.vnode.el &&\n componentInstance.vnode.el.__VUE_I18N__ &&\n instanceData) {\n if (i18n.mode === 'legacy') {\n // ignore global scope on legacy mode\n if (componentInstance.vnode.el.__VUE_I18N__ !==\n i18n.global.__composer) {\n inspectComposer(instanceData, componentInstance.vnode.el.__VUE_I18N__);\n }\n }\n else {\n inspectComposer(instanceData, componentInstance.vnode.el.__VUE_I18N__);\n }\n }\n });\n api.addInspector({\n id: \"vue-i18n-resource-inspector\" /* VueDevToolsIDs.CUSTOM_INSPECTOR */,\n label: VueDevToolsLabels[\"vue-i18n-resource-inspector\" /* VueDevToolsIDs.CUSTOM_INSPECTOR */],\n icon: 'language',\n treeFilterPlaceholder: VueDevToolsPlaceholders[\"vue-i18n-resource-inspector\" /* VueDevToolsIDs.CUSTOM_INSPECTOR */]\n });\n api.on.getInspectorTree(payload => {\n if (payload.app === app &&\n payload.inspectorId === \"vue-i18n-resource-inspector\" /* VueDevToolsIDs.CUSTOM_INSPECTOR */) {\n registerScope(payload, i18n);\n }\n });\n const roots = new Map();\n api.on.getInspectorState(async (payload) => {\n if (payload.app === app &&\n payload.inspectorId === \"vue-i18n-resource-inspector\" /* VueDevToolsIDs.CUSTOM_INSPECTOR */) {\n api.unhighlightElement();\n inspectScope(payload, i18n);\n if (payload.nodeId === 'global') {\n if (!roots.has(payload.app)) {\n const [root] = await api.getComponentInstances(payload.app);\n roots.set(payload.app, root);\n }\n api.highlightElement(roots.get(payload.app));\n }\n else {\n const instance = getComponentInstance(payload.nodeId, i18n);\n instance && api.highlightElement(instance);\n }\n }\n });\n api.on.editInspectorState(payload => {\n if (payload.app === app &&\n payload.inspectorId === \"vue-i18n-resource-inspector\" /* VueDevToolsIDs.CUSTOM_INSPECTOR */) {\n editScope(payload, i18n);\n }\n });\n api.addTimelineLayer({\n id: \"vue-i18n-timeline\" /* VueDevToolsIDs.TIMELINE */,\n label: VueDevToolsLabels[\"vue-i18n-timeline\" /* VueDevToolsIDs.TIMELINE */],\n color: VueDevToolsTimelineColors[\"vue-i18n-timeline\" /* VueDevToolsIDs.TIMELINE */]\n });\n resolve(true);\n });\n }\n catch (e) {\n console.error(e);\n reject(false);\n }\n });\n}\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getI18nScopeLable(instance) {\n return (instance.type.name ||\n instance.type.displayName ||\n instance.type.__file ||\n 'Anonymous');\n}\nfunction updateComponentTreeTags(instance, // eslint-disable-line @typescript-eslint/no-explicit-any\ntreeNode, i18n) {\n // prettier-ignore\n const global = i18n.mode === 'composition'\n ? i18n.global\n : i18n.global.__composer;\n if (instance && instance.vnode.el && instance.vnode.el.__VUE_I18N__) {\n // add custom tags local scope only\n if (instance.vnode.el.__VUE_I18N__ !== global) {\n const tag = {\n label: `i18n (${getI18nScopeLable(instance)} Scope)`,\n textColor: 0x000000,\n backgroundColor: 0xffcd19\n };\n treeNode.tags.push(tag);\n }\n }\n}\nfunction inspectComposer(instanceData, composer) {\n const type = VUE_I18N_COMPONENT_TYPES;\n instanceData.state.push({\n type,\n key: 'locale',\n editable: true,\n value: composer.locale.value\n });\n instanceData.state.push({\n type,\n key: 'availableLocales',\n editable: false,\n value: composer.availableLocales\n });\n instanceData.state.push({\n type,\n key: 'fallbackLocale',\n editable: true,\n value: composer.fallbackLocale.value\n });\n instanceData.state.push({\n type,\n key: 'inheritLocale',\n editable: true,\n value: composer.inheritLocale\n });\n instanceData.state.push({\n type,\n key: 'messages',\n editable: false,\n value: getLocaleMessageValue(composer.messages.value)\n });\n {\n instanceData.state.push({\n type,\n key: 'datetimeFormats',\n editable: false,\n value: composer.datetimeFormats.value\n });\n instanceData.state.push({\n type,\n key: 'numberFormats',\n editable: false,\n value: composer.numberFormats.value\n });\n }\n}\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getLocaleMessageValue(messages) {\n const value = {};\n Object.keys(messages).forEach((key) => {\n const v = messages[key];\n if (isFunction(v) && 'source' in v) {\n value[key] = getMessageFunctionDetails(v);\n }\n else if (isMessageAST(v) && v.loc && v.loc.source) {\n value[key] = v.loc.source;\n }\n else if (isObject(v)) {\n value[key] = getLocaleMessageValue(v);\n }\n else {\n value[key] = v;\n }\n });\n return value;\n}\nconst ESC = {\n '<': '<',\n '>': '>',\n '\"': '"',\n '&': '&'\n};\nfunction escape(s) {\n return s.replace(/[<>\"&]/g, escapeChar);\n}\nfunction escapeChar(a) {\n return ESC[a] || a;\n}\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getMessageFunctionDetails(func) {\n const argString = func.source ? `(\"${escape(func.source)}\")` : `(?)`;\n return {\n _custom: {\n type: 'function',\n display: `ƒ ${argString}`\n }\n };\n}\nfunction registerScope(payload, i18n) {\n payload.rootNodes.push({\n id: 'global',\n label: 'Global Scope'\n });\n // prettier-ignore\n const global = i18n.mode === 'composition'\n ? i18n.global\n : i18n.global.__composer;\n for (const [keyInstance, instance] of i18n.__instances) {\n // prettier-ignore\n const composer = i18n.mode === 'composition'\n ? instance\n : instance.__composer;\n if (global === composer) {\n continue;\n }\n payload.rootNodes.push({\n id: composer.id.toString(),\n label: `${getI18nScopeLable(keyInstance)} Scope`\n });\n }\n}\nfunction getComponentInstance(nodeId, i18n) {\n let instance = null;\n if (nodeId !== 'global') {\n for (const [component, composer] of i18n.__instances.entries()) {\n if (composer.id.toString() === nodeId) {\n instance = component;\n break;\n }\n }\n }\n return instance;\n}\nfunction getComposer$1(nodeId, i18n) {\n if (nodeId === 'global') {\n return i18n.mode === 'composition'\n ? i18n.global\n : i18n.global.__composer;\n }\n else {\n const instance = Array.from(i18n.__instances.values()).find(item => item.id.toString() === nodeId);\n if (instance) {\n return i18n.mode === 'composition'\n ? instance\n : instance.__composer;\n }\n else {\n return null;\n }\n }\n}\nfunction inspectScope(payload, i18n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\n) {\n const composer = getComposer$1(payload.nodeId, i18n);\n if (composer) {\n // TODO:\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n payload.state = makeScopeInspectState(composer);\n }\n return null;\n}\nfunction makeScopeInspectState(composer) {\n const state = {};\n const localeType = 'Locale related info';\n const localeStates = [\n {\n type: localeType,\n key: 'locale',\n editable: true,\n value: composer.locale.value\n },\n {\n type: localeType,\n key: 'fallbackLocale',\n editable: true,\n value: composer.fallbackLocale.value\n },\n {\n type: localeType,\n key: 'availableLocales',\n editable: false,\n value: composer.availableLocales\n },\n {\n type: localeType,\n key: 'inheritLocale',\n editable: true,\n value: composer.inheritLocale\n }\n ];\n state[localeType] = localeStates;\n const localeMessagesType = 'Locale messages info';\n const localeMessagesStates = [\n {\n type: localeMessagesType,\n key: 'messages',\n editable: false,\n value: getLocaleMessageValue(composer.messages.value)\n }\n ];\n state[localeMessagesType] = localeMessagesStates;\n {\n const datetimeFormatsType = 'Datetime formats info';\n const datetimeFormatsStates = [\n {\n type: datetimeFormatsType,\n key: 'datetimeFormats',\n editable: false,\n value: composer.datetimeFormats.value\n }\n ];\n state[datetimeFormatsType] = datetimeFormatsStates;\n const numberFormatsType = 'Datetime formats info';\n const numberFormatsStates = [\n {\n type: numberFormatsType,\n key: 'numberFormats',\n editable: false,\n value: composer.numberFormats.value\n }\n ];\n state[numberFormatsType] = numberFormatsStates;\n }\n return state;\n}\nfunction addTimelineEvent(event, payload) {\n if (devtoolsApi) {\n let groupId;\n if (payload && 'groupId' in payload) {\n groupId = payload.groupId;\n delete payload.groupId;\n }\n devtoolsApi.addTimelineEvent({\n layerId: \"vue-i18n-timeline\" /* VueDevToolsIDs.TIMELINE */,\n event: {\n title: event,\n groupId,\n time: Date.now(),\n meta: {},\n data: payload || {},\n logType: event === \"compile-error\" /* VueDevToolsTimelineEvents.COMPILE_ERROR */\n ? 'error'\n : event === \"fallback\" /* VueDevToolsTimelineEvents.FALBACK */ ||\n event === \"missing\" /* VueDevToolsTimelineEvents.MISSING */\n ? 'warning'\n : 'default'\n }\n });\n }\n}\nfunction editScope(payload, i18n) {\n const composer = getComposer$1(payload.nodeId, i18n);\n if (composer) {\n const [field] = payload.path;\n if (field === 'locale' && isString(payload.state.value)) {\n composer.locale.value = payload.state.value;\n }\n else if (field === 'fallbackLocale' &&\n (isString(payload.state.value) ||\n isArray(payload.state.value) ||\n isObject(payload.state.value))) {\n composer.fallbackLocale.value = payload.state.value;\n }\n else if (field === 'inheritLocale' && isBoolean(payload.state.value)) {\n composer.inheritLocale = payload.state.value;\n }\n }\n}\n\n/**\n * Supports compatibility for legacy vue-i18n APIs\n * This mixin is used when we use vue-i18n@v9.x or later\n */\nfunction defineMixin(vuei18n, composer, i18n) {\n return {\n beforeCreate() {\n const instance = getCurrentInstance();\n /* istanbul ignore if */\n if (!instance) {\n throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);\n }\n const options = this.$options;\n if (options.i18n) {\n const optionsI18n = options.i18n;\n if (options.__i18n) {\n optionsI18n.__i18n = options.__i18n;\n }\n optionsI18n.__root = composer;\n if (this === this.$root) {\n // merge option and gttach global\n this.$i18n = mergeToGlobal(vuei18n, optionsI18n);\n }\n else {\n optionsI18n.__injectWithOption = true;\n optionsI18n.__extender = i18n.__vueI18nExtend;\n // atttach local VueI18n instance\n this.$i18n = createVueI18n(optionsI18n);\n // extend VueI18n instance\n const _vueI18n = this.$i18n;\n if (_vueI18n.__extender) {\n _vueI18n.__disposer = _vueI18n.__extender(this.$i18n);\n }\n }\n }\n else if (options.__i18n) {\n if (this === this.$root) {\n // merge option and gttach global\n this.$i18n = mergeToGlobal(vuei18n, options);\n }\n else {\n // atttach local VueI18n instance\n this.$i18n = createVueI18n({\n __i18n: options.__i18n,\n __injectWithOption: true,\n __extender: i18n.__vueI18nExtend,\n __root: composer\n });\n // extend VueI18n instance\n const _vueI18n = this.$i18n;\n if (_vueI18n.__extender) {\n _vueI18n.__disposer = _vueI18n.__extender(this.$i18n);\n }\n }\n }\n else {\n // attach global VueI18n instance\n this.$i18n = vuei18n;\n }\n if (options.__i18nGlobal) {\n adjustI18nResources(composer, options, options);\n }\n // defines vue-i18n legacy APIs\n this.$t = (...args) => this.$i18n.t(...args);\n this.$rt = (...args) => this.$i18n.rt(...args);\n this.$tc = (...args) => this.$i18n.tc(...args);\n this.$te = (key, locale) => this.$i18n.te(key, locale);\n this.$d = (...args) => this.$i18n.d(...args);\n this.$n = (...args) => this.$i18n.n(...args);\n this.$tm = (key) => this.$i18n.tm(key);\n i18n.__setInstance(instance, this.$i18n);\n },\n mounted() {\n /* istanbul ignore if */\n if (((process.env.NODE_ENV !== 'production') || __VUE_PROD_DEVTOOLS__) &&\n !false &&\n this.$el &&\n this.$i18n) {\n const _vueI18n = this.$i18n;\n this.$el.__VUE_I18N__ = _vueI18n.__composer;\n const emitter = (this.__v_emitter =\n createEmitter());\n _vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter);\n emitter.on('*', addTimelineEvent);\n }\n },\n unmounted() {\n const instance = getCurrentInstance();\n /* istanbul ignore if */\n if (!instance) {\n throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);\n }\n const _vueI18n = this.$i18n;\n /* istanbul ignore if */\n if (((process.env.NODE_ENV !== 'production') || __VUE_PROD_DEVTOOLS__) &&\n !false &&\n this.$el &&\n this.$el.__VUE_I18N__) {\n if (this.__v_emitter) {\n this.__v_emitter.off('*', addTimelineEvent);\n delete this.__v_emitter;\n }\n if (this.$i18n) {\n _vueI18n.__disableEmitter && _vueI18n.__disableEmitter();\n delete this.$el.__VUE_I18N__;\n }\n }\n delete this.$t;\n delete this.$rt;\n delete this.$tc;\n delete this.$te;\n delete this.$d;\n delete this.$n;\n delete this.$tm;\n if (_vueI18n.__disposer) {\n _vueI18n.__disposer();\n delete _vueI18n.__disposer;\n delete _vueI18n.__extender;\n }\n i18n.__deleteInstance(instance);\n delete this.$i18n;\n }\n };\n}\nfunction mergeToGlobal(g, options) {\n g.locale = options.locale || g.locale;\n g.fallbackLocale = options.fallbackLocale || g.fallbackLocale;\n g.missing = options.missing || g.missing;\n g.silentTranslationWarn =\n options.silentTranslationWarn || g.silentFallbackWarn;\n g.silentFallbackWarn = options.silentFallbackWarn || g.silentFallbackWarn;\n g.formatFallbackMessages =\n options.formatFallbackMessages || g.formatFallbackMessages;\n g.postTranslation = options.postTranslation || g.postTranslation;\n g.warnHtmlInMessage = options.warnHtmlInMessage || g.warnHtmlInMessage;\n g.escapeParameterHtml = options.escapeParameterHtml || g.escapeParameterHtml;\n g.sync = options.sync || g.sync;\n g.__composer[SetPluralRulesSymbol](options.pluralizationRules || g.pluralizationRules);\n const messages = getLocaleMessages(g.locale, {\n messages: options.messages,\n __i18n: options.__i18n\n });\n Object.keys(messages).forEach(locale => g.mergeLocaleMessage(locale, messages[locale]));\n if (options.datetimeFormats) {\n Object.keys(options.datetimeFormats).forEach(locale => g.mergeDateTimeFormat(locale, options.datetimeFormats[locale]));\n }\n if (options.numberFormats) {\n Object.keys(options.numberFormats).forEach(locale => g.mergeNumberFormat(locale, options.numberFormats[locale]));\n }\n return g;\n}\n\n/**\n * Injection key for {@link useI18n}\n *\n * @remarks\n * The global injection key for I18n instances with `useI18n`. this injection key is used in Web Components.\n * Specify the i18n instance created by {@link createI18n} together with `provide` function.\n *\n * @VueI18nGeneral\n */\nconst I18nInjectionKey = \n/* #__PURE__*/ makeSymbol('global-vue-i18n');\n// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\nfunction createI18n(options = {}, VueI18nLegacy) {\n // prettier-ignore\n const __legacyMode = __VUE_I18N_LEGACY_API__ && isBoolean(options.legacy)\n ? options.legacy\n : __VUE_I18N_LEGACY_API__;\n // prettier-ignore\n const __globalInjection = isBoolean(options.globalInjection)\n ? options.globalInjection\n : true;\n // prettier-ignore\n const __allowComposition = __VUE_I18N_LEGACY_API__ && __legacyMode\n ? !!options.allowComposition\n : true;\n const __instances = new Map();\n const [globalScope, __global] = createGlobal(options, __legacyMode);\n const symbol = /* #__PURE__*/ makeSymbol((process.env.NODE_ENV !== 'production') ? 'vue-i18n' : '');\n if ((process.env.NODE_ENV !== 'production')) {\n if (__legacyMode && __allowComposition && !false) {\n warn(getWarnMessage(I18nWarnCodes.NOTICE_DROP_ALLOW_COMPOSITION));\n }\n }\n function __getInstance(component) {\n return __instances.get(component) || null;\n }\n function __setInstance(component, instance) {\n __instances.set(component, instance);\n }\n function __deleteInstance(component) {\n __instances.delete(component);\n }\n {\n const i18n = {\n // mode\n get mode() {\n return __VUE_I18N_LEGACY_API__ && __legacyMode\n ? 'legacy'\n : 'composition';\n },\n // allowComposition\n get allowComposition() {\n return __allowComposition;\n },\n // install plugin\n async install(app, ...options) {\n if (((process.env.NODE_ENV !== 'production') || __VUE_PROD_DEVTOOLS__) &&\n !false) {\n app.__VUE_I18N__ = i18n;\n }\n // setup global provider\n app.__VUE_I18N_SYMBOL__ = symbol;\n app.provide(app.__VUE_I18N_SYMBOL__, i18n);\n // set composer & vuei18n extend hook options from plugin options\n if (isPlainObject(options[0])) {\n const opts = options[0];\n i18n.__composerExtend =\n opts.__composerExtend;\n i18n.__vueI18nExtend =\n opts.__vueI18nExtend;\n }\n // global method and properties injection for Composition API\n let globalReleaseHandler = null;\n if (!__legacyMode && __globalInjection) {\n globalReleaseHandler = injectGlobalFields(app, i18n.global);\n }\n // install built-in components and directive\n if (__VUE_I18N_FULL_INSTALL__) {\n apply(app, i18n, ...options);\n }\n // setup mixin for Legacy API\n if (__VUE_I18N_LEGACY_API__ && __legacyMode) {\n app.mixin(defineMixin(__global, __global.__composer, i18n));\n }\n // release global scope\n const unmountApp = app.unmount;\n app.unmount = () => {\n globalReleaseHandler && globalReleaseHandler();\n i18n.dispose();\n unmountApp();\n };\n // setup vue-devtools plugin\n if (((process.env.NODE_ENV !== 'production') || __VUE_PROD_DEVTOOLS__) && !false) {\n const ret = await enableDevTools(app, i18n);\n if (!ret) {\n throw createI18nError(I18nErrorCodes.CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN);\n }\n const emitter = createEmitter();\n if (__legacyMode) {\n const _vueI18n = __global;\n _vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter);\n }\n else {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const _composer = __global;\n _composer[EnableEmitter] && _composer[EnableEmitter](emitter);\n }\n emitter.on('*', addTimelineEvent);\n }\n },\n // global accessor\n get global() {\n return __global;\n },\n dispose() {\n globalScope.stop();\n },\n // @internal\n __instances,\n // @internal\n __getInstance,\n // @internal\n __setInstance,\n // @internal\n __deleteInstance\n };\n return i18n;\n }\n}\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nfunction useI18n(options = {}) {\n const instance = getCurrentInstance();\n if (instance == null) {\n throw createI18nError(I18nErrorCodes.MUST_BE_CALL_SETUP_TOP);\n }\n if (!instance.isCE &&\n instance.appContext.app != null &&\n !instance.appContext.app.__VUE_I18N_SYMBOL__) {\n throw createI18nError(I18nErrorCodes.NOT_INSTALLED);\n }\n const i18n = getI18nInstance(instance);\n const gl = getGlobalComposer(i18n);\n const componentOptions = getComponentOptions(instance);\n const scope = getScope(options, componentOptions);\n if (__VUE_I18N_LEGACY_API__) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if (i18n.mode === 'legacy' && !options.__useComponent) {\n if (!i18n.allowComposition) {\n throw createI18nError(I18nErrorCodes.NOT_AVAILABLE_IN_LEGACY_MODE);\n }\n return useI18nForLegacy(instance, scope, gl, options);\n }\n }\n if (scope === 'global') {\n adjustI18nResources(gl, options, componentOptions);\n return gl;\n }\n if (scope === 'parent') {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let composer = getComposer(i18n, instance, options.__useComponent);\n if (composer == null) {\n if ((process.env.NODE_ENV !== 'production')) {\n warn(getWarnMessage(I18nWarnCodes.NOT_FOUND_PARENT_SCOPE));\n }\n composer = gl;\n }\n return composer;\n }\n const i18nInternal = i18n;\n let composer = i18nInternal.__getInstance(instance);\n if (composer == null) {\n const composerOptions = assign({}, options);\n if ('__i18n' in componentOptions) {\n composerOptions.__i18n = componentOptions.__i18n;\n }\n if (gl) {\n composerOptions.__root = gl;\n }\n composer = createComposer(composerOptions);\n if (i18nInternal.__composerExtend) {\n composer[DisposeSymbol] =\n i18nInternal.__composerExtend(composer);\n }\n setupLifeCycle(i18nInternal, instance, composer);\n i18nInternal.__setInstance(instance, composer);\n }\n return composer;\n}\n/**\n * Cast to VueI18n legacy compatible type\n *\n * @remarks\n * This API is provided only with [vue-i18n-bridge](https://vue-i18n.intlify.dev/guide/migration/ways.html#what-is-vue-i18n-bridge).\n *\n * The purpose of this function is to convert an {@link I18n} instance created with {@link createI18n | createI18n(legacy: true)} into a `vue-i18n@v8.x` compatible instance of `new VueI18n` in a TypeScript environment.\n *\n * @param i18n - An instance of {@link I18n}\n * @returns A i18n instance which is casted to {@link VueI18n} type\n *\n * @VueI18nTip\n * :new: provided by **vue-i18n-bridge only**\n *\n * @VueI18nGeneral\n */\n/* #__NO_SIDE_EFFECTS__ */\nconst castToVueI18n = (i18n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\n) => {\n if (!(__VUE_I18N_BRIDGE__ in i18n)) {\n throw createI18nError(I18nErrorCodes.NOT_COMPATIBLE_LEGACY_VUE_I18N);\n }\n return i18n;\n};\nfunction createGlobal(options, legacyMode, VueI18nLegacy // eslint-disable-line @typescript-eslint/no-explicit-any\n) {\n const scope = effectScope();\n {\n const obj = __VUE_I18N_LEGACY_API__ && legacyMode\n ? scope.run(() => createVueI18n(options))\n : scope.run(() => createComposer(options));\n if (obj == null) {\n throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);\n }\n return [scope, obj];\n }\n}\nfunction getI18nInstance(instance) {\n {\n const i18n = inject(!instance.isCE\n ? instance.appContext.app.__VUE_I18N_SYMBOL__\n : I18nInjectionKey);\n /* istanbul ignore if */\n if (!i18n) {\n throw createI18nError(!instance.isCE\n ? I18nErrorCodes.UNEXPECTED_ERROR\n : I18nErrorCodes.NOT_INSTALLED_WITH_PROVIDE);\n }\n return i18n;\n }\n}\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getScope(options, componentOptions) {\n // prettier-ignore\n return isEmptyObject(options)\n ? ('__i18n' in componentOptions)\n ? 'local'\n : 'global'\n : !options.useScope\n ? 'local'\n : options.useScope;\n}\nfunction getGlobalComposer(i18n) {\n // prettier-ignore\n return i18n.mode === 'composition'\n ? i18n.global\n : i18n.global.__composer\n ;\n}\nfunction getComposer(i18n, target, useComponent = false) {\n let composer = null;\n const root = target.root;\n let current = getParentComponentInstance(target, useComponent);\n while (current != null) {\n const i18nInternal = i18n;\n if (i18n.mode === 'composition') {\n composer = i18nInternal.__getInstance(current);\n }\n else {\n if (__VUE_I18N_LEGACY_API__) {\n const vueI18n = i18nInternal.__getInstance(current);\n if (vueI18n != null) {\n composer = vueI18n\n .__composer;\n if (useComponent &&\n composer &&\n !composer[InejctWithOptionSymbol] // eslint-disable-line @typescript-eslint/no-explicit-any\n ) {\n composer = null;\n }\n }\n }\n }\n if (composer != null) {\n break;\n }\n if (root === current) {\n break;\n }\n current = current.parent;\n }\n return composer;\n}\nfunction getParentComponentInstance(target, useComponent = false) {\n if (target == null) {\n return null;\n }\n {\n // if `useComponent: true` will be specified, we get lexical scope owner instance for use-case slots\n return !useComponent\n ? target.parent\n : target.vnode.ctx || target.parent; // eslint-disable-line @typescript-eslint/no-explicit-any\n }\n}\nfunction setupLifeCycle(i18n, target, composer) {\n let emitter = null;\n {\n onMounted(() => {\n // inject composer instance to DOM for intlify-devtools\n if (((process.env.NODE_ENV !== 'production') || __VUE_PROD_DEVTOOLS__) &&\n !false &&\n target.vnode.el) {\n target.vnode.el.__VUE_I18N__ = composer;\n emitter = createEmitter();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const _composer = composer;\n _composer[EnableEmitter] && _composer[EnableEmitter](emitter);\n emitter.on('*', addTimelineEvent);\n }\n }, target);\n onUnmounted(() => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const _composer = composer;\n // remove composer instance from DOM for intlify-devtools\n if (((process.env.NODE_ENV !== 'production') || __VUE_PROD_DEVTOOLS__) &&\n !false &&\n target.vnode.el &&\n target.vnode.el.__VUE_I18N__) {\n emitter && emitter.off('*', addTimelineEvent);\n _composer[DisableEmitter] && _composer[DisableEmitter]();\n delete target.vnode.el.__VUE_I18N__;\n }\n i18n.__deleteInstance(target);\n // dispose extended resources\n const dispose = _composer[DisposeSymbol];\n if (dispose) {\n dispose();\n delete _composer[DisposeSymbol];\n }\n }, target);\n }\n}\nfunction useI18nForLegacy(instance, scope, root, options = {} // eslint-disable-line @typescript-eslint/no-explicit-any\n) {\n const isLocalScope = scope === 'local';\n const _composer = shallowRef(null);\n if (isLocalScope &&\n instance.proxy &&\n !(instance.proxy.$options.i18n || instance.proxy.$options.__i18n)) {\n throw createI18nError(I18nErrorCodes.MUST_DEFINE_I18N_OPTION_IN_ALLOW_COMPOSITION);\n }\n const _inheritLocale = isBoolean(options.inheritLocale)\n ? options.inheritLocale\n : !isString(options.locale);\n const _locale = ref(\n // prettier-ignore\n !isLocalScope || _inheritLocale\n ? root.locale.value\n : isString(options.locale)\n ? options.locale\n : DEFAULT_LOCALE);\n const _fallbackLocale = ref(\n // prettier-ignore\n !isLocalScope || _inheritLocale\n ? root.fallbackLocale.value\n : isString(options.fallbackLocale) ||\n isArray(options.fallbackLocale) ||\n isPlainObject(options.fallbackLocale) ||\n options.fallbackLocale === false\n ? options.fallbackLocale\n : _locale.value);\n const _messages = ref(getLocaleMessages(_locale.value, options));\n // prettier-ignore\n const _datetimeFormats = ref(isPlainObject(options.datetimeFormats)\n ? options.datetimeFormats\n : { [_locale.value]: {} });\n // prettier-ignore\n const _numberFormats = ref(isPlainObject(options.numberFormats)\n ? options.numberFormats\n : { [_locale.value]: {} });\n // prettier-ignore\n const _missingWarn = isLocalScope\n ? root.missingWarn\n : isBoolean(options.missingWarn) || isRegExp(options.missingWarn)\n ? options.missingWarn\n : true;\n // prettier-ignore\n const _fallbackWarn = isLocalScope\n ? root.fallbackWarn\n : isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)\n ? options.fallbackWarn\n : true;\n // prettier-ignore\n const _fallbackRoot = isLocalScope\n ? root.fallbackRoot\n : isBoolean(options.fallbackRoot)\n ? options.fallbackRoot\n : true;\n // configure fall back to root\n const _fallbackFormat = !!options.fallbackFormat;\n // runtime missing\n const _missing = isFunction(options.missing) ? options.missing : null;\n // postTranslation handler\n const _postTranslation = isFunction(options.postTranslation)\n ? options.postTranslation\n : null;\n // prettier-ignore\n const _warnHtmlMessage = isLocalScope\n ? root.warnHtmlMessage\n : isBoolean(options.warnHtmlMessage)\n ? options.warnHtmlMessage\n : true;\n const _escapeParameter = !!options.escapeParameter;\n // prettier-ignore\n const _modifiers = isLocalScope\n ? root.modifiers\n : isPlainObject(options.modifiers)\n ? options.modifiers\n : {};\n // pluralRules\n const _pluralRules = options.pluralRules || (isLocalScope && root.pluralRules);\n // track reactivity\n function trackReactivityValues() {\n return [\n _locale.value,\n _fallbackLocale.value,\n _messages.value,\n _datetimeFormats.value,\n _numberFormats.value\n ];\n }\n // locale\n const locale = computed({\n get: () => {\n return _composer.value ? _composer.value.locale.value : _locale.value;\n },\n set: val => {\n if (_composer.value) {\n _composer.value.locale.value = val;\n }\n _locale.value = val;\n }\n });\n // fallbackLocale\n const fallbackLocale = computed({\n get: () => {\n return _composer.value\n ? _composer.value.fallbackLocale.value\n : _fallbackLocale.value;\n },\n set: val => {\n if (_composer.value) {\n _composer.value.fallbackLocale.value = val;\n }\n _fallbackLocale.value = val;\n }\n });\n // messages\n const messages = computed(() => {\n if (_composer.value) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return _composer.value.messages.value;\n }\n else {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return _messages.value;\n }\n });\n const datetimeFormats = computed(() => _datetimeFormats.value);\n const numberFormats = computed(() => _numberFormats.value);\n function getPostTranslationHandler() {\n return _composer.value\n ? _composer.value.getPostTranslationHandler()\n : _postTranslation;\n }\n function setPostTranslationHandler(handler) {\n if (_composer.value) {\n _composer.value.setPostTranslationHandler(handler);\n }\n }\n function getMissingHandler() {\n return _composer.value ? _composer.value.getMissingHandler() : _missing;\n }\n function setMissingHandler(handler) {\n if (_composer.value) {\n _composer.value.setMissingHandler(handler);\n }\n }\n function warpWithDeps(fn) {\n trackReactivityValues();\n return fn();\n }\n function t(...args) {\n return _composer.value\n ? warpWithDeps(() => Reflect.apply(_composer.value.t, null, [...args]))\n : warpWithDeps(() => '');\n }\n function rt(...args) {\n return _composer.value\n ? Reflect.apply(_composer.value.rt, null, [...args])\n : '';\n }\n function d(...args) {\n return _composer.value\n ? warpWithDeps(() => Reflect.apply(_composer.value.d, null, [...args]))\n : warpWithDeps(() => '');\n }\n function n(...args) {\n return _composer.value\n ? warpWithDeps(() => Reflect.apply(_composer.value.n, null, [...args]))\n : warpWithDeps(() => '');\n }\n function tm(key) {\n return _composer.value ? _composer.value.tm(key) : {};\n }\n function te(key, locale) {\n return _composer.value ? _composer.value.te(key, locale) : false;\n }\n function getLocaleMessage(locale) {\n return _composer.value ? _composer.value.getLocaleMessage(locale) : {};\n }\n function setLocaleMessage(locale, message) {\n if (_composer.value) {\n _composer.value.setLocaleMessage(locale, message);\n _messages.value[locale] = message;\n }\n }\n function mergeLocaleMessage(locale, message) {\n if (_composer.value) {\n _composer.value.mergeLocaleMessage(locale, message);\n }\n }\n function getDateTimeFormat(locale) {\n return _composer.value ? _composer.value.getDateTimeFormat(locale) : {};\n }\n function setDateTimeFormat(locale, format) {\n if (_composer.value) {\n _composer.value.setDateTimeFormat(locale, format);\n _datetimeFormats.value[locale] = format;\n }\n }\n function mergeDateTimeFormat(locale, format) {\n if (_composer.value) {\n _composer.value.mergeDateTimeFormat(locale, format);\n }\n }\n function getNumberFormat(locale) {\n return _composer.value ? _composer.value.getNumberFormat(locale) : {};\n }\n function setNumberFormat(locale, format) {\n if (_composer.value) {\n _composer.value.setNumberFormat(locale, format);\n _numberFormats.value[locale] = format;\n }\n }\n function mergeNumberFormat(locale, format) {\n if (_composer.value) {\n _composer.value.mergeNumberFormat(locale, format);\n }\n }\n const wrapper = {\n get id() {\n return _composer.value ? _composer.value.id : -1;\n },\n locale,\n fallbackLocale,\n messages,\n datetimeFormats,\n numberFormats,\n get inheritLocale() {\n return _composer.value ? _composer.value.inheritLocale : _inheritLocale;\n },\n set inheritLocale(val) {\n if (_composer.value) {\n _composer.value.inheritLocale = val;\n }\n },\n get availableLocales() {\n return _composer.value\n ? _composer.value.availableLocales\n : Object.keys(_messages.value);\n },\n get modifiers() {\n return (_composer.value ? _composer.value.modifiers : _modifiers);\n },\n get pluralRules() {\n return (_composer.value ? _composer.value.pluralRules : _pluralRules);\n },\n get isGlobal() {\n return _composer.value ? _composer.value.isGlobal : false;\n },\n get missingWarn() {\n return _composer.value ? _composer.value.missingWarn : _missingWarn;\n },\n set missingWarn(val) {\n if (_composer.value) {\n _composer.value.missingWarn = val;\n }\n },\n get fallbackWarn() {\n return _composer.value ? _composer.value.fallbackWarn : _fallbackWarn;\n },\n set fallbackWarn(val) {\n if (_composer.value) {\n _composer.value.missingWarn = val;\n }\n },\n get fallbackRoot() {\n return _composer.value ? _composer.value.fallbackRoot : _fallbackRoot;\n },\n set fallbackRoot(val) {\n if (_composer.value) {\n _composer.value.fallbackRoot = val;\n }\n },\n get fallbackFormat() {\n return _composer.value ? _composer.value.fallbackFormat : _fallbackFormat;\n },\n set fallbackFormat(val) {\n if (_composer.value) {\n _composer.value.fallbackFormat = val;\n }\n },\n get warnHtmlMessage() {\n return _composer.value\n ? _composer.value.warnHtmlMessage\n : _warnHtmlMessage;\n },\n set warnHtmlMessage(val) {\n if (_composer.value) {\n _composer.value.warnHtmlMessage = val;\n }\n },\n get escapeParameter() {\n return _composer.value\n ? _composer.value.escapeParameter\n : _escapeParameter;\n },\n set escapeParameter(val) {\n if (_composer.value) {\n _composer.value.escapeParameter = val;\n }\n },\n t,\n getPostTranslationHandler,\n setPostTranslationHandler,\n getMissingHandler,\n setMissingHandler,\n rt,\n d,\n n,\n tm,\n te,\n getLocaleMessage,\n setLocaleMessage,\n mergeLocaleMessage,\n getDateTimeFormat,\n setDateTimeFormat,\n mergeDateTimeFormat,\n getNumberFormat,\n setNumberFormat,\n mergeNumberFormat\n };\n function sync(composer) {\n composer.locale.value = _locale.value;\n composer.fallbackLocale.value = _fallbackLocale.value;\n Object.keys(_messages.value).forEach(locale => {\n composer.mergeLocaleMessage(locale, _messages.value[locale]);\n });\n Object.keys(_datetimeFormats.value).forEach(locale => {\n composer.mergeDateTimeFormat(locale, _datetimeFormats.value[locale]);\n });\n Object.keys(_numberFormats.value).forEach(locale => {\n composer.mergeNumberFormat(locale, _numberFormats.value[locale]);\n });\n composer.escapeParameter = _escapeParameter;\n composer.fallbackFormat = _fallbackFormat;\n composer.fallbackRoot = _fallbackRoot;\n composer.fallbackWarn = _fallbackWarn;\n composer.missingWarn = _missingWarn;\n composer.warnHtmlMessage = _warnHtmlMessage;\n }\n onBeforeMount(() => {\n if (instance.proxy == null || instance.proxy.$i18n == null) {\n throw createI18nError(I18nErrorCodes.NOT_AVAILABLE_COMPOSITION_IN_LEGACY);\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const composer = (_composer.value = instance.proxy.$i18n\n .__composer);\n if (scope === 'global') {\n _locale.value = composer.locale.value;\n _fallbackLocale.value = composer.fallbackLocale.value;\n _messages.value = composer.messages.value;\n _datetimeFormats.value = composer.datetimeFormats.value;\n _numberFormats.value = composer.numberFormats.value;\n }\n else if (isLocalScope) {\n sync(composer);\n }\n });\n return wrapper;\n}\nconst globalExportProps = [\n 'locale',\n 'fallbackLocale',\n 'availableLocales'\n];\nconst globalExportMethods = ['t', 'rt', 'd', 'n', 'tm', 'te']\n ;\nfunction injectGlobalFields(app, composer) {\n const i18n = Object.create(null);\n globalExportProps.forEach(prop => {\n const desc = Object.getOwnPropertyDescriptor(composer, prop);\n if (!desc) {\n throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);\n }\n const wrap = isRef(desc.value) // check computed props\n ? {\n get() {\n return desc.value.value;\n },\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n set(val) {\n desc.value.value = val;\n }\n }\n : {\n get() {\n return desc.get && desc.get();\n }\n };\n Object.defineProperty(i18n, prop, wrap);\n });\n app.config.globalProperties.$i18n = i18n;\n globalExportMethods.forEach(method => {\n const desc = Object.getOwnPropertyDescriptor(composer, method);\n if (!desc || !desc.value) {\n throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);\n }\n Object.defineProperty(app.config.globalProperties, `$${method}`, desc);\n });\n const dispose = () => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n delete app.config.globalProperties.$i18n;\n globalExportMethods.forEach(method => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n delete app.config.globalProperties[`$${method}`];\n });\n };\n return dispose;\n}\n\n{\n initFeatureFlags();\n}\n// register message compiler at vue-i18n\nif (__INTLIFY_JIT_COMPILATION__) {\n registerMessageCompiler(compile);\n}\nelse {\n registerMessageCompiler(compileToFunction);\n}\n// register message resolver at vue-i18n\nregisterMessageResolver(resolveValue);\n// register fallback locale at vue-i18n\nregisterLocaleFallbacker(fallbackWithLocaleChain);\n// NOTE: experimental !!\nif ((process.env.NODE_ENV !== 'production') || __INTLIFY_PROD_DEVTOOLS__) {\n const target = getGlobalThis();\n target.__INTLIFY__ = true;\n setDevToolsHook(target.__INTLIFY_DEVTOOLS_GLOBAL_HOOK__);\n}\nif ((process.env.NODE_ENV !== 'production')) ;\n\nexport { DatetimeFormat, I18nD, I18nInjectionKey, I18nN, I18nT, NumberFormat, Translation, VERSION, castToVueI18n, createI18n, useI18n, vTDirective };\n","import BaseStyle from '@primevue/core/base/style';\n\nvar theme = function theme(_ref) {\n var dt = _ref.dt;\n return \"\\n.p-tree {\\n background: \".concat(dt('tree.background'), \";\\n color: \").concat(dt('tree.color'), \";\\n padding: \").concat(dt('tree.padding'), \";\\n}\\n\\n.p-tree-root-children,\\n.p-tree-node-children {\\n display: flex;\\n list-style-type: none;\\n flex-direction: column;\\n margin: 0;\\n gap: \").concat(dt('tree.gap'), \";\\n}\\n\\n.p-tree-root-children {\\n padding: \").concat(dt('tree.gap'), \" 0 0 0;\\n}\\n\\n.p-tree-node-children {\\n padding: \").concat(dt('tree.gap'), \" 0 0 \").concat(dt('tree.indent'), \";\\n}\\n\\n.p-tree-node {\\n padding: 0;\\n outline: 0 none;\\n}\\n\\n.p-tree-node-content {\\n border-radius: \").concat(dt('tree.node.border.radius'), \";\\n padding: \").concat(dt('tree.node.padding'), \";\\n display: flex;\\n align-items: center;\\n outline-color: transparent;\\n color: \").concat(dt('tree.node.color'), \";\\n gap: \").concat(dt('tree.node.gap'), \";\\n transition: background \").concat(dt('tree.transition.duration'), \", color \").concat(dt('tree.transition.duration'), \", outline-color \").concat(dt('tree.transition.duration'), \", box-shadow \").concat(dt('tree.transition.duration'), \";\\n}\\n\\n.p-tree-node:focus-visible > .p-tree-node-content {\\n box-shadow: \").concat(dt('tree.node.focus.ring.shadow'), \";\\n outline: \").concat(dt('tree.node.focus.ring.width'), \" \").concat(dt('tree.node.focus.ring.style'), \" \").concat(dt('tree.node.focus.ring.color'), \";\\n outline-offset: \").concat(dt('tree.node.focus.ring.offset'), \";\\n}\\n\\n.p-tree-node-content.p-tree-node-selectable:not(.p-tree-node-selected):hover {\\n background: \").concat(dt('tree.node.hover.background'), \";\\n color: \").concat(dt('tree.node.hover.color'), \";\\n}\\n\\n.p-tree-node-content.p-tree-node-selectable:not(.p-tree-node-selected):hover .p-tree-node-icon {\\n color: \").concat(dt('tree.node.icon.hover.color'), \";\\n}\\n\\n.p-tree-node-content.p-tree-node-selected {\\n background: \").concat(dt('tree.node.selected.background'), \";\\n color: \").concat(dt('tree.node.selected.color'), \";\\n}\\n\\n.p-tree-node-content.p-tree-node-selected .p-tree-node-toggle-button {\\n color: inherit;\\n}\\n\\n.p-tree-node-toggle-button {\\n cursor: pointer;\\n user-select: none;\\n display: inline-flex;\\n align-items: center;\\n justify-content: center;\\n overflow: hidden;\\n position: relative;\\n flex-shrink: 0;\\n width: \").concat(dt('tree.node.toggle.button.size'), \";\\n height: \").concat(dt('tree.node.toggle.button.size'), \";\\n color: \").concat(dt('tree.node.toggle.button.color'), \";\\n border: 0 none;\\n background: transparent;\\n border-radius: \").concat(dt('tree.node.toggle.button.border.radius'), \";\\n transition: background \").concat(dt('tree.transition.duration'), \", color \").concat(dt('tree.transition.duration'), \", border-color \").concat(dt('tree.transition.duration'), \", outline-color \").concat(dt('tree.transition.duration'), \", box-shadow \").concat(dt('tree.transition.duration'), \";\\n outline-color: transparent;\\n padding: 0;\\n}\\n\\n.p-tree-node-toggle-button:enabled:hover {\\n background: \").concat(dt('tree.node.toggle.button.hover.background'), \";\\n color: \").concat(dt('tree.node.toggle.button.hover.color'), \";\\n}\\n\\n.p-tree-node-content.p-tree-node-selected .p-tree-node-toggle-button:hover {\\n background: \").concat(dt('tree.node.toggle.button.selected.hover.background'), \";\\n color: \").concat(dt('tree.node.toggle.button.selected.hover.color'), \";\\n}\\n\\n.p-tree-root {\\n overflow: auto;\\n}\\n\\n.p-tree-node-selectable {\\n cursor: pointer;\\n user-select: none;\\n}\\n\\n.p-tree-node-leaf > .p-tree-node-content .p-tree-node-toggle-button {\\n visibility: hidden;\\n}\\n\\n.p-tree-node-icon {\\n color: \").concat(dt('tree.node.icon.color'), \";\\n transition: color \").concat(dt('tree.transition.duration'), \";\\n}\\n\\n.p-tree-node-content.p-tree-node-selected .p-tree-node-icon {\\n color: \").concat(dt('tree.node.icon.selected.color'), \";\\n}\\n\\n.p-tree-filter-input {\\n width: 100%;\\n}\\n\\n.p-tree-loading {\\n position: relative;\\n height: 100%;\\n}\\n\\n.p-tree-loading-icon {\\n font-size: \").concat(dt('tree.loading.icon.size'), \";\\n width: \").concat(dt('tree.loading.icon.size'), \";\\n height: \").concat(dt('tree.loading.icon.size'), \";\\n}\\n\\n.p-tree .p-tree-mask {\\n position: absolute;\\n z-index: 1;\\n display: flex;\\n align-items: center;\\n justify-content: center;\\n}\\n\\n.p-tree-flex-scrollable {\\n display: flex;\\n flex: 1;\\n height: 100%;\\n flex-direction: column;\\n}\\n\\n.p-tree-flex-scrollable .p-tree-root {\\n flex: 1;\\n}\\n\");\n};\nvar classes = {\n root: function root(_ref2) {\n var props = _ref2.props;\n return ['p-tree p-component', {\n 'p-tree-selectable': props.selectionMode != null,\n 'p-tree-loading': props.loading,\n 'p-tree-flex-scrollable': props.scrollHeight === 'flex'\n }];\n },\n mask: 'p-tree-mask p-overlay-mask',\n loadingIcon: 'p-tree-loading-icon',\n pcFilterInput: 'p-tree-filter-input',\n wrapper: 'p-tree-root',\n //TODO: discuss\n rootChildren: 'p-tree-root-children',\n node: function node(_ref3) {\n var instance = _ref3.instance;\n return ['p-tree-node', {\n 'p-tree-node-leaf': instance.leaf\n }];\n },\n nodeContent: function nodeContent(_ref4) {\n var instance = _ref4.instance;\n return ['p-tree-node-content', instance.node.styleClass, {\n 'p-tree-node-selectable': instance.selectable,\n 'p-tree-node-selected': instance.checkboxMode && instance.$parentInstance.highlightOnSelect ? instance.checked : instance.selected\n }];\n },\n nodeToggleButton: 'p-tree-node-toggle-button',\n nodeToggleIcon: 'p-tree-node-toggle-icon',\n nodeCheckbox: 'p-tree-node-checkbox',\n nodeIcon: 'p-tree-node-icon',\n nodeLabel: 'p-tree-node-label',\n nodeChildren: 'p-tree-node-children'\n};\nvar TreeStyle = BaseStyle.extend({\n name: 'tree',\n theme: theme,\n classes: classes\n});\n\nexport { TreeStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import { resolveFieldData } from '@primeuix/utils/object';\nimport SearchIcon from '@primevue/icons/search';\nimport SpinnerIcon from '@primevue/icons/spinner';\nimport IconField from 'primevue/iconfield';\nimport InputIcon from 'primevue/inputicon';\nimport InputText from 'primevue/inputtext';\nimport BaseComponent from '@primevue/core/basecomponent';\nimport TreeStyle from 'primevue/tree/style';\nimport { getAttribute, findSingle, find } from '@primeuix/utils/dom';\nimport CheckIcon from '@primevue/icons/check';\nimport ChevronDownIcon from '@primevue/icons/chevrondown';\nimport ChevronRightIcon from '@primevue/icons/chevronright';\nimport MinusIcon from '@primevue/icons/minus';\nimport Checkbox from 'primevue/checkbox';\nimport Ripple from 'primevue/ripple';\nimport { resolveComponent, resolveDirective, openBlock, createElementBlock, mergeProps, createElementVNode, withDirectives, Fragment, createBlock, resolveDynamicComponent, normalizeClass, withCtx, createCommentVNode, withModifiers, createTextVNode, toDisplayString, renderList, renderSlot, createVNode } from 'vue';\n\nvar script$2 = {\n name: 'BaseTree',\n \"extends\": BaseComponent,\n props: {\n value: {\n type: null,\n \"default\": null\n },\n expandedKeys: {\n type: null,\n \"default\": null\n },\n selectionKeys: {\n type: null,\n \"default\": null\n },\n selectionMode: {\n type: String,\n \"default\": null\n },\n metaKeySelection: {\n type: Boolean,\n \"default\": false\n },\n loading: {\n type: Boolean,\n \"default\": false\n },\n loadingIcon: {\n type: String,\n \"default\": undefined\n },\n loadingMode: {\n type: String,\n \"default\": 'mask'\n },\n filter: {\n type: Boolean,\n \"default\": false\n },\n filterBy: {\n type: String,\n \"default\": 'label'\n },\n filterMode: {\n type: String,\n \"default\": 'lenient'\n },\n filterPlaceholder: {\n type: String,\n \"default\": null\n },\n filterLocale: {\n type: String,\n \"default\": undefined\n },\n highlightOnSelect: {\n type: Boolean,\n \"default\": false\n },\n scrollHeight: {\n type: String,\n \"default\": null\n },\n level: {\n type: Number,\n \"default\": 0\n },\n ariaLabelledby: {\n type: String,\n \"default\": null\n },\n ariaLabel: {\n type: String,\n \"default\": null\n }\n },\n style: TreeStyle,\n provide: function provide() {\n return {\n $pcTree: this,\n $parentInstance: this\n };\n }\n};\n\nfunction _typeof$1(o) { \"@babel/helpers - typeof\"; return _typeof$1 = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof$1(o); }\nfunction _createForOfIteratorHelper$1(r, e) { var t = \"undefined\" != typeof Symbol && r[Symbol.iterator] || r[\"@@iterator\"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray$1(r)) || e ) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError(\"Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t[\"return\"] || t[\"return\"](); } finally { if (u) throw o; } } }; }\nfunction ownKeys$1(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread$1(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$1(Object(t), !0).forEach(function (r) { _defineProperty$1(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$1(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty$1(e, r, t) { return (r = _toPropertyKey$1(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }\nfunction _toPropertyKey$1(t) { var i = _toPrimitive$1(t, \"string\"); return \"symbol\" == _typeof$1(i) ? i : i + \"\"; }\nfunction _toPrimitive$1(t, r) { if (\"object\" != _typeof$1(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof$1(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nfunction _toConsumableArray$1(r) { return _arrayWithoutHoles$1(r) || _iterableToArray$1(r) || _unsupportedIterableToArray$1(r) || _nonIterableSpread$1(); }\nfunction _nonIterableSpread$1() { throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _unsupportedIterableToArray$1(r, a) { if (r) { if (\"string\" == typeof r) return _arrayLikeToArray$1(r, a); var t = {}.toString.call(r).slice(8, -1); return \"Object\" === t && r.constructor && (t = r.constructor.name), \"Map\" === t || \"Set\" === t ? Array.from(r) : \"Arguments\" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray$1(r, a) : void 0; } }\nfunction _iterableToArray$1(r) { if (\"undefined\" != typeof Symbol && null != r[Symbol.iterator] || null != r[\"@@iterator\"]) return Array.from(r); }\nfunction _arrayWithoutHoles$1(r) { if (Array.isArray(r)) return _arrayLikeToArray$1(r); }\nfunction _arrayLikeToArray$1(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }\nvar script$1 = {\n name: 'TreeNode',\n hostName: 'Tree',\n \"extends\": BaseComponent,\n emits: ['node-toggle', 'node-click', 'checkbox-change'],\n props: {\n node: {\n type: null,\n \"default\": null\n },\n expandedKeys: {\n type: null,\n \"default\": null\n },\n loadingMode: {\n type: String,\n \"default\": 'mask'\n },\n selectionKeys: {\n type: null,\n \"default\": null\n },\n selectionMode: {\n type: String,\n \"default\": null\n },\n templates: {\n type: null,\n \"default\": null\n },\n level: {\n type: Number,\n \"default\": null\n },\n index: null\n },\n nodeTouched: false,\n toggleClicked: false,\n mounted: function mounted() {\n this.setAllNodesTabIndexes();\n },\n methods: {\n toggle: function toggle() {\n this.$emit('node-toggle', this.node);\n this.toggleClicked = true;\n },\n label: function label(node) {\n return typeof node.label === 'function' ? node.label() : node.label;\n },\n onChildNodeToggle: function onChildNodeToggle(node) {\n this.$emit('node-toggle', node);\n },\n getPTOptions: function getPTOptions(key) {\n return this.ptm(key, {\n context: {\n index: this.index,\n expanded: this.expanded,\n selected: this.selected,\n checked: this.checked,\n leaf: this.leaf\n }\n });\n },\n onClick: function onClick(event) {\n if (this.toggleClicked || getAttribute(event.target, '[data-pc-section=\"nodetogglebutton\"]') || getAttribute(event.target.parentElement, '[data-pc-section=\"nodetogglebutton\"]')) {\n this.toggleClicked = false;\n return;\n }\n if (this.isCheckboxSelectionMode()) {\n this.toggleCheckbox();\n } else {\n this.$emit('node-click', {\n originalEvent: event,\n nodeTouched: this.nodeTouched,\n node: this.node\n });\n }\n this.nodeTouched = false;\n },\n onChildNodeClick: function onChildNodeClick(event) {\n this.$emit('node-click', event);\n },\n onTouchEnd: function onTouchEnd() {\n this.nodeTouched = true;\n },\n onKeyDown: function onKeyDown(event) {\n if (!this.isSameNode(event)) return;\n switch (event.code) {\n case 'Tab':\n this.onTabKey(event);\n break;\n case 'ArrowDown':\n this.onArrowDown(event);\n break;\n case 'ArrowUp':\n this.onArrowUp(event);\n break;\n case 'ArrowRight':\n this.onArrowRight(event);\n break;\n case 'ArrowLeft':\n this.onArrowLeft(event);\n break;\n case 'Enter':\n case 'NumpadEnter':\n case 'Space':\n this.onEnterKey(event);\n break;\n }\n },\n onArrowDown: function onArrowDown(event) {\n var nodeElement = event.target.getAttribute('data-pc-section') === 'nodetogglebutton' ? event.target.closest('[role=\"treeitem\"]') : event.target;\n var listElement = nodeElement.children[1];\n if (listElement) {\n this.focusRowChange(nodeElement, listElement.children[0]);\n } else {\n if (nodeElement.nextElementSibling) {\n this.focusRowChange(nodeElement, nodeElement.nextElementSibling);\n } else {\n var nextSiblingAncestor = this.findNextSiblingOfAncestor(nodeElement);\n if (nextSiblingAncestor) {\n this.focusRowChange(nodeElement, nextSiblingAncestor);\n }\n }\n }\n event.preventDefault();\n },\n onArrowUp: function onArrowUp(event) {\n var nodeElement = event.target;\n if (nodeElement.previousElementSibling) {\n this.focusRowChange(nodeElement, nodeElement.previousElementSibling, this.findLastVisibleDescendant(nodeElement.previousElementSibling));\n } else {\n var parentNodeElement = this.getParentNodeElement(nodeElement);\n if (parentNodeElement) {\n this.focusRowChange(nodeElement, parentNodeElement);\n }\n }\n event.preventDefault();\n },\n onArrowRight: function onArrowRight(event) {\n var _this = this;\n if (this.leaf || this.expanded) return;\n event.currentTarget.tabIndex = -1;\n this.$emit('node-toggle', this.node);\n this.$nextTick(function () {\n _this.onArrowDown(event);\n });\n },\n onArrowLeft: function onArrowLeft(event) {\n var togglerElement = findSingle(event.currentTarget, '[data-pc-section=\"nodetogglebutton\"]');\n if (this.level === 0 && !this.expanded) {\n return false;\n }\n if (this.expanded && !this.leaf) {\n togglerElement.click();\n return false;\n }\n var target = this.findBeforeClickableNode(event.currentTarget);\n if (target) {\n this.focusRowChange(event.currentTarget, target);\n }\n },\n onEnterKey: function onEnterKey(event) {\n this.setTabIndexForSelectionMode(event, this.nodeTouched);\n this.onClick(event);\n event.preventDefault();\n },\n onTabKey: function onTabKey() {\n this.setAllNodesTabIndexes();\n },\n setAllNodesTabIndexes: function setAllNodesTabIndexes() {\n var nodes = find(this.$refs.currentNode.closest('[data-pc-section=\"rootchildren\"]'), '[role=\"treeitem\"]');\n var hasSelectedNode = _toConsumableArray$1(nodes).some(function (node) {\n return node.getAttribute('aria-selected') === 'true' || node.getAttribute('aria-checked') === 'true';\n });\n _toConsumableArray$1(nodes).forEach(function (node) {\n node.tabIndex = -1;\n });\n if (hasSelectedNode) {\n var selectedNodes = _toConsumableArray$1(nodes).filter(function (node) {\n return node.getAttribute('aria-selected') === 'true' || node.getAttribute('aria-checked') === 'true';\n });\n selectedNodes[0].tabIndex = 0;\n return;\n }\n _toConsumableArray$1(nodes)[0].tabIndex = 0;\n },\n setTabIndexForSelectionMode: function setTabIndexForSelectionMode(event, nodeTouched) {\n if (this.selectionMode !== null) {\n var elements = _toConsumableArray$1(find(this.$refs.currentNode.parentElement, '[role=\"treeitem\"]'));\n event.currentTarget.tabIndex = nodeTouched === false ? -1 : 0;\n if (elements.every(function (element) {\n return element.tabIndex === -1;\n })) {\n elements[0].tabIndex = 0;\n }\n }\n },\n focusRowChange: function focusRowChange(firstFocusableRow, currentFocusedRow, lastVisibleDescendant) {\n firstFocusableRow.tabIndex = '-1';\n currentFocusedRow.tabIndex = '0';\n this.focusNode(lastVisibleDescendant || currentFocusedRow);\n },\n findBeforeClickableNode: function findBeforeClickableNode(node) {\n var parentListElement = node.closest('ul').closest('li');\n if (parentListElement) {\n var prevNodeButton = findSingle(parentListElement, 'button');\n if (prevNodeButton && prevNodeButton.style.visibility !== 'hidden') {\n return parentListElement;\n }\n return this.findBeforeClickableNode(node.previousElementSibling);\n }\n return null;\n },\n toggleCheckbox: function toggleCheckbox() {\n var _selectionKeys = this.selectionKeys ? _objectSpread$1({}, this.selectionKeys) : {};\n var _check = !this.checked;\n this.propagateDown(this.node, _check, _selectionKeys);\n this.$emit('checkbox-change', {\n node: this.node,\n check: _check,\n selectionKeys: _selectionKeys\n });\n },\n propagateDown: function propagateDown(node, check, selectionKeys) {\n if (check) selectionKeys[node.key] = {\n checked: true,\n partialChecked: false\n };else delete selectionKeys[node.key];\n if (node.children && node.children.length) {\n var _iterator = _createForOfIteratorHelper$1(node.children),\n _step;\n try {\n for (_iterator.s(); !(_step = _iterator.n()).done;) {\n var child = _step.value;\n this.propagateDown(child, check, selectionKeys);\n }\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n }\n },\n propagateUp: function propagateUp(event) {\n var check = event.check;\n var _selectionKeys = _objectSpread$1({}, event.selectionKeys);\n var checkedChildCount = 0;\n var childPartialSelected = false;\n var _iterator2 = _createForOfIteratorHelper$1(this.node.children),\n _step2;\n try {\n for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {\n var child = _step2.value;\n if (_selectionKeys[child.key] && _selectionKeys[child.key].checked) checkedChildCount++;else if (_selectionKeys[child.key] && _selectionKeys[child.key].partialChecked) childPartialSelected = true;\n }\n } catch (err) {\n _iterator2.e(err);\n } finally {\n _iterator2.f();\n }\n if (check && checkedChildCount === this.node.children.length) {\n _selectionKeys[this.node.key] = {\n checked: true,\n partialChecked: false\n };\n } else {\n if (!check) {\n delete _selectionKeys[this.node.key];\n }\n if (childPartialSelected || checkedChildCount > 0 && checkedChildCount !== this.node.children.length) _selectionKeys[this.node.key] = {\n checked: false,\n partialChecked: true\n };else delete _selectionKeys[this.node.key];\n }\n this.$emit('checkbox-change', {\n node: event.node,\n check: event.check,\n selectionKeys: _selectionKeys\n });\n },\n onChildCheckboxChange: function onChildCheckboxChange(event) {\n this.$emit('checkbox-change', event);\n },\n findNextSiblingOfAncestor: function findNextSiblingOfAncestor(nodeElement) {\n var parentNodeElement = this.getParentNodeElement(nodeElement);\n if (parentNodeElement) {\n if (parentNodeElement.nextElementSibling) return parentNodeElement.nextElementSibling;else return this.findNextSiblingOfAncestor(parentNodeElement);\n } else {\n return null;\n }\n },\n findLastVisibleDescendant: function findLastVisibleDescendant(nodeElement) {\n var childrenListElement = nodeElement.children[1];\n if (childrenListElement) {\n var lastChildElement = childrenListElement.children[childrenListElement.children.length - 1];\n return this.findLastVisibleDescendant(lastChildElement);\n } else {\n return nodeElement;\n }\n },\n getParentNodeElement: function getParentNodeElement(nodeElement) {\n var parentNodeElement = nodeElement.parentElement.parentElement;\n return getAttribute(parentNodeElement, 'role') === 'treeitem' ? parentNodeElement : null;\n },\n focusNode: function focusNode(element) {\n element.focus();\n },\n isCheckboxSelectionMode: function isCheckboxSelectionMode() {\n return this.selectionMode === 'checkbox';\n },\n isSameNode: function isSameNode(event) {\n return event.currentTarget && (event.currentTarget.isSameNode(event.target) || event.currentTarget.isSameNode(event.target.closest('[role=\"treeitem\"]')));\n }\n },\n computed: {\n hasChildren: function hasChildren() {\n return this.node.children && this.node.children.length > 0;\n },\n expanded: function expanded() {\n return this.expandedKeys && this.expandedKeys[this.node.key] === true;\n },\n leaf: function leaf() {\n return this.node.leaf === false ? false : !(this.node.children && this.node.children.length);\n },\n selectable: function selectable() {\n return this.node.selectable === false ? false : this.selectionMode != null;\n },\n selected: function selected() {\n return this.selectionMode && this.selectionKeys ? this.selectionKeys[this.node.key] === true : false;\n },\n checkboxMode: function checkboxMode() {\n return this.selectionMode === 'checkbox' && this.node.selectable !== false;\n },\n checked: function checked() {\n return this.selectionKeys ? this.selectionKeys[this.node.key] && this.selectionKeys[this.node.key].checked : false;\n },\n partialChecked: function partialChecked() {\n return this.selectionKeys ? this.selectionKeys[this.node.key] && this.selectionKeys[this.node.key].partialChecked : false;\n },\n ariaChecked: function ariaChecked() {\n return this.selectionMode === 'single' || this.selectionMode === 'multiple' ? this.selected : undefined;\n },\n ariaSelected: function ariaSelected() {\n return this.checkboxMode ? this.checked : undefined;\n }\n },\n components: {\n Checkbox: Checkbox,\n ChevronDownIcon: ChevronDownIcon,\n ChevronRightIcon: ChevronRightIcon,\n CheckIcon: CheckIcon,\n MinusIcon: MinusIcon,\n SpinnerIcon: SpinnerIcon\n },\n directives: {\n ripple: Ripple\n }\n};\n\nvar _hoisted_1$1 = [\"aria-label\", \"aria-selected\", \"aria-expanded\", \"aria-setsize\", \"aria-posinset\", \"aria-level\", \"aria-checked\", \"tabindex\"];\nvar _hoisted_2 = [\"data-p-selected\", \"data-p-selectable\"];\nfunction render$1(_ctx, _cache, $props, $setup, $data, $options) {\n var _component_SpinnerIcon = resolveComponent(\"SpinnerIcon\");\n var _component_Checkbox = resolveComponent(\"Checkbox\");\n var _component_TreeNode = resolveComponent(\"TreeNode\", true);\n var _directive_ripple = resolveDirective(\"ripple\");\n return openBlock(), createElementBlock(\"li\", mergeProps({\n ref: \"currentNode\",\n \"class\": _ctx.cx('node'),\n role: \"treeitem\",\n \"aria-label\": $options.label($props.node),\n \"aria-selected\": $options.ariaSelected,\n \"aria-expanded\": $options.expanded,\n \"aria-setsize\": $props.node.children ? $props.node.children.length : 0,\n \"aria-posinset\": $props.index + 1,\n \"aria-level\": $props.level,\n \"aria-checked\": $options.ariaChecked,\n tabindex: $props.index === 0 ? 0 : -1,\n onKeydown: _cache[4] || (_cache[4] = function () {\n return $options.onKeyDown && $options.onKeyDown.apply($options, arguments);\n })\n }, $props.level === 1 ? $options.getPTOptions('node') : _ctx.ptm('nodeChildren')), [createElementVNode(\"div\", mergeProps({\n \"class\": _ctx.cx('nodeContent'),\n onClick: _cache[2] || (_cache[2] = function () {\n return $options.onClick && $options.onClick.apply($options, arguments);\n }),\n onTouchend: _cache[3] || (_cache[3] = function () {\n return $options.onTouchEnd && $options.onTouchEnd.apply($options, arguments);\n }),\n style: $props.node.style\n }, $options.getPTOptions('nodeContent'), {\n \"data-p-selected\": $options.checkboxMode ? $options.checked : $options.selected,\n \"data-p-selectable\": $options.selectable\n }), [withDirectives((openBlock(), createElementBlock(\"button\", mergeProps({\n type: \"button\",\n \"class\": _ctx.cx('nodeToggleButton'),\n onClick: _cache[0] || (_cache[0] = function () {\n return $options.toggle && $options.toggle.apply($options, arguments);\n }),\n tabindex: \"-1\",\n \"aria-hidden\": \"true\"\n }, $options.getPTOptions('nodeToggleButton')), [$props.node.loading && $props.loadingMode === 'icon' ? (openBlock(), createElementBlock(Fragment, {\n key: 0\n }, [$props.templates['nodetoggleicon'] || $props.templates['nodetogglericon'] ? (openBlock(), createBlock(resolveDynamicComponent($props.templates['nodetoggleicon'] || $props.templates['nodetogglericon']), {\n key: 0,\n \"class\": normalizeClass(_ctx.cx('nodeToggleIcon'))\n }, null, 8, [\"class\"])) : (openBlock(), createBlock(_component_SpinnerIcon, mergeProps({\n key: 1,\n spin: \"\",\n \"class\": _ctx.cx('nodetogglericon')\n }, _ctx.ptm('nodeToggleIcon')), null, 16, [\"class\"]))], 64)) : (openBlock(), createElementBlock(Fragment, {\n key: 1\n }, [$props.templates['nodetoggleicon'] || $props.templates['togglericon'] ? (openBlock(), createBlock(resolveDynamicComponent($props.templates['nodetoggleicon'] || $props.templates['togglericon']), {\n key: 0,\n node: $props.node,\n expanded: $options.expanded,\n \"class\": normalizeClass(_ctx.cx('nodeToggleIcon'))\n }, null, 8, [\"node\", \"expanded\", \"class\"])) : $options.expanded ? (openBlock(), createBlock(resolveDynamicComponent($props.node.expandedIcon ? 'span' : 'ChevronDownIcon'), mergeProps({\n key: 1,\n \"class\": _ctx.cx('nodeToggleIcon')\n }, $options.getPTOptions('nodeToggleIcon')), null, 16, [\"class\"])) : (openBlock(), createBlock(resolveDynamicComponent($props.node.collapsedIcon ? 'span' : 'ChevronRightIcon'), mergeProps({\n key: 2,\n \"class\": _ctx.cx('nodeToggleIcon')\n }, $options.getPTOptions('nodeToggleIcon')), null, 16, [\"class\"]))], 64))], 16)), [[_directive_ripple]]), $options.checkboxMode ? (openBlock(), createBlock(_component_Checkbox, {\n key: 0,\n modelValue: $options.checked,\n binary: true,\n indeterminate: $options.partialChecked,\n \"class\": normalizeClass(_ctx.cx('nodeCheckbox')),\n tabindex: -1,\n unstyled: _ctx.unstyled,\n pt: $options.getPTOptions('nodeCheckbox'),\n \"data-p-partialchecked\": $options.partialChecked\n }, {\n icon: withCtx(function (slotProps) {\n return [$props.templates['checkboxicon'] ? (openBlock(), createBlock(resolveDynamicComponent($props.templates['checkboxicon']), {\n key: 0,\n checked: slotProps.checked,\n partialChecked: $options.partialChecked,\n \"class\": normalizeClass(slotProps[\"class\"])\n }, null, 8, [\"checked\", \"partialChecked\", \"class\"])) : createCommentVNode(\"\", true)];\n }),\n _: 1\n }, 8, [\"modelValue\", \"indeterminate\", \"class\", \"unstyled\", \"pt\", \"data-p-partialchecked\"])) : createCommentVNode(\"\", true), $props.templates['nodeicon'] ? (openBlock(), createBlock(resolveDynamicComponent($props.templates['nodeicon']), mergeProps({\n key: 1,\n node: $props.node,\n \"class\": [_ctx.cx('nodeIcon')]\n }, $options.getPTOptions('nodeIcon')), null, 16, [\"node\", \"class\"])) : (openBlock(), createElementBlock(\"span\", mergeProps({\n key: 2,\n \"class\": [_ctx.cx('nodeIcon'), $props.node.icon]\n }, $options.getPTOptions('nodeIcon')), null, 16)), createElementVNode(\"span\", mergeProps({\n \"class\": _ctx.cx('nodeLabel')\n }, $options.getPTOptions('nodeLabel'), {\n onKeydown: _cache[1] || (_cache[1] = withModifiers(function () {}, [\"stop\"]))\n }), [$props.templates[$props.node.type] || $props.templates['default'] ? (openBlock(), createBlock(resolveDynamicComponent($props.templates[$props.node.type] || $props.templates['default']), {\n key: 0,\n node: $props.node,\n selected: $options.checkboxMode ? $options.checked : $options.selected\n }, null, 8, [\"node\", \"selected\"])) : (openBlock(), createElementBlock(Fragment, {\n key: 1\n }, [createTextVNode(toDisplayString($options.label($props.node)), 1)], 64))], 16)], 16, _hoisted_2), $options.hasChildren && $options.expanded ? (openBlock(), createElementBlock(\"ul\", mergeProps({\n key: 0,\n \"class\": _ctx.cx('nodeChildren'),\n role: \"group\"\n }, _ctx.ptm('nodeChildren')), [(openBlock(true), createElementBlock(Fragment, null, renderList($props.node.children, function (childNode) {\n return openBlock(), createBlock(_component_TreeNode, {\n key: childNode.key,\n node: childNode,\n templates: $props.templates,\n level: $props.level + 1,\n loadingMode: $props.loadingMode,\n expandedKeys: $props.expandedKeys,\n onNodeToggle: $options.onChildNodeToggle,\n onNodeClick: $options.onChildNodeClick,\n selectionMode: $props.selectionMode,\n selectionKeys: $props.selectionKeys,\n onCheckboxChange: $options.propagateUp,\n unstyled: _ctx.unstyled,\n pt: _ctx.pt\n }, null, 8, [\"node\", \"templates\", \"level\", \"loadingMode\", \"expandedKeys\", \"onNodeToggle\", \"onNodeClick\", \"selectionMode\", \"selectionKeys\", \"onCheckboxChange\", \"unstyled\", \"pt\"]);\n }), 128))], 16)) : createCommentVNode(\"\", true)], 16, _hoisted_1$1);\n}\n\nscript$1.render = render$1;\n\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction _createForOfIteratorHelper(r, e) { var t = \"undefined\" != typeof Symbol && r[Symbol.iterator] || r[\"@@iterator\"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e ) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError(\"Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t[\"return\"] || t[\"return\"](); } finally { if (u) throw o; } } }; }\nfunction _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _unsupportedIterableToArray(r, a) { if (r) { if (\"string\" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return \"Object\" === t && r.constructor && (t = r.constructor.name), \"Map\" === t || \"Set\" === t ? Array.from(r) : \"Arguments\" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }\nfunction _iterableToArray(r) { if (\"undefined\" != typeof Symbol && null != r[Symbol.iterator] || null != r[\"@@iterator\"]) return Array.from(r); }\nfunction _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }\nfunction _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }\nfunction _toPropertyKey(t) { var i = _toPrimitive(t, \"string\"); return \"symbol\" == _typeof(i) ? i : i + \"\"; }\nfunction _toPrimitive(t, r) { if (\"object\" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || \"default\"); if (\"object\" != _typeof(i)) return i; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (\"string\" === r ? String : Number)(t); }\nvar script = {\n name: 'Tree',\n \"extends\": script$2,\n inheritAttrs: false,\n emits: ['node-expand', 'node-collapse', 'update:expandedKeys', 'update:selectionKeys', 'node-select', 'node-unselect', 'filter'],\n data: function data() {\n return {\n d_expandedKeys: this.expandedKeys || {},\n filterValue: null\n };\n },\n watch: {\n expandedKeys: function expandedKeys(newValue) {\n this.d_expandedKeys = newValue;\n }\n },\n methods: {\n onNodeToggle: function onNodeToggle(node) {\n var key = node.key;\n if (this.d_expandedKeys[key]) {\n delete this.d_expandedKeys[key];\n this.$emit('node-collapse', node);\n } else {\n this.d_expandedKeys[key] = true;\n this.$emit('node-expand', node);\n }\n this.d_expandedKeys = _objectSpread({}, this.d_expandedKeys);\n this.$emit('update:expandedKeys', this.d_expandedKeys);\n },\n onNodeClick: function onNodeClick(event) {\n if (this.selectionMode != null && event.node.selectable !== false) {\n var metaSelection = event.nodeTouched ? false : this.metaKeySelection;\n var _selectionKeys = metaSelection ? this.handleSelectionWithMetaKey(event) : this.handleSelectionWithoutMetaKey(event);\n this.$emit('update:selectionKeys', _selectionKeys);\n }\n },\n onCheckboxChange: function onCheckboxChange(event) {\n this.$emit('update:selectionKeys', event.selectionKeys);\n if (event.check) this.$emit('node-select', event.node);else this.$emit('node-unselect', event.node);\n },\n handleSelectionWithMetaKey: function handleSelectionWithMetaKey(event) {\n var originalEvent = event.originalEvent;\n var node = event.node;\n var metaKey = originalEvent.metaKey || originalEvent.ctrlKey;\n var selected = this.isNodeSelected(node);\n var _selectionKeys;\n if (selected && metaKey) {\n if (this.isSingleSelectionMode()) {\n _selectionKeys = {};\n } else {\n _selectionKeys = _objectSpread({}, this.selectionKeys);\n delete _selectionKeys[node.key];\n }\n this.$emit('node-unselect', node);\n } else {\n if (this.isSingleSelectionMode()) {\n _selectionKeys = {};\n } else if (this.isMultipleSelectionMode()) {\n _selectionKeys = !metaKey ? {} : this.selectionKeys ? _objectSpread({}, this.selectionKeys) : {};\n }\n _selectionKeys[node.key] = true;\n this.$emit('node-select', node);\n }\n return _selectionKeys;\n },\n handleSelectionWithoutMetaKey: function handleSelectionWithoutMetaKey(event) {\n var node = event.node;\n var selected = this.isNodeSelected(node);\n var _selectionKeys;\n if (this.isSingleSelectionMode()) {\n if (selected) {\n _selectionKeys = {};\n this.$emit('node-unselect', node);\n } else {\n _selectionKeys = {};\n _selectionKeys[node.key] = true;\n this.$emit('node-select', node);\n }\n } else {\n if (selected) {\n _selectionKeys = _objectSpread({}, this.selectionKeys);\n delete _selectionKeys[node.key];\n this.$emit('node-unselect', node);\n } else {\n _selectionKeys = this.selectionKeys ? _objectSpread({}, this.selectionKeys) : {};\n _selectionKeys[node.key] = true;\n this.$emit('node-select', node);\n }\n }\n return _selectionKeys;\n },\n isSingleSelectionMode: function isSingleSelectionMode() {\n return this.selectionMode === 'single';\n },\n isMultipleSelectionMode: function isMultipleSelectionMode() {\n return this.selectionMode === 'multiple';\n },\n isNodeSelected: function isNodeSelected(node) {\n return this.selectionMode && this.selectionKeys ? this.selectionKeys[node.key] === true : false;\n },\n isChecked: function isChecked(node) {\n return this.selectionKeys ? this.selectionKeys[node.key] && this.selectionKeys[node.key].checked : false;\n },\n isNodeLeaf: function isNodeLeaf(node) {\n return node.leaf === false ? false : !(node.children && node.children.length);\n },\n onFilterKeydown: function onFilterKeydown(event) {\n if (event.code === 'Enter' || event.code === 'NumpadEnter') {\n event.preventDefault();\n }\n this.$emit('filter', {\n originalEvent: event,\n value: event.target.value\n });\n },\n findFilteredNodes: function findFilteredNodes(node, paramsWithoutNode) {\n if (node) {\n var matched = false;\n if (node.children) {\n var childNodes = _toConsumableArray(node.children);\n node.children = [];\n var _iterator = _createForOfIteratorHelper(childNodes),\n _step;\n try {\n for (_iterator.s(); !(_step = _iterator.n()).done;) {\n var childNode = _step.value;\n var copyChildNode = _objectSpread({}, childNode);\n if (this.isFilterMatched(copyChildNode, paramsWithoutNode)) {\n matched = true;\n node.children.push(copyChildNode);\n }\n }\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n }\n if (matched) {\n return true;\n }\n }\n },\n isFilterMatched: function isFilterMatched(node, _ref) {\n var searchFields = _ref.searchFields,\n filterText = _ref.filterText,\n strict = _ref.strict;\n var matched = false;\n var _iterator2 = _createForOfIteratorHelper(searchFields),\n _step2;\n try {\n for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {\n var field = _step2.value;\n var fieldValue = String(resolveFieldData(node, field)).toLocaleLowerCase(this.filterLocale);\n if (fieldValue.indexOf(filterText) > -1) {\n matched = true;\n }\n }\n } catch (err) {\n _iterator2.e(err);\n } finally {\n _iterator2.f();\n }\n if (!matched || strict && !this.isNodeLeaf(node)) {\n matched = this.findFilteredNodes(node, {\n searchFields: searchFields,\n filterText: filterText,\n strict: strict\n }) || matched;\n }\n return matched;\n }\n },\n computed: {\n filteredValue: function filteredValue() {\n var filteredNodes = [];\n var searchFields = this.filterBy.split(',');\n var filterText = this.filterValue.trim().toLocaleLowerCase(this.filterLocale);\n var strict = this.filterMode === 'strict';\n var _iterator3 = _createForOfIteratorHelper(this.value),\n _step3;\n try {\n for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {\n var node = _step3.value;\n var _node = _objectSpread({}, node);\n var paramsWithoutNode = {\n searchFields: searchFields,\n filterText: filterText,\n strict: strict\n };\n if (strict && (this.findFilteredNodes(_node, paramsWithoutNode) || this.isFilterMatched(_node, paramsWithoutNode)) || !strict && (this.isFilterMatched(_node, paramsWithoutNode) || this.findFilteredNodes(_node, paramsWithoutNode))) {\n filteredNodes.push(_node);\n }\n }\n } catch (err) {\n _iterator3.e(err);\n } finally {\n _iterator3.f();\n }\n return filteredNodes;\n },\n valueToRender: function valueToRender() {\n if (this.filterValue && this.filterValue.trim().length > 0) return this.filteredValue;else return this.value;\n }\n },\n components: {\n TreeNode: script$1,\n InputText: InputText,\n InputIcon: InputIcon,\n IconField: IconField,\n SearchIcon: SearchIcon,\n SpinnerIcon: SpinnerIcon\n }\n};\n\nvar _hoisted_1 = [\"aria-labelledby\", \"aria-label\"];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n var _component_SpinnerIcon = resolveComponent(\"SpinnerIcon\");\n var _component_InputText = resolveComponent(\"InputText\");\n var _component_SearchIcon = resolveComponent(\"SearchIcon\");\n var _component_InputIcon = resolveComponent(\"InputIcon\");\n var _component_IconField = resolveComponent(\"IconField\");\n var _component_TreeNode = resolveComponent(\"TreeNode\");\n return openBlock(), createElementBlock(\"div\", mergeProps({\n \"class\": _ctx.cx('root')\n }, _ctx.ptmi('root')), [_ctx.loading && _ctx.loadingMode === 'mask' ? (openBlock(), createElementBlock(\"div\", mergeProps({\n key: 0,\n \"class\": _ctx.cx('mask')\n }, _ctx.ptm('mask')), [renderSlot(_ctx.$slots, \"loadingicon\", {\n \"class\": normalizeClass(_ctx.cx('loadingIcon'))\n }, function () {\n return [_ctx.loadingIcon ? (openBlock(), createElementBlock(\"i\", mergeProps({\n key: 0,\n \"class\": [_ctx.cx('loadingIcon'), 'pi-spin', _ctx.loadingIcon]\n }, _ctx.ptm('loadingIcon')), null, 16)) : (openBlock(), createBlock(_component_SpinnerIcon, mergeProps({\n key: 1,\n spin: \"\",\n \"class\": _ctx.cx('loadingIcon')\n }, _ctx.ptm('loadingIcon')), null, 16, [\"class\"]))];\n })], 16)) : createCommentVNode(\"\", true), _ctx.filter ? (openBlock(), createBlock(_component_IconField, mergeProps({\n key: 1,\n unstyled: _ctx.unstyled\n }, _ctx.ptm('pcFilterContainer')), {\n \"default\": withCtx(function () {\n return [createVNode(_component_InputText, mergeProps({\n modelValue: $data.filterValue,\n \"onUpdate:modelValue\": _cache[0] || (_cache[0] = function ($event) {\n return $data.filterValue = $event;\n }),\n autocomplete: \"off\",\n \"class\": _ctx.cx('pcFilterInput'),\n placeholder: _ctx.filterPlaceholder,\n unstyled: _ctx.unstyled,\n onKeydown: $options.onFilterKeydown\n }, _ctx.ptm('pcFilterInput')), null, 16, [\"modelValue\", \"class\", \"placeholder\", \"unstyled\", \"onKeydown\"]), createVNode(_component_InputIcon, mergeProps({\n unstyled: _ctx.unstyled\n }, _ctx.ptm('pcFilterIconContainer')), {\n \"default\": withCtx(function () {\n return [renderSlot(_ctx.$slots, _ctx.$slots.filtericon ? 'filtericon' : 'searchicon', {\n \"class\": normalizeClass(_ctx.cx('filterIcon'))\n }, function () {\n return [createVNode(_component_SearchIcon, mergeProps({\n \"class\": _ctx.cx('filterIcon')\n }, _ctx.ptm('filterIcon')), null, 16, [\"class\"])];\n })];\n }),\n _: 3\n }, 16, [\"unstyled\"])];\n }),\n _: 3\n }, 16, [\"unstyled\"])) : createCommentVNode(\"\", true), createElementVNode(\"div\", mergeProps({\n \"class\": _ctx.cx('wrapper'),\n style: {\n maxHeight: _ctx.scrollHeight\n }\n }, _ctx.ptm('wrapper')), [createElementVNode(\"ul\", mergeProps({\n \"class\": _ctx.cx('rootChildren'),\n role: \"tree\",\n \"aria-labelledby\": _ctx.ariaLabelledby,\n \"aria-label\": _ctx.ariaLabel\n }, _ctx.ptm('rootChildren')), [(openBlock(true), createElementBlock(Fragment, null, renderList($options.valueToRender, function (node, index) {\n return openBlock(), createBlock(_component_TreeNode, {\n key: node.key,\n node: node,\n templates: _ctx.$slots,\n level: _ctx.level + 1,\n index: index,\n expandedKeys: $data.d_expandedKeys,\n onNodeToggle: $options.onNodeToggle,\n onNodeClick: $options.onNodeClick,\n selectionMode: _ctx.selectionMode,\n selectionKeys: _ctx.selectionKeys,\n onCheckboxChange: $options.onCheckboxChange,\n loadingMode: _ctx.loadingMode,\n unstyled: _ctx.unstyled,\n pt: _ctx.pt\n }, null, 8, [\"node\", \"templates\", \"level\", \"index\", \"expandedKeys\", \"onNodeToggle\", \"onNodeClick\", \"selectionMode\", \"selectionKeys\", \"onCheckboxChange\", \"loadingMode\", \"unstyled\", \"pt\"]);\n }), 128))], 16, _hoisted_1)], 16)], 16);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","\r\n\r\n","import BaseStyle from '@primevue/core/base/style';\n\nvar theme = function theme(_ref) {\n var dt = _ref.dt;\n return \"\\n.p-toolbar {\\n display: flex;\\n align-items: center;\\n justify-content: space-between;\\n flex-wrap: wrap;\\n padding: \".concat(dt('toolbar.padding'), \";\\n background: \").concat(dt('toolbar.background'), \";\\n border: 1px solid \").concat(dt('toolbar.border.color'), \";\\n color: \").concat(dt('toolbar.color'), \";\\n border-radius: \").concat(dt('toolbar.border.radius'), \";\\n gap: \").concat(dt('toolbar.gap'), \";\\n}\\n\\n.p-toolbar-start,\\n.p-toolbar-center,\\n.p-toolbar-end {\\n display: flex;\\n align-items: center;\\n}\\n\");\n};\nvar classes = {\n root: 'p-toolbar p-component',\n start: 'p-toolbar-start',\n center: 'p-toolbar-center',\n end: 'p-toolbar-end'\n};\nvar ToolbarStyle = BaseStyle.extend({\n name: 'toolbar',\n theme: theme,\n classes: classes\n});\n\nexport { ToolbarStyle as default };\n//# sourceMappingURL=index.mjs.map\n","import BaseComponent from '@primevue/core/basecomponent';\nimport ToolbarStyle from 'primevue/toolbar/style';\nimport { openBlock, createElementBlock, mergeProps, createElementVNode, renderSlot } from 'vue';\n\nvar script$1 = {\n name: 'BaseToolbar',\n \"extends\": BaseComponent,\n props: {\n ariaLabelledby: {\n type: String,\n \"default\": null\n }\n },\n style: ToolbarStyle,\n provide: function provide() {\n return {\n $pcToolbar: this,\n $parentInstance: this\n };\n }\n};\n\nvar script = {\n name: 'Toolbar',\n \"extends\": script$1,\n inheritAttrs: false\n};\n\nvar _hoisted_1 = [\"aria-labelledby\"];\nfunction render(_ctx, _cache, $props, $setup, $data, $options) {\n return openBlock(), createElementBlock(\"div\", mergeProps({\n \"class\": _ctx.cx('root'),\n role: \"toolbar\",\n \"aria-labelledby\": _ctx.ariaLabelledby\n }, _ctx.ptmi('root')), [createElementVNode(\"div\", mergeProps({\n \"class\": _ctx.cx('start')\n }, _ctx.ptm('start')), [renderSlot(_ctx.$slots, \"start\")], 16), createElementVNode(\"div\", mergeProps({\n \"class\": _ctx.cx('center')\n }, _ctx.ptm('center')), [renderSlot(_ctx.$slots, \"center\")], 16), createElementVNode(\"div\", mergeProps({\n \"class\": _ctx.cx('end')\n }, _ctx.ptm('end')), [renderSlot(_ctx.$slots, \"end\")], 16)], 16, _hoisted_1);\n}\n\nscript.render = render;\n\nexport { script as default };\n//# sourceMappingURL=index.mjs.map\n","\r\n \r\n \r\n \r\n {{\r\n props.title.toUpperCase()\r\n }}\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n\r\n\r\n\r\n\r\n\r\n","\r\n \r\n \r\n \r\n \r\n \r\n \r\n ({\r\n 'data-comfy-node-name': props.node?.data?.name,\r\n onMouseenter: (event: MouseEvent) => {\r\n hoveredComfyNodeName = props.node?.data?.name\r\n\r\n const hoverTarget = event.target as HTMLElement\r\n const targetRect = hoverTarget.getBoundingClientRect()\r\n if (sidebarLocation === 'left') {\r\n nodePreviewStyle.top = `${targetRect.top - 40}px`\r\n nodePreviewStyle.left = `${targetRect.right}px`\r\n } else {\r\n nodePreviewStyle.top = `${targetRect.top - 40}px`\r\n nodePreviewStyle.left = `${targetRect.left - 400}px`\r\n }\r\n },\r\n onMouseleave: () => {\r\n hoveredComfyNodeName = null\r\n }\r\n })\r\n }\"\r\n >\r\n \r\n {{ node.label }}\r\n \r\n \r\n \r\n {{ node.label }}\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n\r\n\r\n\r\n","\r\n\r\n \r\n \r\n \r\n {{ dialogStore.title || ' ' }}\r\n \r\n\r\n \r\n \r\n\r\n\r\n\r\n","\r\n \r\n \r\n \r\n \r\n\r\n\r\n\r\n\r\n\r\n","import { createI18n } from 'vue-i18n'\r\n\r\nconst messages = {\r\n en: {\r\n settings: 'Settings',\r\n searchSettings: 'Search Settings',\r\n noResultsFound: 'No Results Found',\r\n searchFailedMessage:\r\n \"We couldn't find any settings matching your search. Try adjusting your search terms.\",\r\n noTasksFound: 'No Tasks Found',\r\n noTasksFoundMessage: 'There are no tasks in the queue.',\r\n sideToolbar: {\r\n themeToggle: 'Toggle Theme',\r\n queue: 'Queue',\r\n nodeLibrary: 'Node Library',\r\n nodeLibraryTab: {\r\n sortOrder: 'Sort Order'\r\n }\r\n }\r\n },\r\n zh: {\r\n settings: '设置',\r\n searchSettings: '搜索设置',\r\n noResultsFound: '未找到结果',\r\n noTasksFound: '未找到任务',\r\n noTasksFoundMessage: '队列中没有任务。',\r\n searchFailedMessage:\r\n '我们找不到与您的搜索匹配的任何设置。请尝试调整搜索条件。',\r\n sideToolbar: {\r\n themeToggle: '主题切换',\r\n queue: '队列',\r\n nodeLibrary: '节点库',\r\n nodeLibraryTab: {\r\n sortOrder: '排序顺序'\r\n }\r\n }\r\n }\r\n // TODO: Add more languages\r\n}\r\n\r\nexport const i18n = createI18n({\r\n // Must set `false`, as Vue I18n Legacy API is for Vue 2\r\n legacy: false,\r\n locale: navigator.language.split('-')[0] || 'en',\r\n fallbackLocale: 'en',\r\n messages\r\n})\r\n","import { createApp } from 'vue'\r\nimport PrimeVue from 'primevue/config'\r\nimport Aura from '@primevue/themes/aura'\r\nimport { definePreset } from '@primevue/themes'\r\nimport ConfirmationService from 'primevue/confirmationservice'\r\nimport ToastService from 'primevue/toastservice'\r\nimport Tooltip from 'primevue/tooltip'\r\nimport 'primeicons/primeicons.css'\r\n\r\nimport App from './App.vue'\r\nimport { createPinia } from 'pinia'\r\nimport { i18n } from './i18n'\r\n\r\nconst ComfyUIPreset = definePreset(Aura, {\r\n semantic: {\r\n primary: Aura['primitive'].blue\r\n }\r\n})\r\n\r\nconst app = createApp(App)\r\nconst pinia = createPinia()\r\napp.directive('tooltip', Tooltip)\r\napp\r\n .use(PrimeVue, {\r\n theme: {\r\n preset: ComfyUIPreset,\r\n options: {\r\n prefix: 'p',\r\n cssLayer: false,\r\n // This is a workaround for the issue with the dark mode selector\r\n // https://github.com/primefaces/primevue/issues/5515\r\n darkModeSelector: '.dark-theme, :root:has(.dark-theme)'\r\n }\r\n }\r\n })\r\n .use(ConfirmationService)\r\n .use(ToastService)\r\n .use(pinia)\r\n .use(i18n)\r\n .mount('#vue-app')\r\n"],"file":"assets/index-DIiqwEjy.js"} \ No newline at end of file diff --git a/web/assets/index-DJRcbqp_.js b/web/assets/index-DJRcbqp_.js new file mode 100644 index 000000000..2320bc64d --- /dev/null +++ b/web/assets/index-DJRcbqp_.js @@ -0,0 +1,6123 @@ +var __defProp = Object.defineProperty; +var __defProps = Object.defineProperties; +var __getOwnPropDescs = Object.getOwnPropertyDescriptors; +var __getOwnPropSymbols = Object.getOwnPropertySymbols; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __propIsEnum = Object.prototype.propertyIsEnumerable; +var __typeError = (msg) => { + throw TypeError(msg); +}; +var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __spreadValues = (a, b) => { + for (var prop in b || (b = {})) + if (__hasOwnProp.call(b, prop)) + __defNormalProp(a, prop, b[prop]); + if (__getOwnPropSymbols) + for (var prop of __getOwnPropSymbols(b)) { + if (__propIsEnum.call(b, prop)) + __defNormalProp(a, prop, b[prop]); + } + return a; +}; +var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b)); +var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); +var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg); +var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)); +var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value); +var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value); +var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method); +var __async = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +var _PrimitiveNode_instances, onFirstConnection_fn, createWidget_fn, mergeWidgetConfig_fn, isValidConnection_fn, removeWidgets_fn, _convertedToProcess; +import { C as ComfyDialog, $ as $el, a as ComfyApp, b as app, L as LGraphCanvas, c as LiteGraph, d as applyTextReplacements, e as ComfyWidgets, f as addValueControlWidgets, D as DraggableList, g as api, h as LGraphGroup, i as LGraphNode } from "./index-DIiqwEjy.js"; +const _ClipspaceDialog = class _ClipspaceDialog extends ComfyDialog { + static registerButton(name, contextPredicate, callback) { + const item = $el("button", { + type: "button", + textContent: name, + contextPredicate, + onclick: callback + }); + _ClipspaceDialog.items.push(item); + } + static invalidatePreview() { + if (ComfyApp.clipspace && ComfyApp.clipspace.imgs && ComfyApp.clipspace.imgs.length > 0) { + const img_preview = document.getElementById( + "clipspace_preview" + ); + if (img_preview) { + img_preview.src = ComfyApp.clipspace.imgs[ComfyApp.clipspace["selectedIndex"]].src; + img_preview.style.maxHeight = "100%"; + img_preview.style.maxWidth = "100%"; + } + } + } + static invalidate() { + if (_ClipspaceDialog.instance) { + const self = _ClipspaceDialog.instance; + const children = $el("div.comfy-modal-content", [ + self.createImgSettings(), + ...self.createButtons() + ]); + if (self.element) { + self.element.removeChild(self.element.firstChild); + self.element.appendChild(children); + } else { + self.element = $el("div.comfy-modal", { parent: document.body }, [ + children + ]); + } + if (self.element.children[0].children.length <= 1) { + self.element.children[0].appendChild( + $el("p", {}, [ + "Unable to find the features to edit content of a format stored in the current Clipspace." + ]) + ); + } + _ClipspaceDialog.invalidatePreview(); + } + } + constructor() { + super(); + } + createButtons() { + const buttons = []; + for (let idx in _ClipspaceDialog.items) { + const item = _ClipspaceDialog.items[idx]; + if (!item.contextPredicate || item.contextPredicate()) + buttons.push(_ClipspaceDialog.items[idx]); + } + buttons.push( + $el("button", { + type: "button", + textContent: "Close", + onclick: () => { + this.close(); + } + }) + ); + return buttons; + } + createImgSettings() { + if (ComfyApp.clipspace.imgs) { + const combo_items = []; + const imgs = ComfyApp.clipspace.imgs; + for (let i = 0; i < imgs.length; i++) { + combo_items.push($el("option", { value: i }, [`${i}`])); + } + const combo1 = $el( + "select", + { + id: "clipspace_img_selector", + onchange: (event) => { + ComfyApp.clipspace["selectedIndex"] = event.target.selectedIndex; + _ClipspaceDialog.invalidatePreview(); + } + }, + combo_items + ); + const row1 = $el("tr", {}, [ + $el("td", {}, [$el("font", { color: "white" }, ["Select Image"])]), + $el("td", {}, [combo1]) + ]); + const combo2 = $el( + "select", + { + id: "clipspace_img_paste_mode", + onchange: (event) => { + ComfyApp.clipspace["img_paste_mode"] = event.target.value; + } + }, + [ + $el("option", { value: "selected" }, "selected"), + $el("option", { value: "all" }, "all") + ] + ); + combo2.value = ComfyApp.clipspace["img_paste_mode"]; + const row2 = $el("tr", {}, [ + $el("td", {}, [$el("font", { color: "white" }, ["Paste Mode"])]), + $el("td", {}, [combo2]) + ]); + const td = $el( + "td", + { align: "center", width: "100px", height: "100px", colSpan: "2" }, + [$el("img", { id: "clipspace_preview", ondragstart: () => false }, [])] + ); + const row3 = $el("tr", {}, [td]); + return $el("table", {}, [row1, row2, row3]); + } else { + return []; + } + } + createImgPreview() { + if (ComfyApp.clipspace.imgs) { + return $el("img", { id: "clipspace_preview", ondragstart: () => false }); + } else return []; + } + show() { + const img_preview = document.getElementById("clipspace_preview"); + _ClipspaceDialog.invalidate(); + this.element.style.display = "block"; + } +}; +__publicField(_ClipspaceDialog, "items", []); +__publicField(_ClipspaceDialog, "instance", null); +let ClipspaceDialog = _ClipspaceDialog; +app.registerExtension({ + name: "Comfy.Clipspace", + init(app2) { + app2.openClipspace = function() { + if (!ClipspaceDialog.instance) { + ClipspaceDialog.instance = new ClipspaceDialog(); + ComfyApp.clipspace_invalidate_handler = ClipspaceDialog.invalidate; + } + if (ComfyApp.clipspace) { + ClipspaceDialog.instance.show(); + } else app2.ui.dialog.show("Clipspace is Empty!"); + }; + } +}); +window.comfyAPI = window.comfyAPI || {}; +window.comfyAPI.clipspace = window.comfyAPI.clipspace || {}; +window.comfyAPI.clipspace.ClipspaceDialog = ClipspaceDialog; +const colorPalettes = { + dark: { + id: "dark", + name: "Dark (Default)", + colors: { + node_slot: { + CLIP: "#FFD500", + // bright yellow + CLIP_VISION: "#A8DADC", + // light blue-gray + CLIP_VISION_OUTPUT: "#ad7452", + // rusty brown-orange + CONDITIONING: "#FFA931", + // vibrant orange-yellow + CONTROL_NET: "#6EE7B7", + // soft mint green + IMAGE: "#64B5F6", + // bright sky blue + LATENT: "#FF9CF9", + // light pink-purple + MASK: "#81C784", + // muted green + MODEL: "#B39DDB", + // light lavender-purple + STYLE_MODEL: "#C2FFAE", + // light green-yellow + VAE: "#FF6E6E", + // bright red + NOISE: "#B0B0B0", + // gray + GUIDER: "#66FFFF", + // cyan + SAMPLER: "#ECB4B4", + // very soft red + SIGMAS: "#CDFFCD", + // soft lime green + TAESD: "#DCC274" + // cheesecake + }, + litegraph_base: { + BACKGROUND_IMAGE: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAQBJREFUeNrs1rEKwjAUhlETUkj3vP9rdmr1Ysammk2w5wdxuLgcMHyptfawuZX4pJSWZTnfnu/lnIe/jNNxHHGNn//HNbbv+4dr6V+11uF527arU7+u63qfa/bnmh8sWLBgwYJlqRf8MEptXPBXJXa37BSl3ixYsGDBMliwFLyCV/DeLIMFCxYsWLBMwSt4Be/NggXLYMGCBUvBK3iNruC9WbBgwYJlsGApeAWv4L1ZBgsWLFiwYJmCV/AK3psFC5bBggULloJX8BpdwXuzYMGCBctgwVLwCl7Be7MMFixYsGDBsu8FH1FaSmExVfAxBa/gvVmwYMGCZbBg/W4vAQYA5tRF9QYlv/QAAAAASUVORK5CYII=", + CLEAR_BACKGROUND_COLOR: "#222", + NODE_TITLE_COLOR: "#999", + NODE_SELECTED_TITLE_COLOR: "#FFF", + NODE_TEXT_SIZE: 14, + NODE_TEXT_COLOR: "#AAA", + NODE_SUBTEXT_SIZE: 12, + NODE_DEFAULT_COLOR: "#333", + NODE_DEFAULT_BGCOLOR: "#353535", + NODE_DEFAULT_BOXCOLOR: "#666", + NODE_DEFAULT_SHAPE: "box", + NODE_BOX_OUTLINE_COLOR: "#FFF", + DEFAULT_SHADOW_COLOR: "rgba(0,0,0,0.5)", + DEFAULT_GROUP_FONT: 24, + WIDGET_BGCOLOR: "#222", + WIDGET_OUTLINE_COLOR: "#666", + WIDGET_TEXT_COLOR: "#DDD", + WIDGET_SECONDARY_TEXT_COLOR: "#999", + LINK_COLOR: "#9A9", + EVENT_LINK_COLOR: "#A86", + CONNECTING_LINK_COLOR: "#AFA" + }, + comfy_base: { + "fg-color": "#fff", + "bg-color": "#202020", + "comfy-menu-bg": "#353535", + "comfy-input-bg": "#222", + "input-text": "#ddd", + "descrip-text": "#999", + "drag-text": "#ccc", + "error-text": "#ff4444", + "border-color": "#4e4e4e", + "tr-even-bg-color": "#222", + "tr-odd-bg-color": "#353535", + "content-bg": "#4e4e4e", + "content-fg": "#fff", + "content-hover-bg": "#222", + "content-hover-fg": "#fff" + } + } + }, + light: { + id: "light", + name: "Light", + colors: { + node_slot: { + CLIP: "#FFA726", + // orange + CLIP_VISION: "#5C6BC0", + // indigo + CLIP_VISION_OUTPUT: "#8D6E63", + // brown + CONDITIONING: "#EF5350", + // red + CONTROL_NET: "#66BB6A", + // green + IMAGE: "#42A5F5", + // blue + LATENT: "#AB47BC", + // purple + MASK: "#9CCC65", + // light green + MODEL: "#7E57C2", + // deep purple + STYLE_MODEL: "#D4E157", + // lime + VAE: "#FF7043" + // deep orange + }, + litegraph_base: { + BACKGROUND_IMAGE: "data:image/gif;base64,R0lGODlhZABkALMAAAAAAP///+vr6+rq6ujo6Ofn5+bm5uXl5d3d3f///wAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAAkALAAAAABkAGQAAAT/UMhJq7046827HkcoHkYxjgZhnGG6si5LqnIM0/fL4qwwIMAg0CAsEovBIxKhRDaNy2GUOX0KfVFrssrNdpdaqTeKBX+dZ+jYvEaTf+y4W66mC8PUdrE879f9d2mBeoNLfH+IhYBbhIx2jkiHiomQlGKPl4uZe3CaeZifnnijgkESBqipqqusra6vsLGys62SlZO4t7qbuby7CLa+wqGWxL3Gv3jByMOkjc2lw8vOoNSi0czAncXW3Njdx9Pf48/Z4Kbbx+fQ5evZ4u3k1fKR6cn03vHlp7T9/v8A/8Gbp4+gwXoFryXMB2qgwoMMHyKEqA5fxX322FG8tzBcRnMW/zlulPbRncmQGidKjMjyYsOSKEF2FBlJQMCbOHP6c9iSZs+UnGYCdbnSo1CZI5F64kn0p1KnTH02nSoV3dGTV7FFHVqVq1dtWcMmVQZTbNGu72zqXMuW7danVL+6e4t1bEy6MeueBYLXrNO5Ze36jQtWsOG97wIj1vt3St/DjTEORss4nNq2mDP3e7w4r1bFkSET5hy6s2TRlD2/mSxXtSHQhCunXo26NevCpmvD/UU6tuullzULH76q92zdZG/Ltv1a+W+osI/nRmyc+fRi1Xdbh+68+0vv10dH3+77KD/i6IdnX669/frn5Zsjh4/2PXju8+8bzc9/6fj27LFnX11/+IUnXWl7BJfegm79FyB9JOl3oHgSklefgxAC+FmFGpqHIYcCfkhgfCohSKKJVo044YUMttggiBkmp6KFXw1oII24oYhjiDByaKOOHcp3Y5BD/njikSkO+eBREQAAOw==", + CLEAR_BACKGROUND_COLOR: "lightgray", + NODE_TITLE_COLOR: "#222", + NODE_SELECTED_TITLE_COLOR: "#000", + NODE_TEXT_SIZE: 14, + NODE_TEXT_COLOR: "#444", + NODE_SUBTEXT_SIZE: 12, + NODE_DEFAULT_COLOR: "#F7F7F7", + NODE_DEFAULT_BGCOLOR: "#F5F5F5", + NODE_DEFAULT_BOXCOLOR: "#CCC", + NODE_DEFAULT_SHAPE: "box", + NODE_BOX_OUTLINE_COLOR: "#000", + DEFAULT_SHADOW_COLOR: "rgba(0,0,0,0.1)", + DEFAULT_GROUP_FONT: 24, + WIDGET_BGCOLOR: "#D4D4D4", + WIDGET_OUTLINE_COLOR: "#999", + WIDGET_TEXT_COLOR: "#222", + WIDGET_SECONDARY_TEXT_COLOR: "#555", + LINK_COLOR: "#4CAF50", + EVENT_LINK_COLOR: "#FF9800", + CONNECTING_LINK_COLOR: "#2196F3" + }, + comfy_base: { + "fg-color": "#222", + "bg-color": "#DDD", + "comfy-menu-bg": "#F5F5F5", + "comfy-input-bg": "#C9C9C9", + "input-text": "#222", + "descrip-text": "#444", + "drag-text": "#555", + "error-text": "#F44336", + "border-color": "#888", + "tr-even-bg-color": "#f9f9f9", + "tr-odd-bg-color": "#fff", + "content-bg": "#e0e0e0", + "content-fg": "#222", + "content-hover-bg": "#adadad", + "content-hover-fg": "#222" + } + } + }, + solarized: { + id: "solarized", + name: "Solarized", + colors: { + node_slot: { + CLIP: "#2AB7CA", + // light blue + CLIP_VISION: "#6c71c4", + // blue violet + CLIP_VISION_OUTPUT: "#859900", + // olive green + CONDITIONING: "#d33682", + // magenta + CONTROL_NET: "#d1ffd7", + // light mint green + IMAGE: "#5940bb", + // deep blue violet + LATENT: "#268bd2", + // blue + MASK: "#CCC9E7", + // light purple-gray + MODEL: "#dc322f", + // red + STYLE_MODEL: "#1a998a", + // teal + UPSCALE_MODEL: "#054A29", + // dark green + VAE: "#facfad" + // light pink-orange + }, + litegraph_base: { + NODE_TITLE_COLOR: "#fdf6e3", + // Base3 + NODE_SELECTED_TITLE_COLOR: "#A9D400", + NODE_TEXT_SIZE: 14, + NODE_TEXT_COLOR: "#657b83", + // Base00 + NODE_SUBTEXT_SIZE: 12, + NODE_DEFAULT_COLOR: "#094656", + NODE_DEFAULT_BGCOLOR: "#073642", + // Base02 + NODE_DEFAULT_BOXCOLOR: "#839496", + // Base0 + NODE_DEFAULT_SHAPE: "box", + NODE_BOX_OUTLINE_COLOR: "#fdf6e3", + // Base3 + DEFAULT_SHADOW_COLOR: "rgba(0,0,0,0.5)", + DEFAULT_GROUP_FONT: 24, + WIDGET_BGCOLOR: "#002b36", + // Base03 + WIDGET_OUTLINE_COLOR: "#839496", + // Base0 + WIDGET_TEXT_COLOR: "#fdf6e3", + // Base3 + WIDGET_SECONDARY_TEXT_COLOR: "#93a1a1", + // Base1 + LINK_COLOR: "#2aa198", + // Solarized Cyan + EVENT_LINK_COLOR: "#268bd2", + // Solarized Blue + CONNECTING_LINK_COLOR: "#859900" + // Solarized Green + }, + comfy_base: { + "fg-color": "#fdf6e3", + // Base3 + "bg-color": "#002b36", + // Base03 + "comfy-menu-bg": "#073642", + // Base02 + "comfy-input-bg": "#002b36", + // Base03 + "input-text": "#93a1a1", + // Base1 + "descrip-text": "#586e75", + // Base01 + "drag-text": "#839496", + // Base0 + "error-text": "#dc322f", + // Solarized Red + "border-color": "#657b83", + // Base00 + "tr-even-bg-color": "#002b36", + "tr-odd-bg-color": "#073642", + "content-bg": "#657b83", + "content-fg": "#fdf6e3", + "content-hover-bg": "#002b36", + "content-hover-fg": "#fdf6e3" + } + } + }, + arc: { + id: "arc", + name: "Arc", + colors: { + node_slot: { + BOOLEAN: "", + CLIP: "#eacb8b", + CLIP_VISION: "#A8DADC", + CLIP_VISION_OUTPUT: "#ad7452", + CONDITIONING: "#cf876f", + CONTROL_NET: "#00d78d", + CONTROL_NET_WEIGHTS: "", + FLOAT: "", + GLIGEN: "", + IMAGE: "#80a1c0", + IMAGEUPLOAD: "", + INT: "", + LATENT: "#b38ead", + LATENT_KEYFRAME: "", + MASK: "#a3bd8d", + MODEL: "#8978a7", + SAMPLER: "", + SIGMAS: "", + STRING: "", + STYLE_MODEL: "#C2FFAE", + T2I_ADAPTER_WEIGHTS: "", + TAESD: "#DCC274", + TIMESTEP_KEYFRAME: "", + UPSCALE_MODEL: "", + VAE: "#be616b" + }, + litegraph_base: { + BACKGROUND_IMAGE: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAACXBIWXMAAAsTAAALEwEAmpwYAAABcklEQVR4nO3YMUoDARgF4RfxBqZI6/0vZqFn0MYtrLIQMFN8U6V4LAtD+Jm9XG/v30OGl2e/AP7yevz4+vx45nvgF/+QGITEICQGITEIiUFIjNNC3q43u3/YnRJyPOzeQ+0e220nhRzReC8e7R7bbdvl+Jal1Bs46jEIiUFIDEJiEBKDkBhKPbZT6qHdptRTu02p53DUYxASg5AYhMQgJAYhMZR6bKfUQ7tNqad2m1LP4ajHICQGITEIiUFIDEJiKPXYTqmHdptST+02pZ7DUY9BSAxCYhASg5AYhMRQ6rGdUg/tNqWe2m1KPYejHoOQGITEICQGITEIiaHUYzulHtptSj2125R6Dkc9BiExCIlBSAxCYhASQ6nHdko9tNuUemq3KfUcjnoMQmIQEoOQGITEICSGUo/tlHpotyn11G5T6jkc9RiExCAkBiExCIlBSAylHtsp9dBuU+qp3abUczjqMQiJQUgMQmIQEoOQGITE+AHFISNQrFTGuwAAAABJRU5ErkJggg==", + CLEAR_BACKGROUND_COLOR: "#2b2f38", + NODE_TITLE_COLOR: "#b2b7bd", + NODE_SELECTED_TITLE_COLOR: "#FFF", + NODE_TEXT_SIZE: 14, + NODE_TEXT_COLOR: "#AAA", + NODE_SUBTEXT_SIZE: 12, + NODE_DEFAULT_COLOR: "#2b2f38", + NODE_DEFAULT_BGCOLOR: "#242730", + NODE_DEFAULT_BOXCOLOR: "#6e7581", + NODE_DEFAULT_SHAPE: "box", + NODE_BOX_OUTLINE_COLOR: "#FFF", + DEFAULT_SHADOW_COLOR: "rgba(0,0,0,0.5)", + DEFAULT_GROUP_FONT: 22, + WIDGET_BGCOLOR: "#2b2f38", + WIDGET_OUTLINE_COLOR: "#6e7581", + WIDGET_TEXT_COLOR: "#DDD", + WIDGET_SECONDARY_TEXT_COLOR: "#b2b7bd", + LINK_COLOR: "#9A9", + EVENT_LINK_COLOR: "#A86", + CONNECTING_LINK_COLOR: "#AFA" + }, + comfy_base: { + "fg-color": "#fff", + "bg-color": "#2b2f38", + "comfy-menu-bg": "#242730", + "comfy-input-bg": "#2b2f38", + "input-text": "#ddd", + "descrip-text": "#b2b7bd", + "drag-text": "#ccc", + "error-text": "#ff4444", + "border-color": "#6e7581", + "tr-even-bg-color": "#2b2f38", + "tr-odd-bg-color": "#242730", + "content-bg": "#6e7581", + "content-fg": "#fff", + "content-hover-bg": "#2b2f38", + "content-hover-fg": "#fff" + } + } + }, + nord: { + id: "nord", + name: "Nord", + colors: { + node_slot: { + BOOLEAN: "", + CLIP: "#eacb8b", + CLIP_VISION: "#A8DADC", + CLIP_VISION_OUTPUT: "#ad7452", + CONDITIONING: "#cf876f", + CONTROL_NET: "#00d78d", + CONTROL_NET_WEIGHTS: "", + FLOAT: "", + GLIGEN: "", + IMAGE: "#80a1c0", + IMAGEUPLOAD: "", + INT: "", + LATENT: "#b38ead", + LATENT_KEYFRAME: "", + MASK: "#a3bd8d", + MODEL: "#8978a7", + SAMPLER: "", + SIGMAS: "", + STRING: "", + STYLE_MODEL: "#C2FFAE", + T2I_ADAPTER_WEIGHTS: "", + TAESD: "#DCC274", + TIMESTEP_KEYFRAME: "", + UPSCALE_MODEL: "", + VAE: "#be616b" + }, + litegraph_base: { + BACKGROUND_IMAGE: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAAAACXBIWXMAAAsTAAALEwEAmpwYAAAFu2lUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4gPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iQWRvYmUgWE1QIENvcmUgOS4xLWMwMDEgNzkuMTQ2Mjg5OSwgMjAyMy8wNi8yNS0yMDowMTo1NSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczpkYz0iaHR0cDovL3B1cmwub3JnL2RjL2VsZW1lbnRzLzEuMS8iIHhtbG5zOnBob3Rvc2hvcD0iaHR0cDovL25zLmFkb2JlLmNvbS9waG90b3Nob3AvMS4wLyIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0RXZ0PSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VFdmVudCMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIDI1LjEgKFdpbmRvd3MpIiB4bXA6Q3JlYXRlRGF0ZT0iMjAyMy0xMS0xM1QwMDoxODowMiswMTowMCIgeG1wOk1vZGlmeURhdGU9IjIwMjMtMTEtMTVUMDE6MjA6NDUrMDE6MDAiIHhtcDpNZXRhZGF0YURhdGU9IjIwMjMtMTEtMTVUMDE6MjA6NDUrMDE6MDAiIGRjOmZvcm1hdD0iaW1hZ2UvcG5nIiBwaG90b3Nob3A6Q29sb3JNb2RlPSIzIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOjUwNDFhMmZjLTEzNzQtMTk0ZC1hZWY4LTYxMzM1MTVmNjUwMCIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDoyMzFiMTBiMC1iNGZiLTAyNGUtYjEyZS0zMDUzMDNjZDA3YzgiIHhtcE1NOk9yaWdpbmFsRG9jdW1lbnRJRD0ieG1wLmRpZDoyMzFiMTBiMC1iNGZiLTAyNGUtYjEyZS0zMDUzMDNjZDA3YzgiPiA8eG1wTU06SGlzdG9yeT4gPHJkZjpTZXE+IDxyZGY6bGkgc3RFdnQ6YWN0aW9uPSJjcmVhdGVkIiBzdEV2dDppbnN0YW5jZUlEPSJ4bXAuaWlkOjIzMWIxMGIwLWI0ZmItMDI0ZS1iMTJlLTMwNTMwM2NkMDdjOCIgc3RFdnQ6d2hlbj0iMjAyMy0xMS0xM1QwMDoxODowMiswMTowMCIgc3RFdnQ6c29mdHdhcmVBZ2VudD0iQWRvYmUgUGhvdG9zaG9wIDI1LjEgKFdpbmRvd3MpIi8+IDxyZGY6bGkgc3RFdnQ6YWN0aW9uPSJzYXZlZCIgc3RFdnQ6aW5zdGFuY2VJRD0ieG1wLmlpZDo1MDQxYTJmYy0xMzc0LTE5NGQtYWVmOC02MTMzNTE1ZjY1MDAiIHN0RXZ0OndoZW49IjIwMjMtMTEtMTVUMDE6MjA6NDUrMDE6MDAiIHN0RXZ0OnNvZnR3YXJlQWdlbnQ9IkFkb2JlIFBob3Rvc2hvcCAyNS4xIChXaW5kb3dzKSIgc3RFdnQ6Y2hhbmdlZD0iLyIvPiA8L3JkZjpTZXE+IDwveG1wTU06SGlzdG9yeT4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz73jWg/AAAAyUlEQVR42u3WKwoAIBRFQRdiMb1idv9Lsxn9gEFw4Dbb8JCTojbbXEJwjJVL2HKwYMGCBQuWLbDmjr+9zrBGjHl1WVcvy2DBggULFizTWQpewSt4HzwsgwULFiwFr7MUvMtS8D54WLBgGSxYCl7BK3iXZbBgwYIFC5bpLAWv4BW8Dx6WwYIFC5aC11kK3mUpeB88LFiwDBYsBa/gFbzLMliwYMGCBct0loJX8AreBw/LYMGCBUvB6ywF77IUvA8eFixYBgsWrNfWAZPltufdad+1AAAAAElFTkSuQmCC", + CLEAR_BACKGROUND_COLOR: "#212732", + NODE_TITLE_COLOR: "#999", + NODE_SELECTED_TITLE_COLOR: "#e5eaf0", + NODE_TEXT_SIZE: 14, + NODE_TEXT_COLOR: "#bcc2c8", + NODE_SUBTEXT_SIZE: 12, + NODE_DEFAULT_COLOR: "#2e3440", + NODE_DEFAULT_BGCOLOR: "#161b22", + NODE_DEFAULT_BOXCOLOR: "#545d70", + NODE_DEFAULT_SHAPE: "box", + NODE_BOX_OUTLINE_COLOR: "#e5eaf0", + DEFAULT_SHADOW_COLOR: "rgba(0,0,0,0.5)", + DEFAULT_GROUP_FONT: 24, + WIDGET_BGCOLOR: "#2e3440", + WIDGET_OUTLINE_COLOR: "#545d70", + WIDGET_TEXT_COLOR: "#bcc2c8", + WIDGET_SECONDARY_TEXT_COLOR: "#999", + LINK_COLOR: "#9A9", + EVENT_LINK_COLOR: "#A86", + CONNECTING_LINK_COLOR: "#AFA" + }, + comfy_base: { + "fg-color": "#e5eaf0", + "bg-color": "#2e3440", + "comfy-menu-bg": "#161b22", + "comfy-input-bg": "#2e3440", + "input-text": "#bcc2c8", + "descrip-text": "#999", + "drag-text": "#ccc", + "error-text": "#ff4444", + "border-color": "#545d70", + "tr-even-bg-color": "#2e3440", + "tr-odd-bg-color": "#161b22", + "content-bg": "#545d70", + "content-fg": "#e5eaf0", + "content-hover-bg": "#2e3440", + "content-hover-fg": "#e5eaf0" + } + } + }, + github: { + id: "github", + name: "Github", + colors: { + node_slot: { + BOOLEAN: "", + CLIP: "#eacb8b", + CLIP_VISION: "#A8DADC", + CLIP_VISION_OUTPUT: "#ad7452", + CONDITIONING: "#cf876f", + CONTROL_NET: "#00d78d", + CONTROL_NET_WEIGHTS: "", + FLOAT: "", + GLIGEN: "", + IMAGE: "#80a1c0", + IMAGEUPLOAD: "", + INT: "", + LATENT: "#b38ead", + LATENT_KEYFRAME: "", + MASK: "#a3bd8d", + MODEL: "#8978a7", + SAMPLER: "", + SIGMAS: "", + STRING: "", + STYLE_MODEL: "#C2FFAE", + T2I_ADAPTER_WEIGHTS: "", + TAESD: "#DCC274", + TIMESTEP_KEYFRAME: "", + UPSCALE_MODEL: "", + VAE: "#be616b" + }, + litegraph_base: { + BACKGROUND_IMAGE: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAAAACXBIWXMAAAsTAAALEwEAmpwYAAAGlmlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4gPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iQWRvYmUgWE1QIENvcmUgOS4xLWMwMDEgNzkuMTQ2Mjg5OSwgMjAyMy8wNi8yNS0yMDowMTo1NSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczpkYz0iaHR0cDovL3B1cmwub3JnL2RjL2VsZW1lbnRzLzEuMS8iIHhtbG5zOnBob3Rvc2hvcD0iaHR0cDovL25zLmFkb2JlLmNvbS9waG90b3Nob3AvMS4wLyIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0RXZ0PSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VFdmVudCMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIDI1LjEgKFdpbmRvd3MpIiB4bXA6Q3JlYXRlRGF0ZT0iMjAyMy0xMS0xM1QwMDoxODowMiswMTowMCIgeG1wOk1vZGlmeURhdGU9IjIwMjMtMTEtMTVUMDI6MDQ6NTkrMDE6MDAiIHhtcDpNZXRhZGF0YURhdGU9IjIwMjMtMTEtMTVUMDI6MDQ6NTkrMDE6MDAiIGRjOmZvcm1hdD0iaW1hZ2UvcG5nIiBwaG90b3Nob3A6Q29sb3JNb2RlPSIzIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOmIyYzRhNjA5LWJmYTctYTg0MC1iOGFlLTk3MzE2ZjM1ZGIyNyIgeG1wTU06RG9jdW1lbnRJRD0iYWRvYmU6ZG9jaWQ6cGhvdG9zaG9wOjk0ZmNlZGU4LTE1MTctZmQ0MC04ZGU3LWYzOTgxM2E3ODk5ZiIgeG1wTU06T3JpZ2luYWxEb2N1bWVudElEPSJ4bXAuZGlkOjIzMWIxMGIwLWI0ZmItMDI0ZS1iMTJlLTMwNTMwM2NkMDdjOCI+IDx4bXBNTTpIaXN0b3J5PiA8cmRmOlNlcT4gPHJkZjpsaSBzdEV2dDphY3Rpb249ImNyZWF0ZWQiIHN0RXZ0Omluc3RhbmNlSUQ9InhtcC5paWQ6MjMxYjEwYjAtYjRmYi0wMjRlLWIxMmUtMzA1MzAzY2QwN2M4IiBzdEV2dDp3aGVuPSIyMDIzLTExLTEzVDAwOjE4OjAyKzAxOjAwIiBzdEV2dDpzb2Z0d2FyZUFnZW50PSJBZG9iZSBQaG90b3Nob3AgMjUuMSAoV2luZG93cykiLz4gPHJkZjpsaSBzdEV2dDphY3Rpb249InNhdmVkIiBzdEV2dDppbnN0YW5jZUlEPSJ4bXAuaWlkOjQ4OWY1NzlmLTJkNjUtZWQ0Zi04OTg0LTA4NGE2MGE1ZTMzNSIgc3RFdnQ6d2hlbj0iMjAyMy0xMS0xNVQwMjowNDo1OSswMTowMCIgc3RFdnQ6c29mdHdhcmVBZ2VudD0iQWRvYmUgUGhvdG9zaG9wIDI1LjEgKFdpbmRvd3MpIiBzdEV2dDpjaGFuZ2VkPSIvIi8+IDxyZGY6bGkgc3RFdnQ6YWN0aW9uPSJzYXZlZCIgc3RFdnQ6aW5zdGFuY2VJRD0ieG1wLmlpZDpiMmM0YTYwOS1iZmE3LWE4NDAtYjhhZS05NzMxNmYzNWRiMjciIHN0RXZ0OndoZW49IjIwMjMtMTEtMTVUMDI6MDQ6NTkrMDE6MDAiIHN0RXZ0OnNvZnR3YXJlQWdlbnQ9IkFkb2JlIFBob3Rvc2hvcCAyNS4xIChXaW5kb3dzKSIgc3RFdnQ6Y2hhbmdlZD0iLyIvPiA8L3JkZjpTZXE+IDwveG1wTU06SGlzdG9yeT4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz4OTe6GAAAAx0lEQVR42u3WMQoAIQxFwRzJys77X8vSLiRgITif7bYbgrwYc/mKXyBoY4VVBgsWLFiwYFmOlTv+9jfDOjHmr8u6eVkGCxYsWLBgmc5S8ApewXvgYRksWLBgKXidpeBdloL3wMOCBctgwVLwCl7BuyyDBQsWLFiwTGcpeAWv4D3wsAwWLFiwFLzOUvAuS8F74GHBgmWwYCl4Ba/gXZbBggULFixYprMUvIJX8B54WAYLFixYCl5nKXiXpeA98LBgwTJYsGC9tg1o8f4TTtqzNQAAAABJRU5ErkJggg==", + CLEAR_BACKGROUND_COLOR: "#040506", + NODE_TITLE_COLOR: "#999", + NODE_SELECTED_TITLE_COLOR: "#e5eaf0", + NODE_TEXT_SIZE: 14, + NODE_TEXT_COLOR: "#bcc2c8", + NODE_SUBTEXT_SIZE: 12, + NODE_DEFAULT_COLOR: "#161b22", + NODE_DEFAULT_BGCOLOR: "#13171d", + NODE_DEFAULT_BOXCOLOR: "#30363d", + NODE_DEFAULT_SHAPE: "box", + NODE_BOX_OUTLINE_COLOR: "#e5eaf0", + DEFAULT_SHADOW_COLOR: "rgba(0,0,0,0.5)", + DEFAULT_GROUP_FONT: 24, + WIDGET_BGCOLOR: "#161b22", + WIDGET_OUTLINE_COLOR: "#30363d", + WIDGET_TEXT_COLOR: "#bcc2c8", + WIDGET_SECONDARY_TEXT_COLOR: "#999", + LINK_COLOR: "#9A9", + EVENT_LINK_COLOR: "#A86", + CONNECTING_LINK_COLOR: "#AFA" + }, + comfy_base: { + "fg-color": "#e5eaf0", + "bg-color": "#161b22", + "comfy-menu-bg": "#13171d", + "comfy-input-bg": "#161b22", + "input-text": "#bcc2c8", + "descrip-text": "#999", + "drag-text": "#ccc", + "error-text": "#ff4444", + "border-color": "#30363d", + "tr-even-bg-color": "#161b22", + "tr-odd-bg-color": "#13171d", + "content-bg": "#30363d", + "content-fg": "#e5eaf0", + "content-hover-bg": "#161b22", + "content-hover-fg": "#e5eaf0" + } + } + } +}; +const id$4 = "Comfy.ColorPalette"; +const idCustomColorPalettes = "Comfy.CustomColorPalettes"; +const defaultColorPaletteId = "dark"; +const els = { + select: null +}; +app.registerExtension({ + name: id$4, + init() { + LGraphCanvas.prototype.updateBackground = function(image, clearBackgroundColor) { + this._bg_img = new Image(); + this._bg_img.name = image; + this._bg_img.src = image; + this._bg_img.onload = () => { + this.draw(true, true); + }; + this.background_image = image; + this.clear_background = true; + this.clear_background_color = clearBackgroundColor; + this._pattern = null; + }; + }, + addCustomNodeDefs(node_defs) { + const sortObjectKeys = (unordered) => { + return Object.keys(unordered).sort().reduce((obj, key) => { + obj[key] = unordered[key]; + return obj; + }, {}); + }; + function getSlotTypes() { + var types = []; + const defs = node_defs; + for (const nodeId in defs) { + const nodeData = defs[nodeId]; + var inputs = nodeData["input"]["required"]; + if (nodeData["input"]["optional"] !== void 0) { + inputs = Object.assign( + {}, + nodeData["input"]["required"], + nodeData["input"]["optional"] + ); + } + for (const inputName in inputs) { + const inputData = inputs[inputName]; + const type = inputData[0]; + if (!Array.isArray(type)) { + types.push(type); + } + } + for (const o in nodeData["output"]) { + const output = nodeData["output"][o]; + types.push(output); + } + } + return types; + } + function completeColorPalette(colorPalette) { + var types = getSlotTypes(); + for (const type of types) { + if (!colorPalette.colors.node_slot[type]) { + colorPalette.colors.node_slot[type] = ""; + } + } + colorPalette.colors.node_slot = sortObjectKeys( + colorPalette.colors.node_slot + ); + return colorPalette; + } + const getColorPaletteTemplate = () => __async(this, null, function* () { + let colorPalette = { + id: "my_color_palette_unique_id", + name: "My Color Palette", + colors: { + node_slot: {}, + litegraph_base: {}, + comfy_base: {} + } + }; + const defaultColorPalette = colorPalettes[defaultColorPaletteId]; + for (const key in defaultColorPalette.colors.litegraph_base) { + if (!colorPalette.colors.litegraph_base[key]) { + colorPalette.colors.litegraph_base[key] = ""; + } + } + for (const key in defaultColorPalette.colors.comfy_base) { + if (!colorPalette.colors.comfy_base[key]) { + colorPalette.colors.comfy_base[key] = ""; + } + } + return completeColorPalette(colorPalette); + }); + const getCustomColorPalettes = () => { + return app.ui.settings.getSettingValue(idCustomColorPalettes, {}); + }; + const setCustomColorPalettes = (customColorPalettes) => { + return app.ui.settings.setSettingValue( + idCustomColorPalettes, + customColorPalettes + ); + }; + const addCustomColorPalette = (colorPalette) => __async(this, null, function* () { + if (typeof colorPalette !== "object") { + alert("Invalid color palette."); + return; + } + if (!colorPalette.id) { + alert("Color palette missing id."); + return; + } + if (!colorPalette.name) { + alert("Color palette missing name."); + return; + } + if (!colorPalette.colors) { + alert("Color palette missing colors."); + return; + } + if (colorPalette.colors.node_slot && typeof colorPalette.colors.node_slot !== "object") { + alert("Invalid color palette colors.node_slot."); + return; + } + const customColorPalettes = getCustomColorPalettes(); + customColorPalettes[colorPalette.id] = colorPalette; + setCustomColorPalettes(customColorPalettes); + for (const option of els.select.childNodes) { + if (option.value === "custom_" + colorPalette.id) { + els.select.removeChild(option); + } + } + els.select.append( + $el("option", { + textContent: colorPalette.name + " (custom)", + value: "custom_" + colorPalette.id, + selected: true + }) + ); + setColorPalette("custom_" + colorPalette.id); + yield loadColorPalette(colorPalette); + }); + const deleteCustomColorPalette = (colorPaletteId) => __async(this, null, function* () { + const customColorPalettes = getCustomColorPalettes(); + delete customColorPalettes[colorPaletteId]; + setCustomColorPalettes(customColorPalettes); + for (const opt of els.select.childNodes) { + const option = opt; + if (option.value === defaultColorPaletteId) { + option.selected = true; + } + if (option.value === "custom_" + colorPaletteId) { + els.select.removeChild(option); + } + } + setColorPalette(defaultColorPaletteId); + yield loadColorPalette(getColorPalette()); + }); + const loadColorPalette = (colorPalette) => __async(this, null, function* () { + colorPalette = yield completeColorPalette(colorPalette); + if (colorPalette.colors) { + if (colorPalette.colors.node_slot) { + Object.assign( + // @ts-expect-error + app.canvas.default_connection_color_byType, + colorPalette.colors.node_slot + ); + Object.assign( + LGraphCanvas.link_type_colors, + colorPalette.colors.node_slot + ); + } + if (colorPalette.colors.litegraph_base) { + app.canvas.node_title_color = colorPalette.colors.litegraph_base.NODE_TITLE_COLOR; + app.canvas.default_link_color = colorPalette.colors.litegraph_base.LINK_COLOR; + for (const key in colorPalette.colors.litegraph_base) { + if (colorPalette.colors.litegraph_base.hasOwnProperty(key) && LiteGraph.hasOwnProperty(key)) { + LiteGraph[key] = colorPalette.colors.litegraph_base[key]; + } + } + } + if (colorPalette.colors.comfy_base) { + const rootStyle = document.documentElement.style; + for (const key in colorPalette.colors.comfy_base) { + rootStyle.setProperty( + "--" + key, + colorPalette.colors.comfy_base[key] + ); + } + } + app.canvas.draw(true, true); + } + }); + const getColorPalette = (colorPaletteId) => { + if (!colorPaletteId) { + colorPaletteId = app.ui.settings.getSettingValue( + id$4, + defaultColorPaletteId + ); + } + if (colorPaletteId.startsWith("custom_")) { + colorPaletteId = colorPaletteId.substr(7); + let customColorPalettes = getCustomColorPalettes(); + if (customColorPalettes[colorPaletteId]) { + return customColorPalettes[colorPaletteId]; + } + } + return colorPalettes[colorPaletteId]; + }; + const setColorPalette = (colorPaletteId) => { + app.ui.settings.setSettingValue(id$4, colorPaletteId); + }; + const fileInput = $el("input", { + type: "file", + accept: ".json", + style: { display: "none" }, + parent: document.body, + onchange: () => { + const file2 = fileInput.files[0]; + if (file2.type === "application/json" || file2.name.endsWith(".json")) { + const reader = new FileReader(); + reader.onload = () => __async(this, null, function* () { + yield addCustomColorPalette(JSON.parse(reader.result)); + }); + reader.readAsText(file2); + } + } + }); + app.ui.settings.addSetting({ + id: id$4, + name: "Color Palette", + type: (name, setter, value) => { + const options = [ + ...Object.values(colorPalettes).map( + (c) => $el("option", { + textContent: c.name, + value: c.id, + selected: c.id === value + }) + ), + ...Object.values(getCustomColorPalettes()).map( + (c) => $el("option", { + textContent: `${c.name} (custom)`, + value: `custom_${c.id}`, + selected: `custom_${c.id}` === value + }) + ) + ]; + els.select = $el( + "select", + { + style: { + marginBottom: "0.15rem", + width: "100%" + }, + onchange: (e) => { + setter(e.target.value); + } + }, + options + ); + return $el("tr", [ + $el("td", [ + $el("label", { + for: id$4.replaceAll(".", "-"), + textContent: "Color palette" + }) + ]), + $el("td", [ + els.select, + $el( + "div", + { + style: { + display: "grid", + gap: "4px", + gridAutoFlow: "column" + } + }, + [ + $el("input", { + type: "button", + value: "Export", + onclick: () => __async(this, null, function* () { + const colorPaletteId = app.ui.settings.getSettingValue( + id$4, + defaultColorPaletteId + ); + const colorPalette = yield completeColorPalette( + getColorPalette(colorPaletteId) + ); + const json = JSON.stringify(colorPalette, null, 2); + const blob = new Blob([json], { type: "application/json" }); + const url = URL.createObjectURL(blob); + const a = $el("a", { + href: url, + download: colorPaletteId + ".json", + style: { display: "none" }, + parent: document.body + }); + a.click(); + setTimeout(function() { + a.remove(); + window.URL.revokeObjectURL(url); + }, 0); + }) + }), + $el("input", { + type: "button", + value: "Import", + onclick: () => { + fileInput.click(); + } + }), + $el("input", { + type: "button", + value: "Template", + onclick: () => __async(this, null, function* () { + const colorPalette = yield getColorPaletteTemplate(); + const json = JSON.stringify(colorPalette, null, 2); + const blob = new Blob([json], { type: "application/json" }); + const url = URL.createObjectURL(blob); + const a = $el("a", { + href: url, + download: "color_palette.json", + style: { display: "none" }, + parent: document.body + }); + a.click(); + setTimeout(function() { + a.remove(); + window.URL.revokeObjectURL(url); + }, 0); + }) + }), + $el("input", { + type: "button", + value: "Delete", + onclick: () => __async(this, null, function* () { + let colorPaletteId = app.ui.settings.getSettingValue( + id$4, + defaultColorPaletteId + ); + if (colorPalettes[colorPaletteId]) { + alert("You cannot delete a built-in color palette."); + return; + } + if (colorPaletteId.startsWith("custom_")) { + colorPaletteId = colorPaletteId.substr(7); + } + yield deleteCustomColorPalette(colorPaletteId); + }) + }) + ] + ) + ]) + ]); + }, + defaultValue: defaultColorPaletteId, + onChange(value) { + return __async(this, null, function* () { + if (!value) { + return; + } + let palette = colorPalettes[value]; + if (palette) { + yield loadColorPalette(palette); + } else if (value.startsWith("custom_")) { + value = value.substr(7); + let customColorPalettes = getCustomColorPalettes(); + if (customColorPalettes[value]) { + palette = customColorPalettes[value]; + yield loadColorPalette(customColorPalettes[value]); + } + } + let { BACKGROUND_IMAGE, CLEAR_BACKGROUND_COLOR } = palette.colors.litegraph_base; + if (BACKGROUND_IMAGE === void 0 || CLEAR_BACKGROUND_COLOR === void 0) { + const base = colorPalettes["dark"].colors.litegraph_base; + BACKGROUND_IMAGE = base.BACKGROUND_IMAGE; + CLEAR_BACKGROUND_COLOR = base.CLEAR_BACKGROUND_COLOR; + } + app.canvas.updateBackground(BACKGROUND_IMAGE, CLEAR_BACKGROUND_COLOR); + }); + } + }); + } +}); +const ext$2 = { + name: "Comfy.ContextMenuFilter", + init() { + const ctxMenu = LiteGraph.ContextMenu; + LiteGraph.ContextMenu = function(values, options) { + const ctx = ctxMenu.call(this, values, options); + if ((options == null ? void 0 : options.className) === "dark" && (values == null ? void 0 : values.length) > 10) { + const filter = document.createElement("input"); + filter.classList.add("comfy-context-menu-filter"); + filter.placeholder = "Filter list"; + this.root.prepend(filter); + const items = Array.from( + this.root.querySelectorAll(".litemenu-entry") + ); + let displayedItems = [...items]; + let itemCount = displayedItems.length; + requestAnimationFrame(() => { + var _a, _b; + const currentNode = LGraphCanvas.active_canvas.current_node; + const clickedComboValue = (_b = (_a = currentNode.widgets) == null ? void 0 : _a.filter( + (w) => w.type === "combo" && w.options.values.length === values.length + ).find( + (w) => w.options.values.every((v, i) => v === values[i]) + )) == null ? void 0 : _b.value; + let selectedIndex = clickedComboValue ? values.findIndex((v) => v === clickedComboValue) : 0; + if (selectedIndex < 0) { + selectedIndex = 0; + } + let selectedItem = displayedItems[selectedIndex]; + updateSelected(); + function updateSelected() { + selectedItem == null ? void 0 : selectedItem.style.setProperty("background-color", ""); + selectedItem == null ? void 0 : selectedItem.style.setProperty("color", ""); + selectedItem = displayedItems[selectedIndex]; + selectedItem == null ? void 0 : selectedItem.style.setProperty( + "background-color", + "#ccc", + "important" + ); + selectedItem == null ? void 0 : selectedItem.style.setProperty("color", "#000", "important"); + } + const positionList = () => { + const rect = this.root.getBoundingClientRect(); + if (rect.top < 0) { + const scale = 1 - this.root.getBoundingClientRect().height / this.root.clientHeight; + const shift = this.root.clientHeight * scale / 2; + this.root.style.top = -shift + "px"; + } + }; + filter.addEventListener("keydown", (event) => { + switch (event.key) { + case "ArrowUp": + event.preventDefault(); + if (selectedIndex === 0) { + selectedIndex = itemCount - 1; + } else { + selectedIndex--; + } + updateSelected(); + break; + case "ArrowRight": + event.preventDefault(); + selectedIndex = itemCount - 1; + updateSelected(); + break; + case "ArrowDown": + event.preventDefault(); + if (selectedIndex === itemCount - 1) { + selectedIndex = 0; + } else { + selectedIndex++; + } + updateSelected(); + break; + case "ArrowLeft": + event.preventDefault(); + selectedIndex = 0; + updateSelected(); + break; + case "Enter": + selectedItem == null ? void 0 : selectedItem.click(); + break; + case "Escape": + this.close(); + break; + } + }); + filter.addEventListener("input", () => { + const term = filter.value.toLocaleLowerCase(); + displayedItems = items.filter((item) => { + const isVisible = !term || item.textContent.toLocaleLowerCase().includes(term); + item.style.display = isVisible ? "block" : "none"; + return isVisible; + }); + selectedIndex = 0; + if (displayedItems.includes(selectedItem)) { + selectedIndex = displayedItems.findIndex( + (d) => d === selectedItem + ); + } + itemCount = displayedItems.length; + updateSelected(); + if (options.event) { + let top = options.event.clientY - 10; + const bodyRect = document.body.getBoundingClientRect(); + const rootRect = this.root.getBoundingClientRect(); + if (bodyRect.height && top > bodyRect.height - rootRect.height - 10) { + top = Math.max(0, bodyRect.height - rootRect.height - 10); + } + this.root.style.top = top + "px"; + positionList(); + } + }); + requestAnimationFrame(() => { + filter.focus(); + positionList(); + }); + }); + } + return ctx; + }; + LiteGraph.ContextMenu.prototype = ctxMenu.prototype; + } +}; +app.registerExtension(ext$2); +function stripComments(str) { + return str.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g, ""); +} +app.registerExtension({ + name: "Comfy.DynamicPrompts", + nodeCreated(node) { + if (node.widgets) { + const widgets = node.widgets.filter((n) => n.dynamicPrompts); + for (const widget of widgets) { + widget.serializeValue = (workflowNode, widgetIndex) => { + let prompt2 = stripComments(widget.value); + while (prompt2.replace("\\{", "").includes("{") && prompt2.replace("\\}", "").includes("}")) { + const startIndex = prompt2.replace("\\{", "00").indexOf("{"); + const endIndex = prompt2.replace("\\}", "00").indexOf("}"); + const optionsString = prompt2.substring(startIndex + 1, endIndex); + const options = optionsString.split("|"); + const randomIndex = Math.floor(Math.random() * options.length); + const randomOption = options[randomIndex]; + prompt2 = prompt2.substring(0, startIndex) + randomOption + prompt2.substring(endIndex + 1); + } + if (workflowNode == null ? void 0 : workflowNode.widgets_values) + workflowNode.widgets_values[widgetIndex] = prompt2; + return prompt2; + }; + } + } + } +}); +app.registerExtension({ + name: "Comfy.EditAttention", + init() { + const editAttentionDelta = app.ui.settings.addSetting({ + id: "Comfy.EditAttention.Delta", + name: "Ctrl+up/down precision", + type: "slider", + attrs: { + min: 0.01, + max: 0.5, + step: 0.01 + }, + defaultValue: 0.05 + }); + function incrementWeight(weight, delta) { + const floatWeight = parseFloat(weight); + if (isNaN(floatWeight)) return weight; + const newWeight = floatWeight + delta; + if (newWeight < 0) return "0"; + return String(Number(newWeight.toFixed(10))); + } + function findNearestEnclosure(text, cursorPos) { + let start = cursorPos, end = cursorPos; + let openCount = 0, closeCount = 0; + while (start >= 0) { + start--; + if (text[start] === "(" && openCount === closeCount) break; + if (text[start] === "(") openCount++; + if (text[start] === ")") closeCount++; + } + if (start < 0) return false; + openCount = 0; + closeCount = 0; + while (end < text.length) { + if (text[end] === ")" && openCount === closeCount) break; + if (text[end] === "(") openCount++; + if (text[end] === ")") closeCount++; + end++; + } + if (end === text.length) return false; + return { start: start + 1, end }; + } + function addWeightToParentheses(text) { + const parenRegex = /^\((.*)\)$/; + const parenMatch = text.match(parenRegex); + const floatRegex = /:([+-]?(\d*\.)?\d+([eE][+-]?\d+)?)/; + const floatMatch = text.match(floatRegex); + if (parenMatch && !floatMatch) { + return `(${parenMatch[1]}:1.0)`; + } else { + return text; + } + } + function editAttention(event) { + const inputField = event.composedPath()[0]; + const delta = parseFloat(editAttentionDelta.value); + if (inputField.tagName !== "TEXTAREA") return; + if (!(event.key === "ArrowUp" || event.key === "ArrowDown")) return; + if (!event.ctrlKey && !event.metaKey) return; + event.preventDefault(); + let start = inputField.selectionStart; + let end = inputField.selectionEnd; + let selectedText = inputField.value.substring(start, end); + if (!selectedText) { + const nearestEnclosure = findNearestEnclosure(inputField.value, start); + if (nearestEnclosure) { + start = nearestEnclosure.start; + end = nearestEnclosure.end; + selectedText = inputField.value.substring(start, end); + } else { + const delimiters = " .,\\/!?%^*;:{}=-_`~()\r\n "; + while (!delimiters.includes(inputField.value[start - 1]) && start > 0) { + start--; + } + while (!delimiters.includes(inputField.value[end]) && end < inputField.value.length) { + end++; + } + selectedText = inputField.value.substring(start, end); + if (!selectedText) return; + } + } + if (selectedText[selectedText.length - 1] === " ") { + selectedText = selectedText.substring(0, selectedText.length - 1); + end -= 1; + } + if (inputField.value[start - 1] === "(" && inputField.value[end] === ")") { + start -= 1; + end += 1; + selectedText = inputField.value.substring(start, end); + } + if (selectedText[0] !== "(" || selectedText[selectedText.length - 1] !== ")") { + selectedText = `(${selectedText})`; + } + selectedText = addWeightToParentheses(selectedText); + const weightDelta = event.key === "ArrowUp" ? delta : -delta; + const updatedText = selectedText.replace( + /\((.*):(\d+(?:\.\d+)?)\)/, + (match, text, weight) => { + weight = incrementWeight(weight, weightDelta); + if (weight == 1) { + return text; + } else { + return `(${text}:${weight})`; + } + } + ); + inputField.setRangeText(updatedText, start, end, "select"); + } + window.addEventListener("keydown", editAttention); + } +}); +const CONVERTED_TYPE = "converted-widget"; +const VALID_TYPES = ["STRING", "combo", "number", "toggle", "BOOLEAN"]; +const CONFIG = Symbol(); +const GET_CONFIG = Symbol(); +const TARGET = Symbol(); +const replacePropertyName = "Run widget replace on values"; +class PrimitiveNode { + constructor() { + __privateAdd(this, _PrimitiveNode_instances); + __publicField(this, "controlValues"); + __publicField(this, "lastType"); + this.addOutput("connect to widget input", "*"); + this.serialize_widgets = true; + this.isVirtualNode = true; + if (!this.properties || !(replacePropertyName in this.properties)) { + this.addProperty(replacePropertyName, false, "boolean"); + } + } + applyToGraph(extraLinks = []) { + var _a, _b; + if (!((_a = this.outputs[0].links) == null ? void 0 : _a.length)) return; + function get_links(node) { + let links2 = []; + for (const l of node.outputs[0].links) { + const linkInfo = app.graph.links[l]; + const n = node.graph.getNodeById(linkInfo.target_id); + if (n.type == "Reroute") { + links2 = links2.concat(get_links(n)); + } else { + links2.push(l); + } + } + return links2; + } + let links = [ + ...get_links(this).map((l) => app.graph.links[l]), + ...extraLinks + ]; + let v = (_b = this.widgets) == null ? void 0 : _b[0].value; + if (v && this.properties[replacePropertyName]) { + v = applyTextReplacements(app, v); + } + for (const linkInfo of links) { + const node = this.graph.getNodeById(linkInfo.target_id); + const input = node.inputs[linkInfo.target_slot]; + let widget; + if (input.widget[TARGET]) { + widget = input.widget[TARGET]; + } else { + const widgetName = input.widget.name; + if (widgetName) { + widget = node.widgets.find((w) => w.name === widgetName); + } + } + if (widget) { + widget.value = v; + if (widget.callback) { + widget.callback( + widget.value, + app.canvas, + node, + app.canvas.graph_mouse, + {} + ); + } + } + } + } + refreshComboInNode() { + var _a; + const widget = (_a = this.widgets) == null ? void 0 : _a[0]; + if ((widget == null ? void 0 : widget.type) === "combo") { + widget.options.values = this.outputs[0].widget[GET_CONFIG]()[0]; + if (!widget.options.values.includes(widget.value)) { + widget.value = widget.options.values[0]; + widget.callback(widget.value); + } + } + } + onAfterGraphConfigured() { + var _a, _b; + if (((_a = this.outputs[0].links) == null ? void 0 : _a.length) && !((_b = this.widgets) == null ? void 0 : _b.length)) { + if (!__privateMethod(this, _PrimitiveNode_instances, onFirstConnection_fn).call(this)) return; + if (this.widgets) { + for (let i = 0; i < this.widgets_values.length; i++) { + const w = this.widgets[i]; + if (w) { + w.value = this.widgets_values[i]; + } + } + } + __privateMethod(this, _PrimitiveNode_instances, mergeWidgetConfig_fn).call(this); + } + } + onConnectionsChange(_, index, connected) { + var _a; + if (app.configuringGraph) { + return; + } + const links = this.outputs[0].links; + if (connected) { + if ((links == null ? void 0 : links.length) && !((_a = this.widgets) == null ? void 0 : _a.length)) { + __privateMethod(this, _PrimitiveNode_instances, onFirstConnection_fn).call(this); + } + } else { + __privateMethod(this, _PrimitiveNode_instances, mergeWidgetConfig_fn).call(this); + if (!(links == null ? void 0 : links.length)) { + this.onLastDisconnect(); + } + } + } + onConnectOutput(slot, type, input, target_node, target_slot) { + var _a; + if (!input.widget) { + if (!(input.type in ComfyWidgets)) return false; + } + if ((_a = this.outputs[slot].links) == null ? void 0 : _a.length) { + const valid = __privateMethod(this, _PrimitiveNode_instances, isValidConnection_fn).call(this, input); + if (valid) { + this.applyToGraph([{ target_id: target_node.id, target_slot }]); + } + return valid; + } + } + recreateWidget() { + var _a, _b, _c; + const values = (_a = this.widgets) == null ? void 0 : _a.map((w) => w.value); + __privateMethod(this, _PrimitiveNode_instances, removeWidgets_fn).call(this); + __privateMethod(this, _PrimitiveNode_instances, onFirstConnection_fn).call(this, true); + if (values == null ? void 0 : values.length) { + for (let i = 0; i < ((_b = this.widgets) == null ? void 0 : _b.length); i++) + this.widgets[i].value = values[i]; + } + return (_c = this.widgets) == null ? void 0 : _c[0]; + } + onLastDisconnect() { + this.outputs[0].type = "*"; + this.outputs[0].name = "connect to widget input"; + delete this.outputs[0].widget; + __privateMethod(this, _PrimitiveNode_instances, removeWidgets_fn).call(this); + } +} +_PrimitiveNode_instances = new WeakSet(); +onFirstConnection_fn = function(recreating) { + var _a, _b; + if (!this.outputs[0].links) { + this.onLastDisconnect(); + return; + } + const linkId = this.outputs[0].links[0]; + const link = this.graph.links[linkId]; + if (!link) return; + const theirNode = this.graph.getNodeById(link.target_id); + if (!theirNode || !theirNode.inputs) return; + const input = theirNode.inputs[link.target_slot]; + if (!input) return; + let widget; + if (!input.widget) { + if (!(input.type in ComfyWidgets)) return; + widget = { name: input.name, [GET_CONFIG]: () => [input.type, {}] }; + } else { + widget = input.widget; + } + const config = (_a = widget[GET_CONFIG]) == null ? void 0 : _a.call(widget); + if (!config) return; + const { type } = getWidgetType(config); + this.outputs[0].type = type; + this.outputs[0].name = type; + this.outputs[0].widget = widget; + __privateMethod(this, _PrimitiveNode_instances, createWidget_fn).call(this, (_b = widget[CONFIG]) != null ? _b : config, theirNode, widget.name, recreating, widget[TARGET]); +}; +createWidget_fn = function(inputData, node, widgetName, recreating, targetWidget) { + var _a, _b, _c; + let type = inputData[0]; + if (type instanceof Array) { + type = "COMBO"; + } + let widget; + if (type in ComfyWidgets) { + widget = (ComfyWidgets[type](this, "value", inputData, app) || {}).widget; + } else { + widget = this.addWidget(type, "value", null, () => { + }, {}); + } + if (targetWidget) { + widget.value = targetWidget.value; + } else if ((node == null ? void 0 : node.widgets) && widget) { + const theirWidget = node.widgets.find((w) => w.name === widgetName); + if (theirWidget) { + widget.value = theirWidget.value; + } + } + if (!((_a = inputData == null ? void 0 : inputData[1]) == null ? void 0 : _a.control_after_generate) && (widget.type === "number" || widget.type === "combo")) { + let control_value = (_b = this.widgets_values) == null ? void 0 : _b[1]; + if (!control_value) { + control_value = "fixed"; + } + addValueControlWidgets( + this, + widget, + control_value, + void 0, + inputData + ); + let filter = (_c = this.widgets_values) == null ? void 0 : _c[2]; + if (filter && this.widgets.length === 3) { + this.widgets[2].value = filter; + } + } + const controlValues = this.controlValues; + if (this.lastType === this.widgets[0].type && (controlValues == null ? void 0 : controlValues.length) === this.widgets.length - 1) { + for (let i = 0; i < controlValues.length; i++) { + this.widgets[i + 1].value = controlValues[i]; + } + } + const callback = widget.callback; + const self = this; + widget.callback = function() { + const r = callback ? callback.apply(this, arguments) : void 0; + self.applyToGraph(); + return r; + }; + if (!recreating) { + const sz = this.computeSize(); + if (this.size[0] < sz[0]) { + this.size[0] = sz[0]; + } + if (this.size[1] < sz[1]) { + this.size[1] = sz[1]; + } + requestAnimationFrame(() => { + if (this.onResize) { + this.onResize(this.size); + } + }); + } +}; +mergeWidgetConfig_fn = function() { + const output = this.outputs[0]; + const links = output.links; + const hasConfig = !!output.widget[CONFIG]; + if (hasConfig) { + delete output.widget[CONFIG]; + } + if ((links == null ? void 0 : links.length) < 2 && hasConfig) { + if (links.length) { + this.recreateWidget(); + } + return; + } + const config1 = output.widget[GET_CONFIG](); + const isNumber = config1[0] === "INT" || config1[0] === "FLOAT"; + if (!isNumber) return; + for (const linkId of links) { + const link = app.graph.links[linkId]; + if (!link) continue; + const theirNode = app.graph.getNodeById(link.target_id); + const theirInput = theirNode.inputs[link.target_slot]; + __privateMethod(this, _PrimitiveNode_instances, isValidConnection_fn).call(this, theirInput, hasConfig); + } +}; +isValidConnection_fn = function(input, forceUpdate) { + const output = this.outputs[0]; + const config2 = input.widget[GET_CONFIG](); + return !!mergeIfValid.call( + this, + output, + config2, + forceUpdate, + this.recreateWidget + ); +}; +removeWidgets_fn = function() { + var _a; + if (this.widgets) { + for (const w of this.widgets) { + if (w.onRemove) { + w.onRemove(); + } + } + this.controlValues = []; + this.lastType = (_a = this.widgets[0]) == null ? void 0 : _a.type; + for (let i = 1; i < this.widgets.length; i++) { + this.controlValues.push(this.widgets[i].value); + } + setTimeout(() => { + delete this.lastType; + delete this.controlValues; + }, 15); + this.widgets.length = 0; + } +}; +__publicField(PrimitiveNode, "category"); +function getWidgetConfig(slot) { + var _a; + return (_a = slot.widget[CONFIG]) != null ? _a : slot.widget[GET_CONFIG](); +} +function getConfig(widgetName) { + var _a, _b, _c, _d; + const { nodeData } = this.constructor; + return (_d = (_a = nodeData == null ? void 0 : nodeData.input) == null ? void 0 : _a.required[widgetName]) != null ? _d : (_c = (_b = nodeData == null ? void 0 : nodeData.input) == null ? void 0 : _b.optional) == null ? void 0 : _c[widgetName]; +} +function isConvertibleWidget(widget, config) { + var _a; + return (VALID_TYPES.includes(widget.type) || VALID_TYPES.includes(config[0])) && !((_a = widget.options) == null ? void 0 : _a.forceInput); +} +function hideWidget(node, widget, suffix = "") { + var _a; + if ((_a = widget.type) == null ? void 0 : _a.startsWith(CONVERTED_TYPE)) return; + widget.origType = widget.type; + widget.origComputeSize = widget.computeSize; + widget.origSerializeValue = widget.serializeValue; + widget.computeSize = () => [0, -4]; + widget.type = CONVERTED_TYPE + suffix; + widget.serializeValue = () => { + if (!node.inputs) { + return void 0; + } + let node_input = node.inputs.find((i) => { + var _a2; + return ((_a2 = i.widget) == null ? void 0 : _a2.name) === widget.name; + }); + if (!node_input || !node_input.link) { + return void 0; + } + return widget.origSerializeValue ? widget.origSerializeValue() : widget.value; + }; + if (widget.linkedWidgets) { + for (const w of widget.linkedWidgets) { + hideWidget(node, w, ":" + widget.name); + } + } +} +function showWidget(widget) { + widget.type = widget.origType; + widget.computeSize = widget.origComputeSize; + widget.serializeValue = widget.origSerializeValue; + delete widget.origType; + delete widget.origComputeSize; + delete widget.origSerializeValue; + if (widget.linkedWidgets) { + for (const w of widget.linkedWidgets) { + showWidget(w); + } + } +} +function convertToInput(node, widget, config) { + hideWidget(node, widget); + const { type } = getWidgetType(config); + const sz = node.size; + node.addInput(widget.name, type, { + widget: { name: widget.name, [GET_CONFIG]: () => config } + }); + for (const widget2 of node.widgets) { + widget2.last_y += LiteGraph.NODE_SLOT_HEIGHT; + } + node.setSize([Math.max(sz[0], node.size[0]), Math.max(sz[1], node.size[1])]); +} +function convertToWidget(node, widget) { + showWidget(widget); + const sz = node.size; + node.removeInput(node.inputs.findIndex((i) => { + var _a; + return ((_a = i.widget) == null ? void 0 : _a.name) === widget.name; + })); + for (const widget2 of node.widgets) { + widget2.last_y -= LiteGraph.NODE_SLOT_HEIGHT; + } + node.setSize([Math.max(sz[0], node.size[0]), Math.max(sz[1], node.size[1])]); +} +function getWidgetType(config) { + let type = config[0]; + if (type instanceof Array) { + type = "COMBO"; + } + return { type }; +} +function isValidCombo(combo, obj) { + if (!(obj instanceof Array)) { + console.log(`connection rejected: tried to connect combo to ${obj}`); + return false; + } + if (combo.length !== obj.length) { + console.log(`connection rejected: combo lists dont match`); + return false; + } + if (combo.find((v, i) => obj[i] !== v)) { + console.log(`connection rejected: combo lists dont match`); + return false; + } + return true; +} +function isPrimitiveNode(node) { + return node.type === "PrimitiveNode"; +} +function setWidgetConfig(slot, config, target) { + if (!slot.widget) return; + if (config) { + slot.widget[GET_CONFIG] = () => config; + slot.widget[TARGET] = target; + } else { + delete slot.widget; + } + if (slot.link) { + const link = app.graph.links[slot.link]; + if (link) { + const originNode = app.graph.getNodeById(link.origin_id); + if (isPrimitiveNode(originNode)) { + if (config) { + originNode.recreateWidget(); + } else if (!app.configuringGraph) { + originNode.disconnectOutput(0); + originNode.onLastDisconnect(); + } + } + } + } +} +function mergeIfValid(output, config2, forceUpdate, recreateWidget, config1) { + var _a, _b, _c, _d, _e, _f; + if (!config1) { + config1 = (_a = output.widget[CONFIG]) != null ? _a : output.widget[GET_CONFIG](); + } + if (config1[0] instanceof Array) { + if (!isValidCombo(config1[0], config2[0])) return; + } else if (config1[0] !== config2[0]) { + console.log(`connection rejected: types dont match`, config1[0], config2[0]); + return; + } + const keys = /* @__PURE__ */ new Set([ + ...Object.keys((_b = config1[1]) != null ? _b : {}), + ...Object.keys((_c = config2[1]) != null ? _c : {}) + ]); + let customConfig; + const getCustomConfig = () => { + var _a2, _b2; + if (!customConfig) { + if (typeof structuredClone === "undefined") { + customConfig = JSON.parse(JSON.stringify((_a2 = config1[1]) != null ? _a2 : {})); + } else { + customConfig = structuredClone((_b2 = config1[1]) != null ? _b2 : {}); + } + } + return customConfig; + }; + const isNumber = config1[0] === "INT" || config1[0] === "FLOAT"; + for (const k of keys.values()) { + if (k !== "default" && k !== "forceInput" && k !== "defaultInput" && k !== "control_after_generate" && k !== "multiline" && k !== "tooltip") { + let v1 = config1[1][k]; + let v2 = (_d = config2[1]) == null ? void 0 : _d[k]; + if (v1 === v2 || !v1 && !v2) continue; + if (isNumber) { + if (k === "min") { + const theirMax = (_e = config2[1]) == null ? void 0 : _e["max"]; + if (theirMax != null && v1 > theirMax) { + console.log("connection rejected: min > max", v1, theirMax); + return; + } + getCustomConfig()[k] = v1 == null ? v2 : v2 == null ? v1 : Math.max(v1, v2); + continue; + } else if (k === "max") { + const theirMin = (_f = config2[1]) == null ? void 0 : _f["min"]; + if (theirMin != null && v1 < theirMin) { + console.log("connection rejected: max < min", v1, theirMin); + return; + } + getCustomConfig()[k] = v1 == null ? v2 : v2 == null ? v1 : Math.min(v1, v2); + continue; + } else if (k === "step") { + let step; + if (v1 == null) { + step = v2; + } else if (v2 == null) { + step = v1; + } else { + if (v1 < v2) { + const a = v2; + v2 = v1; + v1 = a; + } + if (v1 % v2) { + console.log( + "connection rejected: steps not divisible", + "current:", + v1, + "new:", + v2 + ); + return; + } + step = v1; + } + getCustomConfig()[k] = step; + continue; + } + } + console.log(`connection rejected: config ${k} values dont match`, v1, v2); + return; + } + } + if (customConfig || forceUpdate) { + if (customConfig) { + output.widget[CONFIG] = [config1[0], customConfig]; + } + const widget = recreateWidget == null ? void 0 : recreateWidget.call(this); + if (widget) { + const min = widget.options.min; + const max = widget.options.max; + if (min != null && widget.value < min) widget.value = min; + if (max != null && widget.value > max) widget.value = max; + widget.callback(widget.value); + } + } + return { customConfig }; +} +let useConversionSubmenusSetting; +app.registerExtension({ + name: "Comfy.WidgetInputs", + init() { + useConversionSubmenusSetting = app.ui.settings.addSetting({ + id: "Comfy.NodeInputConversionSubmenus", + name: "Node widget/input conversion sub-menus", + tooltip: "In the node context menu, place the entries that convert between input/widget in sub-menus.", + type: "boolean", + defaultValue: true + }); + }, + beforeRegisterNodeDef(nodeType, nodeData, app2) { + return __async(this, null, function* () { + const origGetExtraMenuOptions = nodeType.prototype.getExtraMenuOptions; + nodeType.prototype.convertWidgetToInput = function(widget) { + var _a; + const config = (_a = getConfig.call(this, widget.name)) != null ? _a : [ + widget.type, + widget.options || {} + ]; + if (!isConvertibleWidget(widget, config)) return false; + convertToInput(this, widget, config); + return true; + }; + nodeType.prototype.getExtraMenuOptions = function(_, options) { + var _a, _b; + const r = origGetExtraMenuOptions ? origGetExtraMenuOptions.apply(this, arguments) : void 0; + if (this.widgets) { + let toInput = []; + let toWidget = []; + for (const w of this.widgets) { + if ((_a = w.options) == null ? void 0 : _a.forceInput) { + continue; + } + if (w.type === CONVERTED_TYPE) { + toWidget.push({ + content: `Convert ${w.name} to widget`, + callback: () => convertToWidget(this, w) + }); + } else { + const config = (_b = getConfig.call(this, w.name)) != null ? _b : [ + w.type, + w.options || {} + ]; + if (isConvertibleWidget(w, config)) { + toInput.push({ + content: `Convert ${w.name} to input`, + callback: () => convertToInput(this, w, config) + }); + } + } + } + if (toInput.length) { + if (useConversionSubmenusSetting.value) { + options.push({ + content: "Convert Widget to Input", + submenu: { + options: toInput + } + }); + } else { + options.push(...toInput, null); + } + } + if (toWidget.length) { + if (useConversionSubmenusSetting.value) { + options.push({ + content: "Convert Input to Widget", + submenu: { + options: toWidget + } + }); + } else { + options.push(...toWidget, null); + } + } + } + return r; + }; + nodeType.prototype.onGraphConfigured = function() { + if (!this.inputs) return; + for (const input of this.inputs) { + if (input.widget) { + if (!input.widget[GET_CONFIG]) { + input.widget[GET_CONFIG] = () => getConfig.call(this, input.widget.name); + } + if (input.widget.config) { + if (input.widget.config[0] instanceof Array) { + input.type = "COMBO"; + const link = app2.graph.links[input.link]; + if (link) { + link.type = input.type; + } + } + delete input.widget.config; + } + const w = this.widgets.find((w2) => w2.name === input.widget.name); + if (w) { + hideWidget(this, w); + } else { + convertToWidget(this, input); + } + } + } + }; + const origOnNodeCreated = nodeType.prototype.onNodeCreated; + nodeType.prototype.onNodeCreated = function() { + var _a, _b, _c; + const r = origOnNodeCreated ? origOnNodeCreated.apply(this) : void 0; + if (!app2.configuringGraph && this.widgets) { + for (const w of this.widgets) { + if (((_a = w == null ? void 0 : w.options) == null ? void 0 : _a.forceInput) || ((_b = w == null ? void 0 : w.options) == null ? void 0 : _b.defaultInput)) { + const config = (_c = getConfig.call(this, w.name)) != null ? _c : [ + w.type, + w.options || {} + ]; + convertToInput(this, w, config); + } + } + } + return r; + }; + const origOnConfigure = nodeType.prototype.onConfigure; + nodeType.prototype.onConfigure = function() { + const r = origOnConfigure ? origOnConfigure.apply(this, arguments) : void 0; + if (!app2.configuringGraph && this.inputs) { + for (const input of this.inputs) { + if (input.widget && !input.widget[GET_CONFIG]) { + input.widget[GET_CONFIG] = () => getConfig.call(this, input.widget.name); + const w = this.widgets.find((w2) => w2.name === input.widget.name); + if (w) { + hideWidget(this, w); + } + } + } + } + return r; + }; + function isNodeAtPos(pos) { + for (const n of app2.graph._nodes) { + if (n.pos[0] === pos[0] && n.pos[1] === pos[1]) { + return true; + } + } + return false; + } + const origOnInputDblClick = nodeType.prototype.onInputDblClick; + const ignoreDblClick = Symbol(); + nodeType.prototype.onInputDblClick = function(slot) { + var _a, _b, _c; + const r = origOnInputDblClick ? origOnInputDblClick.apply(this, arguments) : void 0; + const input = this.inputs[slot]; + if (!input.widget || !input[ignoreDblClick]) { + if (!(input.type in ComfyWidgets) && !(((_c = (_b = (_a = input.widget)[GET_CONFIG]) == null ? void 0 : _b.call(_a)) == null ? void 0 : _c[0]) instanceof Array)) { + return r; + } + } + const node = LiteGraph.createNode("PrimitiveNode"); + app2.graph.add(node); + const pos = [ + this.pos[0] - node.size[0] - 30, + this.pos[1] + ]; + while (isNodeAtPos(pos)) { + pos[1] += LiteGraph.NODE_TITLE_HEIGHT; + } + node.pos = pos; + node.connect(0, this, slot); + node.title = input.name; + input[ignoreDblClick] = true; + setTimeout(() => { + delete input[ignoreDblClick]; + }, 300); + return r; + }; + const onConnectInput = nodeType.prototype.onConnectInput; + nodeType.prototype.onConnectInput = function(targetSlot, type, output, originNode, originSlot) { + var _a, _b, _c, _d, _e, _f; + const v = onConnectInput == null ? void 0 : onConnectInput(this, arguments); + if (type !== "COMBO") return v; + if (originNode.outputs[originSlot].widget) return v; + const targetCombo = (_c = (_b = (_a = this.inputs[targetSlot].widget) == null ? void 0 : _a[GET_CONFIG]) == null ? void 0 : _b.call(_a)) == null ? void 0 : _c[0]; + if (!targetCombo || !(targetCombo instanceof Array)) return v; + const originConfig = (_f = (_e = (_d = originNode.constructor) == null ? void 0 : _d.nodeData) == null ? void 0 : _e.output) == null ? void 0 : _f[originSlot]; + if (!originConfig || !isValidCombo(targetCombo, originConfig)) { + return false; + } + return v; + }; + }); + }, + registerCustomNodes() { + LiteGraph.registerNodeType( + "PrimitiveNode", + Object.assign(PrimitiveNode, { + title: "Primitive" + }) + ); + PrimitiveNode.category = "utils"; + } +}); +window.comfyAPI = window.comfyAPI || {}; +window.comfyAPI.widgetInputs = window.comfyAPI.widgetInputs || {}; +window.comfyAPI.widgetInputs.getWidgetConfig = getWidgetConfig; +window.comfyAPI.widgetInputs.setWidgetConfig = setWidgetConfig; +window.comfyAPI.widgetInputs.mergeIfValid = mergeIfValid; +const ORDER = Symbol(); +function merge(target, source) { + if (typeof target === "object" && typeof source === "object") { + for (const key in source) { + const sv = source[key]; + if (typeof sv === "object") { + let tv = target[key]; + if (!tv) tv = target[key] = {}; + merge(tv, source[key]); + } else { + target[key] = sv; + } + } + } + return target; +} +class ManageGroupDialog extends ComfyDialog { + constructor(app2) { + super(); + __publicField(this, "tabs"); + __publicField(this, "selectedNodeIndex"); + __publicField(this, "selectedTab", "Inputs"); + __publicField(this, "selectedGroup"); + __publicField(this, "modifications", {}); + __publicField(this, "nodeItems"); + __publicField(this, "app"); + __publicField(this, "groupNodeType"); + __publicField(this, "groupNodeDef"); + __publicField(this, "groupData"); + __publicField(this, "innerNodesList"); + __publicField(this, "widgetsPage"); + __publicField(this, "inputsPage"); + __publicField(this, "outputsPage"); + __publicField(this, "draggable"); + this.app = app2; + this.element = $el("dialog.comfy-group-manage", { + parent: document.body + }); + } + get selectedNodeInnerIndex() { + return +this.nodeItems[this.selectedNodeIndex].dataset.nodeindex; + } + changeTab(tab) { + this.tabs[this.selectedTab].tab.classList.remove("active"); + this.tabs[this.selectedTab].page.classList.remove("active"); + this.tabs[tab].tab.classList.add("active"); + this.tabs[tab].page.classList.add("active"); + this.selectedTab = tab; + } + changeNode(index, force) { + if (!force && this.selectedNodeIndex === index) return; + if (this.selectedNodeIndex != null) { + this.nodeItems[this.selectedNodeIndex].classList.remove("selected"); + } + this.nodeItems[index].classList.add("selected"); + this.selectedNodeIndex = index; + if (!this.buildInputsPage() && this.selectedTab === "Inputs") { + this.changeTab("Widgets"); + } + if (!this.buildWidgetsPage() && this.selectedTab === "Widgets") { + this.changeTab("Outputs"); + } + if (!this.buildOutputsPage() && this.selectedTab === "Outputs") { + this.changeTab("Inputs"); + } + this.changeTab(this.selectedTab); + } + getGroupData() { + this.groupNodeType = LiteGraph.registered_node_types["workflow/" + this.selectedGroup]; + this.groupNodeDef = this.groupNodeType.nodeData; + this.groupData = GroupNodeHandler.getGroupData(this.groupNodeType); + } + changeGroup(group, reset = true) { + var _a; + this.selectedGroup = group; + this.getGroupData(); + const nodes = this.groupData.nodeData.nodes; + this.nodeItems = nodes.map( + (n, i) => { + var _a2; + return $el( + "li.draggable-item", + { + dataset: { + nodeindex: n.index + "" + }, + onclick: () => { + this.changeNode(i); + } + }, + [ + $el("span.drag-handle"), + $el( + "div", + { + textContent: (_a2 = n.title) != null ? _a2 : n.type + }, + n.title ? $el("span", { + textContent: n.type + }) : [] + ) + ] + ); + } + ); + this.innerNodesList.replaceChildren(...this.nodeItems); + if (reset) { + this.selectedNodeIndex = null; + this.changeNode(0); + } else { + const items = this.draggable.getAllItems(); + let index = items.findIndex((item) => item.classList.contains("selected")); + if (index === -1) index = this.selectedNodeIndex; + this.changeNode(index, true); + } + const ordered = [...nodes]; + (_a = this.draggable) == null ? void 0 : _a.dispose(); + this.draggable = new DraggableList(this.innerNodesList, "li"); + this.draggable.addEventListener( + "dragend", + ({ detail: { oldPosition, newPosition } }) => { + if (oldPosition === newPosition) return; + ordered.splice(newPosition, 0, ordered.splice(oldPosition, 1)[0]); + for (let i = 0; i < ordered.length; i++) { + this.storeModification({ + nodeIndex: ordered[i].index, + section: ORDER, + prop: "order", + value: i + }); + } + } + ); + } + storeModification(props) { + var _a, _b, _c, _d, _e, _f, _g, _h; + const { nodeIndex, section, prop, value } = props; + const groupMod = (_c = (_a = this.modifications)[_b = this.selectedGroup]) != null ? _c : _a[_b] = {}; + const nodesMod = (_d = groupMod.nodes) != null ? _d : groupMod.nodes = {}; + const nodeMod = (_f = nodesMod[_e = nodeIndex != null ? nodeIndex : this.selectedNodeInnerIndex]) != null ? _f : nodesMod[_e] = {}; + const typeMod = (_g = nodeMod[section]) != null ? _g : nodeMod[section] = {}; + if (typeof value === "object") { + const objMod = (_h = typeMod[prop]) != null ? _h : typeMod[prop] = {}; + Object.assign(objMod, value); + } else { + typeMod[prop] = value; + } + } + getEditElement(section, prop, value, placeholder, checked, checkable = true) { + var _a, _b, _c, _d; + if (value === placeholder) value = ""; + const mods = (_d = (_c = (_b = (_a = this.modifications[this.selectedGroup]) == null ? void 0 : _a.nodes) == null ? void 0 : _b[this.selectedNodeInnerIndex]) == null ? void 0 : _c[section]) == null ? void 0 : _d[prop]; + if (mods) { + if (mods.name != null) { + value = mods.name; + } + if (mods.visible != null) { + checked = mods.visible; + } + } + return $el("div", [ + $el("input", { + value, + placeholder, + type: "text", + onchange: (e) => { + this.storeModification({ + section, + prop, + value: { name: e.target.value } + }); + } + }), + $el("label", { textContent: "Visible" }, [ + $el("input", { + type: "checkbox", + checked, + disabled: !checkable, + onchange: (e) => { + this.storeModification({ + section, + prop, + value: { visible: !!e.target.checked } + }); + } + }) + ]) + ]); + } + buildWidgetsPage() { + var _a, _b; + const widgets = this.groupData.oldToNewWidgetMap[this.selectedNodeInnerIndex]; + const items = Object.keys(widgets != null ? widgets : {}); + const type = app.graph.extra.groupNodes[this.selectedGroup]; + const config = (_b = (_a = type.config) == null ? void 0 : _a[this.selectedNodeInnerIndex]) == null ? void 0 : _b.input; + this.widgetsPage.replaceChildren( + ...items.map((oldName) => { + var _a2; + return this.getEditElement( + "input", + oldName, + widgets[oldName], + oldName, + ((_a2 = config == null ? void 0 : config[oldName]) == null ? void 0 : _a2.visible) !== false + ); + }) + ); + return !!items.length; + } + buildInputsPage() { + var _a, _b; + const inputs = this.groupData.nodeInputs[this.selectedNodeInnerIndex]; + const items = Object.keys(inputs != null ? inputs : {}); + const type = app.graph.extra.groupNodes[this.selectedGroup]; + const config = (_b = (_a = type.config) == null ? void 0 : _a[this.selectedNodeInnerIndex]) == null ? void 0 : _b.input; + this.inputsPage.replaceChildren( + ...items.map((oldName) => { + var _a2; + let value = inputs[oldName]; + if (!value) { + return; + } + return this.getEditElement( + "input", + oldName, + value, + oldName, + ((_a2 = config == null ? void 0 : config[oldName]) == null ? void 0 : _a2.visible) !== false + ); + }).filter(Boolean) + ); + return !!items.length; + } + buildOutputsPage() { + var _a, _b, _c; + const nodes = this.groupData.nodeData.nodes; + const innerNodeDef = this.groupData.getNodeDef( + nodes[this.selectedNodeInnerIndex] + ); + const outputs = (_a = innerNodeDef == null ? void 0 : innerNodeDef.output) != null ? _a : []; + const groupOutputs = this.groupData.oldToNewOutputMap[this.selectedNodeInnerIndex]; + const type = app.graph.extra.groupNodes[this.selectedGroup]; + const config = (_c = (_b = type.config) == null ? void 0 : _b[this.selectedNodeInnerIndex]) == null ? void 0 : _c.output; + const node = this.groupData.nodeData.nodes[this.selectedNodeInnerIndex]; + const checkable = node.type !== "PrimitiveNode"; + this.outputsPage.replaceChildren( + ...outputs.map((type2, slot) => { + var _a2, _b2, _c2, _d; + const groupOutputIndex = groupOutputs == null ? void 0 : groupOutputs[slot]; + const oldName = (_b2 = (_a2 = innerNodeDef.output_name) == null ? void 0 : _a2[slot]) != null ? _b2 : type2; + let value = (_c2 = config == null ? void 0 : config[slot]) == null ? void 0 : _c2.name; + const visible = ((_d = config == null ? void 0 : config[slot]) == null ? void 0 : _d.visible) || groupOutputIndex != null; + if (!value || value === oldName) { + value = ""; + } + return this.getEditElement( + "output", + slot, + value, + oldName, + visible, + checkable + ); + }).filter(Boolean) + ); + return !!outputs.length; + } + show(type) { + var _a, _b; + const groupNodes = Object.keys((_b = (_a = app.graph.extra) == null ? void 0 : _a.groupNodes) != null ? _b : {}).sort( + (a, b) => a.localeCompare(b) + ); + this.innerNodesList = $el( + "ul.comfy-group-manage-list-items" + ); + this.widgetsPage = $el("section.comfy-group-manage-node-page"); + this.inputsPage = $el("section.comfy-group-manage-node-page"); + this.outputsPage = $el("section.comfy-group-manage-node-page"); + const pages = $el("div", [ + this.widgetsPage, + this.inputsPage, + this.outputsPage + ]); + this.tabs = [ + ["Inputs", this.inputsPage], + ["Widgets", this.widgetsPage], + ["Outputs", this.outputsPage] + ].reduce((p, [name, page]) => { + p[name] = { + tab: $el("a", { + onclick: () => { + this.changeTab(name); + }, + textContent: name + }), + page + }; + return p; + }, {}); + const outer = $el("div.comfy-group-manage-outer", [ + $el("header", [ + $el("h2", "Group Nodes"), + $el( + "select", + { + onchange: (e) => { + this.changeGroup(e.target.value); + } + }, + groupNodes.map( + (g) => $el("option", { + textContent: g, + selected: "workflow/" + g === type, + value: g + }) + ) + ) + ]), + $el("main", [ + $el("section.comfy-group-manage-list", this.innerNodesList), + $el("section.comfy-group-manage-node", [ + $el( + "header", + Object.values(this.tabs).map((t) => t.tab) + ), + pages + ]) + ]), + $el("footer", [ + $el( + "button.comfy-btn", + { + onclick: (e) => { + const node = app.graph._nodes.find( + (n) => n.type === "workflow/" + this.selectedGroup + ); + if (node) { + alert( + "This group node is in use in the current workflow, please first remove these." + ); + return; + } + if (confirm( + `Are you sure you want to remove the node: "${this.selectedGroup}"` + )) { + delete app.graph.extra.groupNodes[this.selectedGroup]; + LiteGraph.unregisterNodeType("workflow/" + this.selectedGroup); + } + this.show(); + } + }, + "Delete Group Node" + ), + $el( + "button.comfy-btn", + { + onclick: () => __async(this, null, function* () { + var _a2, _b2; + let nodesByType; + let recreateNodes = []; + const types = {}; + for (const g in this.modifications) { + const type2 = app.graph.extra.groupNodes[g]; + let config = (_a2 = type2.config) != null ? _a2 : type2.config = {}; + let nodeMods = (_b2 = this.modifications[g]) == null ? void 0 : _b2.nodes; + if (nodeMods) { + const keys = Object.keys(nodeMods); + if (nodeMods[keys[0]][ORDER]) { + const orderedNodes = []; + const orderedMods = {}; + const orderedConfig = {}; + for (const n of keys) { + const order = nodeMods[n][ORDER].order; + orderedNodes[order] = type2.nodes[+n]; + orderedMods[order] = nodeMods[n]; + orderedNodes[order].index = order; + } + for (const l of type2.links) { + if (l[0] != null) l[0] = type2.nodes[l[0]].index; + if (l[2] != null) l[2] = type2.nodes[l[2]].index; + } + if (type2.external) { + for (const ext2 of type2.external) { + ext2[0] = type2.nodes[ext2[0]]; + } + } + for (const id2 of keys) { + if (config[id2]) { + orderedConfig[type2.nodes[id2].index] = config[id2]; + } + delete config[id2]; + } + type2.nodes = orderedNodes; + nodeMods = orderedMods; + type2.config = config = orderedConfig; + } + merge(config, nodeMods); + } + types[g] = type2; + if (!nodesByType) { + nodesByType = app.graph._nodes.reduce((p, n) => { + var _a3, _b3; + (_b3 = p[_a3 = n.type]) != null ? _b3 : p[_a3] = []; + p[n.type].push(n); + return p; + }, {}); + } + const nodes = nodesByType["workflow/" + g]; + if (nodes) recreateNodes.push(...nodes); + } + yield GroupNodeConfig.registerFromWorkflow(types, {}); + for (const node of recreateNodes) { + node.recreate(); + } + this.modifications = {}; + this.app.graph.setDirtyCanvas(true, true); + this.changeGroup(this.selectedGroup, false); + }) + }, + "Save" + ), + $el( + "button.comfy-btn", + { onclick: () => this.element.close() }, + "Close" + ) + ]) + ]); + this.element.replaceChildren(outer); + this.changeGroup( + type ? groupNodes.find((g) => "workflow/" + g === type) : groupNodes[0] + ); + this.element.showModal(); + this.element.addEventListener("close", () => { + var _a2; + (_a2 = this.draggable) == null ? void 0 : _a2.dispose(); + }); + } +} +window.comfyAPI = window.comfyAPI || {}; +window.comfyAPI.groupNodeManage = window.comfyAPI.groupNodeManage || {}; +window.comfyAPI.groupNodeManage.ManageGroupDialog = ManageGroupDialog; +const GROUP = Symbol(); +const Workflow = { + InUse: { + Free: 0, + Registered: 1, + InWorkflow: 2 + }, + isInUseGroupNode(name) { + var _a, _b; + const id2 = `workflow/${name}`; + if ((_b = (_a = app.graph.extra) == null ? void 0 : _a.groupNodes) == null ? void 0 : _b[name]) { + if (app.graph._nodes.find((n) => n.type === id2)) { + return Workflow.InUse.InWorkflow; + } else { + return Workflow.InUse.Registered; + } + } + return Workflow.InUse.Free; + }, + storeGroupNode(name, data) { + let extra = app.graph.extra; + if (!extra) app.graph.extra = extra = {}; + let groupNodes = extra.groupNodes; + if (!groupNodes) extra.groupNodes = groupNodes = {}; + groupNodes[name] = data; + } +}; +class GroupNodeBuilder { + constructor(nodes) { + __publicField(this, "nodes"); + __publicField(this, "nodeData"); + this.nodes = nodes; + } + build() { + const name = this.getName(); + if (!name) return; + this.sortNodes(); + this.nodeData = this.getNodeData(); + Workflow.storeGroupNode(name, this.nodeData); + return { name, nodeData: this.nodeData }; + } + getName() { + const name = prompt("Enter group name"); + if (!name) return; + const used = Workflow.isInUseGroupNode(name); + switch (used) { + case Workflow.InUse.InWorkflow: + alert( + "An in use group node with this name already exists embedded in this workflow, please remove any instances or use a new name." + ); + return; + case Workflow.InUse.Registered: + if (!confirm( + "A group node with this name already exists embedded in this workflow, are you sure you want to overwrite it?" + )) { + return; + } + break; + } + return name; + } + sortNodes() { + const nodesInOrder = app.graph.computeExecutionOrder(false); + this.nodes = this.nodes.map((node) => ({ index: nodesInOrder.indexOf(node), node })).sort((a, b) => a.index - b.index || a.node.id - b.node.id).map(({ node }) => node); + } + getNodeData() { + const storeLinkTypes = (config) => { + for (const link of config.links) { + const origin = app.graph.getNodeById(link[4]); + const type = origin.outputs[link[1]].type; + link.push(type); + } + }; + const storeExternalLinks = (config) => { + var _a, _b; + config.external = []; + for (let i = 0; i < this.nodes.length; i++) { + const node = this.nodes[i]; + if (!((_a = node.outputs) == null ? void 0 : _a.length)) continue; + for (let slot = 0; slot < node.outputs.length; slot++) { + let hasExternal = false; + const output = node.outputs[slot]; + let type = output.type; + if (!((_b = output.links) == null ? void 0 : _b.length)) continue; + for (const l of output.links) { + const link = app.graph.links[l]; + if (!link) continue; + if (type === "*") type = link.type; + if (!app.canvas.selected_nodes[link.target_id]) { + hasExternal = true; + break; + } + } + if (hasExternal) { + config.external.push([i, slot, type]); + } + } + } + }; + const backup = localStorage.getItem("litegrapheditor_clipboard"); + try { + app.canvas.copyToClipboard(this.nodes); + const config = JSON.parse( + localStorage.getItem("litegrapheditor_clipboard") + ); + storeLinkTypes(config); + storeExternalLinks(config); + return config; + } finally { + localStorage.setItem("litegrapheditor_clipboard", backup); + } + } +} +const _GroupNodeConfig = class _GroupNodeConfig { + constructor(name, nodeData) { + __publicField(this, "name"); + __publicField(this, "nodeData"); + __publicField(this, "inputCount"); + __publicField(this, "oldToNewOutputMap"); + __publicField(this, "newToOldOutputMap"); + __publicField(this, "oldToNewInputMap"); + __publicField(this, "oldToNewWidgetMap"); + __publicField(this, "newToOldWidgetMap"); + __publicField(this, "primitiveDefs"); + __publicField(this, "widgetToPrimitive"); + __publicField(this, "primitiveToWidget"); + __publicField(this, "nodeInputs"); + __publicField(this, "outputVisibility"); + __publicField(this, "nodeDef"); + __publicField(this, "inputs"); + __publicField(this, "linksFrom"); + __publicField(this, "linksTo"); + __publicField(this, "externalFrom"); + __privateAdd(this, _convertedToProcess, []); + this.name = name; + this.nodeData = nodeData; + this.getLinks(); + this.inputCount = 0; + this.oldToNewOutputMap = {}; + this.newToOldOutputMap = {}; + this.oldToNewInputMap = {}; + this.oldToNewWidgetMap = {}; + this.newToOldWidgetMap = {}; + this.primitiveDefs = {}; + this.widgetToPrimitive = {}; + this.primitiveToWidget = {}; + this.nodeInputs = {}; + this.outputVisibility = []; + } + registerType(source = "workflow") { + return __async(this, null, function* () { + this.nodeDef = { + output: [], + output_name: [], + output_is_list: [], + output_is_hidden: [], + name: source + "/" + this.name, + display_name: this.name, + category: "group nodes" + ("/" + source), + input: { required: {} }, + [GROUP]: this + }; + this.inputs = []; + const seenInputs = {}; + const seenOutputs = {}; + for (let i = 0; i < this.nodeData.nodes.length; i++) { + const node = this.nodeData.nodes[i]; + node.index = i; + this.processNode(node, seenInputs, seenOutputs); + } + for (const p of __privateGet(this, _convertedToProcess)) { + p(); + } + __privateSet(this, _convertedToProcess, null); + yield app.registerNodeDef("workflow/" + this.name, this.nodeDef); + }); + } + getLinks() { + this.linksFrom = {}; + this.linksTo = {}; + this.externalFrom = {}; + for (const l of this.nodeData.links) { + const [sourceNodeId, sourceNodeSlot, targetNodeId, targetNodeSlot] = l; + if (sourceNodeId == null) continue; + if (!this.linksFrom[sourceNodeId]) { + this.linksFrom[sourceNodeId] = {}; + } + if (!this.linksFrom[sourceNodeId][sourceNodeSlot]) { + this.linksFrom[sourceNodeId][sourceNodeSlot] = []; + } + this.linksFrom[sourceNodeId][sourceNodeSlot].push(l); + if (!this.linksTo[targetNodeId]) { + this.linksTo[targetNodeId] = {}; + } + this.linksTo[targetNodeId][targetNodeSlot] = l; + } + if (this.nodeData.external) { + for (const ext2 of this.nodeData.external) { + if (!this.externalFrom[ext2[0]]) { + this.externalFrom[ext2[0]] = { [ext2[1]]: ext2[2] }; + } else { + this.externalFrom[ext2[0]][ext2[1]] = ext2[2]; + } + } + } + } + processNode(node, seenInputs, seenOutputs) { + var _a, _b, _c; + const def = this.getNodeDef(node); + if (!def) return; + const inputs = __spreadValues(__spreadValues({}, (_a = def.input) == null ? void 0 : _a.required), (_b = def.input) == null ? void 0 : _b.optional); + this.inputs.push(this.processNodeInputs(node, seenInputs, inputs)); + if ((_c = def.output) == null ? void 0 : _c.length) this.processNodeOutputs(node, seenOutputs, def); + } + getNodeDef(node) { + var _a, _b, _c, _d, _e; + const def = globalDefs[node.type]; + if (def) return def; + const linksFrom = this.linksFrom[node.index]; + if (node.type === "PrimitiveNode") { + if (!linksFrom) return; + let type = linksFrom["0"][0][5]; + if (type === "COMBO") { + const source = node.outputs[0].widget.name; + const fromTypeName = this.nodeData.nodes[linksFrom["0"][0][2]].type; + const fromType = globalDefs[fromTypeName]; + const input = (_a = fromType.input.required[source]) != null ? _a : fromType.input.optional[source]; + type = input[0]; + } + const def2 = this.primitiveDefs[node.index] = { + input: { + required: { + value: [type, {}] + } + }, + output: [type], + output_name: [], + output_is_list: [] + }; + return def2; + } else if (node.type === "Reroute") { + const linksTo = this.linksTo[node.index]; + if (linksTo && linksFrom && !((_b = this.externalFrom[node.index]) == null ? void 0 : _b[0])) { + return null; + } + let config = {}; + let rerouteType = "*"; + if (linksFrom) { + for (const [, , id2, slot] of linksFrom["0"]) { + const node2 = this.nodeData.nodes[id2]; + const input = node2.inputs[slot]; + if (rerouteType === "*") { + rerouteType = input.type; + } + if (input.widget) { + const targetDef = globalDefs[node2.type]; + const targetWidget = (_c = targetDef.input.required[input.widget.name]) != null ? _c : targetDef.input.optional[input.widget.name]; + const widget = [targetWidget[0], config]; + const res = mergeIfValid( + { + widget + }, + targetWidget, + false, + null, + widget + ); + config = (_d = res == null ? void 0 : res.customConfig) != null ? _d : config; + } + } + } else if (linksTo) { + const [id2, slot] = linksTo["0"]; + rerouteType = this.nodeData.nodes[id2].outputs[slot].type; + } else { + for (const l of this.nodeData.links) { + if (l[2] === node.index) { + rerouteType = l[5]; + break; + } + } + if (rerouteType === "*") { + const t = (_e = this.externalFrom[node.index]) == null ? void 0 : _e[0]; + if (t) { + rerouteType = t; + } + } + } + config.forceInput = true; + return { + input: { + required: { + [rerouteType]: [rerouteType, config] + } + }, + output: [rerouteType], + output_name: [], + output_is_list: [] + }; + } + console.warn( + "Skipping virtual node " + node.type + " when building group node " + this.name + ); + } + getInputConfig(node, inputName, seenInputs, config, extra) { + var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m; + const customConfig = (_c = (_b = (_a = this.nodeData.config) == null ? void 0 : _a[node.index]) == null ? void 0 : _b.input) == null ? void 0 : _c[inputName]; + let name = (_g = (_f = customConfig == null ? void 0 : customConfig.name) != null ? _f : (_e = (_d = node.inputs) == null ? void 0 : _d.find((inp) => inp.name === inputName)) == null ? void 0 : _e.label) != null ? _g : inputName; + let key = name; + let prefix = ""; + if (node.type === "PrimitiveNode" && node.title || name in seenInputs) { + prefix = `${(_h = node.title) != null ? _h : node.type} `; + key = name = `${prefix}${inputName}`; + if (name in seenInputs) { + name = `${prefix}${seenInputs[name]} ${inputName}`; + } + } + seenInputs[key] = ((_i = seenInputs[key]) != null ? _i : 1) + 1; + if (inputName === "seed" || inputName === "noise_seed") { + if (!extra) extra = {}; + extra.control_after_generate = `${prefix}control_after_generate`; + } + if (config[0] === "IMAGEUPLOAD") { + if (!extra) extra = {}; + extra.widget = (_m = (_l = this.oldToNewWidgetMap[node.index]) == null ? void 0 : _l[(_k = (_j = config[1]) == null ? void 0 : _j.widget) != null ? _k : "image"]) != null ? _m : "image"; + } + if (extra) { + config = [config[0], __spreadValues(__spreadValues({}, config[1]), extra)]; + } + return { name, config, customConfig }; + } + processWidgetInputs(inputs, node, inputNames, seenInputs) { + var _a; + const slots = []; + const converted = /* @__PURE__ */ new Map(); + const widgetMap = this.oldToNewWidgetMap[node.index] = {}; + for (const inputName of inputNames) { + let widgetType = app.getWidgetType(inputs[inputName], inputName); + if (widgetType) { + const convertedIndex = (_a = node.inputs) == null ? void 0 : _a.findIndex( + (inp) => { + var _a2; + return inp.name === inputName && ((_a2 = inp.widget) == null ? void 0 : _a2.name) === inputName; + } + ); + if (convertedIndex > -1) { + converted.set(convertedIndex, inputName); + widgetMap[inputName] = null; + } else { + const { name, config } = this.getInputConfig( + node, + inputName, + seenInputs, + inputs[inputName] + ); + this.nodeDef.input.required[name] = config; + widgetMap[inputName] = name; + this.newToOldWidgetMap[name] = { node, inputName }; + } + } else { + slots.push(inputName); + } + } + return { converted, slots }; + } + checkPrimitiveConnection(link, inputName, inputs) { + var _a; + const sourceNode = this.nodeData.nodes[link[0]]; + if (sourceNode.type === "PrimitiveNode") { + const [sourceNodeId, _, targetNodeId, __] = link; + const primitiveDef = this.primitiveDefs[sourceNodeId]; + const targetWidget = inputs[inputName]; + const primitiveConfig = primitiveDef.input.required.value; + const output = { widget: primitiveConfig }; + const config = mergeIfValid( + output, + targetWidget, + false, + null, + primitiveConfig + ); + primitiveConfig[1] = ((_a = config == null ? void 0 : config.customConfig) != null ? _a : inputs[inputName][1]) ? __spreadValues({}, inputs[inputName][1]) : {}; + let name = this.oldToNewWidgetMap[sourceNodeId]["value"]; + name = name.substr(0, name.length - 6); + primitiveConfig[1].control_after_generate = true; + primitiveConfig[1].control_prefix = name; + let toPrimitive = this.widgetToPrimitive[targetNodeId]; + if (!toPrimitive) { + toPrimitive = this.widgetToPrimitive[targetNodeId] = {}; + } + if (toPrimitive[inputName]) { + toPrimitive[inputName].push(sourceNodeId); + } + toPrimitive[inputName] = sourceNodeId; + let toWidget = this.primitiveToWidget[sourceNodeId]; + if (!toWidget) { + toWidget = this.primitiveToWidget[sourceNodeId] = []; + } + toWidget.push({ nodeId: targetNodeId, inputName }); + } + } + processInputSlots(inputs, node, slots, linksTo, inputMap, seenInputs) { + this.nodeInputs[node.index] = {}; + for (let i = 0; i < slots.length; i++) { + const inputName = slots[i]; + if (linksTo[i]) { + this.checkPrimitiveConnection(linksTo[i], inputName, inputs); + continue; + } + const { name, config, customConfig } = this.getInputConfig( + node, + inputName, + seenInputs, + inputs[inputName] + ); + this.nodeInputs[node.index][inputName] = name; + if ((customConfig == null ? void 0 : customConfig.visible) === false) continue; + this.nodeDef.input.required[name] = config; + inputMap[i] = this.inputCount++; + } + } + processConvertedWidgets(inputs, node, slots, converted, linksTo, inputMap, seenInputs) { + const convertedSlots = [...converted.keys()].sort().map((k) => converted.get(k)); + for (let i = 0; i < convertedSlots.length; i++) { + const inputName = convertedSlots[i]; + if (linksTo[slots.length + i]) { + this.checkPrimitiveConnection( + linksTo[slots.length + i], + inputName, + inputs + ); + continue; + } + const { name, config } = this.getInputConfig( + node, + inputName, + seenInputs, + inputs[inputName], + { + defaultInput: true + } + ); + this.nodeDef.input.required[name] = config; + this.newToOldWidgetMap[name] = { node, inputName }; + if (!this.oldToNewWidgetMap[node.index]) { + this.oldToNewWidgetMap[node.index] = {}; + } + this.oldToNewWidgetMap[node.index][inputName] = name; + inputMap[slots.length + i] = this.inputCount++; + } + } + processNodeInputs(node, seenInputs, inputs) { + var _a; + const inputMapping = []; + const inputNames = Object.keys(inputs); + if (!inputNames.length) return; + const { converted, slots } = this.processWidgetInputs( + inputs, + node, + inputNames, + seenInputs + ); + const linksTo = (_a = this.linksTo[node.index]) != null ? _a : {}; + const inputMap = this.oldToNewInputMap[node.index] = {}; + this.processInputSlots(inputs, node, slots, linksTo, inputMap, seenInputs); + __privateGet(this, _convertedToProcess).push( + () => this.processConvertedWidgets( + inputs, + node, + slots, + converted, + linksTo, + inputMap, + seenInputs + ) + ); + return inputMapping; + } + processNodeOutputs(node, seenOutputs, def) { + var _a, _b, _c, _d, _e, _f, _g, _h; + const oldToNew = this.oldToNewOutputMap[node.index] = {}; + for (let outputId = 0; outputId < def.output.length; outputId++) { + const linksFrom = this.linksFrom[node.index]; + const hasLink = (linksFrom == null ? void 0 : linksFrom[outputId]) && !((_a = this.externalFrom[node.index]) == null ? void 0 : _a[outputId]); + const customConfig = (_d = (_c = (_b = this.nodeData.config) == null ? void 0 : _b[node.index]) == null ? void 0 : _c.output) == null ? void 0 : _d[outputId]; + const visible = (_e = customConfig == null ? void 0 : customConfig.visible) != null ? _e : !hasLink; + this.outputVisibility.push(visible); + if (!visible) { + continue; + } + oldToNew[outputId] = this.nodeDef.output.length; + this.newToOldOutputMap[this.nodeDef.output.length] = { + node, + slot: outputId + }; + this.nodeDef.output.push(def.output[outputId]); + this.nodeDef.output_is_list.push(def.output_is_list[outputId]); + let label = customConfig == null ? void 0 : customConfig.name; + if (!label) { + label = (_g = (_f = def.output_name) == null ? void 0 : _f[outputId]) != null ? _g : def.output[outputId]; + const output = node.outputs.find((o) => o.name === label); + if (output == null ? void 0 : output.label) { + label = output.label; + } + } + let name = label; + if (name in seenOutputs) { + const prefix = `${(_h = node.title) != null ? _h : node.type} `; + name = `${prefix}${label}`; + if (name in seenOutputs) { + name = `${prefix}${node.index} ${label}`; + } + } + seenOutputs[name] = 1; + this.nodeDef.output_name.push(name); + } + } + static registerFromWorkflow(groupNodes, missingNodeTypes) { + return __async(this, null, function* () { + const clean = app.clean; + app.clean = function() { + for (const g in groupNodes) { + try { + LiteGraph.unregisterNodeType("workflow/" + g); + } catch (error) { + } + } + app.clean = clean; + }; + for (const g in groupNodes) { + const groupData = groupNodes[g]; + let hasMissing = false; + for (const n of groupData.nodes) { + if (!(n.type in LiteGraph.registered_node_types)) { + missingNodeTypes.push({ + type: n.type, + hint: ` (In group node 'workflow/${g}')` + }); + missingNodeTypes.push({ + type: "workflow/" + g, + action: { + text: "Remove from workflow", + callback: (e) => { + delete groupNodes[g]; + e.target.textContent = "Removed"; + e.target.style.pointerEvents = "none"; + e.target.style.opacity = 0.7; + } + } + }); + hasMissing = true; + } + } + if (hasMissing) continue; + const config = new _GroupNodeConfig(g, groupData); + yield config.registerType(); + } + }); + } +}; +_convertedToProcess = new WeakMap(); +let GroupNodeConfig = _GroupNodeConfig; +class GroupNodeHandler { + constructor(node) { + __publicField(this, "node"); + __publicField(this, "groupData"); + __publicField(this, "innerNodes"); + var _a, _b; + this.node = node; + this.groupData = (_b = (_a = node.constructor) == null ? void 0 : _a.nodeData) == null ? void 0 : _b[GROUP]; + this.node.setInnerNodes = (innerNodes) => { + var _a2; + this.innerNodes = innerNodes; + for (let innerNodeIndex = 0; innerNodeIndex < this.innerNodes.length; innerNodeIndex++) { + const innerNode = this.innerNodes[innerNodeIndex]; + for (const w of (_a2 = innerNode.widgets) != null ? _a2 : []) { + if (w.type === "converted-widget") { + w.serializeValue = w.origSerializeValue; + } + } + innerNode.index = innerNodeIndex; + innerNode.getInputNode = (slot) => { + var _a3, _b2; + const externalSlot = (_a3 = this.groupData.oldToNewInputMap[innerNode.index]) == null ? void 0 : _a3[slot]; + if (externalSlot != null) { + return this.node.getInputNode(externalSlot); + } + const innerLink = (_b2 = this.groupData.linksTo[innerNode.index]) == null ? void 0 : _b2[slot]; + if (!innerLink) return null; + const inputNode = innerNodes[innerLink[0]]; + if (inputNode.type === "PrimitiveNode") return null; + return inputNode; + }; + innerNode.getInputLink = (slot) => { + var _a3, _b2; + const externalSlot = (_a3 = this.groupData.oldToNewInputMap[innerNode.index]) == null ? void 0 : _a3[slot]; + if (externalSlot != null) { + const linkId = this.node.inputs[externalSlot].link; + let link2 = app.graph.links[linkId]; + link2 = __spreadProps(__spreadValues({}, link2), { + target_id: innerNode.id, + target_slot: +slot + }); + return link2; + } + let link = (_b2 = this.groupData.linksTo[innerNode.index]) == null ? void 0 : _b2[slot]; + if (!link) return null; + link = { + origin_id: innerNodes[link[0]].id, + origin_slot: link[1], + target_id: innerNode.id, + target_slot: +slot + }; + return link; + }; + } + }; + this.node.updateLink = (link) => { + var _a2; + link = __spreadValues({}, link); + const output = this.groupData.newToOldOutputMap[link.origin_slot]; + let innerNode = this.innerNodes[output.node.index]; + let l; + while ((innerNode == null ? void 0 : innerNode.type) === "Reroute") { + l = innerNode.getInputLink(0); + innerNode = innerNode.getInputNode(0); + } + if (!innerNode) { + return null; + } + if (l && GroupNodeHandler.isGroupNode(innerNode)) { + return innerNode.updateLink(l); + } + link.origin_id = innerNode.id; + link.origin_slot = (_a2 = l == null ? void 0 : l.origin_slot) != null ? _a2 : output.slot; + return link; + }; + this.node.getInnerNodes = () => { + if (!this.innerNodes) { + this.node.setInnerNodes( + this.groupData.nodeData.nodes.map((n, i) => { + const innerNode = LiteGraph.createNode(n.type); + innerNode.configure(n); + innerNode.id = `${this.node.id}:${i}`; + return innerNode; + }) + ); + } + this.updateInnerWidgets(); + return this.innerNodes; + }; + this.node.recreate = () => __async(this, null, function* () { + const id2 = this.node.id; + const sz = this.node.size; + const nodes = this.node.convertToNodes(); + const groupNode = LiteGraph.createNode(this.node.type); + groupNode.id = id2; + groupNode.setInnerNodes(nodes); + groupNode[GROUP].populateWidgets(); + app.graph.add(groupNode); + groupNode.size = [ + Math.max(groupNode.size[0], sz[0]), + Math.max(groupNode.size[1], sz[1]) + ]; + groupNode[GROUP].replaceNodes(nodes); + return groupNode; + }); + this.node.convertToNodes = () => { + const addInnerNodes = () => { + var _a2, _b2; + const backup = localStorage.getItem("litegrapheditor_clipboard"); + const c = __spreadValues({}, this.groupData.nodeData); + c.nodes = [...c.nodes]; + const innerNodes = this.node.getInnerNodes(); + let ids = []; + for (let i = 0; i < c.nodes.length; i++) { + let id2 = (_a2 = innerNodes == null ? void 0 : innerNodes[i]) == null ? void 0 : _a2.id; + if (id2 == null || isNaN(id2)) { + id2 = void 0; + } else { + ids.push(id2); + } + c.nodes[i] = __spreadProps(__spreadValues({}, c.nodes[i]), { id: id2 }); + } + localStorage.setItem("litegrapheditor_clipboard", JSON.stringify(c)); + app.canvas.pasteFromClipboard(); + localStorage.setItem("litegrapheditor_clipboard", backup); + const [x, y] = this.node.pos; + let top; + let left; + const selectedIds2 = ids.length ? ids : Object.keys(app.canvas.selected_nodes); + const newNodes2 = []; + for (let i = 0; i < selectedIds2.length; i++) { + const id2 = selectedIds2[i]; + const newNode = app.graph.getNodeById(id2); + const innerNode = innerNodes[i]; + newNodes2.push(newNode); + if (left == null || newNode.pos[0] < left) { + left = newNode.pos[0]; + } + if (top == null || newNode.pos[1] < top) { + top = newNode.pos[1]; + } + if (!newNode.widgets) continue; + const map = this.groupData.oldToNewWidgetMap[innerNode.index]; + if (map) { + const widgets = Object.keys(map); + for (const oldName of widgets) { + const newName = map[oldName]; + if (!newName) continue; + const widgetIndex = this.node.widgets.findIndex( + (w) => w.name === newName + ); + if (widgetIndex === -1) continue; + if (innerNode.type === "PrimitiveNode") { + for (let i2 = 0; i2 < newNode.widgets.length; i2++) { + newNode.widgets[i2].value = this.node.widgets[widgetIndex + i2].value; + } + } else { + const outerWidget = this.node.widgets[widgetIndex]; + const newWidget = newNode.widgets.find( + (w) => w.name === oldName + ); + if (!newWidget) continue; + newWidget.value = outerWidget.value; + for (let w = 0; w < ((_b2 = outerWidget.linkedWidgets) == null ? void 0 : _b2.length); w++) { + newWidget.linkedWidgets[w].value = outerWidget.linkedWidgets[w].value; + } + } + } + } + } + for (const newNode of newNodes2) { + newNode.pos = [ + newNode.pos[0] - (left - x), + newNode.pos[1] - (top - y) + ]; + } + return { newNodes: newNodes2, selectedIds: selectedIds2 }; + }; + const reconnectInputs = (selectedIds2) => { + for (const innerNodeIndex in this.groupData.oldToNewInputMap) { + const id2 = selectedIds2[innerNodeIndex]; + const newNode = app.graph.getNodeById(id2); + const map = this.groupData.oldToNewInputMap[innerNodeIndex]; + for (const innerInputId in map) { + const groupSlotId = map[innerInputId]; + if (groupSlotId == null) continue; + const slot = node.inputs[groupSlotId]; + if (slot.link == null) continue; + const link = app.graph.links[slot.link]; + if (!link) continue; + const originNode = app.graph.getNodeById(link.origin_id); + originNode.connect(link.origin_slot, newNode, +innerInputId); + } + } + }; + const reconnectOutputs = (selectedIds2) => { + var _a2; + for (let groupOutputId = 0; groupOutputId < ((_a2 = node.outputs) == null ? void 0 : _a2.length); groupOutputId++) { + const output = node.outputs[groupOutputId]; + if (!output.links) continue; + const links = [...output.links]; + for (const l of links) { + const slot = this.groupData.newToOldOutputMap[groupOutputId]; + const link = app.graph.links[l]; + const targetNode = app.graph.getNodeById(link.target_id); + const newNode = app.graph.getNodeById(selectedIds2[slot.node.index]); + newNode.connect(slot.slot, targetNode, link.target_slot); + } + } + }; + const { newNodes, selectedIds } = addInnerNodes(); + reconnectInputs(selectedIds); + reconnectOutputs(selectedIds); + app.graph.remove(this.node); + return newNodes; + }; + const getExtraMenuOptions = this.node.getExtraMenuOptions; + this.node.getExtraMenuOptions = function(_, options) { + getExtraMenuOptions == null ? void 0 : getExtraMenuOptions.apply(this, arguments); + let optionIndex = options.findIndex((o) => o.content === "Outputs"); + if (optionIndex === -1) optionIndex = options.length; + else optionIndex++; + options.splice( + optionIndex, + 0, + null, + { + content: "Convert to nodes", + callback: () => { + return this.convertToNodes(); + } + }, + { + content: "Manage Group Node", + callback: () => { + new ManageGroupDialog(app).show(this.type); + } + } + ); + }; + const onDrawTitleBox = this.node.onDrawTitleBox; + this.node.onDrawTitleBox = function(ctx, height, size, scale) { + onDrawTitleBox == null ? void 0 : onDrawTitleBox.apply(this, arguments); + const fill = ctx.fillStyle; + ctx.beginPath(); + ctx.rect(11, -height + 11, 2, 2); + ctx.rect(14, -height + 11, 2, 2); + ctx.rect(17, -height + 11, 2, 2); + ctx.rect(11, -height + 14, 2, 2); + ctx.rect(14, -height + 14, 2, 2); + ctx.rect(17, -height + 14, 2, 2); + ctx.rect(11, -height + 17, 2, 2); + ctx.rect(14, -height + 17, 2, 2); + ctx.rect(17, -height + 17, 2, 2); + ctx.fillStyle = this.boxcolor || LiteGraph.NODE_DEFAULT_BOXCOLOR; + ctx.fill(); + ctx.fillStyle = fill; + }; + const onDrawForeground = node.onDrawForeground; + const groupData = this.groupData.nodeData; + node.onDrawForeground = function(ctx) { + var _a2; + const r = (_a2 = onDrawForeground == null ? void 0 : onDrawForeground.apply) == null ? void 0 : _a2.call(onDrawForeground, this, arguments); + if (+app.runningNodeId === this.id && this.runningInternalNodeId !== null) { + const n = groupData.nodes[this.runningInternalNodeId]; + if (!n) return; + const message = `Running ${n.title || n.type} (${this.runningInternalNodeId}/${groupData.nodes.length})`; + ctx.save(); + ctx.font = "12px sans-serif"; + const sz = ctx.measureText(message); + ctx.fillStyle = node.boxcolor || LiteGraph.NODE_DEFAULT_BOXCOLOR; + ctx.beginPath(); + ctx.roundRect( + 0, + -LiteGraph.NODE_TITLE_HEIGHT - 20, + sz.width + 12, + 20, + 5 + ); + ctx.fill(); + ctx.fillStyle = "#fff"; + ctx.fillText(message, 6, -LiteGraph.NODE_TITLE_HEIGHT - 6); + ctx.restore(); + } + }; + const onExecutionStart = this.node.onExecutionStart; + this.node.onExecutionStart = function() { + this.resetExecution = true; + return onExecutionStart == null ? void 0 : onExecutionStart.apply(this, arguments); + }; + const self = this; + const onNodeCreated = this.node.onNodeCreated; + this.node.onNodeCreated = function() { + var _a2; + if (!this.widgets) { + return; + } + const config = self.groupData.nodeData.config; + if (config) { + for (const n in config) { + const inputs = (_a2 = config[n]) == null ? void 0 : _a2.input; + for (const w in inputs) { + if (inputs[w].visible !== false) continue; + const widgetName = self.groupData.oldToNewWidgetMap[n][w]; + const widget = this.widgets.find((w2) => w2.name === widgetName); + if (widget) { + widget.type = "hidden"; + widget.computeSize = () => [0, -4]; + } + } + } + } + return onNodeCreated == null ? void 0 : onNodeCreated.apply(this, arguments); + }; + function handleEvent(type, getId, getEvent) { + const handler = ({ detail }) => { + var _a2; + const id2 = getId(detail); + if (!id2) return; + const node2 = app.graph.getNodeById(id2); + if (node2) return; + const innerNodeIndex = (_a2 = this.innerNodes) == null ? void 0 : _a2.findIndex((n) => n.id == id2); + if (innerNodeIndex > -1) { + this.node.runningInternalNodeId = innerNodeIndex; + api.dispatchEvent( + new CustomEvent(type, { + detail: getEvent(detail, this.node.id + "", this.node) + }) + ); + } + }; + api.addEventListener(type, handler); + return handler; + } + const executing = handleEvent.call( + this, + "executing", + (d) => d, + (d, id2, node2) => id2 + ); + const executed = handleEvent.call( + this, + "executed", + (d) => (d == null ? void 0 : d.display_node) || (d == null ? void 0 : d.node), + (d, id2, node2) => __spreadProps(__spreadValues({}, d), { + node: id2, + display_node: id2, + merge: !node2.resetExecution + }) + ); + const onRemoved = node.onRemoved; + this.node.onRemoved = function() { + onRemoved == null ? void 0 : onRemoved.apply(this, arguments); + api.removeEventListener("executing", executing); + api.removeEventListener("executed", executed); + }; + this.node.refreshComboInNode = (defs) => { + var _a2, _b2, _c, _d, _e; + for (const widgetName in this.groupData.newToOldWidgetMap) { + const widget = this.node.widgets.find((w) => w.name === widgetName); + if ((widget == null ? void 0 : widget.type) === "combo") { + const old = this.groupData.newToOldWidgetMap[widgetName]; + const def = defs[old.node.type]; + const input = (_e = (_b2 = (_a2 = def == null ? void 0 : def.input) == null ? void 0 : _a2.required) == null ? void 0 : _b2[old.inputName]) != null ? _e : (_d = (_c = def == null ? void 0 : def.input) == null ? void 0 : _c.optional) == null ? void 0 : _d[old.inputName]; + if (!input) continue; + widget.options.values = input[0]; + if (old.inputName !== "image" && !widget.options.values.includes(widget.value)) { + widget.value = widget.options.values[0]; + widget.callback(widget.value); + } + } + } + }; + } + updateInnerWidgets() { + var _a, _b; + for (const newWidgetName in this.groupData.newToOldWidgetMap) { + const newWidget = this.node.widgets.find((w) => w.name === newWidgetName); + if (!newWidget) continue; + const newValue = newWidget.value; + const old = this.groupData.newToOldWidgetMap[newWidgetName]; + let innerNode = this.innerNodes[old.node.index]; + if (innerNode.type === "PrimitiveNode") { + innerNode.primitiveValue = newValue; + const primitiveLinked = this.groupData.primitiveToWidget[old.node.index]; + for (const linked of primitiveLinked != null ? primitiveLinked : []) { + const node = this.innerNodes[linked.nodeId]; + const widget2 = node.widgets.find((w) => w.name === linked.inputName); + if (widget2) { + widget2.value = newValue; + } + } + continue; + } else if (innerNode.type === "Reroute") { + const rerouteLinks = this.groupData.linksFrom[old.node.index]; + if (rerouteLinks) { + for (const [_, , targetNodeId, targetSlot] of rerouteLinks["0"]) { + const node = this.innerNodes[targetNodeId]; + const input = node.inputs[targetSlot]; + if (input.widget) { + const widget2 = (_a = node.widgets) == null ? void 0 : _a.find( + (w) => w.name === input.widget.name + ); + if (widget2) { + widget2.value = newValue; + } + } + } + } + } + const widget = (_b = innerNode.widgets) == null ? void 0 : _b.find((w) => w.name === old.inputName); + if (widget) { + widget.value = newValue; + } + } + } + populatePrimitive(node, nodeId, oldName, i, linkedShift) { + var _a, _b; + const primitiveId = (_a = this.groupData.widgetToPrimitive[nodeId]) == null ? void 0 : _a[oldName]; + if (primitiveId == null) return; + const targetWidgetName = this.groupData.oldToNewWidgetMap[primitiveId]["value"]; + const targetWidgetIndex = this.node.widgets.findIndex( + (w) => w.name === targetWidgetName + ); + if (targetWidgetIndex > -1) { + const primitiveNode = this.innerNodes[primitiveId]; + let len = primitiveNode.widgets.length; + if (len - 1 !== ((_b = this.node.widgets[targetWidgetIndex].linkedWidgets) == null ? void 0 : _b.length)) { + len = 1; + } + for (let i2 = 0; i2 < len; i2++) { + this.node.widgets[targetWidgetIndex + i2].value = primitiveNode.widgets[i2].value; + } + } + return true; + } + populateReroute(node, nodeId, map) { + var _a, _b, _c, _d, _e, _f; + if (node.type !== "Reroute") return; + const link = (_b = (_a = this.groupData.linksFrom[nodeId]) == null ? void 0 : _a[0]) == null ? void 0 : _b[0]; + if (!link) return; + const [, , targetNodeId, targetNodeSlot] = link; + const targetNode = this.groupData.nodeData.nodes[targetNodeId]; + const inputs = targetNode.inputs; + const targetWidget = (_c = inputs == null ? void 0 : inputs[targetNodeSlot]) == null ? void 0 : _c.widget; + if (!targetWidget) return; + const offset = inputs.length - ((_e = (_d = targetNode.widgets_values) == null ? void 0 : _d.length) != null ? _e : 0); + const v = (_f = targetNode.widgets_values) == null ? void 0 : _f[targetNodeSlot - offset]; + if (v == null) return; + const widgetName = Object.values(map)[0]; + const widget = this.node.widgets.find((w) => w.name === widgetName); + if (widget) { + widget.value = v; + } + } + populateWidgets() { + var _a, _b, _c, _d, _e, _f; + if (!this.node.widgets) return; + for (let nodeId = 0; nodeId < this.groupData.nodeData.nodes.length; nodeId++) { + const node = this.groupData.nodeData.nodes[nodeId]; + const map = (_a = this.groupData.oldToNewWidgetMap[nodeId]) != null ? _a : {}; + const widgets = Object.keys(map); + if (!((_b = node.widgets_values) == null ? void 0 : _b.length)) { + this.populateReroute(node, nodeId, map); + continue; + } + let linkedShift = 0; + for (let i = 0; i < widgets.length; i++) { + const oldName = widgets[i]; + const newName = map[oldName]; + const widgetIndex = this.node.widgets.findIndex( + (w) => w.name === newName + ); + const mainWidget = this.node.widgets[widgetIndex]; + if (this.populatePrimitive(node, nodeId, oldName, i, linkedShift) || widgetIndex === -1) { + const innerWidget = (_c = this.innerNodes[nodeId].widgets) == null ? void 0 : _c.find( + (w) => w.name === oldName + ); + linkedShift += (_e = (_d = innerWidget == null ? void 0 : innerWidget.linkedWidgets) == null ? void 0 : _d.length) != null ? _e : 0; + } + if (widgetIndex === -1) { + continue; + } + mainWidget.value = node.widgets_values[i + linkedShift]; + for (let w = 0; w < ((_f = mainWidget.linkedWidgets) == null ? void 0 : _f.length); w++) { + this.node.widgets[widgetIndex + w + 1].value = node.widgets_values[i + ++linkedShift]; + } + } + } + } + replaceNodes(nodes) { + let top; + let left; + for (let i = 0; i < nodes.length; i++) { + const node = nodes[i]; + if (left == null || node.pos[0] < left) { + left = node.pos[0]; + } + if (top == null || node.pos[1] < top) { + top = node.pos[1]; + } + this.linkOutputs(node, i); + app.graph.remove(node); + } + this.linkInputs(); + this.node.pos = [left, top]; + } + linkOutputs(originalNode, nodeId) { + var _a; + if (!originalNode.outputs) return; + for (const output of originalNode.outputs) { + if (!output.links) continue; + const links = [...output.links]; + for (const l of links) { + const link = app.graph.links[l]; + if (!link) continue; + const targetNode = app.graph.getNodeById(link.target_id); + const newSlot = (_a = this.groupData.oldToNewOutputMap[nodeId]) == null ? void 0 : _a[link.origin_slot]; + if (newSlot != null) { + this.node.connect(newSlot, targetNode, link.target_slot); + } + } + } + } + linkInputs() { + var _a; + for (const link of (_a = this.groupData.nodeData.links) != null ? _a : []) { + const [, originSlot, targetId, targetSlot, actualOriginId] = link; + const originNode = app.graph.getNodeById(actualOriginId); + if (!originNode) continue; + originNode.connect( + originSlot, + this.node.id, + this.groupData.oldToNewInputMap[targetId][targetSlot] + ); + } + } + static getGroupData(node) { + var _a, _b, _c; + return (_c = (_b = node.nodeData) != null ? _b : (_a = node.constructor) == null ? void 0 : _a.nodeData) == null ? void 0 : _c[GROUP]; + } + static isGroupNode(node) { + var _a, _b; + return !!((_b = (_a = node.constructor) == null ? void 0 : _a.nodeData) == null ? void 0 : _b[GROUP]); + } + static fromNodes(nodes) { + return __async(this, null, function* () { + const builder = new GroupNodeBuilder(nodes); + const res = builder.build(); + if (!res) return; + const { name, nodeData } = res; + const config = new GroupNodeConfig(name, nodeData); + yield config.registerType(); + const groupNode = LiteGraph.createNode(`workflow/${name}`); + groupNode.setInnerNodes(builder.nodes); + groupNode[GROUP].populateWidgets(); + app.graph.add(groupNode); + groupNode[GROUP].replaceNodes(builder.nodes); + return groupNode; + }); + } +} +function addConvertToGroupOptions() { + function addConvertOption(options, index) { + var _a; + const selected = Object.values((_a = app.canvas.selected_nodes) != null ? _a : {}); + const disabled = selected.length < 2 || selected.find((n) => GroupNodeHandler.isGroupNode(n)); + options.splice(index + 1, null, { + content: `Convert to Group Node`, + disabled, + callback: () => __async(this, null, function* () { + return yield GroupNodeHandler.fromNodes(selected); + }) + }); + } + function addManageOption(options, index) { + var _a; + const groups = (_a = app.graph.extra) == null ? void 0 : _a.groupNodes; + const disabled = !groups || !Object.keys(groups).length; + options.splice(index + 1, null, { + content: `Manage Group Nodes`, + disabled, + callback: () => { + new ManageGroupDialog(app).show(); + } + }); + } + const getCanvasMenuOptions = LGraphCanvas.prototype.getCanvasMenuOptions; + LGraphCanvas.prototype.getCanvasMenuOptions = function() { + const options = getCanvasMenuOptions.apply(this, arguments); + const index = options.findIndex((o) => (o == null ? void 0 : o.content) === "Add Group") + 1 || options.length; + addConvertOption(options, index); + addManageOption(options, index + 1); + return options; + }; + const getNodeMenuOptions = LGraphCanvas.prototype.getNodeMenuOptions; + LGraphCanvas.prototype.getNodeMenuOptions = function(node) { + const options = getNodeMenuOptions.apply(this, arguments); + if (!GroupNodeHandler.isGroupNode(node)) { + const index = options.findIndex((o) => (o == null ? void 0 : o.content) === "Outputs") + 1 || options.length - 1; + addConvertOption(options, index); + } + return options; + }; +} +const id$3 = "Comfy.GroupNode"; +let globalDefs; +const ext$1 = { + name: id$3, + setup() { + addConvertToGroupOptions(); + }, + beforeConfigureGraph(graphData, missingNodeTypes) { + return __async(this, null, function* () { + var _a; + const nodes = (_a = graphData == null ? void 0 : graphData.extra) == null ? void 0 : _a.groupNodes; + if (nodes) { + yield GroupNodeConfig.registerFromWorkflow(nodes, missingNodeTypes); + } + }); + }, + addCustomNodeDefs(defs) { + globalDefs = defs; + }, + nodeCreated(node) { + if (GroupNodeHandler.isGroupNode(node)) { + node[GROUP] = new GroupNodeHandler(node); + } + }, + refreshComboInNodes(defs) { + return __async(this, null, function* () { + var _a; + Object.assign(globalDefs, defs); + const nodes = (_a = app.graph.extra) == null ? void 0 : _a.groupNodes; + if (nodes) { + yield GroupNodeConfig.registerFromWorkflow(nodes, {}); + } + }); + } +}; +app.registerExtension(ext$1); +window.comfyAPI = window.comfyAPI || {}; +window.comfyAPI.groupNode = window.comfyAPI.groupNode || {}; +window.comfyAPI.groupNode.GroupNodeConfig = GroupNodeConfig; +window.comfyAPI.groupNode.GroupNodeHandler = GroupNodeHandler; +function setNodeMode(node, mode) { + node.mode = mode; + node.graph.change(); +} +function addNodesToGroup(group, nodes = []) { + var _a; + var x1, y1, x2, y2; + var nx1, ny1, nx2, ny2; + var node; + x1 = y1 = x2 = y2 = -1; + nx1 = ny1 = nx2 = ny2 = -1; + for (var n of [group._nodes, nodes]) { + for (var i in n) { + node = n[i]; + nx1 = node.pos[0]; + ny1 = node.pos[1]; + nx2 = node.pos[0] + node.size[0]; + ny2 = node.pos[1] + node.size[1]; + if (node.type != "Reroute") { + ny1 -= LiteGraph.NODE_TITLE_HEIGHT; + } + if ((_a = node.flags) == null ? void 0 : _a.collapsed) { + ny2 = ny1 + LiteGraph.NODE_TITLE_HEIGHT; + if (node == null ? void 0 : node._collapsed_width) { + nx2 = nx1 + Math.round(node._collapsed_width); + } + } + if (x1 == -1 || nx1 < x1) { + x1 = nx1; + } + if (y1 == -1 || ny1 < y1) { + y1 = ny1; + } + if (x2 == -1 || nx2 > x2) { + x2 = nx2; + } + if (y2 == -1 || ny2 > y2) { + y2 = ny2; + } + } + } + var padding = 10; + y1 = y1 - Math.round(group.font_size * 1.4); + group.pos = [x1 - padding, y1 - padding]; + group.size = [x2 - x1 + padding * 2, y2 - y1 + padding * 2]; +} +app.registerExtension({ + name: "Comfy.GroupOptions", + setup() { + const orig = LGraphCanvas.prototype.getCanvasMenuOptions; + LGraphCanvas.prototype.getCanvasMenuOptions = function() { + const options = orig.apply(this, arguments); + const group = this.graph.getGroupOnPos( + this.graph_mouse[0], + this.graph_mouse[1] + ); + if (!group) { + options.push({ + content: "Add Group For Selected Nodes", + disabled: !Object.keys(app.canvas.selected_nodes || {}).length, + callback: () => { + var group2 = new LiteGraph.LGraphGroup(); + addNodesToGroup(group2, this.selected_nodes); + app.canvas.graph.add(group2); + this.graph.change(); + } + }); + return options; + } + group.recomputeInsideNodes(); + const nodesInGroup = group._nodes; + options.push({ + content: "Add Selected Nodes To Group", + disabled: !Object.keys(app.canvas.selected_nodes || {}).length, + callback: () => { + addNodesToGroup(group, this.selected_nodes); + this.graph.change(); + } + }); + if (nodesInGroup.length === 0) { + return options; + } else { + options.push(null); + } + let allNodesAreSameMode = true; + for (let i = 1; i < nodesInGroup.length; i++) { + if (nodesInGroup[i].mode !== nodesInGroup[0].mode) { + allNodesAreSameMode = false; + break; + } + } + options.push({ + content: "Fit Group To Nodes", + callback: () => { + addNodesToGroup(group); + this.graph.change(); + } + }); + options.push({ + content: "Select Nodes", + callback: () => { + this.selectNodes(nodesInGroup); + this.graph.change(); + this.canvas.focus(); + } + }); + if (allNodesAreSameMode) { + const mode = nodesInGroup[0].mode; + switch (mode) { + case 0: + options.push({ + content: "Set Group Nodes to Never", + callback: () => { + for (const node of nodesInGroup) { + setNodeMode(node, 2); + } + } + }); + options.push({ + content: "Bypass Group Nodes", + callback: () => { + for (const node of nodesInGroup) { + setNodeMode(node, 4); + } + } + }); + break; + case 2: + options.push({ + content: "Set Group Nodes to Always", + callback: () => { + for (const node of nodesInGroup) { + setNodeMode(node, 0); + } + } + }); + options.push({ + content: "Bypass Group Nodes", + callback: () => { + for (const node of nodesInGroup) { + setNodeMode(node, 4); + } + } + }); + break; + case 4: + options.push({ + content: "Set Group Nodes to Always", + callback: () => { + for (const node of nodesInGroup) { + setNodeMode(node, 0); + } + } + }); + options.push({ + content: "Set Group Nodes to Never", + callback: () => { + for (const node of nodesInGroup) { + setNodeMode(node, 2); + } + } + }); + break; + default: + options.push({ + content: "Set Group Nodes to Always", + callback: () => { + for (const node of nodesInGroup) { + setNodeMode(node, 0); + } + } + }); + options.push({ + content: "Set Group Nodes to Never", + callback: () => { + for (const node of nodesInGroup) { + setNodeMode(node, 2); + } + } + }); + options.push({ + content: "Bypass Group Nodes", + callback: () => { + for (const node of nodesInGroup) { + setNodeMode(node, 4); + } + } + }); + break; + } + } else { + options.push({ + content: "Set Group Nodes to Always", + callback: () => { + for (const node of nodesInGroup) { + setNodeMode(node, 0); + } + } + }); + options.push({ + content: "Set Group Nodes to Never", + callback: () => { + for (const node of nodesInGroup) { + setNodeMode(node, 2); + } + } + }); + options.push({ + content: "Bypass Group Nodes", + callback: () => { + for (const node of nodesInGroup) { + setNodeMode(node, 4); + } + } + }); + } + return options; + }; + } +}); +const id$2 = "Comfy.InvertMenuScrolling"; +app.registerExtension({ + name: id$2, + init() { + const ctxMenu = LiteGraph.ContextMenu; + const replace = () => { + LiteGraph.ContextMenu = function(values, options) { + options = options || {}; + if (options.scroll_speed) { + options.scroll_speed *= -1; + } else { + options.scroll_speed = -0.1; + } + return ctxMenu.call(this, values, options); + }; + LiteGraph.ContextMenu.prototype = ctxMenu.prototype; + }; + app.ui.settings.addSetting({ + id: id$2, + name: "Invert Menu Scrolling", + type: "boolean", + defaultValue: false, + onChange(value) { + if (value) { + replace(); + } else { + LiteGraph.ContextMenu = ctxMenu; + } + } + }); + } +}); +app.registerExtension({ + name: "Comfy.Keybinds", + init() { + const keybindListener = function(event) { + const modifierPressed = event.ctrlKey || event.metaKey; + if (modifierPressed && event.key === "Enter") { + if (event.altKey) { + api.interrupt(); + return; + } + app.queuePrompt(event.shiftKey ? -1 : 0).then(); + return; + } + const target = event.composedPath()[0]; + if (["INPUT", "TEXTAREA"].includes(target.tagName)) { + return; + } + const modifierKeyIdMap = { + s: "#comfy-save-button", + o: "#comfy-file-input", + Backspace: "#comfy-clear-button", + d: "#comfy-load-default-button" + }; + const modifierKeybindId = modifierKeyIdMap[event.key]; + if (modifierPressed && modifierKeybindId) { + event.preventDefault(); + const elem = document.querySelector(modifierKeybindId); + elem.click(); + return; + } + if (event.ctrlKey || event.altKey || event.metaKey) { + return; + } + if (event.key === "Escape") { + const modals = document.querySelectorAll(".comfy-modal"); + const modal = Array.from(modals).find( + (modal2) => window.getComputedStyle(modal2).getPropertyValue("display") !== "none" + ); + if (modal) { + modal.style.display = "none"; + } + ; + [...document.querySelectorAll("dialog")].forEach((d) => { + d.close(); + }); + } + const keyIdMap = { + q: ".queue-tab-button.side-bar-button", + h: ".queue-tab-button.side-bar-button", + r: "#comfy-refresh-button" + }; + const buttonId = keyIdMap[event.key]; + if (buttonId) { + const button = document.querySelector(buttonId); + button.click(); + } + }; + window.addEventListener("keydown", keybindListener, true); + } +}); +const id$1 = "Comfy.LinkRenderMode"; +const ext = { + name: id$1, + setup(app2) { + return __async(this, null, function* () { + app2.ui.settings.addSetting({ + id: id$1, + name: "Link Render Mode", + defaultValue: 2, + type: "combo", + // @ts-expect-error + options: [...LiteGraph.LINK_RENDER_MODES, "Hidden"].map((m, i) => ({ + value: i, + text: m, + selected: i == app2.canvas.links_render_mode + })), + onChange(value) { + app2.canvas.links_render_mode = +value; + app2.graph.setDirtyCanvas(true); + } + }); + }); + } +}; +app.registerExtension(ext); +function dataURLToBlob(dataURL) { + const parts = dataURL.split(";base64,"); + const contentType = parts[0].split(":")[1]; + const byteString = atob(parts[1]); + const arrayBuffer = new ArrayBuffer(byteString.length); + const uint8Array = new Uint8Array(arrayBuffer); + for (let i = 0; i < byteString.length; i++) { + uint8Array[i] = byteString.charCodeAt(i); + } + return new Blob([arrayBuffer], { type: contentType }); +} +function loadedImageToBlob(image) { + const canvas = document.createElement("canvas"); + canvas.width = image.width; + canvas.height = image.height; + const ctx = canvas.getContext("2d"); + ctx.drawImage(image, 0, 0); + const dataURL = canvas.toDataURL("image/png", 1); + const blob = dataURLToBlob(dataURL); + return blob; +} +function loadImage(imagePath) { + return new Promise((resolve, reject) => { + const image = new Image(); + image.onload = function() { + resolve(image); + }; + image.src = imagePath; + }); +} +function uploadMask(filepath, formData) { + return __async(this, null, function* () { + yield api.fetchApi("/upload/mask", { + method: "POST", + body: formData + }).then((response) => { + }).catch((error) => { + console.error("Error:", error); + }); + ComfyApp.clipspace.imgs[ComfyApp.clipspace["selectedIndex"]] = new Image(); + ComfyApp.clipspace.imgs[ComfyApp.clipspace["selectedIndex"]].src = api.apiURL( + "/view?" + new URLSearchParams(filepath).toString() + app.getPreviewFormatParam() + app.getRandParam() + ); + if (ComfyApp.clipspace.images) + ComfyApp.clipspace.images[ComfyApp.clipspace["selectedIndex"]] = filepath; + ClipspaceDialog.invalidatePreview(); + }); +} +function prepare_mask(image, maskCanvas, maskCtx, maskColor) { + maskCtx.drawImage(image, 0, 0, maskCanvas.width, maskCanvas.height); + const maskData = maskCtx.getImageData( + 0, + 0, + maskCanvas.width, + maskCanvas.height + ); + for (let i = 0; i < maskData.data.length; i += 4) { + if (maskData.data[i + 3] == 255) maskData.data[i + 3] = 0; + else maskData.data[i + 3] = 255; + maskData.data[i] = maskColor.r; + maskData.data[i + 1] = maskColor.g; + maskData.data[i + 2] = maskColor.b; + } + maskCtx.globalCompositeOperation = "source-over"; + maskCtx.putImageData(maskData, 0, 0); +} +const _MaskEditorDialog = class _MaskEditorDialog extends ComfyDialog { + constructor() { + super(); + __publicField(this, "brush"); + __publicField(this, "maskCtx"); + __publicField(this, "maskCanvas"); + __publicField(this, "brush_size_slider"); + __publicField(this, "brush_opacity_slider"); + __publicField(this, "colorButton"); + __publicField(this, "saveButton"); + __publicField(this, "zoom_ratio"); + __publicField(this, "pan_x"); + __publicField(this, "pan_y"); + __publicField(this, "imgCanvas"); + __publicField(this, "last_display_style"); + __publicField(this, "is_visible"); + __publicField(this, "image"); + __publicField(this, "handler_registered"); + __publicField(this, "brush_slider_input"); + __publicField(this, "cursorX"); + __publicField(this, "cursorY"); + __publicField(this, "mousedown_pan_x"); + __publicField(this, "mousedown_pan_y"); + __publicField(this, "last_pressure"); + __publicField(this, "is_layout_created", false); + __publicField(this, "brush_opacity", 0.7); + __publicField(this, "brush_size", 10); + __publicField(this, "brush_color_mode", "black"); + __publicField(this, "drawing_mode", false); + __publicField(this, "lastx", -1); + __publicField(this, "lasty", -1); + __publicField(this, "lasttime", 0); + this.element = $el("div.comfy-modal", { parent: document.body }, [ + $el("div.comfy-modal-content", [...this.createButtons()]) + ]); + } + static getInstance() { + if (!_MaskEditorDialog.instance) { + _MaskEditorDialog.instance = new _MaskEditorDialog(); + } + return _MaskEditorDialog.instance; + } + createButtons() { + return []; + } + createButton(name, callback) { + var button = document.createElement("button"); + button.style.pointerEvents = "auto"; + button.innerText = name; + button.addEventListener("click", callback); + return button; + } + createLeftButton(name, callback) { + var button = this.createButton(name, callback); + button.style.cssFloat = "left"; + button.style.marginRight = "4px"; + return button; + } + createRightButton(name, callback) { + var button = this.createButton(name, callback); + button.style.cssFloat = "right"; + button.style.marginLeft = "4px"; + return button; + } + createLeftSlider(self, name, callback) { + const divElement = document.createElement("div"); + divElement.id = "maskeditor-slider"; + divElement.style.cssFloat = "left"; + divElement.style.fontFamily = "sans-serif"; + divElement.style.marginRight = "4px"; + divElement.style.color = "var(--input-text)"; + divElement.style.backgroundColor = "var(--comfy-input-bg)"; + divElement.style.borderRadius = "8px"; + divElement.style.borderColor = "var(--border-color)"; + divElement.style.borderStyle = "solid"; + divElement.style.fontSize = "15px"; + divElement.style.height = "21px"; + divElement.style.padding = "1px 6px"; + divElement.style.display = "flex"; + divElement.style.position = "relative"; + divElement.style.top = "2px"; + divElement.style.pointerEvents = "auto"; + self.brush_slider_input = document.createElement("input"); + self.brush_slider_input.setAttribute("type", "range"); + self.brush_slider_input.setAttribute("min", "1"); + self.brush_slider_input.setAttribute("max", "100"); + self.brush_slider_input.setAttribute("value", "10"); + const labelElement = document.createElement("label"); + labelElement.textContent = name; + divElement.appendChild(labelElement); + divElement.appendChild(self.brush_slider_input); + self.brush_slider_input.addEventListener("change", callback); + return divElement; + } + createOpacitySlider(self, name, callback) { + const divElement = document.createElement("div"); + divElement.id = "maskeditor-opacity-slider"; + divElement.style.cssFloat = "left"; + divElement.style.fontFamily = "sans-serif"; + divElement.style.marginRight = "4px"; + divElement.style.color = "var(--input-text)"; + divElement.style.backgroundColor = "var(--comfy-input-bg)"; + divElement.style.borderRadius = "8px"; + divElement.style.borderColor = "var(--border-color)"; + divElement.style.borderStyle = "solid"; + divElement.style.fontSize = "15px"; + divElement.style.height = "21px"; + divElement.style.padding = "1px 6px"; + divElement.style.display = "flex"; + divElement.style.position = "relative"; + divElement.style.top = "2px"; + divElement.style.pointerEvents = "auto"; + self.opacity_slider_input = document.createElement("input"); + self.opacity_slider_input.setAttribute("type", "range"); + self.opacity_slider_input.setAttribute("min", "0.1"); + self.opacity_slider_input.setAttribute("max", "1.0"); + self.opacity_slider_input.setAttribute("step", "0.01"); + self.opacity_slider_input.setAttribute("value", "0.7"); + const labelElement = document.createElement("label"); + labelElement.textContent = name; + divElement.appendChild(labelElement); + divElement.appendChild(self.opacity_slider_input); + self.opacity_slider_input.addEventListener("input", callback); + return divElement; + } + setlayout(imgCanvas, maskCanvas) { + const self = this; + var bottom_panel = document.createElement("div"); + bottom_panel.style.position = "absolute"; + bottom_panel.style.bottom = "0px"; + bottom_panel.style.left = "20px"; + bottom_panel.style.right = "20px"; + bottom_panel.style.height = "50px"; + bottom_panel.style.pointerEvents = "none"; + var brush = document.createElement("div"); + brush.id = "brush"; + brush.style.backgroundColor = "transparent"; + brush.style.outline = "1px dashed black"; + brush.style.boxShadow = "0 0 0 1px white"; + brush.style.borderRadius = "50%"; + brush.style.MozBorderRadius = "50%"; + brush.style.WebkitBorderRadius = "50%"; + brush.style.position = "absolute"; + brush.style.zIndex = "8889"; + brush.style.pointerEvents = "none"; + this.brush = brush; + this.element.appendChild(imgCanvas); + this.element.appendChild(maskCanvas); + this.element.appendChild(bottom_panel); + document.body.appendChild(brush); + var clearButton = this.createLeftButton("Clear", () => { + self.maskCtx.clearRect( + 0, + 0, + self.maskCanvas.width, + self.maskCanvas.height + ); + }); + this.brush_size_slider = this.createLeftSlider( + self, + "Thickness", + (event) => { + self.brush_size = event.target.value; + self.updateBrushPreview(self); + } + ); + this.brush_opacity_slider = this.createOpacitySlider( + self, + "Opacity", + (event) => { + self.brush_opacity = event.target.value; + if (self.brush_color_mode !== "negative") { + self.maskCanvas.style.opacity = self.brush_opacity.toString(); + } + } + ); + this.colorButton = this.createLeftButton(this.getColorButtonText(), () => { + if (self.brush_color_mode === "black") { + self.brush_color_mode = "white"; + } else if (self.brush_color_mode === "white") { + self.brush_color_mode = "negative"; + } else { + self.brush_color_mode = "black"; + } + self.updateWhenBrushColorModeChanged(); + }); + var cancelButton = this.createRightButton("Cancel", () => { + document.removeEventListener("keydown", _MaskEditorDialog.handleKeyDown); + self.close(); + }); + this.saveButton = this.createRightButton("Save", () => { + document.removeEventListener("keydown", _MaskEditorDialog.handleKeyDown); + self.save(); + }); + this.element.appendChild(imgCanvas); + this.element.appendChild(maskCanvas); + this.element.appendChild(bottom_panel); + bottom_panel.appendChild(clearButton); + bottom_panel.appendChild(this.saveButton); + bottom_panel.appendChild(cancelButton); + bottom_panel.appendChild(this.brush_size_slider); + bottom_panel.appendChild(this.brush_opacity_slider); + bottom_panel.appendChild(this.colorButton); + imgCanvas.style.position = "absolute"; + maskCanvas.style.position = "absolute"; + imgCanvas.style.top = "200"; + imgCanvas.style.left = "0"; + maskCanvas.style.top = imgCanvas.style.top; + maskCanvas.style.left = imgCanvas.style.left; + const maskCanvasStyle = this.getMaskCanvasStyle(); + maskCanvas.style.mixBlendMode = maskCanvasStyle.mixBlendMode; + maskCanvas.style.opacity = maskCanvasStyle.opacity.toString(); + } + show() { + return __async(this, null, function* () { + this.zoom_ratio = 1; + this.pan_x = 0; + this.pan_y = 0; + if (!this.is_layout_created) { + const imgCanvas = document.createElement("canvas"); + const maskCanvas = document.createElement("canvas"); + imgCanvas.id = "imageCanvas"; + maskCanvas.id = "maskCanvas"; + this.setlayout(imgCanvas, maskCanvas); + this.imgCanvas = imgCanvas; + this.maskCanvas = maskCanvas; + this.maskCtx = maskCanvas.getContext("2d", { willReadFrequently: true }); + this.setEventHandler(maskCanvas); + this.is_layout_created = true; + const self = this; + const observer = new MutationObserver(function(mutations) { + mutations.forEach(function(mutation) { + if (mutation.type === "attributes" && mutation.attributeName === "style") { + if (self.last_display_style && self.last_display_style != "none" && self.element.style.display == "none") { + self.brush.style.display = "none"; + ComfyApp.onClipspaceEditorClosed(); + } + self.last_display_style = self.element.style.display; + } + }); + }); + const config = { attributes: true }; + observer.observe(this.element, config); + } + document.addEventListener("keydown", _MaskEditorDialog.handleKeyDown); + if (ComfyApp.clipspace_return_node) { + this.saveButton.innerText = "Save to node"; + } else { + this.saveButton.innerText = "Save"; + } + this.saveButton.disabled = false; + this.element.style.display = "block"; + this.element.style.width = "85%"; + this.element.style.margin = "0 7.5%"; + this.element.style.height = "100vh"; + this.element.style.top = "50%"; + this.element.style.left = "42%"; + this.element.style.zIndex = "8888"; + yield this.setImages(this.imgCanvas); + this.is_visible = true; + }); + } + isOpened() { + return this.element.style.display == "block"; + } + invalidateCanvas(orig_image, mask_image) { + this.imgCanvas.width = orig_image.width; + this.imgCanvas.height = orig_image.height; + this.maskCanvas.width = orig_image.width; + this.maskCanvas.height = orig_image.height; + let imgCtx = this.imgCanvas.getContext("2d", { willReadFrequently: true }); + let maskCtx = this.maskCanvas.getContext("2d", { + willReadFrequently: true + }); + imgCtx.drawImage(orig_image, 0, 0, orig_image.width, orig_image.height); + prepare_mask(mask_image, this.maskCanvas, maskCtx, this.getMaskColor()); + } + setImages(imgCanvas) { + return __async(this, null, function* () { + let self = this; + const imgCtx = imgCanvas.getContext("2d", { willReadFrequently: true }); + const maskCtx = this.maskCtx; + const maskCanvas = this.maskCanvas; + imgCtx.clearRect(0, 0, this.imgCanvas.width, this.imgCanvas.height); + maskCtx.clearRect(0, 0, this.maskCanvas.width, this.maskCanvas.height); + const filepath = ComfyApp.clipspace.images; + const alpha_url = new URL( + ComfyApp.clipspace.imgs[ComfyApp.clipspace["selectedIndex"]].src + ); + alpha_url.searchParams.delete("channel"); + alpha_url.searchParams.delete("preview"); + alpha_url.searchParams.set("channel", "a"); + let mask_image = yield loadImage(alpha_url); + const rgb_url = new URL( + ComfyApp.clipspace.imgs[ComfyApp.clipspace["selectedIndex"]].src + ); + rgb_url.searchParams.delete("channel"); + rgb_url.searchParams.set("channel", "rgb"); + this.image = new Image(); + this.image.onload = function() { + maskCanvas.width = self.image.width; + maskCanvas.height = self.image.height; + self.invalidateCanvas(self.image, mask_image); + self.initializeCanvasPanZoom(); + }; + this.image.src = rgb_url.toString(); + }); + } + initializeCanvasPanZoom() { + let drawWidth = this.image.width; + let drawHeight = this.image.height; + let width = this.element.clientWidth; + let height = this.element.clientHeight; + if (this.image.width > width) { + drawWidth = width; + drawHeight = drawWidth / this.image.width * this.image.height; + } + if (drawHeight > height) { + drawHeight = height; + drawWidth = drawHeight / this.image.height * this.image.width; + } + this.zoom_ratio = drawWidth / this.image.width; + const canvasX = (width - drawWidth) / 2; + const canvasY = (height - drawHeight) / 2; + this.pan_x = canvasX; + this.pan_y = canvasY; + this.invalidatePanZoom(); + } + invalidatePanZoom() { + let raw_width = this.image.width * this.zoom_ratio; + let raw_height = this.image.height * this.zoom_ratio; + if (this.pan_x + raw_width < 10) { + this.pan_x = 10 - raw_width; + } + if (this.pan_y + raw_height < 10) { + this.pan_y = 10 - raw_height; + } + let width = `${raw_width}px`; + let height = `${raw_height}px`; + let left = `${this.pan_x}px`; + let top = `${this.pan_y}px`; + this.maskCanvas.style.width = width; + this.maskCanvas.style.height = height; + this.maskCanvas.style.left = left; + this.maskCanvas.style.top = top; + this.imgCanvas.style.width = width; + this.imgCanvas.style.height = height; + this.imgCanvas.style.left = left; + this.imgCanvas.style.top = top; + } + setEventHandler(maskCanvas) { + const self = this; + if (!this.handler_registered) { + maskCanvas.addEventListener("contextmenu", (event) => { + event.preventDefault(); + }); + this.element.addEventListener( + "wheel", + (event) => this.handleWheelEvent(self, event) + ); + this.element.addEventListener( + "pointermove", + (event) => this.pointMoveEvent(self, event) + ); + this.element.addEventListener( + "touchmove", + (event) => this.pointMoveEvent(self, event) + ); + this.element.addEventListener("dragstart", (event) => { + if (event.ctrlKey) { + event.preventDefault(); + } + }); + maskCanvas.addEventListener( + "pointerdown", + (event) => this.handlePointerDown(self, event) + ); + maskCanvas.addEventListener( + "pointermove", + (event) => this.draw_move(self, event) + ); + maskCanvas.addEventListener( + "touchmove", + (event) => this.draw_move(self, event) + ); + maskCanvas.addEventListener("pointerover", (event) => { + this.brush.style.display = "block"; + }); + maskCanvas.addEventListener("pointerleave", (event) => { + this.brush.style.display = "none"; + }); + document.addEventListener("pointerup", _MaskEditorDialog.handlePointerUp); + this.handler_registered = true; + } + } + getMaskCanvasStyle() { + if (this.brush_color_mode === "negative") { + return { + mixBlendMode: "difference", + opacity: "1" + }; + } else { + return { + mixBlendMode: "initial", + opacity: this.brush_opacity + }; + } + } + getMaskColor() { + if (this.brush_color_mode === "black") { + return { r: 0, g: 0, b: 0 }; + } + if (this.brush_color_mode === "white") { + return { r: 255, g: 255, b: 255 }; + } + if (this.brush_color_mode === "negative") { + return { r: 255, g: 255, b: 255 }; + } + return { r: 0, g: 0, b: 0 }; + } + getMaskFillStyle() { + const maskColor = this.getMaskColor(); + return "rgb(" + maskColor.r + "," + maskColor.g + "," + maskColor.b + ")"; + } + getColorButtonText() { + let colorCaption = "unknown"; + if (this.brush_color_mode === "black") { + colorCaption = "black"; + } else if (this.brush_color_mode === "white") { + colorCaption = "white"; + } else if (this.brush_color_mode === "negative") { + colorCaption = "negative"; + } + return "Color: " + colorCaption; + } + updateWhenBrushColorModeChanged() { + this.colorButton.innerText = this.getColorButtonText(); + const maskCanvasStyle = this.getMaskCanvasStyle(); + this.maskCanvas.style.mixBlendMode = maskCanvasStyle.mixBlendMode; + this.maskCanvas.style.opacity = maskCanvasStyle.opacity.toString(); + const maskColor = this.getMaskColor(); + const maskData = this.maskCtx.getImageData( + 0, + 0, + this.maskCanvas.width, + this.maskCanvas.height + ); + for (let i = 0; i < maskData.data.length; i += 4) { + maskData.data[i] = maskColor.r; + maskData.data[i + 1] = maskColor.g; + maskData.data[i + 2] = maskColor.b; + } + this.maskCtx.putImageData(maskData, 0, 0); + } + static handleKeyDown(event) { + const self = _MaskEditorDialog.instance; + if (event.key === "]") { + self.brush_size = Math.min(self.brush_size + 2, 100); + self.brush_slider_input.value = self.brush_size; + } else if (event.key === "[") { + self.brush_size = Math.max(self.brush_size - 2, 1); + self.brush_slider_input.value = self.brush_size; + } else if (event.key === "Enter") { + self.save(); + } + self.updateBrushPreview(self); + } + static handlePointerUp(event) { + event.preventDefault(); + this.mousedown_x = null; + this.mousedown_y = null; + _MaskEditorDialog.instance.drawing_mode = false; + } + updateBrushPreview(self) { + const brush = self.brush; + var centerX = self.cursorX; + var centerY = self.cursorY; + brush.style.width = self.brush_size * 2 * this.zoom_ratio + "px"; + brush.style.height = self.brush_size * 2 * this.zoom_ratio + "px"; + brush.style.left = centerX - self.brush_size * this.zoom_ratio + "px"; + brush.style.top = centerY - self.brush_size * this.zoom_ratio + "px"; + } + handleWheelEvent(self, event) { + event.preventDefault(); + if (event.ctrlKey) { + if (event.deltaY < 0) { + this.zoom_ratio = Math.min(10, this.zoom_ratio + 0.2); + } else { + this.zoom_ratio = Math.max(0.2, this.zoom_ratio - 0.2); + } + this.invalidatePanZoom(); + } else { + if (event.deltaY < 0) this.brush_size = Math.min(this.brush_size + 2, 100); + else this.brush_size = Math.max(this.brush_size - 2, 1); + this.brush_slider_input.value = this.brush_size.toString(); + this.updateBrushPreview(this); + } + } + pointMoveEvent(self, event) { + this.cursorX = event.pageX; + this.cursorY = event.pageY; + self.updateBrushPreview(self); + if (event.ctrlKey) { + event.preventDefault(); + self.pan_move(self, event); + } + let left_button_down = window.TouchEvent && event instanceof TouchEvent || event.buttons == 1; + if (event.shiftKey && left_button_down) { + self.drawing_mode = false; + const y = event.clientY; + let delta = (self.zoom_lasty - y) * 5e-3; + self.zoom_ratio = Math.max( + Math.min(10, self.last_zoom_ratio - delta), + 0.2 + ); + this.invalidatePanZoom(); + return; + } + } + pan_move(self, event) { + if (event.buttons == 1) { + if (_MaskEditorDialog.mousedown_x) { + let deltaX = _MaskEditorDialog.mousedown_x - event.clientX; + let deltaY = _MaskEditorDialog.mousedown_y - event.clientY; + self.pan_x = this.mousedown_pan_x - deltaX; + self.pan_y = this.mousedown_pan_y - deltaY; + self.invalidatePanZoom(); + } + } + } + draw_move(self, event) { + if (event.ctrlKey || event.shiftKey) { + return; + } + event.preventDefault(); + this.cursorX = event.pageX; + this.cursorY = event.pageY; + self.updateBrushPreview(self); + let left_button_down = window.TouchEvent && event instanceof TouchEvent || event.buttons == 1; + let right_button_down = [2, 5, 32].includes(event.buttons); + if (!event.altKey && left_button_down) { + var diff = performance.now() - self.lasttime; + const maskRect = self.maskCanvas.getBoundingClientRect(); + var x = event.offsetX; + var y = event.offsetY; + if (event.offsetX == null) { + x = event.targetTouches[0].clientX - maskRect.left; + } + if (event.offsetY == null) { + y = event.targetTouches[0].clientY - maskRect.top; + } + x /= self.zoom_ratio; + y /= self.zoom_ratio; + var brush_size = this.brush_size; + if (event instanceof PointerEvent && event.pointerType == "pen") { + brush_size *= event.pressure; + this.last_pressure = event.pressure; + } else if (window.TouchEvent && event instanceof TouchEvent && diff < 20) { + brush_size *= this.last_pressure; + } else { + brush_size = this.brush_size; + } + if (diff > 20 && !this.drawing_mode) + requestAnimationFrame(() => { + self.maskCtx.beginPath(); + self.maskCtx.fillStyle = this.getMaskFillStyle(); + self.maskCtx.globalCompositeOperation = "source-over"; + self.maskCtx.arc(x, y, brush_size, 0, Math.PI * 2, false); + self.maskCtx.fill(); + self.lastx = x; + self.lasty = y; + }); + else + requestAnimationFrame(() => { + self.maskCtx.beginPath(); + self.maskCtx.fillStyle = this.getMaskFillStyle(); + self.maskCtx.globalCompositeOperation = "source-over"; + var dx = x - self.lastx; + var dy = y - self.lasty; + var distance = Math.sqrt(dx * dx + dy * dy); + var directionX = dx / distance; + var directionY = dy / distance; + for (var i = 0; i < distance; i += 5) { + var px = self.lastx + directionX * i; + var py = self.lasty + directionY * i; + self.maskCtx.arc(px, py, brush_size, 0, Math.PI * 2, false); + self.maskCtx.fill(); + } + self.lastx = x; + self.lasty = y; + }); + self.lasttime = performance.now(); + } else if (event.altKey && left_button_down || right_button_down) { + const maskRect = self.maskCanvas.getBoundingClientRect(); + const x2 = (event.offsetX || event.targetTouches[0].clientX - maskRect.left) / self.zoom_ratio; + const y2 = (event.offsetY || event.targetTouches[0].clientY - maskRect.top) / self.zoom_ratio; + var brush_size = this.brush_size; + if (event instanceof PointerEvent && event.pointerType == "pen") { + brush_size *= event.pressure; + this.last_pressure = event.pressure; + } else if (window.TouchEvent && event instanceof TouchEvent && diff < 20) { + brush_size *= this.last_pressure; + } else { + brush_size = this.brush_size; + } + if (diff > 20 && !this.drawing_mode) + requestAnimationFrame(() => { + self.maskCtx.beginPath(); + self.maskCtx.globalCompositeOperation = "destination-out"; + self.maskCtx.arc(x2, y2, brush_size, 0, Math.PI * 2, false); + self.maskCtx.fill(); + self.lastx = x2; + self.lasty = y2; + }); + else + requestAnimationFrame(() => { + self.maskCtx.beginPath(); + self.maskCtx.globalCompositeOperation = "destination-out"; + var dx = x2 - self.lastx; + var dy = y2 - self.lasty; + var distance = Math.sqrt(dx * dx + dy * dy); + var directionX = dx / distance; + var directionY = dy / distance; + for (var i = 0; i < distance; i += 5) { + var px = self.lastx + directionX * i; + var py = self.lasty + directionY * i; + self.maskCtx.arc(px, py, brush_size, 0, Math.PI * 2, false); + self.maskCtx.fill(); + } + self.lastx = x2; + self.lasty = y2; + }); + self.lasttime = performance.now(); + } + } + handlePointerDown(self, event) { + if (event.ctrlKey) { + if (event.buttons == 1) { + _MaskEditorDialog.mousedown_x = event.clientX; + _MaskEditorDialog.mousedown_y = event.clientY; + this.mousedown_pan_x = this.pan_x; + this.mousedown_pan_y = this.pan_y; + } + return; + } + var brush_size = this.brush_size; + if (event instanceof PointerEvent && event.pointerType == "pen") { + brush_size *= event.pressure; + this.last_pressure = event.pressure; + } + if ([0, 2, 5].includes(event.button)) { + self.drawing_mode = true; + event.preventDefault(); + if (event.shiftKey) { + self.zoom_lasty = event.clientY; + self.last_zoom_ratio = self.zoom_ratio; + return; + } + const maskRect = self.maskCanvas.getBoundingClientRect(); + const x = (event.offsetX || event.targetTouches[0].clientX - maskRect.left) / self.zoom_ratio; + const y = (event.offsetY || event.targetTouches[0].clientY - maskRect.top) / self.zoom_ratio; + self.maskCtx.beginPath(); + if (!event.altKey && event.button == 0) { + self.maskCtx.fillStyle = this.getMaskFillStyle(); + self.maskCtx.globalCompositeOperation = "source-over"; + } else { + self.maskCtx.globalCompositeOperation = "destination-out"; + } + self.maskCtx.arc(x, y, brush_size, 0, Math.PI * 2, false); + self.maskCtx.fill(); + self.lastx = x; + self.lasty = y; + self.lasttime = performance.now(); + } + } + save() { + return __async(this, null, function* () { + const backupCanvas = document.createElement("canvas"); + const backupCtx = backupCanvas.getContext("2d", { + willReadFrequently: true + }); + backupCanvas.width = this.image.width; + backupCanvas.height = this.image.height; + backupCtx.clearRect(0, 0, backupCanvas.width, backupCanvas.height); + backupCtx.drawImage( + this.maskCanvas, + 0, + 0, + this.maskCanvas.width, + this.maskCanvas.height, + 0, + 0, + backupCanvas.width, + backupCanvas.height + ); + const backupData = backupCtx.getImageData( + 0, + 0, + backupCanvas.width, + backupCanvas.height + ); + for (let i = 0; i < backupData.data.length; i += 4) { + if (backupData.data[i + 3] == 255) backupData.data[i + 3] = 0; + else backupData.data[i + 3] = 255; + backupData.data[i] = 0; + backupData.data[i + 1] = 0; + backupData.data[i + 2] = 0; + } + backupCtx.globalCompositeOperation = "source-over"; + backupCtx.putImageData(backupData, 0, 0); + const formData = new FormData(); + const filename = "clipspace-mask-" + performance.now() + ".png"; + const item = { + filename, + subfolder: "clipspace", + type: "input" + }; + if (ComfyApp.clipspace.images) ComfyApp.clipspace.images[0] = item; + if (ComfyApp.clipspace.widgets) { + const index = ComfyApp.clipspace.widgets.findIndex( + (obj) => obj.name === "image" + ); + if (index >= 0) ComfyApp.clipspace.widgets[index].value = item; + } + const dataURL = backupCanvas.toDataURL(); + const blob = dataURLToBlob(dataURL); + let original_url = new URL(this.image.src); + const original_ref = { + filename: original_url.searchParams.get("filename") + }; + let original_subfolder = original_url.searchParams.get("subfolder"); + if (original_subfolder) original_ref.subfolder = original_subfolder; + let original_type = original_url.searchParams.get("type"); + if (original_type) original_ref.type = original_type; + formData.append("image", blob, filename); + formData.append("original_ref", JSON.stringify(original_ref)); + formData.append("type", "input"); + formData.append("subfolder", "clipspace"); + this.saveButton.innerText = "Saving..."; + this.saveButton.disabled = true; + yield uploadMask(item, formData); + ComfyApp.onClipspaceEditorSave(); + this.close(); + }); + } +}; +__publicField(_MaskEditorDialog, "instance", null); +__publicField(_MaskEditorDialog, "mousedown_x", null); +__publicField(_MaskEditorDialog, "mousedown_y", null); +let MaskEditorDialog = _MaskEditorDialog; +app.registerExtension({ + name: "Comfy.MaskEditor", + init(app2) { + ComfyApp.open_maskeditor = function() { + const dlg = MaskEditorDialog.getInstance(); + if (!dlg.isOpened()) { + dlg.show(); + } + }; + const context_predicate = () => ComfyApp.clipspace && ComfyApp.clipspace.imgs && ComfyApp.clipspace.imgs.length > 0; + ClipspaceDialog.registerButton( + "MaskEditor", + context_predicate, + ComfyApp.open_maskeditor + ); + } +}); +const id = "Comfy.NodeTemplates"; +const file = "comfy.templates.json"; +class ManageTemplates extends ComfyDialog { + constructor() { + super(); + __publicField(this, "templates"); + __publicField(this, "draggedEl"); + __publicField(this, "saveVisualCue"); + __publicField(this, "emptyImg"); + __publicField(this, "importInput"); + this.load().then((v) => { + this.templates = v; + }); + this.element.classList.add("comfy-manage-templates"); + this.draggedEl = null; + this.saveVisualCue = null; + this.emptyImg = new Image(); + this.emptyImg.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs="; + this.importInput = $el("input", { + type: "file", + accept: ".json", + multiple: true, + style: { display: "none" }, + parent: document.body, + onchange: () => this.importAll() + }); + } + createButtons() { + const btns = super.createButtons(); + btns[0].textContent = "Close"; + btns[0].onclick = (e) => { + clearTimeout(this.saveVisualCue); + this.close(); + }; + btns.unshift( + $el("button", { + type: "button", + textContent: "Export", + onclick: () => this.exportAll() + }) + ); + btns.unshift( + $el("button", { + type: "button", + textContent: "Import", + onclick: () => { + this.importInput.click(); + } + }) + ); + return btns; + } + load() { + return __async(this, null, function* () { + let templates = []; + if (app.storageLocation === "server") { + if (app.isNewUserSession) { + const json = localStorage.getItem(id); + if (json) { + templates = JSON.parse(json); + } + yield api.storeUserData(file, json, { stringify: false }); + } else { + const res = yield api.getUserData(file); + if (res.status === 200) { + try { + templates = yield res.json(); + } catch (error) { + } + } else if (res.status !== 404) { + console.error(res.status + " " + res.statusText); + } + } + } else { + const json = localStorage.getItem(id); + if (json) { + templates = JSON.parse(json); + } + } + return templates != null ? templates : []; + }); + } + store() { + return __async(this, null, function* () { + if (app.storageLocation === "server") { + const templates = JSON.stringify(this.templates, void 0, 4); + localStorage.setItem(id, templates); + try { + yield api.storeUserData(file, templates, { stringify: false }); + } catch (error) { + console.error(error); + alert(error.message); + } + } else { + localStorage.setItem(id, JSON.stringify(this.templates)); + } + }); + } + importAll() { + return __async(this, null, function* () { + for (const file2 of this.importInput.files) { + if (file2.type === "application/json" || file2.name.endsWith(".json")) { + const reader = new FileReader(); + reader.onload = () => __async(this, null, function* () { + const importFile = JSON.parse(reader.result); + if (importFile == null ? void 0 : importFile.templates) { + for (const template of importFile.templates) { + if ((template == null ? void 0 : template.name) && (template == null ? void 0 : template.data)) { + this.templates.push(template); + } + } + yield this.store(); + } + }); + yield reader.readAsText(file2); + } + } + this.importInput.value = null; + this.close(); + }); + } + exportAll() { + if (this.templates.length == 0) { + alert("No templates to export."); + return; + } + const json = JSON.stringify({ templates: this.templates }, null, 2); + const blob = new Blob([json], { type: "application/json" }); + const url = URL.createObjectURL(blob); + const a = $el("a", { + href: url, + download: "node_templates.json", + style: { display: "none" }, + parent: document.body + }); + a.click(); + setTimeout(function() { + a.remove(); + window.URL.revokeObjectURL(url); + }, 0); + } + show() { + super.show( + $el( + "div", + {}, + this.templates.flatMap((t, i) => { + let nameInput; + return [ + $el( + "div", + { + dataset: { id: i.toString() }, + className: "templateManagerRow", + style: { + display: "grid", + gridTemplateColumns: "1fr auto", + border: "1px dashed transparent", + gap: "5px", + backgroundColor: "var(--comfy-menu-bg)" + }, + ondragstart: (e) => { + this.draggedEl = e.currentTarget; + e.currentTarget.style.opacity = "0.6"; + e.currentTarget.style.border = "1px dashed yellow"; + e.dataTransfer.effectAllowed = "move"; + e.dataTransfer.setDragImage(this.emptyImg, 0, 0); + }, + ondragend: (e) => { + e.target.style.opacity = "1"; + e.currentTarget.style.border = "1px dashed transparent"; + e.currentTarget.removeAttribute("draggable"); + this.element.querySelectorAll(".templateManagerRow").forEach((el, i2) => { + var prev_i = Number.parseInt(el.dataset.id); + if (el == this.draggedEl && prev_i != i2) { + this.templates.splice( + i2, + 0, + this.templates.splice(prev_i, 1)[0] + ); + } + el.dataset.id = i2.toString(); + }); + this.store(); + }, + ondragover: (e) => { + e.preventDefault(); + if (e.currentTarget == this.draggedEl) return; + let rect = e.currentTarget.getBoundingClientRect(); + if (e.clientY > rect.top + rect.height / 2) { + e.currentTarget.parentNode.insertBefore( + this.draggedEl, + e.currentTarget.nextSibling + ); + } else { + e.currentTarget.parentNode.insertBefore( + this.draggedEl, + e.currentTarget + ); + } + } + }, + [ + $el( + "label", + { + textContent: "Name: ", + style: { + cursor: "grab" + }, + onmousedown: (e) => { + if (e.target.localName == "label") + e.currentTarget.parentNode.draggable = "true"; + } + }, + [ + $el("input", { + value: t.name, + dataset: { name: t.name }, + style: { + transitionProperty: "background-color", + transitionDuration: "0s" + }, + onchange: (e) => { + clearTimeout(this.saveVisualCue); + var el = e.target; + var row = el.parentNode.parentNode; + this.templates[row.dataset.id].name = el.value.trim() || "untitled"; + this.store(); + el.style.backgroundColor = "rgb(40, 95, 40)"; + el.style.transitionDuration = "0s"; + this.saveVisualCue = setTimeout(function() { + el.style.transitionDuration = ".7s"; + el.style.backgroundColor = "var(--comfy-input-bg)"; + }, 15); + }, + onkeypress: (e) => { + var el = e.target; + clearTimeout(this.saveVisualCue); + el.style.transitionDuration = "0s"; + el.style.backgroundColor = "var(--comfy-input-bg)"; + }, + $: (el) => nameInput = el + }) + ] + ), + $el("div", {}, [ + $el("button", { + textContent: "Export", + style: { + fontSize: "12px", + fontWeight: "normal" + }, + onclick: (e) => { + const json = JSON.stringify({ templates: [t] }, null, 2); + const blob = new Blob([json], { + type: "application/json" + }); + const url = URL.createObjectURL(blob); + const a = $el("a", { + href: url, + download: (nameInput.value || t.name) + ".json", + style: { display: "none" }, + parent: document.body + }); + a.click(); + setTimeout(function() { + a.remove(); + window.URL.revokeObjectURL(url); + }, 0); + } + }), + $el("button", { + textContent: "Delete", + style: { + fontSize: "12px", + color: "red", + fontWeight: "normal" + }, + onclick: (e) => { + const item = e.target.parentNode.parentNode; + item.parentNode.removeChild(item); + this.templates.splice(item.dataset.id * 1, 1); + this.store(); + var that = this; + setTimeout(function() { + that.element.querySelectorAll(".templateManagerRow").forEach((el, i2) => { + el.dataset.id = i2.toString(); + }); + }, 0); + } + }) + ]) + ] + ) + ]; + }) + ) + ); + } +} +app.registerExtension({ + name: id, + setup() { + const manage = new ManageTemplates(); + const clipboardAction = (cb) => __async(this, null, function* () { + const old = localStorage.getItem("litegrapheditor_clipboard"); + yield cb(); + localStorage.setItem("litegrapheditor_clipboard", old); + }); + const orig = LGraphCanvas.prototype.getCanvasMenuOptions; + LGraphCanvas.prototype.getCanvasMenuOptions = function() { + const options = orig.apply(this, arguments); + options.push(null); + options.push({ + content: `Save Selected as Template`, + disabled: !Object.keys(app.canvas.selected_nodes || {}).length, + callback: () => { + const name = prompt("Enter name"); + if (!(name == null ? void 0 : name.trim())) return; + clipboardAction(() => { + app.canvas.copyToClipboard(); + let data = localStorage.getItem("litegrapheditor_clipboard"); + data = JSON.parse(data); + const nodeIds = Object.keys(app.canvas.selected_nodes); + for (let i = 0; i < nodeIds.length; i++) { + const node = app.graph.getNodeById(Number.parseInt(nodeIds[i])); + const nodeData = node == null ? void 0 : node.constructor.nodeData; + let groupData = GroupNodeHandler.getGroupData(node); + if (groupData) { + groupData = groupData.nodeData; + if (!data.groupNodes) { + data.groupNodes = {}; + } + data.groupNodes[nodeData.name] = groupData; + data.nodes[i].type = nodeData.name; + } + } + manage.templates.push({ + name, + data: JSON.stringify(data) + }); + manage.store(); + }); + } + }); + const subItems = manage.templates.map((t) => { + return { + content: t.name, + callback: () => { + clipboardAction(() => __async(this, null, function* () { + const data = JSON.parse(t.data); + yield GroupNodeConfig.registerFromWorkflow(data.groupNodes, {}); + localStorage.setItem("litegrapheditor_clipboard", t.data); + app.canvas.pasteFromClipboard(); + })); + } + }; + }); + subItems.push(null, { + content: "Manage", + callback: () => manage.show() + }); + options.push({ + content: "Node Templates", + submenu: { + options: subItems + } + }); + return options; + }; + } +}); +app.registerExtension({ + name: "Comfy.NoteNode", + registerCustomNodes() { + class NoteNode { + constructor() { + __publicField(this, "color", LGraphCanvas.node_colors.yellow.color); + __publicField(this, "bgcolor", LGraphCanvas.node_colors.yellow.bgcolor); + __publicField(this, "groupcolor", LGraphCanvas.node_colors.yellow.groupcolor); + __publicField(this, "properties"); + __publicField(this, "serialize_widgets"); + __publicField(this, "isVirtualNode"); + __publicField(this, "collapsable"); + __publicField(this, "title_mode"); + if (!this.properties) { + this.properties = { text: "" }; + } + ComfyWidgets.STRING( + // @ts-expect-error + // Should we extends LGraphNode? + this, + "", + ["", { default: this.properties.text, multiline: true }], + app + ); + this.serialize_widgets = true; + this.isVirtualNode = true; + } + } + __publicField(NoteNode, "category"); + LiteGraph.registerNodeType( + "Note", + // @ts-expect-error + Object.assign(NoteNode, { + title_mode: LiteGraph.NORMAL_TITLE, + title: "Note", + collapsable: true + }) + ); + NoteNode.category = "utils"; + } +}); +app.registerExtension({ + name: "Comfy.RerouteNode", + registerCustomNodes(app2) { + const _RerouteNode = class _RerouteNode { + constructor() { + if (!this.properties) { + this.properties = {}; + } + this.properties.showOutputText = _RerouteNode.defaultVisibility; + this.properties.horizontal = false; + this.addInput("", "*"); + this.addOutput(this.properties.showOutputText ? "*" : "", "*"); + this.onAfterGraphConfigured = function() { + requestAnimationFrame(() => { + this.onConnectionsChange(LiteGraph.INPUT, null, true, null); + }); + }; + this.onConnectionsChange = function(type, index, connected, link_info) { + var _a, _b, _c, _d, _e; + this.applyOrientation(); + if (connected && type === LiteGraph.OUTPUT) { + const types = new Set( + this.outputs[0].links.map((l) => app2.graph.links[l].type).filter((t) => t !== "*") + ); + if (types.size > 1) { + const linksToDisconnect = []; + for (let i = 0; i < this.outputs[0].links.length - 1; i++) { + const linkId = this.outputs[0].links[i]; + const link = app2.graph.links[linkId]; + linksToDisconnect.push(link); + } + for (const link of linksToDisconnect) { + const node = app2.graph.getNodeById(link.target_id); + node.disconnectInput(link.target_slot); + } + } + } + let currentNode = this; + let updateNodes = []; + let inputType = null; + let inputNode = null; + while (currentNode) { + updateNodes.unshift(currentNode); + const linkId = currentNode.inputs[0].link; + if (linkId !== null) { + const link = app2.graph.links[linkId]; + if (!link) return; + const node = app2.graph.getNodeById(link.origin_id); + const type2 = node.constructor.type; + if (type2 === "Reroute") { + if (node === this) { + currentNode.disconnectInput(link.target_slot); + currentNode = null; + } else { + currentNode = node; + } + } else { + inputNode = currentNode; + inputType = (_b = (_a = node.outputs[link.origin_slot]) == null ? void 0 : _a.type) != null ? _b : null; + break; + } + } else { + currentNode = null; + break; + } + } + const nodes = [this]; + let outputType = null; + while (nodes.length) { + currentNode = nodes.pop(); + const outputs = (currentNode.outputs ? currentNode.outputs[0].links : []) || []; + if (outputs.length) { + for (const linkId of outputs) { + const link = app2.graph.links[linkId]; + if (!link) continue; + const node = app2.graph.getNodeById(link.target_id); + const type2 = node.constructor.type; + if (type2 === "Reroute") { + nodes.push(node); + updateNodes.push(node); + } else { + const nodeOutType = node.inputs && node.inputs[link == null ? void 0 : link.target_slot] && node.inputs[link.target_slot].type ? node.inputs[link.target_slot].type : null; + if (inputType && inputType !== "*" && nodeOutType !== inputType) { + node.disconnectInput(link.target_slot); + } else { + outputType = nodeOutType; + } + } + } + } else { + } + } + const displayType = inputType || outputType || "*"; + const color = LGraphCanvas.link_type_colors[displayType]; + let widgetConfig; + let targetWidget; + let widgetType; + for (const node of updateNodes) { + node.outputs[0].type = inputType || "*"; + node.__outputType = displayType; + node.outputs[0].name = node.properties.showOutputText ? displayType : ""; + node.size = node.computeSize(); + node.applyOrientation(); + for (const l of node.outputs[0].links || []) { + const link = app2.graph.links[l]; + if (link) { + link.color = color; + if (app2.configuringGraph) continue; + const targetNode = app2.graph.getNodeById(link.target_id); + const targetInput = (_c = targetNode.inputs) == null ? void 0 : _c[link.target_slot]; + if (targetInput == null ? void 0 : targetInput.widget) { + const config = getWidgetConfig(targetInput); + if (!widgetConfig) { + widgetConfig = (_d = config[1]) != null ? _d : {}; + widgetType = config[0]; + } + if (!targetWidget) { + targetWidget = (_e = targetNode.widgets) == null ? void 0 : _e.find( + (w) => w.name === targetInput.widget.name + ); + } + const merged = mergeIfValid(targetInput, [ + config[0], + widgetConfig + ]); + if (merged.customConfig) { + widgetConfig = merged.customConfig; + } + } + } + } + } + for (const node of updateNodes) { + if (widgetConfig && outputType) { + node.inputs[0].widget = { name: "value" }; + setWidgetConfig( + node.inputs[0], + [widgetType != null ? widgetType : displayType, widgetConfig], + targetWidget + ); + } else { + setWidgetConfig(node.inputs[0], null); + } + } + if (inputNode) { + const link = app2.graph.links[inputNode.inputs[0].link]; + if (link) { + link.color = color; + } + } + }; + this.clone = function() { + const cloned = _RerouteNode.prototype.clone.apply(this); + cloned.removeOutput(0); + cloned.addOutput(this.properties.showOutputText ? "*" : "", "*"); + cloned.size = cloned.computeSize(); + return cloned; + }; + this.isVirtualNode = true; + } + getExtraMenuOptions(_, options) { + options.unshift( + { + content: (this.properties.showOutputText ? "Hide" : "Show") + " Type", + callback: () => { + this.properties.showOutputText = !this.properties.showOutputText; + if (this.properties.showOutputText) { + this.outputs[0].name = this.__outputType || this.outputs[0].type; + } else { + this.outputs[0].name = ""; + } + this.size = this.computeSize(); + this.applyOrientation(); + app2.graph.setDirtyCanvas(true, true); + } + }, + { + content: (_RerouteNode.defaultVisibility ? "Hide" : "Show") + " Type By Default", + callback: () => { + _RerouteNode.setDefaultTextVisibility( + !_RerouteNode.defaultVisibility + ); + } + }, + { + // naming is inverted with respect to LiteGraphNode.horizontal + // LiteGraphNode.horizontal == true means that + // each slot in the inputs and outputs are laid out horizontally, + // which is the opposite of the visual orientation of the inputs and outputs as a node + content: "Set " + (this.properties.horizontal ? "Horizontal" : "Vertical"), + callback: () => { + this.properties.horizontal = !this.properties.horizontal; + this.applyOrientation(); + } + } + ); + } + applyOrientation() { + this.horizontal = this.properties.horizontal; + if (this.horizontal) { + this.inputs[0].pos = [this.size[0] / 2, 0]; + } else { + delete this.inputs[0].pos; + } + app2.graph.setDirtyCanvas(true, true); + } + computeSize() { + return [ + this.properties.showOutputText && this.outputs && this.outputs.length ? Math.max( + 75, + LiteGraph.NODE_TEXT_SIZE * this.outputs[0].name.length * 0.6 + 40 + ) : 75, + 26 + ]; + } + static setDefaultTextVisibility(visible) { + _RerouteNode.defaultVisibility = visible; + if (visible) { + localStorage["Comfy.RerouteNode.DefaultVisibility"] = "true"; + } else { + delete localStorage["Comfy.RerouteNode.DefaultVisibility"]; + } + } + }; + __publicField(_RerouteNode, "category"); + __publicField(_RerouteNode, "defaultVisibility", false); + let RerouteNode = _RerouteNode; + RerouteNode.setDefaultTextVisibility( + !!localStorage["Comfy.RerouteNode.DefaultVisibility"] + ); + LiteGraph.registerNodeType( + "Reroute", + Object.assign(RerouteNode, { + title_mode: LiteGraph.NO_TITLE, + title: "Reroute", + collapsable: false + }) + ); + RerouteNode.category = "utils"; + } +}); +app.registerExtension({ + name: "Comfy.SaveImageExtraOutput", + beforeRegisterNodeDef(nodeType, nodeData, app2) { + return __async(this, null, function* () { + if (nodeData.name === "SaveImage" || nodeData.name === "SaveAnimatedWEBP") { + const onNodeCreated = nodeType.prototype.onNodeCreated; + nodeType.prototype.onNodeCreated = function() { + const r = onNodeCreated ? onNodeCreated.apply(this, arguments) : void 0; + const widget = this.widgets.find((w) => w.name === "filename_prefix"); + widget.serializeValue = () => { + return applyTextReplacements(app2, widget.value); + }; + return r; + }; + } else { + const onNodeCreated = nodeType.prototype.onNodeCreated; + nodeType.prototype.onNodeCreated = function() { + const r = onNodeCreated ? onNodeCreated.apply(this, arguments) : void 0; + if (!this.properties || !("Node name for S&R" in this.properties)) { + this.addProperty("Node name for S&R", this.constructor.type, "string"); + } + return r; + }; + } + }); + } +}); +let touchZooming; +let touchCount = 0; +app.registerExtension({ + name: "Comfy.SimpleTouchSupport", + setup() { + let zoomPos; + let touchTime; + let lastTouch; + function getMultiTouchPos(e) { + return Math.hypot( + e.touches[0].clientX - e.touches[1].clientX, + e.touches[0].clientY - e.touches[1].clientY + ); + } + app.canvasEl.addEventListener( + "touchstart", + (e) => { + var _a, _b; + touchCount++; + lastTouch = null; + if (((_a = e.touches) == null ? void 0 : _a.length) === 1) { + touchTime = /* @__PURE__ */ new Date(); + lastTouch = e.touches[0]; + } else { + touchTime = null; + if (((_b = e.touches) == null ? void 0 : _b.length) === 2) { + zoomPos = getMultiTouchPos(e); + app.canvas.pointer_is_down = false; + } + } + }, + true + ); + app.canvasEl.addEventListener("touchend", (e) => { + var _a, _b, _c; + touchZooming = false; + touchCount = (_b = (_a = e.touches) == null ? void 0 : _a.length) != null ? _b : touchCount - 1; + if (touchTime && !((_c = e.touches) == null ? void 0 : _c.length)) { + if ((/* @__PURE__ */ new Date()).getTime() - touchTime > 600) { + try { + e.constructor = CustomEvent; + } catch (error) { + } + e.clientX = lastTouch.clientX; + e.clientY = lastTouch.clientY; + app.canvas.pointer_is_down = true; + app.canvas._mousedown_callback(e); + } + touchTime = null; + } + }); + app.canvasEl.addEventListener( + "touchmove", + (e) => { + var _a, _b; + touchTime = null; + if (((_a = e.touches) == null ? void 0 : _a.length) === 2) { + app.canvas.pointer_is_down = false; + touchZooming = true; + LiteGraph.closeAllContextMenus(); + (_b = app.canvas.search_box) == null ? void 0 : _b.close(); + const newZoomPos = getMultiTouchPos(e); + const midX = (e.touches[0].clientX + e.touches[1].clientX) / 2; + const midY = (e.touches[0].clientY + e.touches[1].clientY) / 2; + let scale = app.canvas.ds.scale; + const diff = zoomPos - newZoomPos; + if (diff > 0.5) { + scale *= 1 / 1.07; + } else if (diff < -0.5) { + scale *= 1.07; + } + app.canvas.ds.changeScale(scale, [midX, midY]); + app.canvas.setDirty(true, true); + zoomPos = newZoomPos; + } + }, + true + ); + } +}); +const processMouseDown = LGraphCanvas.prototype.processMouseDown; +LGraphCanvas.prototype.processMouseDown = function(e) { + if (touchZooming || touchCount) { + return; + } + return processMouseDown.apply(this, arguments); +}; +const processMouseMove = LGraphCanvas.prototype.processMouseMove; +LGraphCanvas.prototype.processMouseMove = function(e) { + if (touchZooming || touchCount > 1) { + return; + } + return processMouseMove.apply(this, arguments); +}; +app.registerExtension({ + name: "Comfy.SlotDefaults", + suggestionsNumber: null, + init() { + LiteGraph.search_filter_enabled = true; + LiteGraph.middle_click_slot_add_default_node = true; + this.suggestionsNumber = app.ui.settings.addSetting({ + id: "Comfy.NodeSuggestions.number", + name: "Number of nodes suggestions", + type: "slider", + attrs: { + min: 1, + max: 100, + step: 1 + }, + defaultValue: 5, + onChange: (newVal, oldVal) => { + this.setDefaults(newVal); + } + }); + }, + slot_types_default_out: {}, + slot_types_default_in: {}, + beforeRegisterNodeDef(nodeType, nodeData, app2) { + return __async(this, null, function* () { + var nodeId = nodeData.name; + var inputs = []; + inputs = nodeData["input"]["required"]; + for (const inputKey in inputs) { + var input = inputs[inputKey]; + if (typeof input[0] !== "string") continue; + var type = input[0]; + if (type in ComfyWidgets) { + var customProperties = input[1]; + if (!(customProperties == null ? void 0 : customProperties.forceInput)) continue; + } + if (!(type in this.slot_types_default_out)) { + this.slot_types_default_out[type] = ["Reroute"]; + } + if (this.slot_types_default_out[type].includes(nodeId)) continue; + this.slot_types_default_out[type].push(nodeId); + const lowerType = type.toLocaleLowerCase(); + if (!(lowerType in LiteGraph.registered_slot_in_types)) { + LiteGraph.registered_slot_in_types[lowerType] = { nodes: [] }; + } + LiteGraph.registered_slot_in_types[lowerType].nodes.push( + nodeType.comfyClass + ); + } + var outputs = nodeData["output"]; + for (const key in outputs) { + var type = outputs[key]; + if (!(type in this.slot_types_default_in)) { + this.slot_types_default_in[type] = ["Reroute"]; + } + this.slot_types_default_in[type].push(nodeId); + if (!(type in LiteGraph.registered_slot_out_types)) { + LiteGraph.registered_slot_out_types[type] = { nodes: [] }; + } + LiteGraph.registered_slot_out_types[type].nodes.push(nodeType.comfyClass); + if (!LiteGraph.slot_types_out.includes(type)) { + LiteGraph.slot_types_out.push(type); + } + } + var maxNum = this.suggestionsNumber.value; + this.setDefaults(maxNum); + }); + }, + setDefaults(maxNum) { + LiteGraph.slot_types_default_out = {}; + LiteGraph.slot_types_default_in = {}; + for (const type in this.slot_types_default_out) { + LiteGraph.slot_types_default_out[type] = this.slot_types_default_out[type].slice(0, maxNum); + } + for (const type in this.slot_types_default_in) { + LiteGraph.slot_types_default_in[type] = this.slot_types_default_in[type].slice(0, maxNum); + } + } +}); +function roundVectorToGrid(vec) { + vec[0] = LiteGraph.CANVAS_GRID_SIZE * Math.round(vec[0] / LiteGraph.CANVAS_GRID_SIZE); + vec[1] = LiteGraph.CANVAS_GRID_SIZE * Math.round(vec[1] / LiteGraph.CANVAS_GRID_SIZE); + return vec; +} +app.registerExtension({ + name: "Comfy.SnapToGrid", + init() { + app.ui.settings.addSetting({ + id: "Comfy.SnapToGrid.GridSize", + name: "Grid Size", + type: "slider", + attrs: { + min: 1, + max: 500 + }, + tooltip: "When dragging and resizing nodes while holding shift they will be aligned to the grid, this controls the size of that grid.", + defaultValue: LiteGraph.CANVAS_GRID_SIZE, + onChange(value) { + LiteGraph.CANVAS_GRID_SIZE = +value; + } + }); + const onNodeMoved = app.canvas.onNodeMoved; + app.canvas.onNodeMoved = function(node) { + const r = onNodeMoved == null ? void 0 : onNodeMoved.apply(this, arguments); + if (app.shiftDown) { + for (const id2 in this.selected_nodes) { + this.selected_nodes[id2].alignToGrid(); + } + } + return r; + }; + const onNodeAdded = app.graph.onNodeAdded; + app.graph.onNodeAdded = function(node) { + const onResize = node.onResize; + node.onResize = function() { + if (app.shiftDown) { + roundVectorToGrid(node.size); + } + return onResize == null ? void 0 : onResize.apply(this, arguments); + }; + return onNodeAdded == null ? void 0 : onNodeAdded.apply(this, arguments); + }; + const origDrawNode = LGraphCanvas.prototype.drawNode; + LGraphCanvas.prototype.drawNode = function(node, ctx) { + if (app.shiftDown && this.node_dragged && node.id in this.selected_nodes) { + const [x, y] = roundVectorToGrid([...node.pos]); + const shiftX = x - node.pos[0]; + let shiftY = y - node.pos[1]; + let w, h; + if (node.flags.collapsed) { + w = node._collapsed_width; + h = LiteGraph.NODE_TITLE_HEIGHT; + shiftY -= LiteGraph.NODE_TITLE_HEIGHT; + } else { + w = node.size[0]; + h = node.size[1]; + let titleMode = node.constructor.title_mode; + if (titleMode !== LiteGraph.TRANSPARENT_TITLE && titleMode !== LiteGraph.NO_TITLE) { + h += LiteGraph.NODE_TITLE_HEIGHT; + shiftY -= LiteGraph.NODE_TITLE_HEIGHT; + } + } + const f = ctx.fillStyle; + ctx.fillStyle = "rgba(100, 100, 100, 0.5)"; + ctx.fillRect(shiftX, shiftY, w, h); + ctx.fillStyle = f; + } + return origDrawNode.apply(this, arguments); + }; + let selectedAndMovingGroup = null; + const groupMove = LGraphGroup.prototype.move; + LGraphGroup.prototype.move = function(deltax, deltay, ignore_nodes) { + const v = groupMove.apply(this, arguments); + if (!selectedAndMovingGroup && app.canvas.selected_group === this && (deltax || deltay)) { + selectedAndMovingGroup = this; + } + if (app.canvas.last_mouse_dragging === false && app.shiftDown) { + this.recomputeInsideNodes(); + for (const node of this._nodes) { + node.alignToGrid(); + } + LGraphNode.prototype.alignToGrid.apply(this); + } + return v; + }; + const drawGroups = LGraphCanvas.prototype.drawGroups; + LGraphCanvas.prototype.drawGroups = function(canvas, ctx) { + if (this.selected_group && app.shiftDown) { + if (this.selected_group_resizing) { + roundVectorToGrid(this.selected_group.size); + } else if (selectedAndMovingGroup) { + const [x, y] = roundVectorToGrid([...selectedAndMovingGroup.pos]); + const f = ctx.fillStyle; + const s = ctx.strokeStyle; + ctx.fillStyle = "rgba(100, 100, 100, 0.33)"; + ctx.strokeStyle = "rgba(100, 100, 100, 0.66)"; + ctx.rect(x, y, ...selectedAndMovingGroup.size); + ctx.fill(); + ctx.stroke(); + ctx.fillStyle = f; + ctx.strokeStyle = s; + } + } else if (!this.selected_group) { + selectedAndMovingGroup = null; + } + return drawGroups.apply(this, arguments); + }; + const onGroupAdd = LGraphCanvas.onGroupAdd; + LGraphCanvas.onGroupAdd = function() { + const v = onGroupAdd.apply(app.canvas, arguments); + if (app.shiftDown) { + const lastGroup = app.graph._groups[app.graph._groups.length - 1]; + if (lastGroup) { + roundVectorToGrid(lastGroup.pos); + roundVectorToGrid(lastGroup.size); + } + } + return v; + }; + } +}); +app.registerExtension({ + name: "Comfy.UploadImage", + beforeRegisterNodeDef(nodeType, nodeData, app2) { + return __async(this, null, function* () { + var _a, _b, _c, _d; + if (((_d = (_c = (_b = (_a = nodeData == null ? void 0 : nodeData.input) == null ? void 0 : _a.required) == null ? void 0 : _b.image) == null ? void 0 : _c[1]) == null ? void 0 : _d.image_upload) === true) { + nodeData.input.required.upload = ["IMAGEUPLOAD"]; + } + }); + } +}); +const WEBCAM_READY = Symbol(); +app.registerExtension({ + name: "Comfy.WebcamCapture", + getCustomWidgets(app2) { + return { + WEBCAM(node, inputName) { + let res; + node[WEBCAM_READY] = new Promise((resolve) => res = resolve); + const container = document.createElement("div"); + container.style.background = "rgba(0,0,0,0.25)"; + container.style.textAlign = "center"; + const video = document.createElement("video"); + video.style.height = video.style.width = "100%"; + const loadVideo = () => __async(this, null, function* () { + try { + const stream = yield navigator.mediaDevices.getUserMedia({ + video: true, + audio: false + }); + container.replaceChildren(video); + setTimeout(() => res(video), 500); + video.addEventListener("loadedmetadata", () => res(video), false); + video.srcObject = stream; + video.play(); + } catch (error) { + const label = document.createElement("div"); + label.style.color = "red"; + label.style.overflow = "auto"; + label.style.maxHeight = "100%"; + label.style.whiteSpace = "pre-wrap"; + if (window.isSecureContext) { + label.textContent = "Unable to load webcam, please ensure access is granted:\n" + error.message; + } else { + label.textContent = "Unable to load webcam. A secure context is required, if you are not accessing ComfyUI on localhost (127.0.0.1) you will have to enable TLS (https)\n\n" + error.message; + } + container.replaceChildren(label); + } + }); + loadVideo(); + return { widget: node.addDOMWidget(inputName, "WEBCAM", container) }; + } + }; + }, + nodeCreated(node) { + if (node.type, node.constructor.comfyClass !== "WebcamCapture") return; + let video; + const camera = node.widgets.find((w2) => w2.name === "image"); + const w = node.widgets.find((w2) => w2.name === "width"); + const h = node.widgets.find((w2) => w2.name === "height"); + const captureOnQueue = node.widgets.find( + (w2) => w2.name === "capture_on_queue" + ); + const canvas = document.createElement("canvas"); + const capture = () => { + canvas.width = w.value; + canvas.height = h.value; + const ctx = canvas.getContext("2d"); + ctx.drawImage(video, 0, 0, w.value, h.value); + const data = canvas.toDataURL("image/png"); + const img = new Image(); + img.onload = () => { + node.imgs = [img]; + app.graph.setDirtyCanvas(true); + requestAnimationFrame(() => { + var _a; + (_a = node.setSizeForImage) == null ? void 0 : _a.call(node); + }); + }; + img.src = data; + }; + const btn = node.addWidget( + "button", + "waiting for camera...", + "capture", + capture + ); + btn.disabled = true; + btn.serializeValue = () => void 0; + camera.serializeValue = () => __async(this, null, function* () { + var _a; + if (captureOnQueue.value) { + capture(); + } else if (!((_a = node.imgs) == null ? void 0 : _a.length)) { + const err = `No webcam image captured`; + alert(err); + throw new Error(err); + } + const blob = yield new Promise((r) => canvas.toBlob(r)); + const name = `${+/* @__PURE__ */ new Date()}.png`; + const file2 = new File([blob], name); + const body = new FormData(); + body.append("image", file2); + body.append("subfolder", "webcam"); + body.append("type", "temp"); + const resp = yield api.fetchApi("/upload/image", { + method: "POST", + body + }); + if (resp.status !== 200) { + const err = `Error uploading camera image: ${resp.status} - ${resp.statusText}`; + alert(err); + throw new Error(err); + } + return `webcam/${name} [temp]`; + }); + node[WEBCAM_READY].then((v) => { + video = v; + if (!w.value) { + w.value = video.videoWidth || 640; + h.value = video.videoHeight || 480; + } + btn.disabled = false; + btn.label = "capture"; + }); + } +}); +function splitFilePath(path) { + const folder_separator = path.lastIndexOf("/"); + if (folder_separator === -1) { + return ["", path]; + } + return [ + path.substring(0, folder_separator), + path.substring(folder_separator + 1) + ]; +} +function getResourceURL(subfolder, filename, type = "input") { + const params = [ + "filename=" + encodeURIComponent(filename), + "type=" + type, + "subfolder=" + subfolder, + app.getRandParam().substring(1) + ].join("&"); + return `/view?${params}`; +} +function uploadFile(audioWidget, audioUIWidget, file2, updateNode, pasted = false) { + return __async(this, null, function* () { + try { + const body = new FormData(); + body.append("image", file2); + if (pasted) body.append("subfolder", "pasted"); + const resp = yield api.fetchApi("/upload/image", { + method: "POST", + body + }); + if (resp.status === 200) { + const data = yield resp.json(); + let path = data.name; + if (data.subfolder) path = data.subfolder + "/" + path; + if (!audioWidget.options.values.includes(path)) { + audioWidget.options.values.push(path); + } + if (updateNode) { + audioUIWidget.element.src = api.apiURL( + getResourceURL(...splitFilePath(path)) + ); + audioWidget.value = path; + } + } else { + alert(resp.status + " - " + resp.statusText); + } + } catch (error) { + alert(error); + } + }); +} +app.registerExtension({ + name: "Comfy.AudioWidget", + beforeRegisterNodeDef(nodeType, nodeData) { + return __async(this, null, function* () { + if (["LoadAudio", "SaveAudio", "PreviewAudio"].includes(nodeType.comfyClass)) { + nodeData.input.required.audioUI = ["AUDIO_UI"]; + } + }); + }, + getCustomWidgets() { + return { + AUDIO_UI(node, inputName) { + const audio = document.createElement("audio"); + audio.controls = true; + audio.classList.add("comfy-audio"); + audio.setAttribute("name", "media"); + const audioUIWidget = node.addDOMWidget( + inputName, + /* name=*/ + "audioUI", + audio + ); + audioUIWidget.serialize = false; + const isOutputNode = node.constructor.nodeData.output_node; + if (isOutputNode) { + audioUIWidget.element.classList.add("empty-audio-widget"); + const onExecuted = node.onExecuted; + node.onExecuted = function(message) { + onExecuted == null ? void 0 : onExecuted.apply(this, arguments); + const audios = message.audio; + if (!audios) return; + const audio2 = audios[0]; + audioUIWidget.element.src = api.apiURL( + getResourceURL(audio2.subfolder, audio2.filename, audio2.type) + ); + audioUIWidget.element.classList.remove("empty-audio-widget"); + }; + } + return { widget: audioUIWidget }; + } + }; + }, + onNodeOutputsUpdated(nodeOutputs) { + for (const [nodeId, output] of Object.entries(nodeOutputs)) { + const node = app.graph.getNodeById(Number.parseInt(nodeId)); + if ("audio" in output) { + const audioUIWidget = node.widgets.find( + (w) => w.name === "audioUI" + ); + const audio = output.audio[0]; + audioUIWidget.element.src = api.apiURL( + getResourceURL(audio.subfolder, audio.filename, audio.type) + ); + audioUIWidget.element.classList.remove("empty-audio-widget"); + } + } + } +}); +app.registerExtension({ + name: "Comfy.UploadAudio", + beforeRegisterNodeDef(nodeType, nodeData) { + return __async(this, null, function* () { + var _a, _b, _c, _d; + if (((_d = (_c = (_b = (_a = nodeData == null ? void 0 : nodeData.input) == null ? void 0 : _a.required) == null ? void 0 : _b.audio) == null ? void 0 : _c[1]) == null ? void 0 : _d.audio_upload) === true) { + nodeData.input.required.upload = ["AUDIOUPLOAD"]; + } + }); + }, + getCustomWidgets() { + return { + AUDIOUPLOAD(node, inputName) { + const audioWidget = node.widgets.find( + (w) => w.name === "audio" + ); + const audioUIWidget = node.widgets.find( + (w) => w.name === "audioUI" + ); + const onAudioWidgetUpdate = () => { + audioUIWidget.element.src = api.apiURL( + getResourceURL(...splitFilePath(audioWidget.value)) + ); + }; + if (audioWidget.value) { + onAudioWidgetUpdate(); + } + audioWidget.callback = onAudioWidgetUpdate; + const onGraphConfigured = node.onGraphConfigured; + node.onGraphConfigured = function() { + onGraphConfigured == null ? void 0 : onGraphConfigured.apply(this, arguments); + if (audioWidget.value) { + onAudioWidgetUpdate(); + } + }; + const fileInput = document.createElement("input"); + fileInput.type = "file"; + fileInput.accept = "audio/*"; + fileInput.style.display = "none"; + fileInput.onchange = () => { + if (fileInput.files.length) { + uploadFile(audioWidget, audioUIWidget, fileInput.files[0], true); + } + }; + const uploadWidget = node.addWidget( + "button", + inputName, + /* value=*/ + "", + () => { + fileInput.click(); + } + ); + uploadWidget.label = "choose file to upload"; + uploadWidget.serialize = false; + return { widget: uploadWidget }; + } + }; + } +}); +//# sourceMappingURL=index-DJRcbqp_.js.map diff --git a/web/assets/index-DJRcbqp_.js.map b/web/assets/index-DJRcbqp_.js.map new file mode 100644 index 000000000..5c2925a97 --- /dev/null +++ b/web/assets/index-DJRcbqp_.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index-DJRcbqp_.js","sources":["../../src/extensions/core/clipspace.ts","../../src/extensions/core/colorPalette.ts","../../src/extensions/core/contextMenuFilter.ts","../../src/extensions/core/dynamicPrompts.ts","../../src/extensions/core/editAttention.ts","../../src/extensions/core/widgetInputs.ts","../../src/extensions/core/groupNodeManage.ts","../../src/extensions/core/groupNode.ts","../../src/extensions/core/groupOptions.ts","../../src/extensions/core/invertMenuScrolling.ts","../../src/extensions/core/keybinds.ts","../../src/extensions/core/linkRenderMode.ts","../../src/extensions/core/maskeditor.ts","../../src/extensions/core/nodeTemplates.ts","../../src/extensions/core/noteNode.ts","../../src/extensions/core/rerouteNode.ts","../../src/extensions/core/saveImageExtraOutput.ts","../../src/extensions/core/simpleTouchSupport.ts","../../src/extensions/core/slotDefaults.ts","../../src/extensions/core/snapToGrid.ts","../../src/extensions/core/uploadImage.ts","../../src/extensions/core/webcamCapture.ts","../../src/extensions/core/uploadAudio.ts"],"sourcesContent":["import { app } from '../../scripts/app'\r\nimport { ComfyDialog, $el } from '../../scripts/ui'\r\nimport { ComfyApp } from '../../scripts/app'\r\n\r\nexport class ClipspaceDialog extends ComfyDialog {\r\n static items = []\r\n static instance = null\r\n\r\n static registerButton(name, contextPredicate, callback) {\r\n const item = $el('button', {\r\n type: 'button',\r\n textContent: name,\r\n contextPredicate: contextPredicate,\r\n onclick: callback\r\n })\r\n\r\n ClipspaceDialog.items.push(item)\r\n }\r\n\r\n static invalidatePreview() {\r\n if (\r\n ComfyApp.clipspace &&\r\n ComfyApp.clipspace.imgs &&\r\n ComfyApp.clipspace.imgs.length > 0\r\n ) {\r\n const img_preview = document.getElementById(\r\n 'clipspace_preview'\r\n ) as HTMLImageElement\r\n if (img_preview) {\r\n img_preview.src =\r\n ComfyApp.clipspace.imgs[ComfyApp.clipspace['selectedIndex']].src\r\n img_preview.style.maxHeight = '100%'\r\n img_preview.style.maxWidth = '100%'\r\n }\r\n }\r\n }\r\n\r\n static invalidate() {\r\n if (ClipspaceDialog.instance) {\r\n const self = ClipspaceDialog.instance\r\n // allow reconstruct controls when copying from non-image to image content.\r\n const children = $el('div.comfy-modal-content', [\r\n self.createImgSettings(),\r\n ...self.createButtons()\r\n ])\r\n\r\n if (self.element) {\r\n // update\r\n self.element.removeChild(self.element.firstChild)\r\n self.element.appendChild(children)\r\n } else {\r\n // new\r\n self.element = $el('div.comfy-modal', { parent: document.body }, [\r\n children\r\n ])\r\n }\r\n\r\n if (self.element.children[0].children.length <= 1) {\r\n self.element.children[0].appendChild(\r\n $el('p', {}, [\r\n 'Unable to find the features to edit content of a format stored in the current Clipspace.'\r\n ])\r\n )\r\n }\r\n\r\n ClipspaceDialog.invalidatePreview()\r\n }\r\n }\r\n\r\n constructor() {\r\n super()\r\n }\r\n\r\n createButtons() {\r\n const buttons = []\r\n\r\n for (let idx in ClipspaceDialog.items) {\r\n const item = ClipspaceDialog.items[idx]\r\n if (!item.contextPredicate || item.contextPredicate())\r\n buttons.push(ClipspaceDialog.items[idx])\r\n }\r\n\r\n buttons.push(\r\n $el('button', {\r\n type: 'button',\r\n textContent: 'Close',\r\n onclick: () => {\r\n this.close()\r\n }\r\n })\r\n )\r\n\r\n return buttons\r\n }\r\n\r\n createImgSettings() {\r\n if (ComfyApp.clipspace.imgs) {\r\n const combo_items = []\r\n const imgs = ComfyApp.clipspace.imgs\r\n\r\n for (let i = 0; i < imgs.length; i++) {\r\n combo_items.push($el('option', { value: i }, [`${i}`]))\r\n }\r\n\r\n const combo1 = $el(\r\n 'select',\r\n {\r\n id: 'clipspace_img_selector',\r\n onchange: (event) => {\r\n ComfyApp.clipspace['selectedIndex'] = event.target.selectedIndex\r\n ClipspaceDialog.invalidatePreview()\r\n }\r\n },\r\n combo_items\r\n )\r\n\r\n const row1 = $el('tr', {}, [\r\n $el('td', {}, [$el('font', { color: 'white' }, ['Select Image'])]),\r\n $el('td', {}, [combo1])\r\n ])\r\n\r\n const combo2 = $el(\r\n 'select',\r\n {\r\n id: 'clipspace_img_paste_mode',\r\n onchange: (event) => {\r\n ComfyApp.clipspace['img_paste_mode'] = event.target.value\r\n }\r\n },\r\n [\r\n $el('option', { value: 'selected' }, 'selected'),\r\n $el('option', { value: 'all' }, 'all')\r\n ]\r\n ) as HTMLSelectElement\r\n combo2.value = ComfyApp.clipspace['img_paste_mode']\r\n\r\n const row2 = $el('tr', {}, [\r\n $el('td', {}, [$el('font', { color: 'white' }, ['Paste Mode'])]),\r\n $el('td', {}, [combo2])\r\n ])\r\n\r\n const td = $el(\r\n 'td',\r\n { align: 'center', width: '100px', height: '100px', colSpan: '2' },\r\n [$el('img', { id: 'clipspace_preview', ondragstart: () => false }, [])]\r\n )\r\n\r\n const row3 = $el('tr', {}, [td])\r\n\r\n return $el('table', {}, [row1, row2, row3])\r\n } else {\r\n return []\r\n }\r\n }\r\n\r\n createImgPreview() {\r\n if (ComfyApp.clipspace.imgs) {\r\n return $el('img', { id: 'clipspace_preview', ondragstart: () => false })\r\n } else return []\r\n }\r\n\r\n show() {\r\n const img_preview = document.getElementById('clipspace_preview')\r\n ClipspaceDialog.invalidate()\r\n\r\n this.element.style.display = 'block'\r\n }\r\n}\r\n\r\napp.registerExtension({\r\n name: 'Comfy.Clipspace',\r\n init(app) {\r\n app.openClipspace = function () {\r\n if (!ClipspaceDialog.instance) {\r\n ClipspaceDialog.instance = new ClipspaceDialog()\r\n ComfyApp.clipspace_invalidate_handler = ClipspaceDialog.invalidate\r\n }\r\n\r\n if (ComfyApp.clipspace) {\r\n ClipspaceDialog.instance.show()\r\n } else app.ui.dialog.show('Clipspace is Empty!')\r\n }\r\n }\r\n})\r\n","import { lightenColor } from '@/utils/colorUtil'\r\nimport { app } from '../../scripts/app'\r\nimport { $el } from '../../scripts/ui'\r\nimport type { ColorPalettes, Palette } from '@/types/colorPalette'\r\nimport { LGraphCanvas, LiteGraph } from '@comfyorg/litegraph'\r\n\r\n// Manage color palettes\r\n\r\nconst colorPalettes: ColorPalettes = {\r\n dark: {\r\n id: 'dark',\r\n name: 'Dark (Default)',\r\n colors: {\r\n node_slot: {\r\n CLIP: '#FFD500', // bright yellow\r\n CLIP_VISION: '#A8DADC', // light blue-gray\r\n CLIP_VISION_OUTPUT: '#ad7452', // rusty brown-orange\r\n CONDITIONING: '#FFA931', // vibrant orange-yellow\r\n CONTROL_NET: '#6EE7B7', // soft mint green\r\n IMAGE: '#64B5F6', // bright sky blue\r\n LATENT: '#FF9CF9', // light pink-purple\r\n MASK: '#81C784', // muted green\r\n MODEL: '#B39DDB', // light lavender-purple\r\n STYLE_MODEL: '#C2FFAE', // light green-yellow\r\n VAE: '#FF6E6E', // bright red\r\n NOISE: '#B0B0B0', // gray\r\n GUIDER: '#66FFFF', // cyan\r\n SAMPLER: '#ECB4B4', // very soft red\r\n SIGMAS: '#CDFFCD', // soft lime green\r\n TAESD: '#DCC274' // cheesecake\r\n },\r\n litegraph_base: {\r\n BACKGROUND_IMAGE:\r\n 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAQBJREFUeNrs1rEKwjAUhlETUkj3vP9rdmr1Ysammk2w5wdxuLgcMHyptfawuZX4pJSWZTnfnu/lnIe/jNNxHHGNn//HNbbv+4dr6V+11uF527arU7+u63qfa/bnmh8sWLBgwYJlqRf8MEptXPBXJXa37BSl3ixYsGDBMliwFLyCV/DeLIMFCxYsWLBMwSt4Be/NggXLYMGCBUvBK3iNruC9WbBgwYJlsGApeAWv4L1ZBgsWLFiwYJmCV/AK3psFC5bBggULloJX8BpdwXuzYMGCBctgwVLwCl7Be7MMFixYsGDBsu8FH1FaSmExVfAxBa/gvVmwYMGCZbBg/W4vAQYA5tRF9QYlv/QAAAAASUVORK5CYII=',\r\n CLEAR_BACKGROUND_COLOR: '#222',\r\n NODE_TITLE_COLOR: '#999',\r\n NODE_SELECTED_TITLE_COLOR: '#FFF',\r\n NODE_TEXT_SIZE: 14,\r\n NODE_TEXT_COLOR: '#AAA',\r\n NODE_SUBTEXT_SIZE: 12,\r\n NODE_DEFAULT_COLOR: '#333',\r\n NODE_DEFAULT_BGCOLOR: '#353535',\r\n NODE_DEFAULT_BOXCOLOR: '#666',\r\n NODE_DEFAULT_SHAPE: 'box',\r\n NODE_BOX_OUTLINE_COLOR: '#FFF',\r\n DEFAULT_SHADOW_COLOR: 'rgba(0,0,0,0.5)',\r\n DEFAULT_GROUP_FONT: 24,\r\n\r\n WIDGET_BGCOLOR: '#222',\r\n WIDGET_OUTLINE_COLOR: '#666',\r\n WIDGET_TEXT_COLOR: '#DDD',\r\n WIDGET_SECONDARY_TEXT_COLOR: '#999',\r\n\r\n LINK_COLOR: '#9A9',\r\n EVENT_LINK_COLOR: '#A86',\r\n CONNECTING_LINK_COLOR: '#AFA'\r\n },\r\n comfy_base: {\r\n 'fg-color': '#fff',\r\n 'bg-color': '#202020',\r\n 'comfy-menu-bg': '#353535',\r\n 'comfy-input-bg': '#222',\r\n 'input-text': '#ddd',\r\n 'descrip-text': '#999',\r\n 'drag-text': '#ccc',\r\n 'error-text': '#ff4444',\r\n 'border-color': '#4e4e4e',\r\n 'tr-even-bg-color': '#222',\r\n 'tr-odd-bg-color': '#353535',\r\n 'content-bg': '#4e4e4e',\r\n 'content-fg': '#fff',\r\n 'content-hover-bg': '#222',\r\n 'content-hover-fg': '#fff'\r\n }\r\n }\r\n },\r\n light: {\r\n id: 'light',\r\n name: 'Light',\r\n colors: {\r\n node_slot: {\r\n CLIP: '#FFA726', // orange\r\n CLIP_VISION: '#5C6BC0', // indigo\r\n CLIP_VISION_OUTPUT: '#8D6E63', // brown\r\n CONDITIONING: '#EF5350', // red\r\n CONTROL_NET: '#66BB6A', // green\r\n IMAGE: '#42A5F5', // blue\r\n LATENT: '#AB47BC', // purple\r\n MASK: '#9CCC65', // light green\r\n MODEL: '#7E57C2', // deep purple\r\n STYLE_MODEL: '#D4E157', // lime\r\n VAE: '#FF7043' // deep orange\r\n },\r\n litegraph_base: {\r\n BACKGROUND_IMAGE:\r\n 'data:image/gif;base64,R0lGODlhZABkALMAAAAAAP///+vr6+rq6ujo6Ofn5+bm5uXl5d3d3f///wAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAAkALAAAAABkAGQAAAT/UMhJq7046827HkcoHkYxjgZhnGG6si5LqnIM0/fL4qwwIMAg0CAsEovBIxKhRDaNy2GUOX0KfVFrssrNdpdaqTeKBX+dZ+jYvEaTf+y4W66mC8PUdrE879f9d2mBeoNLfH+IhYBbhIx2jkiHiomQlGKPl4uZe3CaeZifnnijgkESBqipqqusra6vsLGys62SlZO4t7qbuby7CLa+wqGWxL3Gv3jByMOkjc2lw8vOoNSi0czAncXW3Njdx9Pf48/Z4Kbbx+fQ5evZ4u3k1fKR6cn03vHlp7T9/v8A/8Gbp4+gwXoFryXMB2qgwoMMHyKEqA5fxX322FG8tzBcRnMW/zlulPbRncmQGidKjMjyYsOSKEF2FBlJQMCbOHP6c9iSZs+UnGYCdbnSo1CZI5F64kn0p1KnTH02nSoV3dGTV7FFHVqVq1dtWcMmVQZTbNGu72zqXMuW7danVL+6e4t1bEy6MeueBYLXrNO5Ze36jQtWsOG97wIj1vt3St/DjTEORss4nNq2mDP3e7w4r1bFkSET5hy6s2TRlD2/mSxXtSHQhCunXo26NevCpmvD/UU6tuullzULH76q92zdZG/Ltv1a+W+osI/nRmyc+fRi1Xdbh+68+0vv10dH3+77KD/i6IdnX669/frn5Zsjh4/2PXju8+8bzc9/6fj27LFnX11/+IUnXWl7BJfegm79FyB9JOl3oHgSklefgxAC+FmFGpqHIYcCfkhgfCohSKKJVo044YUMttggiBkmp6KFXw1oII24oYhjiDByaKOOHcp3Y5BD/njikSkO+eBREQAAOw==',\r\n CLEAR_BACKGROUND_COLOR: 'lightgray',\r\n NODE_TITLE_COLOR: '#222',\r\n NODE_SELECTED_TITLE_COLOR: '#000',\r\n NODE_TEXT_SIZE: 14,\r\n NODE_TEXT_COLOR: '#444',\r\n NODE_SUBTEXT_SIZE: 12,\r\n NODE_DEFAULT_COLOR: '#F7F7F7',\r\n NODE_DEFAULT_BGCOLOR: '#F5F5F5',\r\n NODE_DEFAULT_BOXCOLOR: '#CCC',\r\n NODE_DEFAULT_SHAPE: 'box',\r\n NODE_BOX_OUTLINE_COLOR: '#000',\r\n DEFAULT_SHADOW_COLOR: 'rgba(0,0,0,0.1)',\r\n DEFAULT_GROUP_FONT: 24,\r\n\r\n WIDGET_BGCOLOR: '#D4D4D4',\r\n WIDGET_OUTLINE_COLOR: '#999',\r\n WIDGET_TEXT_COLOR: '#222',\r\n WIDGET_SECONDARY_TEXT_COLOR: '#555',\r\n\r\n LINK_COLOR: '#4CAF50',\r\n EVENT_LINK_COLOR: '#FF9800',\r\n CONNECTING_LINK_COLOR: '#2196F3'\r\n },\r\n comfy_base: {\r\n 'fg-color': '#222',\r\n 'bg-color': '#DDD',\r\n 'comfy-menu-bg': '#F5F5F5',\r\n 'comfy-input-bg': '#C9C9C9',\r\n 'input-text': '#222',\r\n 'descrip-text': '#444',\r\n 'drag-text': '#555',\r\n 'error-text': '#F44336',\r\n 'border-color': '#888',\r\n 'tr-even-bg-color': '#f9f9f9',\r\n 'tr-odd-bg-color': '#fff',\r\n 'content-bg': '#e0e0e0',\r\n 'content-fg': '#222',\r\n 'content-hover-bg': '#adadad',\r\n 'content-hover-fg': '#222'\r\n }\r\n }\r\n },\r\n solarized: {\r\n id: 'solarized',\r\n name: 'Solarized',\r\n colors: {\r\n node_slot: {\r\n CLIP: '#2AB7CA', // light blue\r\n CLIP_VISION: '#6c71c4', // blue violet\r\n CLIP_VISION_OUTPUT: '#859900', // olive green\r\n CONDITIONING: '#d33682', // magenta\r\n CONTROL_NET: '#d1ffd7', // light mint green\r\n IMAGE: '#5940bb', // deep blue violet\r\n LATENT: '#268bd2', // blue\r\n MASK: '#CCC9E7', // light purple-gray\r\n MODEL: '#dc322f', // red\r\n STYLE_MODEL: '#1a998a', // teal\r\n UPSCALE_MODEL: '#054A29', // dark green\r\n VAE: '#facfad' // light pink-orange\r\n },\r\n litegraph_base: {\r\n NODE_TITLE_COLOR: '#fdf6e3', // Base3\r\n NODE_SELECTED_TITLE_COLOR: '#A9D400',\r\n NODE_TEXT_SIZE: 14,\r\n NODE_TEXT_COLOR: '#657b83', // Base00\r\n NODE_SUBTEXT_SIZE: 12,\r\n NODE_DEFAULT_COLOR: '#094656',\r\n NODE_DEFAULT_BGCOLOR: '#073642', // Base02\r\n NODE_DEFAULT_BOXCOLOR: '#839496', // Base0\r\n NODE_DEFAULT_SHAPE: 'box',\r\n NODE_BOX_OUTLINE_COLOR: '#fdf6e3', // Base3\r\n DEFAULT_SHADOW_COLOR: 'rgba(0,0,0,0.5)',\r\n DEFAULT_GROUP_FONT: 24,\r\n\r\n WIDGET_BGCOLOR: '#002b36', // Base03\r\n WIDGET_OUTLINE_COLOR: '#839496', // Base0\r\n WIDGET_TEXT_COLOR: '#fdf6e3', // Base3\r\n WIDGET_SECONDARY_TEXT_COLOR: '#93a1a1', // Base1\r\n\r\n LINK_COLOR: '#2aa198', // Solarized Cyan\r\n EVENT_LINK_COLOR: '#268bd2', // Solarized Blue\r\n CONNECTING_LINK_COLOR: '#859900' // Solarized Green\r\n },\r\n comfy_base: {\r\n 'fg-color': '#fdf6e3', // Base3\r\n 'bg-color': '#002b36', // Base03\r\n 'comfy-menu-bg': '#073642', // Base02\r\n 'comfy-input-bg': '#002b36', // Base03\r\n 'input-text': '#93a1a1', // Base1\r\n 'descrip-text': '#586e75', // Base01\r\n 'drag-text': '#839496', // Base0\r\n 'error-text': '#dc322f', // Solarized Red\r\n 'border-color': '#657b83', // Base00\r\n 'tr-even-bg-color': '#002b36',\r\n 'tr-odd-bg-color': '#073642',\r\n 'content-bg': '#657b83',\r\n 'content-fg': '#fdf6e3',\r\n 'content-hover-bg': '#002b36',\r\n 'content-hover-fg': '#fdf6e3'\r\n }\r\n }\r\n },\r\n arc: {\r\n id: 'arc',\r\n name: 'Arc',\r\n colors: {\r\n node_slot: {\r\n BOOLEAN: '',\r\n CLIP: '#eacb8b',\r\n CLIP_VISION: '#A8DADC',\r\n CLIP_VISION_OUTPUT: '#ad7452',\r\n CONDITIONING: '#cf876f',\r\n CONTROL_NET: '#00d78d',\r\n CONTROL_NET_WEIGHTS: '',\r\n FLOAT: '',\r\n GLIGEN: '',\r\n IMAGE: '#80a1c0',\r\n IMAGEUPLOAD: '',\r\n INT: '',\r\n LATENT: '#b38ead',\r\n LATENT_KEYFRAME: '',\r\n MASK: '#a3bd8d',\r\n MODEL: '#8978a7',\r\n SAMPLER: '',\r\n SIGMAS: '',\r\n STRING: '',\r\n STYLE_MODEL: '#C2FFAE',\r\n T2I_ADAPTER_WEIGHTS: '',\r\n TAESD: '#DCC274',\r\n TIMESTEP_KEYFRAME: '',\r\n UPSCALE_MODEL: '',\r\n VAE: '#be616b'\r\n },\r\n litegraph_base: {\r\n BACKGROUND_IMAGE:\r\n 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAACXBIWXMAAAsTAAALEwEAmpwYAAABcklEQVR4nO3YMUoDARgF4RfxBqZI6/0vZqFn0MYtrLIQMFN8U6V4LAtD+Jm9XG/v30OGl2e/AP7yevz4+vx45nvgF/+QGITEICQGITEIiUFIjNNC3q43u3/YnRJyPOzeQ+0e220nhRzReC8e7R7bbdvl+Jal1Bs46jEIiUFIDEJiEBKDkBhKPbZT6qHdptRTu02p53DUYxASg5AYhMQgJAYhMZR6bKfUQ7tNqad2m1LP4ajHICQGITEIiUFIDEJiKPXYTqmHdptST+02pZ7DUY9BSAxCYhASg5AYhMRQ6rGdUg/tNqWe2m1KPYejHoOQGITEICQGITEIiaHUYzulHtptSj2125R6Dkc9BiExCIlBSAxCYhASQ6nHdko9tNuUemq3KfUcjnoMQmIQEoOQGITEICSGUo/tlHpotyn11G5T6jkc9RiExCAkBiExCIlBSAylHtsp9dBuU+qp3abUczjqMQiJQUgMQmIQEoOQGITE+AHFISNQrFTGuwAAAABJRU5ErkJggg==',\r\n CLEAR_BACKGROUND_COLOR: '#2b2f38',\r\n NODE_TITLE_COLOR: '#b2b7bd',\r\n NODE_SELECTED_TITLE_COLOR: '#FFF',\r\n NODE_TEXT_SIZE: 14,\r\n NODE_TEXT_COLOR: '#AAA',\r\n NODE_SUBTEXT_SIZE: 12,\r\n NODE_DEFAULT_COLOR: '#2b2f38',\r\n NODE_DEFAULT_BGCOLOR: '#242730',\r\n NODE_DEFAULT_BOXCOLOR: '#6e7581',\r\n NODE_DEFAULT_SHAPE: 'box',\r\n NODE_BOX_OUTLINE_COLOR: '#FFF',\r\n DEFAULT_SHADOW_COLOR: 'rgba(0,0,0,0.5)',\r\n DEFAULT_GROUP_FONT: 22,\r\n WIDGET_BGCOLOR: '#2b2f38',\r\n WIDGET_OUTLINE_COLOR: '#6e7581',\r\n WIDGET_TEXT_COLOR: '#DDD',\r\n WIDGET_SECONDARY_TEXT_COLOR: '#b2b7bd',\r\n LINK_COLOR: '#9A9',\r\n EVENT_LINK_COLOR: '#A86',\r\n CONNECTING_LINK_COLOR: '#AFA'\r\n },\r\n comfy_base: {\r\n 'fg-color': '#fff',\r\n 'bg-color': '#2b2f38',\r\n 'comfy-menu-bg': '#242730',\r\n 'comfy-input-bg': '#2b2f38',\r\n 'input-text': '#ddd',\r\n 'descrip-text': '#b2b7bd',\r\n 'drag-text': '#ccc',\r\n 'error-text': '#ff4444',\r\n 'border-color': '#6e7581',\r\n 'tr-even-bg-color': '#2b2f38',\r\n 'tr-odd-bg-color': '#242730',\r\n 'content-bg': '#6e7581',\r\n 'content-fg': '#fff',\r\n 'content-hover-bg': '#2b2f38',\r\n 'content-hover-fg': '#fff'\r\n }\r\n }\r\n },\r\n nord: {\r\n id: 'nord',\r\n name: 'Nord',\r\n colors: {\r\n node_slot: {\r\n BOOLEAN: '',\r\n CLIP: '#eacb8b',\r\n CLIP_VISION: '#A8DADC',\r\n CLIP_VISION_OUTPUT: '#ad7452',\r\n CONDITIONING: '#cf876f',\r\n CONTROL_NET: '#00d78d',\r\n CONTROL_NET_WEIGHTS: '',\r\n FLOAT: '',\r\n GLIGEN: '',\r\n IMAGE: '#80a1c0',\r\n IMAGEUPLOAD: '',\r\n INT: '',\r\n LATENT: '#b38ead',\r\n LATENT_KEYFRAME: '',\r\n MASK: '#a3bd8d',\r\n MODEL: '#8978a7',\r\n SAMPLER: '',\r\n SIGMAS: '',\r\n STRING: '',\r\n STYLE_MODEL: '#C2FFAE',\r\n T2I_ADAPTER_WEIGHTS: '',\r\n TAESD: '#DCC274',\r\n TIMESTEP_KEYFRAME: '',\r\n UPSCALE_MODEL: '',\r\n VAE: '#be616b'\r\n },\r\n litegraph_base: {\r\n BACKGROUND_IMAGE:\r\n 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAAAACXBIWXMAAAsTAAALEwEAmpwYAAAFu2lUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4gPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iQWRvYmUgWE1QIENvcmUgOS4xLWMwMDEgNzkuMTQ2Mjg5OSwgMjAyMy8wNi8yNS0yMDowMTo1NSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczpkYz0iaHR0cDovL3B1cmwub3JnL2RjL2VsZW1lbnRzLzEuMS8iIHhtbG5zOnBob3Rvc2hvcD0iaHR0cDovL25zLmFkb2JlLmNvbS9waG90b3Nob3AvMS4wLyIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0RXZ0PSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VFdmVudCMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIDI1LjEgKFdpbmRvd3MpIiB4bXA6Q3JlYXRlRGF0ZT0iMjAyMy0xMS0xM1QwMDoxODowMiswMTowMCIgeG1wOk1vZGlmeURhdGU9IjIwMjMtMTEtMTVUMDE6MjA6NDUrMDE6MDAiIHhtcDpNZXRhZGF0YURhdGU9IjIwMjMtMTEtMTVUMDE6MjA6NDUrMDE6MDAiIGRjOmZvcm1hdD0iaW1hZ2UvcG5nIiBwaG90b3Nob3A6Q29sb3JNb2RlPSIzIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOjUwNDFhMmZjLTEzNzQtMTk0ZC1hZWY4LTYxMzM1MTVmNjUwMCIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDoyMzFiMTBiMC1iNGZiLTAyNGUtYjEyZS0zMDUzMDNjZDA3YzgiIHhtcE1NOk9yaWdpbmFsRG9jdW1lbnRJRD0ieG1wLmRpZDoyMzFiMTBiMC1iNGZiLTAyNGUtYjEyZS0zMDUzMDNjZDA3YzgiPiA8eG1wTU06SGlzdG9yeT4gPHJkZjpTZXE+IDxyZGY6bGkgc3RFdnQ6YWN0aW9uPSJjcmVhdGVkIiBzdEV2dDppbnN0YW5jZUlEPSJ4bXAuaWlkOjIzMWIxMGIwLWI0ZmItMDI0ZS1iMTJlLTMwNTMwM2NkMDdjOCIgc3RFdnQ6d2hlbj0iMjAyMy0xMS0xM1QwMDoxODowMiswMTowMCIgc3RFdnQ6c29mdHdhcmVBZ2VudD0iQWRvYmUgUGhvdG9zaG9wIDI1LjEgKFdpbmRvd3MpIi8+IDxyZGY6bGkgc3RFdnQ6YWN0aW9uPSJzYXZlZCIgc3RFdnQ6aW5zdGFuY2VJRD0ieG1wLmlpZDo1MDQxYTJmYy0xMzc0LTE5NGQtYWVmOC02MTMzNTE1ZjY1MDAiIHN0RXZ0OndoZW49IjIwMjMtMTEtMTVUMDE6MjA6NDUrMDE6MDAiIHN0RXZ0OnNvZnR3YXJlQWdlbnQ9IkFkb2JlIFBob3Rvc2hvcCAyNS4xIChXaW5kb3dzKSIgc3RFdnQ6Y2hhbmdlZD0iLyIvPiA8L3JkZjpTZXE+IDwveG1wTU06SGlzdG9yeT4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz73jWg/AAAAyUlEQVR42u3WKwoAIBRFQRdiMb1idv9Lsxn9gEFw4Dbb8JCTojbbXEJwjJVL2HKwYMGCBQuWLbDmjr+9zrBGjHl1WVcvy2DBggULFizTWQpewSt4HzwsgwULFiwFr7MUvMtS8D54WLBgGSxYCl7BK3iXZbBgwYIFC5bpLAWv4BW8Dx6WwYIFC5aC11kK3mUpeB88LFiwDBYsBa/gFbzLMliwYMGCBct0loJX8AreBw/LYMGCBUvB6ywF77IUvA8eFixYBgsWrNfWAZPltufdad+1AAAAAElFTkSuQmCC',\r\n CLEAR_BACKGROUND_COLOR: '#212732',\r\n NODE_TITLE_COLOR: '#999',\r\n NODE_SELECTED_TITLE_COLOR: '#e5eaf0',\r\n NODE_TEXT_SIZE: 14,\r\n NODE_TEXT_COLOR: '#bcc2c8',\r\n NODE_SUBTEXT_SIZE: 12,\r\n NODE_DEFAULT_COLOR: '#2e3440',\r\n NODE_DEFAULT_BGCOLOR: '#161b22',\r\n NODE_DEFAULT_BOXCOLOR: '#545d70',\r\n NODE_DEFAULT_SHAPE: 'box',\r\n NODE_BOX_OUTLINE_COLOR: '#e5eaf0',\r\n DEFAULT_SHADOW_COLOR: 'rgba(0,0,0,0.5)',\r\n DEFAULT_GROUP_FONT: 24,\r\n WIDGET_BGCOLOR: '#2e3440',\r\n WIDGET_OUTLINE_COLOR: '#545d70',\r\n WIDGET_TEXT_COLOR: '#bcc2c8',\r\n WIDGET_SECONDARY_TEXT_COLOR: '#999',\r\n LINK_COLOR: '#9A9',\r\n EVENT_LINK_COLOR: '#A86',\r\n CONNECTING_LINK_COLOR: '#AFA'\r\n },\r\n comfy_base: {\r\n 'fg-color': '#e5eaf0',\r\n 'bg-color': '#2e3440',\r\n 'comfy-menu-bg': '#161b22',\r\n 'comfy-input-bg': '#2e3440',\r\n 'input-text': '#bcc2c8',\r\n 'descrip-text': '#999',\r\n 'drag-text': '#ccc',\r\n 'error-text': '#ff4444',\r\n 'border-color': '#545d70',\r\n 'tr-even-bg-color': '#2e3440',\r\n 'tr-odd-bg-color': '#161b22',\r\n 'content-bg': '#545d70',\r\n 'content-fg': '#e5eaf0',\r\n 'content-hover-bg': '#2e3440',\r\n 'content-hover-fg': '#e5eaf0'\r\n }\r\n }\r\n },\r\n github: {\r\n id: 'github',\r\n name: 'Github',\r\n colors: {\r\n node_slot: {\r\n BOOLEAN: '',\r\n CLIP: '#eacb8b',\r\n CLIP_VISION: '#A8DADC',\r\n CLIP_VISION_OUTPUT: '#ad7452',\r\n CONDITIONING: '#cf876f',\r\n CONTROL_NET: '#00d78d',\r\n CONTROL_NET_WEIGHTS: '',\r\n FLOAT: '',\r\n GLIGEN: '',\r\n IMAGE: '#80a1c0',\r\n IMAGEUPLOAD: '',\r\n INT: '',\r\n LATENT: '#b38ead',\r\n LATENT_KEYFRAME: '',\r\n MASK: '#a3bd8d',\r\n MODEL: '#8978a7',\r\n SAMPLER: '',\r\n SIGMAS: '',\r\n STRING: '',\r\n STYLE_MODEL: '#C2FFAE',\r\n T2I_ADAPTER_WEIGHTS: '',\r\n TAESD: '#DCC274',\r\n TIMESTEP_KEYFRAME: '',\r\n UPSCALE_MODEL: '',\r\n VAE: '#be616b'\r\n },\r\n litegraph_base: {\r\n BACKGROUND_IMAGE:\r\n 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAAAACXBIWXMAAAsTAAALEwEAmpwYAAAGlmlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4gPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iQWRvYmUgWE1QIENvcmUgOS4xLWMwMDEgNzkuMTQ2Mjg5OSwgMjAyMy8wNi8yNS0yMDowMTo1NSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczpkYz0iaHR0cDovL3B1cmwub3JnL2RjL2VsZW1lbnRzLzEuMS8iIHhtbG5zOnBob3Rvc2hvcD0iaHR0cDovL25zLmFkb2JlLmNvbS9waG90b3Nob3AvMS4wLyIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0RXZ0PSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VFdmVudCMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIDI1LjEgKFdpbmRvd3MpIiB4bXA6Q3JlYXRlRGF0ZT0iMjAyMy0xMS0xM1QwMDoxODowMiswMTowMCIgeG1wOk1vZGlmeURhdGU9IjIwMjMtMTEtMTVUMDI6MDQ6NTkrMDE6MDAiIHhtcDpNZXRhZGF0YURhdGU9IjIwMjMtMTEtMTVUMDI6MDQ6NTkrMDE6MDAiIGRjOmZvcm1hdD0iaW1hZ2UvcG5nIiBwaG90b3Nob3A6Q29sb3JNb2RlPSIzIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOmIyYzRhNjA5LWJmYTctYTg0MC1iOGFlLTk3MzE2ZjM1ZGIyNyIgeG1wTU06RG9jdW1lbnRJRD0iYWRvYmU6ZG9jaWQ6cGhvdG9zaG9wOjk0ZmNlZGU4LTE1MTctZmQ0MC04ZGU3LWYzOTgxM2E3ODk5ZiIgeG1wTU06T3JpZ2luYWxEb2N1bWVudElEPSJ4bXAuZGlkOjIzMWIxMGIwLWI0ZmItMDI0ZS1iMTJlLTMwNTMwM2NkMDdjOCI+IDx4bXBNTTpIaXN0b3J5PiA8cmRmOlNlcT4gPHJkZjpsaSBzdEV2dDphY3Rpb249ImNyZWF0ZWQiIHN0RXZ0Omluc3RhbmNlSUQ9InhtcC5paWQ6MjMxYjEwYjAtYjRmYi0wMjRlLWIxMmUtMzA1MzAzY2QwN2M4IiBzdEV2dDp3aGVuPSIyMDIzLTExLTEzVDAwOjE4OjAyKzAxOjAwIiBzdEV2dDpzb2Z0d2FyZUFnZW50PSJBZG9iZSBQaG90b3Nob3AgMjUuMSAoV2luZG93cykiLz4gPHJkZjpsaSBzdEV2dDphY3Rpb249InNhdmVkIiBzdEV2dDppbnN0YW5jZUlEPSJ4bXAuaWlkOjQ4OWY1NzlmLTJkNjUtZWQ0Zi04OTg0LTA4NGE2MGE1ZTMzNSIgc3RFdnQ6d2hlbj0iMjAyMy0xMS0xNVQwMjowNDo1OSswMTowMCIgc3RFdnQ6c29mdHdhcmVBZ2VudD0iQWRvYmUgUGhvdG9zaG9wIDI1LjEgKFdpbmRvd3MpIiBzdEV2dDpjaGFuZ2VkPSIvIi8+IDxyZGY6bGkgc3RFdnQ6YWN0aW9uPSJzYXZlZCIgc3RFdnQ6aW5zdGFuY2VJRD0ieG1wLmlpZDpiMmM0YTYwOS1iZmE3LWE4NDAtYjhhZS05NzMxNmYzNWRiMjciIHN0RXZ0OndoZW49IjIwMjMtMTEtMTVUMDI6MDQ6NTkrMDE6MDAiIHN0RXZ0OnNvZnR3YXJlQWdlbnQ9IkFkb2JlIFBob3Rvc2hvcCAyNS4xIChXaW5kb3dzKSIgc3RFdnQ6Y2hhbmdlZD0iLyIvPiA8L3JkZjpTZXE+IDwveG1wTU06SGlzdG9yeT4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz4OTe6GAAAAx0lEQVR42u3WMQoAIQxFwRzJys77X8vSLiRgITif7bYbgrwYc/mKXyBoY4VVBgsWLFiwYFmOlTv+9jfDOjHmr8u6eVkGCxYsWLBgmc5S8ApewXvgYRksWLBgKXidpeBdloL3wMOCBctgwVLwCl7BuyyDBQsWLFiwTGcpeAWv4D3wsAwWLFiwFLzOUvAuS8F74GHBgmWwYCl4Ba/gXZbBggULFixYprMUvIJX8B54WAYLFixYCl5nKXiXpeA98LBgwTJYsGC9tg1o8f4TTtqzNQAAAABJRU5ErkJggg==',\r\n CLEAR_BACKGROUND_COLOR: '#040506',\r\n NODE_TITLE_COLOR: '#999',\r\n NODE_SELECTED_TITLE_COLOR: '#e5eaf0',\r\n NODE_TEXT_SIZE: 14,\r\n NODE_TEXT_COLOR: '#bcc2c8',\r\n NODE_SUBTEXT_SIZE: 12,\r\n NODE_DEFAULT_COLOR: '#161b22',\r\n NODE_DEFAULT_BGCOLOR: '#13171d',\r\n NODE_DEFAULT_BOXCOLOR: '#30363d',\r\n NODE_DEFAULT_SHAPE: 'box',\r\n NODE_BOX_OUTLINE_COLOR: '#e5eaf0',\r\n DEFAULT_SHADOW_COLOR: 'rgba(0,0,0,0.5)',\r\n DEFAULT_GROUP_FONT: 24,\r\n WIDGET_BGCOLOR: '#161b22',\r\n WIDGET_OUTLINE_COLOR: '#30363d',\r\n WIDGET_TEXT_COLOR: '#bcc2c8',\r\n WIDGET_SECONDARY_TEXT_COLOR: '#999',\r\n LINK_COLOR: '#9A9',\r\n EVENT_LINK_COLOR: '#A86',\r\n CONNECTING_LINK_COLOR: '#AFA'\r\n },\r\n comfy_base: {\r\n 'fg-color': '#e5eaf0',\r\n 'bg-color': '#161b22',\r\n 'comfy-menu-bg': '#13171d',\r\n 'comfy-input-bg': '#161b22',\r\n 'input-text': '#bcc2c8',\r\n 'descrip-text': '#999',\r\n 'drag-text': '#ccc',\r\n 'error-text': '#ff4444',\r\n 'border-color': '#30363d',\r\n 'tr-even-bg-color': '#161b22',\r\n 'tr-odd-bg-color': '#13171d',\r\n 'content-bg': '#30363d',\r\n 'content-fg': '#e5eaf0',\r\n 'content-hover-bg': '#161b22',\r\n 'content-hover-fg': '#e5eaf0'\r\n }\r\n }\r\n }\r\n}\r\n\r\nconst id = 'Comfy.ColorPalette'\r\nconst idCustomColorPalettes = 'Comfy.CustomColorPalettes'\r\nconst defaultColorPaletteId = 'dark'\r\nconst els: { select: HTMLSelectElement | null } = {\r\n select: null\r\n}\r\n// const ctxMenu = LiteGraph.ContextMenu;\r\napp.registerExtension({\r\n name: id,\r\n init() {\r\n /**\r\n * Changes the background color of the canvas.\r\n *\r\n * @method updateBackground\r\n * @param {image} String\r\n * @param {clearBackgroundColor} String\r\n */\r\n // @ts-expect-error\r\n LGraphCanvas.prototype.updateBackground = function (\r\n image,\r\n clearBackgroundColor\r\n ) {\r\n this._bg_img = new Image()\r\n this._bg_img.name = image\r\n this._bg_img.src = image\r\n this._bg_img.onload = () => {\r\n this.draw(true, true)\r\n }\r\n this.background_image = image\r\n\r\n this.clear_background = true\r\n this.clear_background_color = clearBackgroundColor\r\n this._pattern = null\r\n }\r\n },\r\n addCustomNodeDefs(node_defs) {\r\n const sortObjectKeys = (unordered) => {\r\n return Object.keys(unordered)\r\n .sort()\r\n .reduce((obj, key) => {\r\n obj[key] = unordered[key]\r\n return obj\r\n }, {})\r\n }\r\n\r\n function getSlotTypes() {\r\n var types = []\r\n\r\n const defs = node_defs\r\n for (const nodeId in defs) {\r\n const nodeData = defs[nodeId]\r\n\r\n var inputs = nodeData['input']['required']\r\n if (nodeData['input']['optional'] !== undefined) {\r\n inputs = Object.assign(\r\n {},\r\n nodeData['input']['required'],\r\n nodeData['input']['optional']\r\n )\r\n }\r\n\r\n for (const inputName in inputs) {\r\n const inputData = inputs[inputName]\r\n const type = inputData[0]\r\n\r\n if (!Array.isArray(type)) {\r\n types.push(type)\r\n }\r\n }\r\n\r\n for (const o in nodeData['output']) {\r\n const output = nodeData['output'][o]\r\n types.push(output)\r\n }\r\n }\r\n\r\n return types\r\n }\r\n\r\n function completeColorPalette(colorPalette) {\r\n var types = getSlotTypes()\r\n\r\n for (const type of types) {\r\n if (!colorPalette.colors.node_slot[type]) {\r\n colorPalette.colors.node_slot[type] = ''\r\n }\r\n }\r\n\r\n colorPalette.colors.node_slot = sortObjectKeys(\r\n colorPalette.colors.node_slot\r\n )\r\n\r\n return colorPalette\r\n }\r\n\r\n const getColorPaletteTemplate = async () => {\r\n let colorPalette = {\r\n id: 'my_color_palette_unique_id',\r\n name: 'My Color Palette',\r\n colors: {\r\n node_slot: {},\r\n litegraph_base: {},\r\n comfy_base: {}\r\n }\r\n }\r\n\r\n // Copy over missing keys from default color palette\r\n const defaultColorPalette = colorPalettes[defaultColorPaletteId]\r\n for (const key in defaultColorPalette.colors.litegraph_base) {\r\n if (!colorPalette.colors.litegraph_base[key]) {\r\n colorPalette.colors.litegraph_base[key] = ''\r\n }\r\n }\r\n for (const key in defaultColorPalette.colors.comfy_base) {\r\n if (!colorPalette.colors.comfy_base[key]) {\r\n colorPalette.colors.comfy_base[key] = ''\r\n }\r\n }\r\n\r\n return completeColorPalette(colorPalette)\r\n }\r\n\r\n const getCustomColorPalettes = (): ColorPalettes => {\r\n return app.ui.settings.getSettingValue(idCustomColorPalettes, {})\r\n }\r\n\r\n const setCustomColorPalettes = (customColorPalettes: ColorPalettes) => {\r\n return app.ui.settings.setSettingValue(\r\n idCustomColorPalettes,\r\n customColorPalettes\r\n )\r\n }\r\n\r\n const addCustomColorPalette = async (colorPalette) => {\r\n if (typeof colorPalette !== 'object') {\r\n alert('Invalid color palette.')\r\n return\r\n }\r\n\r\n if (!colorPalette.id) {\r\n alert('Color palette missing id.')\r\n return\r\n }\r\n\r\n if (!colorPalette.name) {\r\n alert('Color palette missing name.')\r\n return\r\n }\r\n\r\n if (!colorPalette.colors) {\r\n alert('Color palette missing colors.')\r\n return\r\n }\r\n\r\n if (\r\n colorPalette.colors.node_slot &&\r\n typeof colorPalette.colors.node_slot !== 'object'\r\n ) {\r\n alert('Invalid color palette colors.node_slot.')\r\n return\r\n }\r\n\r\n const customColorPalettes = getCustomColorPalettes()\r\n customColorPalettes[colorPalette.id] = colorPalette\r\n setCustomColorPalettes(customColorPalettes)\r\n\r\n for (const option of els.select.childNodes) {\r\n if (\r\n (option as HTMLOptionElement).value ===\r\n 'custom_' + colorPalette.id\r\n ) {\r\n els.select.removeChild(option)\r\n }\r\n }\r\n\r\n els.select.append(\r\n $el('option', {\r\n textContent: colorPalette.name + ' (custom)',\r\n value: 'custom_' + colorPalette.id,\r\n selected: true\r\n })\r\n )\r\n\r\n setColorPalette('custom_' + colorPalette.id)\r\n await loadColorPalette(colorPalette)\r\n }\r\n\r\n const deleteCustomColorPalette = async (colorPaletteId) => {\r\n const customColorPalettes = getCustomColorPalettes()\r\n delete customColorPalettes[colorPaletteId]\r\n setCustomColorPalettes(customColorPalettes)\r\n\r\n for (const opt of els.select.childNodes) {\r\n const option = opt as HTMLOptionElement\r\n if (option.value === defaultColorPaletteId) {\r\n option.selected = true\r\n }\r\n\r\n if (option.value === 'custom_' + colorPaletteId) {\r\n els.select.removeChild(option)\r\n }\r\n }\r\n\r\n setColorPalette(defaultColorPaletteId)\r\n await loadColorPalette(getColorPalette())\r\n }\r\n\r\n const loadColorPalette = async (colorPalette: Palette) => {\r\n colorPalette = await completeColorPalette(colorPalette)\r\n if (colorPalette.colors) {\r\n // Sets the colors of node slots and links\r\n if (colorPalette.colors.node_slot) {\r\n Object.assign(\r\n // @ts-expect-error\r\n app.canvas.default_connection_color_byType,\r\n colorPalette.colors.node_slot\r\n )\r\n Object.assign(\r\n LGraphCanvas.link_type_colors,\r\n colorPalette.colors.node_slot\r\n )\r\n }\r\n // Sets the colors of the LiteGraph objects\r\n if (colorPalette.colors.litegraph_base) {\r\n // Everything updates correctly in the loop, except the Node Title and Link Color for some reason\r\n app.canvas.node_title_color =\r\n colorPalette.colors.litegraph_base.NODE_TITLE_COLOR\r\n app.canvas.default_link_color =\r\n colorPalette.colors.litegraph_base.LINK_COLOR\r\n\r\n for (const key in colorPalette.colors.litegraph_base) {\r\n if (\r\n colorPalette.colors.litegraph_base.hasOwnProperty(key) &&\r\n LiteGraph.hasOwnProperty(key)\r\n ) {\r\n LiteGraph[key] = colorPalette.colors.litegraph_base[key]\r\n }\r\n }\r\n }\r\n // Sets the color of ComfyUI elements\r\n if (colorPalette.colors.comfy_base) {\r\n const rootStyle = document.documentElement.style\r\n for (const key in colorPalette.colors.comfy_base) {\r\n rootStyle.setProperty(\r\n '--' + key,\r\n colorPalette.colors.comfy_base[key]\r\n )\r\n }\r\n }\r\n app.canvas.draw(true, true)\r\n }\r\n }\r\n\r\n const getColorPalette = (colorPaletteId?) => {\r\n if (!colorPaletteId) {\r\n colorPaletteId = app.ui.settings.getSettingValue(\r\n id,\r\n defaultColorPaletteId\r\n )\r\n }\r\n\r\n if (colorPaletteId.startsWith('custom_')) {\r\n colorPaletteId = colorPaletteId.substr(7)\r\n let customColorPalettes = getCustomColorPalettes()\r\n if (customColorPalettes[colorPaletteId]) {\r\n return customColorPalettes[colorPaletteId]\r\n }\r\n }\r\n\r\n return colorPalettes[colorPaletteId]\r\n }\r\n\r\n const setColorPalette = (colorPaletteId) => {\r\n app.ui.settings.setSettingValue(id, colorPaletteId)\r\n }\r\n\r\n const fileInput = $el('input', {\r\n type: 'file',\r\n accept: '.json',\r\n style: { display: 'none' },\r\n parent: document.body,\r\n onchange: () => {\r\n const file = fileInput.files[0]\r\n if (file.type === 'application/json' || file.name.endsWith('.json')) {\r\n const reader = new FileReader()\r\n reader.onload = async () => {\r\n await addCustomColorPalette(JSON.parse(reader.result as string))\r\n }\r\n reader.readAsText(file)\r\n }\r\n }\r\n }) as HTMLInputElement\r\n\r\n app.ui.settings.addSetting({\r\n id,\r\n name: 'Color Palette',\r\n type: (name, setter, value) => {\r\n const options = [\r\n ...Object.values(colorPalettes).map((c) =>\r\n $el('option', {\r\n textContent: c.name,\r\n value: c.id,\r\n selected: c.id === value\r\n })\r\n ),\r\n ...Object.values(getCustomColorPalettes()).map((c) =>\r\n $el('option', {\r\n textContent: `${c.name} (custom)`,\r\n value: `custom_${c.id}`,\r\n selected: `custom_${c.id}` === value\r\n })\r\n )\r\n ]\r\n\r\n els.select = $el(\r\n 'select',\r\n {\r\n style: {\r\n marginBottom: '0.15rem',\r\n width: '100%'\r\n },\r\n onchange: (e) => {\r\n setter(e.target.value)\r\n }\r\n },\r\n options\r\n ) as HTMLSelectElement\r\n\r\n return $el('tr', [\r\n $el('td', [\r\n $el('label', {\r\n for: id.replaceAll('.', '-'),\r\n textContent: 'Color palette'\r\n })\r\n ]),\r\n $el('td', [\r\n els.select,\r\n $el(\r\n 'div',\r\n {\r\n style: {\r\n display: 'grid',\r\n gap: '4px',\r\n gridAutoFlow: 'column'\r\n }\r\n },\r\n [\r\n $el('input', {\r\n type: 'button',\r\n value: 'Export',\r\n onclick: async () => {\r\n const colorPaletteId = app.ui.settings.getSettingValue(\r\n id,\r\n defaultColorPaletteId\r\n )\r\n const colorPalette = await completeColorPalette(\r\n getColorPalette(colorPaletteId)\r\n )\r\n const json = JSON.stringify(colorPalette, null, 2) // convert the data to a JSON string\r\n const blob = new Blob([json], { type: 'application/json' })\r\n const url = URL.createObjectURL(blob)\r\n const a = $el('a', {\r\n href: url,\r\n download: colorPaletteId + '.json',\r\n style: { display: 'none' },\r\n parent: document.body\r\n })\r\n a.click()\r\n setTimeout(function () {\r\n a.remove()\r\n window.URL.revokeObjectURL(url)\r\n }, 0)\r\n }\r\n }),\r\n $el('input', {\r\n type: 'button',\r\n value: 'Import',\r\n onclick: () => {\r\n fileInput.click()\r\n }\r\n }),\r\n $el('input', {\r\n type: 'button',\r\n value: 'Template',\r\n onclick: async () => {\r\n const colorPalette = await getColorPaletteTemplate()\r\n const json = JSON.stringify(colorPalette, null, 2) // convert the data to a JSON string\r\n const blob = new Blob([json], { type: 'application/json' })\r\n const url = URL.createObjectURL(blob)\r\n const a = $el('a', {\r\n href: url,\r\n download: 'color_palette.json',\r\n style: { display: 'none' },\r\n parent: document.body\r\n })\r\n a.click()\r\n setTimeout(function () {\r\n a.remove()\r\n window.URL.revokeObjectURL(url)\r\n }, 0)\r\n }\r\n }),\r\n $el('input', {\r\n type: 'button',\r\n value: 'Delete',\r\n onclick: async () => {\r\n let colorPaletteId = app.ui.settings.getSettingValue(\r\n id,\r\n defaultColorPaletteId\r\n )\r\n\r\n if (colorPalettes[colorPaletteId]) {\r\n alert('You cannot delete a built-in color palette.')\r\n return\r\n }\r\n\r\n if (colorPaletteId.startsWith('custom_')) {\r\n colorPaletteId = colorPaletteId.substr(7)\r\n }\r\n\r\n await deleteCustomColorPalette(colorPaletteId)\r\n }\r\n })\r\n ]\r\n )\r\n ])\r\n ])\r\n },\r\n defaultValue: defaultColorPaletteId,\r\n async onChange(value) {\r\n if (!value) {\r\n return\r\n }\r\n\r\n let palette = colorPalettes[value]\r\n if (palette) {\r\n await loadColorPalette(palette)\r\n } else if (value.startsWith('custom_')) {\r\n value = value.substr(7)\r\n let customColorPalettes = getCustomColorPalettes()\r\n if (customColorPalettes[value]) {\r\n palette = customColorPalettes[value]\r\n await loadColorPalette(customColorPalettes[value])\r\n }\r\n }\r\n\r\n let { BACKGROUND_IMAGE, CLEAR_BACKGROUND_COLOR } =\r\n palette.colors.litegraph_base\r\n if (\r\n BACKGROUND_IMAGE === undefined ||\r\n CLEAR_BACKGROUND_COLOR === undefined\r\n ) {\r\n const base = colorPalettes['dark'].colors.litegraph_base\r\n BACKGROUND_IMAGE = base.BACKGROUND_IMAGE\r\n CLEAR_BACKGROUND_COLOR = base.CLEAR_BACKGROUND_COLOR\r\n }\r\n // @ts-expect-error\r\n // litegraph.extensions.js\r\n app.canvas.updateBackground(BACKGROUND_IMAGE, CLEAR_BACKGROUND_COLOR)\r\n }\r\n })\r\n }\r\n})\r\n","import { LiteGraph, LGraphCanvas } from '@comfyorg/litegraph'\r\nimport { app } from '../../scripts/app'\r\n\r\n// Adds filtering to combo context menus\r\n\r\nconst ext = {\r\n name: 'Comfy.ContextMenuFilter',\r\n init() {\r\n const ctxMenu = LiteGraph.ContextMenu\r\n // @ts-expect-error\r\n // TODO Very hacky way to modify Litegraph behaviour. Fix this later.\r\n LiteGraph.ContextMenu = function (values, options) {\r\n const ctx = ctxMenu.call(this, values, options)\r\n\r\n // If we are a dark menu (only used for combo boxes) then add a filter input\r\n if (options?.className === 'dark' && values?.length > 10) {\r\n const filter = document.createElement('input')\r\n filter.classList.add('comfy-context-menu-filter')\r\n filter.placeholder = 'Filter list'\r\n this.root.prepend(filter)\r\n\r\n const items = Array.from(\r\n this.root.querySelectorAll('.litemenu-entry')\r\n ) as HTMLElement[]\r\n let displayedItems = [...items]\r\n let itemCount = displayedItems.length\r\n\r\n // We must request an animation frame for the current node of the active canvas to update.\r\n requestAnimationFrame(() => {\r\n // @ts-expect-error\r\n const currentNode = LGraphCanvas.active_canvas.current_node\r\n const clickedComboValue = currentNode.widgets\r\n ?.filter(\r\n (w) =>\r\n w.type === 'combo' && w.options.values.length === values.length\r\n )\r\n .find((w) =>\r\n w.options.values.every((v, i) => v === values[i])\r\n )?.value\r\n\r\n let selectedIndex = clickedComboValue\r\n ? values.findIndex((v) => v === clickedComboValue)\r\n : 0\r\n if (selectedIndex < 0) {\r\n selectedIndex = 0\r\n }\r\n let selectedItem = displayedItems[selectedIndex]\r\n updateSelected()\r\n\r\n // Apply highlighting to the selected item\r\n function updateSelected() {\r\n selectedItem?.style.setProperty('background-color', '')\r\n selectedItem?.style.setProperty('color', '')\r\n selectedItem = displayedItems[selectedIndex]\r\n selectedItem?.style.setProperty(\r\n 'background-color',\r\n '#ccc',\r\n 'important'\r\n )\r\n selectedItem?.style.setProperty('color', '#000', 'important')\r\n }\r\n\r\n const positionList = () => {\r\n const rect = this.root.getBoundingClientRect()\r\n\r\n // If the top is off-screen then shift the element with scaling applied\r\n if (rect.top < 0) {\r\n const scale =\r\n 1 -\r\n this.root.getBoundingClientRect().height /\r\n this.root.clientHeight\r\n const shift = (this.root.clientHeight * scale) / 2\r\n this.root.style.top = -shift + 'px'\r\n }\r\n }\r\n\r\n // Arrow up/down to select items\r\n filter.addEventListener('keydown', (event) => {\r\n switch (event.key) {\r\n case 'ArrowUp':\r\n event.preventDefault()\r\n if (selectedIndex === 0) {\r\n selectedIndex = itemCount - 1\r\n } else {\r\n selectedIndex--\r\n }\r\n updateSelected()\r\n break\r\n case 'ArrowRight':\r\n event.preventDefault()\r\n selectedIndex = itemCount - 1\r\n updateSelected()\r\n break\r\n case 'ArrowDown':\r\n event.preventDefault()\r\n if (selectedIndex === itemCount - 1) {\r\n selectedIndex = 0\r\n } else {\r\n selectedIndex++\r\n }\r\n updateSelected()\r\n break\r\n case 'ArrowLeft':\r\n event.preventDefault()\r\n selectedIndex = 0\r\n updateSelected()\r\n break\r\n case 'Enter':\r\n selectedItem?.click()\r\n break\r\n case 'Escape':\r\n this.close()\r\n break\r\n }\r\n })\r\n\r\n filter.addEventListener('input', () => {\r\n // Hide all items that don't match our filter\r\n const term = filter.value.toLocaleLowerCase()\r\n // When filtering, recompute which items are visible for arrow up/down and maintain selection.\r\n displayedItems = items.filter((item) => {\r\n const isVisible =\r\n !term || item.textContent.toLocaleLowerCase().includes(term)\r\n item.style.display = isVisible ? 'block' : 'none'\r\n return isVisible\r\n })\r\n\r\n selectedIndex = 0\r\n if (displayedItems.includes(selectedItem)) {\r\n selectedIndex = displayedItems.findIndex(\r\n (d) => d === selectedItem\r\n )\r\n }\r\n itemCount = displayedItems.length\r\n\r\n updateSelected()\r\n\r\n // If we have an event then we can try and position the list under the source\r\n if (options.event) {\r\n let top = options.event.clientY - 10\r\n\r\n const bodyRect = document.body.getBoundingClientRect()\r\n const rootRect = this.root.getBoundingClientRect()\r\n if (\r\n bodyRect.height &&\r\n top > bodyRect.height - rootRect.height - 10\r\n ) {\r\n top = Math.max(0, bodyRect.height - rootRect.height - 10)\r\n }\r\n\r\n this.root.style.top = top + 'px'\r\n positionList()\r\n }\r\n })\r\n\r\n requestAnimationFrame(() => {\r\n // Focus the filter box when opening\r\n filter.focus()\r\n\r\n positionList()\r\n })\r\n })\r\n }\r\n\r\n return ctx\r\n }\r\n\r\n LiteGraph.ContextMenu.prototype = ctxMenu.prototype\r\n }\r\n}\r\n\r\napp.registerExtension(ext)\r\n","import { app } from '../../scripts/app'\r\n\r\n// Allows for simple dynamic prompt replacement\r\n// Inputs in the format {a|b} will have a random value of a or b chosen when the prompt is queued.\r\n\r\n/*\r\n * Strips C-style line and block comments from a string\r\n */\r\nfunction stripComments(str) {\r\n return str.replace(/\\/\\*[\\s\\S]*?\\*\\/|\\/\\/.*/g, '')\r\n}\r\n\r\napp.registerExtension({\r\n name: 'Comfy.DynamicPrompts',\r\n nodeCreated(node) {\r\n if (node.widgets) {\r\n // Locate dynamic prompt text widgets\r\n // Include any widgets with dynamicPrompts set to true, and customtext\r\n const widgets = node.widgets.filter((n) => n.dynamicPrompts)\r\n for (const widget of widgets) {\r\n // Override the serialization of the value to resolve dynamic prompts for all widgets supporting it in this node\r\n widget.serializeValue = (workflowNode, widgetIndex) => {\r\n let prompt = stripComments(widget.value)\r\n while (\r\n prompt.replace('\\\\{', '').includes('{') &&\r\n prompt.replace('\\\\}', '').includes('}')\r\n ) {\r\n const startIndex = prompt.replace('\\\\{', '00').indexOf('{')\r\n const endIndex = prompt.replace('\\\\}', '00').indexOf('}')\r\n\r\n const optionsString = prompt.substring(startIndex + 1, endIndex)\r\n const options = optionsString.split('|')\r\n\r\n const randomIndex = Math.floor(Math.random() * options.length)\r\n const randomOption = options[randomIndex]\r\n\r\n prompt =\r\n prompt.substring(0, startIndex) +\r\n randomOption +\r\n prompt.substring(endIndex + 1)\r\n }\r\n\r\n // Overwrite the value in the serialized workflow pnginfo\r\n if (workflowNode?.widgets_values)\r\n workflowNode.widgets_values[widgetIndex] = prompt\r\n\r\n return prompt\r\n }\r\n }\r\n }\r\n }\r\n})\r\n","import { app } from '../../scripts/app'\r\n\r\n// Allows you to edit the attention weight by holding ctrl (or cmd) and using the up/down arrow keys\r\n\r\napp.registerExtension({\r\n name: 'Comfy.EditAttention',\r\n init() {\r\n const editAttentionDelta = app.ui.settings.addSetting({\r\n id: 'Comfy.EditAttention.Delta',\r\n name: 'Ctrl+up/down precision',\r\n type: 'slider',\r\n attrs: {\r\n min: 0.01,\r\n max: 0.5,\r\n step: 0.01\r\n },\r\n defaultValue: 0.05\r\n })\r\n\r\n function incrementWeight(weight, delta) {\r\n const floatWeight = parseFloat(weight)\r\n if (isNaN(floatWeight)) return weight\r\n const newWeight = floatWeight + delta\r\n if (newWeight < 0) return '0'\r\n return String(Number(newWeight.toFixed(10)))\r\n }\r\n\r\n function findNearestEnclosure(text, cursorPos) {\r\n let start = cursorPos,\r\n end = cursorPos\r\n let openCount = 0,\r\n closeCount = 0\r\n\r\n // Find opening parenthesis before cursor\r\n while (start >= 0) {\r\n start--\r\n if (text[start] === '(' && openCount === closeCount) break\r\n if (text[start] === '(') openCount++\r\n if (text[start] === ')') closeCount++\r\n }\r\n if (start < 0) return false\r\n\r\n openCount = 0\r\n closeCount = 0\r\n\r\n // Find closing parenthesis after cursor\r\n while (end < text.length) {\r\n if (text[end] === ')' && openCount === closeCount) break\r\n if (text[end] === '(') openCount++\r\n if (text[end] === ')') closeCount++\r\n end++\r\n }\r\n if (end === text.length) return false\r\n\r\n return { start: start + 1, end: end }\r\n }\r\n\r\n function addWeightToParentheses(text) {\r\n const parenRegex = /^\\((.*)\\)$/\r\n const parenMatch = text.match(parenRegex)\r\n\r\n const floatRegex = /:([+-]?(\\d*\\.)?\\d+([eE][+-]?\\d+)?)/\r\n const floatMatch = text.match(floatRegex)\r\n\r\n if (parenMatch && !floatMatch) {\r\n return `(${parenMatch[1]}:1.0)`\r\n } else {\r\n return text\r\n }\r\n }\r\n\r\n function editAttention(event) {\r\n const inputField = event.composedPath()[0]\r\n const delta = parseFloat(editAttentionDelta.value)\r\n\r\n if (inputField.tagName !== 'TEXTAREA') return\r\n if (!(event.key === 'ArrowUp' || event.key === 'ArrowDown')) return\r\n if (!event.ctrlKey && !event.metaKey) return\r\n\r\n event.preventDefault()\r\n\r\n let start = inputField.selectionStart\r\n let end = inputField.selectionEnd\r\n let selectedText = inputField.value.substring(start, end)\r\n\r\n // If there is no selection, attempt to find the nearest enclosure, or select the current word\r\n if (!selectedText) {\r\n const nearestEnclosure = findNearestEnclosure(inputField.value, start)\r\n if (nearestEnclosure) {\r\n start = nearestEnclosure.start\r\n end = nearestEnclosure.end\r\n selectedText = inputField.value.substring(start, end)\r\n } else {\r\n // Select the current word, find the start and end of the word\r\n const delimiters = ' .,\\\\/!?%^*;:{}=-_`~()\\r\\n\\t'\r\n\r\n while (\r\n !delimiters.includes(inputField.value[start - 1]) &&\r\n start > 0\r\n ) {\r\n start--\r\n }\r\n\r\n while (\r\n !delimiters.includes(inputField.value[end]) &&\r\n end < inputField.value.length\r\n ) {\r\n end++\r\n }\r\n\r\n selectedText = inputField.value.substring(start, end)\r\n if (!selectedText) return\r\n }\r\n }\r\n\r\n // If the selection ends with a space, remove it\r\n if (selectedText[selectedText.length - 1] === ' ') {\r\n selectedText = selectedText.substring(0, selectedText.length - 1)\r\n end -= 1\r\n }\r\n\r\n // If there are parentheses left and right of the selection, select them\r\n if (\r\n inputField.value[start - 1] === '(' &&\r\n inputField.value[end] === ')'\r\n ) {\r\n start -= 1\r\n end += 1\r\n selectedText = inputField.value.substring(start, end)\r\n }\r\n\r\n // If the selection is not enclosed in parentheses, add them\r\n if (\r\n selectedText[0] !== '(' ||\r\n selectedText[selectedText.length - 1] !== ')'\r\n ) {\r\n selectedText = `(${selectedText})`\r\n }\r\n\r\n // If the selection does not have a weight, add a weight of 1.0\r\n selectedText = addWeightToParentheses(selectedText)\r\n\r\n // Increment the weight\r\n const weightDelta = event.key === 'ArrowUp' ? delta : -delta\r\n const updatedText = selectedText.replace(\r\n /\\((.*):(\\d+(?:\\.\\d+)?)\\)/,\r\n (match, text, weight) => {\r\n weight = incrementWeight(weight, weightDelta)\r\n if (weight == 1) {\r\n return text\r\n } else {\r\n return `(${text}:${weight})`\r\n }\r\n }\r\n )\r\n\r\n inputField.setRangeText(updatedText, start, end, 'select')\r\n }\r\n window.addEventListener('keydown', editAttention)\r\n }\r\n})\r\n","import { ComfyWidgets, addValueControlWidgets } from '../../scripts/widgets'\r\nimport { app } from '../../scripts/app'\r\nimport { applyTextReplacements } from '../../scripts/utils'\r\nimport { LiteGraph } from '@comfyorg/litegraph'\r\nimport type { LGraphNode, INodeInputSlot, IWidget } from '@comfyorg/litegraph'\r\n\r\nconst CONVERTED_TYPE = 'converted-widget'\r\nconst VALID_TYPES = ['STRING', 'combo', 'number', 'toggle', 'BOOLEAN']\r\nconst CONFIG = Symbol()\r\nconst GET_CONFIG = Symbol()\r\nconst TARGET = Symbol() // Used for reroutes to specify the real target widget\r\n\r\ninterface PrimitiveNode extends LGraphNode {}\r\n\r\nconst replacePropertyName = 'Run widget replace on values'\r\nclass PrimitiveNode {\r\n controlValues: any[]\r\n lastType: string\r\n static category: string\r\n constructor() {\r\n this.addOutput('connect to widget input', '*')\r\n this.serialize_widgets = true\r\n this.isVirtualNode = true\r\n\r\n if (!this.properties || !(replacePropertyName in this.properties)) {\r\n this.addProperty(replacePropertyName, false, 'boolean')\r\n }\r\n }\r\n\r\n applyToGraph(extraLinks = []) {\r\n if (!this.outputs[0].links?.length) return\r\n\r\n function get_links(node) {\r\n let links = []\r\n for (const l of node.outputs[0].links) {\r\n const linkInfo = app.graph.links[l]\r\n const n = node.graph.getNodeById(linkInfo.target_id)\r\n if (n.type == 'Reroute') {\r\n links = links.concat(get_links(n))\r\n } else {\r\n links.push(l)\r\n }\r\n }\r\n return links\r\n }\r\n\r\n let links = [\r\n ...get_links(this).map((l) => app.graph.links[l]),\r\n ...extraLinks\r\n ]\r\n let v = this.widgets?.[0].value\r\n if (v && this.properties[replacePropertyName]) {\r\n v = applyTextReplacements(app, v)\r\n }\r\n\r\n // For each output link copy our value over the original widget value\r\n for (const linkInfo of links) {\r\n const node = this.graph.getNodeById(linkInfo.target_id)\r\n const input = node.inputs[linkInfo.target_slot]\r\n let widget\r\n if (input.widget[TARGET]) {\r\n widget = input.widget[TARGET]\r\n } else {\r\n const widgetName = (input.widget as { name: string }).name\r\n if (widgetName) {\r\n widget = node.widgets.find((w) => w.name === widgetName)\r\n }\r\n }\r\n\r\n if (widget) {\r\n widget.value = v\r\n if (widget.callback) {\r\n widget.callback(\r\n widget.value,\r\n app.canvas,\r\n node,\r\n app.canvas.graph_mouse,\r\n {}\r\n )\r\n }\r\n }\r\n }\r\n }\r\n\r\n refreshComboInNode() {\r\n const widget = this.widgets?.[0]\r\n if (widget?.type === 'combo') {\r\n widget.options.values = this.outputs[0].widget[GET_CONFIG]()[0]\r\n\r\n if (!widget.options.values.includes(widget.value)) {\r\n widget.value = widget.options.values[0]\r\n ;(widget.callback as Function)(widget.value)\r\n }\r\n }\r\n }\r\n\r\n onAfterGraphConfigured() {\r\n if (this.outputs[0].links?.length && !this.widgets?.length) {\r\n // TODO: Review this check\r\n // @ts-expect-error\r\n if (!this.#onFirstConnection()) return\r\n\r\n // Populate widget values from config data\r\n if (this.widgets) {\r\n for (let i = 0; i < this.widgets_values.length; i++) {\r\n const w = this.widgets[i]\r\n if (w) {\r\n w.value = this.widgets_values[i]\r\n }\r\n }\r\n }\r\n\r\n // Merge values if required\r\n this.#mergeWidgetConfig()\r\n }\r\n }\r\n\r\n onConnectionsChange(_, index, connected) {\r\n if (app.configuringGraph) {\r\n // Dont run while the graph is still setting up\r\n return\r\n }\r\n\r\n const links = this.outputs[0].links\r\n if (connected) {\r\n if (links?.length && !this.widgets?.length) {\r\n this.#onFirstConnection()\r\n }\r\n } else {\r\n // We may have removed a link that caused the constraints to change\r\n this.#mergeWidgetConfig()\r\n\r\n if (!links?.length) {\r\n this.onLastDisconnect()\r\n }\r\n }\r\n }\r\n\r\n onConnectOutput(slot, type, input, target_node, target_slot) {\r\n // Fires before the link is made allowing us to reject it if it isn't valid\r\n // No widget, we cant connect\r\n if (!input.widget) {\r\n if (!(input.type in ComfyWidgets)) return false\r\n }\r\n\r\n if (this.outputs[slot].links?.length) {\r\n const valid = this.#isValidConnection(input)\r\n if (valid) {\r\n // On connect of additional outputs, copy our value to their widget\r\n this.applyToGraph([{ target_id: target_node.id, target_slot }])\r\n }\r\n return valid\r\n }\r\n }\r\n\r\n #onFirstConnection(recreating?: boolean) {\r\n // First connection can fire before the graph is ready on initial load so random things can be missing\r\n if (!this.outputs[0].links) {\r\n this.onLastDisconnect()\r\n return\r\n }\r\n const linkId = this.outputs[0].links[0]\r\n const link = this.graph.links[linkId]\r\n if (!link) return\r\n\r\n const theirNode = this.graph.getNodeById(link.target_id)\r\n if (!theirNode || !theirNode.inputs) return\r\n\r\n const input = theirNode.inputs[link.target_slot]\r\n if (!input) return\r\n\r\n let widget\r\n if (!input.widget) {\r\n if (!(input.type in ComfyWidgets)) return\r\n widget = { name: input.name, [GET_CONFIG]: () => [input.type, {}] } //fake widget\r\n } else {\r\n widget = input.widget\r\n }\r\n\r\n const config = widget[GET_CONFIG]?.()\r\n if (!config) return\r\n\r\n const { type } = getWidgetType(config)\r\n // Update our output to restrict to the widget type\r\n this.outputs[0].type = type\r\n this.outputs[0].name = type\r\n this.outputs[0].widget = widget\r\n\r\n this.#createWidget(\r\n widget[CONFIG] ?? config,\r\n theirNode,\r\n widget.name,\r\n recreating,\r\n widget[TARGET]\r\n )\r\n }\r\n\r\n #createWidget(inputData, node, widgetName, recreating, targetWidget) {\r\n let type = inputData[0]\r\n\r\n if (type instanceof Array) {\r\n type = 'COMBO'\r\n }\r\n\r\n let widget\r\n if (type in ComfyWidgets) {\r\n widget = (ComfyWidgets[type](this, 'value', inputData, app) || {}).widget\r\n } else {\r\n widget = this.addWidget(type, 'value', null, () => {}, {})\r\n }\r\n\r\n if (targetWidget) {\r\n widget.value = targetWidget.value\r\n } else if (node?.widgets && widget) {\r\n const theirWidget = node.widgets.find((w) => w.name === widgetName)\r\n if (theirWidget) {\r\n widget.value = theirWidget.value\r\n }\r\n }\r\n\r\n if (\r\n !inputData?.[1]?.control_after_generate &&\r\n (widget.type === 'number' || widget.type === 'combo')\r\n ) {\r\n let control_value = this.widgets_values?.[1]\r\n if (!control_value) {\r\n control_value = 'fixed'\r\n }\r\n addValueControlWidgets(\r\n this,\r\n widget,\r\n control_value as string,\r\n undefined,\r\n inputData\r\n )\r\n let filter = this.widgets_values?.[2]\r\n if (filter && this.widgets.length === 3) {\r\n this.widgets[2].value = filter\r\n }\r\n }\r\n\r\n // Restore any saved control values\r\n const controlValues = this.controlValues\r\n if (\r\n this.lastType === this.widgets[0].type &&\r\n controlValues?.length === this.widgets.length - 1\r\n ) {\r\n for (let i = 0; i < controlValues.length; i++) {\r\n this.widgets[i + 1].value = controlValues[i]\r\n }\r\n }\r\n\r\n // When our value changes, update other widgets to reflect our changes\r\n // e.g. so LoadImage shows correct image\r\n const callback = widget.callback\r\n const self = this\r\n widget.callback = function () {\r\n const r = callback ? callback.apply(this, arguments) : undefined\r\n self.applyToGraph()\r\n return r\r\n }\r\n\r\n if (!recreating) {\r\n // Grow our node if required\r\n const sz = this.computeSize()\r\n if (this.size[0] < sz[0]) {\r\n this.size[0] = sz[0]\r\n }\r\n if (this.size[1] < sz[1]) {\r\n this.size[1] = sz[1]\r\n }\r\n\r\n requestAnimationFrame(() => {\r\n if (this.onResize) {\r\n this.onResize(this.size)\r\n }\r\n })\r\n }\r\n }\r\n\r\n recreateWidget() {\r\n const values = this.widgets?.map((w) => w.value)\r\n this.#removeWidgets()\r\n this.#onFirstConnection(true)\r\n if (values?.length) {\r\n for (let i = 0; i < this.widgets?.length; i++)\r\n this.widgets[i].value = values[i]\r\n }\r\n return this.widgets?.[0]\r\n }\r\n\r\n #mergeWidgetConfig() {\r\n // Merge widget configs if the node has multiple outputs\r\n const output = this.outputs[0]\r\n const links = output.links\r\n\r\n const hasConfig = !!output.widget[CONFIG]\r\n if (hasConfig) {\r\n delete output.widget[CONFIG]\r\n }\r\n\r\n if (links?.length < 2 && hasConfig) {\r\n // Copy the widget options from the source\r\n if (links.length) {\r\n this.recreateWidget()\r\n }\r\n\r\n return\r\n }\r\n\r\n const config1 = output.widget[GET_CONFIG]()\r\n const isNumber = config1[0] === 'INT' || config1[0] === 'FLOAT'\r\n if (!isNumber) return\r\n\r\n for (const linkId of links) {\r\n const link = app.graph.links[linkId]\r\n if (!link) continue // Can be null when removing a node\r\n\r\n const theirNode = app.graph.getNodeById(link.target_id)\r\n const theirInput = theirNode.inputs[link.target_slot]\r\n\r\n // Call is valid connection so it can merge the configs when validating\r\n this.#isValidConnection(theirInput, hasConfig)\r\n }\r\n }\r\n\r\n #isValidConnection(input: INodeInputSlot, forceUpdate?: boolean) {\r\n // Only allow connections where the configs match\r\n const output = this.outputs[0]\r\n const config2 = input.widget[GET_CONFIG]()\r\n return !!mergeIfValid.call(\r\n this,\r\n output,\r\n config2,\r\n forceUpdate,\r\n this.recreateWidget\r\n )\r\n }\r\n\r\n #removeWidgets() {\r\n if (this.widgets) {\r\n // Allow widgets to cleanup\r\n for (const w of this.widgets) {\r\n if (w.onRemove) {\r\n w.onRemove()\r\n }\r\n }\r\n\r\n // Temporarily store the current values in case the node is being recreated\r\n // e.g. by group node conversion\r\n this.controlValues = []\r\n this.lastType = this.widgets[0]?.type\r\n for (let i = 1; i < this.widgets.length; i++) {\r\n this.controlValues.push(this.widgets[i].value)\r\n }\r\n setTimeout(() => {\r\n delete this.lastType\r\n delete this.controlValues\r\n }, 15)\r\n this.widgets.length = 0\r\n }\r\n }\r\n\r\n onLastDisconnect() {\r\n // We cant remove + re-add the output here as if you drag a link over the same link\r\n // it removes, then re-adds, causing it to break\r\n this.outputs[0].type = '*'\r\n this.outputs[0].name = 'connect to widget input'\r\n delete this.outputs[0].widget\r\n\r\n this.#removeWidgets()\r\n }\r\n}\r\n\r\nexport function getWidgetConfig(slot) {\r\n return slot.widget[CONFIG] ?? slot.widget[GET_CONFIG]()\r\n}\r\n\r\nfunction getConfig(widgetName) {\r\n const { nodeData } = this.constructor\r\n return (\r\n nodeData?.input?.required[widgetName] ??\r\n nodeData?.input?.optional?.[widgetName]\r\n )\r\n}\r\n\r\nfunction isConvertibleWidget(widget, config) {\r\n return (\r\n (VALID_TYPES.includes(widget.type) || VALID_TYPES.includes(config[0])) &&\r\n !widget.options?.forceInput\r\n )\r\n}\r\n\r\nfunction hideWidget(node, widget, suffix = '') {\r\n if (widget.type?.startsWith(CONVERTED_TYPE)) return\r\n widget.origType = widget.type\r\n widget.origComputeSize = widget.computeSize\r\n widget.origSerializeValue = widget.serializeValue\r\n widget.computeSize = () => [0, -4] // -4 is due to the gap litegraph adds between widgets automatically\r\n widget.type = CONVERTED_TYPE + suffix\r\n widget.serializeValue = () => {\r\n // Prevent serializing the widget if we have no input linked\r\n if (!node.inputs) {\r\n return undefined\r\n }\r\n let node_input = node.inputs.find((i) => i.widget?.name === widget.name)\r\n\r\n if (!node_input || !node_input.link) {\r\n return undefined\r\n }\r\n return widget.origSerializeValue\r\n ? widget.origSerializeValue()\r\n : widget.value\r\n }\r\n\r\n // Hide any linked widgets, e.g. seed+seedControl\r\n if (widget.linkedWidgets) {\r\n for (const w of widget.linkedWidgets) {\r\n hideWidget(node, w, ':' + widget.name)\r\n }\r\n }\r\n}\r\n\r\nfunction showWidget(widget) {\r\n widget.type = widget.origType\r\n widget.computeSize = widget.origComputeSize\r\n widget.serializeValue = widget.origSerializeValue\r\n\r\n delete widget.origType\r\n delete widget.origComputeSize\r\n delete widget.origSerializeValue\r\n\r\n // Hide any linked widgets, e.g. seed+seedControl\r\n if (widget.linkedWidgets) {\r\n for (const w of widget.linkedWidgets) {\r\n showWidget(w)\r\n }\r\n }\r\n}\r\n\r\nfunction convertToInput(node, widget, config) {\r\n hideWidget(node, widget)\r\n\r\n const { type } = getWidgetType(config)\r\n\r\n // Add input and store widget config for creating on primitive node\r\n const sz = node.size\r\n node.addInput(widget.name, type, {\r\n widget: { name: widget.name, [GET_CONFIG]: () => config }\r\n })\r\n\r\n for (const widget of node.widgets) {\r\n widget.last_y += LiteGraph.NODE_SLOT_HEIGHT\r\n }\r\n\r\n // Restore original size but grow if needed\r\n node.setSize([Math.max(sz[0], node.size[0]), Math.max(sz[1], node.size[1])])\r\n}\r\n\r\nfunction convertToWidget(node, widget) {\r\n showWidget(widget)\r\n const sz = node.size\r\n node.removeInput(node.inputs.findIndex((i) => i.widget?.name === widget.name))\r\n\r\n for (const widget of node.widgets) {\r\n widget.last_y -= LiteGraph.NODE_SLOT_HEIGHT\r\n }\r\n\r\n // Restore original size but grow if needed\r\n node.setSize([Math.max(sz[0], node.size[0]), Math.max(sz[1], node.size[1])])\r\n}\r\n\r\nfunction getWidgetType(config) {\r\n // Special handling for COMBO so we restrict links based on the entries\r\n let type = config[0]\r\n if (type instanceof Array) {\r\n type = 'COMBO'\r\n }\r\n return { type }\r\n}\r\n\r\nfunction isValidCombo(combo, obj) {\r\n // New input isnt a combo\r\n if (!(obj instanceof Array)) {\r\n console.log(`connection rejected: tried to connect combo to ${obj}`)\r\n return false\r\n }\r\n // New input combo has a different size\r\n if (combo.length !== obj.length) {\r\n console.log(`connection rejected: combo lists dont match`)\r\n return false\r\n }\r\n // New input combo has different elements\r\n if (combo.find((v, i) => obj[i] !== v)) {\r\n console.log(`connection rejected: combo lists dont match`)\r\n return false\r\n }\r\n\r\n return true\r\n}\r\n\r\nfunction isPrimitiveNode(node: LGraphNode): node is PrimitiveNode {\r\n return node.type === 'PrimitiveNode'\r\n}\r\n\r\nexport function setWidgetConfig(slot, config, target?: IWidget) {\r\n if (!slot.widget) return\r\n if (config) {\r\n slot.widget[GET_CONFIG] = () => config\r\n slot.widget[TARGET] = target\r\n } else {\r\n delete slot.widget\r\n }\r\n\r\n if (slot.link) {\r\n const link = app.graph.links[slot.link]\r\n if (link) {\r\n const originNode = app.graph.getNodeById(link.origin_id)\r\n if (isPrimitiveNode(originNode)) {\r\n if (config) {\r\n originNode.recreateWidget()\r\n } else if (!app.configuringGraph) {\r\n originNode.disconnectOutput(0)\r\n originNode.onLastDisconnect()\r\n }\r\n }\r\n }\r\n }\r\n}\r\n\r\nexport function mergeIfValid(\r\n output,\r\n config2,\r\n forceUpdate?: boolean,\r\n recreateWidget?: () => void,\r\n config1?: unknown\r\n) {\r\n if (!config1) {\r\n config1 = output.widget[CONFIG] ?? output.widget[GET_CONFIG]()\r\n }\r\n\r\n if (config1[0] instanceof Array) {\r\n if (!isValidCombo(config1[0], config2[0])) return\r\n } else if (config1[0] !== config2[0]) {\r\n // Types dont match\r\n console.log(`connection rejected: types dont match`, config1[0], config2[0])\r\n return\r\n }\r\n\r\n const keys = new Set([\r\n ...Object.keys(config1[1] ?? {}),\r\n ...Object.keys(config2[1] ?? {})\r\n ])\r\n\r\n let customConfig\r\n const getCustomConfig = () => {\r\n if (!customConfig) {\r\n if (typeof structuredClone === 'undefined') {\r\n customConfig = JSON.parse(JSON.stringify(config1[1] ?? {}))\r\n } else {\r\n customConfig = structuredClone(config1[1] ?? {})\r\n }\r\n }\r\n return customConfig\r\n }\r\n\r\n const isNumber = config1[0] === 'INT' || config1[0] === 'FLOAT'\r\n for (const k of keys.values()) {\r\n if (\r\n k !== 'default' &&\r\n k !== 'forceInput' &&\r\n k !== 'defaultInput' &&\r\n k !== 'control_after_generate' &&\r\n k !== 'multiline' &&\r\n k !== 'tooltip'\r\n ) {\r\n let v1 = config1[1][k]\r\n let v2 = config2[1]?.[k]\r\n\r\n if (v1 === v2 || (!v1 && !v2)) continue\r\n\r\n if (isNumber) {\r\n if (k === 'min') {\r\n const theirMax = config2[1]?.['max']\r\n if (theirMax != null && v1 > theirMax) {\r\n console.log('connection rejected: min > max', v1, theirMax)\r\n return\r\n }\r\n getCustomConfig()[k] =\r\n v1 == null ? v2 : v2 == null ? v1 : Math.max(v1, v2)\r\n continue\r\n } else if (k === 'max') {\r\n const theirMin = config2[1]?.['min']\r\n if (theirMin != null && v1 < theirMin) {\r\n console.log('connection rejected: max < min', v1, theirMin)\r\n return\r\n }\r\n getCustomConfig()[k] =\r\n v1 == null ? v2 : v2 == null ? v1 : Math.min(v1, v2)\r\n continue\r\n } else if (k === 'step') {\r\n let step\r\n if (v1 == null) {\r\n // No current step\r\n step = v2\r\n } else if (v2 == null) {\r\n // No new step\r\n step = v1\r\n } else {\r\n if (v1 < v2) {\r\n // Ensure v1 is larger for the mod\r\n const a = v2\r\n v2 = v1\r\n v1 = a\r\n }\r\n if (v1 % v2) {\r\n console.log(\r\n 'connection rejected: steps not divisible',\r\n 'current:',\r\n v1,\r\n 'new:',\r\n v2\r\n )\r\n return\r\n }\r\n\r\n step = v1\r\n }\r\n\r\n getCustomConfig()[k] = step\r\n continue\r\n }\r\n }\r\n\r\n console.log(`connection rejected: config ${k} values dont match`, v1, v2)\r\n return\r\n }\r\n }\r\n\r\n if (customConfig || forceUpdate) {\r\n if (customConfig) {\r\n output.widget[CONFIG] = [config1[0], customConfig]\r\n }\r\n\r\n const widget = recreateWidget?.call(this)\r\n // When deleting a node this can be null\r\n if (widget) {\r\n const min = widget.options.min\r\n const max = widget.options.max\r\n if (min != null && widget.value < min) widget.value = min\r\n if (max != null && widget.value > max) widget.value = max\r\n widget.callback(widget.value)\r\n }\r\n }\r\n\r\n return { customConfig }\r\n}\r\n\r\nlet useConversionSubmenusSetting\r\napp.registerExtension({\r\n name: 'Comfy.WidgetInputs',\r\n init() {\r\n useConversionSubmenusSetting = app.ui.settings.addSetting({\r\n id: 'Comfy.NodeInputConversionSubmenus',\r\n name: 'Node widget/input conversion sub-menus',\r\n tooltip:\r\n 'In the node context menu, place the entries that convert between input/widget in sub-menus.',\r\n type: 'boolean',\r\n defaultValue: true\r\n })\r\n },\r\n async beforeRegisterNodeDef(nodeType, nodeData, app) {\r\n // Add menu options to convert to/from widgets\r\n const origGetExtraMenuOptions = nodeType.prototype.getExtraMenuOptions\r\n nodeType.prototype.convertWidgetToInput = function (widget) {\r\n const config = getConfig.call(this, widget.name) ?? [\r\n widget.type,\r\n widget.options || {}\r\n ]\r\n if (!isConvertibleWidget(widget, config)) return false\r\n convertToInput(this, widget, config)\r\n return true\r\n }\r\n nodeType.prototype.getExtraMenuOptions = function (_, options) {\r\n const r = origGetExtraMenuOptions\r\n ? origGetExtraMenuOptions.apply(this, arguments)\r\n : undefined\r\n\r\n if (this.widgets) {\r\n let toInput = []\r\n let toWidget = []\r\n for (const w of this.widgets) {\r\n if (w.options?.forceInput) {\r\n continue\r\n }\r\n if (w.type === CONVERTED_TYPE) {\r\n toWidget.push({\r\n content: `Convert ${w.name} to widget`,\r\n callback: () => convertToWidget(this, w)\r\n })\r\n } else {\r\n const config = getConfig.call(this, w.name) ?? [\r\n w.type,\r\n w.options || {}\r\n ]\r\n if (isConvertibleWidget(w, config)) {\r\n toInput.push({\r\n content: `Convert ${w.name} to input`,\r\n callback: () => convertToInput(this, w, config)\r\n })\r\n }\r\n }\r\n }\r\n\r\n //Convert.. main menu\r\n if (toInput.length) {\r\n if (useConversionSubmenusSetting.value) {\r\n options.push({\r\n content: 'Convert Widget to Input',\r\n submenu: {\r\n options: toInput\r\n }\r\n })\r\n } else {\r\n options.push(...toInput, null)\r\n }\r\n }\r\n if (toWidget.length) {\r\n if (useConversionSubmenusSetting.value) {\r\n options.push({\r\n content: 'Convert Input to Widget',\r\n submenu: {\r\n options: toWidget\r\n }\r\n })\r\n } else {\r\n options.push(...toWidget, null)\r\n }\r\n }\r\n }\r\n\r\n return r\r\n }\r\n\r\n nodeType.prototype.onGraphConfigured = function () {\r\n if (!this.inputs) return\r\n\r\n for (const input of this.inputs) {\r\n if (input.widget) {\r\n if (!input.widget[GET_CONFIG]) {\r\n input.widget[GET_CONFIG] = () =>\r\n getConfig.call(this, input.widget.name)\r\n }\r\n\r\n // Cleanup old widget config\r\n if (input.widget.config) {\r\n if (input.widget.config[0] instanceof Array) {\r\n // If we are an old converted combo then replace the input type and the stored link data\r\n input.type = 'COMBO'\r\n\r\n const link = app.graph.links[input.link]\r\n if (link) {\r\n link.type = input.type\r\n }\r\n }\r\n delete input.widget.config\r\n }\r\n\r\n const w = this.widgets.find((w) => w.name === input.widget.name)\r\n if (w) {\r\n hideWidget(this, w)\r\n } else {\r\n convertToWidget(this, input)\r\n }\r\n }\r\n }\r\n }\r\n\r\n const origOnNodeCreated = nodeType.prototype.onNodeCreated\r\n nodeType.prototype.onNodeCreated = function () {\r\n const r = origOnNodeCreated ? origOnNodeCreated.apply(this) : undefined\r\n\r\n // When node is created, convert any force/default inputs\r\n if (!app.configuringGraph && this.widgets) {\r\n for (const w of this.widgets) {\r\n if (w?.options?.forceInput || w?.options?.defaultInput) {\r\n const config = getConfig.call(this, w.name) ?? [\r\n w.type,\r\n w.options || {}\r\n ]\r\n convertToInput(this, w, config)\r\n }\r\n }\r\n }\r\n\r\n return r\r\n }\r\n\r\n const origOnConfigure = nodeType.prototype.onConfigure\r\n nodeType.prototype.onConfigure = function () {\r\n const r = origOnConfigure\r\n ? origOnConfigure.apply(this, arguments)\r\n : undefined\r\n if (!app.configuringGraph && this.inputs) {\r\n // On copy + paste of nodes, ensure that widget configs are set up\r\n for (const input of this.inputs) {\r\n if (input.widget && !input.widget[GET_CONFIG]) {\r\n input.widget[GET_CONFIG] = () =>\r\n getConfig.call(this, input.widget.name)\r\n const w = this.widgets.find((w) => w.name === input.widget.name)\r\n if (w) {\r\n hideWidget(this, w)\r\n }\r\n }\r\n }\r\n }\r\n\r\n return r\r\n }\r\n\r\n function isNodeAtPos(pos) {\r\n for (const n of app.graph._nodes) {\r\n if (n.pos[0] === pos[0] && n.pos[1] === pos[1]) {\r\n return true\r\n }\r\n }\r\n return false\r\n }\r\n\r\n // Double click a widget input to automatically attach a primitive\r\n const origOnInputDblClick = nodeType.prototype.onInputDblClick\r\n const ignoreDblClick = Symbol()\r\n nodeType.prototype.onInputDblClick = function (slot) {\r\n const r = origOnInputDblClick\r\n ? origOnInputDblClick.apply(this, arguments)\r\n : undefined\r\n\r\n const input = this.inputs[slot]\r\n if (!input.widget || !input[ignoreDblClick]) {\r\n // Not a widget input or already handled input\r\n if (\r\n !(input.type in ComfyWidgets) &&\r\n !(input.widget[GET_CONFIG]?.()?.[0] instanceof Array)\r\n ) {\r\n return r //also Not a ComfyWidgets input or combo (do nothing)\r\n }\r\n }\r\n\r\n // Create a primitive node\r\n const node = LiteGraph.createNode('PrimitiveNode')\r\n app.graph.add(node)\r\n\r\n // Calculate a position that wont directly overlap another node\r\n const pos: [number, number] = [\r\n this.pos[0] - node.size[0] - 30,\r\n this.pos[1]\r\n ]\r\n while (isNodeAtPos(pos)) {\r\n pos[1] += LiteGraph.NODE_TITLE_HEIGHT\r\n }\r\n\r\n node.pos = pos\r\n node.connect(0, this, slot)\r\n node.title = input.name\r\n\r\n // Prevent adding duplicates due to triple clicking\r\n input[ignoreDblClick] = true\r\n setTimeout(() => {\r\n delete input[ignoreDblClick]\r\n }, 300)\r\n\r\n return r\r\n }\r\n\r\n // Prevent connecting COMBO lists to converted inputs that dont match types\r\n const onConnectInput = nodeType.prototype.onConnectInput\r\n nodeType.prototype.onConnectInput = function (\r\n targetSlot,\r\n type,\r\n output,\r\n originNode,\r\n originSlot\r\n ) {\r\n const v = onConnectInput?.(this, arguments)\r\n // Not a combo, ignore\r\n if (type !== 'COMBO') return v\r\n // Primitive output, allow that to handle\r\n if (originNode.outputs[originSlot].widget) return v\r\n\r\n // Ensure target is also a combo\r\n const targetCombo = this.inputs[targetSlot].widget?.[GET_CONFIG]?.()?.[0]\r\n if (!targetCombo || !(targetCombo instanceof Array)) return v\r\n\r\n // Check they match\r\n const originConfig =\r\n originNode.constructor?.nodeData?.output?.[originSlot]\r\n if (!originConfig || !isValidCombo(targetCombo, originConfig)) {\r\n return false\r\n }\r\n\r\n return v\r\n }\r\n },\r\n registerCustomNodes() {\r\n LiteGraph.registerNodeType(\r\n 'PrimitiveNode',\r\n Object.assign(PrimitiveNode, {\r\n title: 'Primitive'\r\n })\r\n )\r\n PrimitiveNode.category = 'utils'\r\n }\r\n})\r\n","import { $el, ComfyDialog } from '../../scripts/ui'\r\nimport { DraggableList } from '../../scripts/ui/draggableList'\r\nimport { GroupNodeConfig, GroupNodeHandler } from './groupNode'\r\nimport './groupNodeManage.css'\r\nimport { app, type ComfyApp } from '../../scripts/app'\r\nimport {\r\n LiteGraph,\r\n type LGraphNode,\r\n type LGraphNodeConstructor\r\n} from '@comfyorg/litegraph'\r\n\r\nconst ORDER: symbol = Symbol()\r\n\r\nfunction merge(target, source) {\r\n if (typeof target === 'object' && typeof source === 'object') {\r\n for (const key in source) {\r\n const sv = source[key]\r\n if (typeof sv === 'object') {\r\n let tv = target[key]\r\n if (!tv) tv = target[key] = {}\r\n merge(tv, source[key])\r\n } else {\r\n target[key] = sv\r\n }\r\n }\r\n }\r\n\r\n return target\r\n}\r\n\r\nexport class ManageGroupDialog extends ComfyDialog {\r\n tabs: Record<\r\n 'Inputs' | 'Outputs' | 'Widgets',\r\n { tab: HTMLAnchorElement; page: HTMLElement }\r\n >\r\n selectedNodeIndex: number | null | undefined\r\n selectedTab: keyof ManageGroupDialog['tabs'] = 'Inputs'\r\n selectedGroup: string | undefined\r\n modifications: Record<\r\n string,\r\n Record<\r\n string,\r\n Record<\r\n string,\r\n { name?: string | undefined; visible?: boolean | undefined }\r\n >\r\n >\r\n > = {}\r\n nodeItems: any[]\r\n app: ComfyApp\r\n groupNodeType: LGraphNodeConstructor\r\n groupNodeDef: any\r\n groupData: any\r\n\r\n innerNodesList: HTMLUListElement\r\n widgetsPage: HTMLElement\r\n inputsPage: HTMLElement\r\n outputsPage: HTMLElement\r\n draggable: any\r\n\r\n get selectedNodeInnerIndex() {\r\n return +this.nodeItems[this.selectedNodeIndex].dataset.nodeindex\r\n }\r\n\r\n constructor(app) {\r\n super()\r\n this.app = app\r\n this.element = $el('dialog.comfy-group-manage', {\r\n parent: document.body\r\n }) as HTMLDialogElement\r\n }\r\n\r\n changeTab(tab) {\r\n this.tabs[this.selectedTab].tab.classList.remove('active')\r\n this.tabs[this.selectedTab].page.classList.remove('active')\r\n this.tabs[tab].tab.classList.add('active')\r\n this.tabs[tab].page.classList.add('active')\r\n this.selectedTab = tab\r\n }\r\n\r\n changeNode(index, force?) {\r\n if (!force && this.selectedNodeIndex === index) return\r\n\r\n if (this.selectedNodeIndex != null) {\r\n this.nodeItems[this.selectedNodeIndex].classList.remove('selected')\r\n }\r\n this.nodeItems[index].classList.add('selected')\r\n this.selectedNodeIndex = index\r\n\r\n if (!this.buildInputsPage() && this.selectedTab === 'Inputs') {\r\n this.changeTab('Widgets')\r\n }\r\n if (!this.buildWidgetsPage() && this.selectedTab === 'Widgets') {\r\n this.changeTab('Outputs')\r\n }\r\n if (!this.buildOutputsPage() && this.selectedTab === 'Outputs') {\r\n this.changeTab('Inputs')\r\n }\r\n\r\n this.changeTab(this.selectedTab)\r\n }\r\n\r\n getGroupData() {\r\n this.groupNodeType =\r\n LiteGraph.registered_node_types['workflow/' + this.selectedGroup]\r\n this.groupNodeDef = this.groupNodeType.nodeData\r\n this.groupData = GroupNodeHandler.getGroupData(this.groupNodeType)\r\n }\r\n\r\n changeGroup(group, reset = true) {\r\n this.selectedGroup = group\r\n this.getGroupData()\r\n\r\n const nodes = this.groupData.nodeData.nodes\r\n this.nodeItems = nodes.map((n, i) =>\r\n $el(\r\n 'li.draggable-item',\r\n {\r\n dataset: {\r\n nodeindex: n.index + ''\r\n },\r\n onclick: () => {\r\n this.changeNode(i)\r\n }\r\n },\r\n [\r\n $el('span.drag-handle'),\r\n $el(\r\n 'div',\r\n {\r\n textContent: n.title ?? n.type\r\n },\r\n n.title\r\n ? $el('span', {\r\n textContent: n.type\r\n })\r\n : []\r\n )\r\n ]\r\n )\r\n )\r\n\r\n this.innerNodesList.replaceChildren(...this.nodeItems)\r\n\r\n if (reset) {\r\n this.selectedNodeIndex = null\r\n this.changeNode(0)\r\n } else {\r\n const items = this.draggable.getAllItems()\r\n let index = items.findIndex((item) => item.classList.contains('selected'))\r\n if (index === -1) index = this.selectedNodeIndex\r\n this.changeNode(index, true)\r\n }\r\n\r\n const ordered = [...nodes]\r\n this.draggable?.dispose()\r\n this.draggable = new DraggableList(this.innerNodesList, 'li')\r\n this.draggable.addEventListener(\r\n 'dragend',\r\n ({ detail: { oldPosition, newPosition } }) => {\r\n if (oldPosition === newPosition) return\r\n ordered.splice(newPosition, 0, ordered.splice(oldPosition, 1)[0])\r\n for (let i = 0; i < ordered.length; i++) {\r\n this.storeModification({\r\n nodeIndex: ordered[i].index,\r\n section: ORDER,\r\n prop: 'order',\r\n value: i\r\n })\r\n }\r\n }\r\n )\r\n }\r\n\r\n storeModification(props: {\r\n nodeIndex?: number\r\n section: symbol\r\n prop: string\r\n value: any\r\n }) {\r\n const { nodeIndex, section, prop, value } = props\r\n const groupMod = (this.modifications[this.selectedGroup] ??= {})\r\n const nodesMod = (groupMod.nodes ??= {})\r\n const nodeMod = (nodesMod[nodeIndex ?? this.selectedNodeInnerIndex] ??= {})\r\n const typeMod = (nodeMod[section] ??= {})\r\n if (typeof value === 'object') {\r\n const objMod = (typeMod[prop] ??= {})\r\n Object.assign(objMod, value)\r\n } else {\r\n typeMod[prop] = value\r\n }\r\n }\r\n\r\n getEditElement(section, prop, value, placeholder, checked, checkable = true) {\r\n if (value === placeholder) value = ''\r\n\r\n const mods =\r\n this.modifications[this.selectedGroup]?.nodes?.[\r\n this.selectedNodeInnerIndex\r\n ]?.[section]?.[prop]\r\n if (mods) {\r\n if (mods.name != null) {\r\n value = mods.name\r\n }\r\n if (mods.visible != null) {\r\n checked = mods.visible\r\n }\r\n }\r\n\r\n return $el('div', [\r\n $el('input', {\r\n value,\r\n placeholder,\r\n type: 'text',\r\n onchange: (e) => {\r\n this.storeModification({\r\n section,\r\n prop,\r\n value: { name: e.target.value }\r\n })\r\n }\r\n }),\r\n $el('label', { textContent: 'Visible' }, [\r\n $el('input', {\r\n type: 'checkbox',\r\n checked,\r\n disabled: !checkable,\r\n onchange: (e) => {\r\n this.storeModification({\r\n section,\r\n prop,\r\n value: { visible: !!e.target.checked }\r\n })\r\n }\r\n })\r\n ])\r\n ])\r\n }\r\n\r\n buildWidgetsPage() {\r\n const widgets =\r\n this.groupData.oldToNewWidgetMap[this.selectedNodeInnerIndex]\r\n const items = Object.keys(widgets ?? {})\r\n const type = app.graph.extra.groupNodes[this.selectedGroup]\r\n const config = type.config?.[this.selectedNodeInnerIndex]?.input\r\n this.widgetsPage.replaceChildren(\r\n ...items.map((oldName) => {\r\n return this.getEditElement(\r\n 'input',\r\n oldName,\r\n widgets[oldName],\r\n oldName,\r\n config?.[oldName]?.visible !== false\r\n )\r\n })\r\n )\r\n return !!items.length\r\n }\r\n\r\n buildInputsPage() {\r\n const inputs = this.groupData.nodeInputs[this.selectedNodeInnerIndex]\r\n const items = Object.keys(inputs ?? {})\r\n const type = app.graph.extra.groupNodes[this.selectedGroup]\r\n const config = type.config?.[this.selectedNodeInnerIndex]?.input\r\n this.inputsPage.replaceChildren(\r\n ...items\r\n .map((oldName) => {\r\n let value = inputs[oldName]\r\n if (!value) {\r\n return\r\n }\r\n\r\n return this.getEditElement(\r\n 'input',\r\n oldName,\r\n value,\r\n oldName,\r\n config?.[oldName]?.visible !== false\r\n )\r\n })\r\n .filter(Boolean)\r\n )\r\n return !!items.length\r\n }\r\n\r\n buildOutputsPage() {\r\n const nodes = this.groupData.nodeData.nodes\r\n const innerNodeDef = this.groupData.getNodeDef(\r\n nodes[this.selectedNodeInnerIndex]\r\n )\r\n const outputs = innerNodeDef?.output ?? []\r\n const groupOutputs =\r\n this.groupData.oldToNewOutputMap[this.selectedNodeInnerIndex]\r\n\r\n const type = app.graph.extra.groupNodes[this.selectedGroup]\r\n const config = type.config?.[this.selectedNodeInnerIndex]?.output\r\n const node = this.groupData.nodeData.nodes[this.selectedNodeInnerIndex]\r\n const checkable = node.type !== 'PrimitiveNode'\r\n this.outputsPage.replaceChildren(\r\n ...outputs\r\n .map((type, slot) => {\r\n const groupOutputIndex = groupOutputs?.[slot]\r\n const oldName = innerNodeDef.output_name?.[slot] ?? type\r\n let value = config?.[slot]?.name\r\n const visible = config?.[slot]?.visible || groupOutputIndex != null\r\n if (!value || value === oldName) {\r\n value = ''\r\n }\r\n return this.getEditElement(\r\n 'output',\r\n slot,\r\n value,\r\n oldName,\r\n visible,\r\n checkable\r\n )\r\n })\r\n .filter(Boolean)\r\n )\r\n return !!outputs.length\r\n }\r\n\r\n show(type?) {\r\n const groupNodes = Object.keys(app.graph.extra?.groupNodes ?? {}).sort(\r\n (a, b) => a.localeCompare(b)\r\n )\r\n\r\n this.innerNodesList = $el(\r\n 'ul.comfy-group-manage-list-items'\r\n ) as HTMLUListElement\r\n this.widgetsPage = $el('section.comfy-group-manage-node-page')\r\n this.inputsPage = $el('section.comfy-group-manage-node-page')\r\n this.outputsPage = $el('section.comfy-group-manage-node-page')\r\n const pages = $el('div', [\r\n this.widgetsPage,\r\n this.inputsPage,\r\n this.outputsPage\r\n ])\r\n\r\n this.tabs = [\r\n ['Inputs', this.inputsPage],\r\n ['Widgets', this.widgetsPage],\r\n ['Outputs', this.outputsPage]\r\n ].reduce((p, [name, page]: [string, HTMLElement]) => {\r\n p[name] = {\r\n tab: $el('a', {\r\n onclick: () => {\r\n this.changeTab(name)\r\n },\r\n textContent: name\r\n }),\r\n page\r\n }\r\n return p\r\n }, {}) as any\r\n\r\n const outer = $el('div.comfy-group-manage-outer', [\r\n $el('header', [\r\n $el('h2', 'Group Nodes'),\r\n $el(\r\n 'select',\r\n {\r\n onchange: (e) => {\r\n this.changeGroup(e.target.value)\r\n }\r\n },\r\n groupNodes.map((g) =>\r\n $el('option', {\r\n textContent: g,\r\n selected: 'workflow/' + g === type,\r\n value: g\r\n })\r\n )\r\n )\r\n ]),\r\n $el('main', [\r\n $el('section.comfy-group-manage-list', this.innerNodesList),\r\n $el('section.comfy-group-manage-node', [\r\n $el(\r\n 'header',\r\n Object.values(this.tabs).map((t) => t.tab)\r\n ),\r\n pages\r\n ])\r\n ]),\r\n $el('footer', [\r\n $el(\r\n 'button.comfy-btn',\r\n {\r\n onclick: (e) => {\r\n // @ts-expect-error\r\n const node = app.graph._nodes.find(\r\n (n) => n.type === 'workflow/' + this.selectedGroup\r\n )\r\n if (node) {\r\n alert(\r\n 'This group node is in use in the current workflow, please first remove these.'\r\n )\r\n return\r\n }\r\n if (\r\n confirm(\r\n `Are you sure you want to remove the node: \"${this.selectedGroup}\"`\r\n )\r\n ) {\r\n delete app.graph.extra.groupNodes[this.selectedGroup]\r\n LiteGraph.unregisterNodeType('workflow/' + this.selectedGroup)\r\n }\r\n this.show()\r\n }\r\n },\r\n 'Delete Group Node'\r\n ),\r\n $el(\r\n 'button.comfy-btn',\r\n {\r\n onclick: async () => {\r\n let nodesByType\r\n let recreateNodes = []\r\n const types = {}\r\n for (const g in this.modifications) {\r\n const type = app.graph.extra.groupNodes[g]\r\n let config = (type.config ??= {})\r\n\r\n let nodeMods = this.modifications[g]?.nodes\r\n if (nodeMods) {\r\n const keys = Object.keys(nodeMods)\r\n if (nodeMods[keys[0]][ORDER]) {\r\n // If any node is reordered, they will all need sequencing\r\n const orderedNodes = []\r\n const orderedMods = {}\r\n const orderedConfig = {}\r\n\r\n for (const n of keys) {\r\n const order = nodeMods[n][ORDER].order\r\n orderedNodes[order] = type.nodes[+n]\r\n orderedMods[order] = nodeMods[n]\r\n orderedNodes[order].index = order\r\n }\r\n\r\n // Rewrite links\r\n for (const l of type.links) {\r\n if (l[0] != null) l[0] = type.nodes[l[0]].index\r\n if (l[2] != null) l[2] = type.nodes[l[2]].index\r\n }\r\n\r\n // Rewrite externals\r\n if (type.external) {\r\n for (const ext of type.external) {\r\n ext[0] = type.nodes[ext[0]]\r\n }\r\n }\r\n\r\n // Rewrite modifications\r\n for (const id of keys) {\r\n if (config[id]) {\r\n orderedConfig[type.nodes[id].index] = config[id]\r\n }\r\n delete config[id]\r\n }\r\n\r\n type.nodes = orderedNodes\r\n nodeMods = orderedMods\r\n type.config = config = orderedConfig\r\n }\r\n\r\n merge(config, nodeMods)\r\n }\r\n\r\n types[g] = type\r\n\r\n if (!nodesByType) {\r\n // @ts-expect-error\r\n nodesByType = app.graph._nodes.reduce((p, n) => {\r\n p[n.type] ??= []\r\n p[n.type].push(n)\r\n return p\r\n }, {})\r\n }\r\n\r\n const nodes = nodesByType['workflow/' + g]\r\n if (nodes) recreateNodes.push(...nodes)\r\n }\r\n\r\n await GroupNodeConfig.registerFromWorkflow(types, {})\r\n\r\n for (const node of recreateNodes) {\r\n node.recreate()\r\n }\r\n\r\n this.modifications = {}\r\n this.app.graph.setDirtyCanvas(true, true)\r\n this.changeGroup(this.selectedGroup, false)\r\n }\r\n },\r\n 'Save'\r\n ),\r\n $el(\r\n 'button.comfy-btn',\r\n { onclick: () => this.element.close() },\r\n 'Close'\r\n )\r\n ])\r\n ])\r\n\r\n this.element.replaceChildren(outer)\r\n this.changeGroup(\r\n type ? groupNodes.find((g) => 'workflow/' + g === type) : groupNodes[0]\r\n )\r\n this.element.showModal()\r\n\r\n this.element.addEventListener('close', () => {\r\n this.draggable?.dispose()\r\n })\r\n }\r\n}\r\n","import { app } from '../../scripts/app'\r\nimport { api } from '../../scripts/api'\r\nimport { mergeIfValid } from './widgetInputs'\r\nimport { ManageGroupDialog } from './groupNodeManage'\r\nimport type { LGraphNode } from '@comfyorg/litegraph'\r\nimport { LGraphCanvas, LiteGraph } from '@comfyorg/litegraph'\r\n\r\nconst GROUP = Symbol()\r\n\r\nconst Workflow = {\r\n InUse: {\r\n Free: 0,\r\n Registered: 1,\r\n InWorkflow: 2\r\n },\r\n isInUseGroupNode(name) {\r\n const id = `workflow/${name}`\r\n // Check if lready registered/in use in this workflow\r\n if (app.graph.extra?.groupNodes?.[name]) {\r\n // @ts-expect-error\r\n if (app.graph._nodes.find((n) => n.type === id)) {\r\n return Workflow.InUse.InWorkflow\r\n } else {\r\n return Workflow.InUse.Registered\r\n }\r\n }\r\n return Workflow.InUse.Free\r\n },\r\n storeGroupNode(name, data) {\r\n let extra = app.graph.extra\r\n if (!extra) app.graph.extra = extra = {}\r\n let groupNodes = extra.groupNodes\r\n if (!groupNodes) extra.groupNodes = groupNodes = {}\r\n groupNodes[name] = data\r\n }\r\n}\r\n\r\nclass GroupNodeBuilder {\r\n nodes: LGraphNode[]\r\n nodeData: any\r\n\r\n constructor(nodes) {\r\n this.nodes = nodes\r\n }\r\n\r\n build() {\r\n const name = this.getName()\r\n if (!name) return\r\n\r\n // Sort the nodes so they are in execution order\r\n // this allows for widgets to be in the correct order when reconstructing\r\n this.sortNodes()\r\n\r\n this.nodeData = this.getNodeData()\r\n Workflow.storeGroupNode(name, this.nodeData)\r\n\r\n return { name, nodeData: this.nodeData }\r\n }\r\n\r\n getName() {\r\n const name = prompt('Enter group name')\r\n if (!name) return\r\n const used = Workflow.isInUseGroupNode(name)\r\n switch (used) {\r\n case Workflow.InUse.InWorkflow:\r\n alert(\r\n 'An in use group node with this name already exists embedded in this workflow, please remove any instances or use a new name.'\r\n )\r\n return\r\n case Workflow.InUse.Registered:\r\n if (\r\n !confirm(\r\n 'A group node with this name already exists embedded in this workflow, are you sure you want to overwrite it?'\r\n )\r\n ) {\r\n return\r\n }\r\n break\r\n }\r\n return name\r\n }\r\n\r\n sortNodes() {\r\n // Gets the builders nodes in graph execution order\r\n const nodesInOrder = app.graph.computeExecutionOrder(false)\r\n this.nodes = this.nodes\r\n .map((node) => ({ index: nodesInOrder.indexOf(node), node }))\r\n .sort((a, b) => a.index - b.index || a.node.id - b.node.id)\r\n .map(({ node }) => node)\r\n }\r\n\r\n getNodeData() {\r\n const storeLinkTypes = (config) => {\r\n // Store link types for dynamically typed nodes e.g. reroutes\r\n for (const link of config.links) {\r\n const origin = app.graph.getNodeById(link[4])\r\n const type = origin.outputs[link[1]].type\r\n link.push(type)\r\n }\r\n }\r\n\r\n const storeExternalLinks = (config) => {\r\n // Store any external links to the group in the config so when rebuilding we add extra slots\r\n config.external = []\r\n for (let i = 0; i < this.nodes.length; i++) {\r\n const node = this.nodes[i]\r\n if (!node.outputs?.length) continue\r\n for (let slot = 0; slot < node.outputs.length; slot++) {\r\n let hasExternal = false\r\n const output = node.outputs[slot]\r\n let type = output.type\r\n if (!output.links?.length) continue\r\n for (const l of output.links) {\r\n const link = app.graph.links[l]\r\n if (!link) continue\r\n if (type === '*') type = link.type\r\n\r\n if (!app.canvas.selected_nodes[link.target_id]) {\r\n hasExternal = true\r\n break\r\n }\r\n }\r\n if (hasExternal) {\r\n config.external.push([i, slot, type])\r\n }\r\n }\r\n }\r\n }\r\n\r\n // Use the built in copyToClipboard function to generate the node data we need\r\n const backup = localStorage.getItem('litegrapheditor_clipboard')\r\n try {\r\n // @ts-expect-error\r\n // TODO Figure out if copyToClipboard is really taking this param\r\n app.canvas.copyToClipboard(this.nodes)\r\n const config = JSON.parse(\r\n localStorage.getItem('litegrapheditor_clipboard')\r\n )\r\n\r\n storeLinkTypes(config)\r\n storeExternalLinks(config)\r\n\r\n return config\r\n } finally {\r\n localStorage.setItem('litegrapheditor_clipboard', backup)\r\n }\r\n }\r\n}\r\n\r\nexport class GroupNodeConfig {\r\n name: string\r\n nodeData: any\r\n inputCount: number\r\n oldToNewOutputMap: {}\r\n newToOldOutputMap: {}\r\n oldToNewInputMap: {}\r\n oldToNewWidgetMap: {}\r\n newToOldWidgetMap: {}\r\n primitiveDefs: {}\r\n widgetToPrimitive: {}\r\n primitiveToWidget: {}\r\n nodeInputs: {}\r\n outputVisibility: any[]\r\n nodeDef: any\r\n inputs: any[]\r\n linksFrom: {}\r\n linksTo: {}\r\n externalFrom: {}\r\n\r\n constructor(name, nodeData) {\r\n this.name = name\r\n this.nodeData = nodeData\r\n this.getLinks()\r\n\r\n this.inputCount = 0\r\n this.oldToNewOutputMap = {}\r\n this.newToOldOutputMap = {}\r\n this.oldToNewInputMap = {}\r\n this.oldToNewWidgetMap = {}\r\n this.newToOldWidgetMap = {}\r\n this.primitiveDefs = {}\r\n this.widgetToPrimitive = {}\r\n this.primitiveToWidget = {}\r\n this.nodeInputs = {}\r\n this.outputVisibility = []\r\n }\r\n\r\n async registerType(source = 'workflow') {\r\n this.nodeDef = {\r\n output: [],\r\n output_name: [],\r\n output_is_list: [],\r\n output_is_hidden: [],\r\n name: source + '/' + this.name,\r\n display_name: this.name,\r\n category: 'group nodes' + ('/' + source),\r\n input: { required: {} },\r\n\r\n [GROUP]: this\r\n }\r\n\r\n this.inputs = []\r\n const seenInputs = {}\r\n const seenOutputs = {}\r\n for (let i = 0; i < this.nodeData.nodes.length; i++) {\r\n const node = this.nodeData.nodes[i]\r\n node.index = i\r\n this.processNode(node, seenInputs, seenOutputs)\r\n }\r\n\r\n for (const p of this.#convertedToProcess) {\r\n p()\r\n }\r\n this.#convertedToProcess = null\r\n await app.registerNodeDef('workflow/' + this.name, this.nodeDef)\r\n }\r\n\r\n getLinks() {\r\n this.linksFrom = {}\r\n this.linksTo = {}\r\n this.externalFrom = {}\r\n\r\n // Extract links for easy lookup\r\n for (const l of this.nodeData.links) {\r\n const [sourceNodeId, sourceNodeSlot, targetNodeId, targetNodeSlot] = l\r\n\r\n // Skip links outside the copy config\r\n if (sourceNodeId == null) continue\r\n\r\n if (!this.linksFrom[sourceNodeId]) {\r\n this.linksFrom[sourceNodeId] = {}\r\n }\r\n if (!this.linksFrom[sourceNodeId][sourceNodeSlot]) {\r\n this.linksFrom[sourceNodeId][sourceNodeSlot] = []\r\n }\r\n this.linksFrom[sourceNodeId][sourceNodeSlot].push(l)\r\n\r\n if (!this.linksTo[targetNodeId]) {\r\n this.linksTo[targetNodeId] = {}\r\n }\r\n this.linksTo[targetNodeId][targetNodeSlot] = l\r\n }\r\n\r\n if (this.nodeData.external) {\r\n for (const ext of this.nodeData.external) {\r\n if (!this.externalFrom[ext[0]]) {\r\n this.externalFrom[ext[0]] = { [ext[1]]: ext[2] }\r\n } else {\r\n this.externalFrom[ext[0]][ext[1]] = ext[2]\r\n }\r\n }\r\n }\r\n }\r\n\r\n processNode(node, seenInputs, seenOutputs) {\r\n const def = this.getNodeDef(node)\r\n if (!def) return\r\n\r\n const inputs = { ...def.input?.required, ...def.input?.optional }\r\n\r\n this.inputs.push(this.processNodeInputs(node, seenInputs, inputs))\r\n if (def.output?.length) this.processNodeOutputs(node, seenOutputs, def)\r\n }\r\n\r\n getNodeDef(node) {\r\n const def = globalDefs[node.type]\r\n if (def) return def\r\n\r\n const linksFrom = this.linksFrom[node.index]\r\n if (node.type === 'PrimitiveNode') {\r\n // Skip as its not linked\r\n if (!linksFrom) return\r\n\r\n let type = linksFrom['0'][0][5]\r\n if (type === 'COMBO') {\r\n // Use the array items\r\n const source = node.outputs[0].widget.name\r\n const fromTypeName = this.nodeData.nodes[linksFrom['0'][0][2]].type\r\n const fromType = globalDefs[fromTypeName]\r\n const input =\r\n fromType.input.required[source] ?? fromType.input.optional[source]\r\n type = input[0]\r\n }\r\n\r\n const def = (this.primitiveDefs[node.index] = {\r\n input: {\r\n required: {\r\n value: [type, {}]\r\n }\r\n },\r\n output: [type],\r\n output_name: [],\r\n output_is_list: []\r\n })\r\n return def\r\n } else if (node.type === 'Reroute') {\r\n const linksTo = this.linksTo[node.index]\r\n if (linksTo && linksFrom && !this.externalFrom[node.index]?.[0]) {\r\n // Being used internally\r\n return null\r\n }\r\n\r\n let config = {}\r\n let rerouteType = '*'\r\n if (linksFrom) {\r\n for (const [, , id, slot] of linksFrom['0']) {\r\n const node = this.nodeData.nodes[id]\r\n const input = node.inputs[slot]\r\n if (rerouteType === '*') {\r\n rerouteType = input.type\r\n }\r\n if (input.widget) {\r\n const targetDef = globalDefs[node.type]\r\n const targetWidget =\r\n targetDef.input.required[input.widget.name] ??\r\n targetDef.input.optional[input.widget.name]\r\n\r\n const widget = [targetWidget[0], config]\r\n const res = mergeIfValid(\r\n {\r\n widget\r\n },\r\n targetWidget,\r\n false,\r\n null,\r\n widget\r\n )\r\n config = res?.customConfig ?? config\r\n }\r\n }\r\n } else if (linksTo) {\r\n const [id, slot] = linksTo['0']\r\n rerouteType = this.nodeData.nodes[id].outputs[slot].type\r\n } else {\r\n // Reroute used as a pipe\r\n for (const l of this.nodeData.links) {\r\n if (l[2] === node.index) {\r\n rerouteType = l[5]\r\n break\r\n }\r\n }\r\n if (rerouteType === '*') {\r\n // Check for an external link\r\n const t = this.externalFrom[node.index]?.[0]\r\n if (t) {\r\n rerouteType = t\r\n }\r\n }\r\n }\r\n\r\n // @ts-expect-error\r\n config.forceInput = true\r\n return {\r\n input: {\r\n required: {\r\n [rerouteType]: [rerouteType, config]\r\n }\r\n },\r\n output: [rerouteType],\r\n output_name: [],\r\n output_is_list: []\r\n }\r\n }\r\n\r\n console.warn(\r\n 'Skipping virtual node ' +\r\n node.type +\r\n ' when building group node ' +\r\n this.name\r\n )\r\n }\r\n\r\n getInputConfig(node, inputName, seenInputs, config, extra?) {\r\n const customConfig = this.nodeData.config?.[node.index]?.input?.[inputName]\r\n let name =\r\n customConfig?.name ??\r\n node.inputs?.find((inp) => inp.name === inputName)?.label ??\r\n inputName\r\n let key = name\r\n let prefix = ''\r\n // Special handling for primitive to include the title if it is set rather than just \"value\"\r\n if ((node.type === 'PrimitiveNode' && node.title) || name in seenInputs) {\r\n prefix = `${node.title ?? node.type} `\r\n key = name = `${prefix}${inputName}`\r\n if (name in seenInputs) {\r\n name = `${prefix}${seenInputs[name]} ${inputName}`\r\n }\r\n }\r\n seenInputs[key] = (seenInputs[key] ?? 1) + 1\r\n\r\n if (inputName === 'seed' || inputName === 'noise_seed') {\r\n if (!extra) extra = {}\r\n extra.control_after_generate = `${prefix}control_after_generate`\r\n }\r\n if (config[0] === 'IMAGEUPLOAD') {\r\n if (!extra) extra = {}\r\n extra.widget =\r\n this.oldToNewWidgetMap[node.index]?.[config[1]?.widget ?? 'image'] ??\r\n 'image'\r\n }\r\n\r\n if (extra) {\r\n config = [config[0], { ...config[1], ...extra }]\r\n }\r\n\r\n return { name, config, customConfig }\r\n }\r\n\r\n processWidgetInputs(inputs, node, inputNames, seenInputs) {\r\n const slots = []\r\n const converted = new Map()\r\n const widgetMap = (this.oldToNewWidgetMap[node.index] = {})\r\n for (const inputName of inputNames) {\r\n let widgetType = app.getWidgetType(inputs[inputName], inputName)\r\n if (widgetType) {\r\n const convertedIndex = node.inputs?.findIndex(\r\n (inp) => inp.name === inputName && inp.widget?.name === inputName\r\n )\r\n if (convertedIndex > -1) {\r\n // This widget has been converted to a widget\r\n // We need to store this in the correct position so link ids line up\r\n converted.set(convertedIndex, inputName)\r\n widgetMap[inputName] = null\r\n } else {\r\n // Normal widget\r\n const { name, config } = this.getInputConfig(\r\n node,\r\n inputName,\r\n seenInputs,\r\n inputs[inputName]\r\n )\r\n this.nodeDef.input.required[name] = config\r\n widgetMap[inputName] = name\r\n this.newToOldWidgetMap[name] = { node, inputName }\r\n }\r\n } else {\r\n // Normal input\r\n slots.push(inputName)\r\n }\r\n }\r\n return { converted, slots }\r\n }\r\n\r\n checkPrimitiveConnection(link, inputName, inputs) {\r\n const sourceNode = this.nodeData.nodes[link[0]]\r\n if (sourceNode.type === 'PrimitiveNode') {\r\n // Merge link configurations\r\n const [sourceNodeId, _, targetNodeId, __] = link\r\n const primitiveDef = this.primitiveDefs[sourceNodeId]\r\n const targetWidget = inputs[inputName]\r\n const primitiveConfig = primitiveDef.input.required.value\r\n const output = { widget: primitiveConfig }\r\n const config = mergeIfValid(\r\n output,\r\n targetWidget,\r\n false,\r\n null,\r\n primitiveConfig\r\n )\r\n primitiveConfig[1] =\r\n config?.customConfig ?? inputs[inputName][1]\r\n ? { ...inputs[inputName][1] }\r\n : {}\r\n\r\n let name = this.oldToNewWidgetMap[sourceNodeId]['value']\r\n name = name.substr(0, name.length - 6)\r\n primitiveConfig[1].control_after_generate = true\r\n primitiveConfig[1].control_prefix = name\r\n\r\n let toPrimitive = this.widgetToPrimitive[targetNodeId]\r\n if (!toPrimitive) {\r\n toPrimitive = this.widgetToPrimitive[targetNodeId] = {}\r\n }\r\n if (toPrimitive[inputName]) {\r\n toPrimitive[inputName].push(sourceNodeId)\r\n }\r\n toPrimitive[inputName] = sourceNodeId\r\n\r\n let toWidget = this.primitiveToWidget[sourceNodeId]\r\n if (!toWidget) {\r\n toWidget = this.primitiveToWidget[sourceNodeId] = []\r\n }\r\n toWidget.push({ nodeId: targetNodeId, inputName })\r\n }\r\n }\r\n\r\n processInputSlots(inputs, node, slots, linksTo, inputMap, seenInputs) {\r\n this.nodeInputs[node.index] = {}\r\n for (let i = 0; i < slots.length; i++) {\r\n const inputName = slots[i]\r\n if (linksTo[i]) {\r\n this.checkPrimitiveConnection(linksTo[i], inputName, inputs)\r\n // This input is linked so we can skip it\r\n continue\r\n }\r\n\r\n const { name, config, customConfig } = this.getInputConfig(\r\n node,\r\n inputName,\r\n seenInputs,\r\n inputs[inputName]\r\n )\r\n\r\n this.nodeInputs[node.index][inputName] = name\r\n if (customConfig?.visible === false) continue\r\n\r\n this.nodeDef.input.required[name] = config\r\n inputMap[i] = this.inputCount++\r\n }\r\n }\r\n\r\n processConvertedWidgets(\r\n inputs,\r\n node,\r\n slots,\r\n converted,\r\n linksTo,\r\n inputMap,\r\n seenInputs\r\n ) {\r\n // Add converted widgets sorted into their index order (ordered as they were converted) so link ids match up\r\n const convertedSlots = [...converted.keys()]\r\n .sort()\r\n .map((k) => converted.get(k))\r\n for (let i = 0; i < convertedSlots.length; i++) {\r\n const inputName = convertedSlots[i]\r\n if (linksTo[slots.length + i]) {\r\n this.checkPrimitiveConnection(\r\n linksTo[slots.length + i],\r\n inputName,\r\n inputs\r\n )\r\n // This input is linked so we can skip it\r\n continue\r\n }\r\n\r\n const { name, config } = this.getInputConfig(\r\n node,\r\n inputName,\r\n seenInputs,\r\n inputs[inputName],\r\n {\r\n defaultInput: true\r\n }\r\n )\r\n\r\n this.nodeDef.input.required[name] = config\r\n this.newToOldWidgetMap[name] = { node, inputName }\r\n\r\n if (!this.oldToNewWidgetMap[node.index]) {\r\n this.oldToNewWidgetMap[node.index] = {}\r\n }\r\n this.oldToNewWidgetMap[node.index][inputName] = name\r\n\r\n inputMap[slots.length + i] = this.inputCount++\r\n }\r\n }\r\n\r\n #convertedToProcess = []\r\n processNodeInputs(node, seenInputs, inputs) {\r\n const inputMapping = []\r\n\r\n const inputNames = Object.keys(inputs)\r\n if (!inputNames.length) return\r\n\r\n const { converted, slots } = this.processWidgetInputs(\r\n inputs,\r\n node,\r\n inputNames,\r\n seenInputs\r\n )\r\n const linksTo = this.linksTo[node.index] ?? {}\r\n const inputMap = (this.oldToNewInputMap[node.index] = {})\r\n this.processInputSlots(inputs, node, slots, linksTo, inputMap, seenInputs)\r\n\r\n // Converted inputs have to be processed after all other nodes as they'll be at the end of the list\r\n this.#convertedToProcess.push(() =>\r\n this.processConvertedWidgets(\r\n inputs,\r\n node,\r\n slots,\r\n converted,\r\n linksTo,\r\n inputMap,\r\n seenInputs\r\n )\r\n )\r\n\r\n return inputMapping\r\n }\r\n\r\n processNodeOutputs(node, seenOutputs, def) {\r\n const oldToNew = (this.oldToNewOutputMap[node.index] = {})\r\n\r\n // Add outputs\r\n for (let outputId = 0; outputId < def.output.length; outputId++) {\r\n const linksFrom = this.linksFrom[node.index]\r\n // If this output is linked internally we flag it to hide\r\n const hasLink =\r\n linksFrom?.[outputId] && !this.externalFrom[node.index]?.[outputId]\r\n const customConfig =\r\n this.nodeData.config?.[node.index]?.output?.[outputId]\r\n const visible = customConfig?.visible ?? !hasLink\r\n this.outputVisibility.push(visible)\r\n if (!visible) {\r\n continue\r\n }\r\n\r\n oldToNew[outputId] = this.nodeDef.output.length\r\n this.newToOldOutputMap[this.nodeDef.output.length] = {\r\n node,\r\n slot: outputId\r\n }\r\n this.nodeDef.output.push(def.output[outputId])\r\n this.nodeDef.output_is_list.push(def.output_is_list[outputId])\r\n\r\n let label = customConfig?.name\r\n if (!label) {\r\n label = def.output_name?.[outputId] ?? def.output[outputId]\r\n const output = node.outputs.find((o) => o.name === label)\r\n if (output?.label) {\r\n label = output.label\r\n }\r\n }\r\n\r\n let name = label\r\n if (name in seenOutputs) {\r\n const prefix = `${node.title ?? node.type} `\r\n name = `${prefix}${label}`\r\n if (name in seenOutputs) {\r\n name = `${prefix}${node.index} ${label}`\r\n }\r\n }\r\n seenOutputs[name] = 1\r\n\r\n this.nodeDef.output_name.push(name)\r\n }\r\n }\r\n\r\n static async registerFromWorkflow(groupNodes, missingNodeTypes) {\r\n const clean = app.clean\r\n app.clean = function () {\r\n for (const g in groupNodes) {\r\n try {\r\n LiteGraph.unregisterNodeType('workflow/' + g)\r\n } catch (error) {}\r\n }\r\n app.clean = clean\r\n }\r\n\r\n for (const g in groupNodes) {\r\n const groupData = groupNodes[g]\r\n\r\n let hasMissing = false\r\n for (const n of groupData.nodes) {\r\n // Find missing node types\r\n if (!(n.type in LiteGraph.registered_node_types)) {\r\n missingNodeTypes.push({\r\n type: n.type,\r\n hint: ` (In group node 'workflow/${g}')`\r\n })\r\n\r\n missingNodeTypes.push({\r\n type: 'workflow/' + g,\r\n action: {\r\n text: 'Remove from workflow',\r\n callback: (e) => {\r\n delete groupNodes[g]\r\n e.target.textContent = 'Removed'\r\n e.target.style.pointerEvents = 'none'\r\n e.target.style.opacity = 0.7\r\n }\r\n }\r\n })\r\n\r\n hasMissing = true\r\n }\r\n }\r\n\r\n if (hasMissing) continue\r\n\r\n const config = new GroupNodeConfig(g, groupData)\r\n await config.registerType()\r\n }\r\n }\r\n}\r\n\r\nexport class GroupNodeHandler {\r\n node\r\n groupData\r\n innerNodes: any\r\n\r\n constructor(node) {\r\n this.node = node\r\n this.groupData = node.constructor?.nodeData?.[GROUP]\r\n\r\n this.node.setInnerNodes = (innerNodes) => {\r\n this.innerNodes = innerNodes\r\n\r\n for (\r\n let innerNodeIndex = 0;\r\n innerNodeIndex < this.innerNodes.length;\r\n innerNodeIndex++\r\n ) {\r\n const innerNode = this.innerNodes[innerNodeIndex]\r\n\r\n for (const w of innerNode.widgets ?? []) {\r\n if (w.type === 'converted-widget') {\r\n w.serializeValue = w.origSerializeValue\r\n }\r\n }\r\n\r\n innerNode.index = innerNodeIndex\r\n innerNode.getInputNode = (slot) => {\r\n // Check if this input is internal or external\r\n const externalSlot =\r\n this.groupData.oldToNewInputMap[innerNode.index]?.[slot]\r\n if (externalSlot != null) {\r\n return this.node.getInputNode(externalSlot)\r\n }\r\n\r\n // Internal link\r\n const innerLink = this.groupData.linksTo[innerNode.index]?.[slot]\r\n if (!innerLink) return null\r\n\r\n const inputNode = innerNodes[innerLink[0]]\r\n // Primitives will already apply their values\r\n if (inputNode.type === 'PrimitiveNode') return null\r\n\r\n return inputNode\r\n }\r\n\r\n innerNode.getInputLink = (slot) => {\r\n const externalSlot =\r\n this.groupData.oldToNewInputMap[innerNode.index]?.[slot]\r\n if (externalSlot != null) {\r\n // The inner node is connected via the group node inputs\r\n const linkId = this.node.inputs[externalSlot].link\r\n let link = app.graph.links[linkId]\r\n\r\n // Use the outer link, but update the target to the inner node\r\n // @ts-expect-error\r\n // TODO: Fix this\r\n link = {\r\n ...link,\r\n target_id: innerNode.id,\r\n target_slot: +slot\r\n }\r\n return link\r\n }\r\n\r\n let link = this.groupData.linksTo[innerNode.index]?.[slot]\r\n if (!link) return null\r\n // Use the inner link, but update the origin node to be inner node id\r\n link = {\r\n origin_id: innerNodes[link[0]].id,\r\n origin_slot: link[1],\r\n target_id: innerNode.id,\r\n target_slot: +slot\r\n }\r\n return link\r\n }\r\n }\r\n }\r\n\r\n this.node.updateLink = (link) => {\r\n // Replace the group node reference with the internal node\r\n link = { ...link }\r\n const output = this.groupData.newToOldOutputMap[link.origin_slot]\r\n let innerNode = this.innerNodes[output.node.index]\r\n let l\r\n while (innerNode?.type === 'Reroute') {\r\n l = innerNode.getInputLink(0)\r\n innerNode = innerNode.getInputNode(0)\r\n }\r\n\r\n if (!innerNode) {\r\n return null\r\n }\r\n\r\n if (l && GroupNodeHandler.isGroupNode(innerNode)) {\r\n return innerNode.updateLink(l)\r\n }\r\n\r\n link.origin_id = innerNode.id\r\n link.origin_slot = l?.origin_slot ?? output.slot\r\n return link\r\n }\r\n\r\n this.node.getInnerNodes = () => {\r\n if (!this.innerNodes) {\r\n this.node.setInnerNodes(\r\n this.groupData.nodeData.nodes.map((n, i) => {\r\n const innerNode = LiteGraph.createNode(n.type)\r\n innerNode.configure(n)\r\n // @ts-expect-error\r\n innerNode.id = `${this.node.id}:${i}`\r\n return innerNode\r\n })\r\n )\r\n }\r\n\r\n this.updateInnerWidgets()\r\n\r\n return this.innerNodes\r\n }\r\n\r\n this.node.recreate = async () => {\r\n const id = this.node.id\r\n const sz = this.node.size\r\n const nodes = this.node.convertToNodes()\r\n\r\n const groupNode = LiteGraph.createNode(this.node.type)\r\n groupNode.id = id\r\n\r\n // Reuse the existing nodes for this instance\r\n groupNode.setInnerNodes(nodes)\r\n groupNode[GROUP].populateWidgets()\r\n app.graph.add(groupNode)\r\n groupNode.size = [\r\n Math.max(groupNode.size[0], sz[0]),\r\n Math.max(groupNode.size[1], sz[1])\r\n ]\r\n\r\n // Remove all converted nodes and relink them\r\n groupNode[GROUP].replaceNodes(nodes)\r\n return groupNode\r\n }\r\n\r\n this.node.convertToNodes = () => {\r\n const addInnerNodes = () => {\r\n const backup = localStorage.getItem('litegrapheditor_clipboard')\r\n // Clone the node data so we dont mutate it for other nodes\r\n const c = { ...this.groupData.nodeData }\r\n c.nodes = [...c.nodes]\r\n const innerNodes = this.node.getInnerNodes()\r\n let ids = []\r\n for (let i = 0; i < c.nodes.length; i++) {\r\n let id = innerNodes?.[i]?.id\r\n // Use existing IDs if they are set on the inner nodes\r\n if (id == null || isNaN(id)) {\r\n id = undefined\r\n } else {\r\n ids.push(id)\r\n }\r\n c.nodes[i] = { ...c.nodes[i], id }\r\n }\r\n localStorage.setItem('litegrapheditor_clipboard', JSON.stringify(c))\r\n app.canvas.pasteFromClipboard()\r\n localStorage.setItem('litegrapheditor_clipboard', backup)\r\n\r\n const [x, y] = this.node.pos\r\n let top\r\n let left\r\n // Configure nodes with current widget data\r\n const selectedIds = ids.length\r\n ? ids\r\n : Object.keys(app.canvas.selected_nodes)\r\n const newNodes = []\r\n for (let i = 0; i < selectedIds.length; i++) {\r\n const id = selectedIds[i]\r\n const newNode = app.graph.getNodeById(id)\r\n const innerNode = innerNodes[i]\r\n newNodes.push(newNode)\r\n\r\n if (left == null || newNode.pos[0] < left) {\r\n left = newNode.pos[0]\r\n }\r\n if (top == null || newNode.pos[1] < top) {\r\n top = newNode.pos[1]\r\n }\r\n\r\n if (!newNode.widgets) continue\r\n\r\n const map = this.groupData.oldToNewWidgetMap[innerNode.index]\r\n if (map) {\r\n const widgets = Object.keys(map)\r\n\r\n for (const oldName of widgets) {\r\n const newName = map[oldName]\r\n if (!newName) continue\r\n\r\n const widgetIndex = this.node.widgets.findIndex(\r\n (w) => w.name === newName\r\n )\r\n if (widgetIndex === -1) continue\r\n\r\n // Populate the main and any linked widgets\r\n if (innerNode.type === 'PrimitiveNode') {\r\n for (let i = 0; i < newNode.widgets.length; i++) {\r\n newNode.widgets[i].value =\r\n this.node.widgets[widgetIndex + i].value\r\n }\r\n } else {\r\n const outerWidget = this.node.widgets[widgetIndex]\r\n const newWidget = newNode.widgets.find(\r\n (w) => w.name === oldName\r\n )\r\n if (!newWidget) continue\r\n\r\n newWidget.value = outerWidget.value\r\n for (let w = 0; w < outerWidget.linkedWidgets?.length; w++) {\r\n newWidget.linkedWidgets[w].value =\r\n outerWidget.linkedWidgets[w].value\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n // Shift each node\r\n for (const newNode of newNodes) {\r\n newNode.pos = [\r\n newNode.pos[0] - (left - x),\r\n newNode.pos[1] - (top - y)\r\n ]\r\n }\r\n\r\n return { newNodes, selectedIds }\r\n }\r\n\r\n const reconnectInputs = (selectedIds) => {\r\n for (const innerNodeIndex in this.groupData.oldToNewInputMap) {\r\n const id = selectedIds[innerNodeIndex]\r\n const newNode = app.graph.getNodeById(id)\r\n const map = this.groupData.oldToNewInputMap[innerNodeIndex]\r\n for (const innerInputId in map) {\r\n const groupSlotId = map[innerInputId]\r\n if (groupSlotId == null) continue\r\n const slot = node.inputs[groupSlotId]\r\n if (slot.link == null) continue\r\n const link = app.graph.links[slot.link]\r\n if (!link) continue\r\n // connect this node output to the input of another node\r\n const originNode = app.graph.getNodeById(link.origin_id)\r\n originNode.connect(link.origin_slot, newNode, +innerInputId)\r\n }\r\n }\r\n }\r\n\r\n const reconnectOutputs = (selectedIds) => {\r\n for (\r\n let groupOutputId = 0;\r\n groupOutputId < node.outputs?.length;\r\n groupOutputId++\r\n ) {\r\n const output = node.outputs[groupOutputId]\r\n if (!output.links) continue\r\n const links = [...output.links]\r\n for (const l of links) {\r\n const slot = this.groupData.newToOldOutputMap[groupOutputId]\r\n const link = app.graph.links[l]\r\n const targetNode = app.graph.getNodeById(link.target_id)\r\n const newNode = app.graph.getNodeById(selectedIds[slot.node.index])\r\n newNode.connect(slot.slot, targetNode, link.target_slot)\r\n }\r\n }\r\n }\r\n\r\n const { newNodes, selectedIds } = addInnerNodes()\r\n reconnectInputs(selectedIds)\r\n reconnectOutputs(selectedIds)\r\n app.graph.remove(this.node)\r\n\r\n return newNodes\r\n }\r\n\r\n const getExtraMenuOptions = this.node.getExtraMenuOptions\r\n this.node.getExtraMenuOptions = function (_, options) {\r\n getExtraMenuOptions?.apply(this, arguments)\r\n\r\n let optionIndex = options.findIndex((o) => o.content === 'Outputs')\r\n if (optionIndex === -1) optionIndex = options.length\r\n else optionIndex++\r\n options.splice(\r\n optionIndex,\r\n 0,\r\n null,\r\n {\r\n content: 'Convert to nodes',\r\n callback: () => {\r\n return this.convertToNodes()\r\n }\r\n },\r\n {\r\n content: 'Manage Group Node',\r\n callback: () => {\r\n new ManageGroupDialog(app).show(this.type)\r\n }\r\n }\r\n )\r\n }\r\n\r\n // Draw custom collapse icon to identity this as a group\r\n const onDrawTitleBox = this.node.onDrawTitleBox\r\n this.node.onDrawTitleBox = function (ctx, height, size, scale) {\r\n onDrawTitleBox?.apply(this, arguments)\r\n\r\n const fill = ctx.fillStyle\r\n ctx.beginPath()\r\n ctx.rect(11, -height + 11, 2, 2)\r\n ctx.rect(14, -height + 11, 2, 2)\r\n ctx.rect(17, -height + 11, 2, 2)\r\n ctx.rect(11, -height + 14, 2, 2)\r\n ctx.rect(14, -height + 14, 2, 2)\r\n ctx.rect(17, -height + 14, 2, 2)\r\n ctx.rect(11, -height + 17, 2, 2)\r\n ctx.rect(14, -height + 17, 2, 2)\r\n ctx.rect(17, -height + 17, 2, 2)\r\n\r\n ctx.fillStyle = this.boxcolor || LiteGraph.NODE_DEFAULT_BOXCOLOR\r\n ctx.fill()\r\n ctx.fillStyle = fill\r\n }\r\n\r\n // Draw progress label\r\n const onDrawForeground = node.onDrawForeground\r\n const groupData = this.groupData.nodeData\r\n node.onDrawForeground = function (ctx) {\r\n const r = onDrawForeground?.apply?.(this, arguments)\r\n if (\r\n +app.runningNodeId === this.id &&\r\n this.runningInternalNodeId !== null\r\n ) {\r\n const n = groupData.nodes[this.runningInternalNodeId]\r\n if (!n) return\r\n const message = `Running ${n.title || n.type} (${this.runningInternalNodeId}/${groupData.nodes.length})`\r\n ctx.save()\r\n ctx.font = '12px sans-serif'\r\n const sz = ctx.measureText(message)\r\n ctx.fillStyle = node.boxcolor || LiteGraph.NODE_DEFAULT_BOXCOLOR\r\n ctx.beginPath()\r\n ctx.roundRect(\r\n 0,\r\n -LiteGraph.NODE_TITLE_HEIGHT - 20,\r\n sz.width + 12,\r\n 20,\r\n 5\r\n )\r\n ctx.fill()\r\n\r\n ctx.fillStyle = '#fff'\r\n ctx.fillText(message, 6, -LiteGraph.NODE_TITLE_HEIGHT - 6)\r\n ctx.restore()\r\n }\r\n }\r\n\r\n // Flag this node as needing to be reset\r\n const onExecutionStart = this.node.onExecutionStart\r\n this.node.onExecutionStart = function () {\r\n this.resetExecution = true\r\n return onExecutionStart?.apply(this, arguments)\r\n }\r\n\r\n const self = this\r\n const onNodeCreated = this.node.onNodeCreated\r\n this.node.onNodeCreated = function () {\r\n if (!this.widgets) {\r\n return\r\n }\r\n const config = self.groupData.nodeData.config\r\n if (config) {\r\n for (const n in config) {\r\n const inputs = config[n]?.input\r\n for (const w in inputs) {\r\n if (inputs[w].visible !== false) continue\r\n const widgetName = self.groupData.oldToNewWidgetMap[n][w]\r\n const widget = this.widgets.find((w) => w.name === widgetName)\r\n if (widget) {\r\n widget.type = 'hidden'\r\n widget.computeSize = () => [0, -4]\r\n }\r\n }\r\n }\r\n }\r\n\r\n return onNodeCreated?.apply(this, arguments)\r\n }\r\n\r\n function handleEvent(type, getId, getEvent) {\r\n const handler = ({ detail }) => {\r\n const id = getId(detail)\r\n if (!id) return\r\n const node = app.graph.getNodeById(id)\r\n if (node) return\r\n\r\n const innerNodeIndex = this.innerNodes?.findIndex((n) => n.id == id)\r\n if (innerNodeIndex > -1) {\r\n this.node.runningInternalNodeId = innerNodeIndex\r\n api.dispatchEvent(\r\n new CustomEvent(type, {\r\n detail: getEvent(detail, this.node.id + '', this.node)\r\n })\r\n )\r\n }\r\n }\r\n api.addEventListener(type, handler)\r\n return handler\r\n }\r\n\r\n const executing = handleEvent.call(\r\n this,\r\n 'executing',\r\n (d) => d,\r\n (d, id, node) => id\r\n )\r\n\r\n const executed = handleEvent.call(\r\n this,\r\n 'executed',\r\n (d) => d?.display_node || d?.node,\r\n (d, id, node) => ({\r\n ...d,\r\n node: id,\r\n display_node: id,\r\n merge: !node.resetExecution\r\n })\r\n )\r\n\r\n const onRemoved = node.onRemoved\r\n this.node.onRemoved = function () {\r\n onRemoved?.apply(this, arguments)\r\n api.removeEventListener('executing', executing)\r\n api.removeEventListener('executed', executed)\r\n }\r\n\r\n this.node.refreshComboInNode = (defs) => {\r\n // Update combo widget options\r\n for (const widgetName in this.groupData.newToOldWidgetMap) {\r\n const widget = this.node.widgets.find((w) => w.name === widgetName)\r\n if (widget?.type === 'combo') {\r\n const old = this.groupData.newToOldWidgetMap[widgetName]\r\n const def = defs[old.node.type]\r\n const input =\r\n def?.input?.required?.[old.inputName] ??\r\n def?.input?.optional?.[old.inputName]\r\n if (!input) continue\r\n\r\n widget.options.values = input[0]\r\n\r\n if (\r\n old.inputName !== 'image' &&\r\n !widget.options.values.includes(widget.value)\r\n ) {\r\n widget.value = widget.options.values[0]\r\n widget.callback(widget.value)\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n updateInnerWidgets() {\r\n for (const newWidgetName in this.groupData.newToOldWidgetMap) {\r\n const newWidget = this.node.widgets.find((w) => w.name === newWidgetName)\r\n if (!newWidget) continue\r\n\r\n const newValue = newWidget.value\r\n const old = this.groupData.newToOldWidgetMap[newWidgetName]\r\n let innerNode = this.innerNodes[old.node.index]\r\n\r\n if (innerNode.type === 'PrimitiveNode') {\r\n innerNode.primitiveValue = newValue\r\n const primitiveLinked = this.groupData.primitiveToWidget[old.node.index]\r\n for (const linked of primitiveLinked ?? []) {\r\n const node = this.innerNodes[linked.nodeId]\r\n const widget = node.widgets.find((w) => w.name === linked.inputName)\r\n\r\n if (widget) {\r\n widget.value = newValue\r\n }\r\n }\r\n continue\r\n } else if (innerNode.type === 'Reroute') {\r\n const rerouteLinks = this.groupData.linksFrom[old.node.index]\r\n if (rerouteLinks) {\r\n for (const [_, , targetNodeId, targetSlot] of rerouteLinks['0']) {\r\n const node = this.innerNodes[targetNodeId]\r\n const input = node.inputs[targetSlot]\r\n if (input.widget) {\r\n const widget = node.widgets?.find(\r\n (w) => w.name === input.widget.name\r\n )\r\n if (widget) {\r\n widget.value = newValue\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n const widget = innerNode.widgets?.find((w) => w.name === old.inputName)\r\n if (widget) {\r\n widget.value = newValue\r\n }\r\n }\r\n }\r\n\r\n populatePrimitive(node, nodeId, oldName, i, linkedShift) {\r\n // Converted widget, populate primitive if linked\r\n const primitiveId = this.groupData.widgetToPrimitive[nodeId]?.[oldName]\r\n if (primitiveId == null) return\r\n const targetWidgetName =\r\n this.groupData.oldToNewWidgetMap[primitiveId]['value']\r\n const targetWidgetIndex = this.node.widgets.findIndex(\r\n (w) => w.name === targetWidgetName\r\n )\r\n if (targetWidgetIndex > -1) {\r\n const primitiveNode = this.innerNodes[primitiveId]\r\n let len = primitiveNode.widgets.length\r\n if (\r\n len - 1 !==\r\n this.node.widgets[targetWidgetIndex].linkedWidgets?.length\r\n ) {\r\n // Fallback handling for if some reason the primitive has a different number of widgets\r\n // we dont want to overwrite random widgets, better to leave blank\r\n len = 1\r\n }\r\n for (let i = 0; i < len; i++) {\r\n this.node.widgets[targetWidgetIndex + i].value =\r\n primitiveNode.widgets[i].value\r\n }\r\n }\r\n return true\r\n }\r\n\r\n populateReroute(node, nodeId, map) {\r\n if (node.type !== 'Reroute') return\r\n\r\n const link = this.groupData.linksFrom[nodeId]?.[0]?.[0]\r\n if (!link) return\r\n const [, , targetNodeId, targetNodeSlot] = link\r\n const targetNode = this.groupData.nodeData.nodes[targetNodeId]\r\n const inputs = targetNode.inputs\r\n const targetWidget = inputs?.[targetNodeSlot]?.widget\r\n if (!targetWidget) return\r\n\r\n const offset = inputs.length - (targetNode.widgets_values?.length ?? 0)\r\n const v = targetNode.widgets_values?.[targetNodeSlot - offset]\r\n if (v == null) return\r\n\r\n const widgetName = Object.values(map)[0]\r\n const widget = this.node.widgets.find((w) => w.name === widgetName)\r\n if (widget) {\r\n widget.value = v\r\n }\r\n }\r\n\r\n populateWidgets() {\r\n if (!this.node.widgets) return\r\n\r\n for (\r\n let nodeId = 0;\r\n nodeId < this.groupData.nodeData.nodes.length;\r\n nodeId++\r\n ) {\r\n const node = this.groupData.nodeData.nodes[nodeId]\r\n const map = this.groupData.oldToNewWidgetMap[nodeId] ?? {}\r\n const widgets = Object.keys(map)\r\n\r\n if (!node.widgets_values?.length) {\r\n // special handling for populating values into reroutes\r\n // this allows primitives connect to them to pick up the correct value\r\n this.populateReroute(node, nodeId, map)\r\n continue\r\n }\r\n\r\n let linkedShift = 0\r\n for (let i = 0; i < widgets.length; i++) {\r\n const oldName = widgets[i]\r\n const newName = map[oldName]\r\n const widgetIndex = this.node.widgets.findIndex(\r\n (w) => w.name === newName\r\n )\r\n const mainWidget = this.node.widgets[widgetIndex]\r\n if (\r\n this.populatePrimitive(node, nodeId, oldName, i, linkedShift) ||\r\n widgetIndex === -1\r\n ) {\r\n // Find the inner widget and shift by the number of linked widgets as they will have been removed too\r\n const innerWidget = this.innerNodes[nodeId].widgets?.find(\r\n (w) => w.name === oldName\r\n )\r\n linkedShift += innerWidget?.linkedWidgets?.length ?? 0\r\n }\r\n if (widgetIndex === -1) {\r\n continue\r\n }\r\n\r\n // Populate the main and any linked widget\r\n mainWidget.value = node.widgets_values[i + linkedShift]\r\n for (let w = 0; w < mainWidget.linkedWidgets?.length; w++) {\r\n this.node.widgets[widgetIndex + w + 1].value =\r\n node.widgets_values[i + ++linkedShift]\r\n }\r\n }\r\n }\r\n }\r\n\r\n replaceNodes(nodes) {\r\n let top\r\n let left\r\n\r\n for (let i = 0; i < nodes.length; i++) {\r\n const node = nodes[i]\r\n if (left == null || node.pos[0] < left) {\r\n left = node.pos[0]\r\n }\r\n if (top == null || node.pos[1] < top) {\r\n top = node.pos[1]\r\n }\r\n\r\n this.linkOutputs(node, i)\r\n app.graph.remove(node)\r\n }\r\n\r\n this.linkInputs()\r\n this.node.pos = [left, top]\r\n }\r\n\r\n linkOutputs(originalNode, nodeId) {\r\n if (!originalNode.outputs) return\r\n\r\n for (const output of originalNode.outputs) {\r\n if (!output.links) continue\r\n // Clone the links as they'll be changed if we reconnect\r\n const links = [...output.links]\r\n for (const l of links) {\r\n const link = app.graph.links[l]\r\n if (!link) continue\r\n\r\n const targetNode = app.graph.getNodeById(link.target_id)\r\n const newSlot =\r\n this.groupData.oldToNewOutputMap[nodeId]?.[link.origin_slot]\r\n if (newSlot != null) {\r\n this.node.connect(newSlot, targetNode, link.target_slot)\r\n }\r\n }\r\n }\r\n }\r\n\r\n linkInputs() {\r\n for (const link of this.groupData.nodeData.links ?? []) {\r\n const [, originSlot, targetId, targetSlot, actualOriginId] = link\r\n const originNode = app.graph.getNodeById(actualOriginId)\r\n if (!originNode) continue // this node is in the group\r\n originNode.connect(\r\n originSlot,\r\n this.node.id,\r\n this.groupData.oldToNewInputMap[targetId][targetSlot]\r\n )\r\n }\r\n }\r\n\r\n static getGroupData(node) {\r\n return (node.nodeData ?? node.constructor?.nodeData)?.[GROUP]\r\n }\r\n\r\n static isGroupNode(node) {\r\n return !!node.constructor?.nodeData?.[GROUP]\r\n }\r\n\r\n static async fromNodes(nodes) {\r\n // Process the nodes into the stored workflow group node data\r\n const builder = new GroupNodeBuilder(nodes)\r\n const res = builder.build()\r\n if (!res) return\r\n\r\n const { name, nodeData } = res\r\n\r\n // Convert this data into a LG node definition and register it\r\n const config = new GroupNodeConfig(name, nodeData)\r\n await config.registerType()\r\n\r\n const groupNode = LiteGraph.createNode(`workflow/${name}`)\r\n // Reuse the existing nodes for this instance\r\n groupNode.setInnerNodes(builder.nodes)\r\n groupNode[GROUP].populateWidgets()\r\n app.graph.add(groupNode)\r\n\r\n // Remove all converted nodes and relink them\r\n groupNode[GROUP].replaceNodes(builder.nodes)\r\n return groupNode\r\n }\r\n}\r\n\r\nfunction addConvertToGroupOptions() {\r\n function addConvertOption(options, index) {\r\n const selected = Object.values(app.canvas.selected_nodes ?? {})\r\n const disabled =\r\n selected.length < 2 ||\r\n selected.find((n) => GroupNodeHandler.isGroupNode(n))\r\n options.splice(index + 1, null, {\r\n content: `Convert to Group Node`,\r\n disabled,\r\n callback: async () => {\r\n return await GroupNodeHandler.fromNodes(selected)\r\n }\r\n })\r\n }\r\n\r\n function addManageOption(options, index) {\r\n const groups = app.graph.extra?.groupNodes\r\n const disabled = !groups || !Object.keys(groups).length\r\n options.splice(index + 1, null, {\r\n content: `Manage Group Nodes`,\r\n disabled,\r\n callback: () => {\r\n new ManageGroupDialog(app).show()\r\n }\r\n })\r\n }\r\n\r\n // Add to canvas\r\n const getCanvasMenuOptions = LGraphCanvas.prototype.getCanvasMenuOptions\r\n LGraphCanvas.prototype.getCanvasMenuOptions = function () {\r\n const options = getCanvasMenuOptions.apply(this, arguments)\r\n const index =\r\n options.findIndex((o) => o?.content === 'Add Group') + 1 || options.length\r\n addConvertOption(options, index)\r\n addManageOption(options, index + 1)\r\n return options\r\n }\r\n\r\n // Add to nodes\r\n const getNodeMenuOptions = LGraphCanvas.prototype.getNodeMenuOptions\r\n LGraphCanvas.prototype.getNodeMenuOptions = function (node) {\r\n const options = getNodeMenuOptions.apply(this, arguments)\r\n if (!GroupNodeHandler.isGroupNode(node)) {\r\n const index =\r\n options.findIndex((o) => o?.content === 'Outputs') + 1 ||\r\n options.length - 1\r\n addConvertOption(options, index)\r\n }\r\n return options\r\n }\r\n}\r\n\r\nconst id = 'Comfy.GroupNode'\r\nlet globalDefs\r\nconst ext = {\r\n name: id,\r\n setup() {\r\n addConvertToGroupOptions()\r\n },\r\n async beforeConfigureGraph(graphData, missingNodeTypes) {\r\n const nodes = graphData?.extra?.groupNodes\r\n if (nodes) {\r\n await GroupNodeConfig.registerFromWorkflow(nodes, missingNodeTypes)\r\n }\r\n },\r\n addCustomNodeDefs(defs) {\r\n // Store this so we can mutate it later with group nodes\r\n globalDefs = defs\r\n },\r\n nodeCreated(node) {\r\n if (GroupNodeHandler.isGroupNode(node)) {\r\n node[GROUP] = new GroupNodeHandler(node)\r\n }\r\n },\r\n async refreshComboInNodes(defs) {\r\n // Re-register group nodes so new ones are created with the correct options\r\n Object.assign(globalDefs, defs)\r\n const nodes = app.graph.extra?.groupNodes\r\n if (nodes) {\r\n await GroupNodeConfig.registerFromWorkflow(nodes, {})\r\n }\r\n }\r\n}\r\n\r\napp.registerExtension(ext)\r\n","import { app } from '../../scripts/app'\r\nimport { LGraphCanvas, LiteGraph } from '@comfyorg/litegraph'\r\n\r\nfunction setNodeMode(node, mode) {\r\n node.mode = mode\r\n node.graph.change()\r\n}\r\n\r\nfunction addNodesToGroup(group, nodes = []) {\r\n var x1, y1, x2, y2\r\n var nx1, ny1, nx2, ny2\r\n var node\r\n\r\n x1 = y1 = x2 = y2 = -1\r\n nx1 = ny1 = nx2 = ny2 = -1\r\n\r\n for (var n of [group._nodes, nodes]) {\r\n for (var i in n) {\r\n node = n[i]\r\n\r\n nx1 = node.pos[0]\r\n ny1 = node.pos[1]\r\n nx2 = node.pos[0] + node.size[0]\r\n ny2 = node.pos[1] + node.size[1]\r\n\r\n if (node.type != 'Reroute') {\r\n ny1 -= LiteGraph.NODE_TITLE_HEIGHT\r\n }\r\n\r\n if (node.flags?.collapsed) {\r\n ny2 = ny1 + LiteGraph.NODE_TITLE_HEIGHT\r\n\r\n if (node?._collapsed_width) {\r\n nx2 = nx1 + Math.round(node._collapsed_width)\r\n }\r\n }\r\n\r\n if (x1 == -1 || nx1 < x1) {\r\n x1 = nx1\r\n }\r\n\r\n if (y1 == -1 || ny1 < y1) {\r\n y1 = ny1\r\n }\r\n\r\n if (x2 == -1 || nx2 > x2) {\r\n x2 = nx2\r\n }\r\n\r\n if (y2 == -1 || ny2 > y2) {\r\n y2 = ny2\r\n }\r\n }\r\n }\r\n\r\n var padding = 10\r\n\r\n y1 = y1 - Math.round(group.font_size * 1.4)\r\n\r\n group.pos = [x1 - padding, y1 - padding]\r\n group.size = [x2 - x1 + padding * 2, y2 - y1 + padding * 2]\r\n}\r\n\r\napp.registerExtension({\r\n name: 'Comfy.GroupOptions',\r\n setup() {\r\n const orig = LGraphCanvas.prototype.getCanvasMenuOptions\r\n // graph_mouse\r\n LGraphCanvas.prototype.getCanvasMenuOptions = function () {\r\n const options = orig.apply(this, arguments)\r\n const group = this.graph.getGroupOnPos(\r\n this.graph_mouse[0],\r\n this.graph_mouse[1]\r\n )\r\n if (!group) {\r\n options.push({\r\n content: 'Add Group For Selected Nodes',\r\n disabled: !Object.keys(app.canvas.selected_nodes || {}).length,\r\n callback: () => {\r\n // @ts-expect-error\r\n var group = new LiteGraph.LGraphGroup()\r\n addNodesToGroup(group, this.selected_nodes)\r\n app.canvas.graph.add(group)\r\n this.graph.change()\r\n }\r\n })\r\n\r\n return options\r\n }\r\n\r\n // Group nodes aren't recomputed until the group is moved, this ensures the nodes are up-to-date\r\n group.recomputeInsideNodes()\r\n const nodesInGroup = group._nodes\r\n\r\n options.push({\r\n content: 'Add Selected Nodes To Group',\r\n disabled: !Object.keys(app.canvas.selected_nodes || {}).length,\r\n callback: () => {\r\n addNodesToGroup(group, this.selected_nodes)\r\n this.graph.change()\r\n }\r\n })\r\n\r\n // No nodes in group, return default options\r\n if (nodesInGroup.length === 0) {\r\n return options\r\n } else {\r\n // Add a separator between the default options and the group options\r\n options.push(null)\r\n }\r\n\r\n // Check if all nodes are the same mode\r\n let allNodesAreSameMode = true\r\n for (let i = 1; i < nodesInGroup.length; i++) {\r\n if (nodesInGroup[i].mode !== nodesInGroup[0].mode) {\r\n allNodesAreSameMode = false\r\n break\r\n }\r\n }\r\n\r\n options.push({\r\n content: 'Fit Group To Nodes',\r\n callback: () => {\r\n addNodesToGroup(group)\r\n this.graph.change()\r\n }\r\n })\r\n\r\n options.push({\r\n content: 'Select Nodes',\r\n callback: () => {\r\n this.selectNodes(nodesInGroup)\r\n this.graph.change()\r\n this.canvas.focus()\r\n }\r\n })\r\n\r\n // Modes\r\n // 0: Always\r\n // 1: On Event\r\n // 2: Never\r\n // 3: On Trigger\r\n // 4: Bypass\r\n // If all nodes are the same mode, add a menu option to change the mode\r\n if (allNodesAreSameMode) {\r\n const mode = nodesInGroup[0].mode\r\n switch (mode) {\r\n case 0:\r\n // All nodes are always, option to disable, and bypass\r\n options.push({\r\n content: 'Set Group Nodes to Never',\r\n callback: () => {\r\n for (const node of nodesInGroup) {\r\n setNodeMode(node, 2)\r\n }\r\n }\r\n })\r\n options.push({\r\n content: 'Bypass Group Nodes',\r\n callback: () => {\r\n for (const node of nodesInGroup) {\r\n setNodeMode(node, 4)\r\n }\r\n }\r\n })\r\n break\r\n case 2:\r\n // All nodes are never, option to enable, and bypass\r\n options.push({\r\n content: 'Set Group Nodes to Always',\r\n callback: () => {\r\n for (const node of nodesInGroup) {\r\n setNodeMode(node, 0)\r\n }\r\n }\r\n })\r\n options.push({\r\n content: 'Bypass Group Nodes',\r\n callback: () => {\r\n for (const node of nodesInGroup) {\r\n setNodeMode(node, 4)\r\n }\r\n }\r\n })\r\n break\r\n case 4:\r\n // All nodes are bypass, option to enable, and disable\r\n options.push({\r\n content: 'Set Group Nodes to Always',\r\n callback: () => {\r\n for (const node of nodesInGroup) {\r\n setNodeMode(node, 0)\r\n }\r\n }\r\n })\r\n options.push({\r\n content: 'Set Group Nodes to Never',\r\n callback: () => {\r\n for (const node of nodesInGroup) {\r\n setNodeMode(node, 2)\r\n }\r\n }\r\n })\r\n break\r\n default:\r\n // All nodes are On Trigger or On Event(Or other?), option to disable, set to always, or bypass\r\n options.push({\r\n content: 'Set Group Nodes to Always',\r\n callback: () => {\r\n for (const node of nodesInGroup) {\r\n setNodeMode(node, 0)\r\n }\r\n }\r\n })\r\n options.push({\r\n content: 'Set Group Nodes to Never',\r\n callback: () => {\r\n for (const node of nodesInGroup) {\r\n setNodeMode(node, 2)\r\n }\r\n }\r\n })\r\n options.push({\r\n content: 'Bypass Group Nodes',\r\n callback: () => {\r\n for (const node of nodesInGroup) {\r\n setNodeMode(node, 4)\r\n }\r\n }\r\n })\r\n break\r\n }\r\n } else {\r\n // Nodes are not all the same mode, add a menu option to change the mode to always, never, or bypass\r\n options.push({\r\n content: 'Set Group Nodes to Always',\r\n callback: () => {\r\n for (const node of nodesInGroup) {\r\n setNodeMode(node, 0)\r\n }\r\n }\r\n })\r\n options.push({\r\n content: 'Set Group Nodes to Never',\r\n callback: () => {\r\n for (const node of nodesInGroup) {\r\n setNodeMode(node, 2)\r\n }\r\n }\r\n })\r\n options.push({\r\n content: 'Bypass Group Nodes',\r\n callback: () => {\r\n for (const node of nodesInGroup) {\r\n setNodeMode(node, 4)\r\n }\r\n }\r\n })\r\n }\r\n\r\n return options\r\n }\r\n }\r\n})\r\n","import { LiteGraph } from '@comfyorg/litegraph'\r\nimport { app } from '../../scripts/app'\r\n\r\n// Inverts the scrolling of context menus\r\n\r\nconst id = 'Comfy.InvertMenuScrolling'\r\napp.registerExtension({\r\n name: id,\r\n init() {\r\n const ctxMenu = LiteGraph.ContextMenu\r\n const replace = () => {\r\n // @ts-expect-error\r\n LiteGraph.ContextMenu = function (values, options) {\r\n options = options || {}\r\n if (options.scroll_speed) {\r\n options.scroll_speed *= -1\r\n } else {\r\n options.scroll_speed = -0.1\r\n }\r\n return ctxMenu.call(this, values, options)\r\n }\r\n LiteGraph.ContextMenu.prototype = ctxMenu.prototype\r\n }\r\n app.ui.settings.addSetting({\r\n id,\r\n name: 'Invert Menu Scrolling',\r\n type: 'boolean',\r\n defaultValue: false,\r\n onChange(value) {\r\n if (value) {\r\n replace()\r\n } else {\r\n LiteGraph.ContextMenu = ctxMenu\r\n }\r\n }\r\n })\r\n }\r\n})\r\n","import { app } from '../../scripts/app'\r\nimport { api } from '../../scripts/api'\r\n\r\napp.registerExtension({\r\n name: 'Comfy.Keybinds',\r\n init() {\r\n const keybindListener = function (event) {\r\n const modifierPressed = event.ctrlKey || event.metaKey\r\n\r\n // Queue prompt using (ctrl or command) + enter\r\n if (modifierPressed && event.key === 'Enter') {\r\n // Cancel current prompt using (ctrl or command) + alt + enter\r\n if (event.altKey) {\r\n api.interrupt()\r\n return\r\n }\r\n // Queue prompt as first for generation using (ctrl or command) + shift + enter\r\n app.queuePrompt(event.shiftKey ? -1 : 0).then()\r\n return\r\n }\r\n\r\n const target = event.composedPath()[0]\r\n if (['INPUT', 'TEXTAREA'].includes(target.tagName)) {\r\n return\r\n }\r\n\r\n const modifierKeyIdMap = {\r\n s: '#comfy-save-button',\r\n o: '#comfy-file-input',\r\n Backspace: '#comfy-clear-button',\r\n d: '#comfy-load-default-button'\r\n }\r\n\r\n const modifierKeybindId = modifierKeyIdMap[event.key]\r\n if (modifierPressed && modifierKeybindId) {\r\n event.preventDefault()\r\n\r\n const elem = document.querySelector(modifierKeybindId)\r\n elem.click()\r\n return\r\n }\r\n\r\n // Finished Handling all modifier keybinds, now handle the rest\r\n if (event.ctrlKey || event.altKey || event.metaKey) {\r\n return\r\n }\r\n\r\n // Close out of modals using escape\r\n if (event.key === 'Escape') {\r\n const modals = document.querySelectorAll('.comfy-modal')\r\n const modal = Array.from(modals).find(\r\n (modal) =>\r\n window.getComputedStyle(modal).getPropertyValue('display') !==\r\n 'none'\r\n )\r\n if (modal) {\r\n modal.style.display = 'none'\r\n }\r\n\r\n ;[...document.querySelectorAll('dialog')].forEach((d) => {\r\n d.close()\r\n })\r\n }\r\n\r\n const keyIdMap = {\r\n q: '.queue-tab-button.side-bar-button',\r\n h: '.queue-tab-button.side-bar-button',\r\n r: '#comfy-refresh-button'\r\n }\r\n\r\n const buttonId = keyIdMap[event.key]\r\n if (buttonId) {\r\n const button = document.querySelector(buttonId)\r\n button.click()\r\n }\r\n }\r\n\r\n window.addEventListener('keydown', keybindListener, true)\r\n }\r\n})\r\n","import { app } from '../../scripts/app'\r\nimport { LiteGraph } from '@comfyorg/litegraph'\r\nconst id = 'Comfy.LinkRenderMode'\r\nconst ext = {\r\n name: id,\r\n async setup(app) {\r\n app.ui.settings.addSetting({\r\n id,\r\n name: 'Link Render Mode',\r\n defaultValue: 2,\r\n type: 'combo',\r\n // @ts-expect-error\r\n options: [...LiteGraph.LINK_RENDER_MODES, 'Hidden'].map((m, i) => ({\r\n value: i,\r\n text: m,\r\n selected: i == app.canvas.links_render_mode\r\n })),\r\n onChange(value) {\r\n app.canvas.links_render_mode = +value\r\n app.graph.setDirtyCanvas(true)\r\n }\r\n })\r\n }\r\n}\r\n\r\napp.registerExtension(ext)\r\n","import { app } from '../../scripts/app'\r\nimport { ComfyDialog, $el } from '../../scripts/ui'\r\nimport { ComfyApp } from '../../scripts/app'\r\nimport { api } from '../../scripts/api'\r\nimport { ClipspaceDialog } from './clipspace'\r\n\r\n// Helper function to convert a data URL to a Blob object\r\nfunction dataURLToBlob(dataURL) {\r\n const parts = dataURL.split(';base64,')\r\n const contentType = parts[0].split(':')[1]\r\n const byteString = atob(parts[1])\r\n const arrayBuffer = new ArrayBuffer(byteString.length)\r\n const uint8Array = new Uint8Array(arrayBuffer)\r\n for (let i = 0; i < byteString.length; i++) {\r\n uint8Array[i] = byteString.charCodeAt(i)\r\n }\r\n return new Blob([arrayBuffer], { type: contentType })\r\n}\r\n\r\nfunction loadedImageToBlob(image) {\r\n const canvas = document.createElement('canvas')\r\n\r\n canvas.width = image.width\r\n canvas.height = image.height\r\n\r\n const ctx = canvas.getContext('2d')\r\n\r\n ctx.drawImage(image, 0, 0)\r\n\r\n const dataURL = canvas.toDataURL('image/png', 1)\r\n const blob = dataURLToBlob(dataURL)\r\n\r\n return blob\r\n}\r\n\r\nfunction loadImage(imagePath) {\r\n return new Promise((resolve, reject) => {\r\n const image = new Image()\r\n\r\n image.onload = function () {\r\n resolve(image)\r\n }\r\n\r\n image.src = imagePath\r\n })\r\n}\r\n\r\nasync function uploadMask(filepath, formData) {\r\n await api\r\n .fetchApi('/upload/mask', {\r\n method: 'POST',\r\n body: formData\r\n })\r\n .then((response) => {})\r\n .catch((error) => {\r\n console.error('Error:', error)\r\n })\r\n\r\n ComfyApp.clipspace.imgs[ComfyApp.clipspace['selectedIndex']] = new Image()\r\n ComfyApp.clipspace.imgs[ComfyApp.clipspace['selectedIndex']].src = api.apiURL(\r\n '/view?' +\r\n new URLSearchParams(filepath).toString() +\r\n app.getPreviewFormatParam() +\r\n app.getRandParam()\r\n )\r\n\r\n if (ComfyApp.clipspace.images)\r\n ComfyApp.clipspace.images[ComfyApp.clipspace['selectedIndex']] = filepath\r\n\r\n ClipspaceDialog.invalidatePreview()\r\n}\r\n\r\nfunction prepare_mask(image, maskCanvas, maskCtx, maskColor) {\r\n // paste mask data into alpha channel\r\n maskCtx.drawImage(image, 0, 0, maskCanvas.width, maskCanvas.height)\r\n const maskData = maskCtx.getImageData(\r\n 0,\r\n 0,\r\n maskCanvas.width,\r\n maskCanvas.height\r\n )\r\n\r\n // invert mask\r\n for (let i = 0; i < maskData.data.length; i += 4) {\r\n if (maskData.data[i + 3] == 255) maskData.data[i + 3] = 0\r\n else maskData.data[i + 3] = 255\r\n\r\n maskData.data[i] = maskColor.r\r\n maskData.data[i + 1] = maskColor.g\r\n maskData.data[i + 2] = maskColor.b\r\n }\r\n\r\n maskCtx.globalCompositeOperation = 'source-over'\r\n maskCtx.putImageData(maskData, 0, 0)\r\n}\r\n\r\nclass MaskEditorDialog extends ComfyDialog {\r\n static instance = null\r\n static mousedown_x: number | null = null\r\n static mousedown_y: number | null = null\r\n\r\n brush: HTMLDivElement\r\n maskCtx: any\r\n maskCanvas: HTMLCanvasElement\r\n brush_size_slider: HTMLDivElement\r\n brush_opacity_slider: HTMLDivElement\r\n colorButton: HTMLButtonElement\r\n saveButton: HTMLButtonElement\r\n zoom_ratio: number\r\n pan_x: number\r\n pan_y: number\r\n imgCanvas: HTMLCanvasElement\r\n last_display_style: string\r\n is_visible: boolean\r\n image: HTMLImageElement\r\n handler_registered: boolean\r\n brush_slider_input: HTMLInputElement\r\n cursorX: number\r\n cursorY: number\r\n mousedown_pan_x: number\r\n mousedown_pan_y: number\r\n last_pressure: number\r\n\r\n static getInstance() {\r\n if (!MaskEditorDialog.instance) {\r\n MaskEditorDialog.instance = new MaskEditorDialog()\r\n }\r\n\r\n return MaskEditorDialog.instance\r\n }\r\n\r\n is_layout_created = false\r\n\r\n constructor() {\r\n super()\r\n this.element = $el('div.comfy-modal', { parent: document.body }, [\r\n $el('div.comfy-modal-content', [...this.createButtons()])\r\n ])\r\n }\r\n\r\n createButtons() {\r\n return []\r\n }\r\n\r\n createButton(name, callback): HTMLButtonElement {\r\n var button = document.createElement('button')\r\n button.style.pointerEvents = 'auto'\r\n button.innerText = name\r\n button.addEventListener('click', callback)\r\n return button\r\n }\r\n\r\n createLeftButton(name, callback) {\r\n var button = this.createButton(name, callback)\r\n button.style.cssFloat = 'left'\r\n button.style.marginRight = '4px'\r\n return button\r\n }\r\n\r\n createRightButton(name, callback) {\r\n var button = this.createButton(name, callback)\r\n button.style.cssFloat = 'right'\r\n button.style.marginLeft = '4px'\r\n return button\r\n }\r\n\r\n createLeftSlider(self, name, callback): HTMLDivElement {\r\n const divElement = document.createElement('div')\r\n divElement.id = 'maskeditor-slider'\r\n divElement.style.cssFloat = 'left'\r\n divElement.style.fontFamily = 'sans-serif'\r\n divElement.style.marginRight = '4px'\r\n divElement.style.color = 'var(--input-text)'\r\n divElement.style.backgroundColor = 'var(--comfy-input-bg)'\r\n divElement.style.borderRadius = '8px'\r\n divElement.style.borderColor = 'var(--border-color)'\r\n divElement.style.borderStyle = 'solid'\r\n divElement.style.fontSize = '15px'\r\n divElement.style.height = '21px'\r\n divElement.style.padding = '1px 6px'\r\n divElement.style.display = 'flex'\r\n divElement.style.position = 'relative'\r\n divElement.style.top = '2px'\r\n divElement.style.pointerEvents = 'auto'\r\n self.brush_slider_input = document.createElement('input')\r\n self.brush_slider_input.setAttribute('type', 'range')\r\n self.brush_slider_input.setAttribute('min', '1')\r\n self.brush_slider_input.setAttribute('max', '100')\r\n self.brush_slider_input.setAttribute('value', '10')\r\n const labelElement = document.createElement('label')\r\n labelElement.textContent = name\r\n\r\n divElement.appendChild(labelElement)\r\n divElement.appendChild(self.brush_slider_input)\r\n\r\n self.brush_slider_input.addEventListener('change', callback)\r\n\r\n return divElement\r\n }\r\n\r\n createOpacitySlider(self, name, callback): HTMLDivElement {\r\n const divElement = document.createElement('div')\r\n divElement.id = 'maskeditor-opacity-slider'\r\n divElement.style.cssFloat = 'left'\r\n divElement.style.fontFamily = 'sans-serif'\r\n divElement.style.marginRight = '4px'\r\n divElement.style.color = 'var(--input-text)'\r\n divElement.style.backgroundColor = 'var(--comfy-input-bg)'\r\n divElement.style.borderRadius = '8px'\r\n divElement.style.borderColor = 'var(--border-color)'\r\n divElement.style.borderStyle = 'solid'\r\n divElement.style.fontSize = '15px'\r\n divElement.style.height = '21px'\r\n divElement.style.padding = '1px 6px'\r\n divElement.style.display = 'flex'\r\n divElement.style.position = 'relative'\r\n divElement.style.top = '2px'\r\n divElement.style.pointerEvents = 'auto'\r\n self.opacity_slider_input = document.createElement('input')\r\n self.opacity_slider_input.setAttribute('type', 'range')\r\n self.opacity_slider_input.setAttribute('min', '0.1')\r\n self.opacity_slider_input.setAttribute('max', '1.0')\r\n self.opacity_slider_input.setAttribute('step', '0.01')\r\n self.opacity_slider_input.setAttribute('value', '0.7')\r\n const labelElement = document.createElement('label')\r\n labelElement.textContent = name\r\n\r\n divElement.appendChild(labelElement)\r\n divElement.appendChild(self.opacity_slider_input)\r\n\r\n self.opacity_slider_input.addEventListener('input', callback)\r\n\r\n return divElement\r\n }\r\n\r\n setlayout(imgCanvas: HTMLCanvasElement, maskCanvas: HTMLCanvasElement) {\r\n const self = this\r\n\r\n // If it is specified as relative, using it only as a hidden placeholder for padding is recommended\r\n // to prevent anomalies where it exceeds a certain size and goes outside of the window.\r\n var bottom_panel = document.createElement('div')\r\n bottom_panel.style.position = 'absolute'\r\n bottom_panel.style.bottom = '0px'\r\n bottom_panel.style.left = '20px'\r\n bottom_panel.style.right = '20px'\r\n bottom_panel.style.height = '50px'\r\n bottom_panel.style.pointerEvents = 'none'\r\n\r\n var brush = document.createElement('div')\r\n brush.id = 'brush'\r\n brush.style.backgroundColor = 'transparent'\r\n brush.style.outline = '1px dashed black'\r\n brush.style.boxShadow = '0 0 0 1px white'\r\n brush.style.borderRadius = '50%'\r\n // @ts-expect-error\r\n brush.style.MozBorderRadius = '50%'\r\n // @ts-expect-error\r\n brush.style.WebkitBorderRadius = '50%'\r\n brush.style.position = 'absolute'\r\n brush.style.zIndex = '8889'\r\n brush.style.pointerEvents = 'none'\r\n this.brush = brush\r\n this.element.appendChild(imgCanvas)\r\n this.element.appendChild(maskCanvas)\r\n this.element.appendChild(bottom_panel)\r\n document.body.appendChild(brush)\r\n\r\n var clearButton = this.createLeftButton('Clear', () => {\r\n self.maskCtx.clearRect(\r\n 0,\r\n 0,\r\n self.maskCanvas.width,\r\n self.maskCanvas.height\r\n )\r\n })\r\n\r\n this.brush_size_slider = this.createLeftSlider(\r\n self,\r\n 'Thickness',\r\n (event) => {\r\n self.brush_size = event.target.value\r\n self.updateBrushPreview(self)\r\n }\r\n )\r\n\r\n this.brush_opacity_slider = this.createOpacitySlider(\r\n self,\r\n 'Opacity',\r\n (event) => {\r\n self.brush_opacity = event.target.value\r\n if (self.brush_color_mode !== 'negative') {\r\n self.maskCanvas.style.opacity = self.brush_opacity.toString()\r\n }\r\n }\r\n )\r\n\r\n this.colorButton = this.createLeftButton(this.getColorButtonText(), () => {\r\n if (self.brush_color_mode === 'black') {\r\n self.brush_color_mode = 'white'\r\n } else if (self.brush_color_mode === 'white') {\r\n self.brush_color_mode = 'negative'\r\n } else {\r\n self.brush_color_mode = 'black'\r\n }\r\n\r\n self.updateWhenBrushColorModeChanged()\r\n })\r\n\r\n var cancelButton = this.createRightButton('Cancel', () => {\r\n document.removeEventListener('keydown', MaskEditorDialog.handleKeyDown)\r\n self.close()\r\n })\r\n\r\n this.saveButton = this.createRightButton('Save', () => {\r\n document.removeEventListener('keydown', MaskEditorDialog.handleKeyDown)\r\n self.save()\r\n })\r\n\r\n this.element.appendChild(imgCanvas)\r\n this.element.appendChild(maskCanvas)\r\n this.element.appendChild(bottom_panel)\r\n\r\n bottom_panel.appendChild(clearButton)\r\n bottom_panel.appendChild(this.saveButton)\r\n bottom_panel.appendChild(cancelButton)\r\n bottom_panel.appendChild(this.brush_size_slider)\r\n bottom_panel.appendChild(this.brush_opacity_slider)\r\n bottom_panel.appendChild(this.colorButton)\r\n\r\n imgCanvas.style.position = 'absolute'\r\n maskCanvas.style.position = 'absolute'\r\n\r\n imgCanvas.style.top = '200'\r\n imgCanvas.style.left = '0'\r\n\r\n maskCanvas.style.top = imgCanvas.style.top\r\n maskCanvas.style.left = imgCanvas.style.left\r\n\r\n const maskCanvasStyle = this.getMaskCanvasStyle()\r\n maskCanvas.style.mixBlendMode = maskCanvasStyle.mixBlendMode\r\n maskCanvas.style.opacity = maskCanvasStyle.opacity.toString()\r\n }\r\n\r\n async show() {\r\n this.zoom_ratio = 1.0\r\n this.pan_x = 0\r\n this.pan_y = 0\r\n\r\n if (!this.is_layout_created) {\r\n // layout\r\n const imgCanvas = document.createElement('canvas')\r\n const maskCanvas = document.createElement('canvas')\r\n\r\n imgCanvas.id = 'imageCanvas'\r\n maskCanvas.id = 'maskCanvas'\r\n\r\n this.setlayout(imgCanvas, maskCanvas)\r\n\r\n // prepare content\r\n this.imgCanvas = imgCanvas\r\n this.maskCanvas = maskCanvas\r\n this.maskCtx = maskCanvas.getContext('2d', { willReadFrequently: true })\r\n\r\n this.setEventHandler(maskCanvas)\r\n\r\n this.is_layout_created = true\r\n\r\n // replacement of onClose hook since close is not real close\r\n const self = this\r\n const observer = new MutationObserver(function (mutations) {\r\n mutations.forEach(function (mutation) {\r\n if (\r\n mutation.type === 'attributes' &&\r\n mutation.attributeName === 'style'\r\n ) {\r\n if (\r\n self.last_display_style &&\r\n self.last_display_style != 'none' &&\r\n self.element.style.display == 'none'\r\n ) {\r\n self.brush.style.display = 'none'\r\n ComfyApp.onClipspaceEditorClosed()\r\n }\r\n\r\n self.last_display_style = self.element.style.display\r\n }\r\n })\r\n })\r\n\r\n const config = { attributes: true }\r\n observer.observe(this.element, config)\r\n }\r\n\r\n // The keydown event needs to be reconfigured when closing the dialog as it gets removed.\r\n document.addEventListener('keydown', MaskEditorDialog.handleKeyDown)\r\n\r\n if (ComfyApp.clipspace_return_node) {\r\n this.saveButton.innerText = 'Save to node'\r\n } else {\r\n this.saveButton.innerText = 'Save'\r\n }\r\n this.saveButton.disabled = false\r\n\r\n this.element.style.display = 'block'\r\n this.element.style.width = '85%'\r\n this.element.style.margin = '0 7.5%'\r\n this.element.style.height = '100vh'\r\n this.element.style.top = '50%'\r\n this.element.style.left = '42%'\r\n this.element.style.zIndex = '8888' // NOTE: alert dialog must be high priority.\r\n\r\n await this.setImages(this.imgCanvas)\r\n\r\n this.is_visible = true\r\n }\r\n\r\n isOpened() {\r\n return this.element.style.display == 'block'\r\n }\r\n\r\n invalidateCanvas(orig_image, mask_image) {\r\n this.imgCanvas.width = orig_image.width\r\n this.imgCanvas.height = orig_image.height\r\n\r\n this.maskCanvas.width = orig_image.width\r\n this.maskCanvas.height = orig_image.height\r\n\r\n let imgCtx = this.imgCanvas.getContext('2d', { willReadFrequently: true })\r\n let maskCtx = this.maskCanvas.getContext('2d', {\r\n willReadFrequently: true\r\n })\r\n\r\n imgCtx.drawImage(orig_image, 0, 0, orig_image.width, orig_image.height)\r\n prepare_mask(mask_image, this.maskCanvas, maskCtx, this.getMaskColor())\r\n }\r\n\r\n async setImages(imgCanvas) {\r\n let self = this\r\n\r\n const imgCtx = imgCanvas.getContext('2d', { willReadFrequently: true })\r\n const maskCtx = this.maskCtx\r\n const maskCanvas = this.maskCanvas\r\n\r\n imgCtx.clearRect(0, 0, this.imgCanvas.width, this.imgCanvas.height)\r\n maskCtx.clearRect(0, 0, this.maskCanvas.width, this.maskCanvas.height)\r\n\r\n // image load\r\n const filepath = ComfyApp.clipspace.images\r\n\r\n const alpha_url = new URL(\r\n ComfyApp.clipspace.imgs[ComfyApp.clipspace['selectedIndex']].src\r\n )\r\n alpha_url.searchParams.delete('channel')\r\n alpha_url.searchParams.delete('preview')\r\n alpha_url.searchParams.set('channel', 'a')\r\n let mask_image = await loadImage(alpha_url)\r\n\r\n // original image load\r\n const rgb_url = new URL(\r\n ComfyApp.clipspace.imgs[ComfyApp.clipspace['selectedIndex']].src\r\n )\r\n rgb_url.searchParams.delete('channel')\r\n rgb_url.searchParams.set('channel', 'rgb')\r\n this.image = new Image()\r\n this.image.onload = function () {\r\n maskCanvas.width = self.image.width\r\n maskCanvas.height = self.image.height\r\n\r\n self.invalidateCanvas(self.image, mask_image)\r\n self.initializeCanvasPanZoom()\r\n }\r\n this.image.src = rgb_url.toString()\r\n }\r\n\r\n initializeCanvasPanZoom() {\r\n // set initialize\r\n let drawWidth = this.image.width\r\n let drawHeight = this.image.height\r\n\r\n let width = this.element.clientWidth\r\n let height = this.element.clientHeight\r\n\r\n if (this.image.width > width) {\r\n drawWidth = width\r\n drawHeight = (drawWidth / this.image.width) * this.image.height\r\n }\r\n\r\n if (drawHeight > height) {\r\n drawHeight = height\r\n drawWidth = (drawHeight / this.image.height) * this.image.width\r\n }\r\n\r\n this.zoom_ratio = drawWidth / this.image.width\r\n\r\n const canvasX = (width - drawWidth) / 2\r\n const canvasY = (height - drawHeight) / 2\r\n this.pan_x = canvasX\r\n this.pan_y = canvasY\r\n\r\n this.invalidatePanZoom()\r\n }\r\n\r\n invalidatePanZoom() {\r\n let raw_width = this.image.width * this.zoom_ratio\r\n let raw_height = this.image.height * this.zoom_ratio\r\n\r\n if (this.pan_x + raw_width < 10) {\r\n this.pan_x = 10 - raw_width\r\n }\r\n\r\n if (this.pan_y + raw_height < 10) {\r\n this.pan_y = 10 - raw_height\r\n }\r\n\r\n let width = `${raw_width}px`\r\n let height = `${raw_height}px`\r\n\r\n let left = `${this.pan_x}px`\r\n let top = `${this.pan_y}px`\r\n\r\n this.maskCanvas.style.width = width\r\n this.maskCanvas.style.height = height\r\n this.maskCanvas.style.left = left\r\n this.maskCanvas.style.top = top\r\n\r\n this.imgCanvas.style.width = width\r\n this.imgCanvas.style.height = height\r\n this.imgCanvas.style.left = left\r\n this.imgCanvas.style.top = top\r\n }\r\n\r\n setEventHandler(maskCanvas) {\r\n const self = this\r\n\r\n if (!this.handler_registered) {\r\n maskCanvas.addEventListener('contextmenu', (event) => {\r\n event.preventDefault()\r\n })\r\n\r\n this.element.addEventListener('wheel', (event) =>\r\n this.handleWheelEvent(self, event)\r\n )\r\n this.element.addEventListener('pointermove', (event) =>\r\n this.pointMoveEvent(self, event)\r\n )\r\n this.element.addEventListener('touchmove', (event) =>\r\n this.pointMoveEvent(self, event)\r\n )\r\n\r\n this.element.addEventListener('dragstart', (event) => {\r\n if (event.ctrlKey) {\r\n event.preventDefault()\r\n }\r\n })\r\n\r\n maskCanvas.addEventListener('pointerdown', (event) =>\r\n this.handlePointerDown(self, event)\r\n )\r\n maskCanvas.addEventListener('pointermove', (event) =>\r\n this.draw_move(self, event)\r\n )\r\n maskCanvas.addEventListener('touchmove', (event) =>\r\n this.draw_move(self, event)\r\n )\r\n maskCanvas.addEventListener('pointerover', (event) => {\r\n this.brush.style.display = 'block'\r\n })\r\n maskCanvas.addEventListener('pointerleave', (event) => {\r\n this.brush.style.display = 'none'\r\n })\r\n\r\n document.addEventListener('pointerup', MaskEditorDialog.handlePointerUp)\r\n\r\n this.handler_registered = true\r\n }\r\n }\r\n\r\n getMaskCanvasStyle() {\r\n if (this.brush_color_mode === 'negative') {\r\n return {\r\n mixBlendMode: 'difference',\r\n opacity: '1'\r\n }\r\n } else {\r\n return {\r\n mixBlendMode: 'initial',\r\n opacity: this.brush_opacity\r\n }\r\n }\r\n }\r\n\r\n getMaskColor() {\r\n if (this.brush_color_mode === 'black') {\r\n return { r: 0, g: 0, b: 0 }\r\n }\r\n if (this.brush_color_mode === 'white') {\r\n return { r: 255, g: 255, b: 255 }\r\n }\r\n if (this.brush_color_mode === 'negative') {\r\n // negative effect only works with white color\r\n return { r: 255, g: 255, b: 255 }\r\n }\r\n\r\n return { r: 0, g: 0, b: 0 }\r\n }\r\n\r\n getMaskFillStyle() {\r\n const maskColor = this.getMaskColor()\r\n\r\n return 'rgb(' + maskColor.r + ',' + maskColor.g + ',' + maskColor.b + ')'\r\n }\r\n\r\n getColorButtonText() {\r\n let colorCaption = 'unknown'\r\n\r\n if (this.brush_color_mode === 'black') {\r\n colorCaption = 'black'\r\n } else if (this.brush_color_mode === 'white') {\r\n colorCaption = 'white'\r\n } else if (this.brush_color_mode === 'negative') {\r\n colorCaption = 'negative'\r\n }\r\n\r\n return 'Color: ' + colorCaption\r\n }\r\n\r\n updateWhenBrushColorModeChanged() {\r\n this.colorButton.innerText = this.getColorButtonText()\r\n\r\n // update mask canvas css styles\r\n\r\n const maskCanvasStyle = this.getMaskCanvasStyle()\r\n this.maskCanvas.style.mixBlendMode = maskCanvasStyle.mixBlendMode\r\n this.maskCanvas.style.opacity = maskCanvasStyle.opacity.toString()\r\n\r\n // update mask canvas rgb colors\r\n\r\n const maskColor = this.getMaskColor()\r\n\r\n const maskData = this.maskCtx.getImageData(\r\n 0,\r\n 0,\r\n this.maskCanvas.width,\r\n this.maskCanvas.height\r\n )\r\n\r\n for (let i = 0; i < maskData.data.length; i += 4) {\r\n maskData.data[i] = maskColor.r\r\n maskData.data[i + 1] = maskColor.g\r\n maskData.data[i + 2] = maskColor.b\r\n }\r\n\r\n this.maskCtx.putImageData(maskData, 0, 0)\r\n }\r\n\r\n brush_opacity = 0.7\r\n brush_size = 10\r\n brush_color_mode = 'black'\r\n drawing_mode = false\r\n lastx = -1\r\n lasty = -1\r\n lasttime = 0\r\n\r\n static handleKeyDown(event) {\r\n const self = MaskEditorDialog.instance\r\n if (event.key === ']') {\r\n self.brush_size = Math.min(self.brush_size + 2, 100)\r\n self.brush_slider_input.value = self.brush_size\r\n } else if (event.key === '[') {\r\n self.brush_size = Math.max(self.brush_size - 2, 1)\r\n self.brush_slider_input.value = self.brush_size\r\n } else if (event.key === 'Enter') {\r\n self.save()\r\n }\r\n\r\n self.updateBrushPreview(self)\r\n }\r\n\r\n static handlePointerUp(event) {\r\n event.preventDefault()\r\n\r\n this.mousedown_x = null\r\n this.mousedown_y = null\r\n\r\n MaskEditorDialog.instance.drawing_mode = false\r\n }\r\n\r\n updateBrushPreview(self) {\r\n const brush = self.brush\r\n\r\n var centerX = self.cursorX\r\n var centerY = self.cursorY\r\n\r\n brush.style.width = self.brush_size * 2 * this.zoom_ratio + 'px'\r\n brush.style.height = self.brush_size * 2 * this.zoom_ratio + 'px'\r\n brush.style.left = centerX - self.brush_size * this.zoom_ratio + 'px'\r\n brush.style.top = centerY - self.brush_size * this.zoom_ratio + 'px'\r\n }\r\n\r\n handleWheelEvent(self, event) {\r\n event.preventDefault()\r\n\r\n if (event.ctrlKey) {\r\n // zoom canvas\r\n if (event.deltaY < 0) {\r\n this.zoom_ratio = Math.min(10.0, this.zoom_ratio + 0.2)\r\n } else {\r\n this.zoom_ratio = Math.max(0.2, this.zoom_ratio - 0.2)\r\n }\r\n\r\n this.invalidatePanZoom()\r\n } else {\r\n // adjust brush size\r\n if (event.deltaY < 0) this.brush_size = Math.min(this.brush_size + 2, 100)\r\n else this.brush_size = Math.max(this.brush_size - 2, 1)\r\n\r\n this.brush_slider_input.value = this.brush_size.toString()\r\n\r\n this.updateBrushPreview(this)\r\n }\r\n }\r\n\r\n pointMoveEvent(self, event) {\r\n this.cursorX = event.pageX\r\n this.cursorY = event.pageY\r\n\r\n self.updateBrushPreview(self)\r\n\r\n if (event.ctrlKey) {\r\n event.preventDefault()\r\n self.pan_move(self, event)\r\n }\r\n\r\n let left_button_down =\r\n (window.TouchEvent && event instanceof TouchEvent) || event.buttons == 1\r\n\r\n if (event.shiftKey && left_button_down) {\r\n self.drawing_mode = false\r\n\r\n const y = event.clientY\r\n let delta = (self.zoom_lasty - y) * 0.005\r\n self.zoom_ratio = Math.max(\r\n Math.min(10.0, self.last_zoom_ratio - delta),\r\n 0.2\r\n )\r\n\r\n this.invalidatePanZoom()\r\n return\r\n }\r\n }\r\n\r\n pan_move(self, event) {\r\n if (event.buttons == 1) {\r\n if (MaskEditorDialog.mousedown_x) {\r\n let deltaX = MaskEditorDialog.mousedown_x - event.clientX\r\n let deltaY = MaskEditorDialog.mousedown_y - event.clientY\r\n\r\n self.pan_x = this.mousedown_pan_x - deltaX\r\n self.pan_y = this.mousedown_pan_y - deltaY\r\n\r\n self.invalidatePanZoom()\r\n }\r\n }\r\n }\r\n\r\n draw_move(self, event) {\r\n if (event.ctrlKey || event.shiftKey) {\r\n return\r\n }\r\n\r\n event.preventDefault()\r\n\r\n this.cursorX = event.pageX\r\n this.cursorY = event.pageY\r\n\r\n self.updateBrushPreview(self)\r\n\r\n let left_button_down =\r\n (window.TouchEvent && event instanceof TouchEvent) || event.buttons == 1\r\n let right_button_down = [2, 5, 32].includes(event.buttons)\r\n\r\n if (!event.altKey && left_button_down) {\r\n var diff = performance.now() - self.lasttime\r\n\r\n const maskRect = self.maskCanvas.getBoundingClientRect()\r\n\r\n var x = event.offsetX\r\n var y = event.offsetY\r\n\r\n if (event.offsetX == null) {\r\n x = event.targetTouches[0].clientX - maskRect.left\r\n }\r\n\r\n if (event.offsetY == null) {\r\n y = event.targetTouches[0].clientY - maskRect.top\r\n }\r\n\r\n x /= self.zoom_ratio\r\n y /= self.zoom_ratio\r\n\r\n var brush_size = this.brush_size\r\n if (event instanceof PointerEvent && event.pointerType == 'pen') {\r\n brush_size *= event.pressure\r\n this.last_pressure = event.pressure\r\n } else if (\r\n window.TouchEvent &&\r\n event instanceof TouchEvent &&\r\n diff < 20\r\n ) {\r\n // The firing interval of PointerEvents in Pen is unreliable, so it is supplemented by TouchEvents.\r\n brush_size *= this.last_pressure\r\n } else {\r\n brush_size = this.brush_size\r\n }\r\n\r\n if (diff > 20 && !this.drawing_mode)\r\n requestAnimationFrame(() => {\r\n self.maskCtx.beginPath()\r\n self.maskCtx.fillStyle = this.getMaskFillStyle()\r\n self.maskCtx.globalCompositeOperation = 'source-over'\r\n self.maskCtx.arc(x, y, brush_size, 0, Math.PI * 2, false)\r\n self.maskCtx.fill()\r\n self.lastx = x\r\n self.lasty = y\r\n })\r\n else\r\n requestAnimationFrame(() => {\r\n self.maskCtx.beginPath()\r\n self.maskCtx.fillStyle = this.getMaskFillStyle()\r\n self.maskCtx.globalCompositeOperation = 'source-over'\r\n\r\n var dx = x - self.lastx\r\n var dy = y - self.lasty\r\n\r\n var distance = Math.sqrt(dx * dx + dy * dy)\r\n var directionX = dx / distance\r\n var directionY = dy / distance\r\n\r\n for (var i = 0; i < distance; i += 5) {\r\n var px = self.lastx + directionX * i\r\n var py = self.lasty + directionY * i\r\n self.maskCtx.arc(px, py, brush_size, 0, Math.PI * 2, false)\r\n self.maskCtx.fill()\r\n }\r\n self.lastx = x\r\n self.lasty = y\r\n })\r\n\r\n self.lasttime = performance.now()\r\n } else if ((event.altKey && left_button_down) || right_button_down) {\r\n const maskRect = self.maskCanvas.getBoundingClientRect()\r\n const x =\r\n (event.offsetX || event.targetTouches[0].clientX - maskRect.left) /\r\n self.zoom_ratio\r\n const y =\r\n (event.offsetY || event.targetTouches[0].clientY - maskRect.top) /\r\n self.zoom_ratio\r\n\r\n var brush_size = this.brush_size\r\n if (event instanceof PointerEvent && event.pointerType == 'pen') {\r\n brush_size *= event.pressure\r\n this.last_pressure = event.pressure\r\n } else if (\r\n window.TouchEvent &&\r\n event instanceof TouchEvent &&\r\n diff < 20\r\n ) {\r\n brush_size *= this.last_pressure\r\n } else {\r\n brush_size = this.brush_size\r\n }\r\n\r\n if (diff > 20 && !this.drawing_mode)\r\n // cannot tracking drawing_mode for touch event\r\n requestAnimationFrame(() => {\r\n self.maskCtx.beginPath()\r\n self.maskCtx.globalCompositeOperation = 'destination-out'\r\n self.maskCtx.arc(x, y, brush_size, 0, Math.PI * 2, false)\r\n self.maskCtx.fill()\r\n self.lastx = x\r\n self.lasty = y\r\n })\r\n else\r\n requestAnimationFrame(() => {\r\n self.maskCtx.beginPath()\r\n self.maskCtx.globalCompositeOperation = 'destination-out'\r\n\r\n var dx = x - self.lastx\r\n var dy = y - self.lasty\r\n\r\n var distance = Math.sqrt(dx * dx + dy * dy)\r\n var directionX = dx / distance\r\n var directionY = dy / distance\r\n\r\n for (var i = 0; i < distance; i += 5) {\r\n var px = self.lastx + directionX * i\r\n var py = self.lasty + directionY * i\r\n self.maskCtx.arc(px, py, brush_size, 0, Math.PI * 2, false)\r\n self.maskCtx.fill()\r\n }\r\n self.lastx = x\r\n self.lasty = y\r\n })\r\n\r\n self.lasttime = performance.now()\r\n }\r\n }\r\n\r\n handlePointerDown(self, event) {\r\n if (event.ctrlKey) {\r\n if (event.buttons == 1) {\r\n MaskEditorDialog.mousedown_x = event.clientX\r\n MaskEditorDialog.mousedown_y = event.clientY\r\n\r\n this.mousedown_pan_x = this.pan_x\r\n this.mousedown_pan_y = this.pan_y\r\n }\r\n return\r\n }\r\n\r\n var brush_size = this.brush_size\r\n if (event instanceof PointerEvent && event.pointerType == 'pen') {\r\n brush_size *= event.pressure\r\n this.last_pressure = event.pressure\r\n }\r\n\r\n if ([0, 2, 5].includes(event.button)) {\r\n self.drawing_mode = true\r\n\r\n event.preventDefault()\r\n\r\n if (event.shiftKey) {\r\n self.zoom_lasty = event.clientY\r\n self.last_zoom_ratio = self.zoom_ratio\r\n return\r\n }\r\n\r\n const maskRect = self.maskCanvas.getBoundingClientRect()\r\n const x =\r\n (event.offsetX || event.targetTouches[0].clientX - maskRect.left) /\r\n self.zoom_ratio\r\n const y =\r\n (event.offsetY || event.targetTouches[0].clientY - maskRect.top) /\r\n self.zoom_ratio\r\n\r\n self.maskCtx.beginPath()\r\n if (!event.altKey && event.button == 0) {\r\n self.maskCtx.fillStyle = this.getMaskFillStyle()\r\n self.maskCtx.globalCompositeOperation = 'source-over'\r\n } else {\r\n self.maskCtx.globalCompositeOperation = 'destination-out'\r\n }\r\n self.maskCtx.arc(x, y, brush_size, 0, Math.PI * 2, false)\r\n self.maskCtx.fill()\r\n self.lastx = x\r\n self.lasty = y\r\n self.lasttime = performance.now()\r\n }\r\n }\r\n\r\n async save() {\r\n const backupCanvas = document.createElement('canvas')\r\n const backupCtx = backupCanvas.getContext('2d', {\r\n willReadFrequently: true\r\n })\r\n backupCanvas.width = this.image.width\r\n backupCanvas.height = this.image.height\r\n\r\n backupCtx.clearRect(0, 0, backupCanvas.width, backupCanvas.height)\r\n backupCtx.drawImage(\r\n this.maskCanvas,\r\n 0,\r\n 0,\r\n this.maskCanvas.width,\r\n this.maskCanvas.height,\r\n 0,\r\n 0,\r\n backupCanvas.width,\r\n backupCanvas.height\r\n )\r\n\r\n // paste mask data into alpha channel\r\n const backupData = backupCtx.getImageData(\r\n 0,\r\n 0,\r\n backupCanvas.width,\r\n backupCanvas.height\r\n )\r\n\r\n // refine mask image\r\n for (let i = 0; i < backupData.data.length; i += 4) {\r\n if (backupData.data[i + 3] == 255) backupData.data[i + 3] = 0\r\n else backupData.data[i + 3] = 255\r\n\r\n backupData.data[i] = 0\r\n backupData.data[i + 1] = 0\r\n backupData.data[i + 2] = 0\r\n }\r\n\r\n backupCtx.globalCompositeOperation = 'source-over'\r\n backupCtx.putImageData(backupData, 0, 0)\r\n\r\n const formData = new FormData()\r\n const filename = 'clipspace-mask-' + performance.now() + '.png'\r\n\r\n const item = {\r\n filename: filename,\r\n subfolder: 'clipspace',\r\n type: 'input'\r\n }\r\n\r\n if (ComfyApp.clipspace.images) ComfyApp.clipspace.images[0] = item\r\n\r\n if (ComfyApp.clipspace.widgets) {\r\n const index = ComfyApp.clipspace.widgets.findIndex(\r\n (obj) => obj.name === 'image'\r\n )\r\n\r\n if (index >= 0) ComfyApp.clipspace.widgets[index].value = item\r\n }\r\n\r\n const dataURL = backupCanvas.toDataURL()\r\n const blob = dataURLToBlob(dataURL)\r\n\r\n let original_url = new URL(this.image.src)\r\n\r\n type Ref = { filename: string; subfolder?: string; type?: string }\r\n\r\n const original_ref: Ref = {\r\n filename: original_url.searchParams.get('filename')\r\n }\r\n\r\n let original_subfolder = original_url.searchParams.get('subfolder')\r\n if (original_subfolder) original_ref.subfolder = original_subfolder\r\n\r\n let original_type = original_url.searchParams.get('type')\r\n if (original_type) original_ref.type = original_type\r\n\r\n formData.append('image', blob, filename)\r\n formData.append('original_ref', JSON.stringify(original_ref))\r\n formData.append('type', 'input')\r\n formData.append('subfolder', 'clipspace')\r\n\r\n this.saveButton.innerText = 'Saving...'\r\n this.saveButton.disabled = true\r\n await uploadMask(item, formData)\r\n ComfyApp.onClipspaceEditorSave()\r\n this.close()\r\n }\r\n}\r\n\r\napp.registerExtension({\r\n name: 'Comfy.MaskEditor',\r\n init(app) {\r\n ComfyApp.open_maskeditor = function () {\r\n const dlg = MaskEditorDialog.getInstance()\r\n if (!dlg.isOpened()) {\r\n dlg.show()\r\n }\r\n }\r\n\r\n const context_predicate = () =>\r\n ComfyApp.clipspace &&\r\n ComfyApp.clipspace.imgs &&\r\n ComfyApp.clipspace.imgs.length > 0\r\n ClipspaceDialog.registerButton(\r\n 'MaskEditor',\r\n context_predicate,\r\n ComfyApp.open_maskeditor\r\n )\r\n }\r\n})\r\n","import { app } from '../../scripts/app'\r\nimport { api } from '../../scripts/api'\r\nimport { ComfyDialog, $el } from '../../scripts/ui'\r\nimport { GroupNodeConfig, GroupNodeHandler } from './groupNode'\r\nimport { LGraphCanvas } from '@comfyorg/litegraph'\r\n\r\n// Adds the ability to save and add multiple nodes as a template\r\n// To save:\r\n// Select multiple nodes (ctrl + drag to select a region or ctrl+click individual nodes)\r\n// Right click the canvas\r\n// Save Node Template -> give it a name\r\n//\r\n// To add:\r\n// Right click the canvas\r\n// Node templates -> click the one to add\r\n//\r\n// To delete/rename:\r\n// Right click the canvas\r\n// Node templates -> Manage\r\n//\r\n// To rearrange:\r\n// Open the manage dialog and Drag and drop elements using the \"Name:\" label as handle\r\n\r\nconst id = 'Comfy.NodeTemplates'\r\nconst file = 'comfy.templates.json'\r\n\r\nclass ManageTemplates extends ComfyDialog {\r\n templates: any[]\r\n draggedEl: HTMLElement | null\r\n saveVisualCue: number | null\r\n emptyImg: HTMLImageElement\r\n importInput: HTMLInputElement\r\n\r\n constructor() {\r\n super()\r\n this.load().then((v) => {\r\n this.templates = v\r\n })\r\n\r\n this.element.classList.add('comfy-manage-templates')\r\n this.draggedEl = null\r\n this.saveVisualCue = null\r\n this.emptyImg = new Image()\r\n this.emptyImg.src =\r\n 'data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs='\r\n\r\n this.importInput = $el('input', {\r\n type: 'file',\r\n accept: '.json',\r\n multiple: true,\r\n style: { display: 'none' },\r\n parent: document.body,\r\n onchange: () => this.importAll()\r\n }) as HTMLInputElement\r\n }\r\n\r\n createButtons() {\r\n const btns = super.createButtons()\r\n btns[0].textContent = 'Close'\r\n btns[0].onclick = (e) => {\r\n clearTimeout(this.saveVisualCue)\r\n this.close()\r\n }\r\n btns.unshift(\r\n $el('button', {\r\n type: 'button',\r\n textContent: 'Export',\r\n onclick: () => this.exportAll()\r\n })\r\n )\r\n btns.unshift(\r\n $el('button', {\r\n type: 'button',\r\n textContent: 'Import',\r\n onclick: () => {\r\n this.importInput.click()\r\n }\r\n })\r\n )\r\n return btns\r\n }\r\n\r\n async load() {\r\n let templates = []\r\n if (app.storageLocation === 'server') {\r\n if (app.isNewUserSession) {\r\n // New user so migrate existing templates\r\n const json = localStorage.getItem(id)\r\n if (json) {\r\n templates = JSON.parse(json)\r\n }\r\n await api.storeUserData(file, json, { stringify: false })\r\n } else {\r\n const res = await api.getUserData(file)\r\n if (res.status === 200) {\r\n try {\r\n templates = await res.json()\r\n } catch (error) {}\r\n } else if (res.status !== 404) {\r\n console.error(res.status + ' ' + res.statusText)\r\n }\r\n }\r\n } else {\r\n const json = localStorage.getItem(id)\r\n if (json) {\r\n templates = JSON.parse(json)\r\n }\r\n }\r\n\r\n return templates ?? []\r\n }\r\n\r\n async store() {\r\n if (app.storageLocation === 'server') {\r\n const templates = JSON.stringify(this.templates, undefined, 4)\r\n localStorage.setItem(id, templates) // Backwards compatibility\r\n try {\r\n await api.storeUserData(file, templates, { stringify: false })\r\n } catch (error) {\r\n console.error(error)\r\n alert(error.message)\r\n }\r\n } else {\r\n localStorage.setItem(id, JSON.stringify(this.templates))\r\n }\r\n }\r\n\r\n async importAll() {\r\n for (const file of this.importInput.files) {\r\n if (file.type === 'application/json' || file.name.endsWith('.json')) {\r\n const reader = new FileReader()\r\n reader.onload = async () => {\r\n const importFile = JSON.parse(reader.result as string)\r\n if (importFile?.templates) {\r\n for (const template of importFile.templates) {\r\n if (template?.name && template?.data) {\r\n this.templates.push(template)\r\n }\r\n }\r\n await this.store()\r\n }\r\n }\r\n await reader.readAsText(file)\r\n }\r\n }\r\n\r\n this.importInput.value = null\r\n\r\n this.close()\r\n }\r\n\r\n exportAll() {\r\n if (this.templates.length == 0) {\r\n alert('No templates to export.')\r\n return\r\n }\r\n\r\n const json = JSON.stringify({ templates: this.templates }, null, 2) // convert the data to a JSON string\r\n const blob = new Blob([json], { type: 'application/json' })\r\n const url = URL.createObjectURL(blob)\r\n const a = $el('a', {\r\n href: url,\r\n download: 'node_templates.json',\r\n style: { display: 'none' },\r\n parent: document.body\r\n })\r\n a.click()\r\n setTimeout(function () {\r\n a.remove()\r\n window.URL.revokeObjectURL(url)\r\n }, 0)\r\n }\r\n\r\n show() {\r\n // Show list of template names + delete button\r\n super.show(\r\n $el(\r\n 'div',\r\n {},\r\n this.templates.flatMap((t, i) => {\r\n let nameInput\r\n return [\r\n $el(\r\n 'div',\r\n {\r\n dataset: { id: i.toString() },\r\n className: 'templateManagerRow',\r\n style: {\r\n display: 'grid',\r\n gridTemplateColumns: '1fr auto',\r\n border: '1px dashed transparent',\r\n gap: '5px',\r\n backgroundColor: 'var(--comfy-menu-bg)'\r\n },\r\n ondragstart: (e) => {\r\n this.draggedEl = e.currentTarget\r\n e.currentTarget.style.opacity = '0.6'\r\n e.currentTarget.style.border = '1px dashed yellow'\r\n e.dataTransfer.effectAllowed = 'move'\r\n e.dataTransfer.setDragImage(this.emptyImg, 0, 0)\r\n },\r\n ondragend: (e) => {\r\n e.target.style.opacity = '1'\r\n e.currentTarget.style.border = '1px dashed transparent'\r\n e.currentTarget.removeAttribute('draggable')\r\n\r\n // rearrange the elements\r\n this.element\r\n .querySelectorAll('.templateManagerRow')\r\n .forEach((el: HTMLElement, i) => {\r\n var prev_i = Number.parseInt(el.dataset.id)\r\n\r\n if (el == this.draggedEl && prev_i != i) {\r\n this.templates.splice(\r\n i,\r\n 0,\r\n this.templates.splice(prev_i, 1)[0]\r\n )\r\n }\r\n el.dataset.id = i.toString()\r\n })\r\n this.store()\r\n },\r\n ondragover: (e) => {\r\n e.preventDefault()\r\n if (e.currentTarget == this.draggedEl) return\r\n\r\n let rect = e.currentTarget.getBoundingClientRect()\r\n if (e.clientY > rect.top + rect.height / 2) {\r\n e.currentTarget.parentNode.insertBefore(\r\n this.draggedEl,\r\n e.currentTarget.nextSibling\r\n )\r\n } else {\r\n e.currentTarget.parentNode.insertBefore(\r\n this.draggedEl,\r\n e.currentTarget\r\n )\r\n }\r\n }\r\n },\r\n [\r\n $el(\r\n 'label',\r\n {\r\n textContent: 'Name: ',\r\n style: {\r\n cursor: 'grab'\r\n },\r\n onmousedown: (e) => {\r\n // enable dragging only from the label\r\n if (e.target.localName == 'label')\r\n e.currentTarget.parentNode.draggable = 'true'\r\n }\r\n },\r\n [\r\n $el('input', {\r\n value: t.name,\r\n dataset: { name: t.name },\r\n style: {\r\n transitionProperty: 'background-color',\r\n transitionDuration: '0s'\r\n },\r\n onchange: (e) => {\r\n clearTimeout(this.saveVisualCue)\r\n var el = e.target\r\n var row = el.parentNode.parentNode\r\n this.templates[row.dataset.id].name =\r\n el.value.trim() || 'untitled'\r\n this.store()\r\n el.style.backgroundColor = 'rgb(40, 95, 40)'\r\n el.style.transitionDuration = '0s'\r\n // @ts-expect-error\r\n // In browser env the return value is number.\r\n this.saveVisualCue = setTimeout(function () {\r\n el.style.transitionDuration = '.7s'\r\n el.style.backgroundColor = 'var(--comfy-input-bg)'\r\n }, 15)\r\n },\r\n onkeypress: (e) => {\r\n var el = e.target\r\n clearTimeout(this.saveVisualCue)\r\n el.style.transitionDuration = '0s'\r\n el.style.backgroundColor = 'var(--comfy-input-bg)'\r\n },\r\n $: (el) => (nameInput = el)\r\n })\r\n ]\r\n ),\r\n $el('div', {}, [\r\n $el('button', {\r\n textContent: 'Export',\r\n style: {\r\n fontSize: '12px',\r\n fontWeight: 'normal'\r\n },\r\n onclick: (e) => {\r\n const json = JSON.stringify({ templates: [t] }, null, 2) // convert the data to a JSON string\r\n const blob = new Blob([json], {\r\n type: 'application/json'\r\n })\r\n const url = URL.createObjectURL(blob)\r\n const a = $el('a', {\r\n href: url,\r\n download: (nameInput.value || t.name) + '.json',\r\n style: { display: 'none' },\r\n parent: document.body\r\n })\r\n a.click()\r\n setTimeout(function () {\r\n a.remove()\r\n window.URL.revokeObjectURL(url)\r\n }, 0)\r\n }\r\n }),\r\n $el('button', {\r\n textContent: 'Delete',\r\n style: {\r\n fontSize: '12px',\r\n color: 'red',\r\n fontWeight: 'normal'\r\n },\r\n onclick: (e) => {\r\n const item = e.target.parentNode.parentNode\r\n item.parentNode.removeChild(item)\r\n this.templates.splice(item.dataset.id * 1, 1)\r\n this.store()\r\n // update the rows index, setTimeout ensures that the list is updated\r\n var that = this\r\n setTimeout(function () {\r\n that.element\r\n .querySelectorAll('.templateManagerRow')\r\n .forEach((el: HTMLElement, i) => {\r\n el.dataset.id = i.toString()\r\n })\r\n }, 0)\r\n }\r\n })\r\n ])\r\n ]\r\n )\r\n ]\r\n })\r\n )\r\n )\r\n }\r\n}\r\n\r\napp.registerExtension({\r\n name: id,\r\n setup() {\r\n const manage = new ManageTemplates()\r\n\r\n const clipboardAction = async (cb) => {\r\n // We use the clipboard functions but dont want to overwrite the current user clipboard\r\n // Restore it after we've run our callback\r\n const old = localStorage.getItem('litegrapheditor_clipboard')\r\n await cb()\r\n localStorage.setItem('litegrapheditor_clipboard', old)\r\n }\r\n\r\n const orig = LGraphCanvas.prototype.getCanvasMenuOptions\r\n LGraphCanvas.prototype.getCanvasMenuOptions = function () {\r\n const options = orig.apply(this, arguments)\r\n\r\n options.push(null)\r\n options.push({\r\n content: `Save Selected as Template`,\r\n disabled: !Object.keys(app.canvas.selected_nodes || {}).length,\r\n callback: () => {\r\n const name = prompt('Enter name')\r\n if (!name?.trim()) return\r\n\r\n clipboardAction(() => {\r\n app.canvas.copyToClipboard()\r\n let data = localStorage.getItem('litegrapheditor_clipboard')\r\n data = JSON.parse(data)\r\n const nodeIds = Object.keys(app.canvas.selected_nodes)\r\n for (let i = 0; i < nodeIds.length; i++) {\r\n const node = app.graph.getNodeById(Number.parseInt(nodeIds[i]))\r\n // @ts-expect-error\r\n const nodeData = node?.constructor.nodeData\r\n\r\n let groupData = GroupNodeHandler.getGroupData(node)\r\n if (groupData) {\r\n groupData = groupData.nodeData\r\n // @ts-expect-error\r\n if (!data.groupNodes) {\r\n // @ts-expect-error\r\n data.groupNodes = {}\r\n }\r\n // @ts-expect-error\r\n data.groupNodes[nodeData.name] = groupData\r\n // @ts-expect-error\r\n data.nodes[i].type = nodeData.name\r\n }\r\n }\r\n\r\n manage.templates.push({\r\n name,\r\n data: JSON.stringify(data)\r\n })\r\n manage.store()\r\n })\r\n }\r\n })\r\n\r\n // Map each template to a menu item\r\n const subItems = manage.templates.map((t) => {\r\n return {\r\n content: t.name,\r\n callback: () => {\r\n clipboardAction(async () => {\r\n const data = JSON.parse(t.data)\r\n await GroupNodeConfig.registerFromWorkflow(data.groupNodes, {})\r\n localStorage.setItem('litegrapheditor_clipboard', t.data)\r\n app.canvas.pasteFromClipboard()\r\n })\r\n }\r\n }\r\n })\r\n\r\n subItems.push(null, {\r\n content: 'Manage',\r\n callback: () => manage.show()\r\n })\r\n\r\n options.push({\r\n content: 'Node Templates',\r\n submenu: {\r\n options: subItems\r\n }\r\n })\r\n\r\n return options\r\n }\r\n }\r\n})\r\n","import { LiteGraph, LGraphCanvas } from '@comfyorg/litegraph'\r\nimport { app } from '../../scripts/app'\r\nimport { ComfyWidgets } from '../../scripts/widgets'\r\n// Node that add notes to your project\r\n\r\napp.registerExtension({\r\n name: 'Comfy.NoteNode',\r\n registerCustomNodes() {\r\n class NoteNode {\r\n static category: string\r\n\r\n color = LGraphCanvas.node_colors.yellow.color\r\n bgcolor = LGraphCanvas.node_colors.yellow.bgcolor\r\n groupcolor = LGraphCanvas.node_colors.yellow.groupcolor\r\n properties: { text: string }\r\n serialize_widgets: boolean\r\n isVirtualNode: boolean\r\n collapsable: boolean\r\n title_mode: number\r\n\r\n constructor() {\r\n if (!this.properties) {\r\n this.properties = { text: '' }\r\n }\r\n ComfyWidgets.STRING(\r\n // @ts-expect-error\r\n // Should we extends LGraphNode?\r\n this,\r\n '',\r\n ['', { default: this.properties.text, multiline: true }],\r\n app\r\n )\r\n\r\n this.serialize_widgets = true\r\n this.isVirtualNode = true\r\n }\r\n }\r\n\r\n // Load default visibility\r\n\r\n LiteGraph.registerNodeType(\r\n 'Note',\r\n // @ts-expect-error\r\n Object.assign(NoteNode, {\r\n title_mode: LiteGraph.NORMAL_TITLE,\r\n title: 'Note',\r\n collapsable: true\r\n })\r\n )\r\n\r\n NoteNode.category = 'utils'\r\n }\r\n})\r\n","import { app } from '../../scripts/app'\r\nimport { mergeIfValid, getWidgetConfig, setWidgetConfig } from './widgetInputs'\r\nimport { LiteGraph, LGraphCanvas, LGraphNode } from '@comfyorg/litegraph'\r\n\r\n// Node that allows you to redirect connections for cleaner graphs\r\n\r\napp.registerExtension({\r\n name: 'Comfy.RerouteNode',\r\n registerCustomNodes(app) {\r\n interface RerouteNode extends LGraphNode {\r\n __outputType?: string\r\n }\r\n\r\n class RerouteNode {\r\n static category: string | undefined\r\n static defaultVisibility = false\r\n\r\n constructor() {\r\n if (!this.properties) {\r\n this.properties = {}\r\n }\r\n this.properties.showOutputText = RerouteNode.defaultVisibility\r\n this.properties.horizontal = false\r\n\r\n this.addInput('', '*')\r\n this.addOutput(this.properties.showOutputText ? '*' : '', '*')\r\n\r\n this.onAfterGraphConfigured = function () {\r\n requestAnimationFrame(() => {\r\n this.onConnectionsChange(LiteGraph.INPUT, null, true, null)\r\n })\r\n }\r\n\r\n this.onConnectionsChange = function (\r\n type,\r\n index,\r\n connected,\r\n link_info\r\n ) {\r\n this.applyOrientation()\r\n\r\n // Prevent multiple connections to different types when we have no input\r\n if (connected && type === LiteGraph.OUTPUT) {\r\n // Ignore wildcard nodes as these will be updated to real types\r\n const types = new Set(\r\n this.outputs[0].links\r\n .map((l) => app.graph.links[l].type)\r\n .filter((t) => t !== '*')\r\n )\r\n if (types.size > 1) {\r\n const linksToDisconnect = []\r\n for (let i = 0; i < this.outputs[0].links.length - 1; i++) {\r\n const linkId = this.outputs[0].links[i]\r\n const link = app.graph.links[linkId]\r\n linksToDisconnect.push(link)\r\n }\r\n for (const link of linksToDisconnect) {\r\n const node = app.graph.getNodeById(link.target_id)\r\n node.disconnectInput(link.target_slot)\r\n }\r\n }\r\n }\r\n\r\n // Find root input\r\n let currentNode = this\r\n let updateNodes = []\r\n let inputType = null\r\n let inputNode = null\r\n while (currentNode) {\r\n updateNodes.unshift(currentNode)\r\n const linkId = currentNode.inputs[0].link\r\n if (linkId !== null) {\r\n const link = app.graph.links[linkId]\r\n if (!link) return\r\n const node = app.graph.getNodeById(link.origin_id)\r\n const type = node.constructor.type\r\n if (type === 'Reroute') {\r\n if (node === this) {\r\n // We've found a circle\r\n currentNode.disconnectInput(link.target_slot)\r\n currentNode = null\r\n } else {\r\n // Move the previous node\r\n currentNode = node\r\n }\r\n } else {\r\n // We've found the end\r\n inputNode = currentNode\r\n inputType = node.outputs[link.origin_slot]?.type ?? null\r\n break\r\n }\r\n } else {\r\n // This path has no input node\r\n currentNode = null\r\n break\r\n }\r\n }\r\n\r\n // Find all outputs\r\n const nodes = [this]\r\n let outputType = null\r\n while (nodes.length) {\r\n currentNode = nodes.pop()\r\n const outputs =\r\n (currentNode.outputs ? currentNode.outputs[0].links : []) || []\r\n if (outputs.length) {\r\n for (const linkId of outputs) {\r\n const link = app.graph.links[linkId]\r\n\r\n // When disconnecting sometimes the link is still registered\r\n if (!link) continue\r\n\r\n const node = app.graph.getNodeById(link.target_id)\r\n const type = node.constructor.type\r\n\r\n if (type === 'Reroute') {\r\n // Follow reroute nodes\r\n nodes.push(node)\r\n updateNodes.push(node)\r\n } else {\r\n // We've found an output\r\n const nodeOutType =\r\n node.inputs &&\r\n node.inputs[link?.target_slot] &&\r\n node.inputs[link.target_slot].type\r\n ? node.inputs[link.target_slot].type\r\n : null\r\n if (\r\n inputType &&\r\n inputType !== '*' &&\r\n nodeOutType !== inputType\r\n ) {\r\n // The output doesnt match our input so disconnect it\r\n node.disconnectInput(link.target_slot)\r\n } else {\r\n outputType = nodeOutType\r\n }\r\n }\r\n }\r\n } else {\r\n // No more outputs for this path\r\n }\r\n }\r\n\r\n const displayType = inputType || outputType || '*'\r\n const color = LGraphCanvas.link_type_colors[displayType]\r\n\r\n let widgetConfig\r\n let targetWidget\r\n let widgetType\r\n // Update the types of each node\r\n for (const node of updateNodes) {\r\n // If we dont have an input type we are always wildcard but we'll show the output type\r\n // This lets you change the output link to a different type and all nodes will update\r\n node.outputs[0].type = inputType || '*'\r\n node.__outputType = displayType\r\n node.outputs[0].name = node.properties.showOutputText\r\n ? displayType\r\n : ''\r\n node.size = node.computeSize()\r\n node.applyOrientation()\r\n\r\n for (const l of node.outputs[0].links || []) {\r\n const link = app.graph.links[l]\r\n if (link) {\r\n link.color = color\r\n\r\n if (app.configuringGraph) continue\r\n const targetNode = app.graph.getNodeById(link.target_id)\r\n const targetInput = targetNode.inputs?.[link.target_slot]\r\n if (targetInput?.widget) {\r\n const config = getWidgetConfig(targetInput)\r\n if (!widgetConfig) {\r\n widgetConfig = config[1] ?? {}\r\n widgetType = config[0]\r\n }\r\n if (!targetWidget) {\r\n targetWidget = targetNode.widgets?.find(\r\n (w) => w.name === targetInput.widget.name\r\n )\r\n }\r\n\r\n const merged = mergeIfValid(targetInput, [\r\n config[0],\r\n widgetConfig\r\n ])\r\n if (merged.customConfig) {\r\n widgetConfig = merged.customConfig\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n for (const node of updateNodes) {\r\n if (widgetConfig && outputType) {\r\n node.inputs[0].widget = { name: 'value' }\r\n setWidgetConfig(\r\n node.inputs[0],\r\n [widgetType ?? displayType, widgetConfig],\r\n targetWidget\r\n )\r\n } else {\r\n setWidgetConfig(node.inputs[0], null)\r\n }\r\n }\r\n\r\n if (inputNode) {\r\n const link = app.graph.links[inputNode.inputs[0].link]\r\n if (link) {\r\n link.color = color\r\n }\r\n }\r\n }\r\n\r\n this.clone = function () {\r\n const cloned = RerouteNode.prototype.clone.apply(this)\r\n cloned.removeOutput(0)\r\n cloned.addOutput(this.properties.showOutputText ? '*' : '', '*')\r\n cloned.size = cloned.computeSize()\r\n return cloned\r\n }\r\n\r\n // This node is purely frontend and does not impact the resulting prompt so should not be serialized\r\n this.isVirtualNode = true\r\n }\r\n\r\n getExtraMenuOptions(_, options) {\r\n options.unshift(\r\n {\r\n content:\r\n (this.properties.showOutputText ? 'Hide' : 'Show') + ' Type',\r\n callback: () => {\r\n this.properties.showOutputText = !this.properties.showOutputText\r\n if (this.properties.showOutputText) {\r\n this.outputs[0].name =\r\n this.__outputType || (this.outputs[0].type as string)\r\n } else {\r\n this.outputs[0].name = ''\r\n }\r\n this.size = this.computeSize()\r\n this.applyOrientation()\r\n app.graph.setDirtyCanvas(true, true)\r\n }\r\n },\r\n {\r\n content:\r\n (RerouteNode.defaultVisibility ? 'Hide' : 'Show') +\r\n ' Type By Default',\r\n callback: () => {\r\n RerouteNode.setDefaultTextVisibility(\r\n !RerouteNode.defaultVisibility\r\n )\r\n }\r\n },\r\n {\r\n // naming is inverted with respect to LiteGraphNode.horizontal\r\n // LiteGraphNode.horizontal == true means that\r\n // each slot in the inputs and outputs are laid out horizontally,\r\n // which is the opposite of the visual orientation of the inputs and outputs as a node\r\n content:\r\n 'Set ' + (this.properties.horizontal ? 'Horizontal' : 'Vertical'),\r\n callback: () => {\r\n this.properties.horizontal = !this.properties.horizontal\r\n this.applyOrientation()\r\n }\r\n }\r\n )\r\n }\r\n applyOrientation() {\r\n this.horizontal = this.properties.horizontal\r\n if (this.horizontal) {\r\n // we correct the input position, because LiteGraphNode.horizontal\r\n // doesn't account for title presence\r\n // which reroute nodes don't have\r\n this.inputs[0].pos = [this.size[0] / 2, 0]\r\n } else {\r\n delete this.inputs[0].pos\r\n }\r\n app.graph.setDirtyCanvas(true, true)\r\n }\r\n\r\n computeSize(): [number, number] {\r\n return [\r\n this.properties.showOutputText && this.outputs && this.outputs.length\r\n ? Math.max(\r\n 75,\r\n LiteGraph.NODE_TEXT_SIZE * this.outputs[0].name.length * 0.6 +\r\n 40\r\n )\r\n : 75,\r\n 26\r\n ]\r\n }\r\n\r\n static setDefaultTextVisibility(visible) {\r\n RerouteNode.defaultVisibility = visible\r\n if (visible) {\r\n localStorage['Comfy.RerouteNode.DefaultVisibility'] = 'true'\r\n } else {\r\n delete localStorage['Comfy.RerouteNode.DefaultVisibility']\r\n }\r\n }\r\n }\r\n\r\n // Load default visibility\r\n RerouteNode.setDefaultTextVisibility(\r\n !!localStorage['Comfy.RerouteNode.DefaultVisibility']\r\n )\r\n\r\n LiteGraph.registerNodeType(\r\n 'Reroute',\r\n Object.assign(RerouteNode, {\r\n title_mode: LiteGraph.NO_TITLE,\r\n title: 'Reroute',\r\n collapsable: false\r\n })\r\n )\r\n\r\n RerouteNode.category = 'utils'\r\n }\r\n})\r\n","import { app } from '../../scripts/app'\r\nimport { applyTextReplacements } from '../../scripts/utils'\r\n// Use widget values and dates in output filenames\r\n\r\napp.registerExtension({\r\n name: 'Comfy.SaveImageExtraOutput',\r\n async beforeRegisterNodeDef(nodeType, nodeData, app) {\r\n if (nodeData.name === 'SaveImage' || nodeData.name === 'SaveAnimatedWEBP') {\r\n const onNodeCreated = nodeType.prototype.onNodeCreated\r\n // When the SaveImage node is created we want to override the serialization of the output name widget to run our S&R\r\n nodeType.prototype.onNodeCreated = function () {\r\n const r = onNodeCreated\r\n ? onNodeCreated.apply(this, arguments)\r\n : undefined\r\n\r\n const widget = this.widgets.find((w) => w.name === 'filename_prefix')\r\n widget.serializeValue = () => {\r\n return applyTextReplacements(app, widget.value)\r\n }\r\n\r\n return r\r\n }\r\n } else {\r\n // When any other node is created add a property to alias the node\r\n const onNodeCreated = nodeType.prototype.onNodeCreated\r\n nodeType.prototype.onNodeCreated = function () {\r\n const r = onNodeCreated\r\n ? onNodeCreated.apply(this, arguments)\r\n : undefined\r\n\r\n if (!this.properties || !('Node name for S&R' in this.properties)) {\r\n this.addProperty('Node name for S&R', this.constructor.type, 'string')\r\n }\r\n\r\n return r\r\n }\r\n }\r\n }\r\n})\r\n","import { app } from '../../scripts/app'\r\nimport { LGraphCanvas, LiteGraph } from '@comfyorg/litegraph'\r\n\r\nlet touchZooming\r\nlet touchCount = 0\r\n\r\napp.registerExtension({\r\n name: 'Comfy.SimpleTouchSupport',\r\n setup() {\r\n let zoomPos\r\n let touchTime\r\n let lastTouch\r\n\r\n function getMultiTouchPos(e) {\r\n return Math.hypot(\r\n e.touches[0].clientX - e.touches[1].clientX,\r\n e.touches[0].clientY - e.touches[1].clientY\r\n )\r\n }\r\n\r\n app.canvasEl.addEventListener(\r\n 'touchstart',\r\n (e) => {\r\n touchCount++\r\n lastTouch = null\r\n if (e.touches?.length === 1) {\r\n // Store start time for press+hold for context menu\r\n touchTime = new Date()\r\n lastTouch = e.touches[0]\r\n } else {\r\n touchTime = null\r\n if (e.touches?.length === 2) {\r\n // Store center pos for zoom\r\n zoomPos = getMultiTouchPos(e)\r\n app.canvas.pointer_is_down = false\r\n }\r\n }\r\n },\r\n true\r\n )\r\n\r\n app.canvasEl.addEventListener('touchend', (e: TouchEvent) => {\r\n touchZooming = false\r\n touchCount = e.touches?.length ?? touchCount - 1\r\n if (touchTime && !e.touches?.length) {\r\n if (new Date().getTime() - touchTime > 600) {\r\n try {\r\n // hack to get litegraph to use this event\r\n e.constructor = CustomEvent\r\n } catch (error) {}\r\n // @ts-expect-error\r\n e.clientX = lastTouch.clientX\r\n // @ts-expect-error\r\n e.clientY = lastTouch.clientY\r\n\r\n app.canvas.pointer_is_down = true\r\n // @ts-expect-error\r\n app.canvas._mousedown_callback(e)\r\n }\r\n touchTime = null\r\n }\r\n })\r\n\r\n app.canvasEl.addEventListener(\r\n 'touchmove',\r\n (e) => {\r\n touchTime = null\r\n if (e.touches?.length === 2) {\r\n app.canvas.pointer_is_down = false\r\n touchZooming = true\r\n // @ts-expect-error\r\n LiteGraph.closeAllContextMenus()\r\n // @ts-expect-error\r\n app.canvas.search_box?.close()\r\n const newZoomPos = getMultiTouchPos(e)\r\n\r\n const midX = (e.touches[0].clientX + e.touches[1].clientX) / 2\r\n const midY = (e.touches[0].clientY + e.touches[1].clientY) / 2\r\n\r\n let scale = app.canvas.ds.scale\r\n const diff = zoomPos - newZoomPos\r\n if (diff > 0.5) {\r\n scale *= 1 / 1.07\r\n } else if (diff < -0.5) {\r\n scale *= 1.07\r\n }\r\n app.canvas.ds.changeScale(scale, [midX, midY])\r\n app.canvas.setDirty(true, true)\r\n zoomPos = newZoomPos\r\n }\r\n },\r\n true\r\n )\r\n }\r\n})\r\n\r\nconst processMouseDown = LGraphCanvas.prototype.processMouseDown\r\nLGraphCanvas.prototype.processMouseDown = function (e) {\r\n if (touchZooming || touchCount) {\r\n return\r\n }\r\n return processMouseDown.apply(this, arguments)\r\n}\r\n\r\nconst processMouseMove = LGraphCanvas.prototype.processMouseMove\r\nLGraphCanvas.prototype.processMouseMove = function (e) {\r\n if (touchZooming || touchCount > 1) {\r\n return\r\n }\r\n return processMouseMove.apply(this, arguments)\r\n}\r\n","import { app } from '../../scripts/app'\r\nimport { ComfyWidgets } from '../../scripts/widgets'\r\nimport { LiteGraph } from '@comfyorg/litegraph'\r\n// Adds defaults for quickly adding nodes with middle click on the input/output\r\n\r\napp.registerExtension({\r\n name: 'Comfy.SlotDefaults',\r\n suggestionsNumber: null,\r\n init() {\r\n LiteGraph.search_filter_enabled = true\r\n LiteGraph.middle_click_slot_add_default_node = true\r\n this.suggestionsNumber = app.ui.settings.addSetting({\r\n id: 'Comfy.NodeSuggestions.number',\r\n name: 'Number of nodes suggestions',\r\n type: 'slider',\r\n attrs: {\r\n min: 1,\r\n max: 100,\r\n step: 1\r\n },\r\n defaultValue: 5,\r\n onChange: (newVal, oldVal) => {\r\n this.setDefaults(newVal)\r\n }\r\n })\r\n },\r\n slot_types_default_out: {},\r\n slot_types_default_in: {},\r\n async beforeRegisterNodeDef(nodeType, nodeData, app) {\r\n var nodeId = nodeData.name\r\n var inputs = []\r\n inputs = nodeData['input']['required'] //only show required inputs to reduce the mess also not logical to create node with optional inputs\r\n for (const inputKey in inputs) {\r\n var input = inputs[inputKey]\r\n if (typeof input[0] !== 'string') continue\r\n\r\n var type = input[0]\r\n if (type in ComfyWidgets) {\r\n var customProperties = input[1]\r\n if (!customProperties?.forceInput) continue //ignore widgets that don't force input\r\n }\r\n\r\n if (!(type in this.slot_types_default_out)) {\r\n this.slot_types_default_out[type] = ['Reroute']\r\n }\r\n if (this.slot_types_default_out[type].includes(nodeId)) continue\r\n this.slot_types_default_out[type].push(nodeId)\r\n\r\n // Input types have to be stored as lower case\r\n // Store each node that can handle this input type\r\n const lowerType = type.toLocaleLowerCase()\r\n if (!(lowerType in LiteGraph.registered_slot_in_types)) {\r\n LiteGraph.registered_slot_in_types[lowerType] = { nodes: [] }\r\n }\r\n LiteGraph.registered_slot_in_types[lowerType].nodes.push(\r\n nodeType.comfyClass\r\n )\r\n }\r\n\r\n var outputs = nodeData['output']\r\n for (const key in outputs) {\r\n var type = outputs[key] as string\r\n if (!(type in this.slot_types_default_in)) {\r\n this.slot_types_default_in[type] = ['Reroute'] // [\"Reroute\", \"Primitive\"]; primitive doesn't always work :'()\r\n }\r\n\r\n this.slot_types_default_in[type].push(nodeId)\r\n\r\n // Store each node that can handle this output type\r\n if (!(type in LiteGraph.registered_slot_out_types)) {\r\n LiteGraph.registered_slot_out_types[type] = { nodes: [] }\r\n }\r\n LiteGraph.registered_slot_out_types[type].nodes.push(nodeType.comfyClass)\r\n\r\n if (!LiteGraph.slot_types_out.includes(type)) {\r\n LiteGraph.slot_types_out.push(type)\r\n }\r\n }\r\n var maxNum = this.suggestionsNumber.value\r\n this.setDefaults(maxNum)\r\n },\r\n setDefaults(maxNum) {\r\n LiteGraph.slot_types_default_out = {}\r\n LiteGraph.slot_types_default_in = {}\r\n\r\n for (const type in this.slot_types_default_out) {\r\n LiteGraph.slot_types_default_out[type] = this.slot_types_default_out[\r\n type\r\n ].slice(0, maxNum)\r\n }\r\n for (const type in this.slot_types_default_in) {\r\n LiteGraph.slot_types_default_in[type] = this.slot_types_default_in[\r\n type\r\n ].slice(0, maxNum)\r\n }\r\n }\r\n})\r\n","import { app } from '../../scripts/app'\r\nimport {\r\n LGraphCanvas,\r\n LGraphNode,\r\n LGraphGroup,\r\n LiteGraph\r\n} from '@comfyorg/litegraph'\r\n\r\n// Shift + drag/resize to snap to grid\r\n\r\n/** Rounds a Vector2 in-place to the current CANVAS_GRID_SIZE. */\r\nfunction roundVectorToGrid(vec) {\r\n vec[0] =\r\n LiteGraph.CANVAS_GRID_SIZE * Math.round(vec[0] / LiteGraph.CANVAS_GRID_SIZE)\r\n vec[1] =\r\n LiteGraph.CANVAS_GRID_SIZE * Math.round(vec[1] / LiteGraph.CANVAS_GRID_SIZE)\r\n return vec\r\n}\r\n\r\napp.registerExtension({\r\n name: 'Comfy.SnapToGrid',\r\n init() {\r\n // Add setting to control grid size\r\n app.ui.settings.addSetting({\r\n id: 'Comfy.SnapToGrid.GridSize',\r\n name: 'Grid Size',\r\n type: 'slider',\r\n attrs: {\r\n min: 1,\r\n max: 500\r\n },\r\n tooltip:\r\n 'When dragging and resizing nodes while holding shift they will be aligned to the grid, this controls the size of that grid.',\r\n defaultValue: LiteGraph.CANVAS_GRID_SIZE,\r\n onChange(value) {\r\n LiteGraph.CANVAS_GRID_SIZE = +value\r\n }\r\n })\r\n\r\n // After moving a node, if the shift key is down align it to grid\r\n const onNodeMoved = app.canvas.onNodeMoved\r\n app.canvas.onNodeMoved = function (node) {\r\n const r = onNodeMoved?.apply(this, arguments)\r\n\r\n if (app.shiftDown) {\r\n // Ensure all selected nodes are realigned\r\n for (const id in this.selected_nodes) {\r\n this.selected_nodes[id].alignToGrid()\r\n }\r\n }\r\n\r\n return r\r\n }\r\n\r\n // When a node is added, add a resize handler to it so we can fix align the size with the grid\r\n const onNodeAdded = app.graph.onNodeAdded\r\n app.graph.onNodeAdded = function (node) {\r\n const onResize = node.onResize\r\n node.onResize = function () {\r\n if (app.shiftDown) {\r\n roundVectorToGrid(node.size)\r\n }\r\n return onResize?.apply(this, arguments)\r\n }\r\n return onNodeAdded?.apply(this, arguments)\r\n }\r\n\r\n // Draw a preview of where the node will go if holding shift and the node is selected\r\n const origDrawNode = LGraphCanvas.prototype.drawNode\r\n LGraphCanvas.prototype.drawNode = function (node, ctx) {\r\n if (\r\n app.shiftDown &&\r\n this.node_dragged &&\r\n node.id in this.selected_nodes\r\n ) {\r\n const [x, y] = roundVectorToGrid([...node.pos])\r\n const shiftX = x - node.pos[0]\r\n let shiftY = y - node.pos[1]\r\n\r\n let w, h\r\n if (node.flags.collapsed) {\r\n // @ts-expect-error\r\n w = node._collapsed_width\r\n h = LiteGraph.NODE_TITLE_HEIGHT\r\n shiftY -= LiteGraph.NODE_TITLE_HEIGHT\r\n } else {\r\n w = node.size[0]\r\n h = node.size[1]\r\n // @ts-expect-error\r\n let titleMode = node.constructor.title_mode\r\n if (\r\n titleMode !== LiteGraph.TRANSPARENT_TITLE &&\r\n titleMode !== LiteGraph.NO_TITLE\r\n ) {\r\n h += LiteGraph.NODE_TITLE_HEIGHT\r\n shiftY -= LiteGraph.NODE_TITLE_HEIGHT\r\n }\r\n }\r\n const f = ctx.fillStyle\r\n ctx.fillStyle = 'rgba(100, 100, 100, 0.5)'\r\n ctx.fillRect(shiftX, shiftY, w, h)\r\n ctx.fillStyle = f\r\n }\r\n\r\n return origDrawNode.apply(this, arguments)\r\n }\r\n\r\n /**\r\n * The currently moving, selected group only. Set after the `selected_group` has actually started\r\n * moving.\r\n */\r\n let selectedAndMovingGroup: LGraphGroup | null = null\r\n\r\n /**\r\n * Handles moving a group; tracking when a group has been moved (to show the ghost in `drawGroups`\r\n * below) as well as handle the last move call from LiteGraph's `processMouseUp`.\r\n */\r\n const groupMove = LGraphGroup.prototype.move\r\n LGraphGroup.prototype.move = function (deltax, deltay, ignore_nodes) {\r\n const v = groupMove.apply(this, arguments)\r\n // When we've started moving, set `selectedAndMovingGroup` as LiteGraph sets `selected_group`\r\n // too eagerly and we don't want to behave like we're moving until we get a delta.\r\n if (\r\n !selectedAndMovingGroup &&\r\n app.canvas.selected_group === this &&\r\n (deltax || deltay)\r\n ) {\r\n selectedAndMovingGroup = this\r\n }\r\n\r\n // LiteGraph will call group.move both on mouse-move as well as mouse-up though we only want\r\n // to snap on a mouse-up which we can determine by checking if `app.canvas.last_mouse_dragging`\r\n // has been set to `false`. Essentially, this check here is the equivalent to calling an\r\n // `LGraphGroup.prototype.onNodeMoved` if it had existed.\r\n if (app.canvas.last_mouse_dragging === false && app.shiftDown) {\r\n // After moving a group (while app.shiftDown), snap all the child nodes and, finally,\r\n // align the group itself.\r\n this.recomputeInsideNodes()\r\n for (const node of this._nodes) {\r\n node.alignToGrid()\r\n }\r\n LGraphNode.prototype.alignToGrid.apply(this)\r\n }\r\n return v\r\n }\r\n\r\n /**\r\n * Handles drawing a group when, snapping the size when one is actively being resized tracking and/or\r\n * drawing a ghost box when one is actively being moved. This mimics the node snapping behavior for\r\n * both.\r\n */\r\n const drawGroups = LGraphCanvas.prototype.drawGroups\r\n LGraphCanvas.prototype.drawGroups = function (canvas, ctx) {\r\n if (this.selected_group && app.shiftDown) {\r\n if (this.selected_group_resizing) {\r\n roundVectorToGrid(this.selected_group.size)\r\n } else if (selectedAndMovingGroup) {\r\n // @ts-expect-error\r\n const [x, y] = roundVectorToGrid([...selectedAndMovingGroup.pos])\r\n const f = ctx.fillStyle\r\n const s = ctx.strokeStyle\r\n ctx.fillStyle = 'rgba(100, 100, 100, 0.33)'\r\n ctx.strokeStyle = 'rgba(100, 100, 100, 0.66)'\r\n // @ts-expect-error\r\n ctx.rect(x, y, ...selectedAndMovingGroup.size)\r\n ctx.fill()\r\n ctx.stroke()\r\n ctx.fillStyle = f\r\n ctx.strokeStyle = s\r\n }\r\n } else if (!this.selected_group) {\r\n selectedAndMovingGroup = null\r\n }\r\n return drawGroups.apply(this, arguments)\r\n }\r\n\r\n /** Handles adding a group in a snapping-enabled state. */\r\n const onGroupAdd = LGraphCanvas.onGroupAdd\r\n LGraphCanvas.onGroupAdd = function () {\r\n const v = onGroupAdd.apply(app.canvas, arguments)\r\n if (app.shiftDown) {\r\n // @ts-expect-error\r\n const lastGroup = app.graph._groups[app.graph._groups.length - 1]\r\n if (lastGroup) {\r\n // @ts-expect-error\r\n roundVectorToGrid(lastGroup.pos)\r\n // @ts-expect-error\r\n roundVectorToGrid(lastGroup.size)\r\n }\r\n }\r\n return v\r\n }\r\n }\r\n})\r\n","import { app } from '../../scripts/app'\r\nimport { ComfyNodeDef } from '@/types/apiTypes'\r\n\r\n// Adds an upload button to the nodes\r\n\r\napp.registerExtension({\r\n name: 'Comfy.UploadImage',\r\n async beforeRegisterNodeDef(nodeType, nodeData: ComfyNodeDef, app) {\r\n if (nodeData?.input?.required?.image?.[1]?.image_upload === true) {\r\n nodeData.input.required.upload = ['IMAGEUPLOAD']\r\n }\r\n }\r\n})\r\n","import { app } from '../../scripts/app'\r\nimport { api } from '../../scripts/api'\r\n\r\nconst WEBCAM_READY = Symbol()\r\n\r\napp.registerExtension({\r\n name: 'Comfy.WebcamCapture',\r\n getCustomWidgets(app) {\r\n return {\r\n WEBCAM(node, inputName) {\r\n let res\r\n node[WEBCAM_READY] = new Promise((resolve) => (res = resolve))\r\n\r\n const container = document.createElement('div')\r\n container.style.background = 'rgba(0,0,0,0.25)'\r\n container.style.textAlign = 'center'\r\n\r\n const video = document.createElement('video')\r\n video.style.height = video.style.width = '100%'\r\n\r\n const loadVideo = async () => {\r\n try {\r\n const stream = await navigator.mediaDevices.getUserMedia({\r\n video: true,\r\n audio: false\r\n })\r\n container.replaceChildren(video)\r\n\r\n setTimeout(() => res(video), 500) // Fallback as loadedmetadata doesnt fire sometimes?\r\n video.addEventListener('loadedmetadata', () => res(video), false)\r\n video.srcObject = stream\r\n video.play()\r\n } catch (error) {\r\n const label = document.createElement('div')\r\n label.style.color = 'red'\r\n label.style.overflow = 'auto'\r\n label.style.maxHeight = '100%'\r\n label.style.whiteSpace = 'pre-wrap'\r\n\r\n if (window.isSecureContext) {\r\n label.textContent =\r\n 'Unable to load webcam, please ensure access is granted:\\n' +\r\n error.message\r\n } else {\r\n label.textContent =\r\n 'Unable to load webcam. A secure context is required, if you are not accessing ComfyUI on localhost (127.0.0.1) you will have to enable TLS (https)\\n\\n' +\r\n error.message\r\n }\r\n\r\n container.replaceChildren(label)\r\n }\r\n }\r\n\r\n loadVideo()\r\n\r\n return { widget: node.addDOMWidget(inputName, 'WEBCAM', container) }\r\n }\r\n }\r\n },\r\n nodeCreated(node) {\r\n if ((node.type, node.constructor.comfyClass !== 'WebcamCapture')) return\r\n\r\n let video\r\n const camera = node.widgets.find((w) => w.name === 'image')\r\n const w = node.widgets.find((w) => w.name === 'width')\r\n const h = node.widgets.find((w) => w.name === 'height')\r\n const captureOnQueue = node.widgets.find(\r\n (w) => w.name === 'capture_on_queue'\r\n )\r\n\r\n const canvas = document.createElement('canvas')\r\n\r\n const capture = () => {\r\n canvas.width = w.value\r\n canvas.height = h.value\r\n const ctx = canvas.getContext('2d')\r\n ctx.drawImage(video, 0, 0, w.value, h.value)\r\n const data = canvas.toDataURL('image/png')\r\n\r\n const img = new Image()\r\n img.onload = () => {\r\n node.imgs = [img]\r\n app.graph.setDirtyCanvas(true)\r\n requestAnimationFrame(() => {\r\n node.setSizeForImage?.()\r\n })\r\n }\r\n img.src = data\r\n }\r\n\r\n const btn = node.addWidget(\r\n 'button',\r\n 'waiting for camera...',\r\n 'capture',\r\n capture\r\n )\r\n btn.disabled = true\r\n btn.serializeValue = () => undefined\r\n\r\n camera.serializeValue = async () => {\r\n if (captureOnQueue.value) {\r\n capture()\r\n } else if (!node.imgs?.length) {\r\n const err = `No webcam image captured`\r\n alert(err)\r\n throw new Error(err)\r\n }\r\n\r\n // Upload image to temp storage\r\n const blob = await new Promise((r) => canvas.toBlob(r))\r\n const name = `${+new Date()}.png`\r\n const file = new File([blob], name)\r\n const body = new FormData()\r\n body.append('image', file)\r\n body.append('subfolder', 'webcam')\r\n body.append('type', 'temp')\r\n const resp = await api.fetchApi('/upload/image', {\r\n method: 'POST',\r\n body\r\n })\r\n if (resp.status !== 200) {\r\n const err = `Error uploading camera image: ${resp.status} - ${resp.statusText}`\r\n alert(err)\r\n throw new Error(err)\r\n }\r\n return `webcam/${name} [temp]`\r\n }\r\n\r\n node[WEBCAM_READY].then((v) => {\r\n video = v\r\n // If width isnt specified then use video output resolution\r\n if (!w.value) {\r\n w.value = video.videoWidth || 640\r\n h.value = video.videoHeight || 480\r\n }\r\n btn.disabled = false\r\n btn.label = 'capture'\r\n })\r\n }\r\n})\r\n","import { app } from '../../scripts/app'\r\nimport { api } from '../../scripts/api'\r\nimport type { IWidget } from '@comfyorg/litegraph'\r\nimport type { DOMWidget } from '@/scripts/domWidget'\r\nimport { ComfyNodeDef } from '@/types/apiTypes'\r\n\r\ntype FolderType = 'input' | 'output' | 'temp'\r\n\r\nfunction splitFilePath(path: string): [string, string] {\r\n const folder_separator = path.lastIndexOf('/')\r\n if (folder_separator === -1) {\r\n return ['', path]\r\n }\r\n return [\r\n path.substring(0, folder_separator),\r\n path.substring(folder_separator + 1)\r\n ]\r\n}\r\n\r\nfunction getResourceURL(\r\n subfolder: string,\r\n filename: string,\r\n type: FolderType = 'input'\r\n): string {\r\n const params = [\r\n 'filename=' + encodeURIComponent(filename),\r\n 'type=' + type,\r\n 'subfolder=' + subfolder,\r\n app.getRandParam().substring(1)\r\n ].join('&')\r\n\r\n return `/view?${params}`\r\n}\r\n\r\nasync function uploadFile(\r\n audioWidget: IWidget,\r\n audioUIWidget: DOMWidget,\r\n file: File,\r\n updateNode: boolean,\r\n pasted: boolean = false\r\n) {\r\n try {\r\n // Wrap file in formdata so it includes filename\r\n const body = new FormData()\r\n body.append('image', file)\r\n if (pasted) body.append('subfolder', 'pasted')\r\n const resp = await api.fetchApi('/upload/image', {\r\n method: 'POST',\r\n body\r\n })\r\n\r\n if (resp.status === 200) {\r\n const data = await resp.json()\r\n // Add the file to the dropdown list and update the widget value\r\n let path = data.name\r\n if (data.subfolder) path = data.subfolder + '/' + path\r\n\r\n if (!audioWidget.options.values.includes(path)) {\r\n audioWidget.options.values.push(path)\r\n }\r\n\r\n if (updateNode) {\r\n audioUIWidget.element.src = api.apiURL(\r\n getResourceURL(...splitFilePath(path))\r\n )\r\n audioWidget.value = path\r\n }\r\n } else {\r\n alert(resp.status + ' - ' + resp.statusText)\r\n }\r\n } catch (error) {\r\n alert(error)\r\n }\r\n}\r\n\r\n// AudioWidget MUST be registered first, as AUDIOUPLOAD depends on AUDIO_UI to be\r\n// present.\r\napp.registerExtension({\r\n name: 'Comfy.AudioWidget',\r\n async beforeRegisterNodeDef(nodeType, nodeData) {\r\n if (\r\n ['LoadAudio', 'SaveAudio', 'PreviewAudio'].includes(nodeType.comfyClass)\r\n ) {\r\n nodeData.input.required.audioUI = ['AUDIO_UI']\r\n }\r\n },\r\n getCustomWidgets() {\r\n return {\r\n AUDIO_UI(node, inputName: string) {\r\n const audio = document.createElement('audio')\r\n audio.controls = true\r\n audio.classList.add('comfy-audio')\r\n audio.setAttribute('name', 'media')\r\n\r\n const audioUIWidget: DOMWidget = node.addDOMWidget(\r\n inputName,\r\n /* name=*/ 'audioUI',\r\n audio\r\n )\r\n // @ts-expect-error\r\n // TODO: Sort out the DOMWidget type.\r\n audioUIWidget.serialize = false\r\n\r\n const isOutputNode = node.constructor.nodeData.output_node\r\n if (isOutputNode) {\r\n // Hide the audio widget when there is no audio initially.\r\n audioUIWidget.element.classList.add('empty-audio-widget')\r\n // Populate the audio widget UI on node execution.\r\n const onExecuted = node.onExecuted\r\n node.onExecuted = function (message) {\r\n onExecuted?.apply(this, arguments)\r\n const audios = message.audio\r\n if (!audios) return\r\n const audio = audios[0]\r\n audioUIWidget.element.src = api.apiURL(\r\n getResourceURL(audio.subfolder, audio.filename, audio.type)\r\n )\r\n audioUIWidget.element.classList.remove('empty-audio-widget')\r\n }\r\n }\r\n return { widget: audioUIWidget }\r\n }\r\n }\r\n },\r\n onNodeOutputsUpdated(nodeOutputs: Record) {\r\n for (const [nodeId, output] of Object.entries(nodeOutputs)) {\r\n const node = app.graph.getNodeById(Number.parseInt(nodeId))\r\n if ('audio' in output) {\r\n const audioUIWidget = node.widgets.find(\r\n (w) => w.name === 'audioUI'\r\n ) as unknown as DOMWidget\r\n const audio = output.audio[0]\r\n audioUIWidget.element.src = api.apiURL(\r\n getResourceURL(audio.subfolder, audio.filename, audio.type)\r\n )\r\n audioUIWidget.element.classList.remove('empty-audio-widget')\r\n }\r\n }\r\n }\r\n})\r\n\r\napp.registerExtension({\r\n name: 'Comfy.UploadAudio',\r\n async beforeRegisterNodeDef(nodeType, nodeData: ComfyNodeDef) {\r\n if (nodeData?.input?.required?.audio?.[1]?.audio_upload === true) {\r\n nodeData.input.required.upload = ['AUDIOUPLOAD']\r\n }\r\n },\r\n getCustomWidgets() {\r\n return {\r\n AUDIOUPLOAD(node, inputName: string) {\r\n // The widget that allows user to select file.\r\n const audioWidget: IWidget = node.widgets.find(\r\n (w: IWidget) => w.name === 'audio'\r\n )\r\n const audioUIWidget: DOMWidget = node.widgets.find(\r\n (w: IWidget) => w.name === 'audioUI'\r\n )\r\n\r\n const onAudioWidgetUpdate = () => {\r\n audioUIWidget.element.src = api.apiURL(\r\n getResourceURL(...splitFilePath(audioWidget.value))\r\n )\r\n }\r\n // Initially load default audio file to audioUIWidget.\r\n if (audioWidget.value) {\r\n onAudioWidgetUpdate()\r\n }\r\n audioWidget.callback = onAudioWidgetUpdate\r\n\r\n // Load saved audio file widget values if restoring from workflow\r\n const onGraphConfigured = node.onGraphConfigured\r\n node.onGraphConfigured = function () {\r\n onGraphConfigured?.apply(this, arguments)\r\n if (audioWidget.value) {\r\n onAudioWidgetUpdate()\r\n }\r\n }\r\n\r\n const fileInput = document.createElement('input')\r\n fileInput.type = 'file'\r\n fileInput.accept = 'audio/*'\r\n fileInput.style.display = 'none'\r\n fileInput.onchange = () => {\r\n if (fileInput.files.length) {\r\n uploadFile(audioWidget, audioUIWidget, fileInput.files[0], true)\r\n }\r\n }\r\n // The widget to pop up the upload dialog.\r\n const uploadWidget = node.addWidget(\r\n 'button',\r\n inputName,\r\n /* value=*/ '',\r\n () => {\r\n fileInput.click()\r\n }\r\n )\r\n uploadWidget.label = 'choose file to upload'\r\n uploadWidget.serialize = false\r\n\r\n return { widget: uploadWidget }\r\n }\r\n }\r\n }\r\n})\r\n"],"names":["app","id","file","ext","prompt","links","_a","widget","_b","w","type","_c","def","node","link","selectedIds","newNodes","i","group","modal","x","y","audio"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIO,MAAM,mBAAN,MAAM,yBAAwB,YAAY;AAAA,EAI/C,OAAO,eAAe,MAAM,kBAAkB,UAAU;AAChD,UAAA,OAAO,IAAI,UAAU;AAAA,MACzB,MAAM;AAAA,MACN,aAAa;AAAA,MACb;AAAA,MACA,SAAS;AAAA,IAAA,CACV;AAEe,qBAAA,MAAM,KAAK,IAAI;AAAA,EACjC;AAAA,EAEA,OAAO,oBAAoB;AAEvB,QAAA,SAAS,aACT,SAAS,UAAU,QACnB,SAAS,UAAU,KAAK,SAAS,GACjC;AACA,YAAM,cAAc,SAAS;AAAA,QAC3B;AAAA,MAAA;AAEF,UAAI,aAAa;AACH,oBAAA,MACV,SAAS,UAAU,KAAK,SAAS,UAAU,eAAe,CAAC,EAAE;AAC/D,oBAAY,MAAM,YAAY;AAC9B,oBAAY,MAAM,WAAW;AAAA,MAC/B;AAAA,IACF;AAAA,EACF;AAAA,EAEA,OAAO,aAAa;AAClB,QAAI,iBAAgB,UAAU;AAC5B,YAAM,OAAO,iBAAgB;AAEvB,YAAA,WAAW,IAAI,2BAA2B;AAAA,QAC9C,KAAK,kBAAkB;AAAA,QACvB,GAAG,KAAK,cAAc;AAAA,MAAA,CACvB;AAED,UAAI,KAAK,SAAS;AAEhB,aAAK,QAAQ,YAAY,KAAK,QAAQ,UAAU;AAC3C,aAAA,QAAQ,YAAY,QAAQ;AAAA,MAAA,OAC5B;AAEL,aAAK,UAAU,IAAI,mBAAmB,EAAE,QAAQ,SAAS,QAAQ;AAAA,UAC/D;AAAA,QAAA,CACD;AAAA,MACH;AAEA,UAAI,KAAK,QAAQ,SAAS,CAAC,EAAE,SAAS,UAAU,GAAG;AAC5C,aAAA,QAAQ,SAAS,CAAC,EAAE;AAAA,UACvB,IAAI,KAAK,IAAI;AAAA,YACX;AAAA,UAAA,CACD;AAAA,QAAA;AAAA,MAEL;AAEA,uBAAgB,kBAAkB;AAAA,IACpC;AAAA,EACF;AAAA,EAEA,cAAc;AACN;EACR;AAAA,EAEA,gBAAgB;AACd,UAAM,UAAU,CAAA;AAEP,aAAA,OAAO,iBAAgB,OAAO;AAC/B,YAAA,OAAO,iBAAgB,MAAM,GAAG;AACtC,UAAI,CAAC,KAAK,oBAAoB,KAAK,iBAAiB;AAClD,gBAAQ,KAAK,iBAAgB,MAAM,GAAG,CAAC;AAAA,IAC3C;AAEQ,YAAA;AAAA,MACN,IAAI,UAAU;AAAA,QACZ,MAAM;AAAA,QACN,aAAa;AAAA,QACb,SAAS,MAAM;AACb,eAAK,MAAM;AAAA,QACb;AAAA,MAAA,CACD;AAAA,IAAA;AAGI,WAAA;AAAA,EACT;AAAA,EAEA,oBAAoB;AACd,QAAA,SAAS,UAAU,MAAM;AAC3B,YAAM,cAAc,CAAA;AACd,YAAA,OAAO,SAAS,UAAU;AAEhC,eAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;AACpC,oBAAY,KAAK,IAAI,UAAU,EAAE,OAAO,EAAK,GAAA,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;AAAA,MACxD;AAEA,YAAM,SAAS;AAAA,QACb;AAAA,QACA;AAAA,UACE,IAAI;AAAA,UACJ,UAAU,CAAC,UAAU;AACnB,qBAAS,UAAU,eAAe,IAAI,MAAM,OAAO;AACnD,6BAAgB,kBAAkB;AAAA,UACpC;AAAA,QACF;AAAA,QACA;AAAA,MAAA;AAGF,YAAM,OAAO,IAAI,MAAM,IAAI;AAAA,QACzB,IAAI,MAAM,IAAI,CAAC,IAAI,QAAQ,EAAE,OAAO,QAAW,GAAA,CAAC,cAAc,CAAC,CAAC,CAAC;AAAA,QACjE,IAAI,MAAM,IAAI,CAAC,MAAM,CAAC;AAAA,MAAA,CACvB;AAED,YAAM,SAAS;AAAA,QACb;AAAA,QACA;AAAA,UACE,IAAI;AAAA,UACJ,UAAU,CAAC,UAAU;AACnB,qBAAS,UAAU,gBAAgB,IAAI,MAAM,OAAO;AAAA,UACtD;AAAA,QACF;AAAA,QACA;AAAA,UACE,IAAI,UAAU,EAAE,OAAO,WAAA,GAAc,UAAU;AAAA,UAC/C,IAAI,UAAU,EAAE,OAAO,MAAA,GAAS,KAAK;AAAA,QACvC;AAAA,MAAA;AAEK,aAAA,QAAQ,SAAS,UAAU,gBAAgB;AAElD,YAAM,OAAO,IAAI,MAAM,IAAI;AAAA,QACzB,IAAI,MAAM,IAAI,CAAC,IAAI,QAAQ,EAAE,OAAO,QAAW,GAAA,CAAC,YAAY,CAAC,CAAC,CAAC;AAAA,QAC/D,IAAI,MAAM,IAAI,CAAC,MAAM,CAAC;AAAA,MAAA,CACvB;AAED,YAAM,KAAK;AAAA,QACT;AAAA,QACA,EAAE,OAAO,UAAU,OAAO,SAAS,QAAQ,SAAS,SAAS,IAAI;AAAA,QACjE,CAAC,IAAI,OAAO,EAAE,IAAI,qBAAqB,aAAa,MAAM,SAAS,CAAA,CAAE,CAAC;AAAA,MAAA;AAGxE,YAAM,OAAO,IAAI,MAAM,CAAA,GAAI,CAAC,EAAE,CAAC;AAExB,aAAA,IAAI,SAAS,CAAC,GAAG,CAAC,MAAM,MAAM,IAAI,CAAC;AAAA,IAAA,OACrC;AACL,aAAO;IACT;AAAA,EACF;AAAA,EAEA,mBAAmB;AACb,QAAA,SAAS,UAAU,MAAM;AACpB,aAAA,IAAI,OAAO,EAAE,IAAI,qBAAqB,aAAa,MAAM,OAAO;AAAA,IACzE,cAAc,CAAA;AAAA,EAChB;AAAA,EAEA,OAAO;AACC,UAAA,cAAc,SAAS,eAAe,mBAAmB;AAC/D,qBAAgB,WAAW;AAEtB,SAAA,QAAQ,MAAM,UAAU;AAAA,EAC/B;AACF;AAlKE,cADW,kBACJ,SAAQ,CAAA;AACf,cAFW,kBAEJ,YAAW;AAFb,IAAM,kBAAN;AAqKP,IAAI,kBAAkB;AAAA,EACpB,MAAM;AAAA,EACN,KAAKA,MAAK;AACRA,SAAI,gBAAgB,WAAY;AAC1B,UAAA,CAAC,gBAAgB,UAAU;AACb,wBAAA,WAAW,IAAI;AAC/B,iBAAS,+BAA+B,gBAAgB;AAAA,MAC1D;AAEA,UAAI,SAAS,WAAW;AACtB,wBAAgB,SAAS;YACpBA,MAAI,GAAG,OAAO,KAAK,qBAAqB;AAAA,IAAA;AAAA,EAEnD;AACF,CAAC;;;;AC/KD,MAAM,gBAA+B;AAAA,EACnC,MAAM;AAAA,IACJ,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,QAAQ;AAAA,MACN,WAAW;AAAA,QACT,MAAM;AAAA;AAAA,QACN,aAAa;AAAA;AAAA,QACb,oBAAoB;AAAA;AAAA,QACpB,cAAc;AAAA;AAAA,QACd,aAAa;AAAA;AAAA,QACb,OAAO;AAAA;AAAA,QACP,QAAQ;AAAA;AAAA,QACR,MAAM;AAAA;AAAA,QACN,OAAO;AAAA;AAAA,QACP,aAAa;AAAA;AAAA,QACb,KAAK;AAAA;AAAA,QACL,OAAO;AAAA;AAAA,QACP,QAAQ;AAAA;AAAA,QACR,SAAS;AAAA;AAAA,QACT,QAAQ;AAAA;AAAA,QACR,OAAO;AAAA;AAAA,MACT;AAAA,MACA,gBAAgB;AAAA,QACd,kBACE;AAAA,QACF,wBAAwB;AAAA,QACxB,kBAAkB;AAAA,QAClB,2BAA2B;AAAA,QAC3B,gBAAgB;AAAA,QAChB,iBAAiB;AAAA,QACjB,mBAAmB;AAAA,QACnB,oBAAoB;AAAA,QACpB,sBAAsB;AAAA,QACtB,uBAAuB;AAAA,QACvB,oBAAoB;AAAA,QACpB,wBAAwB;AAAA,QACxB,sBAAsB;AAAA,QACtB,oBAAoB;AAAA,QAEpB,gBAAgB;AAAA,QAChB,sBAAsB;AAAA,QACtB,mBAAmB;AAAA,QACnB,6BAA6B;AAAA,QAE7B,YAAY;AAAA,QACZ,kBAAkB;AAAA,QAClB,uBAAuB;AAAA,MACzB;AAAA,MACA,YAAY;AAAA,QACV,YAAY;AAAA,QACZ,YAAY;AAAA,QACZ,iBAAiB;AAAA,QACjB,kBAAkB;AAAA,QAClB,cAAc;AAAA,QACd,gBAAgB;AAAA,QAChB,aAAa;AAAA,QACb,cAAc;AAAA,QACd,gBAAgB;AAAA,QAChB,oBAAoB;AAAA,QACpB,mBAAmB;AAAA,QACnB,cAAc;AAAA,QACd,cAAc;AAAA,QACd,oBAAoB;AAAA,QACpB,oBAAoB;AAAA,MACtB;AAAA,IACF;AAAA,EACF;AAAA,EACA,OAAO;AAAA,IACL,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,QAAQ;AAAA,MACN,WAAW;AAAA,QACT,MAAM;AAAA;AAAA,QACN,aAAa;AAAA;AAAA,QACb,oBAAoB;AAAA;AAAA,QACpB,cAAc;AAAA;AAAA,QACd,aAAa;AAAA;AAAA,QACb,OAAO;AAAA;AAAA,QACP,QAAQ;AAAA;AAAA,QACR,MAAM;AAAA;AAAA,QACN,OAAO;AAAA;AAAA,QACP,aAAa;AAAA;AAAA,QACb,KAAK;AAAA;AAAA,MACP;AAAA,MACA,gBAAgB;AAAA,QACd,kBACE;AAAA,QACF,wBAAwB;AAAA,QACxB,kBAAkB;AAAA,QAClB,2BAA2B;AAAA,QAC3B,gBAAgB;AAAA,QAChB,iBAAiB;AAAA,QACjB,mBAAmB;AAAA,QACnB,oBAAoB;AAAA,QACpB,sBAAsB;AAAA,QACtB,uBAAuB;AAAA,QACvB,oBAAoB;AAAA,QACpB,wBAAwB;AAAA,QACxB,sBAAsB;AAAA,QACtB,oBAAoB;AAAA,QAEpB,gBAAgB;AAAA,QAChB,sBAAsB;AAAA,QACtB,mBAAmB;AAAA,QACnB,6BAA6B;AAAA,QAE7B,YAAY;AAAA,QACZ,kBAAkB;AAAA,QAClB,uBAAuB;AAAA,MACzB;AAAA,MACA,YAAY;AAAA,QACV,YAAY;AAAA,QACZ,YAAY;AAAA,QACZ,iBAAiB;AAAA,QACjB,kBAAkB;AAAA,QAClB,cAAc;AAAA,QACd,gBAAgB;AAAA,QAChB,aAAa;AAAA,QACb,cAAc;AAAA,QACd,gBAAgB;AAAA,QAChB,oBAAoB;AAAA,QACpB,mBAAmB;AAAA,QACnB,cAAc;AAAA,QACd,cAAc;AAAA,QACd,oBAAoB;AAAA,QACpB,oBAAoB;AAAA,MACtB;AAAA,IACF;AAAA,EACF;AAAA,EACA,WAAW;AAAA,IACT,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,QAAQ;AAAA,MACN,WAAW;AAAA,QACT,MAAM;AAAA;AAAA,QACN,aAAa;AAAA;AAAA,QACb,oBAAoB;AAAA;AAAA,QACpB,cAAc;AAAA;AAAA,QACd,aAAa;AAAA;AAAA,QACb,OAAO;AAAA;AAAA,QACP,QAAQ;AAAA;AAAA,QACR,MAAM;AAAA;AAAA,QACN,OAAO;AAAA;AAAA,QACP,aAAa;AAAA;AAAA,QACb,eAAe;AAAA;AAAA,QACf,KAAK;AAAA;AAAA,MACP;AAAA,MACA,gBAAgB;AAAA,QACd,kBAAkB;AAAA;AAAA,QAClB,2BAA2B;AAAA,QAC3B,gBAAgB;AAAA,QAChB,iBAAiB;AAAA;AAAA,QACjB,mBAAmB;AAAA,QACnB,oBAAoB;AAAA,QACpB,sBAAsB;AAAA;AAAA,QACtB,uBAAuB;AAAA;AAAA,QACvB,oBAAoB;AAAA,QACpB,wBAAwB;AAAA;AAAA,QACxB,sBAAsB;AAAA,QACtB,oBAAoB;AAAA,QAEpB,gBAAgB;AAAA;AAAA,QAChB,sBAAsB;AAAA;AAAA,QACtB,mBAAmB;AAAA;AAAA,QACnB,6BAA6B;AAAA;AAAA,QAE7B,YAAY;AAAA;AAAA,QACZ,kBAAkB;AAAA;AAAA,QAClB,uBAAuB;AAAA;AAAA,MACzB;AAAA,MACA,YAAY;AAAA,QACV,YAAY;AAAA;AAAA,QACZ,YAAY;AAAA;AAAA,QACZ,iBAAiB;AAAA;AAAA,QACjB,kBAAkB;AAAA;AAAA,QAClB,cAAc;AAAA;AAAA,QACd,gBAAgB;AAAA;AAAA,QAChB,aAAa;AAAA;AAAA,QACb,cAAc;AAAA;AAAA,QACd,gBAAgB;AAAA;AAAA,QAChB,oBAAoB;AAAA,QACpB,mBAAmB;AAAA,QACnB,cAAc;AAAA,QACd,cAAc;AAAA,QACd,oBAAoB;AAAA,QACpB,oBAAoB;AAAA,MACtB;AAAA,IACF;AAAA,EACF;AAAA,EACA,KAAK;AAAA,IACH,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,QAAQ;AAAA,MACN,WAAW;AAAA,QACT,SAAS;AAAA,QACT,MAAM;AAAA,QACN,aAAa;AAAA,QACb,oBAAoB;AAAA,QACpB,cAAc;AAAA,QACd,aAAa;AAAA,QACb,qBAAqB;AAAA,QACrB,OAAO;AAAA,QACP,QAAQ;AAAA,QACR,OAAO;AAAA,QACP,aAAa;AAAA,QACb,KAAK;AAAA,QACL,QAAQ;AAAA,QACR,iBAAiB;AAAA,QACjB,MAAM;AAAA,QACN,OAAO;AAAA,QACP,SAAS;AAAA,QACT,QAAQ;AAAA,QACR,QAAQ;AAAA,QACR,aAAa;AAAA,QACb,qBAAqB;AAAA,QACrB,OAAO;AAAA,QACP,mBAAmB;AAAA,QACnB,eAAe;AAAA,QACf,KAAK;AAAA,MACP;AAAA,MACA,gBAAgB;AAAA,QACd,kBACE;AAAA,QACF,wBAAwB;AAAA,QACxB,kBAAkB;AAAA,QAClB,2BAA2B;AAAA,QAC3B,gBAAgB;AAAA,QAChB,iBAAiB;AAAA,QACjB,mBAAmB;AAAA,QACnB,oBAAoB;AAAA,QACpB,sBAAsB;AAAA,QACtB,uBAAuB;AAAA,QACvB,oBAAoB;AAAA,QACpB,wBAAwB;AAAA,QACxB,sBAAsB;AAAA,QACtB,oBAAoB;AAAA,QACpB,gBAAgB;AAAA,QAChB,sBAAsB;AAAA,QACtB,mBAAmB;AAAA,QACnB,6BAA6B;AAAA,QAC7B,YAAY;AAAA,QACZ,kBAAkB;AAAA,QAClB,uBAAuB;AAAA,MACzB;AAAA,MACA,YAAY;AAAA,QACV,YAAY;AAAA,QACZ,YAAY;AAAA,QACZ,iBAAiB;AAAA,QACjB,kBAAkB;AAAA,QAClB,cAAc;AAAA,QACd,gBAAgB;AAAA,QAChB,aAAa;AAAA,QACb,cAAc;AAAA,QACd,gBAAgB;AAAA,QAChB,oBAAoB;AAAA,QACpB,mBAAmB;AAAA,QACnB,cAAc;AAAA,QACd,cAAc;AAAA,QACd,oBAAoB;AAAA,QACpB,oBAAoB;AAAA,MACtB;AAAA,IACF;AAAA,EACF;AAAA,EACA,MAAM;AAAA,IACJ,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,QAAQ;AAAA,MACN,WAAW;AAAA,QACT,SAAS;AAAA,QACT,MAAM;AAAA,QACN,aAAa;AAAA,QACb,oBAAoB;AAAA,QACpB,cAAc;AAAA,QACd,aAAa;AAAA,QACb,qBAAqB;AAAA,QACrB,OAAO;AAAA,QACP,QAAQ;AAAA,QACR,OAAO;AAAA,QACP,aAAa;AAAA,QACb,KAAK;AAAA,QACL,QAAQ;AAAA,QACR,iBAAiB;AAAA,QACjB,MAAM;AAAA,QACN,OAAO;AAAA,QACP,SAAS;AAAA,QACT,QAAQ;AAAA,QACR,QAAQ;AAAA,QACR,aAAa;AAAA,QACb,qBAAqB;AAAA,QACrB,OAAO;AAAA,QACP,mBAAmB;AAAA,QACnB,eAAe;AAAA,QACf,KAAK;AAAA,MACP;AAAA,MACA,gBAAgB;AAAA,QACd,kBACE;AAAA,QACF,wBAAwB;AAAA,QACxB,kBAAkB;AAAA,QAClB,2BAA2B;AAAA,QAC3B,gBAAgB;AAAA,QAChB,iBAAiB;AAAA,QACjB,mBAAmB;AAAA,QACnB,oBAAoB;AAAA,QACpB,sBAAsB;AAAA,QACtB,uBAAuB;AAAA,QACvB,oBAAoB;AAAA,QACpB,wBAAwB;AAAA,QACxB,sBAAsB;AAAA,QACtB,oBAAoB;AAAA,QACpB,gBAAgB;AAAA,QAChB,sBAAsB;AAAA,QACtB,mBAAmB;AAAA,QACnB,6BAA6B;AAAA,QAC7B,YAAY;AAAA,QACZ,kBAAkB;AAAA,QAClB,uBAAuB;AAAA,MACzB;AAAA,MACA,YAAY;AAAA,QACV,YAAY;AAAA,QACZ,YAAY;AAAA,QACZ,iBAAiB;AAAA,QACjB,kBAAkB;AAAA,QAClB,cAAc;AAAA,QACd,gBAAgB;AAAA,QAChB,aAAa;AAAA,QACb,cAAc;AAAA,QACd,gBAAgB;AAAA,QAChB,oBAAoB;AAAA,QACpB,mBAAmB;AAAA,QACnB,cAAc;AAAA,QACd,cAAc;AAAA,QACd,oBAAoB;AAAA,QACpB,oBAAoB;AAAA,MACtB;AAAA,IACF;AAAA,EACF;AAAA,EACA,QAAQ;AAAA,IACN,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,QAAQ;AAAA,MACN,WAAW;AAAA,QACT,SAAS;AAAA,QACT,MAAM;AAAA,QACN,aAAa;AAAA,QACb,oBAAoB;AAAA,QACpB,cAAc;AAAA,QACd,aAAa;AAAA,QACb,qBAAqB;AAAA,QACrB,OAAO;AAAA,QACP,QAAQ;AAAA,QACR,OAAO;AAAA,QACP,aAAa;AAAA,QACb,KAAK;AAAA,QACL,QAAQ;AAAA,QACR,iBAAiB;AAAA,QACjB,MAAM;AAAA,QACN,OAAO;AAAA,QACP,SAAS;AAAA,QACT,QAAQ;AAAA,QACR,QAAQ;AAAA,QACR,aAAa;AAAA,QACb,qBAAqB;AAAA,QACrB,OAAO;AAAA,QACP,mBAAmB;AAAA,QACnB,eAAe;AAAA,QACf,KAAK;AAAA,MACP;AAAA,MACA,gBAAgB;AAAA,QACd,kBACE;AAAA,QACF,wBAAwB;AAAA,QACxB,kBAAkB;AAAA,QAClB,2BAA2B;AAAA,QAC3B,gBAAgB;AAAA,QAChB,iBAAiB;AAAA,QACjB,mBAAmB;AAAA,QACnB,oBAAoB;AAAA,QACpB,sBAAsB;AAAA,QACtB,uBAAuB;AAAA,QACvB,oBAAoB;AAAA,QACpB,wBAAwB;AAAA,QACxB,sBAAsB;AAAA,QACtB,oBAAoB;AAAA,QACpB,gBAAgB;AAAA,QAChB,sBAAsB;AAAA,QACtB,mBAAmB;AAAA,QACnB,6BAA6B;AAAA,QAC7B,YAAY;AAAA,QACZ,kBAAkB;AAAA,QAClB,uBAAuB;AAAA,MACzB;AAAA,MACA,YAAY;AAAA,QACV,YAAY;AAAA,QACZ,YAAY;AAAA,QACZ,iBAAiB;AAAA,QACjB,kBAAkB;AAAA,QAClB,cAAc;AAAA,QACd,gBAAgB;AAAA,QAChB,aAAa;AAAA,QACb,cAAc;AAAA,QACd,gBAAgB;AAAA,QAChB,oBAAoB;AAAA,QACpB,mBAAmB;AAAA,QACnB,cAAc;AAAA,QACd,cAAc;AAAA,QACd,oBAAoB;AAAA,QACpB,oBAAoB;AAAA,MACtB;AAAA,IACF;AAAA,EACF;AACF;AAEA,MAAMC,OAAK;AACX,MAAM,wBAAwB;AAC9B,MAAM,wBAAwB;AAC9B,MAAM,MAA4C;AAAA,EAChD,QAAQ;AACV;AAEA,IAAI,kBAAkB;AAAA,EACpB,MAAMA;AAAAA,EACN,OAAO;AASL,iBAAa,UAAU,mBAAmB,SACxC,OACA,sBACA;AACK,WAAA,UAAU,IAAI;AACnB,WAAK,QAAQ,OAAO;AACpB,WAAK,QAAQ,MAAM;AACd,WAAA,QAAQ,SAAS,MAAM;AACrB,aAAA,KAAK,MAAM,IAAI;AAAA,MAAA;AAEtB,WAAK,mBAAmB;AAExB,WAAK,mBAAmB;AACxB,WAAK,yBAAyB;AAC9B,WAAK,WAAW;AAAA,IAAA;AAAA,EAEpB;AAAA,EACA,kBAAkB,WAAW;AACrB,UAAA,iBAAiB,CAAC,cAAc;AAC7B,aAAA,OAAO,KAAK,SAAS,EACzB,OACA,OAAO,CAAC,KAAK,QAAQ;AAChB,YAAA,GAAG,IAAI,UAAU,GAAG;AACjB,eAAA;AAAA,MACT,GAAG,CAAE,CAAA;AAAA,IAAA;AAGT,aAAS,eAAe;AACtB,UAAI,QAAQ,CAAA;AAEZ,YAAM,OAAO;AACb,iBAAW,UAAU,MAAM;AACnB,cAAA,WAAW,KAAK,MAAM;AAE5B,YAAI,SAAS,SAAS,OAAO,EAAE,UAAU;AACzC,YAAI,SAAS,OAAO,EAAE,UAAU,MAAM,QAAW;AAC/C,mBAAS,OAAO;AAAA,YACd,CAAC;AAAA,YACD,SAAS,OAAO,EAAE,UAAU;AAAA,YAC5B,SAAS,OAAO,EAAE,UAAU;AAAA,UAAA;AAAA,QAEhC;AAEA,mBAAW,aAAa,QAAQ;AACxB,gBAAA,YAAY,OAAO,SAAS;AAC5B,gBAAA,OAAO,UAAU,CAAC;AAExB,cAAI,CAAC,MAAM,QAAQ,IAAI,GAAG;AACxB,kBAAM,KAAK,IAAI;AAAA,UACjB;AAAA,QACF;AAEW,mBAAA,KAAK,SAAS,QAAQ,GAAG;AAClC,gBAAM,SAAS,SAAS,QAAQ,EAAE,CAAC;AACnC,gBAAM,KAAK,MAAM;AAAA,QACnB;AAAA,MACF;AAEO,aAAA;AAAA,IACT;AAEA,aAAS,qBAAqB,cAAc;AAC1C,UAAI,QAAQ;AAEZ,iBAAW,QAAQ,OAAO;AACxB,YAAI,CAAC,aAAa,OAAO,UAAU,IAAI,GAAG;AAC3B,uBAAA,OAAO,UAAU,IAAI,IAAI;AAAA,QACxC;AAAA,MACF;AAEA,mBAAa,OAAO,YAAY;AAAA,QAC9B,aAAa,OAAO;AAAA,MAAA;AAGf,aAAA;AAAA,IACT;AAEA,UAAM,0BAA0B,MAAY;AAC1C,UAAI,eAAe;AAAA,QACjB,IAAI;AAAA,QACJ,MAAM;AAAA,QACN,QAAQ;AAAA,UACN,WAAW,CAAC;AAAA,UACZ,gBAAgB,CAAC;AAAA,UACjB,YAAY,CAAC;AAAA,QACf;AAAA,MAAA;AAII,YAAA,sBAAsB,cAAc,qBAAqB;AACpD,iBAAA,OAAO,oBAAoB,OAAO,gBAAgB;AAC3D,YAAI,CAAC,aAAa,OAAO,eAAe,GAAG,GAAG;AAC/B,uBAAA,OAAO,eAAe,GAAG,IAAI;AAAA,QAC5C;AAAA,MACF;AACW,iBAAA,OAAO,oBAAoB,OAAO,YAAY;AACvD,YAAI,CAAC,aAAa,OAAO,WAAW,GAAG,GAAG;AAC3B,uBAAA,OAAO,WAAW,GAAG,IAAI;AAAA,QACxC;AAAA,MACF;AAEA,aAAO,qBAAqB,YAAY;AAAA,IAAA;AAG1C,UAAM,yBAAyB,MAAqB;AAClD,aAAO,IAAI,GAAG,SAAS,gBAAgB,uBAAuB,CAAA,CAAE;AAAA,IAAA;AAG5D,UAAA,yBAAyB,CAAC,wBAAuC;AAC9D,aAAA,IAAI,GAAG,SAAS;AAAA,QACrB;AAAA,QACA;AAAA,MAAA;AAAA,IACF;AAGI,UAAA,wBAAwB,CAAO,iBAAiB;AAChD,UAAA,OAAO,iBAAiB,UAAU;AACpC,cAAM,wBAAwB;AAC9B;AAAA,MACF;AAEI,UAAA,CAAC,aAAa,IAAI;AACpB,cAAM,2BAA2B;AACjC;AAAA,MACF;AAEI,UAAA,CAAC,aAAa,MAAM;AACtB,cAAM,6BAA6B;AACnC;AAAA,MACF;AAEI,UAAA,CAAC,aAAa,QAAQ;AACxB,cAAM,+BAA+B;AACrC;AAAA,MACF;AAEA,UACE,aAAa,OAAO,aACpB,OAAO,aAAa,OAAO,cAAc,UACzC;AACA,cAAM,yCAAyC;AAC/C;AAAA,MACF;AAEA,YAAM,sBAAsB;AACR,0BAAA,aAAa,EAAE,IAAI;AACvC,6BAAuB,mBAAmB;AAE/B,iBAAA,UAAU,IAAI,OAAO,YAAY;AAC1C,YACG,OAA6B,UAC9B,YAAY,aAAa,IACzB;AACI,cAAA,OAAO,YAAY,MAAM;AAAA,QAC/B;AAAA,MACF;AAEA,UAAI,OAAO;AAAA,QACT,IAAI,UAAU;AAAA,UACZ,aAAa,aAAa,OAAO;AAAA,UACjC,OAAO,YAAY,aAAa;AAAA,UAChC,UAAU;AAAA,QAAA,CACX;AAAA,MAAA;AAGa,sBAAA,YAAY,aAAa,EAAE;AAC3C,YAAM,iBAAiB,YAAY;AAAA,IAAA;AAG/B,UAAA,2BAA2B,CAAO,mBAAmB;AACzD,YAAM,sBAAsB;AAC5B,aAAO,oBAAoB,cAAc;AACzC,6BAAuB,mBAAmB;AAE/B,iBAAA,OAAO,IAAI,OAAO,YAAY;AACvC,cAAM,SAAS;AACX,YAAA,OAAO,UAAU,uBAAuB;AAC1C,iBAAO,WAAW;AAAA,QACpB;AAEI,YAAA,OAAO,UAAU,YAAY,gBAAgB;AAC3C,cAAA,OAAO,YAAY,MAAM;AAAA,QAC/B;AAAA,MACF;AAEA,sBAAgB,qBAAqB;AAC/B,YAAA,iBAAiB,iBAAiB;AAAA,IAAA;AAGpC,UAAA,mBAAmB,CAAO,iBAA0B;AACzC,qBAAA,MAAM,qBAAqB,YAAY;AACtD,UAAI,aAAa,QAAQ;AAEnB,YAAA,aAAa,OAAO,WAAW;AAC1B,iBAAA;AAAA;AAAA,YAEL,IAAI,OAAO;AAAA,YACX,aAAa,OAAO;AAAA,UAAA;AAEf,iBAAA;AAAA,YACL,aAAa;AAAA,YACb,aAAa,OAAO;AAAA,UAAA;AAAA,QAExB;AAEI,YAAA,aAAa,OAAO,gBAAgB;AAEtC,cAAI,OAAO,mBACT,aAAa,OAAO,eAAe;AACrC,cAAI,OAAO,qBACT,aAAa,OAAO,eAAe;AAE1B,qBAAA,OAAO,aAAa,OAAO,gBAAgB;AAElD,gBAAA,aAAa,OAAO,eAAe,eAAe,GAAG,KACrD,UAAU,eAAe,GAAG,GAC5B;AACA,wBAAU,GAAG,IAAI,aAAa,OAAO,eAAe,GAAG;AAAA,YACzD;AAAA,UACF;AAAA,QACF;AAEI,YAAA,aAAa,OAAO,YAAY;AAC5B,gBAAA,YAAY,SAAS,gBAAgB;AAChC,qBAAA,OAAO,aAAa,OAAO,YAAY;AACtC,sBAAA;AAAA,cACR,OAAO;AAAA,cACP,aAAa,OAAO,WAAW,GAAG;AAAA,YAAA;AAAA,UAEtC;AAAA,QACF;AACI,YAAA,OAAO,KAAK,MAAM,IAAI;AAAA,MAC5B;AAAA,IAAA;AAGI,UAAA,kBAAkB,CAAC,mBAAoB;AAC3C,UAAI,CAAC,gBAAgB;AACF,yBAAA,IAAI,GAAG,SAAS;AAAA,UAC/BA;AAAAA,UACA;AAAA,QAAA;AAAA,MAEJ;AAEI,UAAA,eAAe,WAAW,SAAS,GAAG;AACvB,yBAAA,eAAe,OAAO,CAAC;AACxC,YAAI,sBAAsB;AACtB,YAAA,oBAAoB,cAAc,GAAG;AACvC,iBAAO,oBAAoB,cAAc;AAAA,QAC3C;AAAA,MACF;AAEA,aAAO,cAAc,cAAc;AAAA,IAAA;AAG/B,UAAA,kBAAkB,CAAC,mBAAmB;AAC1C,UAAI,GAAG,SAAS,gBAAgBA,MAAI,cAAc;AAAA,IAAA;AAG9C,UAAA,YAAY,IAAI,SAAS;AAAA,MAC7B,MAAM;AAAA,MACN,QAAQ;AAAA,MACR,OAAO,EAAE,SAAS,OAAO;AAAA,MACzB,QAAQ,SAAS;AAAA,MACjB,UAAU,MAAM;AACR,cAAAC,QAAO,UAAU,MAAM,CAAC;AAC9B,YAAIA,MAAK,SAAS,sBAAsBA,MAAK,KAAK,SAAS,OAAO,GAAG;AAC7D,gBAAA,SAAS,IAAI;AACnB,iBAAO,SAAS,MAAY;AAC1B,kBAAM,sBAAsB,KAAK,MAAM,OAAO,MAAgB,CAAC;AAAA,UAAA;AAEjE,iBAAO,WAAWA,KAAI;AAAA,QACxB;AAAA,MACF;AAAA,IAAA,CACD;AAEG,QAAA,GAAG,SAAS,WAAW;AAAA,MAAA,IACzBD;AAAAA,MACA,MAAM;AAAA,MACN,MAAM,CAAC,MAAM,QAAQ,UAAU;AAC7B,cAAM,UAAU;AAAA,UACd,GAAG,OAAO,OAAO,aAAa,EAAE;AAAA,YAAI,CAAC,MACnC,IAAI,UAAU;AAAA,cACZ,aAAa,EAAE;AAAA,cACf,OAAO,EAAE;AAAA,cACT,UAAU,EAAE,OAAO;AAAA,YAAA,CACpB;AAAA,UACH;AAAA,UACA,GAAG,OAAO,OAAO,uBAAA,CAAwB,EAAE;AAAA,YAAI,CAAC,MAC9C,IAAI,UAAU;AAAA,cACZ,aAAa,GAAG,EAAE,IAAI;AAAA,cACtB,OAAO,UAAU,EAAE,EAAE;AAAA,cACrB,UAAU,UAAU,EAAE,EAAE,OAAO;AAAA,YAAA,CAChC;AAAA,UACH;AAAA,QAAA;AAGF,YAAI,SAAS;AAAA,UACX;AAAA,UACA;AAAA,YACE,OAAO;AAAA,cACL,cAAc;AAAA,cACd,OAAO;AAAA,YACT;AAAA,YACA,UAAU,CAAC,MAAM;AACR,qBAAA,EAAE,OAAO,KAAK;AAAA,YACvB;AAAA,UACF;AAAA,UACA;AAAA,QAAA;AAGF,eAAO,IAAI,MAAM;AAAA,UACf,IAAI,MAAM;AAAA,YACR,IAAI,SAAS;AAAA,cACX,KAAKA,KAAG,WAAW,KAAK,GAAG;AAAA,cAC3B,aAAa;AAAA,YAAA,CACd;AAAA,UAAA,CACF;AAAA,UACD,IAAI,MAAM;AAAA,YACR,IAAI;AAAA,YACJ;AAAA,cACE;AAAA,cACA;AAAA,gBACE,OAAO;AAAA,kBACL,SAAS;AAAA,kBACT,KAAK;AAAA,kBACL,cAAc;AAAA,gBAChB;AAAA,cACF;AAAA,cACA;AAAA,gBACE,IAAI,SAAS;AAAA,kBACX,MAAM;AAAA,kBACN,OAAO;AAAA,kBACP,SAAS,MAAY;AACb,0BAAA,iBAAiB,IAAI,GAAG,SAAS;AAAA,sBACrCA;AAAAA,sBACA;AAAA,oBAAA;AAEF,0BAAM,eAAe,MAAM;AAAA,sBACzB,gBAAgB,cAAc;AAAA,oBAAA;AAEhC,0BAAM,OAAO,KAAK,UAAU,cAAc,MAAM,CAAC;AAC3C,0BAAA,OAAO,IAAI,KAAK,CAAC,IAAI,GAAG,EAAE,MAAM,mBAAA,CAAoB;AACpD,0BAAA,MAAM,IAAI,gBAAgB,IAAI;AAC9B,0BAAA,IAAI,IAAI,KAAK;AAAA,sBACjB,MAAM;AAAA,sBACN,UAAU,iBAAiB;AAAA,sBAC3B,OAAO,EAAE,SAAS,OAAO;AAAA,sBACzB,QAAQ,SAAS;AAAA,oBAAA,CAClB;AACD,sBAAE,MAAM;AACR,+BAAW,WAAY;AACrB,wBAAE,OAAO;AACF,6BAAA,IAAI,gBAAgB,GAAG;AAAA,uBAC7B,CAAC;AAAA,kBACN;AAAA,gBAAA,CACD;AAAA,gBACD,IAAI,SAAS;AAAA,kBACX,MAAM;AAAA,kBACN,OAAO;AAAA,kBACP,SAAS,MAAM;AACb,8BAAU,MAAM;AAAA,kBAClB;AAAA,gBAAA,CACD;AAAA,gBACD,IAAI,SAAS;AAAA,kBACX,MAAM;AAAA,kBACN,OAAO;AAAA,kBACP,SAAS,MAAY;AACb,0BAAA,eAAe,MAAM;AAC3B,0BAAM,OAAO,KAAK,UAAU,cAAc,MAAM,CAAC;AAC3C,0BAAA,OAAO,IAAI,KAAK,CAAC,IAAI,GAAG,EAAE,MAAM,mBAAA,CAAoB;AACpD,0BAAA,MAAM,IAAI,gBAAgB,IAAI;AAC9B,0BAAA,IAAI,IAAI,KAAK;AAAA,sBACjB,MAAM;AAAA,sBACN,UAAU;AAAA,sBACV,OAAO,EAAE,SAAS,OAAO;AAAA,sBACzB,QAAQ,SAAS;AAAA,oBAAA,CAClB;AACD,sBAAE,MAAM;AACR,+BAAW,WAAY;AACrB,wBAAE,OAAO;AACF,6BAAA,IAAI,gBAAgB,GAAG;AAAA,uBAC7B,CAAC;AAAA,kBACN;AAAA,gBAAA,CACD;AAAA,gBACD,IAAI,SAAS;AAAA,kBACX,MAAM;AAAA,kBACN,OAAO;AAAA,kBACP,SAAS,MAAY;AACf,wBAAA,iBAAiB,IAAI,GAAG,SAAS;AAAA,sBACnCA;AAAAA,sBACA;AAAA,oBAAA;AAGE,wBAAA,cAAc,cAAc,GAAG;AACjC,4BAAM,6CAA6C;AACnD;AAAA,oBACF;AAEI,wBAAA,eAAe,WAAW,SAAS,GAAG;AACvB,uCAAA,eAAe,OAAO,CAAC;AAAA,oBAC1C;AAEA,0BAAM,yBAAyB,cAAc;AAAA,kBAC/C;AAAA,gBAAA,CACD;AAAA,cACH;AAAA,YACF;AAAA,UAAA,CACD;AAAA,QAAA,CACF;AAAA,MACH;AAAA,MACA,cAAc;AAAA,MACR,SAAS,OAAO;AAAA;AACpB,cAAI,CAAC,OAAO;AACV;AAAA,UACF;AAEI,cAAA,UAAU,cAAc,KAAK;AACjC,cAAI,SAAS;AACX,kBAAM,iBAAiB,OAAO;AAAA,UACrB,WAAA,MAAM,WAAW,SAAS,GAAG;AAC9B,oBAAA,MAAM,OAAO,CAAC;AACtB,gBAAI,sBAAsB;AACtB,gBAAA,oBAAoB,KAAK,GAAG;AAC9B,wBAAU,oBAAoB,KAAK;AAC7B,oBAAA,iBAAiB,oBAAoB,KAAK,CAAC;AAAA,YACnD;AAAA,UACF;AAEA,cAAI,EAAE,kBAAkB,uBAAuB,IAC7C,QAAQ,OAAO;AAEf,cAAA,qBAAqB,UACrB,2BAA2B,QAC3B;AACA,kBAAM,OAAO,cAAc,MAAM,EAAE,OAAO;AAC1C,+BAAmB,KAAK;AACxB,qCAAyB,KAAK;AAAA,UAChC;AAGI,cAAA,OAAO,iBAAiB,kBAAkB,sBAAsB;AAAA,QACtE;AAAA;AAAA,IAAA,CACD;AAAA,EACH;AACF,CAAC;AC/2BD,MAAME,QAAM;AAAA,EACV,MAAM;AAAA,EACN,OAAO;AACL,UAAM,UAAU,UAAU;AAGhB,cAAA,cAAc,SAAU,QAAQ,SAAS;AACjD,YAAM,MAAM,QAAQ,KAAK,MAAM,QAAQ,OAAO;AAG9C,WAAI,mCAAS,eAAc,WAAU,iCAAQ,UAAS,IAAI;AAClD,cAAA,SAAS,SAAS,cAAc,OAAO;AACtC,eAAA,UAAU,IAAI,2BAA2B;AAChD,eAAO,cAAc;AAChB,aAAA,KAAK,QAAQ,MAAM;AAExB,cAAM,QAAQ,MAAM;AAAA,UAClB,KAAK,KAAK,iBAAiB,iBAAiB;AAAA,QAAA;AAE1C,YAAA,iBAAiB,CAAC,GAAG,KAAK;AAC9B,YAAI,YAAY,eAAe;AAG/B,8BAAsB,MAAM;;AAEpB,gBAAA,cAAc,aAAa,cAAc;AACzC,gBAAA,qBAAoB,uBAAY,YAAZ,mBACtB;AAAA,YACA,CAAC,MACC,EAAE,SAAS,WAAW,EAAE,QAAQ,OAAO,WAAW,OAAO;AAAA,YAE5D;AAAA,YAAK,CAAC,MACL,EAAE,QAAQ,OAAO,MAAM,CAAC,GAAG,MAAM,MAAM,OAAO,CAAC,CAAC;AAAA,gBAN1B,mBAOrB;AAED,cAAA,gBAAgB,oBAChB,OAAO,UAAU,CAAC,MAAM,MAAM,iBAAiB,IAC/C;AACJ,cAAI,gBAAgB,GAAG;AACL,4BAAA;AAAA,UAClB;AACI,cAAA,eAAe,eAAe,aAAa;AAChC;AAGf,mBAAS,iBAAiB;AACV,yDAAA,MAAM,YAAY,oBAAoB;AACtC,yDAAA,MAAM,YAAY,SAAS;AACzC,2BAAe,eAAe,aAAa;AAC3C,yDAAc,MAAM;AAAA,cAClB;AAAA,cACA;AAAA,cACA;AAAA;AAEF,yDAAc,MAAM,YAAY,SAAS,QAAQ;AAAA,UACnD;AAEA,gBAAM,eAAe,MAAM;AACnB,kBAAA,OAAO,KAAK,KAAK,sBAAsB;AAGzC,gBAAA,KAAK,MAAM,GAAG;AACV,oBAAA,QACJ,IACA,KAAK,KAAK,sBAAwB,EAAA,SAChC,KAAK,KAAK;AACd,oBAAM,QAAS,KAAK,KAAK,eAAe,QAAS;AACjD,mBAAK,KAAK,MAAM,MAAM,CAAC,QAAQ;AAAA,YACjC;AAAA,UAAA;AAIK,iBAAA,iBAAiB,WAAW,CAAC,UAAU;AAC5C,oBAAQ,MAAM,KAAK;AAAA,cACjB,KAAK;AACH,sBAAM,eAAe;AACrB,oBAAI,kBAAkB,GAAG;AACvB,kCAAgB,YAAY;AAAA,gBAAA,OACvB;AACL;AAAA,gBACF;AACe;AACf;AAAA,cACF,KAAK;AACH,sBAAM,eAAe;AACrB,gCAAgB,YAAY;AACb;AACf;AAAA,cACF,KAAK;AACH,sBAAM,eAAe;AACjB,oBAAA,kBAAkB,YAAY,GAAG;AACnB,kCAAA;AAAA,gBAAA,OACX;AACL;AAAA,gBACF;AACe;AACf;AAAA,cACF,KAAK;AACH,sBAAM,eAAe;AACL,gCAAA;AACD;AACf;AAAA,cACF,KAAK;AACH,6DAAc;AACd;AAAA,cACF,KAAK;AACH,qBAAK,MAAM;AACX;AAAA,YACJ;AAAA,UAAA,CACD;AAEM,iBAAA,iBAAiB,SAAS,MAAM;AAE/B,kBAAA,OAAO,OAAO,MAAM,kBAAkB;AAE3B,6BAAA,MAAM,OAAO,CAAC,SAAS;AAChC,oBAAA,YACJ,CAAC,QAAQ,KAAK,YAAY,kBAAkB,EAAE,SAAS,IAAI;AACxD,mBAAA,MAAM,UAAU,YAAY,UAAU;AACpC,qBAAA;AAAA,YAAA,CACR;AAEe,4BAAA;AACZ,gBAAA,eAAe,SAAS,YAAY,GAAG;AACzC,8BAAgB,eAAe;AAAA,gBAC7B,CAAC,MAAM,MAAM;AAAA,cAAA;AAAA,YAEjB;AACA,wBAAY,eAAe;AAEZ;AAGf,gBAAI,QAAQ,OAAO;AACb,kBAAA,MAAM,QAAQ,MAAM,UAAU;AAE5B,oBAAA,WAAW,SAAS,KAAK,sBAAsB;AAC/C,oBAAA,WAAW,KAAK,KAAK,sBAAsB;AACjD,kBACE,SAAS,UACT,MAAM,SAAS,SAAS,SAAS,SAAS,IAC1C;AACA,sBAAM,KAAK,IAAI,GAAG,SAAS,SAAS,SAAS,SAAS,EAAE;AAAA,cAC1D;AAEK,mBAAA,KAAK,MAAM,MAAM,MAAM;AACf;YACf;AAAA,UAAA,CACD;AAED,gCAAsB,MAAM;AAE1B,mBAAO,MAAM;AAEA;UAAA,CACd;AAAA,QAAA,CACF;AAAA,MACH;AAEO,aAAA;AAAA,IAAA;AAGC,cAAA,YAAY,YAAY,QAAQ;AAAA,EAC5C;AACF;AAEA,IAAI,kBAAkBA,KAAG;ACnKzB,SAAS,cAAc,KAAK;AACnB,SAAA,IAAI,QAAQ,4BAA4B,EAAE;AACnD;AAEA,IAAI,kBAAkB;AAAA,EACpB,MAAM;AAAA,EACN,YAAY,MAAM;AAChB,QAAI,KAAK,SAAS;AAGhB,YAAM,UAAU,KAAK,QAAQ,OAAO,CAAC,MAAM,EAAE,cAAc;AAC3D,iBAAW,UAAU,SAAS;AAErB,eAAA,iBAAiB,CAAC,cAAc,gBAAgB;AACjD,cAAAC,UAAS,cAAc,OAAO,KAAK;AACvC,iBACEA,QAAO,QAAQ,OAAO,EAAE,EAAE,SAAS,GAAG,KACtCA,QAAO,QAAQ,OAAO,EAAE,EAAE,SAAS,GAAG,GACtC;AACA,kBAAM,aAAaA,QAAO,QAAQ,OAAO,IAAI,EAAE,QAAQ,GAAG;AAC1D,kBAAM,WAAWA,QAAO,QAAQ,OAAO,IAAI,EAAE,QAAQ,GAAG;AAExD,kBAAM,gBAAgBA,QAAO,UAAU,aAAa,GAAG,QAAQ;AACzD,kBAAA,UAAU,cAAc,MAAM,GAAG;AAEvC,kBAAM,cAAc,KAAK,MAAM,KAAK,WAAW,QAAQ,MAAM;AACvD,kBAAA,eAAe,QAAQ,WAAW;AAGtC,YAAAA,UAAAA,QAAO,UAAU,GAAG,UAAU,IAC9B,eACAA,QAAO,UAAU,WAAW,CAAC;AAAA,UACjC;AAGA,cAAI,6CAAc;AACH,yBAAA,eAAe,WAAW,IAAIA;AAEtC,iBAAAA;AAAA,QAAA;AAAA,MAEX;AAAA,IACF;AAAA,EACF;AACF,CAAC;AC/CD,IAAI,kBAAkB;AAAA,EACpB,MAAM;AAAA,EACN,OAAO;AACL,UAAM,qBAAqB,IAAI,GAAG,SAAS,WAAW;AAAA,MACpD,IAAI;AAAA,MACJ,MAAM;AAAA,MACN,MAAM;AAAA,MACN,OAAO;AAAA,QACL,KAAK;AAAA,QACL,KAAK;AAAA,QACL,MAAM;AAAA,MACR;AAAA,MACA,cAAc;AAAA,IAAA,CACf;AAEQ,aAAA,gBAAgB,QAAQ,OAAO;AAChC,YAAA,cAAc,WAAW,MAAM;AACjC,UAAA,MAAM,WAAW,EAAU,QAAA;AAC/B,YAAM,YAAY,cAAc;AAC5B,UAAA,YAAY,EAAU,QAAA;AAC1B,aAAO,OAAO,OAAO,UAAU,QAAQ,EAAE,CAAC,CAAC;AAAA,IAC7C;AAES,aAAA,qBAAqB,MAAM,WAAW;AACzC,UAAA,QAAQ,WACV,MAAM;AACJ,UAAA,YAAY,GACd,aAAa;AAGf,aAAO,SAAS,GAAG;AACjB;AACA,YAAI,KAAK,KAAK,MAAM,OAAO,cAAc,WAAY;AACjD,YAAA,KAAK,KAAK,MAAM,IAAK;AACrB,YAAA,KAAK,KAAK,MAAM,IAAK;AAAA,MAC3B;AACI,UAAA,QAAQ,EAAU,QAAA;AAEV,kBAAA;AACC,mBAAA;AAGN,aAAA,MAAM,KAAK,QAAQ;AACxB,YAAI,KAAK,GAAG,MAAM,OAAO,cAAc,WAAY;AAC/C,YAAA,KAAK,GAAG,MAAM,IAAK;AACnB,YAAA,KAAK,GAAG,MAAM,IAAK;AACvB;AAAA,MACF;AACI,UAAA,QAAQ,KAAK,OAAe,QAAA;AAEhC,aAAO,EAAE,OAAO,QAAQ,GAAG,IAAS;AAAA,IACtC;AAEA,aAAS,uBAAuB,MAAM;AACpC,YAAM,aAAa;AACb,YAAA,aAAa,KAAK,MAAM,UAAU;AAExC,YAAM,aAAa;AACb,YAAA,aAAa,KAAK,MAAM,UAAU;AAEpC,UAAA,cAAc,CAAC,YAAY;AACtB,eAAA,IAAI,WAAW,CAAC,CAAC;AAAA,MAAA,OACnB;AACE,eAAA;AAAA,MACT;AAAA,IACF;AAEA,aAAS,cAAc,OAAO;AAC5B,YAAM,aAAa,MAAM,aAAa,EAAE,CAAC;AACnC,YAAA,QAAQ,WAAW,mBAAmB,KAAK;AAE7C,UAAA,WAAW,YAAY,WAAY;AACvC,UAAI,EAAE,MAAM,QAAQ,aAAa,MAAM,QAAQ,aAAc;AAC7D,UAAI,CAAC,MAAM,WAAW,CAAC,MAAM,QAAS;AAEtC,YAAM,eAAe;AAErB,UAAI,QAAQ,WAAW;AACvB,UAAI,MAAM,WAAW;AACrB,UAAI,eAAe,WAAW,MAAM,UAAU,OAAO,GAAG;AAGxD,UAAI,CAAC,cAAc;AACjB,cAAM,mBAAmB,qBAAqB,WAAW,OAAO,KAAK;AACrE,YAAI,kBAAkB;AACpB,kBAAQ,iBAAiB;AACzB,gBAAM,iBAAiB;AACvB,yBAAe,WAAW,MAAM,UAAU,OAAO,GAAG;AAAA,QAAA,OAC/C;AAEL,gBAAM,aAAa;AAGjB,iBAAA,CAAC,WAAW,SAAS,WAAW,MAAM,QAAQ,CAAC,CAAC,KAChD,QAAQ,GACR;AACA;AAAA,UACF;AAGE,iBAAA,CAAC,WAAW,SAAS,WAAW,MAAM,GAAG,CAAC,KAC1C,MAAM,WAAW,MAAM,QACvB;AACA;AAAA,UACF;AAEA,yBAAe,WAAW,MAAM,UAAU,OAAO,GAAG;AACpD,cAAI,CAAC,aAAc;AAAA,QACrB;AAAA,MACF;AAGA,UAAI,aAAa,aAAa,SAAS,CAAC,MAAM,KAAK;AACjD,uBAAe,aAAa,UAAU,GAAG,aAAa,SAAS,CAAC;AACzD,eAAA;AAAA,MACT;AAIE,UAAA,WAAW,MAAM,QAAQ,CAAC,MAAM,OAChC,WAAW,MAAM,GAAG,MAAM,KAC1B;AACS,iBAAA;AACF,eAAA;AACP,uBAAe,WAAW,MAAM,UAAU,OAAO,GAAG;AAAA,MACtD;AAIE,UAAA,aAAa,CAAC,MAAM,OACpB,aAAa,aAAa,SAAS,CAAC,MAAM,KAC1C;AACA,uBAAe,IAAI,YAAY;AAAA,MACjC;AAGA,qBAAe,uBAAuB,YAAY;AAGlD,YAAM,cAAc,MAAM,QAAQ,YAAY,QAAQ,CAAC;AACvD,YAAM,cAAc,aAAa;AAAA,QAC/B;AAAA,QACA,CAAC,OAAO,MAAM,WAAW;AACd,mBAAA,gBAAgB,QAAQ,WAAW;AAC5C,cAAI,UAAU,GAAG;AACR,mBAAA;AAAA,UAAA,OACF;AACE,mBAAA,IAAI,IAAI,IAAI,MAAM;AAAA,UAC3B;AAAA,QACF;AAAA,MAAA;AAGF,iBAAW,aAAa,aAAa,OAAO,KAAK,QAAQ;AAAA,IAC3D;AACO,WAAA,iBAAiB,WAAW,aAAa;AAAA,EAClD;AACF,CAAC;AC1JD,MAAM,iBAAiB;AACvB,MAAM,cAAc,CAAC,UAAU,SAAS,UAAU,UAAU,SAAS;AACrE,MAAM,SAAS,OAAO;AACtB,MAAM,aAAa,OAAO;AAC1B,MAAM,SAAS,OAAO;AAItB,MAAM,sBAAsB;AAC5B,MAAM,cAAc;AAAA,EAIlB,cAAc;AAJhB;AACE;AACA;AAGO,SAAA,UAAU,2BAA2B,GAAG;AAC7C,SAAK,oBAAoB;AACzB,SAAK,gBAAgB;AAErB,QAAI,CAAC,KAAK,cAAc,EAAE,uBAAuB,KAAK,aAAa;AAC5D,WAAA,YAAY,qBAAqB,OAAO,SAAS;AAAA,IACxD;AAAA,EACF;AAAA,EAEA,aAAa,aAAa,IAAI;;AAC5B,QAAI,GAAC,UAAK,QAAQ,CAAC,EAAE,UAAhB,mBAAuB,QAAQ;AAEpC,aAAS,UAAU,MAAM;AACvB,UAAIC,SAAQ,CAAA;AACZ,iBAAW,KAAK,KAAK,QAAQ,CAAC,EAAE,OAAO;AACrC,cAAM,WAAW,IAAI,MAAM,MAAM,CAAC;AAClC,cAAM,IAAI,KAAK,MAAM,YAAY,SAAS,SAAS;AAC/C,YAAA,EAAE,QAAQ,WAAW;AACvBA,mBAAQA,OAAM,OAAO,UAAU,CAAC,CAAC;AAAA,QAAA,OAC5B;AACLA,iBAAM,KAAK,CAAC;AAAA,QACd;AAAA,MACF;AACOA,aAAAA;AAAAA,IACT;AAEA,QAAI,QAAQ;AAAA,MACV,GAAG,UAAU,IAAI,EAAE,IAAI,CAAC,MAAM,IAAI,MAAM,MAAM,CAAC,CAAC;AAAA,MAChD,GAAG;AAAA,IAAA;AAEL,QAAI,KAAI,UAAK,YAAL,mBAAe,GAAG;AAC1B,QAAI,KAAK,KAAK,WAAW,mBAAmB,GAAG;AACzC,UAAA,sBAAsB,KAAK,CAAC;AAAA,IAClC;AAGA,eAAW,YAAY,OAAO;AAC5B,YAAM,OAAO,KAAK,MAAM,YAAY,SAAS,SAAS;AACtD,YAAM,QAAQ,KAAK,OAAO,SAAS,WAAW;AAC1C,UAAA;AACA,UAAA,MAAM,OAAO,MAAM,GAAG;AACf,iBAAA,MAAM,OAAO,MAAM;AAAA,MAAA,OACvB;AACC,cAAA,aAAc,MAAM,OAA4B;AACtD,YAAI,YAAY;AACd,mBAAS,KAAK,QAAQ,KAAK,CAAC,MAAM,EAAE,SAAS,UAAU;AAAA,QACzD;AAAA,MACF;AAEA,UAAI,QAAQ;AACV,eAAO,QAAQ;AACf,YAAI,OAAO,UAAU;AACZ,iBAAA;AAAA,YACL,OAAO;AAAA,YACP,IAAI;AAAA,YACJ;AAAA,YACA,IAAI,OAAO;AAAA,YACX,CAAC;AAAA,UAAA;AAAA,QAEL;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAAA,EAEA,qBAAqB;;AACb,UAAA,UAAS,UAAK,YAAL,mBAAe;AAC1B,SAAA,iCAAQ,UAAS,SAAS;AACrB,aAAA,QAAQ,SAAS,KAAK,QAAQ,CAAC,EAAE,OAAO,UAAU,EAAE,EAAE,CAAC;AAE9D,UAAI,CAAC,OAAO,QAAQ,OAAO,SAAS,OAAO,KAAK,GAAG;AACjD,eAAO,QAAQ,OAAO,QAAQ,OAAO,CAAC;AACpC,eAAO,SAAsB,OAAO,KAAK;AAAA,MAC7C;AAAA,IACF;AAAA,EACF;AAAA,EAEA,yBAAyB;;AACnB,UAAA,UAAK,QAAQ,CAAC,EAAE,UAAhB,mBAAuB,WAAU,GAAC,UAAK,YAAL,mBAAc,SAAQ;AAGtD,UAAA,CAAC,sBAAK,gDAAL,WAA2B;AAGhC,UAAI,KAAK,SAAS;AAChB,iBAAS,IAAI,GAAG,IAAI,KAAK,eAAe,QAAQ,KAAK;AAC7C,gBAAA,IAAI,KAAK,QAAQ,CAAC;AACxB,cAAI,GAAG;AACH,cAAA,QAAQ,KAAK,eAAe,CAAC;AAAA,UACjC;AAAA,QACF;AAAA,MACF;AAGA,4BAAK,gDAAL;AAAA,IACF;AAAA,EACF;AAAA,EAEA,oBAAoB,GAAG,OAAO,WAAW;;AACvC,QAAI,IAAI,kBAAkB;AAExB;AAAA,IACF;AAEA,UAAM,QAAQ,KAAK,QAAQ,CAAC,EAAE;AAC9B,QAAI,WAAW;AACb,WAAI,+BAAO,WAAU,GAAC,UAAK,YAAL,mBAAc,SAAQ;AAC1C,8BAAK,gDAAL;AAAA,MACF;AAAA,IAAA,OACK;AAEL,4BAAK,gDAAL;AAEI,UAAA,EAAC,+BAAO,SAAQ;AAClB,aAAK,iBAAiB;AAAA,MACxB;AAAA,IACF;AAAA,EACF;AAAA,EAEA,gBAAgB,MAAM,MAAM,OAAO,aAAa,aAAa;;AAGvD,QAAA,CAAC,MAAM,QAAQ;AACjB,UAAI,EAAE,MAAM,QAAQ,cAAsB,QAAA;AAAA,IAC5C;AAEA,SAAI,UAAK,QAAQ,IAAI,EAAE,UAAnB,mBAA0B,QAAQ;AAC9B,YAAA,QAAQ,sBAAK,gDAAL,WAAwB;AACtC,UAAI,OAAO;AAEJ,aAAA,aAAa,CAAC,EAAE,WAAW,YAAY,IAAI,YAAa,CAAA,CAAC;AAAA,MAChE;AACO,aAAA;AAAA,IACT;AAAA,EACF;AAAA,EA+HA,iBAAiB;;AACf,UAAM,UAAS,UAAK,YAAL,mBAAc,IAAI,CAAC,MAAM,EAAE;AAC1C,0BAAK,4CAAL;AACA,0BAAK,gDAAL,WAAwB;AACxB,QAAI,iCAAQ,QAAQ;AAClB,eAAS,IAAI,GAAG,MAAI,UAAK,YAAL,mBAAc,SAAQ;AACxC,aAAK,QAAQ,CAAC,EAAE,QAAQ,OAAO,CAAC;AAAA,IACpC;AACO,YAAA,UAAK,YAAL,mBAAe;AAAA,EACxB;AAAA,EA0EA,mBAAmB;AAGZ,SAAA,QAAQ,CAAC,EAAE,OAAO;AAClB,SAAA,QAAQ,CAAC,EAAE,OAAO;AAChB,WAAA,KAAK,QAAQ,CAAC,EAAE;AAEvB,0BAAK,4CAAL;AAAA,EACF;AACF;AArWA;AA4IE,gCAAmB,YAAsB;;AAEvC,MAAI,CAAC,KAAK,QAAQ,CAAC,EAAE,OAAO;AAC1B,SAAK,iBAAiB;AACtB;AAAA,EACF;AACA,QAAM,SAAS,KAAK,QAAQ,CAAC,EAAE,MAAM,CAAC;AACtC,QAAM,OAAO,KAAK,MAAM,MAAM,MAAM;AACpC,MAAI,CAAC,KAAM;AAEX,QAAM,YAAY,KAAK,MAAM,YAAY,KAAK,SAAS;AACvD,MAAI,CAAC,aAAa,CAAC,UAAU,OAAQ;AAErC,QAAM,QAAQ,UAAU,OAAO,KAAK,WAAW;AAC/C,MAAI,CAAC,MAAO;AAER,MAAA;AACA,MAAA,CAAC,MAAM,QAAQ;AACb,QAAA,EAAE,MAAM,QAAQ,cAAe;AACnC,aAAS,EAAE,MAAM,MAAM,MAAM,CAAC,UAAU,GAAG,MAAM,CAAC,MAAM,MAAM,CAAA,CAAE,EAAE;AAAA,EAAA,OAC7D;AACL,aAAS,MAAM;AAAA,EACjB;AAEM,QAAA,UAAS,YAAO,gBAAP;AACf,MAAI,CAAC,OAAQ;AAEb,QAAM,EAAE,KAAA,IAAS,cAAc,MAAM;AAEhC,OAAA,QAAQ,CAAC,EAAE,OAAO;AAClB,OAAA,QAAQ,CAAC,EAAE,OAAO;AAClB,OAAA,QAAQ,CAAC,EAAE,SAAS;AAEpB,wBAAA,2CAAA,YACH,YAAO,MAAM,MAAb,YAAkB,QAClB,WACA,OAAO,MACP,YACA,OAAO,MAAM;AAEjB;AAEA,kBAAc,SAAA,WAAW,MAAM,YAAY,YAAY,cAAc;;AAC/D,MAAA,OAAO,UAAU,CAAC;AAEtB,MAAI,gBAAgB,OAAO;AAClB,WAAA;AAAA,EACT;AAEI,MAAA;AACJ,MAAI,QAAQ,cAAc;AACd,cAAA,aAAa,IAAI,EAAE,MAAM,SAAS,WAAW,GAAG,KAAK,CAAI,GAAA;AAAA,EAAA,OAC9D;AACL,aAAS,KAAK,UAAU,MAAM,SAAS,MAAM,MAAM;AAAA,IAAC,GAAG,CAAE,CAAA;AAAA,EAC3D;AAEA,MAAI,cAAc;AAChB,WAAO,QAAQ,aAAa;AAAA,EAAA,YACnB,6BAAM,YAAW,QAAQ;AAC5B,UAAA,cAAc,KAAK,QAAQ,KAAK,CAAC,MAAM,EAAE,SAAS,UAAU;AAClE,QAAI,aAAa;AACf,aAAO,QAAQ,YAAY;AAAA,IAC7B;AAAA,EACF;AAGE,MAAA,GAAC,4CAAY,OAAZ,mBAAgB,4BAChB,OAAO,SAAS,YAAY,OAAO,SAAS,UAC7C;AACI,QAAA,iBAAgB,UAAK,mBAAL,mBAAsB;AAC1C,QAAI,CAAC,eAAe;AACF,sBAAA;AAAA,IAClB;AACA;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IAAA;AAEE,QAAA,UAAS,UAAK,mBAAL,mBAAsB;AACnC,QAAI,UAAU,KAAK,QAAQ,WAAW,GAAG;AAClC,WAAA,QAAQ,CAAC,EAAE,QAAQ;AAAA,IAC1B;AAAA,EACF;AAGA,QAAM,gBAAgB,KAAK;AAC3B,MACE,KAAK,aAAa,KAAK,QAAQ,CAAC,EAAE,SAClC,+CAAe,YAAW,KAAK,QAAQ,SAAS,GAChD;AACA,aAAS,IAAI,GAAG,IAAI,cAAc,QAAQ,KAAK;AAC7C,WAAK,QAAQ,IAAI,CAAC,EAAE,QAAQ,cAAc,CAAC;AAAA,IAC7C;AAAA,EACF;AAIA,QAAM,WAAW,OAAO;AACxB,QAAM,OAAO;AACb,SAAO,WAAW,WAAY;AAC5B,UAAM,IAAI,WAAW,SAAS,MAAM,MAAM,SAAS,IAAI;AACvD,SAAK,aAAa;AACX,WAAA;AAAA,EAAA;AAGT,MAAI,CAAC,YAAY;AAET,UAAA,KAAK,KAAK;AAChB,QAAI,KAAK,KAAK,CAAC,IAAI,GAAG,CAAC,GAAG;AACxB,WAAK,KAAK,CAAC,IAAI,GAAG,CAAC;AAAA,IACrB;AACA,QAAI,KAAK,KAAK,CAAC,IAAI,GAAG,CAAC,GAAG;AACxB,WAAK,KAAK,CAAC,IAAI,GAAG,CAAC;AAAA,IACrB;AAEA,0BAAsB,MAAM;AAC1B,UAAI,KAAK,UAAU;AACZ,aAAA,SAAS,KAAK,IAAI;AAAA,MACzB;AAAA,IAAA,CACD;AAAA,EACH;AACF;AAaA,uBAAqB,WAAA;AAEb,QAAA,SAAS,KAAK,QAAQ,CAAC;AAC7B,QAAM,QAAQ,OAAO;AAErB,QAAM,YAAY,CAAC,CAAC,OAAO,OAAO,MAAM;AACxC,MAAI,WAAW;AACN,WAAA,OAAO,OAAO,MAAM;AAAA,EAC7B;AAEI,OAAA,+BAAO,UAAS,KAAK,WAAW;AAElC,QAAI,MAAM,QAAQ;AAChB,WAAK,eAAe;AAAA,IACtB;AAEA;AAAA,EACF;AAEA,QAAM,UAAU,OAAO,OAAO,UAAU,EAAE;AAC1C,QAAM,WAAW,QAAQ,CAAC,MAAM,SAAS,QAAQ,CAAC,MAAM;AACxD,MAAI,CAAC,SAAU;AAEf,aAAW,UAAU,OAAO;AAC1B,UAAM,OAAO,IAAI,MAAM,MAAM,MAAM;AACnC,QAAI,CAAC,KAAM;AAEX,UAAM,YAAY,IAAI,MAAM,YAAY,KAAK,SAAS;AACtD,UAAM,aAAa,UAAU,OAAO,KAAK,WAAW;AAG/C,0BAAA,gDAAA,WAAmB,YAAY;AAAA,EACtC;AACF;AAEA,uBAAA,SAAmB,OAAuB,aAAuB;AAEzD,QAAA,SAAS,KAAK,QAAQ,CAAC;AAC7B,QAAM,UAAU,MAAM,OAAO,UAAU,EAAE;AAClC,SAAA,CAAC,CAAC,aAAa;AAAA,IACpB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,KAAK;AAAA,EAAA;AAET;AAEA,mBAAiB,WAAA;;AACf,MAAI,KAAK,SAAS;AAEL,eAAA,KAAK,KAAK,SAAS;AAC5B,UAAI,EAAE,UAAU;AACd,UAAE,SAAS;AAAA,MACb;AAAA,IACF;AAIA,SAAK,gBAAgB;AACrB,SAAK,YAAW,UAAK,QAAQ,CAAC,MAAd,mBAAiB;AACjC,aAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,QAAQ,KAAK;AAC5C,WAAK,cAAc,KAAK,KAAK,QAAQ,CAAC,EAAE,KAAK;AAAA,IAC/C;AACA,eAAW,MAAM;AACf,aAAO,KAAK;AACZ,aAAO,KAAK;AAAA,OACX,EAAE;AACL,SAAK,QAAQ,SAAS;AAAA,EACxB;AACF;AAvVA,cAHI,eAGG;AAoWF,SAAS,gBAAgB,MAAM;;AACpC,UAAO,UAAK,OAAO,MAAM,MAAlB,YAAuB,KAAK,OAAO,UAAU;AACtD;AAEA,SAAS,UAAU,YAAY;;AACvB,QAAA,EAAE,SAAS,IAAI,KAAK;AAExB,UAAA,gDAAU,UAAV,mBAAiB,SAAS,gBAA1B,aACA,gDAAU,UAAV,mBAAiB,aAAjB,mBAA4B;AAEhC;AAEA,SAAS,oBAAoB,QAAQ,QAAQ;;AAC3C,UACG,YAAY,SAAS,OAAO,IAAI,KAAK,YAAY,SAAS,OAAO,CAAC,CAAC,MACpE,GAAC,YAAO,YAAP,mBAAgB;AAErB;AAEA,SAAS,WAAW,MAAM,QAAQ,SAAS,IAAI;;AAC7C,OAAI,YAAO,SAAP,mBAAa,WAAW,gBAAiB;AAC7C,SAAO,WAAW,OAAO;AACzB,SAAO,kBAAkB,OAAO;AAChC,SAAO,qBAAqB,OAAO;AACnC,SAAO,cAAc,MAAM,CAAC,GAAG,EAAE;AACjC,SAAO,OAAO,iBAAiB;AAC/B,SAAO,iBAAiB,MAAM;AAExB,QAAA,CAAC,KAAK,QAAQ;AACT,aAAA;AAAA,IACT;AACI,QAAA,aAAa,KAAK,OAAO,KAAK,CAAC;;AAAM,eAAAC,MAAA,EAAE,WAAF,gBAAAA,IAAU,UAAS,OAAO;AAAA,KAAI;AAEvE,QAAI,CAAC,cAAc,CAAC,WAAW,MAAM;AAC5B,aAAA;AAAA,IACT;AACA,WAAO,OAAO,qBACV,OAAO,uBACP,OAAO;AAAA,EAAA;AAIb,MAAI,OAAO,eAAe;AACb,eAAA,KAAK,OAAO,eAAe;AACpC,iBAAW,MAAM,GAAG,MAAM,OAAO,IAAI;AAAA,IACvC;AAAA,EACF;AACF;AAEA,SAAS,WAAW,QAAQ;AAC1B,SAAO,OAAO,OAAO;AACrB,SAAO,cAAc,OAAO;AAC5B,SAAO,iBAAiB,OAAO;AAE/B,SAAO,OAAO;AACd,SAAO,OAAO;AACd,SAAO,OAAO;AAGd,MAAI,OAAO,eAAe;AACb,eAAA,KAAK,OAAO,eAAe;AACpC,iBAAW,CAAC;AAAA,IACd;AAAA,EACF;AACF;AAEA,SAAS,eAAe,MAAM,QAAQ,QAAQ;AAC5C,aAAW,MAAM,MAAM;AAEvB,QAAM,EAAE,KAAA,IAAS,cAAc,MAAM;AAGrC,QAAM,KAAK,KAAK;AACX,OAAA,SAAS,OAAO,MAAM,MAAM;AAAA,IAC/B,QAAQ,EAAE,MAAM,OAAO,MAAM,CAAC,UAAU,GAAG,MAAM,OAAO;AAAA,EAAA,CACzD;AAEUC,aAAAA,WAAU,KAAK,SAAS;AACjCA,YAAO,UAAU,UAAU;AAAA,EAC7B;AAGK,OAAA,QAAQ,CAAC,KAAK,IAAI,GAAG,CAAC,GAAG,KAAK,KAAK,CAAC,CAAC,GAAG,KAAK,IAAI,GAAG,CAAC,GAAG,KAAK,KAAK,CAAC,CAAC,CAAC,CAAC;AAC7E;AAEA,SAAS,gBAAgB,MAAM,QAAQ;AACrC,aAAW,MAAM;AACjB,QAAM,KAAK,KAAK;AACX,OAAA,YAAY,KAAK,OAAO,UAAU,CAAC;;AAAM,oBAAE,WAAF,mBAAU,UAAS,OAAO;AAAA,GAAI,CAAC;AAElEA,aAAAA,WAAU,KAAK,SAAS;AACjCA,YAAO,UAAU,UAAU;AAAA,EAC7B;AAGK,OAAA,QAAQ,CAAC,KAAK,IAAI,GAAG,CAAC,GAAG,KAAK,KAAK,CAAC,CAAC,GAAG,KAAK,IAAI,GAAG,CAAC,GAAG,KAAK,KAAK,CAAC,CAAC,CAAC,CAAC;AAC7E;AAEA,SAAS,cAAc,QAAQ;AAEzB,MAAA,OAAO,OAAO,CAAC;AACnB,MAAI,gBAAgB,OAAO;AAClB,WAAA;AAAA,EACT;AACA,SAAO,EAAE,KAAK;AAChB;AAEA,SAAS,aAAa,OAAO,KAAK;AAE5B,MAAA,EAAE,eAAe,QAAQ;AACnB,YAAA,IAAI,kDAAkD,GAAG,EAAE;AAC5D,WAAA;AAAA,EACT;AAEI,MAAA,MAAM,WAAW,IAAI,QAAQ;AAC/B,YAAQ,IAAI,6CAA6C;AAClD,WAAA;AAAA,EACT;AAEI,MAAA,MAAM,KAAK,CAAC,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,GAAG;AACtC,YAAQ,IAAI,6CAA6C;AAClD,WAAA;AAAA,EACT;AAEO,SAAA;AACT;AAEA,SAAS,gBAAgB,MAAyC;AAChE,SAAO,KAAK,SAAS;AACvB;AAEgB,SAAA,gBAAgB,MAAM,QAAQ,QAAkB;AAC1D,MAAA,CAAC,KAAK,OAAQ;AAClB,MAAI,QAAQ;AACL,SAAA,OAAO,UAAU,IAAI,MAAM;AAC3B,SAAA,OAAO,MAAM,IAAI;AAAA,EAAA,OACjB;AACL,WAAO,KAAK;AAAA,EACd;AAEA,MAAI,KAAK,MAAM;AACb,UAAM,OAAO,IAAI,MAAM,MAAM,KAAK,IAAI;AACtC,QAAI,MAAM;AACR,YAAM,aAAa,IAAI,MAAM,YAAY,KAAK,SAAS;AACnD,UAAA,gBAAgB,UAAU,GAAG;AAC/B,YAAI,QAAQ;AACV,qBAAW,eAAe;AAAA,QAAA,WACjB,CAAC,IAAI,kBAAkB;AAChC,qBAAW,iBAAiB,CAAC;AAC7B,qBAAW,iBAAiB;AAAA,QAC9B;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;AAEO,SAAS,aACd,QACA,SACA,aACA,gBACA,SACA;;AACA,MAAI,CAAC,SAAS;AACZ,eAAU,YAAO,OAAO,MAAM,MAApB,YAAyB,OAAO,OAAO,UAAU;EAC7D;AAEI,MAAA,QAAQ,CAAC,aAAa,OAAO;AAC3B,QAAA,CAAC,aAAa,QAAQ,CAAC,GAAG,QAAQ,CAAC,CAAC,EAAG;AAAA,aAClC,QAAQ,CAAC,MAAM,QAAQ,CAAC,GAAG;AAEpC,YAAQ,IAAI,yCAAyC,QAAQ,CAAC,GAAG,QAAQ,CAAC,CAAC;AAC3E;AAAA,EACF;AAEM,QAAA,2BAAW,IAAI;AAAA,IACnB,GAAG,OAAO,MAAK,aAAQ,CAAC,MAAT,YAAc,CAAA,CAAE;AAAA,IAC/B,GAAG,OAAO,MAAK,aAAQ,CAAC,MAAT,YAAc,CAAA,CAAE;AAAA,EAAA,CAChC;AAEG,MAAA;AACJ,QAAM,kBAAkB,MAAM;;AAC5B,QAAI,CAAC,cAAc;AACb,UAAA,OAAO,oBAAoB,aAAa;AAC3B,uBAAA,KAAK,MAAM,KAAK,WAAUD,MAAA,QAAQ,CAAC,MAAT,OAAAA,MAAc,CAAE,CAAA,CAAC;AAAA,MAAA,OACrD;AACL,uBAAe,iBAAgBE,MAAA,QAAQ,CAAC,MAAT,OAAAA,MAAc,CAAE,CAAA;AAAA,MACjD;AAAA,IACF;AACO,WAAA;AAAA,EAAA;AAGT,QAAM,WAAW,QAAQ,CAAC,MAAM,SAAS,QAAQ,CAAC,MAAM;AAC7C,aAAA,KAAK,KAAK,UAAU;AAE3B,QAAA,MAAM,aACN,MAAM,gBACN,MAAM,kBACN,MAAM,4BACN,MAAM,eACN,MAAM,WACN;AACA,UAAI,KAAK,QAAQ,CAAC,EAAE,CAAC;AACrB,UAAI,MAAK,aAAQ,CAAC,MAAT,mBAAa;AAEtB,UAAI,OAAO,MAAO,CAAC,MAAM,CAAC,GAAK;AAE/B,UAAI,UAAU;AACZ,YAAI,MAAM,OAAO;AACf,gBAAM,YAAW,aAAQ,CAAC,MAAT,mBAAa;AAC1B,cAAA,YAAY,QAAQ,KAAK,UAAU;AAC7B,oBAAA,IAAI,kCAAkC,IAAI,QAAQ;AAC1D;AAAA,UACF;AACA,0BAAkB,EAAA,CAAC,IACjB,MAAM,OAAO,KAAK,MAAM,OAAO,KAAK,KAAK,IAAI,IAAI,EAAE;AACrD;AAAA,QAAA,WACS,MAAM,OAAO;AACtB,gBAAM,YAAW,aAAQ,CAAC,MAAT,mBAAa;AAC1B,cAAA,YAAY,QAAQ,KAAK,UAAU;AAC7B,oBAAA,IAAI,kCAAkC,IAAI,QAAQ;AAC1D;AAAA,UACF;AACA,0BAAkB,EAAA,CAAC,IACjB,MAAM,OAAO,KAAK,MAAM,OAAO,KAAK,KAAK,IAAI,IAAI,EAAE;AACrD;AAAA,QAAA,WACS,MAAM,QAAQ;AACnB,cAAA;AACJ,cAAI,MAAM,MAAM;AAEP,mBAAA;AAAA,UAAA,WACE,MAAM,MAAM;AAEd,mBAAA;AAAA,UAAA,OACF;AACL,gBAAI,KAAK,IAAI;AAEX,oBAAM,IAAI;AACL,mBAAA;AACA,mBAAA;AAAA,YACP;AACA,gBAAI,KAAK,IAAI;AACH,sBAAA;AAAA,gBACN;AAAA,gBACA;AAAA,gBACA;AAAA,gBACA;AAAA,gBACA;AAAA,cAAA;AAEF;AAAA,YACF;AAEO,mBAAA;AAAA,UACT;AAEgB,0BAAA,EAAE,CAAC,IAAI;AACvB;AAAA,QACF;AAAA,MACF;AAEA,cAAQ,IAAI,+BAA+B,CAAC,sBAAsB,IAAI,EAAE;AACxE;AAAA,IACF;AAAA,EACF;AAEA,MAAI,gBAAgB,aAAa;AAC/B,QAAI,cAAc;AAChB,aAAO,OAAO,MAAM,IAAI,CAAC,QAAQ,CAAC,GAAG,YAAY;AAAA,IACnD;AAEM,UAAA,SAAS,iDAAgB,KAAK;AAEpC,QAAI,QAAQ;AACJ,YAAA,MAAM,OAAO,QAAQ;AACrB,YAAA,MAAM,OAAO,QAAQ;AAC3B,UAAI,OAAO,QAAQ,OAAO,QAAQ,YAAY,QAAQ;AACtD,UAAI,OAAO,QAAQ,OAAO,QAAQ,YAAY,QAAQ;AAC/C,aAAA,SAAS,OAAO,KAAK;AAAA,IAC9B;AAAA,EACF;AAEA,SAAO,EAAE,aAAa;AACxB;AAEA,IAAI;AACJ,IAAI,kBAAkB;AAAA,EACpB,MAAM;AAAA,EACN,OAAO;AAC0B,mCAAA,IAAI,GAAG,SAAS,WAAW;AAAA,MACxD,IAAI;AAAA,MACJ,MAAM;AAAA,MACN,SACE;AAAA,MACF,MAAM;AAAA,MACN,cAAc;AAAA,IAAA,CACf;AAAA,EACH;AAAA,EACM,sBAAsB,UAAU,UAAUR,MAAK;AAAA;AAE7C,YAAA,0BAA0B,SAAS,UAAU;AAC1C,eAAA,UAAU,uBAAuB,SAAU,QAAQ;;AAC1D,cAAM,UAAS,eAAU,KAAK,MAAM,OAAO,IAAI,MAAhC,YAAqC;AAAA,UAClD,OAAO;AAAA,UACP,OAAO,WAAW,CAAC;AAAA,QAAA;AAErB,YAAI,CAAC,oBAAoB,QAAQ,MAAM,EAAU,QAAA;AAClC,uBAAA,MAAM,QAAQ,MAAM;AAC5B,eAAA;AAAA,MAAA;AAET,eAAS,UAAU,sBAAsB,SAAU,GAAG,SAAS;;AAC7D,cAAM,IAAI,0BACN,wBAAwB,MAAM,MAAM,SAAS,IAC7C;AAEJ,YAAI,KAAK,SAAS;AAChB,cAAI,UAAU,CAAA;AACd,cAAI,WAAW,CAAA;AACJ,qBAAA,KAAK,KAAK,SAAS;AACxB,iBAAA,OAAE,YAAF,mBAAW,YAAY;AACzB;AAAA,YACF;AACI,gBAAA,EAAE,SAAS,gBAAgB;AAC7B,uBAAS,KAAK;AAAA,gBACZ,SAAS,WAAW,EAAE,IAAI;AAAA,gBAC1B,UAAU,MAAM,gBAAgB,MAAM,CAAC;AAAA,cAAA,CACxC;AAAA,YAAA,OACI;AACL,oBAAM,UAAS,eAAU,KAAK,MAAM,EAAE,IAAI,MAA3B,YAAgC;AAAA,gBAC7C,EAAE;AAAA,gBACF,EAAE,WAAW,CAAC;AAAA,cAAA;AAEZ,kBAAA,oBAAoB,GAAG,MAAM,GAAG;AAClC,wBAAQ,KAAK;AAAA,kBACX,SAAS,WAAW,EAAE,IAAI;AAAA,kBAC1B,UAAU,MAAM,eAAe,MAAM,GAAG,MAAM;AAAA,gBAAA,CAC/C;AAAA,cACH;AAAA,YACF;AAAA,UACF;AAGA,cAAI,QAAQ,QAAQ;AAClB,gBAAI,6BAA6B,OAAO;AACtC,sBAAQ,KAAK;AAAA,gBACX,SAAS;AAAA,gBACT,SAAS;AAAA,kBACP,SAAS;AAAA,gBACX;AAAA,cAAA,CACD;AAAA,YAAA,OACI;AACG,sBAAA,KAAK,GAAG,SAAS,IAAI;AAAA,YAC/B;AAAA,UACF;AACA,cAAI,SAAS,QAAQ;AACnB,gBAAI,6BAA6B,OAAO;AACtC,sBAAQ,KAAK;AAAA,gBACX,SAAS;AAAA,gBACT,SAAS;AAAA,kBACP,SAAS;AAAA,gBACX;AAAA,cAAA,CACD;AAAA,YAAA,OACI;AACG,sBAAA,KAAK,GAAG,UAAU,IAAI;AAAA,YAChC;AAAA,UACF;AAAA,QACF;AAEO,eAAA;AAAA,MAAA;AAGA,eAAA,UAAU,oBAAoB,WAAY;AAC7C,YAAA,CAAC,KAAK,OAAQ;AAEP,mBAAA,SAAS,KAAK,QAAQ;AAC/B,cAAI,MAAM,QAAQ;AAChB,gBAAI,CAAC,MAAM,OAAO,UAAU,GAAG;AACvB,oBAAA,OAAO,UAAU,IAAI,MACzB,UAAU,KAAK,MAAM,MAAM,OAAO,IAAI;AAAA,YAC1C;AAGI,gBAAA,MAAM,OAAO,QAAQ;AACvB,kBAAI,MAAM,OAAO,OAAO,CAAC,aAAa,OAAO;AAE3C,sBAAM,OAAO;AAEb,sBAAM,OAAOA,KAAI,MAAM,MAAM,MAAM,IAAI;AACvC,oBAAI,MAAM;AACR,uBAAK,OAAO,MAAM;AAAA,gBACpB;AAAA,cACF;AACA,qBAAO,MAAM,OAAO;AAAA,YACtB;AAEM,kBAAA,IAAI,KAAK,QAAQ,KAAK,CAACS,OAAMA,GAAE,SAAS,MAAM,OAAO,IAAI;AAC/D,gBAAI,GAAG;AACL,yBAAW,MAAM,CAAC;AAAA,YAAA,OACb;AACL,8BAAgB,MAAM,KAAK;AAAA,YAC7B;AAAA,UACF;AAAA,QACF;AAAA,MAAA;AAGI,YAAA,oBAAoB,SAAS,UAAU;AACpC,eAAA,UAAU,gBAAgB,WAAY;;AAC7C,cAAM,IAAI,oBAAoB,kBAAkB,MAAM,IAAI,IAAI;AAG9D,YAAI,CAACT,KAAI,oBAAoB,KAAK,SAAS;AAC9B,qBAAA,KAAK,KAAK,SAAS;AAC5B,kBAAI,4BAAG,YAAH,mBAAY,iBAAc,4BAAG,YAAH,mBAAY,eAAc;AACtD,oBAAM,UAAS,eAAU,KAAK,MAAM,EAAE,IAAI,MAA3B,YAAgC;AAAA,gBAC7C,EAAE;AAAA,gBACF,EAAE,WAAW,CAAC;AAAA,cAAA;AAED,6BAAA,MAAM,GAAG,MAAM;AAAA,YAChC;AAAA,UACF;AAAA,QACF;AAEO,eAAA;AAAA,MAAA;AAGH,YAAA,kBAAkB,SAAS,UAAU;AAClC,eAAA,UAAU,cAAc,WAAY;AAC3C,cAAM,IAAI,kBACN,gBAAgB,MAAM,MAAM,SAAS,IACrC;AACJ,YAAI,CAACA,KAAI,oBAAoB,KAAK,QAAQ;AAE7B,qBAAA,SAAS,KAAK,QAAQ;AAC/B,gBAAI,MAAM,UAAU,CAAC,MAAM,OAAO,UAAU,GAAG;AACvC,oBAAA,OAAO,UAAU,IAAI,MACzB,UAAU,KAAK,MAAM,MAAM,OAAO,IAAI;AAClC,oBAAA,IAAI,KAAK,QAAQ,KAAK,CAACS,OAAMA,GAAE,SAAS,MAAM,OAAO,IAAI;AAC/D,kBAAI,GAAG;AACL,2BAAW,MAAM,CAAC;AAAA,cACpB;AAAA,YACF;AAAA,UACF;AAAA,QACF;AAEO,eAAA;AAAA,MAAA;AAGT,eAAS,YAAY,KAAK;AACb,mBAAA,KAAKT,KAAI,MAAM,QAAQ;AAChC,cAAI,EAAE,IAAI,CAAC,MAAM,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,MAAM,IAAI,CAAC,GAAG;AACvC,mBAAA;AAAA,UACT;AAAA,QACF;AACO,eAAA;AAAA,MACT;AAGM,YAAA,sBAAsB,SAAS,UAAU;AAC/C,YAAM,iBAAiB;AACd,eAAA,UAAU,kBAAkB,SAAU,MAAM;;AACnD,cAAM,IAAI,sBACN,oBAAoB,MAAM,MAAM,SAAS,IACzC;AAEE,cAAA,QAAQ,KAAK,OAAO,IAAI;AAC9B,YAAI,CAAC,MAAM,UAAU,CAAC,MAAM,cAAc,GAAG;AAE3C,cACE,EAAE,MAAM,QAAQ,iBAChB,IAAE,uBAAM,QAAO,gBAAb,mDAA+B,eAAc,QAC/C;AACO,mBAAA;AAAA,UACT;AAAA,QACF;AAGM,cAAA,OAAO,UAAU,WAAW,eAAe;AACjDA,aAAI,MAAM,IAAI,IAAI;AAGlB,cAAM,MAAwB;AAAA,UAC5B,KAAK,IAAI,CAAC,IAAI,KAAK,KAAK,CAAC,IAAI;AAAA,UAC7B,KAAK,IAAI,CAAC;AAAA,QAAA;AAEL,eAAA,YAAY,GAAG,GAAG;AACnB,cAAA,CAAC,KAAK,UAAU;AAAA,QACtB;AAEA,aAAK,MAAM;AACN,aAAA,QAAQ,GAAG,MAAM,IAAI;AAC1B,aAAK,QAAQ,MAAM;AAGnB,cAAM,cAAc,IAAI;AACxB,mBAAW,MAAM;AACf,iBAAO,MAAM,cAAc;AAAA,WAC1B,GAAG;AAEC,eAAA;AAAA,MAAA;AAIH,YAAA,iBAAiB,SAAS,UAAU;AAC1C,eAAS,UAAU,iBAAiB,SAClC,YACA,MACA,QACA,YACA,YACA;;AACM,cAAA,IAAI,iDAAiB,MAAM;AAE7B,YAAA,SAAS,QAAgB,QAAA;AAE7B,YAAI,WAAW,QAAQ,UAAU,EAAE,OAAe,QAAA;AAG5C,cAAA,eAAc,sBAAK,OAAO,UAAU,EAAE,WAAxB,mBAAiC,gBAAjC,mDAAmD;AACvE,YAAI,CAAC,eAAe,EAAE,uBAAuB,OAAe,QAAA;AAG5D,cAAM,gBACJ,4BAAW,gBAAX,mBAAwB,aAAxB,mBAAkC,WAAlC,mBAA2C;AAC7C,YAAI,CAAC,gBAAgB,CAAC,aAAa,aAAa,YAAY,GAAG;AACtD,iBAAA;AAAA,QACT;AAEO,eAAA;AAAA,MAAA;AAAA,IAEX;AAAA;AAAA,EACA,sBAAsB;AACV,cAAA;AAAA,MACR;AAAA,MACA,OAAO,OAAO,eAAe;AAAA,QAC3B,OAAO;AAAA,MAAA,CACR;AAAA,IAAA;AAEH,kBAAc,WAAW;AAAA,EAC3B;AACF,CAAC;;;;;;ACr4BD,MAAM,QAAgB,OAAO;AAE7B,SAAS,MAAM,QAAQ,QAAQ;AAC7B,MAAI,OAAO,WAAW,YAAY,OAAO,WAAW,UAAU;AAC5D,eAAW,OAAO,QAAQ;AAClB,YAAA,KAAK,OAAO,GAAG;AACjB,UAAA,OAAO,OAAO,UAAU;AACtB,YAAA,KAAK,OAAO,GAAG;AACnB,YAAI,CAAC,GAAI,MAAK,OAAO,GAAG,IAAI,CAAA;AACtB,cAAA,IAAI,OAAO,GAAG,CAAC;AAAA,MAAA,OAChB;AACL,eAAO,GAAG,IAAI;AAAA,MAChB;AAAA,IACF;AAAA,EACF;AAEO,SAAA;AACT;AAEO,MAAM,0BAA0B,YAA+B;AAAA,EAkCpE,YAAYA,MAAK;AACT;AAlCR;AAIA;AACA,uCAA+C;AAC/C;AACA,yCASI,CAAA;AACJ;AACA;AACA;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AAQE,SAAK,MAAMA;AACN,SAAA,UAAU,IAAI,6BAA6B;AAAA,MAC9C,QAAQ,SAAS;AAAA,IAAA,CAClB;AAAA,EACH;AAAA,EAVA,IAAI,yBAAyB;AAC3B,WAAO,CAAC,KAAK,UAAU,KAAK,iBAAiB,EAAE,QAAQ;AAAA,EACzD;AAAA,EAUA,UAAU,KAAK;AACb,SAAK,KAAK,KAAK,WAAW,EAAE,IAAI,UAAU,OAAO,QAAQ;AACzD,SAAK,KAAK,KAAK,WAAW,EAAE,KAAK,UAAU,OAAO,QAAQ;AAC1D,SAAK,KAAK,GAAG,EAAE,IAAI,UAAU,IAAI,QAAQ;AACzC,SAAK,KAAK,GAAG,EAAE,KAAK,UAAU,IAAI,QAAQ;AAC1C,SAAK,cAAc;AAAA,EACrB;AAAA,EAEA,WAAW,OAAO,OAAQ;AACxB,QAAI,CAAC,SAAS,KAAK,sBAAsB,MAAO;AAE5C,QAAA,KAAK,qBAAqB,MAAM;AAClC,WAAK,UAAU,KAAK,iBAAiB,EAAE,UAAU,OAAO,UAAU;AAAA,IACpE;AACA,SAAK,UAAU,KAAK,EAAE,UAAU,IAAI,UAAU;AAC9C,SAAK,oBAAoB;AAEzB,QAAI,CAAC,KAAK,gBAAA,KAAqB,KAAK,gBAAgB,UAAU;AAC5D,WAAK,UAAU,SAAS;AAAA,IAC1B;AACA,QAAI,CAAC,KAAK,iBAAA,KAAsB,KAAK,gBAAgB,WAAW;AAC9D,WAAK,UAAU,SAAS;AAAA,IAC1B;AACA,QAAI,CAAC,KAAK,iBAAA,KAAsB,KAAK,gBAAgB,WAAW;AAC9D,WAAK,UAAU,QAAQ;AAAA,IACzB;AAEK,SAAA,UAAU,KAAK,WAAW;AAAA,EACjC;AAAA,EAEA,eAAe;AACb,SAAK,gBACH,UAAU,sBAAsB,cAAc,KAAK,aAAa;AAC7D,SAAA,eAAe,KAAK,cAAc;AACvC,SAAK,YAAY,iBAAiB,aAAa,KAAK,aAAa;AAAA,EACnE;AAAA,EAEA,YAAY,OAAO,QAAQ,MAAM;;AAC/B,SAAK,gBAAgB;AACrB,SAAK,aAAa;AAEZ,UAAA,QAAQ,KAAK,UAAU,SAAS;AACtC,SAAK,YAAY,MAAM;AAAA,MAAI,CAAC,GAAG;;AAC7B;AAAA,UACE;AAAA,UACA;AAAA,YACE,SAAS;AAAA,cACP,WAAW,EAAE,QAAQ;AAAA,YACvB;AAAA,YACA,SAAS,MAAM;AACb,mBAAK,WAAW,CAAC;AAAA,YACnB;AAAA,UACF;AAAA,UACA;AAAA,YACE,IAAI,kBAAkB;AAAA,YACtB;AAAA,cACE;AAAA,cACA;AAAA,gBACE,cAAaM,MAAA,EAAE,UAAF,OAAAA,MAAW,EAAE;AAAA,cAC5B;AAAA,cACA,EAAE,QACE,IAAI,QAAQ;AAAA,gBACV,aAAa,EAAE;AAAA,cAChB,CAAA,IACD,CAAC;AAAA,YACP;AAAA,UACF;AAAA,QACF;AAAA;AAAA,IAAA;AAGF,SAAK,eAAe,gBAAgB,GAAG,KAAK,SAAS;AAErD,QAAI,OAAO;AACT,WAAK,oBAAoB;AACzB,WAAK,WAAW,CAAC;AAAA,IAAA,OACZ;AACC,YAAA,QAAQ,KAAK,UAAU,YAAY;AACrC,UAAA,QAAQ,MAAM,UAAU,CAAC,SAAS,KAAK,UAAU,SAAS,UAAU,CAAC;AACrE,UAAA,UAAU,GAAI,SAAQ,KAAK;AAC1B,WAAA,WAAW,OAAO,IAAI;AAAA,IAC7B;AAEM,UAAA,UAAU,CAAC,GAAG,KAAK;AACzB,eAAK,cAAL,mBAAgB;AAChB,SAAK,YAAY,IAAI,cAAc,KAAK,gBAAgB,IAAI;AAC5D,SAAK,UAAU;AAAA,MACb;AAAA,MACA,CAAC,EAAE,QAAQ,EAAE,aAAa,oBAAoB;AAC5C,YAAI,gBAAgB,YAAa;AACzB,gBAAA,OAAO,aAAa,GAAG,QAAQ,OAAO,aAAa,CAAC,EAAE,CAAC,CAAC;AAChE,iBAAS,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;AACvC,eAAK,kBAAkB;AAAA,YACrB,WAAW,QAAQ,CAAC,EAAE;AAAA,YACtB,SAAS;AAAA,YACT,MAAM;AAAA,YACN,OAAO;AAAA,UAAA,CACR;AAAA,QACH;AAAA,MACF;AAAA,IAAA;AAAA,EAEJ;AAAA,EAEA,kBAAkB,OAKf;;AACD,UAAM,EAAE,WAAW,SAAS,MAAM,UAAU;AAC5C,UAAM,YAAY,gBAAK,eAAL,KAAmB,KAAK,mBAAxB,qBAA2C;AACvD,UAAA,YAAY,cAAS,UAAT,qBAAS,QAAU;AACrC,UAAM,WAAW,mBAAS,gCAAa,KAAK,4BAA3B,2BAAuD;AACxE,UAAM,WAAW,yDAAqB,CAAA;AAClC,QAAA,OAAO,UAAU,UAAU;AAC7B,YAAM,UAAU,mDAAkB,CAAA;AAC3B,aAAA,OAAO,QAAQ,KAAK;AAAA,IAAA,OACtB;AACL,cAAQ,IAAI,IAAI;AAAA,IAClB;AAAA,EACF;AAAA,EAEA,eAAe,SAAS,MAAM,OAAO,aAAa,SAAS,YAAY,MAAM;;AACvE,QAAA,UAAU,YAAqB,SAAA;AAEnC,UAAM,QACJ,4BAAK,cAAc,KAAK,aAAa,MAArC,mBAAwC,UAAxC,mBACE,KAAK,4BADP,mBAEI,aAFJ,mBAEe;AACjB,QAAI,MAAM;AACJ,UAAA,KAAK,QAAQ,MAAM;AACrB,gBAAQ,KAAK;AAAA,MACf;AACI,UAAA,KAAK,WAAW,MAAM;AACxB,kBAAU,KAAK;AAAA,MACjB;AAAA,IACF;AAEA,WAAO,IAAI,OAAO;AAAA,MAChB,IAAI,SAAS;AAAA,QACX;AAAA,QACA;AAAA,QACA,MAAM;AAAA,QACN,UAAU,CAAC,MAAM;AACf,eAAK,kBAAkB;AAAA,YACrB;AAAA,YACA;AAAA,YACA,OAAO,EAAE,MAAM,EAAE,OAAO,MAAM;AAAA,UAAA,CAC/B;AAAA,QACH;AAAA,MAAA,CACD;AAAA,MACD,IAAI,SAAS,EAAE,aAAa,aAAa;AAAA,QACvC,IAAI,SAAS;AAAA,UACX,MAAM;AAAA,UACN;AAAA,UACA,UAAU,CAAC;AAAA,UACX,UAAU,CAAC,MAAM;AACf,iBAAK,kBAAkB;AAAA,cACrB;AAAA,cACA;AAAA,cACA,OAAO,EAAE,SAAS,CAAC,CAAC,EAAE,OAAO,QAAQ;AAAA,YAAA,CACtC;AAAA,UACH;AAAA,QAAA,CACD;AAAA,MAAA,CACF;AAAA,IAAA,CACF;AAAA,EACH;AAAA,EAEA,mBAAmB;;AACjB,UAAM,UACJ,KAAK,UAAU,kBAAkB,KAAK,sBAAsB;AAC9D,UAAM,QAAQ,OAAO,KAAK,4BAAW,CAAE,CAAA;AACvC,UAAM,OAAO,IAAI,MAAM,MAAM,WAAW,KAAK,aAAa;AAC1D,UAAM,UAAS,gBAAK,WAAL,mBAAc,KAAK,4BAAnB,mBAA4C;AAC3D,SAAK,YAAY;AAAA,MACf,GAAG,MAAM,IAAI,CAAC,YAAY;;AACxB,eAAO,KAAK;AAAA,UACV;AAAA,UACA;AAAA,UACA,QAAQ,OAAO;AAAA,UACf;AAAA,YACAA,MAAA,iCAAS,aAAT,gBAAAA,IAAmB,aAAY;AAAA,QAAA;AAAA,MACjC,CACD;AAAA,IAAA;AAEI,WAAA,CAAC,CAAC,MAAM;AAAA,EACjB;AAAA,EAEA,kBAAkB;;AAChB,UAAM,SAAS,KAAK,UAAU,WAAW,KAAK,sBAAsB;AACpE,UAAM,QAAQ,OAAO,KAAK,0BAAU,CAAE,CAAA;AACtC,UAAM,OAAO,IAAI,MAAM,MAAM,WAAW,KAAK,aAAa;AAC1D,UAAM,UAAS,gBAAK,WAAL,mBAAc,KAAK,4BAAnB,mBAA4C;AAC3D,SAAK,WAAW;AAAA,MACd,GAAG,MACA,IAAI,CAAC,YAAY;;AACZ,YAAA,QAAQ,OAAO,OAAO;AAC1B,YAAI,CAAC,OAAO;AACV;AAAA,QACF;AAEA,eAAO,KAAK;AAAA,UACV;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,YACAA,MAAA,iCAAS,aAAT,gBAAAA,IAAmB,aAAY;AAAA,QAAA;AAAA,MACjC,CACD,EACA,OAAO,OAAO;AAAA,IAAA;AAEZ,WAAA,CAAC,CAAC,MAAM;AAAA,EACjB;AAAA,EAEA,mBAAmB;;AACX,UAAA,QAAQ,KAAK,UAAU,SAAS;AAChC,UAAA,eAAe,KAAK,UAAU;AAAA,MAClC,MAAM,KAAK,sBAAsB;AAAA,IAAA;AAE7B,UAAA,WAAU,kDAAc,WAAd,YAAwB;AACxC,UAAM,eACJ,KAAK,UAAU,kBAAkB,KAAK,sBAAsB;AAE9D,UAAM,OAAO,IAAI,MAAM,MAAM,WAAW,KAAK,aAAa;AAC1D,UAAM,UAAS,gBAAK,WAAL,mBAAc,KAAK,4BAAnB,mBAA4C;AAC3D,UAAM,OAAO,KAAK,UAAU,SAAS,MAAM,KAAK,sBAAsB;AAChE,UAAA,YAAY,KAAK,SAAS;AAChC,SAAK,YAAY;AAAA,MACf,GAAG,QACA,IAAI,CAACI,OAAM,SAAS;;AACb,cAAA,mBAAmB,6CAAe;AACxC,cAAM,WAAUF,OAAAF,MAAA,aAAa,gBAAb,gBAAAA,IAA2B,UAA3B,OAAAE,MAAoCE;AAChD,YAAA,SAAQC,MAAA,iCAAS,UAAT,gBAAAA,IAAgB;AAC5B,cAAM,YAAU,sCAAS,UAAT,mBAAgB,YAAW,oBAAoB;AAC3D,YAAA,CAAC,SAAS,UAAU,SAAS;AACvB,kBAAA;AAAA,QACV;AACA,eAAO,KAAK;AAAA,UACV;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,QAAA;AAAA,MACF,CACD,EACA,OAAO,OAAO;AAAA,IAAA;AAEZ,WAAA,CAAC,CAAC,QAAQ;AAAA,EACnB;AAAA,EAEA,KAAK,MAAO;;AACJ,UAAA,aAAa,OAAO,MAAK,eAAI,MAAM,UAAV,mBAAiB,eAAjB,YAA+B,CAAE,CAAA,EAAE;AAAA,MAChE,CAAC,GAAG,MAAM,EAAE,cAAc,CAAC;AAAA,IAAA;AAG7B,SAAK,iBAAiB;AAAA,MACpB;AAAA,IAAA;AAEG,SAAA,cAAc,IAAI,sCAAsC;AACxD,SAAA,aAAa,IAAI,sCAAsC;AACvD,SAAA,cAAc,IAAI,sCAAsC;AACvD,UAAA,QAAQ,IAAI,OAAO;AAAA,MACvB,KAAK;AAAA,MACL,KAAK;AAAA,MACL,KAAK;AAAA,IAAA,CACN;AAED,SAAK,OAAO;AAAA,MACV,CAAC,UAAU,KAAK,UAAU;AAAA,MAC1B,CAAC,WAAW,KAAK,WAAW;AAAA,MAC5B,CAAC,WAAW,KAAK,WAAW;AAAA,MAC5B,OAAO,CAAC,GAAG,CAAC,MAAM,IAAI,MAA6B;AACnD,QAAE,IAAI,IAAI;AAAA,QACR,KAAK,IAAI,KAAK;AAAA,UACZ,SAAS,MAAM;AACb,iBAAK,UAAU,IAAI;AAAA,UACrB;AAAA,UACA,aAAa;AAAA,QAAA,CACd;AAAA,QACD;AAAA,MAAA;AAEK,aAAA;AAAA,IACT,GAAG,CAAE,CAAA;AAEC,UAAA,QAAQ,IAAI,gCAAgC;AAAA,MAChD,IAAI,UAAU;AAAA,QACZ,IAAI,MAAM,aAAa;AAAA,QACvB;AAAA,UACE;AAAA,UACA;AAAA,YACE,UAAU,CAAC,MAAM;AACV,mBAAA,YAAY,EAAE,OAAO,KAAK;AAAA,YACjC;AAAA,UACF;AAAA,UACA,WAAW;AAAA,YAAI,CAAC,MACd,IAAI,UAAU;AAAA,cACZ,aAAa;AAAA,cACb,UAAU,cAAc,MAAM;AAAA,cAC9B,OAAO;AAAA,YAAA,CACR;AAAA,UACH;AAAA,QACF;AAAA,MAAA,CACD;AAAA,MACD,IAAI,QAAQ;AAAA,QACV,IAAI,mCAAmC,KAAK,cAAc;AAAA,QAC1D,IAAI,mCAAmC;AAAA,UACrC;AAAA,YACE;AAAA,YACA,OAAO,OAAO,KAAK,IAAI,EAAE,IAAI,CAAC,MAAM,EAAE,GAAG;AAAA,UAC3C;AAAA,UACA;AAAA,QAAA,CACD;AAAA,MAAA,CACF;AAAA,MACD,IAAI,UAAU;AAAA,QACZ;AAAA,UACE;AAAA,UACA;AAAA,YACE,SAAS,CAAC,MAAM;AAER,oBAAA,OAAO,IAAI,MAAM,OAAO;AAAA,gBAC5B,CAAC,MAAM,EAAE,SAAS,cAAc,KAAK;AAAA,cAAA;AAEvC,kBAAI,MAAM;AACR;AAAA,kBACE;AAAA,gBAAA;AAEF;AAAA,cACF;AAEE,kBAAA;AAAA,gBACE,8CAA8C,KAAK,aAAa;AAAA,cAAA,GAElE;AACA,uBAAO,IAAI,MAAM,MAAM,WAAW,KAAK,aAAa;AAC1C,0BAAA,mBAAmB,cAAc,KAAK,aAAa;AAAA,cAC/D;AACA,mBAAK,KAAK;AAAA,YACZ;AAAA,UACF;AAAA,UACA;AAAA,QACF;AAAA,QACA;AAAA,UACE;AAAA,UACA;AAAA,YACE,SAAS,MAAY;;AACf,kBAAA;AACJ,kBAAI,gBAAgB,CAAA;AACpB,oBAAM,QAAQ,CAAA;AACH,yBAAA,KAAK,KAAK,eAAe;AAClC,sBAAMD,QAAO,IAAI,MAAM,MAAM,WAAW,CAAC;AACrC,oBAAA,UAAUA,MAAAA,MAAK,WAALA,OAAAA,MAAAA,MAAK,SAAW;AAE9B,oBAAI,YAAWF,MAAA,KAAK,cAAc,CAAC,MAApB,gBAAAA,IAAuB;AACtC,oBAAI,UAAU;AACN,wBAAA,OAAO,OAAO,KAAK,QAAQ;AACjC,sBAAI,SAAS,KAAK,CAAC,CAAC,EAAE,KAAK,GAAG;AAE5B,0BAAM,eAAe,CAAA;AACrB,0BAAM,cAAc,CAAA;AACpB,0BAAM,gBAAgB,CAAA;AAEtB,+BAAW,KAAK,MAAM;AACpB,4BAAM,QAAQ,SAAS,CAAC,EAAE,KAAK,EAAE;AACjC,mCAAa,KAAK,IAAIE,MAAK,MAAM,CAAC,CAAC;AACvB,kCAAA,KAAK,IAAI,SAAS,CAAC;AAClB,mCAAA,KAAK,EAAE,QAAQ;AAAA,oBAC9B;AAGW,+BAAA,KAAKA,MAAK,OAAO;AAC1B,0BAAI,EAAE,CAAC,KAAK,KAAQ,GAAA,CAAC,IAAIA,MAAK,MAAM,EAAE,CAAC,CAAC,EAAE;AAC1C,0BAAI,EAAE,CAAC,KAAK,KAAQ,GAAA,CAAC,IAAIA,MAAK,MAAM,EAAE,CAAC,CAAC,EAAE;AAAA,oBAC5C;AAGA,wBAAIA,MAAK,UAAU;AACN,iCAAAP,QAAOO,MAAK,UAAU;AAC/B,wBAAAP,KAAI,CAAC,IAAIO,MAAK,MAAMP,KAAI,CAAC,CAAC;AAAA,sBAC5B;AAAA,oBACF;AAGA,+BAAWF,OAAM,MAAM;AACjB,0BAAA,OAAOA,GAAE,GAAG;AACd,sCAAcS,MAAK,MAAMT,GAAE,EAAE,KAAK,IAAI,OAAOA,GAAE;AAAA,sBACjD;AACA,6BAAO,OAAOA,GAAE;AAAA,oBAClB;AAEAS,0BAAK,QAAQ;AACF,+BAAA;AACXA,0BAAK,SAAS,SAAS;AAAA,kBACzB;AAEA,wBAAM,QAAQ,QAAQ;AAAA,gBACxB;AAEA,sBAAM,CAAC,IAAIA;AAEX,oBAAI,CAAC,aAAa;AAEhB,gCAAc,IAAI,MAAM,OAAO,OAAO,CAAC,GAAG,MAAM;;AAC5C,qBAAAF,MAAA,EAAAF,MAAA,EAAE,UAAF,OAAAE,MAAA,EAAAF,OAAY;AACd,sBAAE,EAAE,IAAI,EAAE,KAAK,CAAC;AACT,2BAAA;AAAA,kBACT,GAAG,CAAE,CAAA;AAAA,gBACP;AAEM,sBAAA,QAAQ,YAAY,cAAc,CAAC;AACzC,oBAAI,MAAO,eAAc,KAAK,GAAG,KAAK;AAAA,cACxC;AAEA,oBAAM,gBAAgB,qBAAqB,OAAO,CAAE,CAAA;AAEpD,yBAAW,QAAQ,eAAe;AAChC,qBAAK,SAAS;AAAA,cAChB;AAEA,mBAAK,gBAAgB;AACrB,mBAAK,IAAI,MAAM,eAAe,MAAM,IAAI;AACnC,mBAAA,YAAY,KAAK,eAAe,KAAK;AAAA,YAC5C;AAAA,UACF;AAAA,UACA;AAAA,QACF;AAAA,QACA;AAAA,UACE;AAAA,UACA,EAAE,SAAS,MAAM,KAAK,QAAQ,QAAQ;AAAA,UACtC;AAAA,QACF;AAAA,MAAA,CACD;AAAA,IAAA,CACF;AAEI,SAAA,QAAQ,gBAAgB,KAAK;AAC7B,SAAA;AAAA,MACH,OAAO,WAAW,KAAK,CAAC,MAAM,cAAc,MAAM,IAAI,IAAI,WAAW,CAAC;AAAA,IAAA;AAExE,SAAK,QAAQ;AAER,SAAA,QAAQ,iBAAiB,SAAS,MAAM;;AAC3C,OAAAA,MAAA,KAAK,cAAL,gBAAAA,IAAgB;AAAA,IAAQ,CACzB;AAAA,EACH;AACF;;;;AC5fA,MAAM,QAAQ,OAAO;AAErB,MAAM,WAAW;AAAA,EACf,OAAO;AAAA,IACL,MAAM;AAAA,IACN,YAAY;AAAA,IACZ,YAAY;AAAA,EACd;AAAA,EACA,iBAAiB,MAAM;;AACfL,UAAAA,MAAK,YAAY,IAAI;AAE3B,SAAI,eAAI,MAAM,UAAV,mBAAiB,eAAjB,mBAA8B,OAAO;AAEnC,UAAA,IAAI,MAAM,OAAO,KAAK,CAAC,MAAM,EAAE,SAASA,GAAE,GAAG;AAC/C,eAAO,SAAS,MAAM;AAAA,MAAA,OACjB;AACL,eAAO,SAAS,MAAM;AAAA,MACxB;AAAA,IACF;AACA,WAAO,SAAS,MAAM;AAAA,EACxB;AAAA,EACA,eAAe,MAAM,MAAM;AACrB,QAAA,QAAQ,IAAI,MAAM;AACtB,QAAI,CAAC,MAAO,KAAI,MAAM,QAAQ,QAAQ;AACtC,QAAI,aAAa,MAAM;AACvB,QAAI,CAAC,WAAkB,OAAA,aAAa,aAAa,CAAA;AACjD,eAAW,IAAI,IAAI;AAAA,EACrB;AACF;AAEA,MAAM,iBAAiB;AAAA,EAIrB,YAAY,OAAO;AAHnB;AACA;AAGE,SAAK,QAAQ;AAAA,EACf;AAAA,EAEA,QAAQ;AACA,UAAA,OAAO,KAAK;AAClB,QAAI,CAAC,KAAM;AAIX,SAAK,UAAU;AAEV,SAAA,WAAW,KAAK;AACZ,aAAA,eAAe,MAAM,KAAK,QAAQ;AAE3C,WAAO,EAAE,MAAM,UAAU,KAAK,SAAS;AAAA,EACzC;AAAA,EAEA,UAAU;AACF,UAAA,OAAO,OAAO,kBAAkB;AACtC,QAAI,CAAC,KAAM;AACL,UAAA,OAAO,SAAS,iBAAiB,IAAI;AAC3C,YAAQ,MAAM;AAAA,MACZ,KAAK,SAAS,MAAM;AAClB;AAAA,UACE;AAAA,QAAA;AAEF;AAAA,MACF,KAAK,SAAS,MAAM;AAClB,YACE,CAAC;AAAA,UACC;AAAA,QAAA,GAEF;AACA;AAAA,QACF;AACA;AAAA,IACJ;AACO,WAAA;AAAA,EACT;AAAA,EAEA,YAAY;AAEV,UAAM,eAAe,IAAI,MAAM,sBAAsB,KAAK;AAC1D,SAAK,QAAQ,KAAK,MACf,IAAI,CAAC,UAAU,EAAE,OAAO,aAAa,QAAQ,IAAI,GAAG,KAAK,EAAE,EAC3D,KAAK,CAAC,GAAG,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,KAAK,KAAK,EAAE,KAAK,EAAE,EACzD,IAAI,CAAC,EAAE,KAAA,MAAW,IAAI;AAAA,EAC3B;AAAA,EAEA,cAAc;AACN,UAAA,iBAAiB,CAAC,WAAW;AAEtB,iBAAA,QAAQ,OAAO,OAAO;AAC/B,cAAM,SAAS,IAAI,MAAM,YAAY,KAAK,CAAC,CAAC;AAC5C,cAAM,OAAO,OAAO,QAAQ,KAAK,CAAC,CAAC,EAAE;AACrC,aAAK,KAAK,IAAI;AAAA,MAChB;AAAA,IAAA;AAGI,UAAA,qBAAqB,CAAC,WAAW;;AAErC,aAAO,WAAW;AAClB,eAAS,IAAI,GAAG,IAAI,KAAK,MAAM,QAAQ,KAAK;AACpC,cAAA,OAAO,KAAK,MAAM,CAAC;AACrB,YAAA,GAAC,UAAK,YAAL,mBAAc,QAAQ;AAC3B,iBAAS,OAAO,GAAG,OAAO,KAAK,QAAQ,QAAQ,QAAQ;AACrD,cAAI,cAAc;AACZ,gBAAA,SAAS,KAAK,QAAQ,IAAI;AAChC,cAAI,OAAO,OAAO;AACd,cAAA,GAAC,YAAO,UAAP,mBAAc,QAAQ;AAChB,qBAAA,KAAK,OAAO,OAAO;AAC5B,kBAAM,OAAO,IAAI,MAAM,MAAM,CAAC;AAC9B,gBAAI,CAAC,KAAM;AACP,gBAAA,SAAS,IAAK,QAAO,KAAK;AAE9B,gBAAI,CAAC,IAAI,OAAO,eAAe,KAAK,SAAS,GAAG;AAChC,4BAAA;AACd;AAAA,YACF;AAAA,UACF;AACA,cAAI,aAAa;AACf,mBAAO,SAAS,KAAK,CAAC,GAAG,MAAM,IAAI,CAAC;AAAA,UACtC;AAAA,QACF;AAAA,MACF;AAAA,IAAA;AAII,UAAA,SAAS,aAAa,QAAQ,2BAA2B;AAC3D,QAAA;AAGE,UAAA,OAAO,gBAAgB,KAAK,KAAK;AACrC,YAAM,SAAS,KAAK;AAAA,QAClB,aAAa,QAAQ,2BAA2B;AAAA,MAAA;AAGlD,qBAAe,MAAM;AACrB,yBAAmB,MAAM;AAElB,aAAA;AAAA,IAAA,UACP;AACa,mBAAA,QAAQ,6BAA6B,MAAM;AAAA,IAC1D;AAAA,EACF;AACF;AAEO,MAAM,mBAAN,MAAM,iBAAgB;AAAA,EAoB3B,YAAY,MAAM,UAAU;AAnB5B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAuYA,4CAAsB,CAAA;AApYpB,SAAK,OAAO;AACZ,SAAK,WAAW;AAChB,SAAK,SAAS;AAEd,SAAK,aAAa;AAClB,SAAK,oBAAoB;AACzB,SAAK,oBAAoB;AACzB,SAAK,mBAAmB;AACxB,SAAK,oBAAoB;AACzB,SAAK,oBAAoB;AACzB,SAAK,gBAAgB;AACrB,SAAK,oBAAoB;AACzB,SAAK,oBAAoB;AACzB,SAAK,aAAa;AAClB,SAAK,mBAAmB;EAC1B;AAAA,EAEM,aAAa,SAAS,YAAY;AAAA;AACtC,WAAK,UAAU;AAAA,QACb,QAAQ,CAAC;AAAA,QACT,aAAa,CAAC;AAAA,QACd,gBAAgB,CAAC;AAAA,QACjB,kBAAkB,CAAC;AAAA,QACnB,MAAM,SAAS,MAAM,KAAK;AAAA,QAC1B,cAAc,KAAK;AAAA,QACnB,UAAU,iBAAiB,MAAM;AAAA,QACjC,OAAO,EAAE,UAAU,GAAG;AAAA,QAEtB,CAAC,KAAK,GAAG;AAAA,MAAA;AAGX,WAAK,SAAS;AACd,YAAM,aAAa,CAAA;AACnB,YAAM,cAAc,CAAA;AACpB,eAAS,IAAI,GAAG,IAAI,KAAK,SAAS,MAAM,QAAQ,KAAK;AACnD,cAAM,OAAO,KAAK,SAAS,MAAM,CAAC;AAClC,aAAK,QAAQ;AACR,aAAA,YAAY,MAAM,YAAY,WAAW;AAAA,MAChD;AAEW,iBAAA,KAAK,mBAAK,sBAAqB;AACtC;MACJ;AACA,yBAAK,qBAAsB;AAC3B,YAAM,IAAI,gBAAgB,cAAc,KAAK,MAAM,KAAK,OAAO;AAAA,IACjE;AAAA;AAAA,EAEA,WAAW;AACT,SAAK,YAAY;AACjB,SAAK,UAAU;AACf,SAAK,eAAe;AAGT,eAAA,KAAK,KAAK,SAAS,OAAO;AACnC,YAAM,CAAC,cAAc,gBAAgB,cAAc,cAAc,IAAI;AAGrE,UAAI,gBAAgB,KAAM;AAE1B,UAAI,CAAC,KAAK,UAAU,YAAY,GAAG;AAC5B,aAAA,UAAU,YAAY,IAAI;MACjC;AACA,UAAI,CAAC,KAAK,UAAU,YAAY,EAAE,cAAc,GAAG;AACjD,aAAK,UAAU,YAAY,EAAE,cAAc,IAAI,CAAA;AAAA,MACjD;AACA,WAAK,UAAU,YAAY,EAAE,cAAc,EAAE,KAAK,CAAC;AAEnD,UAAI,CAAC,KAAK,QAAQ,YAAY,GAAG;AAC1B,aAAA,QAAQ,YAAY,IAAI;MAC/B;AACA,WAAK,QAAQ,YAAY,EAAE,cAAc,IAAI;AAAA,IAC/C;AAEI,QAAA,KAAK,SAAS,UAAU;AACfE,iBAAAA,QAAO,KAAK,SAAS,UAAU;AACxC,YAAI,CAAC,KAAK,aAAaA,KAAI,CAAC,CAAC,GAAG;AAC9B,eAAK,aAAaA,KAAI,CAAC,CAAC,IAAI,EAAE,CAACA,KAAI,CAAC,CAAC,GAAGA,KAAI,CAAC,EAAE;AAAA,QAAA,OAC1C;AACA,eAAA,aAAaA,KAAI,CAAC,CAAC,EAAEA,KAAI,CAAC,CAAC,IAAIA,KAAI,CAAC;AAAA,QAC3C;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAAA,EAEA,YAAY,MAAM,YAAY,aAAa;;AACnC,UAAA,MAAM,KAAK,WAAW,IAAI;AAChC,QAAI,CAAC,IAAK;AAEJ,UAAA,SAAS,mCAAK,SAAI,UAAJ,mBAAW,YAAa,SAAI,UAAJ,mBAAW;AAEvD,SAAK,OAAO,KAAK,KAAK,kBAAkB,MAAM,YAAY,MAAM,CAAC;AACjE,SAAI,SAAI,WAAJ,mBAAY,aAAa,mBAAmB,MAAM,aAAa,GAAG;AAAA,EACxE;AAAA,EAEA,WAAW,MAAM;;AACT,UAAA,MAAM,WAAW,KAAK,IAAI;AAChC,QAAI,IAAY,QAAA;AAEhB,UAAM,YAAY,KAAK,UAAU,KAAK,KAAK;AACvC,QAAA,KAAK,SAAS,iBAAiB;AAEjC,UAAI,CAAC,UAAW;AAEhB,UAAI,OAAO,UAAU,GAAG,EAAE,CAAC,EAAE,CAAC;AAC9B,UAAI,SAAS,SAAS;AAEpB,cAAM,SAAS,KAAK,QAAQ,CAAC,EAAE,OAAO;AAChC,cAAA,eAAe,KAAK,SAAS,MAAM,UAAU,GAAG,EAAE,CAAC,EAAE,CAAC,CAAC,EAAE;AACzD,cAAA,WAAW,WAAW,YAAY;AAClC,cAAA,SACJ,cAAS,MAAM,SAAS,MAAM,MAA9B,YAAmC,SAAS,MAAM,SAAS,MAAM;AACnE,eAAO,MAAM,CAAC;AAAA,MAChB;AAEA,YAAMS,OAAO,KAAK,cAAc,KAAK,KAAK,IAAI;AAAA,QAC5C,OAAO;AAAA,UACL,UAAU;AAAA,YACR,OAAO,CAAC,MAAM,EAAE;AAAA,UAClB;AAAA,QACF;AAAA,QACA,QAAQ,CAAC,IAAI;AAAA,QACb,aAAa,CAAC;AAAA,QACd,gBAAgB,CAAC;AAAA,MAAA;AAEZA,aAAAA;AAAAA,IAAA,WACE,KAAK,SAAS,WAAW;AAClC,YAAM,UAAU,KAAK,QAAQ,KAAK,KAAK;AACnC,UAAA,WAAW,aAAa,GAAC,UAAK,aAAa,KAAK,KAAK,MAA5B,mBAAgC,KAAI;AAExD,eAAA;AAAA,MACT;AAEA,UAAI,SAAS,CAAA;AACb,UAAI,cAAc;AAClB,UAAI,WAAW;AACF,mBAAA,CAAKX,EAAAA,EAAAA,KAAI,IAAI,KAAK,UAAU,GAAG,GAAG;AAC3C,gBAAMY,QAAO,KAAK,SAAS,MAAMZ,GAAE;AAC7B,gBAAA,QAAQY,MAAK,OAAO,IAAI;AAC9B,cAAI,gBAAgB,KAAK;AACvB,0BAAc,MAAM;AAAA,UACtB;AACA,cAAI,MAAM,QAAQ;AACV,kBAAA,YAAY,WAAWA,MAAK,IAAI;AACtC,kBAAM,gBACJ,eAAU,MAAM,SAAS,MAAM,OAAO,IAAI,MAA1C,YACA,UAAU,MAAM,SAAS,MAAM,OAAO,IAAI;AAE5C,kBAAM,SAAS,CAAC,aAAa,CAAC,GAAG,MAAM;AACvC,kBAAM,MAAM;AAAA,cACV;AAAA,gBACE;AAAA,cACF;AAAA,cACA;AAAA,cACA;AAAA,cACA;AAAA,cACA;AAAA,YAAA;AAEF,sBAAS,gCAAK,iBAAL,YAAqB;AAAA,UAChC;AAAA,QACF;AAAA,iBACS,SAAS;AAClB,cAAM,CAACZ,KAAI,IAAI,IAAI,QAAQ,GAAG;AAC9B,sBAAc,KAAK,SAAS,MAAMA,GAAE,EAAE,QAAQ,IAAI,EAAE;AAAA,MAAA,OAC/C;AAEM,mBAAA,KAAK,KAAK,SAAS,OAAO;AACnC,cAAI,EAAE,CAAC,MAAM,KAAK,OAAO;AACvB,0BAAc,EAAE,CAAC;AACjB;AAAA,UACF;AAAA,QACF;AACA,YAAI,gBAAgB,KAAK;AAEvB,gBAAM,KAAI,UAAK,aAAa,KAAK,KAAK,MAA5B,mBAAgC;AAC1C,cAAI,GAAG;AACS,0BAAA;AAAA,UAChB;AAAA,QACF;AAAA,MACF;AAGA,aAAO,aAAa;AACb,aAAA;AAAA,QACL,OAAO;AAAA,UACL,UAAU;AAAA,YACR,CAAC,WAAW,GAAG,CAAC,aAAa,MAAM;AAAA,UACrC;AAAA,QACF;AAAA,QACA,QAAQ,CAAC,WAAW;AAAA,QACpB,aAAa,CAAC;AAAA,QACd,gBAAgB,CAAC;AAAA,MAAA;AAAA,IAErB;AAEQ,YAAA;AAAA,MACN,2BACE,KAAK,OACL,+BACA,KAAK;AAAA,IAAA;AAAA,EAEX;AAAA,EAEA,eAAe,MAAM,WAAW,YAAY,QAAQ,OAAQ;;AACpD,UAAA,gBAAe,sBAAK,SAAS,WAAd,mBAAuB,KAAK,WAA5B,mBAAoC,UAApC,mBAA4C;AACjE,QAAI,QACF,wDAAc,SAAd,aACA,gBAAK,WAAL,mBAAa,KAAK,CAAC,QAAQ,IAAI,SAAS,eAAxC,mBAAoD,UADpD,YAEA;AACF,QAAI,MAAM;AACV,QAAI,SAAS;AAEb,QAAK,KAAK,SAAS,mBAAmB,KAAK,SAAU,QAAQ,YAAY;AACvE,eAAS,IAAG,UAAK,UAAL,YAAc,KAAK,IAAI;AACnC,YAAM,OAAO,GAAG,MAAM,GAAG,SAAS;AAClC,UAAI,QAAQ,YAAY;AACtB,eAAO,GAAG,MAAM,GAAG,WAAW,IAAI,CAAC,IAAI,SAAS;AAAA,MAClD;AAAA,IACF;AACA,eAAW,GAAG,MAAK,gBAAW,GAAG,MAAd,YAAmB,KAAK;AAEvC,QAAA,cAAc,UAAU,cAAc,cAAc;AAClD,UAAA,CAAC,MAAO,SAAQ;AACd,YAAA,yBAAyB,GAAG,MAAM;AAAA,IAC1C;AACI,QAAA,OAAO,CAAC,MAAM,eAAe;AAC3B,UAAA,CAAC,MAAO,SAAQ;AACd,YAAA,UACJ,gBAAK,kBAAkB,KAAK,KAAK,MAAjC,oBAAqC,kBAAO,CAAC,MAAR,mBAAW,WAAX,YAAqB,aAA1D,YACA;AAAA,IACJ;AAEA,QAAI,OAAO;AACA,eAAA,CAAC,OAAO,CAAC,GAAG,kCAAK,OAAO,CAAC,IAAM,MAAO;AAAA,IACjD;AAEO,WAAA,EAAE,MAAM,QAAQ;EACzB;AAAA,EAEA,oBAAoB,QAAQ,MAAM,YAAY,YAAY;;AACxD,UAAM,QAAQ,CAAA;AACR,UAAA,gCAAgB;AACtB,UAAM,YAAa,KAAK,kBAAkB,KAAK,KAAK,IAAI;AACxD,eAAW,aAAa,YAAY;AAClC,UAAI,aAAa,IAAI,cAAc,OAAO,SAAS,GAAG,SAAS;AAC/D,UAAI,YAAY;AACR,cAAA,kBAAiB,UAAK,WAAL,mBAAa;AAAA,UAClC,CAAC,QAAQ;;AAAA,uBAAI,SAAS,eAAaK,MAAA,IAAI,WAAJ,gBAAAA,IAAY,UAAS;AAAA;AAAA;AAE1D,YAAI,iBAAiB,IAAI;AAGb,oBAAA,IAAI,gBAAgB,SAAS;AACvC,oBAAU,SAAS,IAAI;AAAA,QAAA,OAClB;AAEL,gBAAM,EAAE,MAAM,OAAO,IAAI,KAAK;AAAA,YAC5B;AAAA,YACA;AAAA,YACA;AAAA,YACA,OAAO,SAAS;AAAA,UAAA;AAElB,eAAK,QAAQ,MAAM,SAAS,IAAI,IAAI;AACpC,oBAAU,SAAS,IAAI;AACvB,eAAK,kBAAkB,IAAI,IAAI,EAAE,MAAM,UAAU;AAAA,QACnD;AAAA,MAAA,OACK;AAEL,cAAM,KAAK,SAAS;AAAA,MACtB;AAAA,IACF;AACO,WAAA,EAAE,WAAW;EACtB;AAAA,EAEA,yBAAyB,MAAM,WAAW,QAAQ;;AAChD,UAAM,aAAa,KAAK,SAAS,MAAM,KAAK,CAAC,CAAC;AAC1C,QAAA,WAAW,SAAS,iBAAiB;AAEvC,YAAM,CAAC,cAAc,GAAG,cAAc,EAAE,IAAI;AACtC,YAAA,eAAe,KAAK,cAAc,YAAY;AAC9C,YAAA,eAAe,OAAO,SAAS;AAC/B,YAAA,kBAAkB,aAAa,MAAM,SAAS;AAC9C,YAAA,SAAS,EAAE,QAAQ;AACzB,YAAM,SAAS;AAAA,QACb;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MAAA;AAEF,sBAAgB,CAAC,MACf,sCAAQ,iBAAR,YAAwB,OAAO,SAAS,EAAE,CAAC,KACvC,mBAAK,OAAO,SAAS,EAAE,CAAC,KACxB;AAEN,UAAI,OAAO,KAAK,kBAAkB,YAAY,EAAE,OAAO;AACvD,aAAO,KAAK,OAAO,GAAG,KAAK,SAAS,CAAC;AACrB,sBAAA,CAAC,EAAE,yBAAyB;AAC5B,sBAAA,CAAC,EAAE,iBAAiB;AAEhC,UAAA,cAAc,KAAK,kBAAkB,YAAY;AACrD,UAAI,CAAC,aAAa;AAChB,sBAAc,KAAK,kBAAkB,YAAY,IAAI,CAAA;AAAA,MACvD;AACI,UAAA,YAAY,SAAS,GAAG;AACd,oBAAA,SAAS,EAAE,KAAK,YAAY;AAAA,MAC1C;AACA,kBAAY,SAAS,IAAI;AAErB,UAAA,WAAW,KAAK,kBAAkB,YAAY;AAClD,UAAI,CAAC,UAAU;AACb,mBAAW,KAAK,kBAAkB,YAAY,IAAI,CAAA;AAAA,MACpD;AACA,eAAS,KAAK,EAAE,QAAQ,cAAc,UAAW,CAAA;AAAA,IACnD;AAAA,EACF;AAAA,EAEA,kBAAkB,QAAQ,MAAM,OAAO,SAAS,UAAU,YAAY;AACpE,SAAK,WAAW,KAAK,KAAK,IAAI,CAAA;AAC9B,aAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AAC/B,YAAA,YAAY,MAAM,CAAC;AACrB,UAAA,QAAQ,CAAC,GAAG;AACd,aAAK,yBAAyB,QAAQ,CAAC,GAAG,WAAW,MAAM;AAE3D;AAAA,MACF;AAEA,YAAM,EAAE,MAAM,QAAQ,iBAAiB,KAAK;AAAA,QAC1C;AAAA,QACA;AAAA,QACA;AAAA,QACA,OAAO,SAAS;AAAA,MAAA;AAGlB,WAAK,WAAW,KAAK,KAAK,EAAE,SAAS,IAAI;AACrC,WAAA,6CAAc,aAAY,MAAO;AAErC,WAAK,QAAQ,MAAM,SAAS,IAAI,IAAI;AAC3B,eAAA,CAAC,IAAI,KAAK;AAAA,IACrB;AAAA,EACF;AAAA,EAEA,wBACE,QACA,MACA,OACA,WACA,SACA,UACA,YACA;AAEA,UAAM,iBAAiB,CAAC,GAAG,UAAU,MAAM,EACxC,KAAK,EACL,IAAI,CAAC,MAAM,UAAU,IAAI,CAAC,CAAC;AAC9B,aAAS,IAAI,GAAG,IAAI,eAAe,QAAQ,KAAK;AACxC,YAAA,YAAY,eAAe,CAAC;AAClC,UAAI,QAAQ,MAAM,SAAS,CAAC,GAAG;AACxB,aAAA;AAAA,UACH,QAAQ,MAAM,SAAS,CAAC;AAAA,UACxB;AAAA,UACA;AAAA,QAAA;AAGF;AAAA,MACF;AAEA,YAAM,EAAE,MAAM,OAAO,IAAI,KAAK;AAAA,QAC5B;AAAA,QACA;AAAA,QACA;AAAA,QACA,OAAO,SAAS;AAAA,QAChB;AAAA,UACE,cAAc;AAAA,QAChB;AAAA,MAAA;AAGF,WAAK,QAAQ,MAAM,SAAS,IAAI,IAAI;AACpC,WAAK,kBAAkB,IAAI,IAAI,EAAE,MAAM,UAAU;AAEjD,UAAI,CAAC,KAAK,kBAAkB,KAAK,KAAK,GAAG;AACvC,aAAK,kBAAkB,KAAK,KAAK,IAAI,CAAA;AAAA,MACvC;AACA,WAAK,kBAAkB,KAAK,KAAK,EAAE,SAAS,IAAI;AAEhD,eAAS,MAAM,SAAS,CAAC,IAAI,KAAK;AAAA,IACpC;AAAA,EACF;AAAA,EAGA,kBAAkB,MAAM,YAAY,QAAQ;;AAC1C,UAAM,eAAe,CAAA;AAEf,UAAA,aAAa,OAAO,KAAK,MAAM;AACjC,QAAA,CAAC,WAAW,OAAQ;AAExB,UAAM,EAAE,WAAW,MAAM,IAAI,KAAK;AAAA,MAChC;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IAAA;AAEF,UAAM,WAAU,UAAK,QAAQ,KAAK,KAAK,MAAvB,YAA4B;AAC5C,UAAM,WAAY,KAAK,iBAAiB,KAAK,KAAK,IAAI;AACtD,SAAK,kBAAkB,QAAQ,MAAM,OAAO,SAAS,UAAU,UAAU;AAGzE,uBAAK,qBAAoB;AAAA,MAAK,MAC5B,KAAK;AAAA,QACH;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,IAAA;AAGK,WAAA;AAAA,EACT;AAAA,EAEA,mBAAmB,MAAM,aAAa,KAAK;;AACzC,UAAM,WAAY,KAAK,kBAAkB,KAAK,KAAK,IAAI;AAGvD,aAAS,WAAW,GAAG,WAAW,IAAI,OAAO,QAAQ,YAAY;AAC/D,YAAM,YAAY,KAAK,UAAU,KAAK,KAAK;AAErC,YAAA,WACJ,uCAAY,cAAa,GAAC,UAAK,aAAa,KAAK,KAAK,MAA5B,mBAAgC;AACtD,YAAA,gBACJ,sBAAK,SAAS,WAAd,mBAAuB,KAAK,WAA5B,mBAAoC,WAApC,mBAA6C;AACzC,YAAA,WAAU,kDAAc,YAAd,YAAyB,CAAC;AACrC,WAAA,iBAAiB,KAAK,OAAO;AAClC,UAAI,CAAC,SAAS;AACZ;AAAA,MACF;AAEA,eAAS,QAAQ,IAAI,KAAK,QAAQ,OAAO;AACzC,WAAK,kBAAkB,KAAK,QAAQ,OAAO,MAAM,IAAI;AAAA,QACnD;AAAA,QACA,MAAM;AAAA,MAAA;AAER,WAAK,QAAQ,OAAO,KAAK,IAAI,OAAO,QAAQ,CAAC;AAC7C,WAAK,QAAQ,eAAe,KAAK,IAAI,eAAe,QAAQ,CAAC;AAE7D,UAAI,QAAQ,6CAAc;AAC1B,UAAI,CAAC,OAAO;AACV,iBAAQ,eAAI,gBAAJ,mBAAkB,cAAlB,YAA+B,IAAI,OAAO,QAAQ;AACpD,cAAA,SAAS,KAAK,QAAQ,KAAK,CAAC,MAAM,EAAE,SAAS,KAAK;AACxD,YAAI,iCAAQ,OAAO;AACjB,kBAAQ,OAAO;AAAA,QACjB;AAAA,MACF;AAEA,UAAI,OAAO;AACX,UAAI,QAAQ,aAAa;AACvB,cAAM,SAAS,IAAG,UAAK,UAAL,YAAc,KAAK,IAAI;AAClC,eAAA,GAAG,MAAM,GAAG,KAAK;AACxB,YAAI,QAAQ,aAAa;AACvB,iBAAO,GAAG,MAAM,GAAG,KAAK,KAAK,IAAI,KAAK;AAAA,QACxC;AAAA,MACF;AACA,kBAAY,IAAI,IAAI;AAEf,WAAA,QAAQ,YAAY,KAAK,IAAI;AAAA,IACpC;AAAA,EACF;AAAA,EAEA,OAAa,qBAAqB,YAAY,kBAAkB;AAAA;AAC9D,YAAM,QAAQ,IAAI;AAClB,UAAI,QAAQ,WAAY;AACtB,mBAAW,KAAK,YAAY;AACtB,cAAA;AACQ,sBAAA,mBAAmB,cAAc,CAAC;AAAA,mBACrC,OAAO;AAAA,UAAC;AAAA,QACnB;AACA,YAAI,QAAQ;AAAA,MAAA;AAGd,iBAAW,KAAK,YAAY;AACpB,cAAA,YAAY,WAAW,CAAC;AAE9B,YAAI,aAAa;AACN,mBAAA,KAAK,UAAU,OAAO;AAE/B,cAAI,EAAE,EAAE,QAAQ,UAAU,wBAAwB;AAChD,6BAAiB,KAAK;AAAA,cACpB,MAAM,EAAE;AAAA,cACR,MAAM,6BAA6B,CAAC;AAAA,YAAA,CACrC;AAED,6BAAiB,KAAK;AAAA,cACpB,MAAM,cAAc;AAAA,cACpB,QAAQ;AAAA,gBACN,MAAM;AAAA,gBACN,UAAU,CAAC,MAAM;AACf,yBAAO,WAAW,CAAC;AACnB,oBAAE,OAAO,cAAc;AACrB,oBAAA,OAAO,MAAM,gBAAgB;AAC7B,oBAAA,OAAO,MAAM,UAAU;AAAA,gBAC3B;AAAA,cACF;AAAA,YAAA,CACD;AAEY,yBAAA;AAAA,UACf;AAAA,QACF;AAEA,YAAI,WAAY;AAEhB,cAAM,SAAS,IAAI,iBAAgB,GAAG,SAAS;AAC/C,cAAM,OAAO;MACf;AAAA,IACF;AAAA;AACF;AA/HE;AAzZK,IAAM,kBAAN;AA0hBA,MAAM,iBAAiB;AAAA,EAK5B,YAAY,MAAM;AAJlB;AACA;AACA;;AAGE,SAAK,OAAO;AACZ,SAAK,aAAY,gBAAK,gBAAL,mBAAkB,aAAlB,mBAA6B;AAEzC,SAAA,KAAK,gBAAgB,CAAC,eAAe;;AACxC,WAAK,aAAa;AAElB,eACM,iBAAiB,GACrB,iBAAiB,KAAK,WAAW,QACjC,kBACA;AACM,cAAA,YAAY,KAAK,WAAW,cAAc;AAEhD,mBAAW,MAAKA,MAAA,UAAU,YAAV,OAAAA,MAAqB,CAAA,GAAI;AACnC,cAAA,EAAE,SAAS,oBAAoB;AACjC,cAAE,iBAAiB,EAAE;AAAA,UACvB;AAAA,QACF;AAEA,kBAAU,QAAQ;AACR,kBAAA,eAAe,CAAC,SAAS;;AAEjC,gBAAM,gBACJA,MAAA,KAAK,UAAU,iBAAiB,UAAU,KAAK,MAA/C,gBAAAA,IAAmD;AACrD,cAAI,gBAAgB,MAAM;AACjB,mBAAA,KAAK,KAAK,aAAa,YAAY;AAAA,UAC5C;AAGA,gBAAM,aAAYE,MAAA,KAAK,UAAU,QAAQ,UAAU,KAAK,MAAtC,gBAAAA,IAA0C;AACxD,cAAA,CAAC,UAAkB,QAAA;AAEvB,gBAAM,YAAY,WAAW,UAAU,CAAC,CAAC;AAErC,cAAA,UAAU,SAAS,gBAAwB,QAAA;AAExC,iBAAA;AAAA,QAAA;AAGC,kBAAA,eAAe,CAAC,SAAS;;AACjC,gBAAM,gBACJF,MAAA,KAAK,UAAU,iBAAiB,UAAU,KAAK,MAA/C,gBAAAA,IAAmD;AACrD,cAAI,gBAAgB,MAAM;AAExB,kBAAM,SAAS,KAAK,KAAK,OAAO,YAAY,EAAE;AAC9C,gBAAIQ,QAAO,IAAI,MAAM,MAAM,MAAM;AAKjCA,oBAAO,iCACFA,QADE;AAAA,cAEL,WAAW,UAAU;AAAA,cACrB,aAAa,CAAC;AAAA,YAAA;AAETA,mBAAAA;AAAAA,UACT;AAEA,cAAI,QAAON,MAAA,KAAK,UAAU,QAAQ,UAAU,KAAK,MAAtC,gBAAAA,IAA0C;AACjD,cAAA,CAAC,KAAa,QAAA;AAEX,iBAAA;AAAA,YACL,WAAW,WAAW,KAAK,CAAC,CAAC,EAAE;AAAA,YAC/B,aAAa,KAAK,CAAC;AAAA,YACnB,WAAW,UAAU;AAAA,YACrB,aAAa,CAAC;AAAA,UAAA;AAET,iBAAA;AAAA,QAAA;AAAA,MAEX;AAAA,IAAA;AAGG,SAAA,KAAK,aAAa,CAAC,SAAS;;AAExB,aAAA,mBAAK;AACZ,YAAM,SAAS,KAAK,UAAU,kBAAkB,KAAK,WAAW;AAChE,UAAI,YAAY,KAAK,WAAW,OAAO,KAAK,KAAK;AAC7C,UAAA;AACG,cAAA,uCAAW,UAAS,WAAW;AAChC,YAAA,UAAU,aAAa,CAAC;AAChB,oBAAA,UAAU,aAAa,CAAC;AAAA,MACtC;AAEA,UAAI,CAAC,WAAW;AACP,eAAA;AAAA,MACT;AAEA,UAAI,KAAK,iBAAiB,YAAY,SAAS,GAAG;AACzC,eAAA,UAAU,WAAW,CAAC;AAAA,MAC/B;AAEA,WAAK,YAAY,UAAU;AACtB,WAAA,eAAcF,MAAA,uBAAG,gBAAH,OAAAA,MAAkB,OAAO;AACrC,aAAA;AAAA,IAAA;AAGJ,SAAA,KAAK,gBAAgB,MAAM;AAC1B,UAAA,CAAC,KAAK,YAAY;AACpB,aAAK,KAAK;AAAA,UACR,KAAK,UAAU,SAAS,MAAM,IAAI,CAAC,GAAG,MAAM;AAC1C,kBAAM,YAAY,UAAU,WAAW,EAAE,IAAI;AAC7C,sBAAU,UAAU,CAAC;AAErB,sBAAU,KAAK,GAAG,KAAK,KAAK,EAAE,IAAI,CAAC;AAC5B,mBAAA;AAAA,UAAA,CACR;AAAA,QAAA;AAAA,MAEL;AAEA,WAAK,mBAAmB;AAExB,aAAO,KAAK;AAAA,IAAA;AAGT,SAAA,KAAK,WAAW,MAAY;AACzBL,YAAAA,MAAK,KAAK,KAAK;AACf,YAAA,KAAK,KAAK,KAAK;AACf,YAAA,QAAQ,KAAK,KAAK,eAAe;AAEvC,YAAM,YAAY,UAAU,WAAW,KAAK,KAAK,IAAI;AACrD,gBAAU,KAAKA;AAGf,gBAAU,cAAc,KAAK;AACnB,gBAAA,KAAK,EAAE;AACb,UAAA,MAAM,IAAI,SAAS;AACvB,gBAAU,OAAO;AAAA,QACf,KAAK,IAAI,UAAU,KAAK,CAAC,GAAG,GAAG,CAAC,CAAC;AAAA,QACjC,KAAK,IAAI,UAAU,KAAK,CAAC,GAAG,GAAG,CAAC,CAAC;AAAA,MAAA;AAIzB,gBAAA,KAAK,EAAE,aAAa,KAAK;AAC5B,aAAA;AAAA,IAAA;AAGJ,SAAA,KAAK,iBAAiB,MAAM;AAC/B,YAAM,gBAAgB,MAAM;;AACpB,cAAA,SAAS,aAAa,QAAQ,2BAA2B;AAE/D,cAAM,IAAI,mBAAK,KAAK,UAAU;AAC9B,UAAE,QAAQ,CAAC,GAAG,EAAE,KAAK;AACf,cAAA,aAAa,KAAK,KAAK,cAAc;AAC3C,YAAI,MAAM,CAAA;AACV,iBAAS,IAAI,GAAG,IAAI,EAAE,MAAM,QAAQ,KAAK;AACnCA,cAAAA,OAAKK,MAAA,yCAAa,OAAb,gBAAAA,IAAiB;AAE1B,cAAIL,OAAM,QAAQ,MAAMA,GAAE,GAAG;AAC3BA,kBAAK;AAAA,UAAA,OACA;AACL,gBAAI,KAAKA,GAAE;AAAA,UACb;AACE,YAAA,MAAM,CAAC,IAAI,iCAAK,EAAE,MAAM,CAAC,IAAd,EAAiB,IAAAA;QAChC;AACA,qBAAa,QAAQ,6BAA6B,KAAK,UAAU,CAAC,CAAC;AACnE,YAAI,OAAO;AACE,qBAAA,QAAQ,6BAA6B,MAAM;AAExD,cAAM,CAAC,GAAG,CAAC,IAAI,KAAK,KAAK;AACrB,YAAA;AACA,YAAA;AAEEc,cAAAA,eAAc,IAAI,SACpB,MACA,OAAO,KAAK,IAAI,OAAO,cAAc;AACzC,cAAMC,YAAW,CAAA;AACjB,iBAAS,IAAI,GAAG,IAAID,aAAY,QAAQ,KAAK;AACrCd,gBAAAA,MAAKc,aAAY,CAAC;AACxB,gBAAM,UAAU,IAAI,MAAM,YAAYd,GAAE;AAClC,gBAAA,YAAY,WAAW,CAAC;AAC9Be,oBAAS,KAAK,OAAO;AAErB,cAAI,QAAQ,QAAQ,QAAQ,IAAI,CAAC,IAAI,MAAM;AAClC,mBAAA,QAAQ,IAAI,CAAC;AAAA,UACtB;AACA,cAAI,OAAO,QAAQ,QAAQ,IAAI,CAAC,IAAI,KAAK;AACjC,kBAAA,QAAQ,IAAI,CAAC;AAAA,UACrB;AAEI,cAAA,CAAC,QAAQ,QAAS;AAEtB,gBAAM,MAAM,KAAK,UAAU,kBAAkB,UAAU,KAAK;AAC5D,cAAI,KAAK;AACD,kBAAA,UAAU,OAAO,KAAK,GAAG;AAE/B,uBAAW,WAAW,SAAS;AACvB,oBAAA,UAAU,IAAI,OAAO;AAC3B,kBAAI,CAAC,QAAS;AAER,oBAAA,cAAc,KAAK,KAAK,QAAQ;AAAA,gBACpC,CAAC,MAAM,EAAE,SAAS;AAAA,cAAA;AAEpB,kBAAI,gBAAgB,GAAI;AAGpB,kBAAA,UAAU,SAAS,iBAAiB;AACtC,yBAASC,KAAI,GAAGA,KAAI,QAAQ,QAAQ,QAAQA,MAAK;AACvC,0BAAA,QAAQA,EAAC,EAAE,QACjB,KAAK,KAAK,QAAQ,cAAcA,EAAC,EAAE;AAAA,gBACvC;AAAA,cAAA,OACK;AACL,sBAAM,cAAc,KAAK,KAAK,QAAQ,WAAW;AAC3C,sBAAA,YAAY,QAAQ,QAAQ;AAAA,kBAChC,CAAC,MAAM,EAAE,SAAS;AAAA,gBAAA;AAEpB,oBAAI,CAAC,UAAW;AAEhB,0BAAU,QAAQ,YAAY;AAC9B,yBAAS,IAAI,GAAG,MAAIT,MAAA,YAAY,kBAAZ,gBAAAA,IAA2B,SAAQ,KAAK;AAC1D,4BAAU,cAAc,CAAC,EAAE,QACzB,YAAY,cAAc,CAAC,EAAE;AAAA,gBACjC;AAAA,cACF;AAAA,YACF;AAAA,UACF;AAAA,QACF;AAGA,mBAAW,WAAWQ,WAAU;AAC9B,kBAAQ,MAAM;AAAA,YACZ,QAAQ,IAAI,CAAC,KAAK,OAAO;AAAA,YACzB,QAAQ,IAAI,CAAC,KAAK,MAAM;AAAA,UAAA;AAAA,QAE5B;AAEA,eAAO,EAAE,UAAAA,WAAU,aAAAD,aAAY;AAAA,MAAA;AAG3B,YAAA,kBAAkB,CAACA,iBAAgB;AAC5B,mBAAA,kBAAkB,KAAK,UAAU,kBAAkB;AACtDd,gBAAAA,MAAKc,aAAY,cAAc;AACrC,gBAAM,UAAU,IAAI,MAAM,YAAYd,GAAE;AACxC,gBAAM,MAAM,KAAK,UAAU,iBAAiB,cAAc;AAC1D,qBAAW,gBAAgB,KAAK;AACxB,kBAAA,cAAc,IAAI,YAAY;AACpC,gBAAI,eAAe,KAAM;AACnB,kBAAA,OAAO,KAAK,OAAO,WAAW;AAChC,gBAAA,KAAK,QAAQ,KAAM;AACvB,kBAAM,OAAO,IAAI,MAAM,MAAM,KAAK,IAAI;AACtC,gBAAI,CAAC,KAAM;AAEX,kBAAM,aAAa,IAAI,MAAM,YAAY,KAAK,SAAS;AACvD,uBAAW,QAAQ,KAAK,aAAa,SAAS,CAAC,YAAY;AAAA,UAC7D;AAAA,QACF;AAAA,MAAA;AAGI,YAAA,mBAAmB,CAACc,iBAAgB;;AACxC,iBACM,gBAAgB,GACpB,kBAAgBT,MAAA,KAAK,YAAL,gBAAAA,IAAc,SAC9B,iBACA;AACM,gBAAA,SAAS,KAAK,QAAQ,aAAa;AACrC,cAAA,CAAC,OAAO,MAAO;AACnB,gBAAM,QAAQ,CAAC,GAAG,OAAO,KAAK;AAC9B,qBAAW,KAAK,OAAO;AACrB,kBAAM,OAAO,KAAK,UAAU,kBAAkB,aAAa;AAC3D,kBAAM,OAAO,IAAI,MAAM,MAAM,CAAC;AAC9B,kBAAM,aAAa,IAAI,MAAM,YAAY,KAAK,SAAS;AACjD,kBAAA,UAAU,IAAI,MAAM,YAAYS,aAAY,KAAK,KAAK,KAAK,CAAC;AAClE,oBAAQ,QAAQ,KAAK,MAAM,YAAY,KAAK,WAAW;AAAA,UACzD;AAAA,QACF;AAAA,MAAA;AAGF,YAAM,EAAE,UAAU,YAAY,IAAI,cAAc;AAChD,sBAAgB,WAAW;AAC3B,uBAAiB,WAAW;AACxB,UAAA,MAAM,OAAO,KAAK,IAAI;AAEnB,aAAA;AAAA,IAAA;AAGH,UAAA,sBAAsB,KAAK,KAAK;AACtC,SAAK,KAAK,sBAAsB,SAAU,GAAG,SAAS;AAC/B,iEAAA,MAAM,MAAM;AAEjC,UAAI,cAAc,QAAQ,UAAU,CAAC,MAAM,EAAE,YAAY,SAAS;AAC9D,UAAA,gBAAgB,GAAI,eAAc,QAAQ;AAAA,UACzC;AACG,cAAA;AAAA,QACN;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,UACE,SAAS;AAAA,UACT,UAAU,MAAM;AACd,mBAAO,KAAK;UACd;AAAA,QACF;AAAA,QACA;AAAA,UACE,SAAS;AAAA,UACT,UAAU,MAAM;AACd,gBAAI,kBAAkB,GAAG,EAAE,KAAK,KAAK,IAAI;AAAA,UAC3C;AAAA,QACF;AAAA,MAAA;AAAA,IACF;AAII,UAAA,iBAAiB,KAAK,KAAK;AACjC,SAAK,KAAK,iBAAiB,SAAU,KAAK,QAAQ,MAAM,OAAO;AAC7C,uDAAA,MAAM,MAAM;AAE5B,YAAM,OAAO,IAAI;AACjB,UAAI,UAAU;AACd,UAAI,KAAK,IAAI,CAAC,SAAS,IAAI,GAAG,CAAC;AAC/B,UAAI,KAAK,IAAI,CAAC,SAAS,IAAI,GAAG,CAAC;AAC/B,UAAI,KAAK,IAAI,CAAC,SAAS,IAAI,GAAG,CAAC;AAC/B,UAAI,KAAK,IAAI,CAAC,SAAS,IAAI,GAAG,CAAC;AAC/B,UAAI,KAAK,IAAI,CAAC,SAAS,IAAI,GAAG,CAAC;AAC/B,UAAI,KAAK,IAAI,CAAC,SAAS,IAAI,GAAG,CAAC;AAC/B,UAAI,KAAK,IAAI,CAAC,SAAS,IAAI,GAAG,CAAC;AAC/B,UAAI,KAAK,IAAI,CAAC,SAAS,IAAI,GAAG,CAAC;AAC/B,UAAI,KAAK,IAAI,CAAC,SAAS,IAAI,GAAG,CAAC;AAE3B,UAAA,YAAY,KAAK,YAAY,UAAU;AAC3C,UAAI,KAAK;AACT,UAAI,YAAY;AAAA,IAAA;AAIlB,UAAM,mBAAmB,KAAK;AACxB,UAAA,YAAY,KAAK,UAAU;AAC5B,SAAA,mBAAmB,SAAU,KAAK;;AACrC,YAAM,KAAIT,MAAA,qDAAkB,UAAlB,gBAAAA,IAAA,uBAA0B,MAAM;AAC1C,UACE,CAAC,IAAI,kBAAkB,KAAK,MAC5B,KAAK,0BAA0B,MAC/B;AACA,cAAM,IAAI,UAAU,MAAM,KAAK,qBAAqB;AACpD,YAAI,CAAC,EAAG;AACR,cAAM,UAAU,WAAW,EAAE,SAAS,EAAE,IAAI,KAAK,KAAK,qBAAqB,IAAI,UAAU,MAAM,MAAM;AACrG,YAAI,KAAK;AACT,YAAI,OAAO;AACL,cAAA,KAAK,IAAI,YAAY,OAAO;AAC9B,YAAA,YAAY,KAAK,YAAY,UAAU;AAC3C,YAAI,UAAU;AACV,YAAA;AAAA,UACF;AAAA,UACA,CAAC,UAAU,oBAAoB;AAAA,UAC/B,GAAG,QAAQ;AAAA,UACX;AAAA,UACA;AAAA,QAAA;AAEF,YAAI,KAAK;AAET,YAAI,YAAY;AAChB,YAAI,SAAS,SAAS,GAAG,CAAC,UAAU,oBAAoB,CAAC;AACzD,YAAI,QAAQ;AAAA,MACd;AAAA,IAAA;AAII,UAAA,mBAAmB,KAAK,KAAK;AAC9B,SAAA,KAAK,mBAAmB,WAAY;AACvC,WAAK,iBAAiB;AACf,aAAA,qDAAkB,MAAM,MAAM;AAAA,IAAS;AAGhD,UAAM,OAAO;AACP,UAAA,gBAAgB,KAAK,KAAK;AAC3B,SAAA,KAAK,gBAAgB,WAAY;;AAChC,UAAA,CAAC,KAAK,SAAS;AACjB;AAAA,MACF;AACM,YAAA,SAAS,KAAK,UAAU,SAAS;AACvC,UAAI,QAAQ;AACV,mBAAW,KAAK,QAAQ;AAChB,gBAAA,UAASA,MAAA,OAAO,CAAC,MAAR,gBAAAA,IAAW;AAC1B,qBAAW,KAAK,QAAQ;AACtB,gBAAI,OAAO,CAAC,EAAE,YAAY,MAAO;AACjC,kBAAM,aAAa,KAAK,UAAU,kBAAkB,CAAC,EAAE,CAAC;AAClD,kBAAA,SAAS,KAAK,QAAQ,KAAK,CAACG,OAAMA,GAAE,SAAS,UAAU;AAC7D,gBAAI,QAAQ;AACV,qBAAO,OAAO;AACd,qBAAO,cAAc,MAAM,CAAC,GAAG,EAAE;AAAA,YACnC;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAEO,aAAA,+CAAe,MAAM,MAAM;AAAA,IAAS;AAGpC,aAAA,YAAY,MAAM,OAAO,UAAU;AAC1C,YAAM,UAAU,CAAC,EAAE,aAAa;;AACxBR,cAAAA,MAAK,MAAM,MAAM;AACvB,YAAI,CAACA,IAAI;AACT,cAAMY,QAAO,IAAI,MAAM,YAAYZ,GAAE;AACrC,YAAIY,MAAM;AAEJ,cAAA,kBAAiBP,MAAA,KAAK,eAAL,gBAAAA,IAAiB,UAAU,CAAC,MAAM,EAAE,MAAML;AACjE,YAAI,iBAAiB,IAAI;AACvB,eAAK,KAAK,wBAAwB;AAC9B,cAAA;AAAA,YACF,IAAI,YAAY,MAAM;AAAA,cACpB,QAAQ,SAAS,QAAQ,KAAK,KAAK,KAAK,IAAI,KAAK,IAAI;AAAA,YAAA,CACtD;AAAA,UAAA;AAAA,QAEL;AAAA,MAAA;AAEE,UAAA,iBAAiB,MAAM,OAAO;AAC3B,aAAA;AAAA,IACT;AAEA,UAAM,YAAY,YAAY;AAAA,MAC5B;AAAA,MACA;AAAA,MACA,CAAC,MAAM;AAAA,MACP,CAAC,GAAGA,KAAIY,UAASZ;AAAAA,IAAA;AAGnB,UAAM,WAAW,YAAY;AAAA,MAC3B;AAAA,MACA;AAAA,MACA,CAAC,OAAM,uBAAG,kBAAgB,uBAAG;AAAA,MAC7B,CAAC,GAAGA,KAAIY,UAAU,iCACb,IADa;AAAA,QAEhB,MAAMZ;AAAAA,QACN,cAAcA;AAAAA,QACd,OAAO,CAACY,MAAK;AAAA,MAAA;AAAA,IACf;AAGF,UAAM,YAAY,KAAK;AAClB,SAAA,KAAK,YAAY,WAAY;AACrB,6CAAA,MAAM,MAAM;AACnB,UAAA,oBAAoB,aAAa,SAAS;AAC1C,UAAA,oBAAoB,YAAY,QAAQ;AAAA,IAAA;AAGzC,SAAA,KAAK,qBAAqB,CAAC,SAAS;;AAE5B,iBAAA,cAAc,KAAK,UAAU,mBAAmB;AACnD,cAAA,SAAS,KAAK,KAAK,QAAQ,KAAK,CAAC,MAAM,EAAE,SAAS,UAAU;AAC9D,aAAA,iCAAQ,UAAS,SAAS;AAC5B,gBAAM,MAAM,KAAK,UAAU,kBAAkB,UAAU;AACvD,gBAAM,MAAM,KAAK,IAAI,KAAK,IAAI;AACxB,gBAAA,SACJ,MAAAL,OAAAF,MAAA,2BAAK,UAAL,gBAAAA,IAAY,aAAZ,gBAAAE,IAAuB,IAAI,eAA3B,aACA,sCAAK,UAAL,mBAAY,aAAZ,mBAAuB,IAAI;AAC7B,cAAI,CAAC,MAAO;AAEL,iBAAA,QAAQ,SAAS,MAAM,CAAC;AAG7B,cAAA,IAAI,cAAc,WAClB,CAAC,OAAO,QAAQ,OAAO,SAAS,OAAO,KAAK,GAC5C;AACA,mBAAO,QAAQ,OAAO,QAAQ,OAAO,CAAC;AAC/B,mBAAA,SAAS,OAAO,KAAK;AAAA,UAC9B;AAAA,QACF;AAAA,MACF;AAAA,IAAA;AAAA,EAEJ;AAAA,EAEA,qBAAqB;;AACR,eAAA,iBAAiB,KAAK,UAAU,mBAAmB;AACtD,YAAA,YAAY,KAAK,KAAK,QAAQ,KAAK,CAAC,MAAM,EAAE,SAAS,aAAa;AACxE,UAAI,CAAC,UAAW;AAEhB,YAAM,WAAW,UAAU;AAC3B,YAAM,MAAM,KAAK,UAAU,kBAAkB,aAAa;AAC1D,UAAI,YAAY,KAAK,WAAW,IAAI,KAAK,KAAK;AAE1C,UAAA,UAAU,SAAS,iBAAiB;AACtC,kBAAU,iBAAiB;AAC3B,cAAM,kBAAkB,KAAK,UAAU,kBAAkB,IAAI,KAAK,KAAK;AAC5D,mBAAA,UAAU,4CAAmB,IAAI;AAC1C,gBAAM,OAAO,KAAK,WAAW,OAAO,MAAM;AACpCD,gBAAAA,UAAS,KAAK,QAAQ,KAAK,CAAC,MAAM,EAAE,SAAS,OAAO,SAAS;AAEnE,cAAIA,SAAQ;AACVA,oBAAO,QAAQ;AAAA,UACjB;AAAA,QACF;AACA;AAAA,MAAA,WACS,UAAU,SAAS,WAAW;AACvC,cAAM,eAAe,KAAK,UAAU,UAAU,IAAI,KAAK,KAAK;AAC5D,YAAI,cAAc;AACL,qBAAA,CAAC,KAAK,cAAc,UAAU,KAAK,aAAa,GAAG,GAAG;AACzD,kBAAA,OAAO,KAAK,WAAW,YAAY;AACnC,kBAAA,QAAQ,KAAK,OAAO,UAAU;AACpC,gBAAI,MAAM,QAAQ;AACVA,oBAAAA,WAAS,UAAK,YAAL,mBAAc;AAAA,gBAC3B,CAAC,MAAM,EAAE,SAAS,MAAM,OAAO;AAAA;AAEjC,kBAAIA,SAAQ;AACVA,wBAAO,QAAQ;AAAA,cACjB;AAAA,YACF;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAEM,YAAA,UAAS,eAAU,YAAV,mBAAmB,KAAK,CAAC,MAAM,EAAE,SAAS,IAAI;AAC7D,UAAI,QAAQ;AACV,eAAO,QAAQ;AAAA,MACjB;AAAA,IACF;AAAA,EACF;AAAA,EAEA,kBAAkB,MAAM,QAAQ,SAAS,GAAG,aAAa;;AAEvD,UAAM,eAAc,UAAK,UAAU,kBAAkB,MAAM,MAAvC,mBAA2C;AAC/D,QAAI,eAAe,KAAM;AACzB,UAAM,mBACJ,KAAK,UAAU,kBAAkB,WAAW,EAAE,OAAO;AACjD,UAAA,oBAAoB,KAAK,KAAK,QAAQ;AAAA,MAC1C,CAAC,MAAM,EAAE,SAAS;AAAA,IAAA;AAEpB,QAAI,oBAAoB,IAAI;AACpB,YAAA,gBAAgB,KAAK,WAAW,WAAW;AAC7C,UAAA,MAAM,cAAc,QAAQ;AAE9B,UAAA,MAAM,QACN,UAAK,KAAK,QAAQ,iBAAiB,EAAE,kBAArC,mBAAoD,SACpD;AAGM,cAAA;AAAA,MACR;AACA,eAASU,KAAI,GAAGA,KAAI,KAAKA,MAAK;AACvB,aAAA,KAAK,QAAQ,oBAAoBA,EAAC,EAAE,QACvC,cAAc,QAAQA,EAAC,EAAE;AAAA,MAC7B;AAAA,IACF;AACO,WAAA;AAAA,EACT;AAAA,EAEA,gBAAgB,MAAM,QAAQ,KAAK;;AAC7B,QAAA,KAAK,SAAS,UAAW;AAEvB,UAAA,QAAO,gBAAK,UAAU,UAAU,MAAM,MAA/B,mBAAmC,OAAnC,mBAAwC;AACrD,QAAI,CAAC,KAAM;AACX,UAAM,KAAK,cAAc,cAAc,IAAI;AAC3C,UAAM,aAAa,KAAK,UAAU,SAAS,MAAM,YAAY;AAC7D,UAAM,SAAS,WAAW;AACpB,UAAA,gBAAe,sCAAS,oBAAT,mBAA0B;AAC/C,QAAI,CAAC,aAAc;AAEnB,UAAM,SAAS,OAAO,WAAU,sBAAW,mBAAX,mBAA2B,WAA3B,YAAqC;AACrE,UAAM,KAAI,gBAAW,mBAAX,mBAA4B,iBAAiB;AACvD,QAAI,KAAK,KAAM;AAEf,UAAM,aAAa,OAAO,OAAO,GAAG,EAAE,CAAC;AACjC,UAAA,SAAS,KAAK,KAAK,QAAQ,KAAK,CAAC,MAAM,EAAE,SAAS,UAAU;AAClE,QAAI,QAAQ;AACV,aAAO,QAAQ;AAAA,IACjB;AAAA,EACF;AAAA,EAEA,kBAAkB;;AACZ,QAAA,CAAC,KAAK,KAAK,QAAS;AAGlB,aAAA,SAAS,GACb,SAAS,KAAK,UAAU,SAAS,MAAM,QACvC,UACA;AACA,YAAM,OAAO,KAAK,UAAU,SAAS,MAAM,MAAM;AACjD,YAAM,OAAM,UAAK,UAAU,kBAAkB,MAAM,MAAvC,YAA4C;AAClD,YAAA,UAAU,OAAO,KAAK,GAAG;AAE3B,UAAA,GAAC,UAAK,mBAAL,mBAAqB,SAAQ;AAG3B,aAAA,gBAAgB,MAAM,QAAQ,GAAG;AACtC;AAAA,MACF;AAEA,UAAI,cAAc;AAClB,eAAS,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;AACjC,cAAA,UAAU,QAAQ,CAAC;AACnB,cAAA,UAAU,IAAI,OAAO;AACrB,cAAA,cAAc,KAAK,KAAK,QAAQ;AAAA,UACpC,CAAC,MAAM,EAAE,SAAS;AAAA,QAAA;AAEpB,cAAM,aAAa,KAAK,KAAK,QAAQ,WAAW;AAE9C,YAAA,KAAK,kBAAkB,MAAM,QAAQ,SAAS,GAAG,WAAW,KAC5D,gBAAgB,IAChB;AAEA,gBAAM,eAAc,UAAK,WAAW,MAAM,EAAE,YAAxB,mBAAiC;AAAA,YACnD,CAAC,MAAM,EAAE,SAAS;AAAA;AAEL,0BAAA,sDAAa,kBAAb,mBAA4B,WAA5B,YAAsC;AAAA,QACvD;AACA,YAAI,gBAAgB,IAAI;AACtB;AAAA,QACF;AAGA,mBAAW,QAAQ,KAAK,eAAe,IAAI,WAAW;AACtD,iBAAS,IAAI,GAAG,MAAI,gBAAW,kBAAX,mBAA0B,SAAQ,KAAK;AACpD,eAAA,KAAK,QAAQ,cAAc,IAAI,CAAC,EAAE,QACrC,KAAK,eAAe,IAAI,EAAE,WAAW;AAAA,QACzC;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAAA,EAEA,aAAa,OAAO;AACd,QAAA;AACA,QAAA;AAEJ,aAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AAC/B,YAAA,OAAO,MAAM,CAAC;AACpB,UAAI,QAAQ,QAAQ,KAAK,IAAI,CAAC,IAAI,MAAM;AAC/B,eAAA,KAAK,IAAI,CAAC;AAAA,MACnB;AACA,UAAI,OAAO,QAAQ,KAAK,IAAI,CAAC,IAAI,KAAK;AAC9B,cAAA,KAAK,IAAI,CAAC;AAAA,MAClB;AAEK,WAAA,YAAY,MAAM,CAAC;AACpB,UAAA,MAAM,OAAO,IAAI;AAAA,IACvB;AAEA,SAAK,WAAW;AAChB,SAAK,KAAK,MAAM,CAAC,MAAM,GAAG;AAAA,EAC5B;AAAA,EAEA,YAAY,cAAc,QAAQ;;AAC5B,QAAA,CAAC,aAAa,QAAS;AAEhB,eAAA,UAAU,aAAa,SAAS;AACrC,UAAA,CAAC,OAAO,MAAO;AAEnB,YAAM,QAAQ,CAAC,GAAG,OAAO,KAAK;AAC9B,iBAAW,KAAK,OAAO;AACrB,cAAM,OAAO,IAAI,MAAM,MAAM,CAAC;AAC9B,YAAI,CAAC,KAAM;AAEX,cAAM,aAAa,IAAI,MAAM,YAAY,KAAK,SAAS;AACvD,cAAM,WACJ,UAAK,UAAU,kBAAkB,MAAM,MAAvC,mBAA2C,KAAK;AAClD,YAAI,WAAW,MAAM;AACnB,eAAK,KAAK,QAAQ,SAAS,YAAY,KAAK,WAAW;AAAA,QACzD;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAAA,EAEA,aAAa;;AACX,eAAW,SAAQ,UAAK,UAAU,SAAS,UAAxB,YAAiC,IAAI;AACtD,YAAM,CAAA,EAAG,YAAY,UAAU,YAAY,cAAc,IAAI;AAC7D,YAAM,aAAa,IAAI,MAAM,YAAY,cAAc;AACvD,UAAI,CAAC,WAAY;AACN,iBAAA;AAAA,QACT;AAAA,QACA,KAAK,KAAK;AAAA,QACV,KAAK,UAAU,iBAAiB,QAAQ,EAAE,UAAU;AAAA,MAAA;AAAA,IAExD;AAAA,EACF;AAAA,EAEA,OAAO,aAAa,MAAM;;AACxB,YAAQ,gBAAK,aAAL,aAAiB,UAAK,gBAAL,mBAAkB,aAAnC,mBAA+C;AAAA,EACzD;AAAA,EAEA,OAAO,YAAY,MAAM;;AACvB,WAAO,CAAC,GAAC,gBAAK,gBAAL,mBAAkB,aAAlB,mBAA6B;AAAA,EACxC;AAAA,EAEA,OAAa,UAAU,OAAO;AAAA;AAEtB,YAAA,UAAU,IAAI,iBAAiB,KAAK;AACpC,YAAA,MAAM,QAAQ;AACpB,UAAI,CAAC,IAAK;AAEJ,YAAA,EAAE,MAAM,SAAa,IAAA;AAG3B,YAAM,SAAS,IAAI,gBAAgB,MAAM,QAAQ;AACjD,YAAM,OAAO;AAEb,YAAM,YAAY,UAAU,WAAW,YAAY,IAAI,EAAE;AAE/C,gBAAA,cAAc,QAAQ,KAAK;AAC3B,gBAAA,KAAK,EAAE;AACb,UAAA,MAAM,IAAI,SAAS;AAGvB,gBAAU,KAAK,EAAE,aAAa,QAAQ,KAAK;AACpC,aAAA;AAAA,IACT;AAAA;AACF;AAEA,SAAS,2BAA2B;AACzB,WAAA,iBAAiB,SAAS,OAAO;;AACxC,UAAM,WAAW,OAAO,QAAO,SAAI,OAAO,mBAAX,YAA6B,CAAA,CAAE;AACxD,UAAA,WACJ,SAAS,SAAS,KAClB,SAAS,KAAK,CAAC,MAAM,iBAAiB,YAAY,CAAC,CAAC;AAC9C,YAAA,OAAO,QAAQ,GAAG,MAAM;AAAA,MAC9B,SAAS;AAAA,MACT;AAAA,MACA,UAAU,MAAY;AACb,eAAA,MAAM,iBAAiB,UAAU,QAAQ;AAAA,MAClD;AAAA,IAAA,CACD;AAAA,EACH;AAES,WAAA,gBAAgB,SAAS,OAAO;;AACjC,UAAA,UAAS,SAAI,MAAM,UAAV,mBAAiB;AAChC,UAAM,WAAW,CAAC,UAAU,CAAC,OAAO,KAAK,MAAM,EAAE;AACzC,YAAA,OAAO,QAAQ,GAAG,MAAM;AAAA,MAC9B,SAAS;AAAA,MACT;AAAA,MACA,UAAU,MAAM;AACV,YAAA,kBAAkB,GAAG,EAAE;MAC7B;AAAA,IAAA,CACD;AAAA,EACH;AAGM,QAAA,uBAAuB,aAAa,UAAU;AACvC,eAAA,UAAU,uBAAuB,WAAY;AACxD,UAAM,UAAU,qBAAqB,MAAM,MAAM,SAAS;AACpD,UAAA,QACJ,QAAQ,UAAU,CAAC,OAAM,uBAAG,aAAY,WAAW,IAAI,KAAK,QAAQ;AACtE,qBAAiB,SAAS,KAAK;AACf,oBAAA,SAAS,QAAQ,CAAC;AAC3B,WAAA;AAAA,EAAA;AAIH,QAAA,qBAAqB,aAAa,UAAU;AACrC,eAAA,UAAU,qBAAqB,SAAU,MAAM;AAC1D,UAAM,UAAU,mBAAmB,MAAM,MAAM,SAAS;AACxD,QAAI,CAAC,iBAAiB,YAAY,IAAI,GAAG;AACjC,YAAA,QACJ,QAAQ,UAAU,CAAC,OAAM,uBAAG,aAAY,SAAS,IAAI,KACrD,QAAQ,SAAS;AACnB,uBAAiB,SAAS,KAAK;AAAA,IACjC;AACO,WAAA;AAAA,EAAA;AAEX;AAEA,MAAMhB,OAAK;AACX,IAAI;AACJ,MAAME,QAAM;AAAA,EACV,MAAMF;AAAAA,EACN,QAAQ;AACmB;EAC3B;AAAA,EACM,qBAAqB,WAAW,kBAAkB;AAAA;;AAChD,YAAA,SAAQ,4CAAW,UAAX,mBAAkB;AAChC,UAAI,OAAO;AACH,cAAA,gBAAgB,qBAAqB,OAAO,gBAAgB;AAAA,MACpE;AAAA,IACF;AAAA;AAAA,EACA,kBAAkB,MAAM;AAET,iBAAA;AAAA,EACf;AAAA,EACA,YAAY,MAAM;AACZ,QAAA,iBAAiB,YAAY,IAAI,GAAG;AACtC,WAAK,KAAK,IAAI,IAAI,iBAAiB,IAAI;AAAA,IACzC;AAAA,EACF;AAAA,EACM,oBAAoB,MAAM;AAAA;;AAEvB,aAAA,OAAO,YAAY,IAAI;AACxB,YAAA,SAAQ,SAAI,MAAM,UAAV,mBAAiB;AAC/B,UAAI,OAAO;AACT,cAAM,gBAAgB,qBAAqB,OAAO,CAAE,CAAA;AAAA,MACtD;AAAA,IACF;AAAA;AACF;AAEA,IAAI,kBAAkBE,KAAG;;;;;AC37CzB,SAAS,YAAY,MAAM,MAAM;AAC/B,OAAK,OAAO;AACZ,OAAK,MAAM;AACb;AAEA,SAAS,gBAAgB,OAAO,QAAQ,IAAI;;AACtC,MAAA,IAAI,IAAI,IAAI;AACZ,MAAA,KAAK,KAAK,KAAK;AACf,MAAA;AAEC,OAAA,KAAK,KAAK,KAAK;AACd,QAAA,MAAM,MAAM,MAAM;AAExB,WAAS,KAAK,CAAC,MAAM,QAAQ,KAAK,GAAG;AACnC,aAAS,KAAK,GAAG;AACf,aAAO,EAAE,CAAC;AAEJ,YAAA,KAAK,IAAI,CAAC;AACV,YAAA,KAAK,IAAI,CAAC;AAChB,YAAM,KAAK,IAAI,CAAC,IAAI,KAAK,KAAK,CAAC;AAC/B,YAAM,KAAK,IAAI,CAAC,IAAI,KAAK,KAAK,CAAC;AAE3B,UAAA,KAAK,QAAQ,WAAW;AAC1B,eAAO,UAAU;AAAA,MACnB;AAEI,WAAA,UAAK,UAAL,mBAAY,WAAW;AACzB,cAAM,MAAM,UAAU;AAEtB,YAAI,6BAAM,kBAAkB;AAC1B,gBAAM,MAAM,KAAK,MAAM,KAAK,gBAAgB;AAAA,QAC9C;AAAA,MACF;AAEI,UAAA,MAAM,MAAM,MAAM,IAAI;AACnB,aAAA;AAAA,MACP;AAEI,UAAA,MAAM,MAAM,MAAM,IAAI;AACnB,aAAA;AAAA,MACP;AAEI,UAAA,MAAM,MAAM,MAAM,IAAI;AACnB,aAAA;AAAA,MACP;AAEI,UAAA,MAAM,MAAM,MAAM,IAAI;AACnB,aAAA;AAAA,MACP;AAAA,IACF;AAAA,EACF;AAEA,MAAI,UAAU;AAEd,OAAK,KAAK,KAAK,MAAM,MAAM,YAAY,GAAG;AAE1C,QAAM,MAAM,CAAC,KAAK,SAAS,KAAK,OAAO;AACjC,QAAA,OAAO,CAAC,KAAK,KAAK,UAAU,GAAG,KAAK,KAAK,UAAU,CAAC;AAC5D;AAEA,IAAI,kBAAkB;AAAA,EACpB,MAAM;AAAA,EACN,QAAQ;AACA,UAAA,OAAO,aAAa,UAAU;AAEvB,iBAAA,UAAU,uBAAuB,WAAY;AACxD,YAAM,UAAU,KAAK,MAAM,MAAM,SAAS;AACpC,YAAA,QAAQ,KAAK,MAAM;AAAA,QACvB,KAAK,YAAY,CAAC;AAAA,QAClB,KAAK,YAAY,CAAC;AAAA,MAAA;AAEpB,UAAI,CAAC,OAAO;AACV,gBAAQ,KAAK;AAAA,UACX,SAAS;AAAA,UACT,UAAU,CAAC,OAAO,KAAK,IAAI,OAAO,kBAAkB,CAAE,CAAA,EAAE;AAAA,UACxD,UAAU,MAAM;AAEVe,gBAAAA,SAAQ,IAAI,UAAU;AACVA,4BAAAA,QAAO,KAAK,cAAc;AACtC,gBAAA,OAAO,MAAM,IAAIA,MAAK;AAC1B,iBAAK,MAAM;UACb;AAAA,QAAA,CACD;AAEM,eAAA;AAAA,MACT;AAGA,YAAM,qBAAqB;AAC3B,YAAM,eAAe,MAAM;AAE3B,cAAQ,KAAK;AAAA,QACX,SAAS;AAAA,QACT,UAAU,CAAC,OAAO,KAAK,IAAI,OAAO,kBAAkB,CAAE,CAAA,EAAE;AAAA,QACxD,UAAU,MAAM;AACE,0BAAA,OAAO,KAAK,cAAc;AAC1C,eAAK,MAAM;QACb;AAAA,MAAA,CACD;AAGG,UAAA,aAAa,WAAW,GAAG;AACtB,eAAA;AAAA,MAAA,OACF;AAEL,gBAAQ,KAAK,IAAI;AAAA,MACnB;AAGA,UAAI,sBAAsB;AAC1B,eAAS,IAAI,GAAG,IAAI,aAAa,QAAQ,KAAK;AAC5C,YAAI,aAAa,CAAC,EAAE,SAAS,aAAa,CAAC,EAAE,MAAM;AAC3B,gCAAA;AACtB;AAAA,QACF;AAAA,MACF;AAEA,cAAQ,KAAK;AAAA,QACX,SAAS;AAAA,QACT,UAAU,MAAM;AACd,0BAAgB,KAAK;AACrB,eAAK,MAAM;QACb;AAAA,MAAA,CACD;AAED,cAAQ,KAAK;AAAA,QACX,SAAS;AAAA,QACT,UAAU,MAAM;AACd,eAAK,YAAY,YAAY;AAC7B,eAAK,MAAM;AACX,eAAK,OAAO;QACd;AAAA,MAAA,CACD;AASD,UAAI,qBAAqB;AACjB,cAAA,OAAO,aAAa,CAAC,EAAE;AAC7B,gBAAQ,MAAM;AAAA,UACZ,KAAK;AAEH,oBAAQ,KAAK;AAAA,cACX,SAAS;AAAA,cACT,UAAU,MAAM;AACd,2BAAW,QAAQ,cAAc;AAC/B,8BAAY,MAAM,CAAC;AAAA,gBACrB;AAAA,cACF;AAAA,YAAA,CACD;AACD,oBAAQ,KAAK;AAAA,cACX,SAAS;AAAA,cACT,UAAU,MAAM;AACd,2BAAW,QAAQ,cAAc;AAC/B,8BAAY,MAAM,CAAC;AAAA,gBACrB;AAAA,cACF;AAAA,YAAA,CACD;AACD;AAAA,UACF,KAAK;AAEH,oBAAQ,KAAK;AAAA,cACX,SAAS;AAAA,cACT,UAAU,MAAM;AACd,2BAAW,QAAQ,cAAc;AAC/B,8BAAY,MAAM,CAAC;AAAA,gBACrB;AAAA,cACF;AAAA,YAAA,CACD;AACD,oBAAQ,KAAK;AAAA,cACX,SAAS;AAAA,cACT,UAAU,MAAM;AACd,2BAAW,QAAQ,cAAc;AAC/B,8BAAY,MAAM,CAAC;AAAA,gBACrB;AAAA,cACF;AAAA,YAAA,CACD;AACD;AAAA,UACF,KAAK;AAEH,oBAAQ,KAAK;AAAA,cACX,SAAS;AAAA,cACT,UAAU,MAAM;AACd,2BAAW,QAAQ,cAAc;AAC/B,8BAAY,MAAM,CAAC;AAAA,gBACrB;AAAA,cACF;AAAA,YAAA,CACD;AACD,oBAAQ,KAAK;AAAA,cACX,SAAS;AAAA,cACT,UAAU,MAAM;AACd,2BAAW,QAAQ,cAAc;AAC/B,8BAAY,MAAM,CAAC;AAAA,gBACrB;AAAA,cACF;AAAA,YAAA,CACD;AACD;AAAA,UACF;AAEE,oBAAQ,KAAK;AAAA,cACX,SAAS;AAAA,cACT,UAAU,MAAM;AACd,2BAAW,QAAQ,cAAc;AAC/B,8BAAY,MAAM,CAAC;AAAA,gBACrB;AAAA,cACF;AAAA,YAAA,CACD;AACD,oBAAQ,KAAK;AAAA,cACX,SAAS;AAAA,cACT,UAAU,MAAM;AACd,2BAAW,QAAQ,cAAc;AAC/B,8BAAY,MAAM,CAAC;AAAA,gBACrB;AAAA,cACF;AAAA,YAAA,CACD;AACD,oBAAQ,KAAK;AAAA,cACX,SAAS;AAAA,cACT,UAAU,MAAM;AACd,2BAAW,QAAQ,cAAc;AAC/B,8BAAY,MAAM,CAAC;AAAA,gBACrB;AAAA,cACF;AAAA,YAAA,CACD;AACD;AAAA,QACJ;AAAA,MAAA,OACK;AAEL,gBAAQ,KAAK;AAAA,UACX,SAAS;AAAA,UACT,UAAU,MAAM;AACd,uBAAW,QAAQ,cAAc;AAC/B,0BAAY,MAAM,CAAC;AAAA,YACrB;AAAA,UACF;AAAA,QAAA,CACD;AACD,gBAAQ,KAAK;AAAA,UACX,SAAS;AAAA,UACT,UAAU,MAAM;AACd,uBAAW,QAAQ,cAAc;AAC/B,0BAAY,MAAM,CAAC;AAAA,YACrB;AAAA,UACF;AAAA,QAAA,CACD;AACD,gBAAQ,KAAK;AAAA,UACX,SAAS;AAAA,UACT,UAAU,MAAM;AACd,uBAAW,QAAQ,cAAc;AAC/B,0BAAY,MAAM,CAAC;AAAA,YACrB;AAAA,UACF;AAAA,QAAA,CACD;AAAA,MACH;AAEO,aAAA;AAAA,IAAA;AAAA,EAEX;AACF,CAAC;AClQD,MAAMjB,OAAK;AACX,IAAI,kBAAkB;AAAA,EACpB,MAAMA;AAAAA,EACN,OAAO;AACL,UAAM,UAAU,UAAU;AAC1B,UAAM,UAAU,MAAM;AAEV,gBAAA,cAAc,SAAU,QAAQ,SAAS;AACjD,kBAAU,WAAW;AACrB,YAAI,QAAQ,cAAc;AACxB,kBAAQ,gBAAgB;AAAA,QAAA,OACnB;AACL,kBAAQ,eAAe;AAAA,QACzB;AACA,eAAO,QAAQ,KAAK,MAAM,QAAQ,OAAO;AAAA,MAAA;AAEjC,gBAAA,YAAY,YAAY,QAAQ;AAAA,IAAA;AAExC,QAAA,GAAG,SAAS,WAAW;AAAA,MAAA,IACzBA;AAAAA,MACA,MAAM;AAAA,MACN,MAAM;AAAA,MACN,cAAc;AAAA,MACd,SAAS,OAAO;AACd,YAAI,OAAO;AACD;QAAA,OACH;AACL,oBAAU,cAAc;AAAA,QAC1B;AAAA,MACF;AAAA,IAAA,CACD;AAAA,EACH;AACF,CAAC;AClCD,IAAI,kBAAkB;AAAA,EACpB,MAAM;AAAA,EACN,OAAO;AACC,UAAA,kBAAkB,SAAU,OAAO;AACjC,YAAA,kBAAkB,MAAM,WAAW,MAAM;AAG3C,UAAA,mBAAmB,MAAM,QAAQ,SAAS;AAE5C,YAAI,MAAM,QAAQ;AAChB,cAAI,UAAU;AACd;AAAA,QACF;AAEA,YAAI,YAAY,MAAM,WAAW,KAAK,CAAC,EAAE;AACzC;AAAA,MACF;AAEA,YAAM,SAAS,MAAM,aAAa,EAAE,CAAC;AACrC,UAAI,CAAC,SAAS,UAAU,EAAE,SAAS,OAAO,OAAO,GAAG;AAClD;AAAA,MACF;AAEA,YAAM,mBAAmB;AAAA,QACvB,GAAG;AAAA,QACH,GAAG;AAAA,QACH,WAAW;AAAA,QACX,GAAG;AAAA,MAAA;AAGC,YAAA,oBAAoB,iBAAiB,MAAM,GAAG;AACpD,UAAI,mBAAmB,mBAAmB;AACxC,cAAM,eAAe;AAEf,cAAA,OAAO,SAAS,cAAc,iBAAiB;AACrD,aAAK,MAAM;AACX;AAAA,MACF;AAGA,UAAI,MAAM,WAAW,MAAM,UAAU,MAAM,SAAS;AAClD;AAAA,MACF;AAGI,UAAA,MAAM,QAAQ,UAAU;AACpB,cAAA,SAAS,SAAS,iBAA8B,cAAc;AACpE,cAAM,QAAQ,MAAM,KAAK,MAAM,EAAE;AAAA,UAC/B,CAACkB,WACC,OAAO,iBAAiBA,MAAK,EAAE,iBAAiB,SAAS,MACzD;AAAA,QAAA;AAEJ,YAAI,OAAO;AACT,gBAAM,MAAM,UAAU;AAAA,QACxB;AAEA;AAAE,SAAA,GAAG,SAAS,iBAAiB,QAAQ,CAAC,EAAE,QAAQ,CAAC,MAAM;AACvD,YAAE,MAAM;AAAA,QAAA,CACT;AAAA,MACH;AAEA,YAAM,WAAW;AAAA,QACf,GAAG;AAAA,QACH,GAAG;AAAA,QACH,GAAG;AAAA,MAAA;AAGC,YAAA,WAAW,SAAS,MAAM,GAAG;AACnC,UAAI,UAAU;AACN,cAAA,SAAS,SAAS,cAAc,QAAQ;AAC9C,eAAO,MAAM;AAAA,MACf;AAAA,IAAA;AAGK,WAAA,iBAAiB,WAAW,iBAAiB,IAAI;AAAA,EAC1D;AACF,CAAC;AC7ED,MAAMlB,OAAK;AACX,MAAM,MAAM;AAAA,EACV,MAAMA;AAAAA,EACA,MAAMD,MAAK;AAAA;AACfA,WAAI,GAAG,SAAS,WAAW;AAAA,QAAA,IACzBC;AAAAA,QACA,MAAM;AAAA,QACN,cAAc;AAAA,QACd,MAAM;AAAA;AAAA,QAEN,SAAS,CAAC,GAAG,UAAU,mBAAmB,QAAQ,EAAE,IAAI,CAAC,GAAG,OAAO;AAAA,UACjE,OAAO;AAAA,UACP,MAAM;AAAA,UACN,UAAU,KAAKD,KAAI,OAAO;AAAA,QAAA,EAC1B;AAAA,QACF,SAAS,OAAO;AACdA,eAAI,OAAO,oBAAoB,CAAC;AAChCA,eAAI,MAAM,eAAe,IAAI;AAAA,QAC/B;AAAA,MAAA,CACD;AAAA,IACH;AAAA;AACF;AAEA,IAAI,kBAAkB,GAAG;AClBzB,SAAS,cAAc,SAAS;AACxB,QAAA,QAAQ,QAAQ,MAAM,UAAU;AACtC,QAAM,cAAc,MAAM,CAAC,EAAE,MAAM,GAAG,EAAE,CAAC;AACzC,QAAM,aAAa,KAAK,MAAM,CAAC,CAAC;AAChC,QAAM,cAAc,IAAI,YAAY,WAAW,MAAM;AAC/C,QAAA,aAAa,IAAI,WAAW,WAAW;AAC7C,WAAS,IAAI,GAAG,IAAI,WAAW,QAAQ,KAAK;AAC1C,eAAW,CAAC,IAAI,WAAW,WAAW,CAAC;AAAA,EACzC;AACO,SAAA,IAAI,KAAK,CAAC,WAAW,GAAG,EAAE,MAAM,aAAa;AACtD;AAEA,SAAS,kBAAkB,OAAO;AAC1B,QAAA,SAAS,SAAS,cAAc,QAAQ;AAE9C,SAAO,QAAQ,MAAM;AACrB,SAAO,SAAS,MAAM;AAEhB,QAAA,MAAM,OAAO,WAAW,IAAI;AAE9B,MAAA,UAAU,OAAO,GAAG,CAAC;AAEzB,QAAM,UAAU,OAAO,UAAU,aAAa,CAAC;AACzC,QAAA,OAAO,cAAc,OAAO;AAE3B,SAAA;AACT;AAEA,SAAS,UAAU,WAAW;AAC5B,SAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AAChC,UAAA,QAAQ,IAAI;AAElB,UAAM,SAAS,WAAY;AACzB,cAAQ,KAAK;AAAA,IAAA;AAGf,UAAM,MAAM;AAAA,EAAA,CACb;AACH;AAEA,SAAe,WAAW,UAAU,UAAU;AAAA;AACtC,UAAA,IACH,SAAS,gBAAgB;AAAA,MACxB,QAAQ;AAAA,MACR,MAAM;AAAA,IAAA,CACP,EACA,KAAK,CAAC,aAAa;AAAA,IAAA,CAAE,EACrB,MAAM,CAAC,UAAU;AACR,cAAA,MAAM,UAAU,KAAK;AAAA,IAAA,CAC9B;AAEM,aAAA,UAAU,KAAK,SAAS,UAAU,eAAe,CAAC,IAAI,IAAI;AAC1D,aAAA,UAAU,KAAK,SAAS,UAAU,eAAe,CAAC,EAAE,MAAM,IAAI;AAAA,MACrE,WACE,IAAI,gBAAgB,QAAQ,EAAE,aAC9B,IAAI,sBAAA,IACJ,IAAI,aAAa;AAAA,IAAA;AAGrB,QAAI,SAAS,UAAU;AACrB,eAAS,UAAU,OAAO,SAAS,UAAU,eAAe,CAAC,IAAI;AAEnE,oBAAgB,kBAAkB;AAAA,EACpC;AAAA;AAEA,SAAS,aAAa,OAAO,YAAY,SAAS,WAAW;AAE3D,UAAQ,UAAU,OAAO,GAAG,GAAG,WAAW,OAAO,WAAW,MAAM;AAClE,QAAM,WAAW,QAAQ;AAAA,IACvB;AAAA,IACA;AAAA,IACA,WAAW;AAAA,IACX,WAAW;AAAA,EAAA;AAIb,WAAS,IAAI,GAAG,IAAI,SAAS,KAAK,QAAQ,KAAK,GAAG;AAC5C,QAAA,SAAS,KAAK,IAAI,CAAC,KAAK,IAAc,UAAA,KAAK,IAAI,CAAC,IAAI;AAAA,QAC1C,UAAA,KAAK,IAAI,CAAC,IAAI;AAEnB,aAAA,KAAK,CAAC,IAAI,UAAU;AAC7B,aAAS,KAAK,IAAI,CAAC,IAAI,UAAU;AACjC,aAAS,KAAK,IAAI,CAAC,IAAI,UAAU;AAAA,EACnC;AAEA,UAAQ,2BAA2B;AAC3B,UAAA,aAAa,UAAU,GAAG,CAAC;AACrC;AAEA,MAAM,oBAAN,MAAM,0BAAyB,YAAY;AAAA,EAqCzC,cAAc;AACN;AAjCR;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAUA,6CAAoB;AA4gBpB,yCAAgB;AAChB,sCAAa;AACb,4CAAmB;AACnB,wCAAe;AACf,iCAAQ;AACR,iCAAQ;AACR,oCAAW;AA9gBT,SAAK,UAAU,IAAI,mBAAmB,EAAE,QAAQ,SAAS,QAAQ;AAAA,MAC/D,IAAI,2BAA2B,CAAC,GAAG,KAAK,cAAe,CAAA,CAAC;AAAA,IAAA,CACzD;AAAA,EACH;AAAA,EAfA,OAAO,cAAc;AACf,QAAA,CAAC,kBAAiB,UAAU;AACb,wBAAA,WAAW,IAAI;IAClC;AAEA,WAAO,kBAAiB;AAAA,EAC1B;AAAA,EAWA,gBAAgB;AACd,WAAO;EACT;AAAA,EAEA,aAAa,MAAM,UAA6B;AAC1C,QAAA,SAAS,SAAS,cAAc,QAAQ;AAC5C,WAAO,MAAM,gBAAgB;AAC7B,WAAO,YAAY;AACZ,WAAA,iBAAiB,SAAS,QAAQ;AAClC,WAAA;AAAA,EACT;AAAA,EAEA,iBAAiB,MAAM,UAAU;AAC/B,QAAI,SAAS,KAAK,aAAa,MAAM,QAAQ;AAC7C,WAAO,MAAM,WAAW;AACxB,WAAO,MAAM,cAAc;AACpB,WAAA;AAAA,EACT;AAAA,EAEA,kBAAkB,MAAM,UAAU;AAChC,QAAI,SAAS,KAAK,aAAa,MAAM,QAAQ;AAC7C,WAAO,MAAM,WAAW;AACxB,WAAO,MAAM,aAAa;AACnB,WAAA;AAAA,EACT;AAAA,EAEA,iBAAiB,MAAM,MAAM,UAA0B;AAC/C,UAAA,aAAa,SAAS,cAAc,KAAK;AAC/C,eAAW,KAAK;AAChB,eAAW,MAAM,WAAW;AAC5B,eAAW,MAAM,aAAa;AAC9B,eAAW,MAAM,cAAc;AAC/B,eAAW,MAAM,QAAQ;AACzB,eAAW,MAAM,kBAAkB;AACnC,eAAW,MAAM,eAAe;AAChC,eAAW,MAAM,cAAc;AAC/B,eAAW,MAAM,cAAc;AAC/B,eAAW,MAAM,WAAW;AAC5B,eAAW,MAAM,SAAS;AAC1B,eAAW,MAAM,UAAU;AAC3B,eAAW,MAAM,UAAU;AAC3B,eAAW,MAAM,WAAW;AAC5B,eAAW,MAAM,MAAM;AACvB,eAAW,MAAM,gBAAgB;AAC5B,SAAA,qBAAqB,SAAS,cAAc,OAAO;AACnD,SAAA,mBAAmB,aAAa,QAAQ,OAAO;AAC/C,SAAA,mBAAmB,aAAa,OAAO,GAAG;AAC1C,SAAA,mBAAmB,aAAa,OAAO,KAAK;AAC5C,SAAA,mBAAmB,aAAa,SAAS,IAAI;AAC5C,UAAA,eAAe,SAAS,cAAc,OAAO;AACnD,iBAAa,cAAc;AAE3B,eAAW,YAAY,YAAY;AACxB,eAAA,YAAY,KAAK,kBAAkB;AAEzC,SAAA,mBAAmB,iBAAiB,UAAU,QAAQ;AAEpD,WAAA;AAAA,EACT;AAAA,EAEA,oBAAoB,MAAM,MAAM,UAA0B;AAClD,UAAA,aAAa,SAAS,cAAc,KAAK;AAC/C,eAAW,KAAK;AAChB,eAAW,MAAM,WAAW;AAC5B,eAAW,MAAM,aAAa;AAC9B,eAAW,MAAM,cAAc;AAC/B,eAAW,MAAM,QAAQ;AACzB,eAAW,MAAM,kBAAkB;AACnC,eAAW,MAAM,eAAe;AAChC,eAAW,MAAM,cAAc;AAC/B,eAAW,MAAM,cAAc;AAC/B,eAAW,MAAM,WAAW;AAC5B,eAAW,MAAM,SAAS;AAC1B,eAAW,MAAM,UAAU;AAC3B,eAAW,MAAM,UAAU;AAC3B,eAAW,MAAM,WAAW;AAC5B,eAAW,MAAM,MAAM;AACvB,eAAW,MAAM,gBAAgB;AAC5B,SAAA,uBAAuB,SAAS,cAAc,OAAO;AACrD,SAAA,qBAAqB,aAAa,QAAQ,OAAO;AACjD,SAAA,qBAAqB,aAAa,OAAO,KAAK;AAC9C,SAAA,qBAAqB,aAAa,OAAO,KAAK;AAC9C,SAAA,qBAAqB,aAAa,QAAQ,MAAM;AAChD,SAAA,qBAAqB,aAAa,SAAS,KAAK;AAC/C,UAAA,eAAe,SAAS,cAAc,OAAO;AACnD,iBAAa,cAAc;AAE3B,eAAW,YAAY,YAAY;AACxB,eAAA,YAAY,KAAK,oBAAoB;AAE3C,SAAA,qBAAqB,iBAAiB,SAAS,QAAQ;AAErD,WAAA;AAAA,EACT;AAAA,EAEA,UAAU,WAA8B,YAA+B;AACrE,UAAM,OAAO;AAIT,QAAA,eAAe,SAAS,cAAc,KAAK;AAC/C,iBAAa,MAAM,WAAW;AAC9B,iBAAa,MAAM,SAAS;AAC5B,iBAAa,MAAM,OAAO;AAC1B,iBAAa,MAAM,QAAQ;AAC3B,iBAAa,MAAM,SAAS;AAC5B,iBAAa,MAAM,gBAAgB;AAE/B,QAAA,QAAQ,SAAS,cAAc,KAAK;AACxC,UAAM,KAAK;AACX,UAAM,MAAM,kBAAkB;AAC9B,UAAM,MAAM,UAAU;AACtB,UAAM,MAAM,YAAY;AACxB,UAAM,MAAM,eAAe;AAE3B,UAAM,MAAM,kBAAkB;AAE9B,UAAM,MAAM,qBAAqB;AACjC,UAAM,MAAM,WAAW;AACvB,UAAM,MAAM,SAAS;AACrB,UAAM,MAAM,gBAAgB;AAC5B,SAAK,QAAQ;AACR,SAAA,QAAQ,YAAY,SAAS;AAC7B,SAAA,QAAQ,YAAY,UAAU;AAC9B,SAAA,QAAQ,YAAY,YAAY;AAC5B,aAAA,KAAK,YAAY,KAAK;AAE/B,QAAI,cAAc,KAAK,iBAAiB,SAAS,MAAM;AACrD,WAAK,QAAQ;AAAA,QACX;AAAA,QACA;AAAA,QACA,KAAK,WAAW;AAAA,QAChB,KAAK,WAAW;AAAA,MAAA;AAAA,IAClB,CACD;AAED,SAAK,oBAAoB,KAAK;AAAA,MAC5B;AAAA,MACA;AAAA,MACA,CAAC,UAAU;AACJ,aAAA,aAAa,MAAM,OAAO;AAC/B,aAAK,mBAAmB,IAAI;AAAA,MAC9B;AAAA,IAAA;AAGF,SAAK,uBAAuB,KAAK;AAAA,MAC/B;AAAA,MACA;AAAA,MACA,CAAC,UAAU;AACJ,aAAA,gBAAgB,MAAM,OAAO;AAC9B,YAAA,KAAK,qBAAqB,YAAY;AACxC,eAAK,WAAW,MAAM,UAAU,KAAK,cAAc;QACrD;AAAA,MACF;AAAA,IAAA;AAGF,SAAK,cAAc,KAAK,iBAAiB,KAAK,mBAAA,GAAsB,MAAM;AACpE,UAAA,KAAK,qBAAqB,SAAS;AACrC,aAAK,mBAAmB;AAAA,MAAA,WACf,KAAK,qBAAqB,SAAS;AAC5C,aAAK,mBAAmB;AAAA,MAAA,OACnB;AACL,aAAK,mBAAmB;AAAA,MAC1B;AAEA,WAAK,gCAAgC;AAAA,IAAA,CACtC;AAED,QAAI,eAAe,KAAK,kBAAkB,UAAU,MAAM;AAC/C,eAAA,oBAAoB,WAAW,kBAAiB,aAAa;AACtE,WAAK,MAAM;AAAA,IAAA,CACZ;AAED,SAAK,aAAa,KAAK,kBAAkB,QAAQ,MAAM;AAC5C,eAAA,oBAAoB,WAAW,kBAAiB,aAAa;AACtE,WAAK,KAAK;AAAA,IAAA,CACX;AAEI,SAAA,QAAQ,YAAY,SAAS;AAC7B,SAAA,QAAQ,YAAY,UAAU;AAC9B,SAAA,QAAQ,YAAY,YAAY;AAErC,iBAAa,YAAY,WAAW;AACvB,iBAAA,YAAY,KAAK,UAAU;AACxC,iBAAa,YAAY,YAAY;AACxB,iBAAA,YAAY,KAAK,iBAAiB;AAClC,iBAAA,YAAY,KAAK,oBAAoB;AACrC,iBAAA,YAAY,KAAK,WAAW;AAEzC,cAAU,MAAM,WAAW;AAC3B,eAAW,MAAM,WAAW;AAE5B,cAAU,MAAM,MAAM;AACtB,cAAU,MAAM,OAAO;AAEZ,eAAA,MAAM,MAAM,UAAU,MAAM;AAC5B,eAAA,MAAM,OAAO,UAAU,MAAM;AAElC,UAAA,kBAAkB,KAAK;AAClB,eAAA,MAAM,eAAe,gBAAgB;AAChD,eAAW,MAAM,UAAU,gBAAgB,QAAQ,SAAS;AAAA,EAC9D;AAAA,EAEM,OAAO;AAAA;AACX,WAAK,aAAa;AAClB,WAAK,QAAQ;AACb,WAAK,QAAQ;AAET,UAAA,CAAC,KAAK,mBAAmB;AAErB,cAAA,YAAY,SAAS,cAAc,QAAQ;AAC3C,cAAA,aAAa,SAAS,cAAc,QAAQ;AAElD,kBAAU,KAAK;AACf,mBAAW,KAAK;AAEX,aAAA,UAAU,WAAW,UAAU;AAGpC,aAAK,YAAY;AACjB,aAAK,aAAa;AAClB,aAAK,UAAU,WAAW,WAAW,MAAM,EAAE,oBAAoB,MAAM;AAEvE,aAAK,gBAAgB,UAAU;AAE/B,aAAK,oBAAoB;AAGzB,cAAM,OAAO;AACb,cAAM,WAAW,IAAI,iBAAiB,SAAU,WAAW;AAC/C,oBAAA,QAAQ,SAAU,UAAU;AACpC,gBACE,SAAS,SAAS,gBAClB,SAAS,kBAAkB,SAC3B;AAEE,kBAAA,KAAK,sBACL,KAAK,sBAAsB,UAC3B,KAAK,QAAQ,MAAM,WAAW,QAC9B;AACK,qBAAA,MAAM,MAAM,UAAU;AAC3B,yBAAS,wBAAwB;AAAA,cACnC;AAEK,mBAAA,qBAAqB,KAAK,QAAQ,MAAM;AAAA,YAC/C;AAAA,UAAA,CACD;AAAA,QAAA,CACF;AAEK,cAAA,SAAS,EAAE,YAAY;AACpB,iBAAA,QAAQ,KAAK,SAAS,MAAM;AAAA,MACvC;AAGS,eAAA,iBAAiB,WAAW,kBAAiB,aAAa;AAEnE,UAAI,SAAS,uBAAuB;AAClC,aAAK,WAAW,YAAY;AAAA,MAAA,OACvB;AACL,aAAK,WAAW,YAAY;AAAA,MAC9B;AACA,WAAK,WAAW,WAAW;AAEtB,WAAA,QAAQ,MAAM,UAAU;AACxB,WAAA,QAAQ,MAAM,QAAQ;AACtB,WAAA,QAAQ,MAAM,SAAS;AACvB,WAAA,QAAQ,MAAM,SAAS;AACvB,WAAA,QAAQ,MAAM,MAAM;AACpB,WAAA,QAAQ,MAAM,OAAO;AACrB,WAAA,QAAQ,MAAM,SAAS;AAEtB,YAAA,KAAK,UAAU,KAAK,SAAS;AAEnC,WAAK,aAAa;AAAA,IACpB;AAAA;AAAA,EAEA,WAAW;AACF,WAAA,KAAK,QAAQ,MAAM,WAAW;AAAA,EACvC;AAAA,EAEA,iBAAiB,YAAY,YAAY;AAClC,SAAA,UAAU,QAAQ,WAAW;AAC7B,SAAA,UAAU,SAAS,WAAW;AAE9B,SAAA,WAAW,QAAQ,WAAW;AAC9B,SAAA,WAAW,SAAS,WAAW;AAEhC,QAAA,SAAS,KAAK,UAAU,WAAW,MAAM,EAAE,oBAAoB,MAAM;AACzE,QAAI,UAAU,KAAK,WAAW,WAAW,MAAM;AAAA,MAC7C,oBAAoB;AAAA,IAAA,CACrB;AAED,WAAO,UAAU,YAAY,GAAG,GAAG,WAAW,OAAO,WAAW,MAAM;AACtE,iBAAa,YAAY,KAAK,YAAY,SAAS,KAAK,cAAc;AAAA,EACxE;AAAA,EAEM,UAAU,WAAW;AAAA;AACzB,UAAI,OAAO;AAEX,YAAM,SAAS,UAAU,WAAW,MAAM,EAAE,oBAAoB,MAAM;AACtE,YAAM,UAAU,KAAK;AACrB,YAAM,aAAa,KAAK;AAEjB,aAAA,UAAU,GAAG,GAAG,KAAK,UAAU,OAAO,KAAK,UAAU,MAAM;AAC1D,cAAA,UAAU,GAAG,GAAG,KAAK,WAAW,OAAO,KAAK,WAAW,MAAM;AAG/D,YAAA,WAAW,SAAS,UAAU;AAEpC,YAAM,YAAY,IAAI;AAAA,QACpB,SAAS,UAAU,KAAK,SAAS,UAAU,eAAe,CAAC,EAAE;AAAA,MAAA;AAErD,gBAAA,aAAa,OAAO,SAAS;AAC7B,gBAAA,aAAa,OAAO,SAAS;AAC7B,gBAAA,aAAa,IAAI,WAAW,GAAG;AACrC,UAAA,aAAa,MAAM,UAAU,SAAS;AAG1C,YAAM,UAAU,IAAI;AAAA,QAClB,SAAS,UAAU,KAAK,SAAS,UAAU,eAAe,CAAC,EAAE;AAAA,MAAA;AAEvD,cAAA,aAAa,OAAO,SAAS;AAC7B,cAAA,aAAa,IAAI,WAAW,KAAK;AACpC,WAAA,QAAQ,IAAI;AACZ,WAAA,MAAM,SAAS,WAAY;AACnB,mBAAA,QAAQ,KAAK,MAAM;AACnB,mBAAA,SAAS,KAAK,MAAM;AAE1B,aAAA,iBAAiB,KAAK,OAAO,UAAU;AAC5C,aAAK,wBAAwB;AAAA,MAAA;AAE1B,WAAA,MAAM,MAAM,QAAQ,SAAS;AAAA,IACpC;AAAA;AAAA,EAEA,0BAA0B;AAEpB,QAAA,YAAY,KAAK,MAAM;AACvB,QAAA,aAAa,KAAK,MAAM;AAExB,QAAA,QAAQ,KAAK,QAAQ;AACrB,QAAA,SAAS,KAAK,QAAQ;AAEtB,QAAA,KAAK,MAAM,QAAQ,OAAO;AAChB,kBAAA;AACZ,mBAAc,YAAY,KAAK,MAAM,QAAS,KAAK,MAAM;AAAA,IAC3D;AAEA,QAAI,aAAa,QAAQ;AACV,mBAAA;AACb,kBAAa,aAAa,KAAK,MAAM,SAAU,KAAK,MAAM;AAAA,IAC5D;AAEK,SAAA,aAAa,YAAY,KAAK,MAAM;AAEnC,UAAA,WAAW,QAAQ,aAAa;AAChC,UAAA,WAAW,SAAS,cAAc;AACxC,SAAK,QAAQ;AACb,SAAK,QAAQ;AAEb,SAAK,kBAAkB;AAAA,EACzB;AAAA,EAEA,oBAAoB;AAClB,QAAI,YAAY,KAAK,MAAM,QAAQ,KAAK;AACxC,QAAI,aAAa,KAAK,MAAM,SAAS,KAAK;AAEtC,QAAA,KAAK,QAAQ,YAAY,IAAI;AAC/B,WAAK,QAAQ,KAAK;AAAA,IACpB;AAEI,QAAA,KAAK,QAAQ,aAAa,IAAI;AAChC,WAAK,QAAQ,KAAK;AAAA,IACpB;AAEI,QAAA,QAAQ,GAAG,SAAS;AACpB,QAAA,SAAS,GAAG,UAAU;AAEtB,QAAA,OAAO,GAAG,KAAK,KAAK;AACpB,QAAA,MAAM,GAAG,KAAK,KAAK;AAElB,SAAA,WAAW,MAAM,QAAQ;AACzB,SAAA,WAAW,MAAM,SAAS;AAC1B,SAAA,WAAW,MAAM,OAAO;AACxB,SAAA,WAAW,MAAM,MAAM;AAEvB,SAAA,UAAU,MAAM,QAAQ;AACxB,SAAA,UAAU,MAAM,SAAS;AACzB,SAAA,UAAU,MAAM,OAAO;AACvB,SAAA,UAAU,MAAM,MAAM;AAAA,EAC7B;AAAA,EAEA,gBAAgB,YAAY;AAC1B,UAAM,OAAO;AAET,QAAA,CAAC,KAAK,oBAAoB;AACjB,iBAAA,iBAAiB,eAAe,CAAC,UAAU;AACpD,cAAM,eAAe;AAAA,MAAA,CACtB;AAED,WAAK,QAAQ;AAAA,QAAiB;AAAA,QAAS,CAAC,UACtC,KAAK,iBAAiB,MAAM,KAAK;AAAA,MAAA;AAEnC,WAAK,QAAQ;AAAA,QAAiB;AAAA,QAAe,CAAC,UAC5C,KAAK,eAAe,MAAM,KAAK;AAAA,MAAA;AAEjC,WAAK,QAAQ;AAAA,QAAiB;AAAA,QAAa,CAAC,UAC1C,KAAK,eAAe,MAAM,KAAK;AAAA,MAAA;AAGjC,WAAK,QAAQ,iBAAiB,aAAa,CAAC,UAAU;AACpD,YAAI,MAAM,SAAS;AACjB,gBAAM,eAAe;AAAA,QACvB;AAAA,MAAA,CACD;AAEU,iBAAA;AAAA,QAAiB;AAAA,QAAe,CAAC,UAC1C,KAAK,kBAAkB,MAAM,KAAK;AAAA,MAAA;AAEzB,iBAAA;AAAA,QAAiB;AAAA,QAAe,CAAC,UAC1C,KAAK,UAAU,MAAM,KAAK;AAAA,MAAA;AAEjB,iBAAA;AAAA,QAAiB;AAAA,QAAa,CAAC,UACxC,KAAK,UAAU,MAAM,KAAK;AAAA,MAAA;AAEjB,iBAAA,iBAAiB,eAAe,CAAC,UAAU;AAC/C,aAAA,MAAM,MAAM,UAAU;AAAA,MAAA,CAC5B;AACU,iBAAA,iBAAiB,gBAAgB,CAAC,UAAU;AAChD,aAAA,MAAM,MAAM,UAAU;AAAA,MAAA,CAC5B;AAEQ,eAAA,iBAAiB,aAAa,kBAAiB,eAAe;AAEvE,WAAK,qBAAqB;AAAA,IAC5B;AAAA,EACF;AAAA,EAEA,qBAAqB;AACf,QAAA,KAAK,qBAAqB,YAAY;AACjC,aAAA;AAAA,QACL,cAAc;AAAA,QACd,SAAS;AAAA,MAAA;AAAA,IACX,OACK;AACE,aAAA;AAAA,QACL,cAAc;AAAA,QACd,SAAS,KAAK;AAAA,MAAA;AAAA,IAElB;AAAA,EACF;AAAA,EAEA,eAAe;AACT,QAAA,KAAK,qBAAqB,SAAS;AACrC,aAAO,EAAE,GAAG,GAAG,GAAG,GAAG,GAAG;IAC1B;AACI,QAAA,KAAK,qBAAqB,SAAS;AACrC,aAAO,EAAE,GAAG,KAAK,GAAG,KAAK,GAAG;IAC9B;AACI,QAAA,KAAK,qBAAqB,YAAY;AAExC,aAAO,EAAE,GAAG,KAAK,GAAG,KAAK,GAAG;IAC9B;AAEA,WAAO,EAAE,GAAG,GAAG,GAAG,GAAG,GAAG;EAC1B;AAAA,EAEA,mBAAmB;AACX,UAAA,YAAY,KAAK;AAEhB,WAAA,SAAS,UAAU,IAAI,MAAM,UAAU,IAAI,MAAM,UAAU,IAAI;AAAA,EACxE;AAAA,EAEA,qBAAqB;AACnB,QAAI,eAAe;AAEf,QAAA,KAAK,qBAAqB,SAAS;AACtB,qBAAA;AAAA,IAAA,WACN,KAAK,qBAAqB,SAAS;AAC7B,qBAAA;AAAA,IAAA,WACN,KAAK,qBAAqB,YAAY;AAChC,qBAAA;AAAA,IACjB;AAEA,WAAO,YAAY;AAAA,EACrB;AAAA,EAEA,kCAAkC;AAC3B,SAAA,YAAY,YAAY,KAAK,mBAAmB;AAI/C,UAAA,kBAAkB,KAAK;AACxB,SAAA,WAAW,MAAM,eAAe,gBAAgB;AACrD,SAAK,WAAW,MAAM,UAAU,gBAAgB,QAAQ;AAIlD,UAAA,YAAY,KAAK;AAEjB,UAAA,WAAW,KAAK,QAAQ;AAAA,MAC5B;AAAA,MACA;AAAA,MACA,KAAK,WAAW;AAAA,MAChB,KAAK,WAAW;AAAA,IAAA;AAGlB,aAAS,IAAI,GAAG,IAAI,SAAS,KAAK,QAAQ,KAAK,GAAG;AACvC,eAAA,KAAK,CAAC,IAAI,UAAU;AAC7B,eAAS,KAAK,IAAI,CAAC,IAAI,UAAU;AACjC,eAAS,KAAK,IAAI,CAAC,IAAI,UAAU;AAAA,IACnC;AAEA,SAAK,QAAQ,aAAa,UAAU,GAAG,CAAC;AAAA,EAC1C;AAAA,EAUA,OAAO,cAAc,OAAO;AAC1B,UAAM,OAAO,kBAAiB;AAC1B,QAAA,MAAM,QAAQ,KAAK;AACrB,WAAK,aAAa,KAAK,IAAI,KAAK,aAAa,GAAG,GAAG;AAC9C,WAAA,mBAAmB,QAAQ,KAAK;AAAA,IAAA,WAC5B,MAAM,QAAQ,KAAK;AAC5B,WAAK,aAAa,KAAK,IAAI,KAAK,aAAa,GAAG,CAAC;AAC5C,WAAA,mBAAmB,QAAQ,KAAK;AAAA,IAAA,WAC5B,MAAM,QAAQ,SAAS;AAChC,WAAK,KAAK;AAAA,IACZ;AAEA,SAAK,mBAAmB,IAAI;AAAA,EAC9B;AAAA,EAEA,OAAO,gBAAgB,OAAO;AAC5B,UAAM,eAAe;AAErB,SAAK,cAAc;AACnB,SAAK,cAAc;AAEnB,sBAAiB,SAAS,eAAe;AAAA,EAC3C;AAAA,EAEA,mBAAmB,MAAM;AACvB,UAAM,QAAQ,KAAK;AAEnB,QAAI,UAAU,KAAK;AACnB,QAAI,UAAU,KAAK;AAEnB,UAAM,MAAM,QAAQ,KAAK,aAAa,IAAI,KAAK,aAAa;AAC5D,UAAM,MAAM,SAAS,KAAK,aAAa,IAAI,KAAK,aAAa;AAC7D,UAAM,MAAM,OAAO,UAAU,KAAK,aAAa,KAAK,aAAa;AACjE,UAAM,MAAM,MAAM,UAAU,KAAK,aAAa,KAAK,aAAa;AAAA,EAClE;AAAA,EAEA,iBAAiB,MAAM,OAAO;AAC5B,UAAM,eAAe;AAErB,QAAI,MAAM,SAAS;AAEb,UAAA,MAAM,SAAS,GAAG;AACpB,aAAK,aAAa,KAAK,IAAI,IAAM,KAAK,aAAa,GAAG;AAAA,MAAA,OACjD;AACL,aAAK,aAAa,KAAK,IAAI,KAAK,KAAK,aAAa,GAAG;AAAA,MACvD;AAEA,WAAK,kBAAkB;AAAA,IAAA,OAClB;AAED,UAAA,MAAM,SAAS,EAAQ,MAAA,aAAa,KAAK,IAAI,KAAK,aAAa,GAAG,GAAG;AAAA,gBAC/D,aAAa,KAAK,IAAI,KAAK,aAAa,GAAG,CAAC;AAEtD,WAAK,mBAAmB,QAAQ,KAAK,WAAW,SAAS;AAEzD,WAAK,mBAAmB,IAAI;AAAA,IAC9B;AAAA,EACF;AAAA,EAEA,eAAe,MAAM,OAAO;AAC1B,SAAK,UAAU,MAAM;AACrB,SAAK,UAAU,MAAM;AAErB,SAAK,mBAAmB,IAAI;AAE5B,QAAI,MAAM,SAAS;AACjB,YAAM,eAAe;AAChB,WAAA,SAAS,MAAM,KAAK;AAAA,IAC3B;AAEA,QAAI,mBACD,OAAO,cAAc,iBAAiB,cAAe,MAAM,WAAW;AAErE,QAAA,MAAM,YAAY,kBAAkB;AACtC,WAAK,eAAe;AAEpB,YAAM,IAAI,MAAM;AACZ,UAAA,SAAS,KAAK,aAAa,KAAK;AACpC,WAAK,aAAa,KAAK;AAAA,QACrB,KAAK,IAAI,IAAM,KAAK,kBAAkB,KAAK;AAAA,QAC3C;AAAA,MAAA;AAGF,WAAK,kBAAkB;AACvB;AAAA,IACF;AAAA,EACF;AAAA,EAEA,SAAS,MAAM,OAAO;AAChB,QAAA,MAAM,WAAW,GAAG;AACtB,UAAI,kBAAiB,aAAa;AAC5B,YAAA,SAAS,kBAAiB,cAAc,MAAM;AAC9C,YAAA,SAAS,kBAAiB,cAAc,MAAM;AAE7C,aAAA,QAAQ,KAAK,kBAAkB;AAC/B,aAAA,QAAQ,KAAK,kBAAkB;AAEpC,aAAK,kBAAkB;AAAA,MACzB;AAAA,IACF;AAAA,EACF;AAAA,EAEA,UAAU,MAAM,OAAO;AACjB,QAAA,MAAM,WAAW,MAAM,UAAU;AACnC;AAAA,IACF;AAEA,UAAM,eAAe;AAErB,SAAK,UAAU,MAAM;AACrB,SAAK,UAAU,MAAM;AAErB,SAAK,mBAAmB,IAAI;AAE5B,QAAI,mBACD,OAAO,cAAc,iBAAiB,cAAe,MAAM,WAAW;AACrE,QAAA,oBAAoB,CAAC,GAAG,GAAG,EAAE,EAAE,SAAS,MAAM,OAAO;AAErD,QAAA,CAAC,MAAM,UAAU,kBAAkB;AACrC,UAAI,OAAO,YAAY,IAAI,IAAI,KAAK;AAE9B,YAAA,WAAW,KAAK,WAAW,sBAAsB;AAEvD,UAAI,IAAI,MAAM;AACd,UAAI,IAAI,MAAM;AAEV,UAAA,MAAM,WAAW,MAAM;AACzB,YAAI,MAAM,cAAc,CAAC,EAAE,UAAU,SAAS;AAAA,MAChD;AAEI,UAAA,MAAM,WAAW,MAAM;AACzB,YAAI,MAAM,cAAc,CAAC,EAAE,UAAU,SAAS;AAAA,MAChD;AAEA,WAAK,KAAK;AACV,WAAK,KAAK;AAEV,UAAI,aAAa,KAAK;AACtB,UAAI,iBAAiB,gBAAgB,MAAM,eAAe,OAAO;AAC/D,sBAAc,MAAM;AACpB,aAAK,gBAAgB,MAAM;AAAA,MAAA,WAE3B,OAAO,cACP,iBAAiB,cACjB,OAAO,IACP;AAEA,sBAAc,KAAK;AAAA,MAAA,OACd;AACL,qBAAa,KAAK;AAAA,MACpB;AAEI,UAAA,OAAO,MAAM,CAAC,KAAK;AACrB,8BAAsB,MAAM;AAC1B,eAAK,QAAQ;AACR,eAAA,QAAQ,YAAY,KAAK,iBAAiB;AAC/C,eAAK,QAAQ,2BAA2B;AACnC,eAAA,QAAQ,IAAI,GAAG,GAAG,YAAY,GAAG,KAAK,KAAK,GAAG,KAAK;AACxD,eAAK,QAAQ;AACb,eAAK,QAAQ;AACb,eAAK,QAAQ;AAAA,QAAA,CACd;AAAA;AAED,8BAAsB,MAAM;AAC1B,eAAK,QAAQ;AACR,eAAA,QAAQ,YAAY,KAAK,iBAAiB;AAC/C,eAAK,QAAQ,2BAA2B;AAEpC,cAAA,KAAK,IAAI,KAAK;AACd,cAAA,KAAK,IAAI,KAAK;AAElB,cAAI,WAAW,KAAK,KAAK,KAAK,KAAK,KAAK,EAAE;AAC1C,cAAI,aAAa,KAAK;AACtB,cAAI,aAAa,KAAK;AAEtB,mBAAS,IAAI,GAAG,IAAI,UAAU,KAAK,GAAG;AAChC,gBAAA,KAAK,KAAK,QAAQ,aAAa;AAC/B,gBAAA,KAAK,KAAK,QAAQ,aAAa;AAC9B,iBAAA,QAAQ,IAAI,IAAI,IAAI,YAAY,GAAG,KAAK,KAAK,GAAG,KAAK;AAC1D,iBAAK,QAAQ;UACf;AACA,eAAK,QAAQ;AACb,eAAK,QAAQ;AAAA,QAAA,CACd;AAEE,WAAA,WAAW,YAAY;IAClB,WAAA,MAAM,UAAU,oBAAqB,mBAAmB;AAC5D,YAAA,WAAW,KAAK,WAAW,sBAAsB;AACjDoB,YAAAA,MACH,MAAM,WAAW,MAAM,cAAc,CAAC,EAAE,UAAU,SAAS,QAC5D,KAAK;AACDC,YAAAA,MACH,MAAM,WAAW,MAAM,cAAc,CAAC,EAAE,UAAU,SAAS,OAC5D,KAAK;AAEP,UAAI,aAAa,KAAK;AACtB,UAAI,iBAAiB,gBAAgB,MAAM,eAAe,OAAO;AAC/D,sBAAc,MAAM;AACpB,aAAK,gBAAgB,MAAM;AAAA,MAAA,WAE3B,OAAO,cACP,iBAAiB,cACjB,OAAO,IACP;AACA,sBAAc,KAAK;AAAA,MAAA,OACd;AACL,qBAAa,KAAK;AAAA,MACpB;AAEI,UAAA,OAAO,MAAM,CAAC,KAAK;AAErB,8BAAsB,MAAM;AAC1B,eAAK,QAAQ;AACb,eAAK,QAAQ,2BAA2B;AACnC,eAAA,QAAQ,IAAID,IAAGC,IAAG,YAAY,GAAG,KAAK,KAAK,GAAG,KAAK;AACxD,eAAK,QAAQ;AACb,eAAK,QAAQD;AACb,eAAK,QAAQC;AAAAA,QAAA,CACd;AAAA;AAED,8BAAsB,MAAM;AAC1B,eAAK,QAAQ;AACb,eAAK,QAAQ,2BAA2B;AAEpC,cAAA,KAAKD,KAAI,KAAK;AACd,cAAA,KAAKC,KAAI,KAAK;AAElB,cAAI,WAAW,KAAK,KAAK,KAAK,KAAK,KAAK,EAAE;AAC1C,cAAI,aAAa,KAAK;AACtB,cAAI,aAAa,KAAK;AAEtB,mBAAS,IAAI,GAAG,IAAI,UAAU,KAAK,GAAG;AAChC,gBAAA,KAAK,KAAK,QAAQ,aAAa;AAC/B,gBAAA,KAAK,KAAK,QAAQ,aAAa;AAC9B,iBAAA,QAAQ,IAAI,IAAI,IAAI,YAAY,GAAG,KAAK,KAAK,GAAG,KAAK;AAC1D,iBAAK,QAAQ;UACf;AACA,eAAK,QAAQD;AACb,eAAK,QAAQC;AAAAA,QAAA,CACd;AAEE,WAAA,WAAW,YAAY;IAC9B;AAAA,EACF;AAAA,EAEA,kBAAkB,MAAM,OAAO;AAC7B,QAAI,MAAM,SAAS;AACb,UAAA,MAAM,WAAW,GAAG;AACtB,0BAAiB,cAAc,MAAM;AACrC,0BAAiB,cAAc,MAAM;AAErC,aAAK,kBAAkB,KAAK;AAC5B,aAAK,kBAAkB,KAAK;AAAA,MAC9B;AACA;AAAA,IACF;AAEA,QAAI,aAAa,KAAK;AACtB,QAAI,iBAAiB,gBAAgB,MAAM,eAAe,OAAO;AAC/D,oBAAc,MAAM;AACpB,WAAK,gBAAgB,MAAM;AAAA,IAC7B;AAEI,QAAA,CAAC,GAAG,GAAG,CAAC,EAAE,SAAS,MAAM,MAAM,GAAG;AACpC,WAAK,eAAe;AAEpB,YAAM,eAAe;AAErB,UAAI,MAAM,UAAU;AAClB,aAAK,aAAa,MAAM;AACxB,aAAK,kBAAkB,KAAK;AAC5B;AAAA,MACF;AAEM,YAAA,WAAW,KAAK,WAAW,sBAAsB;AACjD,YAAA,KACH,MAAM,WAAW,MAAM,cAAc,CAAC,EAAE,UAAU,SAAS,QAC5D,KAAK;AACD,YAAA,KACH,MAAM,WAAW,MAAM,cAAc,CAAC,EAAE,UAAU,SAAS,OAC5D,KAAK;AAEP,WAAK,QAAQ;AACb,UAAI,CAAC,MAAM,UAAU,MAAM,UAAU,GAAG;AACjC,aAAA,QAAQ,YAAY,KAAK,iBAAiB;AAC/C,aAAK,QAAQ,2BAA2B;AAAA,MAAA,OACnC;AACL,aAAK,QAAQ,2BAA2B;AAAA,MAC1C;AACK,WAAA,QAAQ,IAAI,GAAG,GAAG,YAAY,GAAG,KAAK,KAAK,GAAG,KAAK;AACxD,WAAK,QAAQ;AACb,WAAK,QAAQ;AACb,WAAK,QAAQ;AACR,WAAA,WAAW,YAAY;IAC9B;AAAA,EACF;AAAA,EAEM,OAAO;AAAA;AACL,YAAA,eAAe,SAAS,cAAc,QAAQ;AAC9C,YAAA,YAAY,aAAa,WAAW,MAAM;AAAA,QAC9C,oBAAoB;AAAA,MAAA,CACrB;AACY,mBAAA,QAAQ,KAAK,MAAM;AACnB,mBAAA,SAAS,KAAK,MAAM;AAEjC,gBAAU,UAAU,GAAG,GAAG,aAAa,OAAO,aAAa,MAAM;AACvD,gBAAA;AAAA,QACR,KAAK;AAAA,QACL;AAAA,QACA;AAAA,QACA,KAAK,WAAW;AAAA,QAChB,KAAK,WAAW;AAAA,QAChB;AAAA,QACA;AAAA,QACA,aAAa;AAAA,QACb,aAAa;AAAA,MAAA;AAIf,YAAM,aAAa,UAAU;AAAA,QAC3B;AAAA,QACA;AAAA,QACA,aAAa;AAAA,QACb,aAAa;AAAA,MAAA;AAIf,eAAS,IAAI,GAAG,IAAI,WAAW,KAAK,QAAQ,KAAK,GAAG;AAC9C,YAAA,WAAW,KAAK,IAAI,CAAC,KAAK,IAAgB,YAAA,KAAK,IAAI,CAAC,IAAI;AAAA,YAC5C,YAAA,KAAK,IAAI,CAAC,IAAI;AAEnB,mBAAA,KAAK,CAAC,IAAI;AACV,mBAAA,KAAK,IAAI,CAAC,IAAI;AACd,mBAAA,KAAK,IAAI,CAAC,IAAI;AAAA,MAC3B;AAEA,gBAAU,2BAA2B;AAC3B,gBAAA,aAAa,YAAY,GAAG,CAAC;AAEjC,YAAA,WAAW,IAAI;AACrB,YAAM,WAAW,oBAAoB,YAAY,IAAA,IAAQ;AAEzD,YAAM,OAAO;AAAA,QACX;AAAA,QACA,WAAW;AAAA,QACX,MAAM;AAAA,MAAA;AAGR,UAAI,SAAS,UAAU,iBAAiB,UAAU,OAAO,CAAC,IAAI;AAE1D,UAAA,SAAS,UAAU,SAAS;AACxB,cAAA,QAAQ,SAAS,UAAU,QAAQ;AAAA,UACvC,CAAC,QAAQ,IAAI,SAAS;AAAA,QAAA;AAGxB,YAAI,SAAS,EAAG,UAAS,UAAU,QAAQ,KAAK,EAAE,QAAQ;AAAA,MAC5D;AAEM,YAAA,UAAU,aAAa;AACvB,YAAA,OAAO,cAAc,OAAO;AAElC,UAAI,eAAe,IAAI,IAAI,KAAK,MAAM,GAAG;AAIzC,YAAM,eAAoB;AAAA,QACxB,UAAU,aAAa,aAAa,IAAI,UAAU;AAAA,MAAA;AAGpD,UAAI,qBAAqB,aAAa,aAAa,IAAI,WAAW;AAC9D,UAAA,iCAAiC,YAAY;AAEjD,UAAI,gBAAgB,aAAa,aAAa,IAAI,MAAM;AACpD,UAAA,4BAA4B,OAAO;AAE9B,eAAA,OAAO,SAAS,MAAM,QAAQ;AACvC,eAAS,OAAO,gBAAgB,KAAK,UAAU,YAAY,CAAC;AACnD,eAAA,OAAO,QAAQ,OAAO;AACtB,eAAA,OAAO,aAAa,WAAW;AAExC,WAAK,WAAW,YAAY;AAC5B,WAAK,WAAW,WAAW;AACrB,YAAA,WAAW,MAAM,QAAQ;AAC/B,eAAS,sBAAsB;AAC/B,WAAK,MAAM;AAAA,IACb;AAAA;AACF;AAx7BE,cADI,mBACG,YAAW;AAClB,cAFI,mBAEG,eAA6B;AACpC,cAHI,mBAGG,eAA6B;AAHtC,IAAM,mBAAN;AA27BA,IAAI,kBAAkB;AAAA,EACpB,MAAM;AAAA,EACN,KAAKrB,MAAK;AACR,aAAS,kBAAkB,WAAY;AAC/B,YAAA,MAAM,iBAAiB;AACzB,UAAA,CAAC,IAAI,YAAY;AACnB,YAAI,KAAK;AAAA,MACX;AAAA,IAAA;AAGI,UAAA,oBAAoB,MACxB,SAAS,aACT,SAAS,UAAU,QACnB,SAAS,UAAU,KAAK,SAAS;AACnB,oBAAA;AAAA,MACd;AAAA,MACA;AAAA,MACA,SAAS;AAAA,IAAA;AAAA,EAEb;AACF,CAAC;ACxhCD,MAAM,KAAK;AACX,MAAM,OAAO;AAEb,MAAM,wBAAwB,YAAY;AAAA,EAOxC,cAAc;AACN;AAPR;AACA;AACA;AACA;AACA;AAIE,SAAK,KAAK,EAAE,KAAK,CAAC,MAAM;AACtB,WAAK,YAAY;AAAA,IAAA,CAClB;AAEI,SAAA,QAAQ,UAAU,IAAI,wBAAwB;AACnD,SAAK,YAAY;AACjB,SAAK,gBAAgB;AAChB,SAAA,WAAW,IAAI;AACpB,SAAK,SAAS,MACZ;AAEG,SAAA,cAAc,IAAI,SAAS;AAAA,MAC9B,MAAM;AAAA,MACN,QAAQ;AAAA,MACR,UAAU;AAAA,MACV,OAAO,EAAE,SAAS,OAAO;AAAA,MACzB,QAAQ,SAAS;AAAA,MACjB,UAAU,MAAM,KAAK,UAAU;AAAA,IAAA,CAChC;AAAA,EACH;AAAA,EAEA,gBAAgB;AACR,UAAA,OAAO,MAAM;AACd,SAAA,CAAC,EAAE,cAAc;AACtB,SAAK,CAAC,EAAE,UAAU,CAAC,MAAM;AACvB,mBAAa,KAAK,aAAa;AAC/B,WAAK,MAAM;AAAA,IAAA;AAER,SAAA;AAAA,MACH,IAAI,UAAU;AAAA,QACZ,MAAM;AAAA,QACN,aAAa;AAAA,QACb,SAAS,MAAM,KAAK,UAAU;AAAA,MAAA,CAC/B;AAAA,IAAA;AAEE,SAAA;AAAA,MACH,IAAI,UAAU;AAAA,QACZ,MAAM;AAAA,QACN,aAAa;AAAA,QACb,SAAS,MAAM;AACb,eAAK,YAAY;QACnB;AAAA,MAAA,CACD;AAAA,IAAA;AAEI,WAAA;AAAA,EACT;AAAA,EAEM,OAAO;AAAA;AACX,UAAI,YAAY,CAAA;AACZ,UAAA,IAAI,oBAAoB,UAAU;AACpC,YAAI,IAAI,kBAAkB;AAElB,gBAAA,OAAO,aAAa,QAAQ,EAAE;AACpC,cAAI,MAAM;AACI,wBAAA,KAAK,MAAM,IAAI;AAAA,UAC7B;AACA,gBAAM,IAAI,cAAc,MAAM,MAAM,EAAE,WAAW,OAAO;AAAA,QAAA,OACnD;AACL,gBAAM,MAAM,MAAM,IAAI,YAAY,IAAI;AAClC,cAAA,IAAI,WAAW,KAAK;AAClB,gBAAA;AACU,0BAAA,MAAM,IAAI;qBACf,OAAO;AAAA,YAAC;AAAA,UAAA,WACR,IAAI,WAAW,KAAK;AAC7B,oBAAQ,MAAM,IAAI,SAAS,MAAM,IAAI,UAAU;AAAA,UACjD;AAAA,QACF;AAAA,MAAA,OACK;AACC,cAAA,OAAO,aAAa,QAAQ,EAAE;AACpC,YAAI,MAAM;AACI,sBAAA,KAAK,MAAM,IAAI;AAAA,QAC7B;AAAA,MACF;AAEA,aAAO,gCAAa,CAAA;AAAA,IACtB;AAAA;AAAA,EAEM,QAAQ;AAAA;AACR,UAAA,IAAI,oBAAoB,UAAU;AACpC,cAAM,YAAY,KAAK,UAAU,KAAK,WAAW,QAAW,CAAC;AAChD,qBAAA,QAAQ,IAAI,SAAS;AAC9B,YAAA;AACF,gBAAM,IAAI,cAAc,MAAM,WAAW,EAAE,WAAW,OAAO;AAAA,iBACtD,OAAO;AACd,kBAAQ,MAAM,KAAK;AACnB,gBAAM,MAAM,OAAO;AAAA,QACrB;AAAA,MAAA,OACK;AACL,qBAAa,QAAQ,IAAI,KAAK,UAAU,KAAK,SAAS,CAAC;AAAA,MACzD;AAAA,IACF;AAAA;AAAA,EAEM,YAAY;AAAA;AACLE,iBAAAA,SAAQ,KAAK,YAAY,OAAO;AACzC,YAAIA,MAAK,SAAS,sBAAsBA,MAAK,KAAK,SAAS,OAAO,GAAG;AAC7D,gBAAA,SAAS,IAAI;AACnB,iBAAO,SAAS,MAAY;AAC1B,kBAAM,aAAa,KAAK,MAAM,OAAO,MAAgB;AACrD,gBAAI,yCAAY,WAAW;AACd,yBAAA,YAAY,WAAW,WAAW;AACvC,qBAAA,qCAAU,UAAQ,qCAAU,OAAM;AAC/B,uBAAA,UAAU,KAAK,QAAQ;AAAA,gBAC9B;AAAA,cACF;AACA,oBAAM,KAAK;YACb;AAAA,UAAA;AAEI,gBAAA,OAAO,WAAWA,KAAI;AAAA,QAC9B;AAAA,MACF;AAEA,WAAK,YAAY,QAAQ;AAEzB,WAAK,MAAM;AAAA,IACb;AAAA;AAAA,EAEA,YAAY;AACN,QAAA,KAAK,UAAU,UAAU,GAAG;AAC9B,YAAM,yBAAyB;AAC/B;AAAA,IACF;AAEM,UAAA,OAAO,KAAK,UAAU,EAAE,WAAW,KAAK,UAAa,GAAA,MAAM,CAAC;AAC5D,UAAA,OAAO,IAAI,KAAK,CAAC,IAAI,GAAG,EAAE,MAAM,mBAAA,CAAoB;AACpD,UAAA,MAAM,IAAI,gBAAgB,IAAI;AAC9B,UAAA,IAAI,IAAI,KAAK;AAAA,MACjB,MAAM;AAAA,MACN,UAAU;AAAA,MACV,OAAO,EAAE,SAAS,OAAO;AAAA,MACzB,QAAQ,SAAS;AAAA,IAAA,CAClB;AACD,MAAE,MAAM;AACR,eAAW,WAAY;AACrB,QAAE,OAAO;AACF,aAAA,IAAI,gBAAgB,GAAG;AAAA,OAC7B,CAAC;AAAA,EACN;AAAA,EAEA,OAAO;AAEC,UAAA;AAAA,MACJ;AAAA,QACE;AAAA,QACA,CAAC;AAAA,QACD,KAAK,UAAU,QAAQ,CAAC,GAAG,MAAM;AAC3B,cAAA;AACG,iBAAA;AAAA,YACL;AAAA,cACE;AAAA,cACA;AAAA,gBACE,SAAS,EAAE,IAAI,EAAE,WAAW;AAAA,gBAC5B,WAAW;AAAA,gBACX,OAAO;AAAA,kBACL,SAAS;AAAA,kBACT,qBAAqB;AAAA,kBACrB,QAAQ;AAAA,kBACR,KAAK;AAAA,kBACL,iBAAiB;AAAA,gBACnB;AAAA,gBACA,aAAa,CAAC,MAAM;AAClB,uBAAK,YAAY,EAAE;AACjB,oBAAA,cAAc,MAAM,UAAU;AAC9B,oBAAA,cAAc,MAAM,SAAS;AAC/B,oBAAE,aAAa,gBAAgB;AAC/B,oBAAE,aAAa,aAAa,KAAK,UAAU,GAAG,CAAC;AAAA,gBACjD;AAAA,gBACA,WAAW,CAAC,MAAM;AACd,oBAAA,OAAO,MAAM,UAAU;AACvB,oBAAA,cAAc,MAAM,SAAS;AAC7B,oBAAA,cAAc,gBAAgB,WAAW;AAG3C,uBAAK,QACF,iBAAiB,qBAAqB,EACtC,QAAQ,CAAC,IAAiBe,OAAM;AAC/B,wBAAI,SAAS,OAAO,SAAS,GAAG,QAAQ,EAAE;AAE1C,wBAAI,MAAM,KAAK,aAAa,UAAUA,IAAG;AACvC,2BAAK,UAAU;AAAA,wBACbA;AAAAA,wBACA;AAAA,wBACA,KAAK,UAAU,OAAO,QAAQ,CAAC,EAAE,CAAC;AAAA,sBAAA;AAAA,oBAEtC;AACG,uBAAA,QAAQ,KAAKA,GAAE,SAAS;AAAA,kBAAA,CAC5B;AACH,uBAAK,MAAM;AAAA,gBACb;AAAA,gBACA,YAAY,CAAC,MAAM;AACjB,oBAAE,eAAe;AACb,sBAAA,EAAE,iBAAiB,KAAK,UAAW;AAEnC,sBAAA,OAAO,EAAE,cAAc,sBAAsB;AACjD,sBAAI,EAAE,UAAU,KAAK,MAAM,KAAK,SAAS,GAAG;AAC1C,sBAAE,cAAc,WAAW;AAAA,sBACzB,KAAK;AAAA,sBACL,EAAE,cAAc;AAAA,oBAAA;AAAA,kBAClB,OACK;AACL,sBAAE,cAAc,WAAW;AAAA,sBACzB,KAAK;AAAA,sBACL,EAAE;AAAA,oBAAA;AAAA,kBAEN;AAAA,gBACF;AAAA,cACF;AAAA,cACA;AAAA,gBACE;AAAA,kBACE;AAAA,kBACA;AAAA,oBACE,aAAa;AAAA,oBACb,OAAO;AAAA,sBACL,QAAQ;AAAA,oBACV;AAAA,oBACA,aAAa,CAAC,MAAM;AAEd,0BAAA,EAAE,OAAO,aAAa;AACtB,0BAAA,cAAc,WAAW,YAAY;AAAA,oBAC3C;AAAA,kBACF;AAAA,kBACA;AAAA,oBACE,IAAI,SAAS;AAAA,sBACX,OAAO,EAAE;AAAA,sBACT,SAAS,EAAE,MAAM,EAAE,KAAK;AAAA,sBACxB,OAAO;AAAA,wBACL,oBAAoB;AAAA,wBACpB,oBAAoB;AAAA,sBACtB;AAAA,sBACA,UAAU,CAAC,MAAM;AACf,qCAAa,KAAK,aAAa;AAC/B,4BAAI,KAAK,EAAE;AACP,4BAAA,MAAM,GAAG,WAAW;AACnB,6BAAA,UAAU,IAAI,QAAQ,EAAE,EAAE,OAC7B,GAAG,MAAM,KAAA,KAAU;AACrB,6BAAK,MAAM;AACX,2BAAG,MAAM,kBAAkB;AAC3B,2BAAG,MAAM,qBAAqB;AAGzB,6BAAA,gBAAgB,WAAW,WAAY;AAC1C,6BAAG,MAAM,qBAAqB;AAC9B,6BAAG,MAAM,kBAAkB;AAAA,2BAC1B,EAAE;AAAA,sBACP;AAAA,sBACA,YAAY,CAAC,MAAM;AACjB,4BAAI,KAAK,EAAE;AACX,qCAAa,KAAK,aAAa;AAC/B,2BAAG,MAAM,qBAAqB;AAC9B,2BAAG,MAAM,kBAAkB;AAAA,sBAC7B;AAAA,sBACA,GAAG,CAAC,OAAQ,YAAY;AAAA,oBAAA,CACzB;AAAA,kBACH;AAAA,gBACF;AAAA,gBACA,IAAI,OAAO,IAAI;AAAA,kBACb,IAAI,UAAU;AAAA,oBACZ,aAAa;AAAA,oBACb,OAAO;AAAA,sBACL,UAAU;AAAA,sBACV,YAAY;AAAA,oBACd;AAAA,oBACA,SAAS,CAAC,MAAM;AACR,4BAAA,OAAO,KAAK,UAAU,EAAE,WAAW,CAAC,CAAC,EAAK,GAAA,MAAM,CAAC;AACvD,4BAAM,OAAO,IAAI,KAAK,CAAC,IAAI,GAAG;AAAA,wBAC5B,MAAM;AAAA,sBAAA,CACP;AACK,4BAAA,MAAM,IAAI,gBAAgB,IAAI;AAC9B,4BAAA,IAAI,IAAI,KAAK;AAAA,wBACjB,MAAM;AAAA,wBACN,WAAW,UAAU,SAAS,EAAE,QAAQ;AAAA,wBACxC,OAAO,EAAE,SAAS,OAAO;AAAA,wBACzB,QAAQ,SAAS;AAAA,sBAAA,CAClB;AACD,wBAAE,MAAM;AACR,iCAAW,WAAY;AACrB,0BAAE,OAAO;AACF,+BAAA,IAAI,gBAAgB,GAAG;AAAA,yBAC7B,CAAC;AAAA,oBACN;AAAA,kBAAA,CACD;AAAA,kBACD,IAAI,UAAU;AAAA,oBACZ,aAAa;AAAA,oBACb,OAAO;AAAA,sBACL,UAAU;AAAA,sBACV,OAAO;AAAA,sBACP,YAAY;AAAA,oBACd;AAAA,oBACA,SAAS,CAAC,MAAM;AACR,4BAAA,OAAO,EAAE,OAAO,WAAW;AAC5B,2BAAA,WAAW,YAAY,IAAI;AAChC,2BAAK,UAAU,OAAO,KAAK,QAAQ,KAAK,GAAG,CAAC;AAC5C,2BAAK,MAAM;AAEX,0BAAI,OAAO;AACX,iCAAW,WAAY;AACrB,6BAAK,QACF,iBAAiB,qBAAqB,EACtC,QAAQ,CAAC,IAAiBA,OAAM;AAC5B,6BAAA,QAAQ,KAAKA,GAAE,SAAS;AAAA,wBAAA,CAC5B;AAAA,yBACF,CAAC;AAAA,oBACN;AAAA,kBAAA,CACD;AAAA,gBAAA,CACF;AAAA,cACH;AAAA,YACF;AAAA,UAAA;AAAA,QACF,CACD;AAAA,MACH;AAAA,IAAA;AAAA,EAEJ;AACF;AAEA,IAAI,kBAAkB;AAAA,EACpB,MAAM;AAAA,EACN,QAAQ;AACA,UAAA,SAAS,IAAI;AAEb,UAAA,kBAAkB,CAAO,OAAO;AAG9B,YAAA,MAAM,aAAa,QAAQ,2BAA2B;AAC5D,YAAM,GAAG;AACI,mBAAA,QAAQ,6BAA6B,GAAG;AAAA,IAAA;AAGjD,UAAA,OAAO,aAAa,UAAU;AACvB,iBAAA,UAAU,uBAAuB,WAAY;AACxD,YAAM,UAAU,KAAK,MAAM,MAAM,SAAS;AAE1C,cAAQ,KAAK,IAAI;AACjB,cAAQ,KAAK;AAAA,QACX,SAAS;AAAA,QACT,UAAU,CAAC,OAAO,KAAK,IAAI,OAAO,kBAAkB,CAAE,CAAA,EAAE;AAAA,QACxD,UAAU,MAAM;AACR,gBAAA,OAAO,OAAO,YAAY;AAC5B,cAAA,EAAC,6BAAM,QAAQ;AAEnB,0BAAgB,MAAM;AACpB,gBAAI,OAAO;AACP,gBAAA,OAAO,aAAa,QAAQ,2BAA2B;AACpD,mBAAA,KAAK,MAAM,IAAI;AACtB,kBAAM,UAAU,OAAO,KAAK,IAAI,OAAO,cAAc;AACrD,qBAAS,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;AACjC,oBAAA,OAAO,IAAI,MAAM,YAAY,OAAO,SAAS,QAAQ,CAAC,CAAC,CAAC;AAExD,oBAAA,WAAW,6BAAM,YAAY;AAE/B,kBAAA,YAAY,iBAAiB,aAAa,IAAI;AAClD,kBAAI,WAAW;AACb,4BAAY,UAAU;AAElB,oBAAA,CAAC,KAAK,YAAY;AAEpB,uBAAK,aAAa;gBACpB;AAEK,qBAAA,WAAW,SAAS,IAAI,IAAI;AAEjC,qBAAK,MAAM,CAAC,EAAE,OAAO,SAAS;AAAA,cAChC;AAAA,YACF;AAEA,mBAAO,UAAU,KAAK;AAAA,cACpB;AAAA,cACA,MAAM,KAAK,UAAU,IAAI;AAAA,YAAA,CAC1B;AACD,mBAAO,MAAM;AAAA,UAAA,CACd;AAAA,QACH;AAAA,MAAA,CACD;AAGD,YAAM,WAAW,OAAO,UAAU,IAAI,CAAC,MAAM;AACpC,eAAA;AAAA,UACL,SAAS,EAAE;AAAA,UACX,UAAU,MAAM;AACd,4BAAgB,MAAY;AAC1B,oBAAM,OAAO,KAAK,MAAM,EAAE,IAAI;AAC9B,oBAAM,gBAAgB,qBAAqB,KAAK,YAAY,CAAE,CAAA;AACjD,2BAAA,QAAQ,6BAA6B,EAAE,IAAI;AACxD,kBAAI,OAAO;YAAmB,EAC/B;AAAA,UACH;AAAA,QAAA;AAAA,MACF,CACD;AAED,eAAS,KAAK,MAAM;AAAA,QAClB,SAAS;AAAA,QACT,UAAU,MAAM,OAAO,KAAK;AAAA,MAAA,CAC7B;AAED,cAAQ,KAAK;AAAA,QACX,SAAS;AAAA,QACT,SAAS;AAAA,UACP,SAAS;AAAA,QACX;AAAA,MAAA,CACD;AAEM,aAAA;AAAA,IAAA;AAAA,EAEX;AACF,CAAC;AChbD,IAAI,kBAAkB;AAAA,EACpB,MAAM;AAAA,EACN,sBAAsB;AAAA,IACpB,MAAM,SAAS;AAAA,MAYb,cAAc;AATd,qCAAQ,aAAa,YAAY,OAAO;AACxC,uCAAU,aAAa,YAAY,OAAO;AAC1C,0CAAa,aAAa,YAAY,OAAO;AAC7C;AACA;AACA;AACA;AACA;AAGM,YAAA,CAAC,KAAK,YAAY;AACf,eAAA,aAAa,EAAE,MAAM,GAAG;AAAA,QAC/B;AACa,qBAAA;AAAA;AAAA;AAAA,UAGX;AAAA,UACA;AAAA,UACA,CAAC,IAAI,EAAE,SAAS,KAAK,WAAW,MAAM,WAAW,MAAM;AAAA,UACvD;AAAA,QAAA;AAGF,aAAK,oBAAoB;AACzB,aAAK,gBAAgB;AAAA,MACvB;AAAA,IACF;AA3BE,kBADI,UACG;AA+BC,cAAA;AAAA,MACR;AAAA;AAAA,MAEA,OAAO,OAAO,UAAU;AAAA,QACtB,YAAY,UAAU;AAAA,QACtB,OAAO;AAAA,QACP,aAAa;AAAA,MAAA,CACd;AAAA,IAAA;AAGH,aAAS,WAAW;AAAA,EACtB;AACF,CAAC;AC9CD,IAAI,kBAAkB;AAAA,EACpB,MAAM;AAAA,EACN,oBAAoBjB,MAAK;AAKvB,UAAM,eAAN,MAAM,aAAY;AAAA,MAIhB,cAAc;AACR,YAAA,CAAC,KAAK,YAAY;AACpB,eAAK,aAAa;QACpB;AACK,aAAA,WAAW,iBAAiB,aAAY;AAC7C,aAAK,WAAW,aAAa;AAExB,aAAA,SAAS,IAAI,GAAG;AACrB,aAAK,UAAU,KAAK,WAAW,iBAAiB,MAAM,IAAI,GAAG;AAE7D,aAAK,yBAAyB,WAAY;AACxC,gCAAsB,MAAM;AAC1B,iBAAK,oBAAoB,UAAU,OAAO,MAAM,MAAM,IAAI;AAAA,UAAA,CAC3D;AAAA,QAAA;AAGH,aAAK,sBAAsB,SACzB,MACA,OACA,WACA,WACA;;AACA,eAAK,iBAAiB;AAGlB,cAAA,aAAa,SAAS,UAAU,QAAQ;AAE1C,kBAAM,QAAQ,IAAI;AAAA,cAChB,KAAK,QAAQ,CAAC,EAAE,MACb,IAAI,CAAC,MAAMA,KAAI,MAAM,MAAM,CAAC,EAAE,IAAI,EAClC,OAAO,CAAC,MAAM,MAAM,GAAG;AAAA,YAAA;AAExB,gBAAA,MAAM,OAAO,GAAG;AAClB,oBAAM,oBAAoB,CAAA;AACjB,uBAAA,IAAI,GAAG,IAAI,KAAK,QAAQ,CAAC,EAAE,MAAM,SAAS,GAAG,KAAK;AACzD,sBAAM,SAAS,KAAK,QAAQ,CAAC,EAAE,MAAM,CAAC;AACtC,sBAAM,OAAOA,KAAI,MAAM,MAAM,MAAM;AACnC,kCAAkB,KAAK,IAAI;AAAA,cAC7B;AACA,yBAAW,QAAQ,mBAAmB;AACpC,sBAAM,OAAOA,KAAI,MAAM,YAAY,KAAK,SAAS;AAC5C,qBAAA,gBAAgB,KAAK,WAAW;AAAA,cACvC;AAAA,YACF;AAAA,UACF;AAGA,cAAI,cAAc;AAClB,cAAI,cAAc,CAAA;AAClB,cAAI,YAAY;AAChB,cAAI,YAAY;AAChB,iBAAO,aAAa;AAClB,wBAAY,QAAQ,WAAW;AAC/B,kBAAM,SAAS,YAAY,OAAO,CAAC,EAAE;AACrC,gBAAI,WAAW,MAAM;AACnB,oBAAM,OAAOA,KAAI,MAAM,MAAM,MAAM;AACnC,kBAAI,CAAC,KAAM;AACX,oBAAM,OAAOA,KAAI,MAAM,YAAY,KAAK,SAAS;AAC3CU,oBAAAA,QAAO,KAAK,YAAY;AAC9B,kBAAIA,UAAS,WAAW;AACtB,oBAAI,SAAS,MAAM;AAEL,8BAAA,gBAAgB,KAAK,WAAW;AAC9B,gCAAA;AAAA,gBAAA,OACT;AAES,gCAAA;AAAA,gBAChB;AAAA,cAAA,OACK;AAEO,4BAAA;AACZ,6BAAY,gBAAK,QAAQ,KAAK,WAAW,MAA7B,mBAAgC,SAAhC,YAAwC;AACpD;AAAA,cACF;AAAA,YAAA,OACK;AAES,4BAAA;AACd;AAAA,YACF;AAAA,UACF;AAGM,gBAAA,QAAQ,CAAC,IAAI;AACnB,cAAI,aAAa;AACjB,iBAAO,MAAM,QAAQ;AACnB,0BAAc,MAAM;AACd,kBAAA,WACH,YAAY,UAAU,YAAY,QAAQ,CAAC,EAAE,QAAQ,CAAC,MAAM;AAC/D,gBAAI,QAAQ,QAAQ;AAClB,yBAAW,UAAU,SAAS;AAC5B,sBAAM,OAAOV,KAAI,MAAM,MAAM,MAAM;AAGnC,oBAAI,CAAC,KAAM;AAEX,sBAAM,OAAOA,KAAI,MAAM,YAAY,KAAK,SAAS;AAC3CU,sBAAAA,QAAO,KAAK,YAAY;AAE9B,oBAAIA,UAAS,WAAW;AAEtB,wBAAM,KAAK,IAAI;AACf,8BAAY,KAAK,IAAI;AAAA,gBAAA,OAChB;AAEL,wBAAM,cACJ,KAAK,UACL,KAAK,OAAO,6BAAM,WAAW,KAC7B,KAAK,OAAO,KAAK,WAAW,EAAE,OAC1B,KAAK,OAAO,KAAK,WAAW,EAAE,OAC9B;AACN,sBACE,aACA,cAAc,OACd,gBAAgB,WAChB;AAEK,yBAAA,gBAAgB,KAAK,WAAW;AAAA,kBAAA,OAChC;AACQ,iCAAA;AAAA,kBACf;AAAA,gBACF;AAAA,cACF;AAAA,YAAA,OACK;AAAA,YAEP;AAAA,UACF;AAEM,gBAAA,cAAc,aAAa,cAAc;AACzC,gBAAA,QAAQ,aAAa,iBAAiB,WAAW;AAEnD,cAAA;AACA,cAAA;AACA,cAAA;AAEJ,qBAAW,QAAQ,aAAa;AAG9B,iBAAK,QAAQ,CAAC,EAAE,OAAO,aAAa;AACpC,iBAAK,eAAe;AACpB,iBAAK,QAAQ,CAAC,EAAE,OAAO,KAAK,WAAW,iBACnC,cACA;AACC,iBAAA,OAAO,KAAK;AACjB,iBAAK,iBAAiB;AAEtB,uBAAW,KAAK,KAAK,QAAQ,CAAC,EAAE,SAAS,IAAI;AAC3C,oBAAM,OAAOV,KAAI,MAAM,MAAM,CAAC;AAC9B,kBAAI,MAAM;AACR,qBAAK,QAAQ;AAEb,oBAAIA,KAAI,iBAAkB;AAC1B,sBAAM,aAAaA,KAAI,MAAM,YAAY,KAAK,SAAS;AACvD,sBAAM,eAAc,gBAAW,WAAX,mBAAoB,KAAK;AAC7C,oBAAI,2CAAa,QAAQ;AACjB,wBAAA,SAAS,gBAAgB,WAAW;AAC1C,sBAAI,CAAC,cAAc;AACF,oCAAA,YAAO,CAAC,MAAR,YAAa;AAC5B,iCAAa,OAAO,CAAC;AAAA,kBACvB;AACA,sBAAI,CAAC,cAAc;AACjB,oCAAe,gBAAW,YAAX,mBAAoB;AAAA,sBACjC,CAAC,MAAM,EAAE,SAAS,YAAY,OAAO;AAAA;AAAA,kBAEzC;AAEM,wBAAA,SAAS,aAAa,aAAa;AAAA,oBACvC,OAAO,CAAC;AAAA,oBACR;AAAA,kBAAA,CACD;AACD,sBAAI,OAAO,cAAc;AACvB,mCAAe,OAAO;AAAA,kBACxB;AAAA,gBACF;AAAA,cACF;AAAA,YACF;AAAA,UACF;AAEA,qBAAW,QAAQ,aAAa;AAC9B,gBAAI,gBAAgB,YAAY;AAC9B,mBAAK,OAAO,CAAC,EAAE,SAAS,EAAE,MAAM;AAChC;AAAA,gBACE,KAAK,OAAO,CAAC;AAAA,gBACb,CAAC,kCAAc,aAAa,YAAY;AAAA,gBACxC;AAAA,cAAA;AAAA,YACF,OACK;AACL,8BAAgB,KAAK,OAAO,CAAC,GAAG,IAAI;AAAA,YACtC;AAAA,UACF;AAEA,cAAI,WAAW;AACP,kBAAA,OAAOA,KAAI,MAAM,MAAM,UAAU,OAAO,CAAC,EAAE,IAAI;AACrD,gBAAI,MAAM;AACR,mBAAK,QAAQ;AAAA,YACf;AAAA,UACF;AAAA,QAAA;AAGF,aAAK,QAAQ,WAAY;AACvB,gBAAM,SAAS,aAAY,UAAU,MAAM,MAAM,IAAI;AACrD,iBAAO,aAAa,CAAC;AACrB,iBAAO,UAAU,KAAK,WAAW,iBAAiB,MAAM,IAAI,GAAG;AACxD,iBAAA,OAAO,OAAO;AACd,iBAAA;AAAA,QAAA;AAIT,aAAK,gBAAgB;AAAA,MACvB;AAAA,MAEA,oBAAoB,GAAG,SAAS;AACtB,gBAAA;AAAA,UACN;AAAA,YACE,UACG,KAAK,WAAW,iBAAiB,SAAS,UAAU;AAAA,YACvD,UAAU,MAAM;AACd,mBAAK,WAAW,iBAAiB,CAAC,KAAK,WAAW;AAC9C,kBAAA,KAAK,WAAW,gBAAgB;AAC7B,qBAAA,QAAQ,CAAC,EAAE,OACd,KAAK,gBAAiB,KAAK,QAAQ,CAAC,EAAE;AAAA,cAAA,OACnC;AACA,qBAAA,QAAQ,CAAC,EAAE,OAAO;AAAA,cACzB;AACK,mBAAA,OAAO,KAAK;AACjB,mBAAK,iBAAiB;AACtBA,mBAAI,MAAM,eAAe,MAAM,IAAI;AAAA,YACrC;AAAA,UACF;AAAA,UACA;AAAA,YACE,UACG,aAAY,oBAAoB,SAAS,UAC1C;AAAA,YACF,UAAU,MAAM;AACF,2BAAA;AAAA,gBACV,CAAC,aAAY;AAAA,cAAA;AAAA,YAEjB;AAAA,UACF;AAAA,UACA;AAAA;AAAA;AAAA;AAAA;AAAA,YAKE,SACE,UAAU,KAAK,WAAW,aAAa,eAAe;AAAA,YACxD,UAAU,MAAM;AACd,mBAAK,WAAW,aAAa,CAAC,KAAK,WAAW;AAC9C,mBAAK,iBAAiB;AAAA,YACxB;AAAA,UACF;AAAA,QAAA;AAAA,MAEJ;AAAA,MACA,mBAAmB;AACZ,aAAA,aAAa,KAAK,WAAW;AAClC,YAAI,KAAK,YAAY;AAId,eAAA,OAAO,CAAC,EAAE,MAAM,CAAC,KAAK,KAAK,CAAC,IAAI,GAAG,CAAC;AAAA,QAAA,OACpC;AACE,iBAAA,KAAK,OAAO,CAAC,EAAE;AAAA,QACxB;AACAA,aAAI,MAAM,eAAe,MAAM,IAAI;AAAA,MACrC;AAAA,MAEA,cAAgC;AACvB,eAAA;AAAA,UACL,KAAK,WAAW,kBAAkB,KAAK,WAAW,KAAK,QAAQ,SAC3D,KAAK;AAAA,YACH;AAAA,YACA,UAAU,iBAAiB,KAAK,QAAQ,CAAC,EAAE,KAAK,SAAS,MACvD;AAAA,UAAA,IAEJ;AAAA,UACJ;AAAA,QAAA;AAAA,MAEJ;AAAA,MAEA,OAAO,yBAAyB,SAAS;AACvC,qBAAY,oBAAoB;AAChC,YAAI,SAAS;AACX,uBAAa,qCAAqC,IAAI;AAAA,QAAA,OACjD;AACL,iBAAO,aAAa,qCAAqC;AAAA,QAC3D;AAAA,MACF;AAAA,IACF;AAjSE,kBADI,cACG;AACP,kBAFI,cAEG,qBAAoB;AAF7B,QAAM,cAAN;AAqSY,gBAAA;AAAA,MACV,CAAC,CAAC,aAAa,qCAAqC;AAAA,IAAA;AAG5C,cAAA;AAAA,MACR;AAAA,MACA,OAAO,OAAO,aAAa;AAAA,QACzB,YAAY,UAAU;AAAA,QACtB,OAAO;AAAA,QACP,aAAa;AAAA,MAAA,CACd;AAAA,IAAA;AAGH,gBAAY,WAAW;AAAA,EACzB;AACF,CAAC;AC7TD,IAAI,kBAAkB;AAAA,EACpB,MAAM;AAAA,EACA,sBAAsB,UAAU,UAAUA,MAAK;AAAA;AACnD,UAAI,SAAS,SAAS,eAAe,SAAS,SAAS,oBAAoB;AACnE,cAAA,gBAAgB,SAAS,UAAU;AAEhC,iBAAA,UAAU,gBAAgB,WAAY;AAC7C,gBAAM,IAAI,gBACN,cAAc,MAAM,MAAM,SAAS,IACnC;AAEE,gBAAA,SAAS,KAAK,QAAQ,KAAK,CAAC,MAAM,EAAE,SAAS,iBAAiB;AACpE,iBAAO,iBAAiB,MAAM;AACrB,mBAAA,sBAAsBA,MAAK,OAAO,KAAK;AAAA,UAAA;AAGzC,iBAAA;AAAA,QAAA;AAAA,MACT,OACK;AAEC,cAAA,gBAAgB,SAAS,UAAU;AAChC,iBAAA,UAAU,gBAAgB,WAAY;AAC7C,gBAAM,IAAI,gBACN,cAAc,MAAM,MAAM,SAAS,IACnC;AAEJ,cAAI,CAAC,KAAK,cAAc,EAAE,uBAAuB,KAAK,aAAa;AACjE,iBAAK,YAAY,qBAAqB,KAAK,YAAY,MAAM,QAAQ;AAAA,UACvE;AAEO,iBAAA;AAAA,QAAA;AAAA,MAEX;AAAA,IACF;AAAA;AACF,CAAC;ACnCD,IAAI;AACJ,IAAI,aAAa;AAEjB,IAAI,kBAAkB;AAAA,EACpB,MAAM;AAAA,EACN,QAAQ;AACF,QAAA;AACA,QAAA;AACA,QAAA;AAEJ,aAAS,iBAAiB,GAAG;AAC3B,aAAO,KAAK;AAAA,QACV,EAAE,QAAQ,CAAC,EAAE,UAAU,EAAE,QAAQ,CAAC,EAAE;AAAA,QACpC,EAAE,QAAQ,CAAC,EAAE,UAAU,EAAE,QAAQ,CAAC,EAAE;AAAA,MAAA;AAAA,IAExC;AAEA,QAAI,SAAS;AAAA,MACX;AAAA,MACA,CAAC,MAAM;;AACL;AACY,oBAAA;AACR,cAAA,OAAE,YAAF,mBAAW,YAAW,GAAG;AAE3B,0CAAgB;AACJ,sBAAA,EAAE,QAAQ,CAAC;AAAA,QAAA,OAClB;AACO,sBAAA;AACR,gBAAA,OAAE,YAAF,mBAAW,YAAW,GAAG;AAE3B,sBAAU,iBAAiB,CAAC;AAC5B,gBAAI,OAAO,kBAAkB;AAAA,UAC/B;AAAA,QACF;AAAA,MACF;AAAA,MACA;AAAA,IAAA;AAGF,QAAI,SAAS,iBAAiB,YAAY,CAAC,MAAkB;;AAC5C,qBAAA;AACF,oBAAA,aAAE,YAAF,mBAAW,WAAX,YAAqB,aAAa;AAC/C,UAAI,aAAa,GAAC,OAAE,YAAF,mBAAW,SAAQ;AACnC,iCAAQ,KAAK,GAAE,QAAQ,IAAI,YAAY,KAAK;AACtC,cAAA;AAEF,cAAE,cAAc;AAAA,mBACT,OAAO;AAAA,UAAC;AAEjB,YAAE,UAAU,UAAU;AAEtB,YAAE,UAAU,UAAU;AAEtB,cAAI,OAAO,kBAAkB;AAEzB,cAAA,OAAO,oBAAoB,CAAC;AAAA,QAClC;AACY,oBAAA;AAAA,MACd;AAAA,IAAA,CACD;AAED,QAAI,SAAS;AAAA,MACX;AAAA,MACA,CAAC,MAAM;;AACO,oBAAA;AACR,cAAA,OAAE,YAAF,mBAAW,YAAW,GAAG;AAC3B,cAAI,OAAO,kBAAkB;AACd,yBAAA;AAEf,oBAAU,qBAAqB;AAE3B,oBAAA,OAAO,eAAP,mBAAmB;AACjB,gBAAA,aAAa,iBAAiB,CAAC;AAE/B,gBAAA,QAAQ,EAAE,QAAQ,CAAC,EAAE,UAAU,EAAE,QAAQ,CAAC,EAAE,WAAW;AACvD,gBAAA,QAAQ,EAAE,QAAQ,CAAC,EAAE,UAAU,EAAE,QAAQ,CAAC,EAAE,WAAW;AAEzD,cAAA,QAAQ,IAAI,OAAO,GAAG;AAC1B,gBAAM,OAAO,UAAU;AACvB,cAAI,OAAO,KAAK;AACd,qBAAS,IAAI;AAAA,UAAA,WACJ,OAAO,MAAM;AACb,qBAAA;AAAA,UACX;AACA,cAAI,OAAO,GAAG,YAAY,OAAO,CAAC,MAAM,IAAI,CAAC;AACzC,cAAA,OAAO,SAAS,MAAM,IAAI;AACpB,oBAAA;AAAA,QACZ;AAAA,MACF;AAAA,MACA;AAAA,IAAA;AAAA,EAEJ;AACF,CAAC;AAED,MAAM,mBAAmB,aAAa,UAAU;AAChD,aAAa,UAAU,mBAAmB,SAAU,GAAG;AACrD,MAAI,gBAAgB,YAAY;AAC9B;AAAA,EACF;AACO,SAAA,iBAAiB,MAAM,MAAM,SAAS;AAC/C;AAEA,MAAM,mBAAmB,aAAa,UAAU;AAChD,aAAa,UAAU,mBAAmB,SAAU,GAAG;AACjD,MAAA,gBAAgB,aAAa,GAAG;AAClC;AAAA,EACF;AACO,SAAA,iBAAiB,MAAM,MAAM,SAAS;AAC/C;ACzGA,IAAI,kBAAkB;AAAA,EACpB,MAAM;AAAA,EACN,mBAAmB;AAAA,EACnB,OAAO;AACL,cAAU,wBAAwB;AAClC,cAAU,qCAAqC;AAC/C,SAAK,oBAAoB,IAAI,GAAG,SAAS,WAAW;AAAA,MAClD,IAAI;AAAA,MACJ,MAAM;AAAA,MACN,MAAM;AAAA,MACN,OAAO;AAAA,QACL,KAAK;AAAA,QACL,KAAK;AAAA,QACL,MAAM;AAAA,MACR;AAAA,MACA,cAAc;AAAA,MACd,UAAU,CAAC,QAAQ,WAAW;AAC5B,aAAK,YAAY,MAAM;AAAA,MACzB;AAAA,IAAA,CACD;AAAA,EACH;AAAA,EACA,wBAAwB,CAAC;AAAA,EACzB,uBAAuB,CAAC;AAAA,EAClB,sBAAsB,UAAU,UAAUA,MAAK;AAAA;AACnD,UAAI,SAAS,SAAS;AACtB,UAAI,SAAS,CAAA;AACJ,eAAA,SAAS,OAAO,EAAE,UAAU;AACrC,iBAAW,YAAY,QAAQ;AACzB,YAAA,QAAQ,OAAO,QAAQ;AAC3B,YAAI,OAAO,MAAM,CAAC,MAAM,SAAU;AAE9B,YAAA,OAAO,MAAM,CAAC;AAClB,YAAI,QAAQ,cAAc;AACpB,cAAA,mBAAmB,MAAM,CAAC;AAC1B,cAAA,EAAC,qDAAkB,YAAY;AAAA,QACrC;AAEI,YAAA,EAAE,QAAQ,KAAK,yBAAyB;AAC1C,eAAK,uBAAuB,IAAI,IAAI,CAAC,SAAS;AAAA,QAChD;AACA,YAAI,KAAK,uBAAuB,IAAI,EAAE,SAAS,MAAM,EAAG;AACxD,aAAK,uBAAuB,IAAI,EAAE,KAAK,MAAM;AAIvC,cAAA,YAAY,KAAK;AACnB,YAAA,EAAE,aAAa,UAAU,2BAA2B;AACtD,oBAAU,yBAAyB,SAAS,IAAI,EAAE,OAAO,CAAG,EAAA;AAAA,QAC9D;AACU,kBAAA,yBAAyB,SAAS,EAAE,MAAM;AAAA,UAClD,SAAS;AAAA,QAAA;AAAA,MAEb;AAEI,UAAA,UAAU,SAAS,QAAQ;AAC/B,iBAAW,OAAO,SAAS;AACrB,YAAA,OAAO,QAAQ,GAAG;AAClB,YAAA,EAAE,QAAQ,KAAK,wBAAwB;AACzC,eAAK,sBAAsB,IAAI,IAAI,CAAC,SAAS;AAAA,QAC/C;AAEA,aAAK,sBAAsB,IAAI,EAAE,KAAK,MAAM;AAGxC,YAAA,EAAE,QAAQ,UAAU,4BAA4B;AAClD,oBAAU,0BAA0B,IAAI,IAAI,EAAE,OAAO,CAAG,EAAA;AAAA,QAC1D;AACA,kBAAU,0BAA0B,IAAI,EAAE,MAAM,KAAK,SAAS,UAAU;AAExE,YAAI,CAAC,UAAU,eAAe,SAAS,IAAI,GAAG;AAClC,oBAAA,eAAe,KAAK,IAAI;AAAA,QACpC;AAAA,MACF;AACI,UAAA,SAAS,KAAK,kBAAkB;AACpC,WAAK,YAAY,MAAM;AAAA,IACzB;AAAA;AAAA,EACA,YAAY,QAAQ;AAClB,cAAU,yBAAyB;AACnC,cAAU,wBAAwB;AAEvB,eAAA,QAAQ,KAAK,wBAAwB;AACpC,gBAAA,uBAAuB,IAAI,IAAI,KAAK,uBAC5C,IACF,EAAE,MAAM,GAAG,MAAM;AAAA,IACnB;AACW,eAAA,QAAQ,KAAK,uBAAuB;AACnC,gBAAA,sBAAsB,IAAI,IAAI,KAAK,sBAC3C,IACF,EAAE,MAAM,GAAG,MAAM;AAAA,IACnB;AAAA,EACF;AACF,CAAC;ACrFD,SAAS,kBAAkB,KAAK;AAC1B,MAAA,CAAC,IACH,UAAU,mBAAmB,KAAK,MAAM,IAAI,CAAC,IAAI,UAAU,gBAAgB;AACzE,MAAA,CAAC,IACH,UAAU,mBAAmB,KAAK,MAAM,IAAI,CAAC,IAAI,UAAU,gBAAgB;AACtE,SAAA;AACT;AAEA,IAAI,kBAAkB;AAAA,EACpB,MAAM;AAAA,EACN,OAAO;AAED,QAAA,GAAG,SAAS,WAAW;AAAA,MACzB,IAAI;AAAA,MACJ,MAAM;AAAA,MACN,MAAM;AAAA,MACN,OAAO;AAAA,QACL,KAAK;AAAA,QACL,KAAK;AAAA,MACP;AAAA,MACA,SACE;AAAA,MACF,cAAc,UAAU;AAAA,MACxB,SAAS,OAAO;AACd,kBAAU,mBAAmB,CAAC;AAAA,MAChC;AAAA,IAAA,CACD;AAGK,UAAA,cAAc,IAAI,OAAO;AAC3B,QAAA,OAAO,cAAc,SAAU,MAAM;AACvC,YAAM,IAAI,2CAAa,MAAM,MAAM;AAEnC,UAAI,IAAI,WAAW;AAEN,mBAAAC,OAAM,KAAK,gBAAgB;AAC/B,eAAA,eAAeA,GAAE,EAAE,YAAY;AAAA,QACtC;AAAA,MACF;AAEO,aAAA;AAAA,IAAA;AAIH,UAAA,cAAc,IAAI,MAAM;AAC1B,QAAA,MAAM,cAAc,SAAU,MAAM;AACtC,YAAM,WAAW,KAAK;AACtB,WAAK,WAAW,WAAY;AAC1B,YAAI,IAAI,WAAW;AACjB,4BAAkB,KAAK,IAAI;AAAA,QAC7B;AACO,eAAA,qCAAU,MAAM,MAAM;AAAA,MAAS;AAEjC,aAAA,2CAAa,MAAM,MAAM;AAAA,IAAS;AAIrC,UAAA,eAAe,aAAa,UAAU;AAC5C,iBAAa,UAAU,WAAW,SAAU,MAAM,KAAK;AACrD,UACE,IAAI,aACJ,KAAK,gBACL,KAAK,MAAM,KAAK,gBAChB;AACM,cAAA,CAAC,GAAG,CAAC,IAAI,kBAAkB,CAAC,GAAG,KAAK,GAAG,CAAC;AAC9C,cAAM,SAAS,IAAI,KAAK,IAAI,CAAC;AAC7B,YAAI,SAAS,IAAI,KAAK,IAAI,CAAC;AAE3B,YAAI,GAAG;AACH,YAAA,KAAK,MAAM,WAAW;AAExB,cAAI,KAAK;AACT,cAAI,UAAU;AACd,oBAAU,UAAU;AAAA,QAAA,OACf;AACD,cAAA,KAAK,KAAK,CAAC;AACX,cAAA,KAAK,KAAK,CAAC;AAEX,cAAA,YAAY,KAAK,YAAY;AACjC,cACE,cAAc,UAAU,qBACxB,cAAc,UAAU,UACxB;AACA,iBAAK,UAAU;AACf,sBAAU,UAAU;AAAA,UACtB;AAAA,QACF;AACA,cAAM,IAAI,IAAI;AACd,YAAI,YAAY;AAChB,YAAI,SAAS,QAAQ,QAAQ,GAAG,CAAC;AACjC,YAAI,YAAY;AAAA,MAClB;AAEO,aAAA,aAAa,MAAM,MAAM,SAAS;AAAA,IAAA;AAO3C,QAAI,yBAA6C;AAM3C,UAAA,YAAY,YAAY,UAAU;AACxC,gBAAY,UAAU,OAAO,SAAU,QAAQ,QAAQ,cAAc;AACnE,YAAM,IAAI,UAAU,MAAM,MAAM,SAAS;AAGzC,UACE,CAAC,0BACD,IAAI,OAAO,mBAAmB,SAC7B,UAAU,SACX;AACyB,iCAAA;AAAA,MAC3B;AAMA,UAAI,IAAI,OAAO,wBAAwB,SAAS,IAAI,WAAW;AAG7D,aAAK,qBAAqB;AACf,mBAAA,QAAQ,KAAK,QAAQ;AAC9B,eAAK,YAAY;AAAA,QACnB;AACW,mBAAA,UAAU,YAAY,MAAM,IAAI;AAAA,MAC7C;AACO,aAAA;AAAA,IAAA;AAQH,UAAA,aAAa,aAAa,UAAU;AAC1C,iBAAa,UAAU,aAAa,SAAU,QAAQ,KAAK;AACrD,UAAA,KAAK,kBAAkB,IAAI,WAAW;AACxC,YAAI,KAAK,yBAAyB;AACd,4BAAA,KAAK,eAAe,IAAI;AAAA,mBACjC,wBAAwB;AAE3B,gBAAA,CAAC,GAAG,CAAC,IAAI,kBAAkB,CAAC,GAAG,uBAAuB,GAAG,CAAC;AAChE,gBAAM,IAAI,IAAI;AACd,gBAAM,IAAI,IAAI;AACd,cAAI,YAAY;AAChB,cAAI,cAAc;AAElB,cAAI,KAAK,GAAG,GAAG,GAAG,uBAAuB,IAAI;AAC7C,cAAI,KAAK;AACT,cAAI,OAAO;AACX,cAAI,YAAY;AAChB,cAAI,cAAc;AAAA,QACpB;AAAA,MAAA,WACS,CAAC,KAAK,gBAAgB;AACN,iCAAA;AAAA,MAC3B;AACO,aAAA,WAAW,MAAM,MAAM,SAAS;AAAA,IAAA;AAIzC,UAAM,aAAa,aAAa;AAChC,iBAAa,aAAa,WAAY;AACpC,YAAM,IAAI,WAAW,MAAM,IAAI,QAAQ,SAAS;AAChD,UAAI,IAAI,WAAW;AAEX,cAAA,YAAY,IAAI,MAAM,QAAQ,IAAI,MAAM,QAAQ,SAAS,CAAC;AAChE,YAAI,WAAW;AAEb,4BAAkB,UAAU,GAAG;AAE/B,4BAAkB,UAAU,IAAI;AAAA,QAClC;AAAA,MACF;AACO,aAAA;AAAA,IAAA;AAAA,EAEX;AACF,CAAC;AC5LD,IAAI,kBAAkB;AAAA,EACpB,MAAM;AAAA,EACA,sBAAsB,UAAU,UAAwBD,MAAK;AAAA;;AACjE,YAAI,4DAAU,UAAV,mBAAiB,aAAjB,mBAA2B,UAA3B,mBAAmC,OAAnC,mBAAuC,kBAAiB,MAAM;AAChE,iBAAS,MAAM,SAAS,SAAS,CAAC,aAAa;AAAA,MACjD;AAAA,IACF;AAAA;AACF,CAAC;ACTD,MAAM,eAAe,OAAO;AAE5B,IAAI,kBAAkB;AAAA,EACpB,MAAM;AAAA,EACN,iBAAiBA,MAAK;AACb,WAAA;AAAA,MACL,OAAO,MAAM,WAAW;AAClB,YAAA;AACJ,aAAK,YAAY,IAAI,IAAI,QAAQ,CAAC,YAAa,MAAM,OAAQ;AAEvD,cAAA,YAAY,SAAS,cAAc,KAAK;AAC9C,kBAAU,MAAM,aAAa;AAC7B,kBAAU,MAAM,YAAY;AAEtB,cAAA,QAAQ,SAAS,cAAc,OAAO;AAC5C,cAAM,MAAM,SAAS,MAAM,MAAM,QAAQ;AAEzC,cAAM,YAAY,MAAY;AACxB,cAAA;AACF,kBAAM,SAAS,MAAM,UAAU,aAAa,aAAa;AAAA,cACvD,OAAO;AAAA,cACP,OAAO;AAAA,YAAA,CACR;AACD,sBAAU,gBAAgB,KAAK;AAE/B,uBAAW,MAAM,IAAI,KAAK,GAAG,GAAG;AAChC,kBAAM,iBAAiB,kBAAkB,MAAM,IAAI,KAAK,GAAG,KAAK;AAChE,kBAAM,YAAY;AAClB,kBAAM,KAAK;AAAA,mBACJ,OAAO;AACR,kBAAA,QAAQ,SAAS,cAAc,KAAK;AAC1C,kBAAM,MAAM,QAAQ;AACpB,kBAAM,MAAM,WAAW;AACvB,kBAAM,MAAM,YAAY;AACxB,kBAAM,MAAM,aAAa;AAEzB,gBAAI,OAAO,iBAAiB;AACpB,oBAAA,cACJ,8DACA,MAAM;AAAA,YAAA,OACH;AACC,oBAAA,cACJ,2JACA,MAAM;AAAA,YACV;AAEA,sBAAU,gBAAgB,KAAK;AAAA,UACjC;AAAA,QAAA;AAGQ;AAEV,eAAO,EAAE,QAAQ,KAAK,aAAa,WAAW,UAAU,SAAS;MACnE;AAAA,IAAA;AAAA,EAEJ;AAAA,EACA,YAAY,MAAM;AAChB,QAAK,KAAK,MAAM,KAAK,YAAY,eAAe,gBAAkB;AAE9D,QAAA;AACE,UAAA,SAAS,KAAK,QAAQ,KAAK,CAACS,OAAMA,GAAE,SAAS,OAAO;AACpD,UAAA,IAAI,KAAK,QAAQ,KAAK,CAACA,OAAMA,GAAE,SAAS,OAAO;AAC/C,UAAA,IAAI,KAAK,QAAQ,KAAK,CAACA,OAAMA,GAAE,SAAS,QAAQ;AAChD,UAAA,iBAAiB,KAAK,QAAQ;AAAA,MAClC,CAACA,OAAMA,GAAE,SAAS;AAAA,IAAA;AAGd,UAAA,SAAS,SAAS,cAAc,QAAQ;AAE9C,UAAM,UAAU,MAAM;AACpB,aAAO,QAAQ,EAAE;AACjB,aAAO,SAAS,EAAE;AACZ,YAAA,MAAM,OAAO,WAAW,IAAI;AAClC,UAAI,UAAU,OAAO,GAAG,GAAG,EAAE,OAAO,EAAE,KAAK;AACrC,YAAA,OAAO,OAAO,UAAU,WAAW;AAEnC,YAAA,MAAM,IAAI;AAChB,UAAI,SAAS,MAAM;AACZ,aAAA,OAAO,CAAC,GAAG;AACZ,YAAA,MAAM,eAAe,IAAI;AAC7B,8BAAsB,MAAM;;AAC1B,qBAAK,oBAAL;AAAA,QAAuB,CACxB;AAAA,MAAA;AAEH,UAAI,MAAM;AAAA,IAAA;AAGZ,UAAM,MAAM,KAAK;AAAA,MACf;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IAAA;AAEF,QAAI,WAAW;AACf,QAAI,iBAAiB,MAAM;AAE3B,WAAO,iBAAiB,MAAY;;AAClC,UAAI,eAAe,OAAO;AAChB;MACC,WAAA,GAAC,UAAK,SAAL,mBAAW,SAAQ;AAC7B,cAAM,MAAM;AACZ,cAAM,GAAG;AACH,cAAA,IAAI,MAAM,GAAG;AAAA,MACrB;AAGM,YAAA,OAAO,MAAM,IAAI,QAAc,CAAC,MAAM,OAAO,OAAO,CAAC,CAAC;AAC5D,YAAM,OAAO,GAAG,CAAC,oBAAI,KAAM,CAAA;AAC3B,YAAMP,QAAO,IAAI,KAAK,CAAC,IAAI,GAAG,IAAI;AAC5B,YAAA,OAAO,IAAI;AACZ,WAAA,OAAO,SAASA,KAAI;AACpB,WAAA,OAAO,aAAa,QAAQ;AAC5B,WAAA,OAAO,QAAQ,MAAM;AAC1B,YAAM,OAAO,MAAM,IAAI,SAAS,iBAAiB;AAAA,QAC/C,QAAQ;AAAA,QACR;AAAA,MAAA,CACD;AACG,UAAA,KAAK,WAAW,KAAK;AACvB,cAAM,MAAM,iCAAiC,KAAK,MAAM,MAAM,KAAK,UAAU;AAC7E,cAAM,GAAG;AACH,cAAA,IAAI,MAAM,GAAG;AAAA,MACrB;AACA,aAAO,UAAU,IAAI;AAAA,IAAA;AAGvB,SAAK,YAAY,EAAE,KAAK,CAAC,MAAM;AACrB,cAAA;AAEJ,UAAA,CAAC,EAAE,OAAO;AACV,UAAA,QAAQ,MAAM,cAAc;AAC5B,UAAA,QAAQ,MAAM,eAAe;AAAA,MACjC;AACA,UAAI,WAAW;AACf,UAAI,QAAQ;AAAA,IAAA,CACb;AAAA,EACH;AACF,CAAC;ACnID,SAAS,cAAc,MAAgC;AAC/C,QAAA,mBAAmB,KAAK,YAAY,GAAG;AAC7C,MAAI,qBAAqB,IAAI;AACpB,WAAA,CAAC,IAAI,IAAI;AAAA,EAClB;AACO,SAAA;AAAA,IACL,KAAK,UAAU,GAAG,gBAAgB;AAAA,IAClC,KAAK,UAAU,mBAAmB,CAAC;AAAA,EAAA;AAEvC;AAEA,SAAS,eACP,WACA,UACA,OAAmB,SACX;AACR,QAAM,SAAS;AAAA,IACb,cAAc,mBAAmB,QAAQ;AAAA,IACzC,UAAU;AAAA,IACV,eAAe;AAAA,IACf,IAAI,aAAA,EAAe,UAAU,CAAC;AAAA,EAAA,EAC9B,KAAK,GAAG;AAEV,SAAO,SAAS,MAAM;AACxB;AAEA,SAAe,WACb,aACA,eACAA,OACA,YACA,SAAkB,OAClB;AAAA;AACI,QAAA;AAEI,YAAA,OAAO,IAAI;AACZ,WAAA,OAAO,SAASA,KAAI;AACzB,UAAI,OAAQ,MAAK,OAAO,aAAa,QAAQ;AAC7C,YAAM,OAAO,MAAM,IAAI,SAAS,iBAAiB;AAAA,QAC/C,QAAQ;AAAA,QACR;AAAA,MAAA,CACD;AAEG,UAAA,KAAK,WAAW,KAAK;AACjB,cAAA,OAAO,MAAM,KAAK;AAExB,YAAI,OAAO,KAAK;AAChB,YAAI,KAAK,UAAkB,QAAA,KAAK,YAAY,MAAM;AAElD,YAAI,CAAC,YAAY,QAAQ,OAAO,SAAS,IAAI,GAAG;AAClC,sBAAA,QAAQ,OAAO,KAAK,IAAI;AAAA,QACtC;AAEA,YAAI,YAAY;AACA,wBAAA,QAAQ,MAAM,IAAI;AAAA,YAC9B,eAAe,GAAG,cAAc,IAAI,CAAC;AAAA,UAAA;AAEvC,sBAAY,QAAQ;AAAA,QACtB;AAAA,MAAA,OACK;AACL,cAAM,KAAK,SAAS,QAAQ,KAAK,UAAU;AAAA,MAC7C;AAAA,aACO,OAAO;AACd,YAAM,KAAK;AAAA,IACb;AAAA,EACF;AAAA;AAIA,IAAI,kBAAkB;AAAA,EACpB,MAAM;AAAA,EACA,sBAAsB,UAAU,UAAU;AAAA;AAE5C,UAAA,CAAC,aAAa,aAAa,cAAc,EAAE,SAAS,SAAS,UAAU,GACvE;AACA,iBAAS,MAAM,SAAS,UAAU,CAAC,UAAU;AAAA,MAC/C;AAAA,IACF;AAAA;AAAA,EACA,mBAAmB;AACV,WAAA;AAAA,MACL,SAAS,MAAM,WAAmB;AAC1B,cAAA,QAAQ,SAAS,cAAc,OAAO;AAC5C,cAAM,WAAW;AACX,cAAA,UAAU,IAAI,aAAa;AAC3B,cAAA,aAAa,QAAQ,OAAO;AAElC,cAAM,gBAA6C,KAAK;AAAA,UACtD;AAAA;AAAA,UACW;AAAA,UACX;AAAA,QAAA;AAIF,sBAAc,YAAY;AAEpB,cAAA,eAAe,KAAK,YAAY,SAAS;AAC/C,YAAI,cAAc;AAEF,wBAAA,QAAQ,UAAU,IAAI,oBAAoB;AAExD,gBAAM,aAAa,KAAK;AACnB,eAAA,aAAa,SAAU,SAAS;AACvB,qDAAA,MAAM,MAAM;AACxB,kBAAM,SAAS,QAAQ;AACvB,gBAAI,CAAC,OAAQ;AACPoB,kBAAAA,SAAQ,OAAO,CAAC;AACR,0BAAA,QAAQ,MAAM,IAAI;AAAA,cAC9B,eAAeA,OAAM,WAAWA,OAAM,UAAUA,OAAM,IAAI;AAAA,YAAA;AAE9C,0BAAA,QAAQ,UAAU,OAAO,oBAAoB;AAAA,UAAA;AAAA,QAE/D;AACO,eAAA,EAAE,QAAQ;MACnB;AAAA,IAAA;AAAA,EAEJ;AAAA,EACA,qBAAqB,aAAkC;AACrD,eAAW,CAAC,QAAQ,MAAM,KAAK,OAAO,QAAQ,WAAW,GAAG;AAC1D,YAAM,OAAO,IAAI,MAAM,YAAY,OAAO,SAAS,MAAM,CAAC;AAC1D,UAAI,WAAW,QAAQ;AACf,cAAA,gBAAgB,KAAK,QAAQ;AAAA,UACjC,CAAC,MAAM,EAAE,SAAS;AAAA,QAAA;AAEd,cAAA,QAAQ,OAAO,MAAM,CAAC;AACd,sBAAA,QAAQ,MAAM,IAAI;AAAA,UAC9B,eAAe,MAAM,WAAW,MAAM,UAAU,MAAM,IAAI;AAAA,QAAA;AAE9C,sBAAA,QAAQ,UAAU,OAAO,oBAAoB;AAAA,MAC7D;AAAA,IACF;AAAA,EACF;AACF,CAAC;AAED,IAAI,kBAAkB;AAAA,EACpB,MAAM;AAAA,EACA,sBAAsB,UAAU,UAAwB;AAAA;;AAC5D,YAAI,4DAAU,UAAV,mBAAiB,aAAjB,mBAA2B,UAA3B,mBAAmC,OAAnC,mBAAuC,kBAAiB,MAAM;AAChE,iBAAS,MAAM,SAAS,SAAS,CAAC,aAAa;AAAA,MACjD;AAAA,IACF;AAAA;AAAA,EACA,mBAAmB;AACV,WAAA;AAAA,MACL,YAAY,MAAM,WAAmB;AAE7B,cAAA,cAAuB,KAAK,QAAQ;AAAA,UACxC,CAAC,MAAe,EAAE,SAAS;AAAA,QAAA;AAEvB,cAAA,gBAA6C,KAAK,QAAQ;AAAA,UAC9D,CAAC,MAAe,EAAE,SAAS;AAAA,QAAA;AAG7B,cAAM,sBAAsB,MAAM;AAClB,wBAAA,QAAQ,MAAM,IAAI;AAAA,YAC9B,eAAe,GAAG,cAAc,YAAY,KAAK,CAAC;AAAA,UAAA;AAAA,QACpD;AAGF,YAAI,YAAY,OAAO;AACD;QACtB;AACA,oBAAY,WAAW;AAGvB,cAAM,oBAAoB,KAAK;AAC/B,aAAK,oBAAoB,WAAY;AAChB,iEAAA,MAAM,MAAM;AAC/B,cAAI,YAAY,OAAO;AACD;UACtB;AAAA,QAAA;AAGI,cAAA,YAAY,SAAS,cAAc,OAAO;AAChD,kBAAU,OAAO;AACjB,kBAAU,SAAS;AACnB,kBAAU,MAAM,UAAU;AAC1B,kBAAU,WAAW,MAAM;AACrB,cAAA,UAAU,MAAM,QAAQ;AAC1B,uBAAW,aAAa,eAAe,UAAU,MAAM,CAAC,GAAG,IAAI;AAAA,UACjE;AAAA,QAAA;AAGF,cAAM,eAAe,KAAK;AAAA,UACxB;AAAA,UACA;AAAA;AAAA,UACY;AAAA,UACZ,MAAM;AACJ,sBAAU,MAAM;AAAA,UAClB;AAAA,QAAA;AAEF,qBAAa,QAAQ;AACrB,qBAAa,YAAY;AAElB,eAAA,EAAE,QAAQ;MACnB;AAAA,IAAA;AAAA,EAEJ;AACF,CAAC;"} \ No newline at end of file diff --git a/web/extensions/core/groupNodeManage.css b/web/assets/index-DjWyclij.css similarity index 100% rename from web/extensions/core/groupNodeManage.css rename to web/assets/index-DjWyclij.css diff --git a/web/assets/primeicons-C6QP2o4f.woff2 b/web/assets/primeicons-C6QP2o4f.woff2 new file mode 100644 index 000000000..26fb21983 Binary files /dev/null and b/web/assets/primeicons-C6QP2o4f.woff2 differ diff --git a/web/assets/primeicons-DMOk5skT.eot b/web/assets/primeicons-DMOk5skT.eot new file mode 100644 index 000000000..6e7e08a33 Binary files /dev/null and b/web/assets/primeicons-DMOk5skT.eot differ diff --git a/web/assets/primeicons-Dr5RGzOO.svg b/web/assets/primeicons-Dr5RGzOO.svg new file mode 100644 index 000000000..fde255ee3 --- /dev/null +++ b/web/assets/primeicons-Dr5RGzOO.svg @@ -0,0 +1,345 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/web/assets/primeicons-MpK4pl85.ttf b/web/assets/primeicons-MpK4pl85.ttf new file mode 100644 index 000000000..06fa9b1ad Binary files /dev/null and b/web/assets/primeicons-MpK4pl85.ttf differ diff --git a/web/assets/primeicons-WjwUDZjB.woff b/web/assets/primeicons-WjwUDZjB.woff new file mode 100644 index 000000000..62c47a2a1 Binary files /dev/null and b/web/assets/primeicons-WjwUDZjB.woff differ diff --git a/web/scripts/ui/userSelection.css b/web/assets/userSelection-BGzn1LuN.css similarity index 96% rename from web/scripts/ui/userSelection.css rename to web/assets/userSelection-BGzn1LuN.css index 35c9d6614..61c4ddb02 100644 --- a/web/scripts/ui/userSelection.css +++ b/web/assets/userSelection-BGzn1LuN.css @@ -50,6 +50,11 @@ margin-top: 10px; } +.comfy-user-selection input::-moz-placeholder { + color: var(--descrip-text); + opacity: 1; +} + .comfy-user-selection input::placeholder { color: var(--descrip-text); opacity: 1; @@ -67,12 +72,8 @@ margin: 10px 0; padding: 10px; display: block; - text-align: center; width: 100%; color: var(--descrip-text); -} - -.comfy-user-selection-inner .or-separator { overflow: hidden; text-align: center; margin-left: -10px; diff --git a/web/assets/userSelection-BifVfRyx.js b/web/assets/userSelection-BifVfRyx.js new file mode 100644 index 000000000..3a4d4ebd6 --- /dev/null +++ b/web/assets/userSelection-BifVfRyx.js @@ -0,0 +1,138 @@ +var __async = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +import { j as createSpinner, g as api, $ as $el } from "./index-DIiqwEjy.js"; +class UserSelectionScreen { + show(users, user) { + return __async(this, null, function* () { + const userSelection = document.getElementById("comfy-user-selection"); + userSelection.style.display = ""; + return new Promise((resolve) => { + const input = userSelection.getElementsByTagName("input")[0]; + const select = userSelection.getElementsByTagName("select")[0]; + const inputSection = input.closest("section"); + const selectSection = select.closest("section"); + const form = userSelection.getElementsByTagName("form")[0]; + const error = userSelection.getElementsByClassName("comfy-user-error")[0]; + const button = userSelection.getElementsByClassName( + "comfy-user-button-next" + )[0]; + let inputActive = null; + input.addEventListener("focus", () => { + inputSection.classList.add("selected"); + selectSection.classList.remove("selected"); + inputActive = true; + }); + select.addEventListener("focus", () => { + inputSection.classList.remove("selected"); + selectSection.classList.add("selected"); + inputActive = false; + select.style.color = ""; + }); + select.addEventListener("blur", () => { + if (!select.value) { + select.style.color = "var(--descrip-text)"; + } + }); + form.addEventListener("submit", (e) => __async(this, null, function* () { + var _a, _b, _c; + e.preventDefault(); + if (inputActive == null) { + error.textContent = "Please enter a username or select an existing user."; + } else if (inputActive) { + const username = input.value.trim(); + if (!username) { + error.textContent = "Please enter a username."; + return; + } + input.disabled = select.disabled = // @ts-expect-error + input.readonly = // @ts-expect-error + select.readonly = true; + const spinner = createSpinner(); + button.prepend(spinner); + try { + const resp = yield api.createUser(username); + if (resp.status >= 300) { + let message = "Error creating user: " + resp.status + " " + resp.statusText; + try { + const res = yield resp.json(); + if (res.error) { + message = res.error; + } + } catch (error2) { + } + throw new Error(message); + } + resolve({ username, userId: yield resp.json(), created: true }); + } catch (err) { + spinner.remove(); + error.textContent = (_c = (_b = (_a = err.message) != null ? _a : err.statusText) != null ? _b : err) != null ? _c : "An unknown error occurred."; + input.disabled = select.disabled = // @ts-expect-error + input.readonly = // @ts-expect-error + select.readonly = false; + return; + } + } else if (!select.value) { + error.textContent = "Please select an existing user."; + return; + } else { + resolve({ + username: users[select.value], + userId: select.value, + created: false + }); + } + })); + if (user) { + const name = localStorage["Comfy.userName"]; + if (name) { + input.value = name; + } + } + if (input.value) { + input.focus(); + } + const userIds = Object.keys(users != null ? users : {}); + if (userIds.length) { + for (const u of userIds) { + $el("option", { textContent: users[u], value: u, parent: select }); + } + select.style.color = "var(--descrip-text)"; + if (select.value) { + select.focus(); + } + } else { + userSelection.classList.add("no-users"); + input.focus(); + } + }).then((r) => { + userSelection.remove(); + return r; + }); + }); + } +} +window.comfyAPI = window.comfyAPI || {}; +window.comfyAPI.userSelection = window.comfyAPI.userSelection || {}; +window.comfyAPI.userSelection.UserSelectionScreen = UserSelectionScreen; +export { + UserSelectionScreen +}; +//# sourceMappingURL=userSelection-BifVfRyx.js.map diff --git a/web/assets/userSelection-BifVfRyx.js.map b/web/assets/userSelection-BifVfRyx.js.map new file mode 100644 index 000000000..372411c30 --- /dev/null +++ b/web/assets/userSelection-BifVfRyx.js.map @@ -0,0 +1 @@ +{"version":3,"file":"userSelection-BifVfRyx.js","sources":["../../src/scripts/ui/userSelection.ts"],"sourcesContent":["import { api } from '../api'\r\nimport { $el } from '../ui'\r\nimport { createSpinner } from './spinner'\r\nimport './userSelection.css'\r\n\r\ninterface SelectedUser {\r\n username: string\r\n userId: string\r\n created: boolean\r\n}\r\n\r\nexport class UserSelectionScreen {\r\n async show(users, user): Promise {\r\n const userSelection = document.getElementById('comfy-user-selection')\r\n userSelection.style.display = ''\r\n return new Promise((resolve) => {\r\n const input = userSelection.getElementsByTagName('input')[0]\r\n const select = userSelection.getElementsByTagName('select')[0]\r\n const inputSection = input.closest('section')\r\n const selectSection = select.closest('section')\r\n const form = userSelection.getElementsByTagName('form')[0]\r\n const error = userSelection.getElementsByClassName('comfy-user-error')[0]\r\n const button = userSelection.getElementsByClassName(\r\n 'comfy-user-button-next'\r\n )[0]\r\n\r\n let inputActive = null\r\n input.addEventListener('focus', () => {\r\n inputSection.classList.add('selected')\r\n selectSection.classList.remove('selected')\r\n inputActive = true\r\n })\r\n select.addEventListener('focus', () => {\r\n inputSection.classList.remove('selected')\r\n selectSection.classList.add('selected')\r\n inputActive = false\r\n select.style.color = ''\r\n })\r\n select.addEventListener('blur', () => {\r\n if (!select.value) {\r\n select.style.color = 'var(--descrip-text)'\r\n }\r\n })\r\n\r\n form.addEventListener('submit', async (e) => {\r\n e.preventDefault()\r\n if (inputActive == null) {\r\n error.textContent =\r\n 'Please enter a username or select an existing user.'\r\n } else if (inputActive) {\r\n const username = input.value.trim()\r\n if (!username) {\r\n error.textContent = 'Please enter a username.'\r\n return\r\n }\r\n\r\n // Create new user\r\n // Property 'readonly' does not exist on type 'HTMLSelectElement'.ts(2339)\r\n // Property 'readonly' does not exist on type 'HTMLInputElement'. Did you mean 'readOnly'?ts(2551)\r\n input.disabled =\r\n select.disabled =\r\n // @ts-expect-error\r\n input.readonly =\r\n // @ts-expect-error\r\n select.readonly =\r\n true\r\n const spinner = createSpinner()\r\n button.prepend(spinner)\r\n try {\r\n const resp = await api.createUser(username)\r\n if (resp.status >= 300) {\r\n let message =\r\n 'Error creating user: ' + resp.status + ' ' + resp.statusText\r\n try {\r\n const res = await resp.json()\r\n if (res.error) {\r\n message = res.error\r\n }\r\n } catch (error) {}\r\n throw new Error(message)\r\n }\r\n\r\n resolve({ username, userId: await resp.json(), created: true })\r\n } catch (err) {\r\n spinner.remove()\r\n error.textContent =\r\n err.message ??\r\n err.statusText ??\r\n err ??\r\n 'An unknown error occurred.'\r\n // Property 'readonly' does not exist on type 'HTMLSelectElement'.ts(2339)\r\n // Property 'readonly' does not exist on type 'HTMLInputElement'. Did you mean 'readOnly'?ts(2551)\r\n input.disabled =\r\n select.disabled =\r\n // @ts-expect-error\r\n input.readonly =\r\n // @ts-expect-error\r\n select.readonly =\r\n false\r\n return\r\n }\r\n } else if (!select.value) {\r\n error.textContent = 'Please select an existing user.'\r\n return\r\n } else {\r\n resolve({\r\n username: users[select.value],\r\n userId: select.value,\r\n created: false\r\n })\r\n }\r\n })\r\n\r\n if (user) {\r\n const name = localStorage['Comfy.userName']\r\n if (name) {\r\n input.value = name\r\n }\r\n }\r\n if (input.value) {\r\n // Focus the input, do this separately as sometimes browsers like to fill in the value\r\n input.focus()\r\n }\r\n\r\n const userIds = Object.keys(users ?? {})\r\n if (userIds.length) {\r\n for (const u of userIds) {\r\n $el('option', { textContent: users[u], value: u, parent: select })\r\n }\r\n select.style.color = 'var(--descrip-text)'\r\n\r\n if (select.value) {\r\n // Focus the select, do this separately as sometimes browsers like to fill in the value\r\n select.focus()\r\n }\r\n } else {\r\n userSelection.classList.add('no-users')\r\n input.focus()\r\n }\r\n }).then((r: SelectedUser) => {\r\n userSelection.remove()\r\n return r\r\n })\r\n }\r\n}\r\n"],"names":["error"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAWO,MAAM,oBAAoB;AAAA,EACzB,KAAK,OAAO,MAA6B;AAAA;AACvC,YAAA,gBAAgB,SAAS,eAAe,sBAAsB;AACpE,oBAAc,MAAM,UAAU;AACvB,aAAA,IAAI,QAAQ,CAAC,YAAY;AAC9B,cAAM,QAAQ,cAAc,qBAAqB,OAAO,EAAE,CAAC;AAC3D,cAAM,SAAS,cAAc,qBAAqB,QAAQ,EAAE,CAAC;AACvD,cAAA,eAAe,MAAM,QAAQ,SAAS;AACtC,cAAA,gBAAgB,OAAO,QAAQ,SAAS;AAC9C,cAAM,OAAO,cAAc,qBAAqB,MAAM,EAAE,CAAC;AACzD,cAAM,QAAQ,cAAc,uBAAuB,kBAAkB,EAAE,CAAC;AACxE,cAAM,SAAS,cAAc;AAAA,UAC3B;AAAA,UACA,CAAC;AAEH,YAAI,cAAc;AACZ,cAAA,iBAAiB,SAAS,MAAM;AACvB,uBAAA,UAAU,IAAI,UAAU;AACvB,wBAAA,UAAU,OAAO,UAAU;AAC3B,wBAAA;AAAA,QAAA,CACf;AACM,eAAA,iBAAiB,SAAS,MAAM;AACxB,uBAAA,UAAU,OAAO,UAAU;AAC1B,wBAAA,UAAU,IAAI,UAAU;AACxB,wBAAA;AACd,iBAAO,MAAM,QAAQ;AAAA,QAAA,CACtB;AACM,eAAA,iBAAiB,QAAQ,MAAM;AAChC,cAAA,CAAC,OAAO,OAAO;AACjB,mBAAO,MAAM,QAAQ;AAAA,UACvB;AAAA,QAAA,CACD;AAEI,aAAA,iBAAiB,UAAU,CAAO,MAAM;;AAC3C,YAAE,eAAe;AACjB,cAAI,eAAe,MAAM;AACvB,kBAAM,cACJ;AAAA,qBACO,aAAa;AAChB,kBAAA,WAAW,MAAM,MAAM,KAAK;AAClC,gBAAI,CAAC,UAAU;AACb,oBAAM,cAAc;AACpB;AAAA,YACF;AAKA,kBAAM,WACJ,OAAO;AAAA,YAEP,MAAM;AAAA,YAEN,OAAO,WACL;AACJ,kBAAM,UAAU;AAChB,mBAAO,QAAQ,OAAO;AAClB,gBAAA;AACF,oBAAM,OAAO,MAAM,IAAI,WAAW,QAAQ;AACtC,kBAAA,KAAK,UAAU,KAAK;AACtB,oBAAI,UACF,0BAA0B,KAAK,SAAS,MAAM,KAAK;AACjD,oBAAA;AACI,wBAAA,MAAM,MAAM,KAAK;AACvB,sBAAI,IAAI,OAAO;AACb,8BAAU,IAAI;AAAA,kBAChB;AAAA,yBACOA,QAAO;AAAA,gBAAC;AACX,sBAAA,IAAI,MAAM,OAAO;AAAA,cACzB;AAEQ,sBAAA,EAAE,UAAU,QAAQ,MAAM,KAAK,QAAQ,SAAS,KAAA,CAAM;AAAA,qBACvD,KAAK;AACZ,sBAAQ,OAAO;AACf,oBAAM,eACJ,qBAAI,YAAJ,YACA,IAAI,eADJ,YAEA,QAFA,YAGA;AAGF,oBAAM,WACJ,OAAO;AAAA,cAEP,MAAM;AAAA,cAEN,OAAO,WACL;AACJ;AAAA,YACF;AAAA,UAAA,WACS,CAAC,OAAO,OAAO;AACxB,kBAAM,cAAc;AACpB;AAAA,UAAA,OACK;AACG,oBAAA;AAAA,cACN,UAAU,MAAM,OAAO,KAAK;AAAA,cAC5B,QAAQ,OAAO;AAAA,cACf,SAAS;AAAA,YAAA,CACV;AAAA,UACH;AAAA,QAAA,EACD;AAED,YAAI,MAAM;AACF,gBAAA,OAAO,aAAa,gBAAgB;AAC1C,cAAI,MAAM;AACR,kBAAM,QAAQ;AAAA,UAChB;AAAA,QACF;AACA,YAAI,MAAM,OAAO;AAEf,gBAAM,MAAM;AAAA,QACd;AAEA,cAAM,UAAU,OAAO,KAAK,wBAAS,CAAE,CAAA;AACvC,YAAI,QAAQ,QAAQ;AAClB,qBAAW,KAAK,SAAS;AACnB,gBAAA,UAAU,EAAE,aAAa,MAAM,CAAC,GAAG,OAAO,GAAG,QAAQ,OAAQ,CAAA;AAAA,UACnE;AACA,iBAAO,MAAM,QAAQ;AAErB,cAAI,OAAO,OAAO;AAEhB,mBAAO,MAAM;AAAA,UACf;AAAA,QAAA,OACK;AACS,wBAAA,UAAU,IAAI,UAAU;AACtC,gBAAM,MAAM;AAAA,QACd;AAAA,MAAA,CACD,EAAE,KAAK,CAAC,MAAoB;AAC3B,sBAAc,OAAO;AACd,eAAA;AAAA,MAAA,CACR;AAAA,IACH;AAAA;AACF;;;;"} \ No newline at end of file diff --git a/web/extensions/core/clipspace.js b/web/extensions/core/clipspace.js index e376a02f7..004b17c5b 100644 --- a/web/extensions/core/clipspace.js +++ b/web/extensions/core/clipspace.js @@ -1,166 +1,2 @@ -import { app } from "../../scripts/app.js"; -import { ComfyDialog, $el } from "../../scripts/ui.js"; -import { ComfyApp } from "../../scripts/app.js"; - -export class ClipspaceDialog extends ComfyDialog { - static items = []; - static instance = null; - - static registerButton(name, contextPredicate, callback) { - const item = - $el("button", { - type: "button", - textContent: name, - contextPredicate: contextPredicate, - onclick: callback - }) - - ClipspaceDialog.items.push(item); - } - - static invalidatePreview() { - if(ComfyApp.clipspace && ComfyApp.clipspace.imgs && ComfyApp.clipspace.imgs.length > 0) { - const img_preview = document.getElementById("clipspace_preview"); - if(img_preview) { - img_preview.src = ComfyApp.clipspace.imgs[ComfyApp.clipspace['selectedIndex']].src; - img_preview.style.maxHeight = "100%"; - img_preview.style.maxWidth = "100%"; - } - } - } - - static invalidate() { - if(ClipspaceDialog.instance) { - const self = ClipspaceDialog.instance; - // allow reconstruct controls when copying from non-image to image content. - const children = $el("div.comfy-modal-content", [ self.createImgSettings(), ...self.createButtons() ]); - - if(self.element) { - // update - self.element.removeChild(self.element.firstChild); - self.element.appendChild(children); - } - else { - // new - self.element = $el("div.comfy-modal", { parent: document.body }, [children,]); - } - - if(self.element.children[0].children.length <= 1) { - self.element.children[0].appendChild($el("p", {}, ["Unable to find the features to edit content of a format stored in the current Clipspace."])); - } - - ClipspaceDialog.invalidatePreview(); - } - } - - constructor() { - super(); - } - - createButtons(self) { - const buttons = []; - - for(let idx in ClipspaceDialog.items) { - const item = ClipspaceDialog.items[idx]; - if(!item.contextPredicate || item.contextPredicate()) - buttons.push(ClipspaceDialog.items[idx]); - } - - buttons.push( - $el("button", { - type: "button", - textContent: "Close", - onclick: () => { this.close(); } - }) - ); - - return buttons; - } - - createImgSettings() { - if(ComfyApp.clipspace.imgs) { - const combo_items = []; - const imgs = ComfyApp.clipspace.imgs; - - for(let i=0; i < imgs.length; i++) { - combo_items.push($el("option", {value:i}, [`${i}`])); - } - - const combo1 = $el("select", - {id:"clipspace_img_selector", onchange:(event) => { - ComfyApp.clipspace['selectedIndex'] = event.target.selectedIndex; - ClipspaceDialog.invalidatePreview(); - } }, combo_items); - - const row1 = - $el("tr", {}, - [ - $el("td", {}, [$el("font", {color:"white"}, ["Select Image"])]), - $el("td", {}, [combo1]) - ]); - - - const combo2 = $el("select", - {id:"clipspace_img_paste_mode", onchange:(event) => { - ComfyApp.clipspace['img_paste_mode'] = event.target.value; - } }, - [ - $el("option", {value:'selected'}, 'selected'), - $el("option", {value:'all'}, 'all') - ]); - combo2.value = ComfyApp.clipspace['img_paste_mode']; - - const row2 = - $el("tr", {}, - [ - $el("td", {}, [$el("font", {color:"white"}, ["Paste Mode"])]), - $el("td", {}, [combo2]) - ]); - - const td = $el("td", {align:'center', width:'100px', height:'100px', colSpan:'2'}, - [ $el("img",{id:"clipspace_preview", ondragstart:() => false},[]) ]); - - const row3 = - $el("tr", {}, [td]); - - return $el("table", {}, [row1, row2, row3]); - } - else { - return []; - } - } - - createImgPreview() { - if(ComfyApp.clipspace.imgs) { - return $el("img",{id:"clipspace_preview", ondragstart:() => false}); - } - else - return []; - } - - show() { - const img_preview = document.getElementById("clipspace_preview"); - ClipspaceDialog.invalidate(); - - this.element.style.display = "block"; - } -} - -app.registerExtension({ - name: "Comfy.Clipspace", - init(app) { - app.openClipspace = - function () { - if(!ClipspaceDialog.instance) { - ClipspaceDialog.instance = new ClipspaceDialog(app); - ComfyApp.clipspace_invalidate_handler = ClipspaceDialog.invalidate; - } - - if(ComfyApp.clipspace) { - ClipspaceDialog.instance.show(); - } - else - app.ui.dialog.show("Clipspace is Empty!"); - }; - } -}); \ No newline at end of file +// Shim for extensions\core\clipspace.ts +export const ClipspaceDialog = window.comfyAPI.clipspace.ClipspaceDialog; diff --git a/web/extensions/core/colorPalette.js b/web/extensions/core/colorPalette.js deleted file mode 100644 index 245f3b93e..000000000 --- a/web/extensions/core/colorPalette.js +++ /dev/null @@ -1,785 +0,0 @@ -import {app} from "../../scripts/app.js"; -import {$el} from "../../scripts/ui.js"; - -// Manage color palettes - -const colorPalettes = { - "dark": { - "id": "dark", - "name": "Dark (Default)", - "colors": { - "node_slot": { - "CLIP": "#FFD500", // bright yellow - "CLIP_VISION": "#A8DADC", // light blue-gray - "CLIP_VISION_OUTPUT": "#ad7452", // rusty brown-orange - "CONDITIONING": "#FFA931", // vibrant orange-yellow - "CONTROL_NET": "#6EE7B7", // soft mint green - "IMAGE": "#64B5F6", // bright sky blue - "LATENT": "#FF9CF9", // light pink-purple - "MASK": "#81C784", // muted green - "MODEL": "#B39DDB", // light lavender-purple - "STYLE_MODEL": "#C2FFAE", // light green-yellow - "VAE": "#FF6E6E", // bright red - "NOISE": "#B0B0B0", // gray - "GUIDER": "#66FFFF", // cyan - "SAMPLER": "#ECB4B4", // very soft red - "SIGMAS": "#CDFFCD", // soft lime green - "TAESD": "#DCC274", // cheesecake - }, - "litegraph_base": { - "BACKGROUND_IMAGE": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAQBJREFUeNrs1rEKwjAUhlETUkj3vP9rdmr1Ysammk2w5wdxuLgcMHyptfawuZX4pJSWZTnfnu/lnIe/jNNxHHGNn//HNbbv+4dr6V+11uF527arU7+u63qfa/bnmh8sWLBgwYJlqRf8MEptXPBXJXa37BSl3ixYsGDBMliwFLyCV/DeLIMFCxYsWLBMwSt4Be/NggXLYMGCBUvBK3iNruC9WbBgwYJlsGApeAWv4L1ZBgsWLFiwYJmCV/AK3psFC5bBggULloJX8BpdwXuzYMGCBctgwVLwCl7Be7MMFixYsGDBsu8FH1FaSmExVfAxBa/gvVmwYMGCZbBg/W4vAQYA5tRF9QYlv/QAAAAASUVORK5CYII=", - "CLEAR_BACKGROUND_COLOR": "#222", - "NODE_TITLE_COLOR": "#999", - "NODE_SELECTED_TITLE_COLOR": "#FFF", - "NODE_TEXT_SIZE": 14, - "NODE_TEXT_COLOR": "#AAA", - "NODE_SUBTEXT_SIZE": 12, - "NODE_DEFAULT_COLOR": "#333", - "NODE_DEFAULT_BGCOLOR": "#353535", - "NODE_DEFAULT_BOXCOLOR": "#666", - "NODE_DEFAULT_SHAPE": "box", - "NODE_BOX_OUTLINE_COLOR": "#FFF", - "DEFAULT_SHADOW_COLOR": "rgba(0,0,0,0.5)", - "DEFAULT_GROUP_FONT": 24, - - "WIDGET_BGCOLOR": "#222", - "WIDGET_OUTLINE_COLOR": "#666", - "WIDGET_TEXT_COLOR": "#DDD", - "WIDGET_SECONDARY_TEXT_COLOR": "#999", - - "LINK_COLOR": "#9A9", - "EVENT_LINK_COLOR": "#A86", - "CONNECTING_LINK_COLOR": "#AFA", - }, - "comfy_base": { - "fg-color": "#fff", - "bg-color": "#202020", - "comfy-menu-bg": "#353535", - "comfy-input-bg": "#222", - "input-text": "#ddd", - "descrip-text": "#999", - "drag-text": "#ccc", - "error-text": "#ff4444", - "border-color": "#4e4e4e", - "tr-even-bg-color": "#222", - "tr-odd-bg-color": "#353535", - "content-bg": "#4e4e4e", - "content-fg": "#fff", - "content-hover-bg": "#222", - "content-hover-fg": "#fff" - } - }, - }, - "light": { - "id": "light", - "name": "Light", - "colors": { - "node_slot": { - "CLIP": "#FFA726", // orange - "CLIP_VISION": "#5C6BC0", // indigo - "CLIP_VISION_OUTPUT": "#8D6E63", // brown - "CONDITIONING": "#EF5350", // red - "CONTROL_NET": "#66BB6A", // green - "IMAGE": "#42A5F5", // blue - "LATENT": "#AB47BC", // purple - "MASK": "#9CCC65", // light green - "MODEL": "#7E57C2", // deep purple - "STYLE_MODEL": "#D4E157", // lime - "VAE": "#FF7043", // deep orange - }, - "litegraph_base": { - "BACKGROUND_IMAGE": "data:image/gif;base64,R0lGODlhZABkALMAAAAAAP///+vr6+rq6ujo6Ofn5+bm5uXl5d3d3f///wAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAAkALAAAAABkAGQAAAT/UMhJq7046827HkcoHkYxjgZhnGG6si5LqnIM0/fL4qwwIMAg0CAsEovBIxKhRDaNy2GUOX0KfVFrssrNdpdaqTeKBX+dZ+jYvEaTf+y4W66mC8PUdrE879f9d2mBeoNLfH+IhYBbhIx2jkiHiomQlGKPl4uZe3CaeZifnnijgkESBqipqqusra6vsLGys62SlZO4t7qbuby7CLa+wqGWxL3Gv3jByMOkjc2lw8vOoNSi0czAncXW3Njdx9Pf48/Z4Kbbx+fQ5evZ4u3k1fKR6cn03vHlp7T9/v8A/8Gbp4+gwXoFryXMB2qgwoMMHyKEqA5fxX322FG8tzBcRnMW/zlulPbRncmQGidKjMjyYsOSKEF2FBlJQMCbOHP6c9iSZs+UnGYCdbnSo1CZI5F64kn0p1KnTH02nSoV3dGTV7FFHVqVq1dtWcMmVQZTbNGu72zqXMuW7danVL+6e4t1bEy6MeueBYLXrNO5Ze36jQtWsOG97wIj1vt3St/DjTEORss4nNq2mDP3e7w4r1bFkSET5hy6s2TRlD2/mSxXtSHQhCunXo26NevCpmvD/UU6tuullzULH76q92zdZG/Ltv1a+W+osI/nRmyc+fRi1Xdbh+68+0vv10dH3+77KD/i6IdnX669/frn5Zsjh4/2PXju8+8bzc9/6fj27LFnX11/+IUnXWl7BJfegm79FyB9JOl3oHgSklefgxAC+FmFGpqHIYcCfkhgfCohSKKJVo044YUMttggiBkmp6KFXw1oII24oYhjiDByaKOOHcp3Y5BD/njikSkO+eBREQAAOw==", - "CLEAR_BACKGROUND_COLOR": "lightgray", - "NODE_TITLE_COLOR": "#222", - "NODE_SELECTED_TITLE_COLOR": "#000", - "NODE_TEXT_SIZE": 14, - "NODE_TEXT_COLOR": "#444", - "NODE_SUBTEXT_SIZE": 12, - "NODE_DEFAULT_COLOR": "#F7F7F7", - "NODE_DEFAULT_BGCOLOR": "#F5F5F5", - "NODE_DEFAULT_BOXCOLOR": "#CCC", - "NODE_DEFAULT_SHAPE": "box", - "NODE_BOX_OUTLINE_COLOR": "#000", - "DEFAULT_SHADOW_COLOR": "rgba(0,0,0,0.1)", - "DEFAULT_GROUP_FONT": 24, - - "WIDGET_BGCOLOR": "#D4D4D4", - "WIDGET_OUTLINE_COLOR": "#999", - "WIDGET_TEXT_COLOR": "#222", - "WIDGET_SECONDARY_TEXT_COLOR": "#555", - - "LINK_COLOR": "#4CAF50", - "EVENT_LINK_COLOR": "#FF9800", - "CONNECTING_LINK_COLOR": "#2196F3", - }, - "comfy_base": { - "fg-color": "#222", - "bg-color": "#DDD", - "comfy-menu-bg": "#F5F5F5", - "comfy-input-bg": "#C9C9C9", - "input-text": "#222", - "descrip-text": "#444", - "drag-text": "#555", - "error-text": "#F44336", - "border-color": "#888", - "tr-even-bg-color": "#f9f9f9", - "tr-odd-bg-color": "#fff", - "content-bg": "#e0e0e0", - "content-fg": "#222", - "content-hover-bg": "#adadad", - "content-hover-fg": "#222" - } - }, - }, - "solarized": { - "id": "solarized", - "name": "Solarized", - "colors": { - "node_slot": { - "CLIP": "#2AB7CA", // light blue - "CLIP_VISION": "#6c71c4", // blue violet - "CLIP_VISION_OUTPUT": "#859900", // olive green - "CONDITIONING": "#d33682", // magenta - "CONTROL_NET": "#d1ffd7", // light mint green - "IMAGE": "#5940bb", // deep blue violet - "LATENT": "#268bd2", // blue - "MASK": "#CCC9E7", // light purple-gray - "MODEL": "#dc322f", // red - "STYLE_MODEL": "#1a998a", // teal - "UPSCALE_MODEL": "#054A29", // dark green - "VAE": "#facfad", // light pink-orange - }, - "litegraph_base": { - "NODE_TITLE_COLOR": "#fdf6e3", // Base3 - "NODE_SELECTED_TITLE_COLOR": "#A9D400", - "NODE_TEXT_SIZE": 14, - "NODE_TEXT_COLOR": "#657b83", // Base00 - "NODE_SUBTEXT_SIZE": 12, - "NODE_DEFAULT_COLOR": "#094656", - "NODE_DEFAULT_BGCOLOR": "#073642", // Base02 - "NODE_DEFAULT_BOXCOLOR": "#839496", // Base0 - "NODE_DEFAULT_SHAPE": "box", - "NODE_BOX_OUTLINE_COLOR": "#fdf6e3", // Base3 - "DEFAULT_SHADOW_COLOR": "rgba(0,0,0,0.5)", - "DEFAULT_GROUP_FONT": 24, - - "WIDGET_BGCOLOR": "#002b36", // Base03 - "WIDGET_OUTLINE_COLOR": "#839496", // Base0 - "WIDGET_TEXT_COLOR": "#fdf6e3", // Base3 - "WIDGET_SECONDARY_TEXT_COLOR": "#93a1a1", // Base1 - - "LINK_COLOR": "#2aa198", // Solarized Cyan - "EVENT_LINK_COLOR": "#268bd2", // Solarized Blue - "CONNECTING_LINK_COLOR": "#859900", // Solarized Green - }, - "comfy_base": { - "fg-color": "#fdf6e3", // Base3 - "bg-color": "#002b36", // Base03 - "comfy-menu-bg": "#073642", // Base02 - "comfy-input-bg": "#002b36", // Base03 - "input-text": "#93a1a1", // Base1 - "descrip-text": "#586e75", // Base01 - "drag-text": "#839496", // Base0 - "error-text": "#dc322f", // Solarized Red - "border-color": "#657b83", // Base00 - "tr-even-bg-color": "#002b36", - "tr-odd-bg-color": "#073642", - "content-bg": "#657b83", - "content-fg": "#fdf6e3", - "content-hover-bg": "#002b36", - "content-hover-fg": "#fdf6e3" - } - }, - }, - "arc": { - "id": "arc", - "name": "Arc", - "colors": { - "node_slot": { - "BOOLEAN": "", - "CLIP": "#eacb8b", - "CLIP_VISION": "#A8DADC", - "CLIP_VISION_OUTPUT": "#ad7452", - "CONDITIONING": "#cf876f", - "CONTROL_NET": "#00d78d", - "CONTROL_NET_WEIGHTS": "", - "FLOAT": "", - "GLIGEN": "", - "IMAGE": "#80a1c0", - "IMAGEUPLOAD": "", - "INT": "", - "LATENT": "#b38ead", - "LATENT_KEYFRAME": "", - "MASK": "#a3bd8d", - "MODEL": "#8978a7", - "SAMPLER": "", - "SIGMAS": "", - "STRING": "", - "STYLE_MODEL": "#C2FFAE", - "T2I_ADAPTER_WEIGHTS": "", - "TAESD": "#DCC274", - "TIMESTEP_KEYFRAME": "", - "UPSCALE_MODEL": "", - "VAE": "#be616b" - }, - "litegraph_base": { - "BACKGROUND_IMAGE": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAACXBIWXMAAAsTAAALEwEAmpwYAAABcklEQVR4nO3YMUoDARgF4RfxBqZI6/0vZqFn0MYtrLIQMFN8U6V4LAtD+Jm9XG/v30OGl2e/AP7yevz4+vx45nvgF/+QGITEICQGITEIiUFIjNNC3q43u3/YnRJyPOzeQ+0e220nhRzReC8e7R7bbdvl+Jal1Bs46jEIiUFIDEJiEBKDkBhKPbZT6qHdptRTu02p53DUYxASg5AYhMQgJAYhMZR6bKfUQ7tNqad2m1LP4ajHICQGITEIiUFIDEJiKPXYTqmHdptST+02pZ7DUY9BSAxCYhASg5AYhMRQ6rGdUg/tNqWe2m1KPYejHoOQGITEICQGITEIiaHUYzulHtptSj2125R6Dkc9BiExCIlBSAxCYhASQ6nHdko9tNuUemq3KfUcjnoMQmIQEoOQGITEICSGUo/tlHpotyn11G5T6jkc9RiExCAkBiExCIlBSAylHtsp9dBuU+qp3abUczjqMQiJQUgMQmIQEoOQGITE+AHFISNQrFTGuwAAAABJRU5ErkJggg==", - "CLEAR_BACKGROUND_COLOR": "#2b2f38", - "NODE_TITLE_COLOR": "#b2b7bd", - "NODE_SELECTED_TITLE_COLOR": "#FFF", - "NODE_TEXT_SIZE": 14, - "NODE_TEXT_COLOR": "#AAA", - "NODE_SUBTEXT_SIZE": 12, - "NODE_DEFAULT_COLOR": "#2b2f38", - "NODE_DEFAULT_BGCOLOR": "#242730", - "NODE_DEFAULT_BOXCOLOR": "#6e7581", - "NODE_DEFAULT_SHAPE": "box", - "NODE_BOX_OUTLINE_COLOR": "#FFF", - "DEFAULT_SHADOW_COLOR": "rgba(0,0,0,0.5)", - "DEFAULT_GROUP_FONT": 22, - "WIDGET_BGCOLOR": "#2b2f38", - "WIDGET_OUTLINE_COLOR": "#6e7581", - "WIDGET_TEXT_COLOR": "#DDD", - "WIDGET_SECONDARY_TEXT_COLOR": "#b2b7bd", - "LINK_COLOR": "#9A9", - "EVENT_LINK_COLOR": "#A86", - "CONNECTING_LINK_COLOR": "#AFA" - }, - "comfy_base": { - "fg-color": "#fff", - "bg-color": "#2b2f38", - "comfy-menu-bg": "#242730", - "comfy-input-bg": "#2b2f38", - "input-text": "#ddd", - "descrip-text": "#b2b7bd", - "drag-text": "#ccc", - "error-text": "#ff4444", - "border-color": "#6e7581", - "tr-even-bg-color": "#2b2f38", - "tr-odd-bg-color": "#242730", - "content-bg": "#6e7581", - "content-fg": "#fff", - "content-hover-bg": "#2b2f38", - "content-hover-fg": "#fff" - } - }, - }, - "nord": { - "id": "nord", - "name": "Nord", - "colors": { - "node_slot": { - "BOOLEAN": "", - "CLIP": "#eacb8b", - "CLIP_VISION": "#A8DADC", - "CLIP_VISION_OUTPUT": "#ad7452", - "CONDITIONING": "#cf876f", - "CONTROL_NET": "#00d78d", - "CONTROL_NET_WEIGHTS": "", - "FLOAT": "", - "GLIGEN": "", - "IMAGE": "#80a1c0", - "IMAGEUPLOAD": "", - "INT": "", - "LATENT": "#b38ead", - "LATENT_KEYFRAME": "", - "MASK": "#a3bd8d", - "MODEL": "#8978a7", - "SAMPLER": "", - "SIGMAS": "", - "STRING": "", - "STYLE_MODEL": "#C2FFAE", - "T2I_ADAPTER_WEIGHTS": "", - "TAESD": "#DCC274", - "TIMESTEP_KEYFRAME": "", - "UPSCALE_MODEL": "", - "VAE": "#be616b" - }, - "litegraph_base": { - "BACKGROUND_IMAGE": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAAAACXBIWXMAAAsTAAALEwEAmpwYAAAFu2lUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4gPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iQWRvYmUgWE1QIENvcmUgOS4xLWMwMDEgNzkuMTQ2Mjg5OSwgMjAyMy8wNi8yNS0yMDowMTo1NSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczpkYz0iaHR0cDovL3B1cmwub3JnL2RjL2VsZW1lbnRzLzEuMS8iIHhtbG5zOnBob3Rvc2hvcD0iaHR0cDovL25zLmFkb2JlLmNvbS9waG90b3Nob3AvMS4wLyIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0RXZ0PSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VFdmVudCMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIDI1LjEgKFdpbmRvd3MpIiB4bXA6Q3JlYXRlRGF0ZT0iMjAyMy0xMS0xM1QwMDoxODowMiswMTowMCIgeG1wOk1vZGlmeURhdGU9IjIwMjMtMTEtMTVUMDE6MjA6NDUrMDE6MDAiIHhtcDpNZXRhZGF0YURhdGU9IjIwMjMtMTEtMTVUMDE6MjA6NDUrMDE6MDAiIGRjOmZvcm1hdD0iaW1hZ2UvcG5nIiBwaG90b3Nob3A6Q29sb3JNb2RlPSIzIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOjUwNDFhMmZjLTEzNzQtMTk0ZC1hZWY4LTYxMzM1MTVmNjUwMCIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDoyMzFiMTBiMC1iNGZiLTAyNGUtYjEyZS0zMDUzMDNjZDA3YzgiIHhtcE1NOk9yaWdpbmFsRG9jdW1lbnRJRD0ieG1wLmRpZDoyMzFiMTBiMC1iNGZiLTAyNGUtYjEyZS0zMDUzMDNjZDA3YzgiPiA8eG1wTU06SGlzdG9yeT4gPHJkZjpTZXE+IDxyZGY6bGkgc3RFdnQ6YWN0aW9uPSJjcmVhdGVkIiBzdEV2dDppbnN0YW5jZUlEPSJ4bXAuaWlkOjIzMWIxMGIwLWI0ZmItMDI0ZS1iMTJlLTMwNTMwM2NkMDdjOCIgc3RFdnQ6d2hlbj0iMjAyMy0xMS0xM1QwMDoxODowMiswMTowMCIgc3RFdnQ6c29mdHdhcmVBZ2VudD0iQWRvYmUgUGhvdG9zaG9wIDI1LjEgKFdpbmRvd3MpIi8+IDxyZGY6bGkgc3RFdnQ6YWN0aW9uPSJzYXZlZCIgc3RFdnQ6aW5zdGFuY2VJRD0ieG1wLmlpZDo1MDQxYTJmYy0xMzc0LTE5NGQtYWVmOC02MTMzNTE1ZjY1MDAiIHN0RXZ0OndoZW49IjIwMjMtMTEtMTVUMDE6MjA6NDUrMDE6MDAiIHN0RXZ0OnNvZnR3YXJlQWdlbnQ9IkFkb2JlIFBob3Rvc2hvcCAyNS4xIChXaW5kb3dzKSIgc3RFdnQ6Y2hhbmdlZD0iLyIvPiA8L3JkZjpTZXE+IDwveG1wTU06SGlzdG9yeT4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz73jWg/AAAAyUlEQVR42u3WKwoAIBRFQRdiMb1idv9Lsxn9gEFw4Dbb8JCTojbbXEJwjJVL2HKwYMGCBQuWLbDmjr+9zrBGjHl1WVcvy2DBggULFizTWQpewSt4HzwsgwULFiwFr7MUvMtS8D54WLBgGSxYCl7BK3iXZbBgwYIFC5bpLAWv4BW8Dx6WwYIFC5aC11kK3mUpeB88LFiwDBYsBa/gFbzLMliwYMGCBct0loJX8AreBw/LYMGCBUvB6ywF77IUvA8eFixYBgsWrNfWAZPltufdad+1AAAAAElFTkSuQmCC", - "CLEAR_BACKGROUND_COLOR": "#212732", - "NODE_TITLE_COLOR": "#999", - "NODE_SELECTED_TITLE_COLOR": "#e5eaf0", - "NODE_TEXT_SIZE": 14, - "NODE_TEXT_COLOR": "#bcc2c8", - "NODE_SUBTEXT_SIZE": 12, - "NODE_DEFAULT_COLOR": "#2e3440", - "NODE_DEFAULT_BGCOLOR": "#161b22", - "NODE_DEFAULT_BOXCOLOR": "#545d70", - "NODE_DEFAULT_SHAPE": "box", - "NODE_BOX_OUTLINE_COLOR": "#e5eaf0", - "DEFAULT_SHADOW_COLOR": "rgba(0,0,0,0.5)", - "DEFAULT_GROUP_FONT": 24, - "WIDGET_BGCOLOR": "#2e3440", - "WIDGET_OUTLINE_COLOR": "#545d70", - "WIDGET_TEXT_COLOR": "#bcc2c8", - "WIDGET_SECONDARY_TEXT_COLOR": "#999", - "LINK_COLOR": "#9A9", - "EVENT_LINK_COLOR": "#A86", - "CONNECTING_LINK_COLOR": "#AFA" - }, - "comfy_base": { - "fg-color": "#e5eaf0", - "bg-color": "#2e3440", - "comfy-menu-bg": "#161b22", - "comfy-input-bg": "#2e3440", - "input-text": "#bcc2c8", - "descrip-text": "#999", - "drag-text": "#ccc", - "error-text": "#ff4444", - "border-color": "#545d70", - "tr-even-bg-color": "#2e3440", - "tr-odd-bg-color": "#161b22", - "content-bg": "#545d70", - "content-fg": "#e5eaf0", - "content-hover-bg": "#2e3440", - "content-hover-fg": "#e5eaf0" - } - }, - }, - "github": { - "id": "github", - "name": "Github", - "colors": { - "node_slot": { - "BOOLEAN": "", - "CLIP": "#eacb8b", - "CLIP_VISION": "#A8DADC", - "CLIP_VISION_OUTPUT": "#ad7452", - "CONDITIONING": "#cf876f", - "CONTROL_NET": "#00d78d", - "CONTROL_NET_WEIGHTS": "", - "FLOAT": "", - "GLIGEN": "", - "IMAGE": "#80a1c0", - "IMAGEUPLOAD": "", - "INT": "", - "LATENT": "#b38ead", - "LATENT_KEYFRAME": "", - "MASK": "#a3bd8d", - "MODEL": "#8978a7", - "SAMPLER": "", - "SIGMAS": "", - "STRING": "", - "STYLE_MODEL": "#C2FFAE", - "T2I_ADAPTER_WEIGHTS": "", - "TAESD": "#DCC274", - "TIMESTEP_KEYFRAME": "", - "UPSCALE_MODEL": "", - "VAE": "#be616b" - }, - "litegraph_base": { - "BACKGROUND_IMAGE": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAAAACXBIWXMAAAsTAAALEwEAmpwYAAAGlmlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4gPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iQWRvYmUgWE1QIENvcmUgOS4xLWMwMDEgNzkuMTQ2Mjg5OSwgMjAyMy8wNi8yNS0yMDowMTo1NSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczpkYz0iaHR0cDovL3B1cmwub3JnL2RjL2VsZW1lbnRzLzEuMS8iIHhtbG5zOnBob3Rvc2hvcD0iaHR0cDovL25zLmFkb2JlLmNvbS9waG90b3Nob3AvMS4wLyIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0RXZ0PSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VFdmVudCMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIDI1LjEgKFdpbmRvd3MpIiB4bXA6Q3JlYXRlRGF0ZT0iMjAyMy0xMS0xM1QwMDoxODowMiswMTowMCIgeG1wOk1vZGlmeURhdGU9IjIwMjMtMTEtMTVUMDI6MDQ6NTkrMDE6MDAiIHhtcDpNZXRhZGF0YURhdGU9IjIwMjMtMTEtMTVUMDI6MDQ6NTkrMDE6MDAiIGRjOmZvcm1hdD0iaW1hZ2UvcG5nIiBwaG90b3Nob3A6Q29sb3JNb2RlPSIzIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOmIyYzRhNjA5LWJmYTctYTg0MC1iOGFlLTk3MzE2ZjM1ZGIyNyIgeG1wTU06RG9jdW1lbnRJRD0iYWRvYmU6ZG9jaWQ6cGhvdG9zaG9wOjk0ZmNlZGU4LTE1MTctZmQ0MC04ZGU3LWYzOTgxM2E3ODk5ZiIgeG1wTU06T3JpZ2luYWxEb2N1bWVudElEPSJ4bXAuZGlkOjIzMWIxMGIwLWI0ZmItMDI0ZS1iMTJlLTMwNTMwM2NkMDdjOCI+IDx4bXBNTTpIaXN0b3J5PiA8cmRmOlNlcT4gPHJkZjpsaSBzdEV2dDphY3Rpb249ImNyZWF0ZWQiIHN0RXZ0Omluc3RhbmNlSUQ9InhtcC5paWQ6MjMxYjEwYjAtYjRmYi0wMjRlLWIxMmUtMzA1MzAzY2QwN2M4IiBzdEV2dDp3aGVuPSIyMDIzLTExLTEzVDAwOjE4OjAyKzAxOjAwIiBzdEV2dDpzb2Z0d2FyZUFnZW50PSJBZG9iZSBQaG90b3Nob3AgMjUuMSAoV2luZG93cykiLz4gPHJkZjpsaSBzdEV2dDphY3Rpb249InNhdmVkIiBzdEV2dDppbnN0YW5jZUlEPSJ4bXAuaWlkOjQ4OWY1NzlmLTJkNjUtZWQ0Zi04OTg0LTA4NGE2MGE1ZTMzNSIgc3RFdnQ6d2hlbj0iMjAyMy0xMS0xNVQwMjowNDo1OSswMTowMCIgc3RFdnQ6c29mdHdhcmVBZ2VudD0iQWRvYmUgUGhvdG9zaG9wIDI1LjEgKFdpbmRvd3MpIiBzdEV2dDpjaGFuZ2VkPSIvIi8+IDxyZGY6bGkgc3RFdnQ6YWN0aW9uPSJzYXZlZCIgc3RFdnQ6aW5zdGFuY2VJRD0ieG1wLmlpZDpiMmM0YTYwOS1iZmE3LWE4NDAtYjhhZS05NzMxNmYzNWRiMjciIHN0RXZ0OndoZW49IjIwMjMtMTEtMTVUMDI6MDQ6NTkrMDE6MDAiIHN0RXZ0OnNvZnR3YXJlQWdlbnQ9IkFkb2JlIFBob3Rvc2hvcCAyNS4xIChXaW5kb3dzKSIgc3RFdnQ6Y2hhbmdlZD0iLyIvPiA8L3JkZjpTZXE+IDwveG1wTU06SGlzdG9yeT4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz4OTe6GAAAAx0lEQVR42u3WMQoAIQxFwRzJys77X8vSLiRgITif7bYbgrwYc/mKXyBoY4VVBgsWLFiwYFmOlTv+9jfDOjHmr8u6eVkGCxYsWLBgmc5S8ApewXvgYRksWLBgKXidpeBdloL3wMOCBctgwVLwCl7BuyyDBQsWLFiwTGcpeAWv4D3wsAwWLFiwFLzOUvAuS8F74GHBgmWwYCl4Ba/gXZbBggULFixYprMUvIJX8B54WAYLFixYCl5nKXiXpeA98LBgwTJYsGC9tg1o8f4TTtqzNQAAAABJRU5ErkJggg==", - "CLEAR_BACKGROUND_COLOR": "#040506", - "NODE_TITLE_COLOR": "#999", - "NODE_SELECTED_TITLE_COLOR": "#e5eaf0", - "NODE_TEXT_SIZE": 14, - "NODE_TEXT_COLOR": "#bcc2c8", - "NODE_SUBTEXT_SIZE": 12, - "NODE_DEFAULT_COLOR": "#161b22", - "NODE_DEFAULT_BGCOLOR": "#13171d", - "NODE_DEFAULT_BOXCOLOR": "#30363d", - "NODE_DEFAULT_SHAPE": "box", - "NODE_BOX_OUTLINE_COLOR": "#e5eaf0", - "DEFAULT_SHADOW_COLOR": "rgba(0,0,0,0.5)", - "DEFAULT_GROUP_FONT": 24, - "WIDGET_BGCOLOR": "#161b22", - "WIDGET_OUTLINE_COLOR": "#30363d", - "WIDGET_TEXT_COLOR": "#bcc2c8", - "WIDGET_SECONDARY_TEXT_COLOR": "#999", - "LINK_COLOR": "#9A9", - "EVENT_LINK_COLOR": "#A86", - "CONNECTING_LINK_COLOR": "#AFA" - }, - "comfy_base": { - "fg-color": "#e5eaf0", - "bg-color": "#161b22", - "comfy-menu-bg": "#13171d", - "comfy-input-bg": "#161b22", - "input-text": "#bcc2c8", - "descrip-text": "#999", - "drag-text": "#ccc", - "error-text": "#ff4444", - "border-color": "#30363d", - "tr-even-bg-color": "#161b22", - "tr-odd-bg-color": "#13171d", - "content-bg": "#30363d", - "content-fg": "#e5eaf0", - "content-hover-bg": "#161b22", - "content-hover-fg": "#e5eaf0" - } - }, - } -}; - -const id = "Comfy.ColorPalette"; -const idCustomColorPalettes = "Comfy.CustomColorPalettes"; -const defaultColorPaletteId = "dark"; -const els = {} -// const ctxMenu = LiteGraph.ContextMenu; -app.registerExtension({ - name: id, - addCustomNodeDefs(node_defs) { - const sortObjectKeys = (unordered) => { - return Object.keys(unordered).sort().reduce((obj, key) => { - obj[key] = unordered[key]; - return obj; - }, {}); - }; - - function getSlotTypes() { - var types = []; - - const defs = node_defs; - for (const nodeId in defs) { - const nodeData = defs[nodeId]; - - var inputs = nodeData["input"]["required"]; - if (nodeData["input"]["optional"] !== undefined) { - inputs = Object.assign({}, nodeData["input"]["required"], nodeData["input"]["optional"]) - } - - for (const inputName in inputs) { - const inputData = inputs[inputName]; - const type = inputData[0]; - - if (!Array.isArray(type)) { - types.push(type); - } - } - - for (const o in nodeData["output"]) { - const output = nodeData["output"][o]; - types.push(output); - } - } - - return types; - } - - function completeColorPalette(colorPalette) { - var types = getSlotTypes(); - - for (const type of types) { - if (!colorPalette.colors.node_slot[type]) { - colorPalette.colors.node_slot[type] = ""; - } - } - - colorPalette.colors.node_slot = sortObjectKeys(colorPalette.colors.node_slot); - - return colorPalette; - } - - const getColorPaletteTemplate = async () => { - let colorPalette = { - "id": "my_color_palette_unique_id", - "name": "My Color Palette", - "colors": { - "node_slot": {}, - "litegraph_base": {}, - "comfy_base": {} - } - }; - - // Copy over missing keys from default color palette - const defaultColorPalette = colorPalettes[defaultColorPaletteId]; - for (const key in defaultColorPalette.colors.litegraph_base) { - if (!colorPalette.colors.litegraph_base[key]) { - colorPalette.colors.litegraph_base[key] = ""; - } - } - for (const key in defaultColorPalette.colors.comfy_base) { - if (!colorPalette.colors.comfy_base[key]) { - colorPalette.colors.comfy_base[key] = ""; - } - } - - return completeColorPalette(colorPalette); - }; - - const getCustomColorPalettes = () => { - return app.ui.settings.getSettingValue(idCustomColorPalettes, {}); - }; - - const setCustomColorPalettes = (customColorPalettes) => { - return app.ui.settings.setSettingValue(idCustomColorPalettes, customColorPalettes); - }; - - const addCustomColorPalette = async (colorPalette) => { - if (typeof (colorPalette) !== "object") { - alert("Invalid color palette."); - return; - } - - if (!colorPalette.id) { - alert("Color palette missing id."); - return; - } - - if (!colorPalette.name) { - alert("Color palette missing name."); - return; - } - - if (!colorPalette.colors) { - alert("Color palette missing colors."); - return; - } - - if (colorPalette.colors.node_slot && typeof (colorPalette.colors.node_slot) !== "object") { - alert("Invalid color palette colors.node_slot."); - return; - } - - const customColorPalettes = getCustomColorPalettes(); - customColorPalettes[colorPalette.id] = colorPalette; - setCustomColorPalettes(customColorPalettes); - - for (const option of els.select.childNodes) { - if (option.value === "custom_" + colorPalette.id) { - els.select.removeChild(option); - } - } - - els.select.append($el("option", { - textContent: colorPalette.name + " (custom)", - value: "custom_" + colorPalette.id, - selected: true - })); - - setColorPalette("custom_" + colorPalette.id); - await loadColorPalette(colorPalette); - }; - - const deleteCustomColorPalette = async (colorPaletteId) => { - const customColorPalettes = getCustomColorPalettes(); - delete customColorPalettes[colorPaletteId]; - setCustomColorPalettes(customColorPalettes); - - for (const option of els.select.childNodes) { - if (option.value === defaultColorPaletteId) { - option.selected = true; - } - - if (option.value === "custom_" + colorPaletteId) { - els.select.removeChild(option); - } - } - - setColorPalette(defaultColorPaletteId); - await loadColorPalette(getColorPalette()); - }; - - const loadColorPalette = async (colorPalette) => { - colorPalette = await completeColorPalette(colorPalette); - if (colorPalette.colors) { - // Sets the colors of node slots and links - if (colorPalette.colors.node_slot) { - Object.assign(app.canvas.default_connection_color_byType, colorPalette.colors.node_slot); - Object.assign(LGraphCanvas.link_type_colors, colorPalette.colors.node_slot); - } - // Sets the colors of the LiteGraph objects - if (colorPalette.colors.litegraph_base) { - // Everything updates correctly in the loop, except the Node Title and Link Color for some reason - app.canvas.node_title_color = colorPalette.colors.litegraph_base.NODE_TITLE_COLOR; - app.canvas.default_link_color = colorPalette.colors.litegraph_base.LINK_COLOR; - - for (const key in colorPalette.colors.litegraph_base) { - if (colorPalette.colors.litegraph_base.hasOwnProperty(key) && LiteGraph.hasOwnProperty(key)) { - LiteGraph[key] = colorPalette.colors.litegraph_base[key]; - } - } - } - // Sets the color of ComfyUI elements - if (colorPalette.colors.comfy_base) { - const rootStyle = document.documentElement.style; - for (const key in colorPalette.colors.comfy_base) { - rootStyle.setProperty('--' + key, colorPalette.colors.comfy_base[key]); - } - } - app.canvas.draw(true, true); - } - }; - - const getColorPalette = (colorPaletteId) => { - if (!colorPaletteId) { - colorPaletteId = app.ui.settings.getSettingValue(id, defaultColorPaletteId); - } - - if (colorPaletteId.startsWith("custom_")) { - colorPaletteId = colorPaletteId.substr(7); - let customColorPalettes = getCustomColorPalettes(); - if (customColorPalettes[colorPaletteId]) { - return customColorPalettes[colorPaletteId]; - } - } - - return colorPalettes[colorPaletteId]; - }; - - const setColorPalette = (colorPaletteId) => { - app.ui.settings.setSettingValue(id, colorPaletteId); - }; - - const fileInput = $el("input", { - type: "file", - accept: ".json", - style: {display: "none"}, - parent: document.body, - onchange: () => { - const file = fileInput.files[0]; - if (file.type === "application/json" || file.name.endsWith(".json")) { - const reader = new FileReader(); - reader.onload = async () => { - await addCustomColorPalette(JSON.parse(reader.result)); - }; - reader.readAsText(file); - } - }, - }); - - app.ui.settings.addSetting({ - id, - name: "Color Palette", - type: (name, setter, value) => { - const options = [ - ...Object.values(colorPalettes).map(c=> $el("option", { - textContent: c.name, - value: c.id, - selected: c.id === value - })), - ...Object.values(getCustomColorPalettes()).map(c=>$el("option", { - textContent: `${c.name} (custom)`, - value: `custom_${c.id}`, - selected: `custom_${c.id}` === value - })) , - ]; - - els.select = $el("select", { - style: { - marginBottom: "0.15rem", - width: "100%", - }, - onchange: (e) => { - setter(e.target.value); - } - }, options) - - return $el("tr", [ - $el("td", [ - $el("label", { - for: id.replaceAll(".", "-"), - textContent: "Color palette", - }), - ]), - $el("td", [ - els.select, - $el("div", { - style: { - display: "grid", - gap: "4px", - gridAutoFlow: "column", - }, - }, [ - $el("input", { - type: "button", - value: "Export", - onclick: async () => { - const colorPaletteId = app.ui.settings.getSettingValue(id, defaultColorPaletteId); - const colorPalette = await completeColorPalette(getColorPalette(colorPaletteId)); - const json = JSON.stringify(colorPalette, null, 2); // convert the data to a JSON string - const blob = new Blob([json], {type: "application/json"}); - const url = URL.createObjectURL(blob); - const a = $el("a", { - href: url, - download: colorPaletteId + ".json", - style: {display: "none"}, - parent: document.body, - }); - a.click(); - setTimeout(function () { - a.remove(); - window.URL.revokeObjectURL(url); - }, 0); - }, - }), - $el("input", { - type: "button", - value: "Import", - onclick: () => { - fileInput.click(); - } - }), - $el("input", { - type: "button", - value: "Template", - onclick: async () => { - const colorPalette = await getColorPaletteTemplate(); - const json = JSON.stringify(colorPalette, null, 2); // convert the data to a JSON string - const blob = new Blob([json], {type: "application/json"}); - const url = URL.createObjectURL(blob); - const a = $el("a", { - href: url, - download: "color_palette.json", - style: {display: "none"}, - parent: document.body, - }); - a.click(); - setTimeout(function () { - a.remove(); - window.URL.revokeObjectURL(url); - }, 0); - } - }), - $el("input", { - type: "button", - value: "Delete", - onclick: async () => { - let colorPaletteId = app.ui.settings.getSettingValue(id, defaultColorPaletteId); - - if (colorPalettes[colorPaletteId]) { - alert("You cannot delete a built-in color palette."); - return; - } - - if (colorPaletteId.startsWith("custom_")) { - colorPaletteId = colorPaletteId.substr(7); - } - - await deleteCustomColorPalette(colorPaletteId); - } - }), - ]), - ]), - ]) - }, - defaultValue: defaultColorPaletteId, - async onChange(value) { - if (!value) { - return; - } - - let palette = colorPalettes[value]; - if (palette) { - await loadColorPalette(palette); - } else if (value.startsWith("custom_")) { - value = value.substr(7); - let customColorPalettes = getCustomColorPalettes(); - if (customColorPalettes[value]) { - palette = customColorPalettes[value]; - await loadColorPalette(customColorPalettes[value]); - } - } - - let {BACKGROUND_IMAGE, CLEAR_BACKGROUND_COLOR} = palette.colors.litegraph_base; - if (BACKGROUND_IMAGE === undefined || CLEAR_BACKGROUND_COLOR === undefined) { - const base = colorPalettes["dark"].colors.litegraph_base; - BACKGROUND_IMAGE = base.BACKGROUND_IMAGE; - CLEAR_BACKGROUND_COLOR = base.CLEAR_BACKGROUND_COLOR; - } - app.canvas.updateBackground(BACKGROUND_IMAGE, CLEAR_BACKGROUND_COLOR); - }, - }); - }, -}); diff --git a/web/extensions/core/contextMenuFilter.js b/web/extensions/core/contextMenuFilter.js deleted file mode 100644 index 0a305391a..000000000 --- a/web/extensions/core/contextMenuFilter.js +++ /dev/null @@ -1,148 +0,0 @@ -import {app} from "../../scripts/app.js"; - -// Adds filtering to combo context menus - -const ext = { - name: "Comfy.ContextMenuFilter", - init() { - const ctxMenu = LiteGraph.ContextMenu; - - LiteGraph.ContextMenu = function (values, options) { - const ctx = ctxMenu.call(this, values, options); - - // If we are a dark menu (only used for combo boxes) then add a filter input - if (options?.className === "dark" && values?.length > 10) { - const filter = document.createElement("input"); - filter.classList.add("comfy-context-menu-filter"); - filter.placeholder = "Filter list"; - this.root.prepend(filter); - - const items = Array.from(this.root.querySelectorAll(".litemenu-entry")); - let displayedItems = [...items]; - let itemCount = displayedItems.length; - - // We must request an animation frame for the current node of the active canvas to update. - requestAnimationFrame(() => { - const currentNode = LGraphCanvas.active_canvas.current_node; - const clickedComboValue = currentNode.widgets - ?.filter(w => w.type === "combo" && w.options.values.length === values.length) - .find(w => w.options.values.every((v, i) => v === values[i])) - ?.value; - - let selectedIndex = clickedComboValue ? values.findIndex(v => v === clickedComboValue) : 0; - if (selectedIndex < 0) { - selectedIndex = 0; - } - let selectedItem = displayedItems[selectedIndex]; - updateSelected(); - - // Apply highlighting to the selected item - function updateSelected() { - selectedItem?.style.setProperty("background-color", ""); - selectedItem?.style.setProperty("color", ""); - selectedItem = displayedItems[selectedIndex]; - selectedItem?.style.setProperty("background-color", "#ccc", "important"); - selectedItem?.style.setProperty("color", "#000", "important"); - } - - const positionList = () => { - const rect = this.root.getBoundingClientRect(); - - // If the top is off-screen then shift the element with scaling applied - if (rect.top < 0) { - const scale = 1 - this.root.getBoundingClientRect().height / this.root.clientHeight; - const shift = (this.root.clientHeight * scale) / 2; - this.root.style.top = -shift + "px"; - } - } - - // Arrow up/down to select items - filter.addEventListener("keydown", (event) => { - switch (event.key) { - case "ArrowUp": - event.preventDefault(); - if (selectedIndex === 0) { - selectedIndex = itemCount - 1; - } else { - selectedIndex--; - } - updateSelected(); - break; - case "ArrowRight": - event.preventDefault(); - selectedIndex = itemCount - 1; - updateSelected(); - break; - case "ArrowDown": - event.preventDefault(); - if (selectedIndex === itemCount - 1) { - selectedIndex = 0; - } else { - selectedIndex++; - } - updateSelected(); - break; - case "ArrowLeft": - event.preventDefault(); - selectedIndex = 0; - updateSelected(); - break; - case "Enter": - selectedItem?.click(); - break; - case "Escape": - this.close(); - break; - } - }); - - filter.addEventListener("input", () => { - // Hide all items that don't match our filter - const term = filter.value.toLocaleLowerCase(); - // When filtering, recompute which items are visible for arrow up/down and maintain selection. - displayedItems = items.filter(item => { - const isVisible = !term || item.textContent.toLocaleLowerCase().includes(term); - item.style.display = isVisible ? "block" : "none"; - return isVisible; - }); - - selectedIndex = 0; - if (displayedItems.includes(selectedItem)) { - selectedIndex = displayedItems.findIndex(d => d === selectedItem); - } - itemCount = displayedItems.length; - - updateSelected(); - - // If we have an event then we can try and position the list under the source - if (options.event) { - let top = options.event.clientY - 10; - - const bodyRect = document.body.getBoundingClientRect(); - const rootRect = this.root.getBoundingClientRect(); - if (bodyRect.height && top > bodyRect.height - rootRect.height - 10) { - top = Math.max(0, bodyRect.height - rootRect.height - 10); - } - - this.root.style.top = top + "px"; - positionList(); - } - }); - - requestAnimationFrame(() => { - // Focus the filter box when opening - filter.focus(); - - positionList(); - }); - }) - } - - return ctx; - }; - - LiteGraph.ContextMenu.prototype = ctxMenu.prototype; - }, -} - -app.registerExtension(ext); diff --git a/web/extensions/core/dynamicPrompts.js b/web/extensions/core/dynamicPrompts.js deleted file mode 100644 index 7417361ba..000000000 --- a/web/extensions/core/dynamicPrompts.js +++ /dev/null @@ -1,48 +0,0 @@ -import { app } from "../../scripts/app.js"; - -// Allows for simple dynamic prompt replacement -// Inputs in the format {a|b} will have a random value of a or b chosen when the prompt is queued. - -/* - * Strips C-style line and block comments from a string - */ -function stripComments(str) { - return str.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g,''); -} - -app.registerExtension({ - name: "Comfy.DynamicPrompts", - nodeCreated(node) { - if (node.widgets) { - // Locate dynamic prompt text widgets - // Include any widgets with dynamicPrompts set to true, and customtext - const widgets = node.widgets.filter( - (n) => n.dynamicPrompts - ); - for (const widget of widgets) { - // Override the serialization of the value to resolve dynamic prompts for all widgets supporting it in this node - widget.serializeValue = (workflowNode, widgetIndex) => { - let prompt = stripComments(widget.value); - while (prompt.replace("\\{", "").includes("{") && prompt.replace("\\}", "").includes("}")) { - const startIndex = prompt.replace("\\{", "00").indexOf("{"); - const endIndex = prompt.replace("\\}", "00").indexOf("}"); - - const optionsString = prompt.substring(startIndex + 1, endIndex); - const options = optionsString.split("|"); - - const randomIndex = Math.floor(Math.random() * options.length); - const randomOption = options[randomIndex]; - - prompt = prompt.substring(0, startIndex) + randomOption + prompt.substring(endIndex + 1); - } - - // Overwrite the value in the serialized workflow pnginfo - if (workflowNode?.widgets_values) - workflowNode.widgets_values[widgetIndex] = prompt; - - return prompt; - }; - } - } - }, -}); diff --git a/web/extensions/core/editAttention.js b/web/extensions/core/editAttention.js deleted file mode 100644 index 6792b2357..000000000 --- a/web/extensions/core/editAttention.js +++ /dev/null @@ -1,144 +0,0 @@ -import { app } from "../../scripts/app.js"; - -// Allows you to edit the attention weight by holding ctrl (or cmd) and using the up/down arrow keys - -app.registerExtension({ - name: "Comfy.EditAttention", - init() { - const editAttentionDelta = app.ui.settings.addSetting({ - id: "Comfy.EditAttention.Delta", - name: "Ctrl+up/down precision", - type: "slider", - attrs: { - min: 0.01, - max: 0.5, - step: 0.01, - }, - defaultValue: 0.05, - }); - - function incrementWeight(weight, delta) { - const floatWeight = parseFloat(weight); - if (isNaN(floatWeight)) return weight; - const newWeight = floatWeight + delta; - if (newWeight < 0) return "0"; - return String(Number(newWeight.toFixed(10))); - } - - function findNearestEnclosure(text, cursorPos) { - let start = cursorPos, end = cursorPos; - let openCount = 0, closeCount = 0; - - // Find opening parenthesis before cursor - while (start >= 0) { - start--; - if (text[start] === "(" && openCount === closeCount) break; - if (text[start] === "(") openCount++; - if (text[start] === ")") closeCount++; - } - if (start < 0) return false; - - openCount = 0; - closeCount = 0; - - // Find closing parenthesis after cursor - while (end < text.length) { - if (text[end] === ")" && openCount === closeCount) break; - if (text[end] === "(") openCount++; - if (text[end] === ")") closeCount++; - end++; - } - if (end === text.length) return false; - - return { start: start + 1, end: end }; - } - - function addWeightToParentheses(text) { - const parenRegex = /^\((.*)\)$/; - const parenMatch = text.match(parenRegex); - - const floatRegex = /:([+-]?(\d*\.)?\d+([eE][+-]?\d+)?)/; - const floatMatch = text.match(floatRegex); - - if (parenMatch && !floatMatch) { - return `(${parenMatch[1]}:1.0)`; - } else { - return text; - } - }; - - function editAttention(event) { - const inputField = event.composedPath()[0]; - const delta = parseFloat(editAttentionDelta.value); - - if (inputField.tagName !== "TEXTAREA") return; - if (!(event.key === "ArrowUp" || event.key === "ArrowDown")) return; - if (!event.ctrlKey && !event.metaKey) return; - - event.preventDefault(); - - let start = inputField.selectionStart; - let end = inputField.selectionEnd; - let selectedText = inputField.value.substring(start, end); - - // If there is no selection, attempt to find the nearest enclosure, or select the current word - if (!selectedText) { - const nearestEnclosure = findNearestEnclosure(inputField.value, start); - if (nearestEnclosure) { - start = nearestEnclosure.start; - end = nearestEnclosure.end; - selectedText = inputField.value.substring(start, end); - } else { - // Select the current word, find the start and end of the word - const delimiters = " .,\\/!?%^*;:{}=-_`~()\r\n\t"; - - while (!delimiters.includes(inputField.value[start - 1]) && start > 0) { - start--; - } - - while (!delimiters.includes(inputField.value[end]) && end < inputField.value.length) { - end++; - } - - selectedText = inputField.value.substring(start, end); - if (!selectedText) return; - } - } - - // If the selection ends with a space, remove it - if (selectedText[selectedText.length - 1] === " ") { - selectedText = selectedText.substring(0, selectedText.length - 1); - end -= 1; - } - - // If there are parentheses left and right of the selection, select them - if (inputField.value[start - 1] === "(" && inputField.value[end] === ")") { - start -= 1; - end += 1; - selectedText = inputField.value.substring(start, end); - } - - // If the selection is not enclosed in parentheses, add them - if (selectedText[0] !== "(" || selectedText[selectedText.length - 1] !== ")") { - selectedText = `(${selectedText})`; - } - - // If the selection does not have a weight, add a weight of 1.0 - selectedText = addWeightToParentheses(selectedText); - - // Increment the weight - const weightDelta = event.key === "ArrowUp" ? delta : -delta; - const updatedText = selectedText.replace(/\((.*):(\d+(?:\.\d+)?)\)/, (match, text, weight) => { - weight = incrementWeight(weight, weightDelta); - if (weight == 1) { - return text; - } else { - return `(${text}:${weight})`; - } - }); - - inputField.setRangeText(updatedText, start, end, "select"); - } - window.addEventListener("keydown", editAttention); - }, -}); diff --git a/web/extensions/core/groupNode.js b/web/extensions/core/groupNode.js index 9a2238908..fc43ddc41 100644 --- a/web/extensions/core/groupNode.js +++ b/web/extensions/core/groupNode.js @@ -1,1281 +1,3 @@ -import { app } from "../../scripts/app.js"; -import { api } from "../../scripts/api.js"; -import { mergeIfValid } from "./widgetInputs.js"; -import { ManageGroupDialog } from "./groupNodeManage.js"; - -const GROUP = Symbol(); - -const Workflow = { - InUse: { - Free: 0, - Registered: 1, - InWorkflow: 2, - }, - isInUseGroupNode(name) { - const id = `workflow/${name}`; - // Check if lready registered/in use in this workflow - if (app.graph.extra?.groupNodes?.[name]) { - if (app.graph._nodes.find((n) => n.type === id)) { - return Workflow.InUse.InWorkflow; - } else { - return Workflow.InUse.Registered; - } - } - return Workflow.InUse.Free; - }, - storeGroupNode(name, data) { - let extra = app.graph.extra; - if (!extra) app.graph.extra = extra = {}; - let groupNodes = extra.groupNodes; - if (!groupNodes) extra.groupNodes = groupNodes = {}; - groupNodes[name] = data; - }, -}; - -class GroupNodeBuilder { - constructor(nodes) { - this.nodes = nodes; - } - - build() { - const name = this.getName(); - if (!name) return; - - // Sort the nodes so they are in execution order - // this allows for widgets to be in the correct order when reconstructing - this.sortNodes(); - - this.nodeData = this.getNodeData(); - Workflow.storeGroupNode(name, this.nodeData); - - return { name, nodeData: this.nodeData }; - } - - getName() { - const name = prompt("Enter group name"); - if (!name) return; - const used = Workflow.isInUseGroupNode(name); - switch (used) { - case Workflow.InUse.InWorkflow: - alert( - "An in use group node with this name already exists embedded in this workflow, please remove any instances or use a new name." - ); - return; - case Workflow.InUse.Registered: - if (!confirm("A group node with this name already exists embedded in this workflow, are you sure you want to overwrite it?")) { - return; - } - break; - } - return name; - } - - sortNodes() { - // Gets the builders nodes in graph execution order - const nodesInOrder = app.graph.computeExecutionOrder(false); - this.nodes = this.nodes - .map((node) => ({ index: nodesInOrder.indexOf(node), node })) - .sort((a, b) => a.index - b.index || a.node.id - b.node.id) - .map(({ node }) => node); - } - - getNodeData() { - const storeLinkTypes = (config) => { - // Store link types for dynamically typed nodes e.g. reroutes - for (const link of config.links) { - const origin = app.graph.getNodeById(link[4]); - const type = origin.outputs[link[1]].type; - link.push(type); - } - }; - - const storeExternalLinks = (config) => { - // Store any external links to the group in the config so when rebuilding we add extra slots - config.external = []; - for (let i = 0; i < this.nodes.length; i++) { - const node = this.nodes[i]; - if (!node.outputs?.length) continue; - for (let slot = 0; slot < node.outputs.length; slot++) { - let hasExternal = false; - const output = node.outputs[slot]; - let type = output.type; - if (!output.links?.length) continue; - for (const l of output.links) { - const link = app.graph.links[l]; - if (!link) continue; - if (type === "*") type = link.type; - - if (!app.canvas.selected_nodes[link.target_id]) { - hasExternal = true; - break; - } - } - if (hasExternal) { - config.external.push([i, slot, type]); - } - } - } - }; - - // Use the built in copyToClipboard function to generate the node data we need - const backup = localStorage.getItem("litegrapheditor_clipboard"); - try { - app.canvas.copyToClipboard(this.nodes); - const config = JSON.parse(localStorage.getItem("litegrapheditor_clipboard")); - - storeLinkTypes(config); - storeExternalLinks(config); - - return config; - } finally { - localStorage.setItem("litegrapheditor_clipboard", backup); - } - } -} - -export class GroupNodeConfig { - constructor(name, nodeData) { - this.name = name; - this.nodeData = nodeData; - this.getLinks(); - - this.inputCount = 0; - this.oldToNewOutputMap = {}; - this.newToOldOutputMap = {}; - this.oldToNewInputMap = {}; - this.oldToNewWidgetMap = {}; - this.newToOldWidgetMap = {}; - this.primitiveDefs = {}; - this.widgetToPrimitive = {}; - this.primitiveToWidget = {}; - this.nodeInputs = {}; - this.outputVisibility = []; - } - - async registerType(source = "workflow") { - this.nodeDef = { - output: [], - output_name: [], - output_is_list: [], - output_is_hidden: [], - name: source + "/" + this.name, - display_name: this.name, - category: "group nodes" + ("/" + source), - input: { required: {} }, - - [GROUP]: this, - }; - - this.inputs = []; - const seenInputs = {}; - const seenOutputs = {}; - for (let i = 0; i < this.nodeData.nodes.length; i++) { - const node = this.nodeData.nodes[i]; - node.index = i; - this.processNode(node, seenInputs, seenOutputs); - } - - for (const p of this.#convertedToProcess) { - p(); - } - this.#convertedToProcess = null; - await app.registerNodeDef("workflow/" + this.name, this.nodeDef); - } - - getLinks() { - this.linksFrom = {}; - this.linksTo = {}; - this.externalFrom = {}; - - // Extract links for easy lookup - for (const l of this.nodeData.links) { - const [sourceNodeId, sourceNodeSlot, targetNodeId, targetNodeSlot] = l; - - // Skip links outside the copy config - if (sourceNodeId == null) continue; - - if (!this.linksFrom[sourceNodeId]) { - this.linksFrom[sourceNodeId] = {}; - } - if (!this.linksFrom[sourceNodeId][sourceNodeSlot]) { - this.linksFrom[sourceNodeId][sourceNodeSlot] = []; - } - this.linksFrom[sourceNodeId][sourceNodeSlot].push(l); - - if (!this.linksTo[targetNodeId]) { - this.linksTo[targetNodeId] = {}; - } - this.linksTo[targetNodeId][targetNodeSlot] = l; - } - - if (this.nodeData.external) { - for (const ext of this.nodeData.external) { - if (!this.externalFrom[ext[0]]) { - this.externalFrom[ext[0]] = { [ext[1]]: ext[2] }; - } else { - this.externalFrom[ext[0]][ext[1]] = ext[2]; - } - } - } - } - - processNode(node, seenInputs, seenOutputs) { - const def = this.getNodeDef(node); - if (!def) return; - - const inputs = { ...def.input?.required, ...def.input?.optional }; - - this.inputs.push(this.processNodeInputs(node, seenInputs, inputs)); - if (def.output?.length) this.processNodeOutputs(node, seenOutputs, def); - } - - getNodeDef(node) { - const def = globalDefs[node.type]; - if (def) return def; - - const linksFrom = this.linksFrom[node.index]; - if (node.type === "PrimitiveNode") { - // Skip as its not linked - if (!linksFrom) return; - - let type = linksFrom["0"][0][5]; - if (type === "COMBO") { - // Use the array items - const source = node.outputs[0].widget.name; - const fromTypeName = this.nodeData.nodes[linksFrom["0"][0][2]].type; - const fromType = globalDefs[fromTypeName]; - const input = fromType.input.required[source] ?? fromType.input.optional[source]; - type = input[0]; - } - - const def = (this.primitiveDefs[node.index] = { - input: { - required: { - value: [type, {}], - }, - }, - output: [type], - output_name: [], - output_is_list: [], - }); - return def; - } else if (node.type === "Reroute") { - const linksTo = this.linksTo[node.index]; - if (linksTo && linksFrom && !this.externalFrom[node.index]?.[0]) { - // Being used internally - return null; - } - - let config = {}; - let rerouteType = "*"; - if (linksFrom) { - for (const [, , id, slot] of linksFrom["0"]) { - const node = this.nodeData.nodes[id]; - const input = node.inputs[slot]; - if (rerouteType === "*") { - rerouteType = input.type; - } - if (input.widget) { - const targetDef = globalDefs[node.type]; - const targetWidget = targetDef.input.required[input.widget.name] ?? targetDef.input.optional[input.widget.name]; - - const widget = [targetWidget[0], config]; - const res = mergeIfValid( - { - widget, - }, - targetWidget, - false, - null, - widget - ); - config = res?.customConfig ?? config; - } - } - } else if (linksTo) { - const [id, slot] = linksTo["0"]; - rerouteType = this.nodeData.nodes[id].outputs[slot].type; - } else { - // Reroute used as a pipe - for (const l of this.nodeData.links) { - if (l[2] === node.index) { - rerouteType = l[5]; - break; - } - } - if (rerouteType === "*") { - // Check for an external link - const t = this.externalFrom[node.index]?.[0]; - if (t) { - rerouteType = t; - } - } - } - - config.forceInput = true; - return { - input: { - required: { - [rerouteType]: [rerouteType, config], - }, - }, - output: [rerouteType], - output_name: [], - output_is_list: [], - }; - } - - console.warn("Skipping virtual node " + node.type + " when building group node " + this.name); - } - - getInputConfig(node, inputName, seenInputs, config, extra) { - const customConfig = this.nodeData.config?.[node.index]?.input?.[inputName]; - let name = customConfig?.name ?? node.inputs?.find((inp) => inp.name === inputName)?.label ?? inputName; - let key = name; - let prefix = ""; - // Special handling for primitive to include the title if it is set rather than just "value" - if ((node.type === "PrimitiveNode" && node.title) || name in seenInputs) { - prefix = `${node.title ?? node.type} `; - key = name = `${prefix}${inputName}`; - if (name in seenInputs) { - name = `${prefix}${seenInputs[name]} ${inputName}`; - } - } - seenInputs[key] = (seenInputs[key] ?? 1) + 1; - - if (inputName === "seed" || inputName === "noise_seed") { - if (!extra) extra = {}; - extra.control_after_generate = `${prefix}control_after_generate`; - } - if (config[0] === "IMAGEUPLOAD") { - if (!extra) extra = {}; - extra.widget = this.oldToNewWidgetMap[node.index]?.[config[1]?.widget ?? "image"] ?? "image"; - } - - if (extra) { - config = [config[0], { ...config[1], ...extra }]; - } - - return { name, config, customConfig }; - } - - processWidgetInputs(inputs, node, inputNames, seenInputs) { - const slots = []; - const converted = new Map(); - const widgetMap = (this.oldToNewWidgetMap[node.index] = {}); - for (const inputName of inputNames) { - let widgetType = app.getWidgetType(inputs[inputName], inputName); - if (widgetType) { - const convertedIndex = node.inputs?.findIndex((inp) => inp.name === inputName && inp.widget?.name === inputName); - if (convertedIndex > -1) { - // This widget has been converted to a widget - // We need to store this in the correct position so link ids line up - converted.set(convertedIndex, inputName); - widgetMap[inputName] = null; - } else { - // Normal widget - const { name, config } = this.getInputConfig(node, inputName, seenInputs, inputs[inputName]); - this.nodeDef.input.required[name] = config; - widgetMap[inputName] = name; - this.newToOldWidgetMap[name] = { node, inputName }; - } - } else { - // Normal input - slots.push(inputName); - } - } - return { converted, slots }; - } - - checkPrimitiveConnection(link, inputName, inputs) { - const sourceNode = this.nodeData.nodes[link[0]]; - if (sourceNode.type === "PrimitiveNode") { - // Merge link configurations - const [sourceNodeId, _, targetNodeId, __] = link; - const primitiveDef = this.primitiveDefs[sourceNodeId]; - const targetWidget = inputs[inputName]; - const primitiveConfig = primitiveDef.input.required.value; - const output = { widget: primitiveConfig }; - const config = mergeIfValid(output, targetWidget, false, null, primitiveConfig); - primitiveConfig[1] = config?.customConfig ?? inputs[inputName][1] ? { ...inputs[inputName][1] } : {}; - - let name = this.oldToNewWidgetMap[sourceNodeId]["value"]; - name = name.substr(0, name.length - 6); - primitiveConfig[1].control_after_generate = true; - primitiveConfig[1].control_prefix = name; - - let toPrimitive = this.widgetToPrimitive[targetNodeId]; - if (!toPrimitive) { - toPrimitive = this.widgetToPrimitive[targetNodeId] = {}; - } - if (toPrimitive[inputName]) { - toPrimitive[inputName].push(sourceNodeId); - } - toPrimitive[inputName] = sourceNodeId; - - let toWidget = this.primitiveToWidget[sourceNodeId]; - if (!toWidget) { - toWidget = this.primitiveToWidget[sourceNodeId] = []; - } - toWidget.push({ nodeId: targetNodeId, inputName }); - } - } - - processInputSlots(inputs, node, slots, linksTo, inputMap, seenInputs) { - this.nodeInputs[node.index] = {}; - for (let i = 0; i < slots.length; i++) { - const inputName = slots[i]; - if (linksTo[i]) { - this.checkPrimitiveConnection(linksTo[i], inputName, inputs); - // This input is linked so we can skip it - continue; - } - - const { name, config, customConfig } = this.getInputConfig(node, inputName, seenInputs, inputs[inputName]); - - this.nodeInputs[node.index][inputName] = name; - if(customConfig?.visible === false) continue; - - this.nodeDef.input.required[name] = config; - inputMap[i] = this.inputCount++; - } - } - - processConvertedWidgets(inputs, node, slots, converted, linksTo, inputMap, seenInputs) { - // Add converted widgets sorted into their index order (ordered as they were converted) so link ids match up - const convertedSlots = [...converted.keys()].sort().map((k) => converted.get(k)); - for (let i = 0; i < convertedSlots.length; i++) { - const inputName = convertedSlots[i]; - if (linksTo[slots.length + i]) { - this.checkPrimitiveConnection(linksTo[slots.length + i], inputName, inputs); - // This input is linked so we can skip it - continue; - } - - const { name, config } = this.getInputConfig(node, inputName, seenInputs, inputs[inputName], { - defaultInput: true, - }); - - this.nodeDef.input.required[name] = config; - this.newToOldWidgetMap[name] = { node, inputName }; - - if (!this.oldToNewWidgetMap[node.index]) { - this.oldToNewWidgetMap[node.index] = {}; - } - this.oldToNewWidgetMap[node.index][inputName] = name; - - inputMap[slots.length + i] = this.inputCount++; - } - } - - #convertedToProcess = []; - processNodeInputs(node, seenInputs, inputs) { - const inputMapping = []; - - const inputNames = Object.keys(inputs); - if (!inputNames.length) return; - - const { converted, slots } = this.processWidgetInputs(inputs, node, inputNames, seenInputs); - const linksTo = this.linksTo[node.index] ?? {}; - const inputMap = (this.oldToNewInputMap[node.index] = {}); - this.processInputSlots(inputs, node, slots, linksTo, inputMap, seenInputs); - - // Converted inputs have to be processed after all other nodes as they'll be at the end of the list - this.#convertedToProcess.push(() => this.processConvertedWidgets(inputs, node, slots, converted, linksTo, inputMap, seenInputs)); - - return inputMapping; - } - - processNodeOutputs(node, seenOutputs, def) { - const oldToNew = (this.oldToNewOutputMap[node.index] = {}); - - // Add outputs - for (let outputId = 0; outputId < def.output.length; outputId++) { - const linksFrom = this.linksFrom[node.index]; - // If this output is linked internally we flag it to hide - const hasLink = linksFrom?.[outputId] && !this.externalFrom[node.index]?.[outputId]; - const customConfig = this.nodeData.config?.[node.index]?.output?.[outputId]; - const visible = customConfig?.visible ?? !hasLink; - this.outputVisibility.push(visible); - if (!visible) { - continue; - } - - oldToNew[outputId] = this.nodeDef.output.length; - this.newToOldOutputMap[this.nodeDef.output.length] = { node, slot: outputId }; - this.nodeDef.output.push(def.output[outputId]); - this.nodeDef.output_is_list.push(def.output_is_list[outputId]); - - let label = customConfig?.name; - if (!label) { - label = def.output_name?.[outputId] ?? def.output[outputId]; - const output = node.outputs.find((o) => o.name === label); - if (output?.label) { - label = output.label; - } - } - - let name = label; - if (name in seenOutputs) { - const prefix = `${node.title ?? node.type} `; - name = `${prefix}${label}`; - if (name in seenOutputs) { - name = `${prefix}${node.index} ${label}`; - } - } - seenOutputs[name] = 1; - - this.nodeDef.output_name.push(name); - } - } - - static async registerFromWorkflow(groupNodes, missingNodeTypes) { - const clean = app.clean; - app.clean = function () { - for (const g in groupNodes) { - try { - LiteGraph.unregisterNodeType("workflow/" + g); - } catch (error) {} - } - app.clean = clean; - }; - - for (const g in groupNodes) { - const groupData = groupNodes[g]; - - let hasMissing = false; - for (const n of groupData.nodes) { - // Find missing node types - if (!(n.type in LiteGraph.registered_node_types)) { - missingNodeTypes.push({ - type: n.type, - hint: ` (In group node 'workflow/${g}')`, - }); - - missingNodeTypes.push({ - type: "workflow/" + g, - action: { - text: "Remove from workflow", - callback: (e) => { - delete groupNodes[g]; - e.target.textContent = "Removed"; - e.target.style.pointerEvents = "none"; - e.target.style.opacity = 0.7; - }, - }, - }); - - hasMissing = true; - } - } - - if (hasMissing) continue; - - const config = new GroupNodeConfig(g, groupData); - await config.registerType(); - } - } -} - -export class GroupNodeHandler { - node; - groupData; - - constructor(node) { - this.node = node; - this.groupData = node.constructor?.nodeData?.[GROUP]; - - this.node.setInnerNodes = (innerNodes) => { - this.innerNodes = innerNodes; - - for (let innerNodeIndex = 0; innerNodeIndex < this.innerNodes.length; innerNodeIndex++) { - const innerNode = this.innerNodes[innerNodeIndex]; - - for (const w of innerNode.widgets ?? []) { - if (w.type === "converted-widget") { - w.serializeValue = w.origSerializeValue; - } - } - - innerNode.index = innerNodeIndex; - innerNode.getInputNode = (slot) => { - // Check if this input is internal or external - const externalSlot = this.groupData.oldToNewInputMap[innerNode.index]?.[slot]; - if (externalSlot != null) { - return this.node.getInputNode(externalSlot); - } - - // Internal link - const innerLink = this.groupData.linksTo[innerNode.index]?.[slot]; - if (!innerLink) return null; - - const inputNode = innerNodes[innerLink[0]]; - // Primitives will already apply their values - if (inputNode.type === "PrimitiveNode") return null; - - return inputNode; - }; - - innerNode.getInputLink = (slot) => { - const externalSlot = this.groupData.oldToNewInputMap[innerNode.index]?.[slot]; - if (externalSlot != null) { - // The inner node is connected via the group node inputs - const linkId = this.node.inputs[externalSlot].link; - let link = app.graph.links[linkId]; - - // Use the outer link, but update the target to the inner node - link = { - ...link, - target_id: innerNode.id, - target_slot: +slot, - }; - return link; - } - - let link = this.groupData.linksTo[innerNode.index]?.[slot]; - if (!link) return null; - // Use the inner link, but update the origin node to be inner node id - link = { - origin_id: innerNodes[link[0]].id, - origin_slot: link[1], - target_id: innerNode.id, - target_slot: +slot, - }; - return link; - }; - } - }; - - this.node.updateLink = (link) => { - // Replace the group node reference with the internal node - link = { ...link }; - const output = this.groupData.newToOldOutputMap[link.origin_slot]; - let innerNode = this.innerNodes[output.node.index]; - let l; - while (innerNode?.type === "Reroute") { - l = innerNode.getInputLink(0); - innerNode = innerNode.getInputNode(0); - } - - if (!innerNode) { - return null; - } - - if (l && GroupNodeHandler.isGroupNode(innerNode)) { - return innerNode.updateLink(l); - } - - link.origin_id = innerNode.id; - link.origin_slot = l?.origin_slot ?? output.slot; - return link; - }; - - this.node.getInnerNodes = () => { - if (!this.innerNodes) { - this.node.setInnerNodes( - this.groupData.nodeData.nodes.map((n, i) => { - const innerNode = LiteGraph.createNode(n.type); - innerNode.configure(n); - innerNode.id = `${this.node.id}:${i}`; - return innerNode; - }) - ); - } - - this.updateInnerWidgets(); - - return this.innerNodes; - }; - - this.node.recreate = async () => { - const id = this.node.id; - const sz = this.node.size; - const nodes = this.node.convertToNodes(); - - const groupNode = LiteGraph.createNode(this.node.type); - groupNode.id = id; - - // Reuse the existing nodes for this instance - groupNode.setInnerNodes(nodes); - groupNode[GROUP].populateWidgets(); - app.graph.add(groupNode); - groupNode.size = [Math.max(groupNode.size[0], sz[0]), Math.max(groupNode.size[1], sz[1])]; - - // Remove all converted nodes and relink them - groupNode[GROUP].replaceNodes(nodes); - return groupNode; - }; - - this.node.convertToNodes = () => { - const addInnerNodes = () => { - const backup = localStorage.getItem("litegrapheditor_clipboard"); - // Clone the node data so we dont mutate it for other nodes - const c = { ...this.groupData.nodeData }; - c.nodes = [...c.nodes]; - const innerNodes = this.node.getInnerNodes(); - let ids = []; - for (let i = 0; i < c.nodes.length; i++) { - let id = innerNodes?.[i]?.id; - // Use existing IDs if they are set on the inner nodes - if (id == null || isNaN(id)) { - id = undefined; - } else { - ids.push(id); - } - c.nodes[i] = { ...c.nodes[i], id }; - } - localStorage.setItem("litegrapheditor_clipboard", JSON.stringify(c)); - app.canvas.pasteFromClipboard(); - localStorage.setItem("litegrapheditor_clipboard", backup); - - const [x, y] = this.node.pos; - let top; - let left; - // Configure nodes with current widget data - const selectedIds = ids.length ? ids : Object.keys(app.canvas.selected_nodes); - const newNodes = []; - for (let i = 0; i < selectedIds.length; i++) { - const id = selectedIds[i]; - const newNode = app.graph.getNodeById(id); - const innerNode = innerNodes[i]; - newNodes.push(newNode); - - if (left == null || newNode.pos[0] < left) { - left = newNode.pos[0]; - } - if (top == null || newNode.pos[1] < top) { - top = newNode.pos[1]; - } - - if (!newNode.widgets) continue; - - const map = this.groupData.oldToNewWidgetMap[innerNode.index]; - if (map) { - const widgets = Object.keys(map); - - for (const oldName of widgets) { - const newName = map[oldName]; - if (!newName) continue; - - const widgetIndex = this.node.widgets.findIndex((w) => w.name === newName); - if (widgetIndex === -1) continue; - - // Populate the main and any linked widgets - if (innerNode.type === "PrimitiveNode") { - for (let i = 0; i < newNode.widgets.length; i++) { - newNode.widgets[i].value = this.node.widgets[widgetIndex + i].value; - } - } else { - const outerWidget = this.node.widgets[widgetIndex]; - const newWidget = newNode.widgets.find((w) => w.name === oldName); - if (!newWidget) continue; - - newWidget.value = outerWidget.value; - for (let w = 0; w < outerWidget.linkedWidgets?.length; w++) { - newWidget.linkedWidgets[w].value = outerWidget.linkedWidgets[w].value; - } - } - } - } - } - - // Shift each node - for (const newNode of newNodes) { - newNode.pos = [newNode.pos[0] - (left - x), newNode.pos[1] - (top - y)]; - } - - return { newNodes, selectedIds }; - }; - - const reconnectInputs = (selectedIds) => { - for (const innerNodeIndex in this.groupData.oldToNewInputMap) { - const id = selectedIds[innerNodeIndex]; - const newNode = app.graph.getNodeById(id); - const map = this.groupData.oldToNewInputMap[innerNodeIndex]; - for (const innerInputId in map) { - const groupSlotId = map[innerInputId]; - if (groupSlotId == null) continue; - const slot = node.inputs[groupSlotId]; - if (slot.link == null) continue; - const link = app.graph.links[slot.link]; - if (!link) continue; - // connect this node output to the input of another node - const originNode = app.graph.getNodeById(link.origin_id); - originNode.connect(link.origin_slot, newNode, +innerInputId); - } - } - }; - - const reconnectOutputs = (selectedIds) => { - for (let groupOutputId = 0; groupOutputId < node.outputs?.length; groupOutputId++) { - const output = node.outputs[groupOutputId]; - if (!output.links) continue; - const links = [...output.links]; - for (const l of links) { - const slot = this.groupData.newToOldOutputMap[groupOutputId]; - const link = app.graph.links[l]; - const targetNode = app.graph.getNodeById(link.target_id); - const newNode = app.graph.getNodeById(selectedIds[slot.node.index]); - newNode.connect(slot.slot, targetNode, link.target_slot); - } - } - }; - - const { newNodes, selectedIds } = addInnerNodes(); - reconnectInputs(selectedIds); - reconnectOutputs(selectedIds); - app.graph.remove(this.node); - - return newNodes; - }; - - const getExtraMenuOptions = this.node.getExtraMenuOptions; - this.node.getExtraMenuOptions = function (_, options) { - getExtraMenuOptions?.apply(this, arguments); - - let optionIndex = options.findIndex((o) => o.content === "Outputs"); - if (optionIndex === -1) optionIndex = options.length; - else optionIndex++; - options.splice( - optionIndex, - 0, - null, - { - content: "Convert to nodes", - callback: () => { - return this.convertToNodes(); - }, - }, - { - content: "Manage Group Node", - callback: () => { - new ManageGroupDialog(app).show(this.type); - }, - } - ); - }; - - // Draw custom collapse icon to identity this as a group - const onDrawTitleBox = this.node.onDrawTitleBox; - this.node.onDrawTitleBox = function (ctx, height, size, scale) { - onDrawTitleBox?.apply(this, arguments); - - const fill = ctx.fillStyle; - ctx.beginPath(); - ctx.rect(11, -height + 11, 2, 2); - ctx.rect(14, -height + 11, 2, 2); - ctx.rect(17, -height + 11, 2, 2); - ctx.rect(11, -height + 14, 2, 2); - ctx.rect(14, -height + 14, 2, 2); - ctx.rect(17, -height + 14, 2, 2); - ctx.rect(11, -height + 17, 2, 2); - ctx.rect(14, -height + 17, 2, 2); - ctx.rect(17, -height + 17, 2, 2); - - ctx.fillStyle = this.boxcolor || LiteGraph.NODE_DEFAULT_BOXCOLOR; - ctx.fill(); - ctx.fillStyle = fill; - }; - - // Draw progress label - const onDrawForeground = node.onDrawForeground; - const groupData = this.groupData.nodeData; - node.onDrawForeground = function (ctx) { - const r = onDrawForeground?.apply?.(this, arguments); - if (+app.runningNodeId === this.id && this.runningInternalNodeId !== null) { - const n = groupData.nodes[this.runningInternalNodeId]; - if(!n) return; - const message = `Running ${n.title || n.type} (${this.runningInternalNodeId}/${groupData.nodes.length})`; - ctx.save(); - ctx.font = "12px sans-serif"; - const sz = ctx.measureText(message); - ctx.fillStyle = node.boxcolor || LiteGraph.NODE_DEFAULT_BOXCOLOR; - ctx.beginPath(); - ctx.roundRect(0, -LiteGraph.NODE_TITLE_HEIGHT - 20, sz.width + 12, 20, 5); - ctx.fill(); - - ctx.fillStyle = "#fff"; - ctx.fillText(message, 6, -LiteGraph.NODE_TITLE_HEIGHT - 6); - ctx.restore(); - } - }; - - // Flag this node as needing to be reset - const onExecutionStart = this.node.onExecutionStart; - this.node.onExecutionStart = function () { - this.resetExecution = true; - return onExecutionStart?.apply(this, arguments); - }; - - const self = this; - const onNodeCreated = this.node.onNodeCreated; - this.node.onNodeCreated = function () { - if (!this.widgets) { - return; - } - const config = self.groupData.nodeData.config; - if (config) { - for (const n in config) { - const inputs = config[n]?.input; - for (const w in inputs) { - if (inputs[w].visible !== false) continue; - const widgetName = self.groupData.oldToNewWidgetMap[n][w]; - const widget = this.widgets.find((w) => w.name === widgetName); - if (widget) { - widget.type = "hidden"; - widget.computeSize = () => [0, -4]; - } - } - } - } - - return onNodeCreated?.apply(this, arguments); - }; - - function handleEvent(type, getId, getEvent) { - const handler = ({ detail }) => { - const id = getId(detail); - if (!id) return; - const node = app.graph.getNodeById(id); - if (node) return; - - const innerNodeIndex = this.innerNodes?.findIndex((n) => n.id == id); - if (innerNodeIndex > -1) { - this.node.runningInternalNodeId = innerNodeIndex; - api.dispatchEvent(new CustomEvent(type, { detail: getEvent(detail, this.node.id + "", this.node) })); - } - }; - api.addEventListener(type, handler); - return handler; - } - - const executing = handleEvent.call( - this, - "executing", - (d) => d, - (d, id, node) => id - ); - - const executed = handleEvent.call( - this, - "executed", - (d) => d?.node, - (d, id, node) => ({ ...d, node: id, merge: !node.resetExecution }) - ); - - const onRemoved = node.onRemoved; - this.node.onRemoved = function () { - onRemoved?.apply(this, arguments); - api.removeEventListener("executing", executing); - api.removeEventListener("executed", executed); - }; - - this.node.refreshComboInNode = (defs) => { - // Update combo widget options - for (const widgetName in this.groupData.newToOldWidgetMap) { - const widget = this.node.widgets.find((w) => w.name === widgetName); - if (widget?.type === "combo") { - const old = this.groupData.newToOldWidgetMap[widgetName]; - const def = defs[old.node.type]; - const input = def?.input?.required?.[old.inputName] ?? def?.input?.optional?.[old.inputName]; - if (!input) continue; - - widget.options.values = input[0]; - - if (old.inputName !== "image" && !widget.options.values.includes(widget.value)) { - widget.value = widget.options.values[0]; - widget.callback(widget.value); - } - } - } - }; - } - - updateInnerWidgets() { - for (const newWidgetName in this.groupData.newToOldWidgetMap) { - const newWidget = this.node.widgets.find((w) => w.name === newWidgetName); - if (!newWidget) continue; - - const newValue = newWidget.value; - const old = this.groupData.newToOldWidgetMap[newWidgetName]; - let innerNode = this.innerNodes[old.node.index]; - - if (innerNode.type === "PrimitiveNode") { - innerNode.primitiveValue = newValue; - const primitiveLinked = this.groupData.primitiveToWidget[old.node.index]; - for (const linked of primitiveLinked ?? []) { - const node = this.innerNodes[linked.nodeId]; - const widget = node.widgets.find((w) => w.name === linked.inputName); - - if (widget) { - widget.value = newValue; - } - } - continue; - } else if (innerNode.type === "Reroute") { - const rerouteLinks = this.groupData.linksFrom[old.node.index]; - if (rerouteLinks) { - for (const [_, , targetNodeId, targetSlot] of rerouteLinks["0"]) { - const node = this.innerNodes[targetNodeId]; - const input = node.inputs[targetSlot]; - if (input.widget) { - const widget = node.widgets?.find((w) => w.name === input.widget.name); - if (widget) { - widget.value = newValue; - } - } - } - } - } - - const widget = innerNode.widgets?.find((w) => w.name === old.inputName); - if (widget) { - widget.value = newValue; - } - } - } - - populatePrimitive(node, nodeId, oldName, i, linkedShift) { - // Converted widget, populate primitive if linked - const primitiveId = this.groupData.widgetToPrimitive[nodeId]?.[oldName]; - if (primitiveId == null) return; - const targetWidgetName = this.groupData.oldToNewWidgetMap[primitiveId]["value"]; - const targetWidgetIndex = this.node.widgets.findIndex((w) => w.name === targetWidgetName); - if (targetWidgetIndex > -1) { - const primitiveNode = this.innerNodes[primitiveId]; - let len = primitiveNode.widgets.length; - if (len - 1 !== this.node.widgets[targetWidgetIndex].linkedWidgets?.length) { - // Fallback handling for if some reason the primitive has a different number of widgets - // we dont want to overwrite random widgets, better to leave blank - len = 1; - } - for (let i = 0; i < len; i++) { - this.node.widgets[targetWidgetIndex + i].value = primitiveNode.widgets[i].value; - } - } - return true; - } - - populateReroute(node, nodeId, map) { - if (node.type !== "Reroute") return; - - const link = this.groupData.linksFrom[nodeId]?.[0]?.[0]; - if (!link) return; - const [, , targetNodeId, targetNodeSlot] = link; - const targetNode = this.groupData.nodeData.nodes[targetNodeId]; - const inputs = targetNode.inputs; - const targetWidget = inputs?.[targetNodeSlot]?.widget; - if (!targetWidget) return; - - const offset = inputs.length - (targetNode.widgets_values?.length ?? 0); - const v = targetNode.widgets_values?.[targetNodeSlot - offset]; - if (v == null) return; - - const widgetName = Object.values(map)[0]; - const widget = this.node.widgets.find((w) => w.name === widgetName); - if (widget) { - widget.value = v; - } - } - - populateWidgets() { - if (!this.node.widgets) return; - - for (let nodeId = 0; nodeId < this.groupData.nodeData.nodes.length; nodeId++) { - const node = this.groupData.nodeData.nodes[nodeId]; - const map = this.groupData.oldToNewWidgetMap[nodeId] ?? {}; - const widgets = Object.keys(map); - - if (!node.widgets_values?.length) { - // special handling for populating values into reroutes - // this allows primitives connect to them to pick up the correct value - this.populateReroute(node, nodeId, map); - continue; - } - - let linkedShift = 0; - for (let i = 0; i < widgets.length; i++) { - const oldName = widgets[i]; - const newName = map[oldName]; - const widgetIndex = this.node.widgets.findIndex((w) => w.name === newName); - const mainWidget = this.node.widgets[widgetIndex]; - if (this.populatePrimitive(node, nodeId, oldName, i, linkedShift) || widgetIndex === -1) { - // Find the inner widget and shift by the number of linked widgets as they will have been removed too - const innerWidget = this.innerNodes[nodeId].widgets?.find((w) => w.name === oldName); - linkedShift += innerWidget?.linkedWidgets?.length ?? 0; - } - if (widgetIndex === -1) { - continue; - } - - // Populate the main and any linked widget - mainWidget.value = node.widgets_values[i + linkedShift]; - for (let w = 0; w < mainWidget.linkedWidgets?.length; w++) { - this.node.widgets[widgetIndex + w + 1].value = node.widgets_values[i + ++linkedShift]; - } - } - } - } - - replaceNodes(nodes) { - let top; - let left; - - for (let i = 0; i < nodes.length; i++) { - const node = nodes[i]; - if (left == null || node.pos[0] < left) { - left = node.pos[0]; - } - if (top == null || node.pos[1] < top) { - top = node.pos[1]; - } - - this.linkOutputs(node, i); - app.graph.remove(node); - } - - this.linkInputs(); - this.node.pos = [left, top]; - } - - linkOutputs(originalNode, nodeId) { - if (!originalNode.outputs) return; - - for (const output of originalNode.outputs) { - if (!output.links) continue; - // Clone the links as they'll be changed if we reconnect - const links = [...output.links]; - for (const l of links) { - const link = app.graph.links[l]; - if (!link) continue; - - const targetNode = app.graph.getNodeById(link.target_id); - const newSlot = this.groupData.oldToNewOutputMap[nodeId]?.[link.origin_slot]; - if (newSlot != null) { - this.node.connect(newSlot, targetNode, link.target_slot); - } - } - } - } - - linkInputs() { - for (const link of this.groupData.nodeData.links ?? []) { - const [, originSlot, targetId, targetSlot, actualOriginId] = link; - const originNode = app.graph.getNodeById(actualOriginId); - if (!originNode) continue; // this node is in the group - originNode.connect(originSlot, this.node.id, this.groupData.oldToNewInputMap[targetId][targetSlot]); - } - } - - static getGroupData(node) { - return (node.nodeData ?? node.constructor?.nodeData)?.[GROUP]; - } - - static isGroupNode(node) { - return !!node.constructor?.nodeData?.[GROUP]; - } - - static async fromNodes(nodes) { - // Process the nodes into the stored workflow group node data - const builder = new GroupNodeBuilder(nodes); - const res = builder.build(); - if (!res) return; - - const { name, nodeData } = res; - - // Convert this data into a LG node definition and register it - const config = new GroupNodeConfig(name, nodeData); - await config.registerType(); - - const groupNode = LiteGraph.createNode(`workflow/${name}`); - // Reuse the existing nodes for this instance - groupNode.setInnerNodes(builder.nodes); - groupNode[GROUP].populateWidgets(); - app.graph.add(groupNode); - - // Remove all converted nodes and relink them - groupNode[GROUP].replaceNodes(builder.nodes); - return groupNode; - } -} - -function addConvertToGroupOptions() { - function addConvertOption(options, index) { - const selected = Object.values(app.canvas.selected_nodes ?? {}); - const disabled = selected.length < 2 || selected.find((n) => GroupNodeHandler.isGroupNode(n)); - options.splice(index + 1, null, { - content: `Convert to Group Node`, - disabled, - callback: async () => { - return await GroupNodeHandler.fromNodes(selected); - }, - }); - } - - function addManageOption(options, index) { - const groups = app.graph.extra?.groupNodes; - const disabled = !groups || !Object.keys(groups).length; - options.splice(index + 1, null, { - content: `Manage Group Nodes`, - disabled, - callback: () => { - new ManageGroupDialog(app).show(); - }, - }); - } - - // Add to canvas - const getCanvasMenuOptions = LGraphCanvas.prototype.getCanvasMenuOptions; - LGraphCanvas.prototype.getCanvasMenuOptions = function () { - const options = getCanvasMenuOptions.apply(this, arguments); - const index = options.findIndex((o) => o?.content === "Add Group") + 1 || options.length; - addConvertOption(options, index); - addManageOption(options, index + 1); - return options; - }; - - // Add to nodes - const getNodeMenuOptions = LGraphCanvas.prototype.getNodeMenuOptions; - LGraphCanvas.prototype.getNodeMenuOptions = function (node) { - const options = getNodeMenuOptions.apply(this, arguments); - if (!GroupNodeHandler.isGroupNode(node)) { - const index = options.findIndex((o) => o?.content === "Outputs") + 1 || options.length - 1; - addConvertOption(options, index); - } - return options; - }; -} - -const id = "Comfy.GroupNode"; -let globalDefs; -const ext = { - name: id, - setup() { - addConvertToGroupOptions(); - }, - async beforeConfigureGraph(graphData, missingNodeTypes) { - const nodes = graphData?.extra?.groupNodes; - if (nodes) { - await GroupNodeConfig.registerFromWorkflow(nodes, missingNodeTypes); - } - }, - addCustomNodeDefs(defs) { - // Store this so we can mutate it later with group nodes - globalDefs = defs; - }, - nodeCreated(node) { - if (GroupNodeHandler.isGroupNode(node)) { - node[GROUP] = new GroupNodeHandler(node); - } - }, - async refreshComboInNodes(defs) { - // Re-register group nodes so new ones are created with the correct options - Object.assign(globalDefs, defs); - const nodes = app.graph.extra?.groupNodes; - if (nodes) { - await GroupNodeConfig.registerFromWorkflow(nodes, {}); - } - } -}; - -app.registerExtension(ext); \ No newline at end of file +// Shim for extensions\core\groupNode.ts +export const GroupNodeConfig = window.comfyAPI.groupNode.GroupNodeConfig; +export const GroupNodeHandler = window.comfyAPI.groupNode.GroupNodeHandler; diff --git a/web/extensions/core/groupNodeManage.js b/web/extensions/core/groupNodeManage.js index 1ab338386..913c2c60c 100644 --- a/web/extensions/core/groupNodeManage.js +++ b/web/extensions/core/groupNodeManage.js @@ -1,422 +1,2 @@ -import { $el, ComfyDialog } from "../../scripts/ui.js"; -import { DraggableList } from "../../scripts/ui/draggableList.js"; -import { addStylesheet } from "../../scripts/utils.js"; -import { GroupNodeConfig, GroupNodeHandler } from "./groupNode.js"; - -addStylesheet(import.meta.url); - -const ORDER = Symbol(); - -function merge(target, source) { - if (typeof target === "object" && typeof source === "object") { - for (const key in source) { - const sv = source[key]; - if (typeof sv === "object") { - let tv = target[key]; - if (!tv) tv = target[key] = {}; - merge(tv, source[key]); - } else { - target[key] = sv; - } - } - } - - return target; -} - -export class ManageGroupDialog extends ComfyDialog { - /** @type { Record<"Inputs" | "Outputs" | "Widgets", {tab: HTMLAnchorElement, page: HTMLElement}> } */ - tabs = {}; - /** @type { number | null | undefined } */ - selectedNodeIndex; - /** @type { keyof ManageGroupDialog["tabs"] } */ - selectedTab = "Inputs"; - /** @type { string | undefined } */ - selectedGroup; - - /** @type { Record>> } */ - modifications = {}; - - get selectedNodeInnerIndex() { - return +this.nodeItems[this.selectedNodeIndex].dataset.nodeindex; - } - - constructor(app) { - super(); - this.app = app; - this.element = $el("dialog.comfy-group-manage", { - parent: document.body, - }); - } - - changeTab(tab) { - this.tabs[this.selectedTab].tab.classList.remove("active"); - this.tabs[this.selectedTab].page.classList.remove("active"); - this.tabs[tab].tab.classList.add("active"); - this.tabs[tab].page.classList.add("active"); - this.selectedTab = tab; - } - - changeNode(index, force) { - if (!force && this.selectedNodeIndex === index) return; - - if (this.selectedNodeIndex != null) { - this.nodeItems[this.selectedNodeIndex].classList.remove("selected"); - } - this.nodeItems[index].classList.add("selected"); - this.selectedNodeIndex = index; - - if (!this.buildInputsPage() && this.selectedTab === "Inputs") { - this.changeTab("Widgets"); - } - if (!this.buildWidgetsPage() && this.selectedTab === "Widgets") { - this.changeTab("Outputs"); - } - if (!this.buildOutputsPage() && this.selectedTab === "Outputs") { - this.changeTab("Inputs"); - } - - this.changeTab(this.selectedTab); - } - - getGroupData() { - this.groupNodeType = LiteGraph.registered_node_types["workflow/" + this.selectedGroup]; - this.groupNodeDef = this.groupNodeType.nodeData; - this.groupData = GroupNodeHandler.getGroupData(this.groupNodeType); - } - - changeGroup(group, reset = true) { - this.selectedGroup = group; - this.getGroupData(); - - const nodes = this.groupData.nodeData.nodes; - this.nodeItems = nodes.map((n, i) => - $el( - "li.draggable-item", - { - dataset: { - nodeindex: n.index + "", - }, - onclick: () => { - this.changeNode(i); - }, - }, - [ - $el("span.drag-handle"), - $el( - "div", - { - textContent: n.title ?? n.type, - }, - n.title - ? $el("span", { - textContent: n.type, - }) - : [] - ), - ] - ) - ); - - this.innerNodesList.replaceChildren(...this.nodeItems); - - if (reset) { - this.selectedNodeIndex = null; - this.changeNode(0); - } else { - const items = this.draggable.getAllItems(); - let index = items.findIndex(item => item.classList.contains("selected")); - if(index === -1) index = this.selectedNodeIndex; - this.changeNode(index, true); - } - - const ordered = [...nodes]; - this.draggable?.dispose(); - this.draggable = new DraggableList(this.innerNodesList, "li"); - this.draggable.addEventListener("dragend", ({ detail: { oldPosition, newPosition } }) => { - if (oldPosition === newPosition) return; - ordered.splice(newPosition, 0, ordered.splice(oldPosition, 1)[0]); - for (let i = 0; i < ordered.length; i++) { - this.storeModification({ nodeIndex: ordered[i].index, section: ORDER, prop: "order", value: i }); - } - }); - } - - storeModification({ nodeIndex, section, prop, value }) { - const groupMod = (this.modifications[this.selectedGroup] ??= {}); - const nodesMod = (groupMod.nodes ??= {}); - const nodeMod = (nodesMod[nodeIndex ?? this.selectedNodeInnerIndex] ??= {}); - const typeMod = (nodeMod[section] ??= {}); - if (typeof value === "object") { - const objMod = (typeMod[prop] ??= {}); - Object.assign(objMod, value); - } else { - typeMod[prop] = value; - } - } - - getEditElement(section, prop, value, placeholder, checked, checkable = true) { - if (value === placeholder) value = ""; - - const mods = this.modifications[this.selectedGroup]?.nodes?.[this.selectedNodeInnerIndex]?.[section]?.[prop]; - if (mods) { - if (mods.name != null) { - value = mods.name; - } - if (mods.visible != null) { - checked = mods.visible; - } - } - - return $el("div", [ - $el("input", { - value, - placeholder, - type: "text", - onchange: (e) => { - this.storeModification({ section, prop, value: { name: e.target.value } }); - }, - }), - $el("label", { textContent: "Visible" }, [ - $el("input", { - type: "checkbox", - checked, - disabled: !checkable, - onchange: (e) => { - this.storeModification({ section, prop, value: { visible: !!e.target.checked } }); - }, - }), - ]), - ]); - } - - buildWidgetsPage() { - const widgets = this.groupData.oldToNewWidgetMap[this.selectedNodeInnerIndex]; - const items = Object.keys(widgets ?? {}); - const type = app.graph.extra.groupNodes[this.selectedGroup]; - const config = type.config?.[this.selectedNodeInnerIndex]?.input; - this.widgetsPage.replaceChildren( - ...items.map((oldName) => { - return this.getEditElement("input", oldName, widgets[oldName], oldName, config?.[oldName]?.visible !== false); - }) - ); - return !!items.length; - } - - buildInputsPage() { - const inputs = this.groupData.nodeInputs[this.selectedNodeInnerIndex]; - const items = Object.keys(inputs ?? {}); - const type = app.graph.extra.groupNodes[this.selectedGroup]; - const config = type.config?.[this.selectedNodeInnerIndex]?.input; - this.inputsPage.replaceChildren( - ...items - .map((oldName) => { - let value = inputs[oldName]; - if (!value) { - return; - } - - return this.getEditElement("input", oldName, value, oldName, config?.[oldName]?.visible !== false); - }) - .filter(Boolean) - ); - return !!items.length; - } - - buildOutputsPage() { - const nodes = this.groupData.nodeData.nodes; - const innerNodeDef = this.groupData.getNodeDef(nodes[this.selectedNodeInnerIndex]); - const outputs = innerNodeDef?.output ?? []; - const groupOutputs = this.groupData.oldToNewOutputMap[this.selectedNodeInnerIndex]; - - const type = app.graph.extra.groupNodes[this.selectedGroup]; - const config = type.config?.[this.selectedNodeInnerIndex]?.output; - const node = this.groupData.nodeData.nodes[this.selectedNodeInnerIndex]; - const checkable = node.type !== "PrimitiveNode"; - this.outputsPage.replaceChildren( - ...outputs - .map((type, slot) => { - const groupOutputIndex = groupOutputs?.[slot]; - const oldName = innerNodeDef.output_name?.[slot] ?? type; - let value = config?.[slot]?.name; - const visible = config?.[slot]?.visible || groupOutputIndex != null; - if (!value || value === oldName) { - value = ""; - } - return this.getEditElement("output", slot, value, oldName, visible, checkable); - }) - .filter(Boolean) - ); - return !!outputs.length; - } - - show(type) { - const groupNodes = Object.keys(app.graph.extra?.groupNodes ?? {}).sort((a, b) => a.localeCompare(b)); - - this.innerNodesList = $el("ul.comfy-group-manage-list-items"); - this.widgetsPage = $el("section.comfy-group-manage-node-page"); - this.inputsPage = $el("section.comfy-group-manage-node-page"); - this.outputsPage = $el("section.comfy-group-manage-node-page"); - const pages = $el("div", [this.widgetsPage, this.inputsPage, this.outputsPage]); - - this.tabs = [ - ["Inputs", this.inputsPage], - ["Widgets", this.widgetsPage], - ["Outputs", this.outputsPage], - ].reduce((p, [name, page]) => { - p[name] = { - tab: $el("a", { - onclick: () => { - this.changeTab(name); - }, - textContent: name, - }), - page, - }; - return p; - }, {}); - - const outer = $el("div.comfy-group-manage-outer", [ - $el("header", [ - $el("h2", "Group Nodes"), - $el( - "select", - { - onchange: (e) => { - this.changeGroup(e.target.value); - }, - }, - groupNodes.map((g) => - $el("option", { - textContent: g, - selected: "workflow/" + g === type, - value: g, - }) - ) - ), - ]), - $el("main", [ - $el("section.comfy-group-manage-list", this.innerNodesList), - $el("section.comfy-group-manage-node", [ - $el( - "header", - Object.values(this.tabs).map((t) => t.tab) - ), - pages, - ]), - ]), - $el("footer", [ - $el( - "button.comfy-btn", - { - onclick: (e) => { - const node = app.graph._nodes.find((n) => n.type === "workflow/" + this.selectedGroup); - if (node) { - alert("This group node is in use in the current workflow, please first remove these."); - return; - } - if (confirm(`Are you sure you want to remove the node: "${this.selectedGroup}"`)) { - delete app.graph.extra.groupNodes[this.selectedGroup]; - LiteGraph.unregisterNodeType("workflow/" + this.selectedGroup); - } - this.show(); - }, - }, - "Delete Group Node" - ), - $el( - "button.comfy-btn", - { - onclick: async () => { - let nodesByType; - let recreateNodes = []; - const types = {}; - for (const g in this.modifications) { - const type = app.graph.extra.groupNodes[g]; - let config = (type.config ??= {}); - - let nodeMods = this.modifications[g]?.nodes; - if (nodeMods) { - const keys = Object.keys(nodeMods); - if (nodeMods[keys[0]][ORDER]) { - // If any node is reordered, they will all need sequencing - const orderedNodes = []; - const orderedMods = {}; - const orderedConfig = {}; - - for (const n of keys) { - const order = nodeMods[n][ORDER].order; - orderedNodes[order] = type.nodes[+n]; - orderedMods[order] = nodeMods[n]; - orderedNodes[order].index = order; - } - - // Rewrite links - for (const l of type.links) { - if (l[0] != null) l[0] = type.nodes[l[0]].index; - if (l[2] != null) l[2] = type.nodes[l[2]].index; - } - - // Rewrite externals - if (type.external) { - for (const ext of type.external) { - ext[0] = type.nodes[ext[0]]; - } - } - - // Rewrite modifications - for (const id of keys) { - if (config[id]) { - orderedConfig[type.nodes[id].index] = config[id]; - } - delete config[id]; - } - - type.nodes = orderedNodes; - nodeMods = orderedMods; - type.config = config = orderedConfig; - } - - merge(config, nodeMods); - } - - types[g] = type; - - if (!nodesByType) { - nodesByType = app.graph._nodes.reduce((p, n) => { - p[n.type] ??= []; - p[n.type].push(n); - return p; - }, {}); - } - - const nodes = nodesByType["workflow/" + g]; - if (nodes) recreateNodes.push(...nodes); - } - - await GroupNodeConfig.registerFromWorkflow(types, {}); - - for (const node of recreateNodes) { - node.recreate(); - } - - this.modifications = {}; - this.app.graph.setDirtyCanvas(true, true); - this.changeGroup(this.selectedGroup, false); - }, - }, - "Save" - ), - $el("button.comfy-btn", { onclick: () => this.element.close() }, "Close"), - ]), - ]); - - this.element.replaceChildren(outer); - this.changeGroup(type ? groupNodes.find((g) => "workflow/" + g === type) : groupNodes[0]); - this.element.showModal(); - - this.element.addEventListener("close", () => { - this.draggable?.dispose(); - }); - } -} \ No newline at end of file +// Shim for extensions\core\groupNodeManage.ts +export const ManageGroupDialog = window.comfyAPI.groupNodeManage.ManageGroupDialog; diff --git a/web/extensions/core/groupOptions.js b/web/extensions/core/groupOptions.js deleted file mode 100644 index 5dd21e730..000000000 --- a/web/extensions/core/groupOptions.js +++ /dev/null @@ -1,259 +0,0 @@ -import {app} from "../../scripts/app.js"; - -function setNodeMode(node, mode) { - node.mode = mode; - node.graph.change(); -} - -function addNodesToGroup(group, nodes=[]) { - var x1, y1, x2, y2; - var nx1, ny1, nx2, ny2; - var node; - - x1 = y1 = x2 = y2 = -1; - nx1 = ny1 = nx2 = ny2 = -1; - - for (var n of [group._nodes, nodes]) { - for (var i in n) { - node = n[i] - - nx1 = node.pos[0] - ny1 = node.pos[1] - nx2 = node.pos[0] + node.size[0] - ny2 = node.pos[1] + node.size[1] - - if (node.type != "Reroute") { - ny1 -= LiteGraph.NODE_TITLE_HEIGHT; - } - - if (node.flags?.collapsed) { - ny2 = ny1 + LiteGraph.NODE_TITLE_HEIGHT; - - if (node?._collapsed_width) { - nx2 = nx1 + Math.round(node._collapsed_width); - } - } - - if (x1 == -1 || nx1 < x1) { - x1 = nx1; - } - - if (y1 == -1 || ny1 < y1) { - y1 = ny1; - } - - if (x2 == -1 || nx2 > x2) { - x2 = nx2; - } - - if (y2 == -1 || ny2 > y2) { - y2 = ny2; - } - } - } - - var padding = 10; - - y1 = y1 - Math.round(group.font_size * 1.4); - - group.pos = [x1 - padding, y1 - padding]; - group.size = [x2 - x1 + padding * 2, y2 - y1 + padding * 2]; -} - -app.registerExtension({ - name: "Comfy.GroupOptions", - setup() { - const orig = LGraphCanvas.prototype.getCanvasMenuOptions; - // graph_mouse - LGraphCanvas.prototype.getCanvasMenuOptions = function () { - const options = orig.apply(this, arguments); - const group = this.graph.getGroupOnPos(this.graph_mouse[0], this.graph_mouse[1]); - if (!group) { - options.push({ - content: "Add Group For Selected Nodes", - disabled: !Object.keys(app.canvas.selected_nodes || {}).length, - callback: () => { - var group = new LiteGraph.LGraphGroup(); - addNodesToGroup(group, this.selected_nodes) - app.canvas.graph.add(group); - this.graph.change(); - } - }); - - return options; - } - - // Group nodes aren't recomputed until the group is moved, this ensures the nodes are up-to-date - group.recomputeInsideNodes(); - const nodesInGroup = group._nodes; - - options.push({ - content: "Add Selected Nodes To Group", - disabled: !Object.keys(app.canvas.selected_nodes || {}).length, - callback: () => { - addNodesToGroup(group, this.selected_nodes) - this.graph.change(); - } - }); - - // No nodes in group, return default options - if (nodesInGroup.length === 0) { - return options; - } else { - // Add a separator between the default options and the group options - options.push(null); - } - - // Check if all nodes are the same mode - let allNodesAreSameMode = true; - for (let i = 1; i < nodesInGroup.length; i++) { - if (nodesInGroup[i].mode !== nodesInGroup[0].mode) { - allNodesAreSameMode = false; - break; - } - } - - options.push({ - content: "Fit Group To Nodes", - callback: () => { - addNodesToGroup(group) - this.graph.change(); - } - }); - - options.push({ - content: "Select Nodes", - callback: () => { - this.selectNodes(nodesInGroup); - this.graph.change(); - this.canvas.focus(); - } - }); - - // Modes - // 0: Always - // 1: On Event - // 2: Never - // 3: On Trigger - // 4: Bypass - // If all nodes are the same mode, add a menu option to change the mode - if (allNodesAreSameMode) { - const mode = nodesInGroup[0].mode; - switch (mode) { - case 0: - // All nodes are always, option to disable, and bypass - options.push({ - content: "Set Group Nodes to Never", - callback: () => { - for (const node of nodesInGroup) { - setNodeMode(node, 2); - } - } - }); - options.push({ - content: "Bypass Group Nodes", - callback: () => { - for (const node of nodesInGroup) { - setNodeMode(node, 4); - } - } - }); - break; - case 2: - // All nodes are never, option to enable, and bypass - options.push({ - content: "Set Group Nodes to Always", - callback: () => { - for (const node of nodesInGroup) { - setNodeMode(node, 0); - } - } - }); - options.push({ - content: "Bypass Group Nodes", - callback: () => { - for (const node of nodesInGroup) { - setNodeMode(node, 4); - } - } - }); - break; - case 4: - // All nodes are bypass, option to enable, and disable - options.push({ - content: "Set Group Nodes to Always", - callback: () => { - for (const node of nodesInGroup) { - setNodeMode(node, 0); - } - } - }); - options.push({ - content: "Set Group Nodes to Never", - callback: () => { - for (const node of nodesInGroup) { - setNodeMode(node, 2); - } - } - }); - break; - default: - // All nodes are On Trigger or On Event(Or other?), option to disable, set to always, or bypass - options.push({ - content: "Set Group Nodes to Always", - callback: () => { - for (const node of nodesInGroup) { - setNodeMode(node, 0); - } - } - }); - options.push({ - content: "Set Group Nodes to Never", - callback: () => { - for (const node of nodesInGroup) { - setNodeMode(node, 2); - } - } - }); - options.push({ - content: "Bypass Group Nodes", - callback: () => { - for (const node of nodesInGroup) { - setNodeMode(node, 4); - } - } - }); - break; - } - } else { - // Nodes are not all the same mode, add a menu option to change the mode to always, never, or bypass - options.push({ - content: "Set Group Nodes to Always", - callback: () => { - for (const node of nodesInGroup) { - setNodeMode(node, 0); - } - } - }); - options.push({ - content: "Set Group Nodes to Never", - callback: () => { - for (const node of nodesInGroup) { - setNodeMode(node, 2); - } - } - }); - options.push({ - content: "Bypass Group Nodes", - callback: () => { - for (const node of nodesInGroup) { - setNodeMode(node, 4); - } - } - }); - } - - return options - } - } -}); diff --git a/web/extensions/core/invertMenuScrolling.js b/web/extensions/core/invertMenuScrolling.js deleted file mode 100644 index 98a1786ab..000000000 --- a/web/extensions/core/invertMenuScrolling.js +++ /dev/null @@ -1,36 +0,0 @@ -import { app } from "../../scripts/app.js"; - -// Inverts the scrolling of context menus - -const id = "Comfy.InvertMenuScrolling"; -app.registerExtension({ - name: id, - init() { - const ctxMenu = LiteGraph.ContextMenu; - const replace = () => { - LiteGraph.ContextMenu = function (values, options) { - options = options || {}; - if (options.scroll_speed) { - options.scroll_speed *= -1; - } else { - options.scroll_speed = -0.1; - } - return ctxMenu.call(this, values, options); - }; - LiteGraph.ContextMenu.prototype = ctxMenu.prototype; - }; - app.ui.settings.addSetting({ - id, - name: "Invert Menu Scrolling", - type: "boolean", - defaultValue: false, - onChange(value) { - if (value) { - replace(); - } else { - LiteGraph.ContextMenu = ctxMenu; - } - }, - }); - }, -}); diff --git a/web/extensions/core/keybinds.js b/web/extensions/core/keybinds.js deleted file mode 100644 index ac367c116..000000000 --- a/web/extensions/core/keybinds.js +++ /dev/null @@ -1,69 +0,0 @@ -import {app} from "../../scripts/app.js"; - -app.registerExtension({ - name: "Comfy.Keybinds", - init() { - const keybindListener = function (event) { - const modifierPressed = event.ctrlKey || event.metaKey; - - // Queue prompt using ctrl or command + enter - if (modifierPressed && event.key === "Enter") { - app.queuePrompt(event.shiftKey ? -1 : 0).then(); - return; - } - - const target = event.composedPath()[0]; - if (["INPUT", "TEXTAREA"].includes(target.tagName)) { - return; - } - - const modifierKeyIdMap = { - s: "#comfy-save-button", - o: "#comfy-file-input", - Backspace: "#comfy-clear-button", - d: "#comfy-load-default-button", - }; - - const modifierKeybindId = modifierKeyIdMap[event.key]; - if (modifierPressed && modifierKeybindId) { - event.preventDefault(); - - const elem = document.querySelector(modifierKeybindId); - elem.click(); - return; - } - - // Finished Handling all modifier keybinds, now handle the rest - if (event.ctrlKey || event.altKey || event.metaKey) { - return; - } - - // Close out of modals using escape - if (event.key === "Escape") { - const modals = document.querySelectorAll(".comfy-modal"); - const modal = Array.from(modals).find(modal => window.getComputedStyle(modal).getPropertyValue("display") !== "none"); - if (modal) { - modal.style.display = "none"; - } - - [...document.querySelectorAll("dialog")].forEach(d => { - d.close(); - }); - } - - const keyIdMap = { - q: "#comfy-view-queue-button", - h: "#comfy-view-history-button", - r: "#comfy-refresh-button", - }; - - const buttonId = keyIdMap[event.key]; - if (buttonId) { - const button = document.querySelector(buttonId); - button.click(); - } - } - - window.addEventListener("keydown", keybindListener, true); - } -}); diff --git a/web/extensions/core/linkRenderMode.js b/web/extensions/core/linkRenderMode.js deleted file mode 100644 index fb4df4234..000000000 --- a/web/extensions/core/linkRenderMode.js +++ /dev/null @@ -1,25 +0,0 @@ -import { app } from "../../scripts/app.js"; - -const id = "Comfy.LinkRenderMode"; -const ext = { - name: id, - async setup(app) { - app.ui.settings.addSetting({ - id, - name: "Link Render Mode", - defaultValue: 2, - type: "combo", - options: [...LiteGraph.LINK_RENDER_MODES, "Hidden"].map((m, i) => ({ - value: i, - text: m, - selected: i == app.canvas.links_render_mode, - })), - onChange(value) { - app.canvas.links_render_mode = +value; - app.graph.setDirtyCanvas(true); - }, - }); - }, -}; - -app.registerExtension(ext); diff --git a/web/extensions/core/maskeditor.js b/web/extensions/core/maskeditor.js deleted file mode 100644 index 36f7496e7..000000000 --- a/web/extensions/core/maskeditor.js +++ /dev/null @@ -1,967 +0,0 @@ -import { app } from "../../scripts/app.js"; -import { ComfyDialog, $el } from "../../scripts/ui.js"; -import { ComfyApp } from "../../scripts/app.js"; -import { api } from "../../scripts/api.js" -import { ClipspaceDialog } from "./clipspace.js"; - -// Helper function to convert a data URL to a Blob object -function dataURLToBlob(dataURL) { - const parts = dataURL.split(';base64,'); - const contentType = parts[0].split(':')[1]; - const byteString = atob(parts[1]); - const arrayBuffer = new ArrayBuffer(byteString.length); - const uint8Array = new Uint8Array(arrayBuffer); - for (let i = 0; i < byteString.length; i++) { - uint8Array[i] = byteString.charCodeAt(i); - } - return new Blob([arrayBuffer], { type: contentType }); -} - -function loadedImageToBlob(image) { - const canvas = document.createElement('canvas'); - - canvas.width = image.width; - canvas.height = image.height; - - const ctx = canvas.getContext('2d'); - - ctx.drawImage(image, 0, 0); - - const dataURL = canvas.toDataURL('image/png', 1); - const blob = dataURLToBlob(dataURL); - - return blob; -} - -function loadImage(imagePath) { - return new Promise((resolve, reject) => { - const image = new Image(); - - image.onload = function() { - resolve(image); - }; - - image.src = imagePath; - }); -} - -async function uploadMask(filepath, formData) { - await api.fetchApi('/upload/mask', { - method: 'POST', - body: formData - }).then(response => {}).catch(error => { - console.error('Error:', error); - }); - - ComfyApp.clipspace.imgs[ComfyApp.clipspace['selectedIndex']] = new Image(); - ComfyApp.clipspace.imgs[ComfyApp.clipspace['selectedIndex']].src = api.apiURL("/view?" + new URLSearchParams(filepath).toString() + app.getPreviewFormatParam() + app.getRandParam()); - - if(ComfyApp.clipspace.images) - ComfyApp.clipspace.images[ComfyApp.clipspace['selectedIndex']] = filepath; - - ClipspaceDialog.invalidatePreview(); -} - -function prepare_mask(image, maskCanvas, maskCtx, maskColor) { - // paste mask data into alpha channel - maskCtx.drawImage(image, 0, 0, maskCanvas.width, maskCanvas.height); - const maskData = maskCtx.getImageData(0, 0, maskCanvas.width, maskCanvas.height); - - // invert mask - for (let i = 0; i < maskData.data.length; i += 4) { - if(maskData.data[i+3] == 255) - maskData.data[i+3] = 0; - else - maskData.data[i+3] = 255; - - maskData.data[i] = maskColor.r; - maskData.data[i+1] = maskColor.g; - maskData.data[i+2] = maskColor.b; - } - - maskCtx.globalCompositeOperation = 'source-over'; - maskCtx.putImageData(maskData, 0, 0); -} - -class MaskEditorDialog extends ComfyDialog { - static instance = null; - - static getInstance() { - if(!MaskEditorDialog.instance) { - MaskEditorDialog.instance = new MaskEditorDialog(app); - } - - return MaskEditorDialog.instance; - } - - is_layout_created = false; - - constructor() { - super(); - this.element = $el("div.comfy-modal", { parent: document.body }, - [ $el("div.comfy-modal-content", - [...this.createButtons()]), - ]); - } - - createButtons() { - return []; - } - - createButton(name, callback) { - var button = document.createElement("button"); - button.style.pointerEvents = "auto"; - button.innerText = name; - button.addEventListener("click", callback); - return button; - } - - createLeftButton(name, callback) { - var button = this.createButton(name, callback); - button.style.cssFloat = "left"; - button.style.marginRight = "4px"; - return button; - } - - createRightButton(name, callback) { - var button = this.createButton(name, callback); - button.style.cssFloat = "right"; - button.style.marginLeft = "4px"; - return button; - } - - createLeftSlider(self, name, callback) { - const divElement = document.createElement('div'); - divElement.id = "maskeditor-slider"; - divElement.style.cssFloat = "left"; - divElement.style.fontFamily = "sans-serif"; - divElement.style.marginRight = "4px"; - divElement.style.color = "var(--input-text)"; - divElement.style.backgroundColor = "var(--comfy-input-bg)"; - divElement.style.borderRadius = "8px"; - divElement.style.borderColor = "var(--border-color)"; - divElement.style.borderStyle = "solid"; - divElement.style.fontSize = "15px"; - divElement.style.height = "21px"; - divElement.style.padding = "1px 6px"; - divElement.style.display = "flex"; - divElement.style.position = "relative"; - divElement.style.top = "2px"; - divElement.style.pointerEvents = "auto"; - self.brush_slider_input = document.createElement('input'); - self.brush_slider_input.setAttribute('type', 'range'); - self.brush_slider_input.setAttribute('min', '1'); - self.brush_slider_input.setAttribute('max', '100'); - self.brush_slider_input.setAttribute('value', '10'); - const labelElement = document.createElement("label"); - labelElement.textContent = name; - - divElement.appendChild(labelElement); - divElement.appendChild(self.brush_slider_input); - - self.brush_slider_input.addEventListener("change", callback); - - return divElement; - } - - createOpacitySlider(self, name, callback) { - const divElement = document.createElement('div'); - divElement.id = "maskeditor-opacity-slider"; - divElement.style.cssFloat = "left"; - divElement.style.fontFamily = "sans-serif"; - divElement.style.marginRight = "4px"; - divElement.style.color = "var(--input-text)"; - divElement.style.backgroundColor = "var(--comfy-input-bg)"; - divElement.style.borderRadius = "8px"; - divElement.style.borderColor = "var(--border-color)"; - divElement.style.borderStyle = "solid"; - divElement.style.fontSize = "15px"; - divElement.style.height = "21px"; - divElement.style.padding = "1px 6px"; - divElement.style.display = "flex"; - divElement.style.position = "relative"; - divElement.style.top = "2px"; - divElement.style.pointerEvents = "auto"; - self.opacity_slider_input = document.createElement('input'); - self.opacity_slider_input.setAttribute('type', 'range'); - self.opacity_slider_input.setAttribute('min', '0.1'); - self.opacity_slider_input.setAttribute('max', '1.0'); - self.opacity_slider_input.setAttribute('step', '0.01') - self.opacity_slider_input.setAttribute('value', '0.7'); - const labelElement = document.createElement("label"); - labelElement.textContent = name; - - divElement.appendChild(labelElement); - divElement.appendChild(self.opacity_slider_input); - - self.opacity_slider_input.addEventListener("input", callback); - - return divElement; - } - - setlayout(imgCanvas, maskCanvas) { - const self = this; - - // If it is specified as relative, using it only as a hidden placeholder for padding is recommended - // to prevent anomalies where it exceeds a certain size and goes outside of the window. - var bottom_panel = document.createElement("div"); - bottom_panel.style.position = "absolute"; - bottom_panel.style.bottom = "0px"; - bottom_panel.style.left = "20px"; - bottom_panel.style.right = "20px"; - bottom_panel.style.height = "50px"; - bottom_panel.style.pointerEvents = "none"; - - var brush = document.createElement("div"); - brush.id = "brush"; - brush.style.backgroundColor = "transparent"; - brush.style.outline = "1px dashed black"; - brush.style.boxShadow = "0 0 0 1px white"; - brush.style.borderRadius = "50%"; - brush.style.MozBorderRadius = "50%"; - brush.style.WebkitBorderRadius = "50%"; - brush.style.position = "absolute"; - brush.style.zIndex = 8889; - brush.style.pointerEvents = "none"; - this.brush = brush; - this.element.appendChild(imgCanvas); - this.element.appendChild(maskCanvas); - this.element.appendChild(bottom_panel); - document.body.appendChild(brush); - - var clearButton = this.createLeftButton("Clear", () => { - self.maskCtx.clearRect(0, 0, self.maskCanvas.width, self.maskCanvas.height); - }); - - this.brush_size_slider = this.createLeftSlider(self, "Thickness", (event) => { - self.brush_size = event.target.value; - self.updateBrushPreview(self, null, null); - }); - - this.brush_opacity_slider = this.createOpacitySlider(self, "Opacity", (event) => { - self.brush_opacity = event.target.value; - if (self.brush_color_mode !== "negative") { - self.maskCanvas.style.opacity = self.brush_opacity; - } - }); - - this.colorButton = this.createLeftButton(this.getColorButtonText(), () => { - if (self.brush_color_mode === "black") { - self.brush_color_mode = "white"; - } - else if (self.brush_color_mode === "white") { - self.brush_color_mode = "negative"; - } - else { - self.brush_color_mode = "black"; - } - - self.updateWhenBrushColorModeChanged(); - }); - - var cancelButton = this.createRightButton("Cancel", () => { - document.removeEventListener("mouseup", MaskEditorDialog.handleMouseUp); - document.removeEventListener("keydown", MaskEditorDialog.handleKeyDown); - self.close(); - }); - - this.saveButton = this.createRightButton("Save", () => { - document.removeEventListener("mouseup", MaskEditorDialog.handleMouseUp); - document.removeEventListener("keydown", MaskEditorDialog.handleKeyDown); - self.save(); - }); - - this.element.appendChild(imgCanvas); - this.element.appendChild(maskCanvas); - this.element.appendChild(bottom_panel); - - bottom_panel.appendChild(clearButton); - bottom_panel.appendChild(this.saveButton); - bottom_panel.appendChild(cancelButton); - bottom_panel.appendChild(this.brush_size_slider); - bottom_panel.appendChild(this.brush_opacity_slider); - bottom_panel.appendChild(this.colorButton); - - imgCanvas.style.position = "absolute"; - maskCanvas.style.position = "absolute"; - - imgCanvas.style.top = "200"; - imgCanvas.style.left = "0"; - - maskCanvas.style.top = imgCanvas.style.top; - maskCanvas.style.left = imgCanvas.style.left; - - const maskCanvasStyle = this.getMaskCanvasStyle(); - maskCanvas.style.mixBlendMode = maskCanvasStyle.mixBlendMode; - maskCanvas.style.opacity = maskCanvasStyle.opacity; - } - - async show() { - this.zoom_ratio = 1.0; - this.pan_x = 0; - this.pan_y = 0; - - if(!this.is_layout_created) { - // layout - const imgCanvas = document.createElement('canvas'); - const maskCanvas = document.createElement('canvas'); - - imgCanvas.id = "imageCanvas"; - maskCanvas.id = "maskCanvas"; - - this.setlayout(imgCanvas, maskCanvas); - - // prepare content - this.imgCanvas = imgCanvas; - this.maskCanvas = maskCanvas; - this.maskCtx = maskCanvas.getContext('2d', {willReadFrequently: true }); - - this.setEventHandler(maskCanvas); - - this.is_layout_created = true; - - // replacement of onClose hook since close is not real close - const self = this; - const observer = new MutationObserver(function(mutations) { - mutations.forEach(function(mutation) { - if (mutation.type === 'attributes' && mutation.attributeName === 'style') { - if(self.last_display_style && self.last_display_style != 'none' && self.element.style.display == 'none') { - document.removeEventListener("mouseup", MaskEditorDialog.handleMouseUp); - self.brush.style.display = "none"; - ComfyApp.onClipspaceEditorClosed(); - } - - self.last_display_style = self.element.style.display; - } - }); - }); - - const config = { attributes: true }; - observer.observe(this.element, config); - } - - // The keydown event needs to be reconfigured when closing the dialog as it gets removed. - document.addEventListener('keydown', MaskEditorDialog.handleKeyDown); - - if(ComfyApp.clipspace_return_node) { - this.saveButton.innerText = "Save to node"; - } - else { - this.saveButton.innerText = "Save"; - } - this.saveButton.disabled = false; - - this.element.style.display = "block"; - this.element.style.width = "85%"; - this.element.style.margin = "0 7.5%"; - this.element.style.height = "100vh"; - this.element.style.top = "50%"; - this.element.style.left = "42%"; - this.element.style.zIndex = 8888; // NOTE: alert dialog must be high priority. - - await this.setImages(this.imgCanvas); - - this.is_visible = true; - } - - isOpened() { - return this.element.style.display == "block"; - } - - invalidateCanvas(orig_image, mask_image) { - this.imgCanvas.width = orig_image.width; - this.imgCanvas.height = orig_image.height; - - this.maskCanvas.width = orig_image.width; - this.maskCanvas.height = orig_image.height; - - let imgCtx = this.imgCanvas.getContext('2d', {willReadFrequently: true }); - let maskCtx = this.maskCanvas.getContext('2d', {willReadFrequently: true }); - - imgCtx.drawImage(orig_image, 0, 0, orig_image.width, orig_image.height); - prepare_mask(mask_image, this.maskCanvas, maskCtx, this.getMaskColor()); - } - - async setImages(imgCanvas) { - let self = this; - - const imgCtx = imgCanvas.getContext('2d', {willReadFrequently: true }); - const maskCtx = this.maskCtx; - const maskCanvas = this.maskCanvas; - - imgCtx.clearRect(0,0,this.imgCanvas.width,this.imgCanvas.height); - maskCtx.clearRect(0,0,this.maskCanvas.width,this.maskCanvas.height); - - // image load - const filepath = ComfyApp.clipspace.images; - - const alpha_url = new URL(ComfyApp.clipspace.imgs[ComfyApp.clipspace['selectedIndex']].src) - alpha_url.searchParams.delete('channel'); - alpha_url.searchParams.delete('preview'); - alpha_url.searchParams.set('channel', 'a'); - let mask_image = await loadImage(alpha_url); - - // original image load - const rgb_url = new URL(ComfyApp.clipspace.imgs[ComfyApp.clipspace['selectedIndex']].src); - rgb_url.searchParams.delete('channel'); - rgb_url.searchParams.set('channel', 'rgb'); - this.image = new Image(); - this.image.onload = function() { - maskCanvas.width = self.image.width; - maskCanvas.height = self.image.height; - - self.invalidateCanvas(self.image, mask_image); - self.initializeCanvasPanZoom(); - }; - this.image.src = rgb_url; - } - - initializeCanvasPanZoom() { - // set initialize - let drawWidth = this.image.width; - let drawHeight = this.image.height; - - let width = this.element.clientWidth; - let height = this.element.clientHeight; - - if (this.image.width > width) { - drawWidth = width; - drawHeight = (drawWidth / this.image.width) * this.image.height; - } - - if (drawHeight > height) { - drawHeight = height; - drawWidth = (drawHeight / this.image.height) * this.image.width; - } - - this.zoom_ratio = drawWidth/this.image.width; - - const canvasX = (width - drawWidth) / 2; - const canvasY = (height - drawHeight) / 2; - this.pan_x = canvasX; - this.pan_y = canvasY; - - this.invalidatePanZoom(); - } - - - invalidatePanZoom() { - let raw_width = this.image.width * this.zoom_ratio; - let raw_height = this.image.height * this.zoom_ratio; - - if(this.pan_x + raw_width < 10) { - this.pan_x = 10 - raw_width; - } - - if(this.pan_y + raw_height < 10) { - this.pan_y = 10 - raw_height; - } - - let width = `${raw_width}px`; - let height = `${raw_height}px`; - - let left = `${this.pan_x}px`; - let top = `${this.pan_y}px`; - - this.maskCanvas.style.width = width; - this.maskCanvas.style.height = height; - this.maskCanvas.style.left = left; - this.maskCanvas.style.top = top; - - this.imgCanvas.style.width = width; - this.imgCanvas.style.height = height; - this.imgCanvas.style.left = left; - this.imgCanvas.style.top = top; - } - - - setEventHandler(maskCanvas) { - const self = this; - - if(!this.handler_registered) { - maskCanvas.addEventListener("contextmenu", (event) => { - event.preventDefault(); - }); - - this.element.addEventListener('wheel', (event) => this.handleWheelEvent(self,event)); - this.element.addEventListener('pointermove', (event) => this.pointMoveEvent(self,event)); - this.element.addEventListener('touchmove', (event) => this.pointMoveEvent(self,event)); - - this.element.addEventListener('dragstart', (event) => { - if(event.ctrlKey) { - event.preventDefault(); - } - }); - - maskCanvas.addEventListener('pointerdown', (event) => this.handlePointerDown(self,event)); - maskCanvas.addEventListener('pointermove', (event) => this.draw_move(self,event)); - maskCanvas.addEventListener('touchmove', (event) => this.draw_move(self,event)); - maskCanvas.addEventListener('pointerover', (event) => { this.brush.style.display = "block"; }); - maskCanvas.addEventListener('pointerleave', (event) => { this.brush.style.display = "none"; }); - - document.addEventListener('pointerup', MaskEditorDialog.handlePointerUp); - - this.handler_registered = true; - } - } - - getMaskCanvasStyle() { - if (this.brush_color_mode === "negative") { - return { - mixBlendMode: "difference", - opacity: "1", - }; - } - else { - return { - mixBlendMode: "initial", - opacity: this.brush_opacity, - }; - } - } - - getMaskColor() { - if (this.brush_color_mode === "black") { - return { r: 0, g: 0, b: 0 }; - } - if (this.brush_color_mode === "white") { - return { r: 255, g: 255, b: 255 }; - } - if (this.brush_color_mode === "negative") { - // negative effect only works with white color - return { r: 255, g: 255, b: 255 }; - } - - return { r: 0, g: 0, b: 0 }; - } - - getMaskFillStyle() { - const maskColor = this.getMaskColor(); - - return "rgb(" + maskColor.r + "," + maskColor.g + "," + maskColor.b + ")"; - } - - getColorButtonText() { - let colorCaption = "unknown"; - - if (this.brush_color_mode === "black") { - colorCaption = "black"; - } - else if (this.brush_color_mode === "white") { - colorCaption = "white"; - } - else if (this.brush_color_mode === "negative") { - colorCaption = "negative"; - } - - return "Color: " + colorCaption; - } - - updateWhenBrushColorModeChanged() { - this.colorButton.innerText = this.getColorButtonText(); - - // update mask canvas css styles - - const maskCanvasStyle = this.getMaskCanvasStyle(); - this.maskCanvas.style.mixBlendMode = maskCanvasStyle.mixBlendMode; - this.maskCanvas.style.opacity = maskCanvasStyle.opacity; - - // update mask canvas rgb colors - - const maskColor = this.getMaskColor(); - - const maskData = this.maskCtx.getImageData(0, 0, this.maskCanvas.width, this.maskCanvas.height); - - for (let i = 0; i < maskData.data.length; i += 4) { - maskData.data[i] = maskColor.r; - maskData.data[i+1] = maskColor.g; - maskData.data[i+2] = maskColor.b; - } - - this.maskCtx.putImageData(maskData, 0, 0); - } - - brush_opacity = 0.7; - brush_size = 10; - brush_color_mode = "black"; - drawing_mode = false; - lastx = -1; - lasty = -1; - lasttime = 0; - - static handleKeyDown(event) { - const self = MaskEditorDialog.instance; - if (event.key === ']') { - self.brush_size = Math.min(self.brush_size+2, 100); - self.brush_slider_input.value = self.brush_size; - } else if (event.key === '[') { - self.brush_size = Math.max(self.brush_size-2, 1); - self.brush_slider_input.value = self.brush_size; - } else if(event.key === 'Enter') { - self.save(); - } - - self.updateBrushPreview(self); - } - - static handlePointerUp(event) { - event.preventDefault(); - - this.mousedown_x = null; - this.mousedown_y = null; - - MaskEditorDialog.instance.drawing_mode = false; - } - - updateBrushPreview(self) { - const brush = self.brush; - - var centerX = self.cursorX; - var centerY = self.cursorY; - - brush.style.width = self.brush_size * 2 * this.zoom_ratio + "px"; - brush.style.height = self.brush_size * 2 * this.zoom_ratio + "px"; - brush.style.left = (centerX - self.brush_size * this.zoom_ratio) + "px"; - brush.style.top = (centerY - self.brush_size * this.zoom_ratio) + "px"; - } - - handleWheelEvent(self, event) { - event.preventDefault(); - - if(event.ctrlKey) { - // zoom canvas - if(event.deltaY < 0) { - this.zoom_ratio = Math.min(10.0, this.zoom_ratio+0.2); - } - else { - this.zoom_ratio = Math.max(0.2, this.zoom_ratio-0.2); - } - - this.invalidatePanZoom(); - } - else { - // adjust brush size - if(event.deltaY < 0) - this.brush_size = Math.min(this.brush_size+2, 100); - else - this.brush_size = Math.max(this.brush_size-2, 1); - - this.brush_slider_input.value = this.brush_size; - - this.updateBrushPreview(this); - } - } - - pointMoveEvent(self, event) { - this.cursorX = event.pageX; - this.cursorY = event.pageY; - - self.updateBrushPreview(self); - - if(event.ctrlKey) { - event.preventDefault(); - self.pan_move(self, event); - } - - let left_button_down = window.TouchEvent && event instanceof TouchEvent || event.buttons == 1; - - if(event.shiftKey && left_button_down) { - self.drawing_mode = false; - - const y = event.clientY; - let delta = (self.zoom_lasty - y)*0.005; - self.zoom_ratio = Math.max(Math.min(10.0, self.last_zoom_ratio - delta), 0.2); - - this.invalidatePanZoom(); - return; - } - } - - pan_move(self, event) { - if(event.buttons == 1) { - if(this.mousedown_x) { - let deltaX = this.mousedown_x - event.clientX; - let deltaY = this.mousedown_y - event.clientY; - - self.pan_x = this.mousedown_pan_x - deltaX; - self.pan_y = this.mousedown_pan_y - deltaY; - - self.invalidatePanZoom(); - } - } - } - - draw_move(self, event) { - if(event.ctrlKey || event.shiftKey) { - return; - } - - event.preventDefault(); - - this.cursorX = event.pageX; - this.cursorY = event.pageY; - - self.updateBrushPreview(self); - - let left_button_down = window.TouchEvent && event instanceof TouchEvent || event.buttons == 1; - let right_button_down = [2, 5, 32].includes(event.buttons); - - if (!event.altKey && left_button_down) { - var diff = performance.now() - self.lasttime; - - const maskRect = self.maskCanvas.getBoundingClientRect(); - - var x = event.offsetX; - var y = event.offsetY - - if(event.offsetX == null) { - x = event.targetTouches[0].clientX - maskRect.left; - } - - if(event.offsetY == null) { - y = event.targetTouches[0].clientY - maskRect.top; - } - - x /= self.zoom_ratio; - y /= self.zoom_ratio; - - var brush_size = this.brush_size; - if(event instanceof PointerEvent && event.pointerType == 'pen') { - brush_size *= event.pressure; - this.last_pressure = event.pressure; - } - else if(window.TouchEvent && event instanceof TouchEvent && diff < 20){ - // The firing interval of PointerEvents in Pen is unreliable, so it is supplemented by TouchEvents. - brush_size *= this.last_pressure; - } - else { - brush_size = this.brush_size; - } - - if(diff > 20 && !this.drawing_mode) - requestAnimationFrame(() => { - self.maskCtx.beginPath(); - self.maskCtx.fillStyle = this.getMaskFillStyle(); - self.maskCtx.globalCompositeOperation = "source-over"; - self.maskCtx.arc(x, y, brush_size, 0, Math.PI * 2, false); - self.maskCtx.fill(); - self.lastx = x; - self.lasty = y; - }); - else - requestAnimationFrame(() => { - self.maskCtx.beginPath(); - self.maskCtx.fillStyle = this.getMaskFillStyle(); - self.maskCtx.globalCompositeOperation = "source-over"; - - var dx = x - self.lastx; - var dy = y - self.lasty; - - var distance = Math.sqrt(dx * dx + dy * dy); - var directionX = dx / distance; - var directionY = dy / distance; - - for (var i = 0; i < distance; i+=5) { - var px = self.lastx + (directionX * i); - var py = self.lasty + (directionY * i); - self.maskCtx.arc(px, py, brush_size, 0, Math.PI * 2, false); - self.maskCtx.fill(); - } - self.lastx = x; - self.lasty = y; - }); - - self.lasttime = performance.now(); - } - else if((event.altKey && left_button_down) || right_button_down) { - const maskRect = self.maskCanvas.getBoundingClientRect(); - const x = (event.offsetX || event.targetTouches[0].clientX - maskRect.left) / self.zoom_ratio; - const y = (event.offsetY || event.targetTouches[0].clientY - maskRect.top) / self.zoom_ratio; - - var brush_size = this.brush_size; - if(event instanceof PointerEvent && event.pointerType == 'pen') { - brush_size *= event.pressure; - this.last_pressure = event.pressure; - } - else if(window.TouchEvent && event instanceof TouchEvent && diff < 20){ - brush_size *= this.last_pressure; - } - else { - brush_size = this.brush_size; - } - - if(diff > 20 && !drawing_mode) // cannot tracking drawing_mode for touch event - requestAnimationFrame(() => { - self.maskCtx.beginPath(); - self.maskCtx.globalCompositeOperation = "destination-out"; - self.maskCtx.arc(x, y, brush_size, 0, Math.PI * 2, false); - self.maskCtx.fill(); - self.lastx = x; - self.lasty = y; - }); - else - requestAnimationFrame(() => { - self.maskCtx.beginPath(); - self.maskCtx.globalCompositeOperation = "destination-out"; - - var dx = x - self.lastx; - var dy = y - self.lasty; - - var distance = Math.sqrt(dx * dx + dy * dy); - var directionX = dx / distance; - var directionY = dy / distance; - - for (var i = 0; i < distance; i+=5) { - var px = self.lastx + (directionX * i); - var py = self.lasty + (directionY * i); - self.maskCtx.arc(px, py, brush_size, 0, Math.PI * 2, false); - self.maskCtx.fill(); - } - self.lastx = x; - self.lasty = y; - }); - - self.lasttime = performance.now(); - } - } - - handlePointerDown(self, event) { - if(event.ctrlKey) { - if (event.buttons == 1) { - this.mousedown_x = event.clientX; - this.mousedown_y = event.clientY; - - this.mousedown_pan_x = this.pan_x; - this.mousedown_pan_y = this.pan_y; - } - return; - } - - var brush_size = this.brush_size; - if(event instanceof PointerEvent && event.pointerType == 'pen') { - brush_size *= event.pressure; - this.last_pressure = event.pressure; - } - - if ([0, 2, 5].includes(event.button)) { - self.drawing_mode = true; - - event.preventDefault(); - - if(event.shiftKey) { - self.zoom_lasty = event.clientY; - self.last_zoom_ratio = self.zoom_ratio; - return; - } - - const maskRect = self.maskCanvas.getBoundingClientRect(); - const x = (event.offsetX || event.targetTouches[0].clientX - maskRect.left) / self.zoom_ratio; - const y = (event.offsetY || event.targetTouches[0].clientY - maskRect.top) / self.zoom_ratio; - - self.maskCtx.beginPath(); - if (!event.altKey && event.button == 0) { - self.maskCtx.fillStyle = this.getMaskFillStyle(); - self.maskCtx.globalCompositeOperation = "source-over"; - } else { - self.maskCtx.globalCompositeOperation = "destination-out"; - } - self.maskCtx.arc(x, y, brush_size, 0, Math.PI * 2, false); - self.maskCtx.fill(); - self.lastx = x; - self.lasty = y; - self.lasttime = performance.now(); - } - } - - async save() { - const backupCanvas = document.createElement('canvas'); - const backupCtx = backupCanvas.getContext('2d', {willReadFrequently:true}); - backupCanvas.width = this.image.width; - backupCanvas.height = this.image.height; - - backupCtx.clearRect(0,0, backupCanvas.width, backupCanvas.height); - backupCtx.drawImage(this.maskCanvas, - 0, 0, this.maskCanvas.width, this.maskCanvas.height, - 0, 0, backupCanvas.width, backupCanvas.height); - - // paste mask data into alpha channel - const backupData = backupCtx.getImageData(0, 0, backupCanvas.width, backupCanvas.height); - - // refine mask image - for (let i = 0; i < backupData.data.length; i += 4) { - if(backupData.data[i+3] == 255) - backupData.data[i+3] = 0; - else - backupData.data[i+3] = 255; - - backupData.data[i] = 0; - backupData.data[i+1] = 0; - backupData.data[i+2] = 0; - } - - backupCtx.globalCompositeOperation = 'source-over'; - backupCtx.putImageData(backupData, 0, 0); - - const formData = new FormData(); - const filename = "clipspace-mask-" + performance.now() + ".png"; - - const item = - { - "filename": filename, - "subfolder": "clipspace", - "type": "input", - }; - - if(ComfyApp.clipspace.images) - ComfyApp.clipspace.images[0] = item; - - if(ComfyApp.clipspace.widgets) { - const index = ComfyApp.clipspace.widgets.findIndex(obj => obj.name === 'image'); - - if(index >= 0) - ComfyApp.clipspace.widgets[index].value = item; - } - - const dataURL = backupCanvas.toDataURL(); - const blob = dataURLToBlob(dataURL); - - let original_url = new URL(this.image.src); - - const original_ref = { filename: original_url.searchParams.get('filename') }; - - let original_subfolder = original_url.searchParams.get("subfolder"); - if(original_subfolder) - original_ref.subfolder = original_subfolder; - - let original_type = original_url.searchParams.get("type"); - if(original_type) - original_ref.type = original_type; - - formData.append('image', blob, filename); - formData.append('original_ref', JSON.stringify(original_ref)); - formData.append('type', "input"); - formData.append('subfolder', "clipspace"); - - this.saveButton.innerText = "Saving..."; - this.saveButton.disabled = true; - await uploadMask(item, formData); - ComfyApp.onClipspaceEditorSave(); - this.close(); - } -} - -app.registerExtension({ - name: "Comfy.MaskEditor", - init(app) { - ComfyApp.open_maskeditor = - function () { - const dlg = MaskEditorDialog.getInstance(); - if(!dlg.isOpened()) { - dlg.show(); - } - }; - - const context_predicate = () => ComfyApp.clipspace && ComfyApp.clipspace.imgs && ComfyApp.clipspace.imgs.length > 0 - ClipspaceDialog.registerButton("MaskEditor", context_predicate, ComfyApp.open_maskeditor); - } -}); diff --git a/web/extensions/core/nodeTemplates.js b/web/extensions/core/nodeTemplates.js deleted file mode 100644 index 9350ba654..000000000 --- a/web/extensions/core/nodeTemplates.js +++ /dev/null @@ -1,412 +0,0 @@ -import { app } from "../../scripts/app.js"; -import { api } from "../../scripts/api.js"; -import { ComfyDialog, $el } from "../../scripts/ui.js"; -import { GroupNodeConfig, GroupNodeHandler } from "./groupNode.js"; - -// Adds the ability to save and add multiple nodes as a template -// To save: -// Select multiple nodes (ctrl + drag to select a region or ctrl+click individual nodes) -// Right click the canvas -// Save Node Template -> give it a name -// -// To add: -// Right click the canvas -// Node templates -> click the one to add -// -// To delete/rename: -// Right click the canvas -// Node templates -> Manage -// -// To rearrange: -// Open the manage dialog and Drag and drop elements using the "Name:" label as handle - -const id = "Comfy.NodeTemplates"; -const file = "comfy.templates.json"; - -class ManageTemplates extends ComfyDialog { - constructor() { - super(); - this.load().then((v) => { - this.templates = v; - }); - - this.element.classList.add("comfy-manage-templates"); - this.draggedEl = null; - this.saveVisualCue = null; - this.emptyImg = new Image(); - this.emptyImg.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs="; - - this.importInput = $el("input", { - type: "file", - accept: ".json", - multiple: true, - style: { display: "none" }, - parent: document.body, - onchange: () => this.importAll(), - }); - } - - createButtons() { - const btns = super.createButtons(); - btns[0].textContent = "Close"; - btns[0].onclick = (e) => { - clearTimeout(this.saveVisualCue); - this.close(); - }; - btns.unshift( - $el("button", { - type: "button", - textContent: "Export", - onclick: () => this.exportAll(), - }) - ); - btns.unshift( - $el("button", { - type: "button", - textContent: "Import", - onclick: () => { - this.importInput.click(); - }, - }) - ); - return btns; - } - - async load() { - let templates = []; - if (app.storageLocation === "server") { - if (app.isNewUserSession) { - // New user so migrate existing templates - const json = localStorage.getItem(id); - if (json) { - templates = JSON.parse(json); - } - await api.storeUserData(file, json, { stringify: false }); - } else { - const res = await api.getUserData(file); - if (res.status === 200) { - try { - templates = await res.json(); - } catch (error) { - } - } else if (res.status !== 404) { - console.error(res.status + " " + res.statusText); - } - } - } else { - const json = localStorage.getItem(id); - if (json) { - templates = JSON.parse(json); - } - } - - return templates ?? []; - } - - async store() { - if(app.storageLocation === "server") { - const templates = JSON.stringify(this.templates, undefined, 4); - localStorage.setItem(id, templates); // Backwards compatibility - try { - await api.storeUserData(file, templates, { stringify: false }); - } catch (error) { - console.error(error); - alert(error.message); - } - } else { - localStorage.setItem(id, JSON.stringify(this.templates)); - } - } - - async importAll() { - for (const file of this.importInput.files) { - if (file.type === "application/json" || file.name.endsWith(".json")) { - const reader = new FileReader(); - reader.onload = async () => { - const importFile = JSON.parse(reader.result); - if (importFile?.templates) { - for (const template of importFile.templates) { - if (template?.name && template?.data) { - this.templates.push(template); - } - } - await this.store(); - } - }; - await reader.readAsText(file); - } - } - - this.importInput.value = null; - - this.close(); - } - - exportAll() { - if (this.templates.length == 0) { - alert("No templates to export."); - return; - } - - const json = JSON.stringify({ templates: this.templates }, null, 2); // convert the data to a JSON string - const blob = new Blob([json], { type: "application/json" }); - const url = URL.createObjectURL(blob); - const a = $el("a", { - href: url, - download: "node_templates.json", - style: { display: "none" }, - parent: document.body, - }); - a.click(); - setTimeout(function () { - a.remove(); - window.URL.revokeObjectURL(url); - }, 0); - } - - show() { - // Show list of template names + delete button - super.show( - $el( - "div", - {}, - this.templates.flatMap((t,i) => { - let nameInput; - return [ - $el( - "div", - { - dataset: { id: i }, - className: "tempateManagerRow", - style: { - display: "grid", - gridTemplateColumns: "1fr auto", - border: "1px dashed transparent", - gap: "5px", - backgroundColor: "var(--comfy-menu-bg)" - }, - ondragstart: (e) => { - this.draggedEl = e.currentTarget; - e.currentTarget.style.opacity = "0.6"; - e.currentTarget.style.border = "1px dashed yellow"; - e.dataTransfer.effectAllowed = 'move'; - e.dataTransfer.setDragImage(this.emptyImg, 0, 0); - }, - ondragend: (e) => { - e.target.style.opacity = "1"; - e.currentTarget.style.border = "1px dashed transparent"; - e.currentTarget.removeAttribute("draggable"); - - // rearrange the elements - this.element.querySelectorAll('.tempateManagerRow').forEach((el,i) => { - var prev_i = el.dataset.id; - - if ( el == this.draggedEl && prev_i != i ) { - this.templates.splice(i, 0, this.templates.splice(prev_i, 1)[0]); - } - el.dataset.id = i; - }); - this.store(); - }, - ondragover: (e) => { - e.preventDefault(); - if ( e.currentTarget == this.draggedEl ) - return; - - let rect = e.currentTarget.getBoundingClientRect(); - if (e.clientY > rect.top + rect.height / 2) { - e.currentTarget.parentNode.insertBefore(this.draggedEl, e.currentTarget.nextSibling); - } else { - e.currentTarget.parentNode.insertBefore(this.draggedEl, e.currentTarget); - } - } - }, - [ - $el( - "label", - { - textContent: "Name: ", - style: { - cursor: "grab", - }, - onmousedown: (e) => { - // enable dragging only from the label - if (e.target.localName == 'label') - e.currentTarget.parentNode.draggable = 'true'; - } - }, - [ - $el("input", { - value: t.name, - dataset: { name: t.name }, - style: { - transitionProperty: 'background-color', - transitionDuration: '0s', - }, - onchange: (e) => { - clearTimeout(this.saveVisualCue); - var el = e.target; - var row = el.parentNode.parentNode; - this.templates[row.dataset.id].name = el.value.trim() || 'untitled'; - this.store(); - el.style.backgroundColor = 'rgb(40, 95, 40)'; - el.style.transitionDuration = '0s'; - this.saveVisualCue = setTimeout(function () { - el.style.transitionDuration = '.7s'; - el.style.backgroundColor = 'var(--comfy-input-bg)'; - }, 15); - }, - onkeypress: (e) => { - var el = e.target; - clearTimeout(this.saveVisualCue); - el.style.transitionDuration = '0s'; - el.style.backgroundColor = 'var(--comfy-input-bg)'; - }, - $: (el) => (nameInput = el), - }) - ] - ), - $el( - "div", - {}, - [ - $el("button", { - textContent: "Export", - style: { - fontSize: "12px", - fontWeight: "normal", - }, - onclick: (e) => { - const json = JSON.stringify({templates: [t]}, null, 2); // convert the data to a JSON string - const blob = new Blob([json], {type: "application/json"}); - const url = URL.createObjectURL(blob); - const a = $el("a", { - href: url, - download: (nameInput.value || t.name) + ".json", - style: {display: "none"}, - parent: document.body, - }); - a.click(); - setTimeout(function () { - a.remove(); - window.URL.revokeObjectURL(url); - }, 0); - }, - }), - $el("button", { - textContent: "Delete", - style: { - fontSize: "12px", - color: "red", - fontWeight: "normal", - }, - onclick: (e) => { - const item = e.target.parentNode.parentNode; - item.parentNode.removeChild(item); - this.templates.splice(item.dataset.id*1, 1); - this.store(); - // update the rows index, setTimeout ensures that the list is updated - var that = this; - setTimeout(function (){ - that.element.querySelectorAll('.tempateManagerRow').forEach((el,i) => { - el.dataset.id = i; - }); - }, 0); - }, - }), - ] - ), - ] - ) - ]; - }) - ) - ); - } -} - -app.registerExtension({ - name: id, - setup() { - const manage = new ManageTemplates(); - - const clipboardAction = async (cb) => { - // We use the clipboard functions but dont want to overwrite the current user clipboard - // Restore it after we've run our callback - const old = localStorage.getItem("litegrapheditor_clipboard"); - await cb(); - localStorage.setItem("litegrapheditor_clipboard", old); - }; - - const orig = LGraphCanvas.prototype.getCanvasMenuOptions; - LGraphCanvas.prototype.getCanvasMenuOptions = function () { - const options = orig.apply(this, arguments); - - options.push(null); - options.push({ - content: `Save Selected as Template`, - disabled: !Object.keys(app.canvas.selected_nodes || {}).length, - callback: () => { - const name = prompt("Enter name"); - if (!name?.trim()) return; - - clipboardAction(() => { - app.canvas.copyToClipboard(); - let data = localStorage.getItem("litegrapheditor_clipboard"); - data = JSON.parse(data); - const nodeIds = Object.keys(app.canvas.selected_nodes); - for (let i = 0; i < nodeIds.length; i++) { - const node = app.graph.getNodeById(nodeIds[i]); - const nodeData = node?.constructor.nodeData; - - let groupData = GroupNodeHandler.getGroupData(node); - if (groupData) { - groupData = groupData.nodeData; - if (!data.groupNodes) { - data.groupNodes = {}; - } - data.groupNodes[nodeData.name] = groupData; - data.nodes[i].type = nodeData.name; - } - } - - manage.templates.push({ - name, - data: JSON.stringify(data), - }); - manage.store(); - }); - }, - }); - - // Map each template to a menu item - const subItems = manage.templates.map((t) => { - return { - content: t.name, - callback: () => { - clipboardAction(async () => { - const data = JSON.parse(t.data); - await GroupNodeConfig.registerFromWorkflow(data.groupNodes, {}); - localStorage.setItem("litegrapheditor_clipboard", t.data); - app.canvas.pasteFromClipboard(); - }); - }, - }; - }); - - subItems.push(null, { - content: "Manage", - callback: () => manage.show(), - }); - - options.push({ - content: "Node Templates", - submenu: { - options: subItems, - }, - }); - - return options; - }; - }, -}); diff --git a/web/extensions/core/noteNode.js b/web/extensions/core/noteNode.js deleted file mode 100644 index 8d89054e9..000000000 --- a/web/extensions/core/noteNode.js +++ /dev/null @@ -1,41 +0,0 @@ -import {app} from "../../scripts/app.js"; -import {ComfyWidgets} from "../../scripts/widgets.js"; -// Node that add notes to your project - -app.registerExtension({ - name: "Comfy.NoteNode", - registerCustomNodes() { - class NoteNode { - color=LGraphCanvas.node_colors.yellow.color; - bgcolor=LGraphCanvas.node_colors.yellow.bgcolor; - groupcolor = LGraphCanvas.node_colors.yellow.groupcolor; - constructor() { - if (!this.properties) { - this.properties = {}; - this.properties.text=""; - } - - ComfyWidgets.STRING(this, "", ["", {default:this.properties.text, multiline: true}], app) - - this.serialize_widgets = true; - this.isVirtualNode = true; - - } - - - } - - // Load default visibility - - LiteGraph.registerNodeType( - "Note", - Object.assign(NoteNode, { - title_mode: LiteGraph.NORMAL_TITLE, - title: "Note", - collapsable: true, - }) - ); - - NoteNode.category = "utils"; - }, -}); diff --git a/web/extensions/core/rerouteNode.js b/web/extensions/core/rerouteNode.js deleted file mode 100644 index 4feff91e5..000000000 --- a/web/extensions/core/rerouteNode.js +++ /dev/null @@ -1,274 +0,0 @@ -import { app } from "../../scripts/app.js"; -import { mergeIfValid, getWidgetConfig, setWidgetConfig } from "./widgetInputs.js"; - -// Node that allows you to redirect connections for cleaner graphs - -app.registerExtension({ - name: "Comfy.RerouteNode", - registerCustomNodes(app) { - class RerouteNode { - constructor() { - if (!this.properties) { - this.properties = {}; - } - this.properties.showOutputText = RerouteNode.defaultVisibility; - this.properties.horizontal = false; - - this.addInput("", "*"); - this.addOutput(this.properties.showOutputText ? "*" : "", "*"); - - this.onAfterGraphConfigured = function () { - requestAnimationFrame(() => { - this.onConnectionsChange(LiteGraph.INPUT, null, true, null); - }); - }; - - this.onConnectionsChange = function (type, index, connected, link_info) { - this.applyOrientation(); - - // Prevent multiple connections to different types when we have no input - if (connected && type === LiteGraph.OUTPUT) { - // Ignore wildcard nodes as these will be updated to real types - const types = new Set(this.outputs[0].links.map((l) => app.graph.links[l].type).filter((t) => t !== "*")); - if (types.size > 1) { - const linksToDisconnect = []; - for (let i = 0; i < this.outputs[0].links.length - 1; i++) { - const linkId = this.outputs[0].links[i]; - const link = app.graph.links[linkId]; - linksToDisconnect.push(link); - } - for (const link of linksToDisconnect) { - const node = app.graph.getNodeById(link.target_id); - node.disconnectInput(link.target_slot); - } - } - } - - // Find root input - let currentNode = this; - let updateNodes = []; - let inputType = null; - let inputNode = null; - while (currentNode) { - updateNodes.unshift(currentNode); - const linkId = currentNode.inputs[0].link; - if (linkId !== null) { - const link = app.graph.links[linkId]; - if (!link) return; - const node = app.graph.getNodeById(link.origin_id); - const type = node.constructor.type; - if (type === "Reroute") { - if (node === this) { - // We've found a circle - currentNode.disconnectInput(link.target_slot); - currentNode = null; - } else { - // Move the previous node - currentNode = node; - } - } else { - // We've found the end - inputNode = currentNode; - inputType = node.outputs[link.origin_slot]?.type ?? null; - break; - } - } else { - // This path has no input node - currentNode = null; - break; - } - } - - // Find all outputs - const nodes = [this]; - let outputType = null; - while (nodes.length) { - currentNode = nodes.pop(); - const outputs = (currentNode.outputs ? currentNode.outputs[0].links : []) || []; - if (outputs.length) { - for (const linkId of outputs) { - const link = app.graph.links[linkId]; - - // When disconnecting sometimes the link is still registered - if (!link) continue; - - const node = app.graph.getNodeById(link.target_id); - const type = node.constructor.type; - - if (type === "Reroute") { - // Follow reroute nodes - nodes.push(node); - updateNodes.push(node); - } else { - // We've found an output - const nodeOutType = - node.inputs && node.inputs[link?.target_slot] && node.inputs[link.target_slot].type - ? node.inputs[link.target_slot].type - : null; - if (inputType && inputType !== "*" && nodeOutType !== inputType) { - // The output doesnt match our input so disconnect it - node.disconnectInput(link.target_slot); - } else { - outputType = nodeOutType; - } - } - } - } else { - // No more outputs for this path - } - } - - const displayType = inputType || outputType || "*"; - const color = LGraphCanvas.link_type_colors[displayType]; - - let widgetConfig; - let targetWidget; - let widgetType; - // Update the types of each node - for (const node of updateNodes) { - // If we dont have an input type we are always wildcard but we'll show the output type - // This lets you change the output link to a different type and all nodes will update - node.outputs[0].type = inputType || "*"; - node.__outputType = displayType; - node.outputs[0].name = node.properties.showOutputText ? displayType : ""; - node.size = node.computeSize(); - node.applyOrientation(); - - for (const l of node.outputs[0].links || []) { - const link = app.graph.links[l]; - if (link) { - link.color = color; - - if (app.configuringGraph) continue; - const targetNode = app.graph.getNodeById(link.target_id); - const targetInput = targetNode.inputs?.[link.target_slot]; - if (targetInput?.widget) { - const config = getWidgetConfig(targetInput); - if (!widgetConfig) { - widgetConfig = config[1] ?? {}; - widgetType = config[0]; - } - if (!targetWidget) { - targetWidget = targetNode.widgets?.find((w) => w.name === targetInput.widget.name); - } - - const merged = mergeIfValid(targetInput, [config[0], widgetConfig]); - if (merged.customConfig) { - widgetConfig = merged.customConfig; - } - } - } - } - } - - for (const node of updateNodes) { - if (widgetConfig && outputType) { - node.inputs[0].widget = { name: "value" }; - setWidgetConfig(node.inputs[0], [widgetType ?? displayType, widgetConfig], targetWidget); - } else { - setWidgetConfig(node.inputs[0], null); - } - } - - if (inputNode) { - const link = app.graph.links[inputNode.inputs[0].link]; - if (link) { - link.color = color; - } - } - }; - - this.clone = function () { - const cloned = RerouteNode.prototype.clone.apply(this); - cloned.removeOutput(0); - cloned.addOutput(this.properties.showOutputText ? "*" : "", "*"); - cloned.size = cloned.computeSize(); - return cloned; - }; - - // This node is purely frontend and does not impact the resulting prompt so should not be serialized - this.isVirtualNode = true; - } - - getExtraMenuOptions(_, options) { - options.unshift( - { - content: (this.properties.showOutputText ? "Hide" : "Show") + " Type", - callback: () => { - this.properties.showOutputText = !this.properties.showOutputText; - if (this.properties.showOutputText) { - this.outputs[0].name = this.__outputType || this.outputs[0].type; - } else { - this.outputs[0].name = ""; - } - this.size = this.computeSize(); - this.applyOrientation(); - app.graph.setDirtyCanvas(true, true); - }, - }, - { - content: (RerouteNode.defaultVisibility ? "Hide" : "Show") + " Type By Default", - callback: () => { - RerouteNode.setDefaultTextVisibility(!RerouteNode.defaultVisibility); - }, - }, - { - // naming is inverted with respect to LiteGraphNode.horizontal - // LiteGraphNode.horizontal == true means that - // each slot in the inputs and outputs are layed out horizontally, - // which is the opposite of the visual orientation of the inputs and outputs as a node - content: "Set " + (this.properties.horizontal ? "Horizontal" : "Vertical"), - callback: () => { - this.properties.horizontal = !this.properties.horizontal; - this.applyOrientation(); - }, - } - ); - } - applyOrientation() { - this.horizontal = this.properties.horizontal; - if (this.horizontal) { - // we correct the input position, because LiteGraphNode.horizontal - // doesn't account for title presence - // which reroute nodes don't have - this.inputs[0].pos = [this.size[0] / 2, 0]; - } else { - delete this.inputs[0].pos; - } - app.graph.setDirtyCanvas(true, true); - } - - computeSize() { - return [ - this.properties.showOutputText && this.outputs && this.outputs.length - ? Math.max(75, LiteGraph.NODE_TEXT_SIZE * this.outputs[0].name.length * 0.6 + 40) - : 75, - 26, - ]; - } - - static setDefaultTextVisibility(visible) { - RerouteNode.defaultVisibility = visible; - if (visible) { - localStorage["Comfy.RerouteNode.DefaultVisibility"] = "true"; - } else { - delete localStorage["Comfy.RerouteNode.DefaultVisibility"]; - } - } - } - - // Load default visibility - RerouteNode.setDefaultTextVisibility(!!localStorage["Comfy.RerouteNode.DefaultVisibility"]); - - LiteGraph.registerNodeType( - "Reroute", - Object.assign(RerouteNode, { - title_mode: LiteGraph.NO_TITLE, - title: "Reroute", - collapsable: false, - }) - ); - - RerouteNode.category = "utils"; - }, -}); diff --git a/web/extensions/core/saveImageExtraOutput.js b/web/extensions/core/saveImageExtraOutput.js deleted file mode 100644 index a0506b43b..000000000 --- a/web/extensions/core/saveImageExtraOutput.js +++ /dev/null @@ -1,35 +0,0 @@ -import { app } from "../../scripts/app.js"; -import { applyTextReplacements } from "../../scripts/utils.js"; -// Use widget values and dates in output filenames - -app.registerExtension({ - name: "Comfy.SaveImageExtraOutput", - async beforeRegisterNodeDef(nodeType, nodeData, app) { - if (nodeData.name === "SaveImage") { - const onNodeCreated = nodeType.prototype.onNodeCreated; - // When the SaveImage node is created we want to override the serialization of the output name widget to run our S&R - nodeType.prototype.onNodeCreated = function () { - const r = onNodeCreated ? onNodeCreated.apply(this, arguments) : undefined; - - const widget = this.widgets.find((w) => w.name === "filename_prefix"); - widget.serializeValue = () => { - return applyTextReplacements(app, widget.value); - }; - - return r; - }; - } else { - // When any other node is created add a property to alias the node - const onNodeCreated = nodeType.prototype.onNodeCreated; - nodeType.prototype.onNodeCreated = function () { - const r = onNodeCreated ? onNodeCreated.apply(this, arguments) : undefined; - - if (!this.properties || !("Node name for S&R" in this.properties)) { - this.addProperty("Node name for S&R", this.constructor.type, "string"); - } - - return r; - }; - } - }, -}); diff --git a/web/extensions/core/simpleTouchSupport.js b/web/extensions/core/simpleTouchSupport.js deleted file mode 100644 index 041fc2c4c..000000000 --- a/web/extensions/core/simpleTouchSupport.js +++ /dev/null @@ -1,102 +0,0 @@ -import { app } from "../../scripts/app.js"; - -let touchZooming; -let touchCount = 0; - -app.registerExtension({ - name: "Comfy.SimpleTouchSupport", - setup() { - let zoomPos; - let touchTime; - let lastTouch; - - function getMultiTouchPos(e) { - return Math.hypot(e.touches[0].clientX - e.touches[1].clientX, e.touches[0].clientY - e.touches[1].clientY); - } - - app.canvasEl.addEventListener( - "touchstart", - (e) => { - touchCount++; - lastTouch = null; - if (e.touches?.length === 1) { - // Store start time for press+hold for context menu - touchTime = new Date(); - lastTouch = e.touches[0]; - } else { - touchTime = null; - if (e.touches?.length === 2) { - // Store center pos for zoom - zoomPos = getMultiTouchPos(e); - app.canvas.pointer_is_down = false; - } - } - }, - true - ); - - app.canvasEl.addEventListener("touchend", (e) => { - touchZooming = false; - touchCount = e.touches?.length ?? touchCount - 1; - if (touchTime && !e.touches?.length) { - if (new Date() - touchTime > 600) { - try { - // hack to get litegraph to use this event - e.constructor = CustomEvent; - } catch (error) {} - e.clientX = lastTouch.clientX; - e.clientY = lastTouch.clientY; - - app.canvas.pointer_is_down = true; - app.canvas._mousedown_callback(e); - } - touchTime = null; - } - }); - - app.canvasEl.addEventListener( - "touchmove", - (e) => { - touchTime = null; - if (e.touches?.length === 2) { - app.canvas.pointer_is_down = false; - touchZooming = true; - LiteGraph.closeAllContextMenus(); - app.canvas.search_box?.close(); - const newZoomPos = getMultiTouchPos(e); - - const midX = (e.touches[0].clientX + e.touches[1].clientX) / 2; - const midY = (e.touches[0].clientY + e.touches[1].clientY) / 2; - - let scale = app.canvas.ds.scale; - const diff = zoomPos - newZoomPos; - if (diff > 0.5) { - scale *= 1 / 1.07; - } else if (diff < -0.5) { - scale *= 1.07; - } - app.canvas.ds.changeScale(scale, [midX, midY]); - app.canvas.setDirty(true, true); - zoomPos = newZoomPos; - } - }, - true - ); - }, -}); - -const processMouseDown = LGraphCanvas.prototype.processMouseDown; -LGraphCanvas.prototype.processMouseDown = function (e) { - if (touchZooming || touchCount) { - return; - } - return processMouseDown.apply(this, arguments); -}; - -const processMouseMove = LGraphCanvas.prototype.processMouseMove; -LGraphCanvas.prototype.processMouseMove = function (e) { - if (touchZooming || touchCount > 1) { - return; - } - return processMouseMove.apply(this, arguments); -}; diff --git a/web/extensions/core/slotDefaults.js b/web/extensions/core/slotDefaults.js deleted file mode 100644 index 718d25405..000000000 --- a/web/extensions/core/slotDefaults.js +++ /dev/null @@ -1,91 +0,0 @@ -import { app } from "../../scripts/app.js"; -import { ComfyWidgets } from "../../scripts/widgets.js"; -// Adds defaults for quickly adding nodes with middle click on the input/output - -app.registerExtension({ - name: "Comfy.SlotDefaults", - suggestionsNumber: null, - init() { - LiteGraph.search_filter_enabled = true; - LiteGraph.middle_click_slot_add_default_node = true; - this.suggestionsNumber = app.ui.settings.addSetting({ - id: "Comfy.NodeSuggestions.number", - name: "Number of nodes suggestions", - type: "slider", - attrs: { - min: 1, - max: 100, - step: 1, - }, - defaultValue: 5, - onChange: (newVal, oldVal) => { - this.setDefaults(newVal); - } - }); - }, - slot_types_default_out: {}, - slot_types_default_in: {}, - async beforeRegisterNodeDef(nodeType, nodeData, app) { - var nodeId = nodeData.name; - var inputs = []; - inputs = nodeData["input"]["required"]; //only show required inputs to reduce the mess also not logical to create node with optional inputs - for (const inputKey in inputs) { - var input = (inputs[inputKey]); - if (typeof input[0] !== "string") continue; - - var type = input[0] - if (type in ComfyWidgets) { - var customProperties = input[1] - if (!(customProperties?.forceInput)) continue; //ignore widgets that don't force input - } - - if (!(type in this.slot_types_default_out)) { - this.slot_types_default_out[type] = ["Reroute"]; - } - if (this.slot_types_default_out[type].includes(nodeId)) continue; - this.slot_types_default_out[type].push(nodeId); - - // Input types have to be stored as lower case - // Store each node that can handle this input type - const lowerType = type.toLocaleLowerCase(); - if (!(lowerType in LiteGraph.registered_slot_in_types)) { - LiteGraph.registered_slot_in_types[lowerType] = { nodes: [] }; - } - LiteGraph.registered_slot_in_types[lowerType].nodes.push(nodeType.comfyClass); - } - - var outputs = nodeData["output"]; - for (const key in outputs) { - var type = outputs[key]; - if (!(type in this.slot_types_default_in)) { - this.slot_types_default_in[type] = ["Reroute"];// ["Reroute", "Primitive"]; primitive doesn't always work :'() - } - - this.slot_types_default_in[type].push(nodeId); - - // Store each node that can handle this output type - if (!(type in LiteGraph.registered_slot_out_types)) { - LiteGraph.registered_slot_out_types[type] = { nodes: [] }; - } - LiteGraph.registered_slot_out_types[type].nodes.push(nodeType.comfyClass); - - if(!LiteGraph.slot_types_out.includes(type)) { - LiteGraph.slot_types_out.push(type); - } - } - var maxNum = this.suggestionsNumber.value; - this.setDefaults(maxNum); - }, - setDefaults(maxNum) { - - LiteGraph.slot_types_default_out = {}; - LiteGraph.slot_types_default_in = {}; - - for (const type in this.slot_types_default_out) { - LiteGraph.slot_types_default_out[type] = this.slot_types_default_out[type].slice(0, maxNum); - } - for (const type in this.slot_types_default_in) { - LiteGraph.slot_types_default_in[type] = this.slot_types_default_in[type].slice(0, maxNum); - } - } -}); diff --git a/web/extensions/core/snapToGrid.js b/web/extensions/core/snapToGrid.js deleted file mode 100644 index aac017748..000000000 --- a/web/extensions/core/snapToGrid.js +++ /dev/null @@ -1,171 +0,0 @@ -import { app } from "../../scripts/app.js"; - -// Shift + drag/resize to snap to grid - -/** Rounds a Vector2 in-place to the current CANVAS_GRID_SIZE. */ -function roundVectorToGrid(vec) { - vec[0] = LiteGraph.CANVAS_GRID_SIZE * Math.round(vec[0] / LiteGraph.CANVAS_GRID_SIZE); - vec[1] = LiteGraph.CANVAS_GRID_SIZE * Math.round(vec[1] / LiteGraph.CANVAS_GRID_SIZE); - return vec; -} - -app.registerExtension({ - name: "Comfy.SnapToGrid", - init() { - // Add setting to control grid size - app.ui.settings.addSetting({ - id: "Comfy.SnapToGrid.GridSize", - name: "Grid Size", - type: "slider", - attrs: { - min: 1, - max: 500, - }, - tooltip: - "When dragging and resizing nodes while holding shift they will be aligned to the grid, this controls the size of that grid.", - defaultValue: LiteGraph.CANVAS_GRID_SIZE, - onChange(value) { - LiteGraph.CANVAS_GRID_SIZE = +value; - }, - }); - - // After moving a node, if the shift key is down align it to grid - const onNodeMoved = app.canvas.onNodeMoved; - app.canvas.onNodeMoved = function (node) { - const r = onNodeMoved?.apply(this, arguments); - - if (app.shiftDown) { - // Ensure all selected nodes are realigned - for (const id in this.selected_nodes) { - this.selected_nodes[id].alignToGrid(); - } - } - - return r; - }; - - // When a node is added, add a resize handler to it so we can fix align the size with the grid - const onNodeAdded = app.graph.onNodeAdded; - app.graph.onNodeAdded = function (node) { - const onResize = node.onResize; - node.onResize = function () { - if (app.shiftDown) { - roundVectorToGrid(node.size); - } - return onResize?.apply(this, arguments); - }; - return onNodeAdded?.apply(this, arguments); - }; - - // Draw a preview of where the node will go if holding shift and the node is selected - const origDrawNode = LGraphCanvas.prototype.drawNode; - LGraphCanvas.prototype.drawNode = function (node, ctx) { - if (app.shiftDown && this.node_dragged && node.id in this.selected_nodes) { - const [x, y] = roundVectorToGrid([...node.pos]); - const shiftX = x - node.pos[0]; - let shiftY = y - node.pos[1]; - - let w, h; - if (node.flags.collapsed) { - w = node._collapsed_width; - h = LiteGraph.NODE_TITLE_HEIGHT; - shiftY -= LiteGraph.NODE_TITLE_HEIGHT; - } else { - w = node.size[0]; - h = node.size[1]; - let titleMode = node.constructor.title_mode; - if (titleMode !== LiteGraph.TRANSPARENT_TITLE && titleMode !== LiteGraph.NO_TITLE) { - h += LiteGraph.NODE_TITLE_HEIGHT; - shiftY -= LiteGraph.NODE_TITLE_HEIGHT; - } - } - const f = ctx.fillStyle; - ctx.fillStyle = "rgba(100, 100, 100, 0.5)"; - ctx.fillRect(shiftX, shiftY, w, h); - ctx.fillStyle = f; - } - - return origDrawNode.apply(this, arguments); - }; - - - - /** - * The currently moving, selected group only. Set after the `selected_group` has actually started - * moving. - */ - let selectedAndMovingGroup = null; - - /** - * Handles moving a group; tracking when a group has been moved (to show the ghost in `drawGroups` - * below) as well as handle the last move call from LiteGraph's `processMouseUp`. - */ - const groupMove = LGraphGroup.prototype.move; - LGraphGroup.prototype.move = function(deltax, deltay, ignore_nodes) { - const v = groupMove.apply(this, arguments); - // When we've started moving, set `selectedAndMovingGroup` as LiteGraph sets `selected_group` - // too eagerly and we don't want to behave like we're moving until we get a delta. - if (!selectedAndMovingGroup && app.canvas.selected_group === this && (deltax || deltay)) { - selectedAndMovingGroup = this; - } - - // LiteGraph will call group.move both on mouse-move as well as mouse-up though we only want - // to snap on a mouse-up which we can determine by checking if `app.canvas.last_mouse_dragging` - // has been set to `false`. Essentially, this check here is the equivilant to calling an - // `LGraphGroup.prototype.onNodeMoved` if it had existed. - if (app.canvas.last_mouse_dragging === false && app.shiftDown) { - // After moving a group (while app.shiftDown), snap all the child nodes and, finally, - // align the group itself. - this.recomputeInsideNodes(); - for (const node of this._nodes) { - node.alignToGrid(); - } - LGraphNode.prototype.alignToGrid.apply(this); - } - return v; - }; - - /** - * Handles drawing a group when, snapping the size when one is actively being resized tracking and/or - * drawing a ghost box when one is actively being moved. This mimics the node snapping behavior for - * both. - */ - const drawGroups = LGraphCanvas.prototype.drawGroups; - LGraphCanvas.prototype.drawGroups = function (canvas, ctx) { - if (this.selected_group && app.shiftDown) { - if (this.selected_group_resizing) { - roundVectorToGrid(this.selected_group.size); - } else if (selectedAndMovingGroup) { - const [x, y] = roundVectorToGrid([...selectedAndMovingGroup.pos]); - const f = ctx.fillStyle; - const s = ctx.strokeStyle; - ctx.fillStyle = "rgba(100, 100, 100, 0.33)"; - ctx.strokeStyle = "rgba(100, 100, 100, 0.66)"; - ctx.rect(x, y, ...selectedAndMovingGroup.size); - ctx.fill(); - ctx.stroke(); - ctx.fillStyle = f; - ctx.strokeStyle = s; - } - } else if (!this.selected_group) { - selectedAndMovingGroup = null; - } - return drawGroups.apply(this, arguments); - }; - - - /** Handles adding a group in a snapping-enabled state. */ - const onGroupAdd = LGraphCanvas.onGroupAdd; - LGraphCanvas.onGroupAdd = function() { - const v = onGroupAdd.apply(app.canvas, arguments); - if (app.shiftDown) { - const lastGroup = app.graph._groups[app.graph._groups.length - 1]; - if (lastGroup) { - roundVectorToGrid(lastGroup.pos); - roundVectorToGrid(lastGroup.size); - } - } - return v; - }; - }, -}); diff --git a/web/extensions/core/uploadAudio.js b/web/extensions/core/uploadAudio.js deleted file mode 100644 index 9dfa029bf..000000000 --- a/web/extensions/core/uploadAudio.js +++ /dev/null @@ -1,186 +0,0 @@ -import { app } from "../../scripts/app.js" -import { api } from "../../scripts/api.js" - -function splitFilePath(path) { - const folder_separator = path.lastIndexOf("/") - if (folder_separator === -1) { - return ["", path] - } - return [ - path.substring(0, folder_separator), - path.substring(folder_separator + 1) - ] -} - -function getResourceURL(subfolder, filename, type = "input") { - const params = [ - "filename=" + encodeURIComponent(filename), - "type=" + type, - "subfolder=" + subfolder, - app.getRandParam().substring(1) - ].join("&") - - return `/view?${params}` -} - -async function uploadFile( - audioWidget, - audioUIWidget, - file, - updateNode, - pasted = false -) { - try { - // Wrap file in formdata so it includes filename - const body = new FormData() - body.append("image", file) - if (pasted) body.append("subfolder", "pasted") - const resp = await api.fetchApi("/upload/image", { - method: "POST", - body - }) - - if (resp.status === 200) { - const data = await resp.json() - // Add the file to the dropdown list and update the widget value - let path = data.name - if (data.subfolder) path = data.subfolder + "/" + path - - if (!audioWidget.options.values.includes(path)) { - audioWidget.options.values.push(path) - } - - if (updateNode) { - audioUIWidget.element.src = api.apiURL( - getResourceURL(...splitFilePath(path)) - ) - audioWidget.value = path - } - } else { - alert(resp.status + " - " + resp.statusText) - } - } catch (error) { - alert(error) - } -} - -// AudioWidget MUST be registered first, as AUDIOUPLOAD depends on AUDIO_UI to be -// present. -app.registerExtension({ - name: "Comfy.AudioWidget", - async beforeRegisterNodeDef(nodeType, nodeData) { - if (["LoadAudio", "SaveAudio", "PreviewAudio"].includes(nodeType.comfyClass)) { - nodeData.input.required.audioUI = ["AUDIO_UI"] - } - }, - getCustomWidgets() { - return { - AUDIO_UI(node, inputName) { - const audio = document.createElement("audio") - audio.controls = true - audio.classList.add("comfy-audio") - audio.setAttribute("name", "media") - - const audioUIWidget = node.addDOMWidget( - inputName, - /* name=*/ "audioUI", - audio - ) - // @ts-ignore - // TODO: Sort out the DOMWidget type. - audioUIWidget.serialize = false - - const isOutputNode = node.constructor.nodeData.output_node - if (isOutputNode) { - // Hide the audio widget when there is no audio initially. - audioUIWidget.element.classList.add("empty-audio-widget") - // Populate the audio widget UI on node execution. - const onExecuted = node.onExecuted - node.onExecuted = function(message) { - onExecuted?.apply(this, arguments) - const audios = message.audio - if (!audios) return - const audio = audios[0] - audioUIWidget.element.src = api.apiURL( - getResourceURL(audio.subfolder, audio.filename, audio.type) - ) - audioUIWidget.element.classList.remove("empty-audio-widget") - } - } - return { widget: audioUIWidget } - } - } - }, - onNodeOutputsUpdated(nodeOutputs) { - for (const [nodeId, output] of Object.entries(nodeOutputs)) { - const node = app.graph.getNodeById(Number.parseInt(nodeId)); - if ("audio" in output) { - const audioUIWidget = node.widgets.find((w) => w.name === "audioUI"); - const audio = output.audio[0]; - audioUIWidget.element.src = api.apiURL(getResourceURL(audio.subfolder, audio.filename, audio.type)); - audioUIWidget.element.classList.remove("empty-audio-widget"); - } - } - }, -}) - -app.registerExtension({ - name: "Comfy.UploadAudio", - async beforeRegisterNodeDef(nodeType, nodeData) { - if (nodeData?.input?.required?.audio?.[1]?.audio_upload === true) { - nodeData.input.required.upload = ["AUDIOUPLOAD"] - } - }, - getCustomWidgets() { - return { - AUDIOUPLOAD(node, inputName) { - // The widget that allows user to select file. - const audioWidget = node.widgets.find(w => w.name === "audio") - const audioUIWidget = node.widgets.find(w => w.name === "audioUI") - - const onAudioWidgetUpdate = () => { - audioUIWidget.element.src = api.apiURL( - getResourceURL(...splitFilePath(audioWidget.value)) - ) - } - // Initially load default audio file to audioUIWidget. - if (audioWidget.value) { - onAudioWidgetUpdate() - } - audioWidget.callback = onAudioWidgetUpdate - - // Load saved audio file widget values if restoring from workflow - const onGraphConfigured = node.onGraphConfigured; - node.onGraphConfigured = function() { - onGraphConfigured?.apply(this, arguments) - if (audioWidget.value) { - onAudioWidgetUpdate() - } - } - - const fileInput = document.createElement("input") - fileInput.type = "file" - fileInput.accept = "audio/*" - fileInput.style.display = "none" - fileInput.onchange = () => { - if (fileInput.files.length) { - uploadFile(audioWidget, audioUIWidget, fileInput.files[0], true) - } - } - // The widget to pop up the upload dialog. - const uploadWidget = node.addWidget( - "button", - inputName, - /* value=*/ "", - () => { - fileInput.click() - } - ) - uploadWidget.label = "choose file to upload" - uploadWidget.serialize = false - - return { widget: uploadWidget } - } - } - } -}) diff --git a/web/extensions/core/uploadImage.js b/web/extensions/core/uploadImage.js deleted file mode 100644 index 530c4599e..000000000 --- a/web/extensions/core/uploadImage.js +++ /dev/null @@ -1,12 +0,0 @@ -import { app } from "../../scripts/app.js"; - -// Adds an upload button to the nodes - -app.registerExtension({ - name: "Comfy.UploadImage", - async beforeRegisterNodeDef(nodeType, nodeData, app) { - if (nodeData?.input?.required?.image?.[1]?.image_upload === true) { - nodeData.input.required.upload = ["IMAGEUPLOAD"]; - } - }, -}); diff --git a/web/extensions/core/webcamCapture.js b/web/extensions/core/webcamCapture.js deleted file mode 100644 index dd5725bd4..000000000 --- a/web/extensions/core/webcamCapture.js +++ /dev/null @@ -1,126 +0,0 @@ -import { app } from "../../scripts/app.js"; -import { api } from "../../scripts/api.js"; - -const WEBCAM_READY = Symbol(); - -app.registerExtension({ - name: "Comfy.WebcamCapture", - getCustomWidgets(app) { - return { - WEBCAM(node, inputName) { - let res; - node[WEBCAM_READY] = new Promise((resolve) => (res = resolve)); - - const container = document.createElement("div"); - container.style.background = "rgba(0,0,0,0.25)"; - container.style.textAlign = "center"; - - const video = document.createElement("video"); - video.style.height = video.style.width = "100%"; - - const loadVideo = async () => { - try { - const stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); - container.replaceChildren(video); - - setTimeout(() => res(video), 500); // Fallback as loadedmetadata doesnt fire sometimes? - video.addEventListener("loadedmetadata", () => res(video), false); - video.srcObject = stream; - video.play(); - } catch (error) { - const label = document.createElement("div"); - label.style.color = "red"; - label.style.overflow = "auto"; - label.style.maxHeight = "100%"; - label.style.whiteSpace = "pre-wrap"; - - if (window.isSecureContext) { - label.textContent = "Unable to load webcam, please ensure access is granted:\n" + error.message; - } else { - label.textContent = "Unable to load webcam. A secure context is required, if you are not accessing ComfyUI on localhost (127.0.0.1) you will have to enable TLS (https)\n\n" + error.message; - } - - container.replaceChildren(label); - } - }; - - loadVideo(); - - return { widget: node.addDOMWidget(inputName, "WEBCAM", container) }; - }, - }; - }, - nodeCreated(node) { - if ((node.type, node.constructor.comfyClass !== "WebcamCapture")) return; - - let video; - const camera = node.widgets.find((w) => w.name === "image"); - const w = node.widgets.find((w) => w.name === "width"); - const h = node.widgets.find((w) => w.name === "height"); - const captureOnQueue = node.widgets.find((w) => w.name === "capture_on_queue"); - - const canvas = document.createElement("canvas"); - - const capture = () => { - canvas.width = w.value; - canvas.height = h.value; - const ctx = canvas.getContext("2d"); - ctx.drawImage(video, 0, 0, w.value, h.value); - const data = canvas.toDataURL("image/png"); - - const img = new Image(); - img.onload = () => { - node.imgs = [img]; - app.graph.setDirtyCanvas(true); - requestAnimationFrame(() => { - node.setSizeForImage?.(); - }); - }; - img.src = data; - }; - - const btn = node.addWidget("button", "waiting for camera...", "capture", capture); - btn.disabled = true; - btn.serializeValue = () => undefined; - - camera.serializeValue = async () => { - if (captureOnQueue.value) { - capture(); - } else if (!node.imgs?.length) { - const err = `No webcam image captured`; - alert(err); - throw new Error(err); - } - - // Upload image to temp storage - const blob = await new Promise((r) => canvas.toBlob(r)); - const name = `${+new Date()}.png`; - const file = new File([blob], name); - const body = new FormData(); - body.append("image", file); - body.append("subfolder", "webcam"); - body.append("type", "temp"); - const resp = await api.fetchApi("/upload/image", { - method: "POST", - body, - }); - if (resp.status !== 200) { - const err = `Error uploading camera image: ${resp.status} - ${resp.statusText}`; - alert(err); - throw new Error(err); - } - return `webcam/${name} [temp]`; - }; - - node[WEBCAM_READY].then((v) => { - video = v; - // If width isnt specified then use video output resolution - if (!w.value) { - w.value = video.videoWidth || 640; - h.value = video.videoHeight || 480; - } - btn.disabled = false; - btn.label = "capture"; - }); - }, -}); diff --git a/web/extensions/core/widgetInputs.js b/web/extensions/core/widgetInputs.js index f1a1d22cd..286418d48 100644 --- a/web/extensions/core/widgetInputs.js +++ b/web/extensions/core/widgetInputs.js @@ -1,800 +1,4 @@ -import { ComfyWidgets, addValueControlWidgets } from "../../scripts/widgets.js"; -import { app } from "../../scripts/app.js"; -import { applyTextReplacements } from "../../scripts/utils.js"; - -const CONVERTED_TYPE = "converted-widget"; -const VALID_TYPES = ["STRING", "combo", "number", "BOOLEAN"]; -const CONFIG = Symbol(); -const GET_CONFIG = Symbol(); -const TARGET = Symbol(); // Used for reroutes to specify the real target widget - -export function getWidgetConfig(slot) { - return slot.widget[CONFIG] ?? slot.widget[GET_CONFIG](); -} - -function getConfig(widgetName) { - const { nodeData } = this.constructor; - return nodeData?.input?.required[widgetName] ?? nodeData?.input?.optional?.[widgetName]; -} - -function isConvertableWidget(widget, config) { - return (VALID_TYPES.includes(widget.type) || VALID_TYPES.includes(config[0])) && !widget.options?.forceInput; -} - -function hideWidget(node, widget, suffix = "") { - if (widget.type?.startsWith(CONVERTED_TYPE)) return; - widget.origType = widget.type; - widget.origComputeSize = widget.computeSize; - widget.origSerializeValue = widget.serializeValue; - widget.computeSize = () => [0, -4]; // -4 is due to the gap litegraph adds between widgets automatically - widget.type = CONVERTED_TYPE + suffix; - widget.serializeValue = () => { - // Prevent serializing the widget if we have no input linked - if (!node.inputs) { - return undefined; - } - let node_input = node.inputs.find((i) => i.widget?.name === widget.name); - - if (!node_input || !node_input.link) { - return undefined; - } - return widget.origSerializeValue ? widget.origSerializeValue() : widget.value; - }; - - // Hide any linked widgets, e.g. seed+seedControl - if (widget.linkedWidgets) { - for (const w of widget.linkedWidgets) { - hideWidget(node, w, ":" + widget.name); - } - } -} - -function showWidget(widget) { - widget.type = widget.origType; - widget.computeSize = widget.origComputeSize; - widget.serializeValue = widget.origSerializeValue; - - delete widget.origType; - delete widget.origComputeSize; - delete widget.origSerializeValue; - - // Hide any linked widgets, e.g. seed+seedControl - if (widget.linkedWidgets) { - for (const w of widget.linkedWidgets) { - showWidget(w); - } - } -} - -function convertToInput(node, widget, config) { - hideWidget(node, widget); - - const { type } = getWidgetType(config); - - // Add input and store widget config for creating on primitive node - const sz = node.size; - node.addInput(widget.name, type, { - widget: { name: widget.name, [GET_CONFIG]: () => config }, - }); - - for (const widget of node.widgets) { - widget.last_y += LiteGraph.NODE_SLOT_HEIGHT; - } - - // Restore original size but grow if needed - node.setSize([Math.max(sz[0], node.size[0]), Math.max(sz[1], node.size[1])]); -} - -function convertToWidget(node, widget) { - showWidget(widget); - const sz = node.size; - node.removeInput(node.inputs.findIndex((i) => i.widget?.name === widget.name)); - - for (const widget of node.widgets) { - widget.last_y -= LiteGraph.NODE_SLOT_HEIGHT; - } - - // Restore original size but grow if needed - node.setSize([Math.max(sz[0], node.size[0]), Math.max(sz[1], node.size[1])]); -} - -function getWidgetType(config) { - // Special handling for COMBO so we restrict links based on the entries - let type = config[0]; - if (type instanceof Array) { - type = "COMBO"; - } - return { type }; -} - -function isValidCombo(combo, obj) { - // New input isnt a combo - if (!(obj instanceof Array)) { - console.log(`connection rejected: tried to connect combo to ${obj}`); - return false; - } - // New imput combo has a different size - if (combo.length !== obj.length) { - console.log(`connection rejected: combo lists dont match`); - return false; - } - // New input combo has different elements - if (combo.find((v, i) => obj[i] !== v)) { - console.log(`connection rejected: combo lists dont match`); - return false; - } - - return true; -} - -export function setWidgetConfig(slot, config, target) { - if (!slot.widget) return; - if (config) { - slot.widget[GET_CONFIG] = () => config; - slot.widget[TARGET] = target; - } else { - delete slot.widget; - } - - if (slot.link) { - const link = app.graph.links[slot.link]; - if (link) { - const originNode = app.graph.getNodeById(link.origin_id); - if (originNode.type === "PrimitiveNode") { - if (config) { - originNode.recreateWidget(); - } else if(!app.configuringGraph) { - originNode.disconnectOutput(0); - originNode.onLastDisconnect(); - } - } - } - } -} - -export function mergeIfValid(output, config2, forceUpdate, recreateWidget, config1) { - if (!config1) { - config1 = output.widget[CONFIG] ?? output.widget[GET_CONFIG](); - } - - if (config1[0] instanceof Array) { - if (!isValidCombo(config1[0], config2[0])) return false; - } else if (config1[0] !== config2[0]) { - // Types dont match - console.log(`connection rejected: types dont match`, config1[0], config2[0]); - return false; - } - - const keys = new Set([...Object.keys(config1[1] ?? {}), ...Object.keys(config2[1] ?? {})]); - - let customConfig; - const getCustomConfig = () => { - if (!customConfig) { - if (typeof structuredClone === "undefined") { - customConfig = JSON.parse(JSON.stringify(config1[1] ?? {})); - } else { - customConfig = structuredClone(config1[1] ?? {}); - } - } - return customConfig; - }; - - const isNumber = config1[0] === "INT" || config1[0] === "FLOAT"; - for (const k of keys.values()) { - if (k !== "default" && k !== "forceInput" && k !== "defaultInput" && k !== "control_after_generate" && k !== "multiline") { - let v1 = config1[1][k]; - let v2 = config2[1]?.[k]; - - if (v1 === v2 || (!v1 && !v2)) continue; - - if (isNumber) { - if (k === "min") { - const theirMax = config2[1]?.["max"]; - if (theirMax != null && v1 > theirMax) { - console.log("connection rejected: min > max", v1, theirMax); - return false; - } - getCustomConfig()[k] = v1 == null ? v2 : v2 == null ? v1 : Math.max(v1, v2); - continue; - } else if (k === "max") { - const theirMin = config2[1]?.["min"]; - if (theirMin != null && v1 < theirMin) { - console.log("connection rejected: max < min", v1, theirMin); - return false; - } - getCustomConfig()[k] = v1 == null ? v2 : v2 == null ? v1 : Math.min(v1, v2); - continue; - } else if (k === "step") { - let step; - if (v1 == null) { - // No current step - step = v2; - } else if (v2 == null) { - // No new step - step = v1; - } else { - if (v1 < v2) { - // Ensure v1 is larger for the mod - const a = v2; - v2 = v1; - v1 = a; - } - if (v1 % v2) { - console.log("connection rejected: steps not divisible", "current:", v1, "new:", v2); - return false; - } - - step = v1; - } - - getCustomConfig()[k] = step; - continue; - } - } - - console.log(`connection rejected: config ${k} values dont match`, v1, v2); - return false; - } - } - - if (customConfig || forceUpdate) { - if (customConfig) { - output.widget[CONFIG] = [config1[0], customConfig]; - } - - const widget = recreateWidget?.call(this); - // When deleting a node this can be null - if (widget) { - const min = widget.options.min; - const max = widget.options.max; - if (min != null && widget.value < min) widget.value = min; - if (max != null && widget.value > max) widget.value = max; - widget.callback(widget.value); - } - } - - return { customConfig }; -} - -let useConversionSubmenusSetting; -app.registerExtension({ - name: "Comfy.WidgetInputs", - init() { - useConversionSubmenusSetting = app.ui.settings.addSetting({ - id: "Comfy.NodeInputConversionSubmenus", - name: "Node widget/input conversion sub-menus", - tooltip: "In the node context menu, place the entries that convert between input/widget in sub-menus.", - type: "boolean", - defaultValue: true, - }); - }, - async beforeRegisterNodeDef(nodeType, nodeData, app) { - // Add menu options to conver to/from widgets - const origGetExtraMenuOptions = nodeType.prototype.getExtraMenuOptions; - nodeType.prototype.convertWidgetToInput = function (widget) { - const config = getConfig.call(this, widget.name) ?? [widget.type, widget.options || {}]; - if (!isConvertableWidget(widget, config)) return false; - convertToInput(this, widget, config); - return true; - }; - nodeType.prototype.getExtraMenuOptions = function (_, options) { - const r = origGetExtraMenuOptions ? origGetExtraMenuOptions.apply(this, arguments) : undefined; - - if (this.widgets) { - let toInput = []; - let toWidget = []; - for (const w of this.widgets) { - if (w.options?.forceInput) { - continue; - } - if (w.type === CONVERTED_TYPE) { - toWidget.push({ - content: `Convert ${w.name} to widget`, - callback: () => convertToWidget(this, w), - }); - } else { - const config = getConfig.call(this, w.name) ?? [w.type, w.options || {}]; - if (isConvertableWidget(w, config)) { - toInput.push({ - content: `Convert ${w.name} to input`, - callback: () => convertToInput(this, w, config), - }); - } - } - } - - //Convert.. main menu - if (toInput.length) { - if (useConversionSubmenusSetting.value) { - options.push({ - content: "Convert Widget to Input", - submenu: { - options: toInput, - }, - }); - } else { - options.push(...toInput, null); - } - } - if (toWidget.length) { - if (useConversionSubmenusSetting.value) { - options.push({ - content: "Convert Input to Widget", - submenu: { - options: toWidget, - }, - }); - } else { - options.push(...toWidget, null); - } - } - } - - return r; - }; - - nodeType.prototype.onGraphConfigured = function () { - if (!this.inputs) return; - - for (const input of this.inputs) { - if (input.widget) { - if (!input.widget[GET_CONFIG]) { - input.widget[GET_CONFIG] = () => getConfig.call(this, input.widget.name); - } - - // Cleanup old widget config - if (input.widget.config) { - if (input.widget.config[0] instanceof Array) { - // If we are an old converted combo then replace the input type and the stored link data - input.type = "COMBO"; - - const link = app.graph.links[input.link]; - if (link) { - link.type = input.type; - } - } - delete input.widget.config; - } - - const w = this.widgets.find((w) => w.name === input.widget.name); - if (w) { - hideWidget(this, w); - } else { - convertToWidget(this, input); - } - } - } - }; - - const origOnNodeCreated = nodeType.prototype.onNodeCreated; - nodeType.prototype.onNodeCreated = function () { - const r = origOnNodeCreated ? origOnNodeCreated.apply(this) : undefined; - - // When node is created, convert any force/default inputs - if (!app.configuringGraph && this.widgets) { - for (const w of this.widgets) { - if (w?.options?.forceInput || w?.options?.defaultInput) { - const config = getConfig.call(this, w.name) ?? [w.type, w.options || {}]; - convertToInput(this, w, config); - } - } - } - - return r; - }; - - const origOnConfigure = nodeType.prototype.onConfigure; - nodeType.prototype.onConfigure = function () { - const r = origOnConfigure ? origOnConfigure.apply(this, arguments) : undefined; - if (!app.configuringGraph && this.inputs) { - // On copy + paste of nodes, ensure that widget configs are set up - for (const input of this.inputs) { - if (input.widget && !input.widget[GET_CONFIG]) { - input.widget[GET_CONFIG] = () => getConfig.call(this, input.widget.name); - const w = this.widgets.find((w) => w.name === input.widget.name); - if (w) { - hideWidget(this, w); - } - } - } - } - - return r; - }; - - function isNodeAtPos(pos) { - for (const n of app.graph._nodes) { - if (n.pos[0] === pos[0] && n.pos[1] === pos[1]) { - return true; - } - } - return false; - } - - // Double click a widget input to automatically attach a primitive - const origOnInputDblClick = nodeType.prototype.onInputDblClick; - const ignoreDblClick = Symbol(); - nodeType.prototype.onInputDblClick = function (slot) { - const r = origOnInputDblClick ? origOnInputDblClick.apply(this, arguments) : undefined; - - const input = this.inputs[slot]; - if (!input.widget || !input[ignoreDblClick]) { - // Not a widget input or already handled input - if (!(input.type in ComfyWidgets) && !(input.widget[GET_CONFIG]?.()?.[0] instanceof Array)) { - return r; //also Not a ComfyWidgets input or combo (do nothing) - } - } - - // Create a primitive node - const node = LiteGraph.createNode("PrimitiveNode"); - app.graph.add(node); - - // Calculate a position that wont directly overlap another node - const pos = [this.pos[0] - node.size[0] - 30, this.pos[1]]; - while (isNodeAtPos(pos)) { - pos[1] += LiteGraph.NODE_TITLE_HEIGHT; - } - - node.pos = pos; - node.connect(0, this, slot); - node.title = input.name; - - // Prevent adding duplicates due to triple clicking - input[ignoreDblClick] = true; - setTimeout(() => { - delete input[ignoreDblClick]; - }, 300); - - return r; - }; - - // Prevent connecting COMBO lists to converted inputs that dont match types - const onConnectInput = nodeType.prototype.onConnectInput; - nodeType.prototype.onConnectInput = function (targetSlot, type, output, originNode, originSlot) { - const v = onConnectInput?.(this, arguments); - // Not a combo, ignore - if (type !== "COMBO") return v; - // Primitive output, allow that to handle - if (originNode.outputs[originSlot].widget) return v; - - // Ensure target is also a combo - const targetCombo = this.inputs[targetSlot].widget?.[GET_CONFIG]?.()?.[0]; - if (!targetCombo || !(targetCombo instanceof Array)) return v; - - // Check they match - const originConfig = originNode.constructor?.nodeData?.output?.[originSlot]; - if (!originConfig || !isValidCombo(targetCombo, originConfig)) { - return false; - } - - return v; - }; - }, - registerCustomNodes() { - const replacePropertyName = "Run widget replace on values"; - class PrimitiveNode { - constructor() { - this.addOutput("connect to widget input", "*"); - this.serialize_widgets = true; - this.isVirtualNode = true; - - if (!this.properties || !(replacePropertyName in this.properties)) { - this.addProperty(replacePropertyName, false, "boolean"); - } - } - - applyToGraph(extraLinks = []) { - if (!this.outputs[0].links?.length) return; - - function get_links(node) { - let links = []; - for (const l of node.outputs[0].links) { - const linkInfo = app.graph.links[l]; - const n = node.graph.getNodeById(linkInfo.target_id); - if (n.type == "Reroute") { - links = links.concat(get_links(n)); - } else { - links.push(l); - } - } - return links; - } - - let links = [...get_links(this).map((l) => app.graph.links[l]), ...extraLinks]; - let v = this.widgets?.[0].value; - if(v && this.properties[replacePropertyName]) { - v = applyTextReplacements(app, v); - } - - // For each output link copy our value over the original widget value - for (const linkInfo of links) { - const node = this.graph.getNodeById(linkInfo.target_id); - const input = node.inputs[linkInfo.target_slot]; - let widget; - if (input.widget[TARGET]) { - widget = input.widget[TARGET]; - } else { - const widgetName = input.widget.name; - if (widgetName) { - widget = node.widgets.find((w) => w.name === widgetName); - } - } - - if (widget) { - widget.value = v; - if (widget.callback) { - widget.callback(widget.value, app.canvas, node, app.canvas.graph_mouse, {}); - } - } - } - } - - refreshComboInNode() { - const widget = this.widgets?.[0]; - if (widget?.type === "combo") { - widget.options.values = this.outputs[0].widget[GET_CONFIG]()[0]; - - if (!widget.options.values.includes(widget.value)) { - widget.value = widget.options.values[0]; - widget.callback(widget.value); - } - } - } - - onAfterGraphConfigured() { - if (this.outputs[0].links?.length && !this.widgets?.length) { - if (!this.#onFirstConnection()) return; - - // Populate widget values from config data - if (this.widgets) { - for (let i = 0; i < this.widgets_values.length; i++) { - const w = this.widgets[i]; - if (w) { - w.value = this.widgets_values[i]; - } - } - } - - // Merge values if required - this.#mergeWidgetConfig(); - } - } - - onConnectionsChange(_, index, connected) { - if (app.configuringGraph) { - // Dont run while the graph is still setting up - return; - } - - const links = this.outputs[0].links; - if (connected) { - if (links?.length && !this.widgets?.length) { - this.#onFirstConnection(); - } - } else { - // We may have removed a link that caused the constraints to change - this.#mergeWidgetConfig(); - - if (!links?.length) { - this.onLastDisconnect(); - } - } - } - - onConnectOutput(slot, type, input, target_node, target_slot) { - // Fires before the link is made allowing us to reject it if it isn't valid - // No widget, we cant connect - if (!input.widget) { - if (!(input.type in ComfyWidgets)) return false; - } - - if (this.outputs[slot].links?.length) { - const valid = this.#isValidConnection(input); - if (valid) { - // On connect of additional outputs, copy our value to their widget - this.applyToGraph([{ target_id: target_node.id, target_slot }]); - } - return valid; - } - } - - #onFirstConnection(recreating) { - // First connection can fire before the graph is ready on initial load so random things can be missing - if (!this.outputs[0].links) { - this.onLastDisconnect(); - return; - } - const linkId = this.outputs[0].links[0]; - const link = this.graph.links[linkId]; - if (!link) return; - - const theirNode = this.graph.getNodeById(link.target_id); - if (!theirNode || !theirNode.inputs) return; - - const input = theirNode.inputs[link.target_slot]; - if (!input) return; - - let widget; - if (!input.widget) { - if (!(input.type in ComfyWidgets)) return; - widget = { name: input.name, [GET_CONFIG]: () => [input.type, {}] }; //fake widget - } else { - widget = input.widget; - } - - const config = widget[GET_CONFIG]?.(); - if (!config) return; - - const { type } = getWidgetType(config); - // Update our output to restrict to the widget type - this.outputs[0].type = type; - this.outputs[0].name = type; - this.outputs[0].widget = widget; - - this.#createWidget(widget[CONFIG] ?? config, theirNode, widget.name, recreating, widget[TARGET]); - } - - #createWidget(inputData, node, widgetName, recreating, targetWidget) { - let type = inputData[0]; - - if (type instanceof Array) { - type = "COMBO"; - } - - let widget; - if (type in ComfyWidgets) { - widget = (ComfyWidgets[type](this, "value", inputData, app) || {}).widget; - } else { - widget = this.addWidget(type, "value", null, () => {}, {}); - } - - if (targetWidget) { - widget.value = targetWidget.value; - } else if (node?.widgets && widget) { - const theirWidget = node.widgets.find((w) => w.name === widgetName); - if (theirWidget) { - widget.value = theirWidget.value; - } - } - - if (!inputData?.[1]?.control_after_generate && (widget.type === "number" || widget.type === "combo")) { - let control_value = this.widgets_values?.[1]; - if (!control_value) { - control_value = "fixed"; - } - addValueControlWidgets(this, widget, control_value, undefined, inputData); - let filter = this.widgets_values?.[2]; - if (filter && this.widgets.length === 3) { - this.widgets[2].value = filter; - } - } - - // Restore any saved control values - const controlValues = this.controlValues; - if(this.lastType === this.widgets[0].type && controlValues?.length === this.widgets.length - 1) { - for(let i = 0; i < controlValues.length; i++) { - this.widgets[i + 1].value = controlValues[i]; - } - } - - // When our value changes, update other widgets to reflect our changes - // e.g. so LoadImage shows correct image - const callback = widget.callback; - const self = this; - widget.callback = function () { - const r = callback ? callback.apply(this, arguments) : undefined; - self.applyToGraph(); - return r; - }; - - if (!recreating) { - // Grow our node if required - const sz = this.computeSize(); - if (this.size[0] < sz[0]) { - this.size[0] = sz[0]; - } - if (this.size[1] < sz[1]) { - this.size[1] = sz[1]; - } - - requestAnimationFrame(() => { - if (this.onResize) { - this.onResize(this.size); - } - }); - } - } - - recreateWidget() { - const values = this.widgets?.map((w) => w.value); - this.#removeWidgets(); - this.#onFirstConnection(true); - if (values?.length) { - for (let i = 0; i < this.widgets?.length; i++) this.widgets[i].value = values[i]; - } - return this.widgets?.[0]; - } - - #mergeWidgetConfig() { - // Merge widget configs if the node has multiple outputs - const output = this.outputs[0]; - const links = output.links; - - const hasConfig = !!output.widget[CONFIG]; - if (hasConfig) { - delete output.widget[CONFIG]; - } - - if (links?.length < 2 && hasConfig) { - // Copy the widget options from the source - if (links.length) { - this.recreateWidget(); - } - - return; - } - - const config1 = output.widget[GET_CONFIG](); - const isNumber = config1[0] === "INT" || config1[0] === "FLOAT"; - if (!isNumber) return; - - for (const linkId of links) { - const link = app.graph.links[linkId]; - if (!link) continue; // Can be null when removing a node - - const theirNode = app.graph.getNodeById(link.target_id); - const theirInput = theirNode.inputs[link.target_slot]; - - // Call is valid connection so it can merge the configs when validating - this.#isValidConnection(theirInput, hasConfig); - } - } - - #isValidConnection(input, forceUpdate) { - // Only allow connections where the configs match - const output = this.outputs[0]; - const config2 = input.widget[GET_CONFIG](); - return !!mergeIfValid.call(this, output, config2, forceUpdate, this.recreateWidget); - } - - #removeWidgets() { - if (this.widgets) { - // Allow widgets to cleanup - for (const w of this.widgets) { - if (w.onRemove) { - w.onRemove(); - } - } - - // Temporarily store the current values in case the node is being recreated - // e.g. by group node conversion - this.controlValues = []; - this.lastType = this.widgets[0]?.type; - for(let i = 1; i < this.widgets.length; i++) { - this.controlValues.push(this.widgets[i].value); - } - setTimeout(() => { delete this.lastType; delete this.controlValues }, 15); - this.widgets.length = 0; - } - } - - onLastDisconnect() { - // We cant remove + re-add the output here as if you drag a link over the same link - // it removes, then re-adds, causing it to break - this.outputs[0].type = "*"; - this.outputs[0].name = "connect to widget input"; - delete this.outputs[0].widget; - - this.#removeWidgets(); - } - } - - LiteGraph.registerNodeType( - "PrimitiveNode", - Object.assign(PrimitiveNode, { - title: "Primitive", - }) - ); - PrimitiveNode.category = "utils"; - }, -}); +// Shim for extensions\core\widgetInputs.ts +export const getWidgetConfig = window.comfyAPI.widgetInputs.getWidgetConfig; +export const setWidgetConfig = window.comfyAPI.widgetInputs.setWidgetConfig; +export const mergeIfValid = window.comfyAPI.widgetInputs.mergeIfValid; diff --git a/web/extensions/logging.js.example b/web/extensions/logging.js.example deleted file mode 100644 index d015096a2..000000000 --- a/web/extensions/logging.js.example +++ /dev/null @@ -1,55 +0,0 @@ -import { app } from "../scripts/app.js"; - -const ext = { - // Unique name for the extension - name: "Example.LoggingExtension", - async init(app) { - // Any initial setup to run as soon as the page loads - console.log("[logging]", "extension init"); - }, - async setup(app) { - // Any setup to run after the app is created - console.log("[logging]", "extension setup"); - }, - async addCustomNodeDefs(defs, app) { - // Add custom node definitions - // These definitions will be configured and registered automatically - // defs is a lookup core nodes, add yours into this - console.log("[logging]", "add custom node definitions", "current nodes:", Object.keys(defs)); - }, - async getCustomWidgets(app) { - // Return custom widget types - // See ComfyWidgets for widget examples - console.log("[logging]", "provide custom widgets"); - }, - async beforeRegisterNodeDef(nodeType, nodeData, app) { - // Run custom logic before a node definition is registered with the graph - console.log("[logging]", "before register node: ", nodeType, nodeData); - - // This fires for every node definition so only log once - delete ext.beforeRegisterNodeDef; - }, - async registerCustomNodes(app) { - // Register any custom node implementations here allowing for more flexability than a custom node def - console.log("[logging]", "register custom nodes"); - }, - loadedGraphNode(node, app) { - // Fires for each node when loading/dragging/etc a workflow json or png - // If you break something in the backend and want to patch workflows in the frontend - // This is the place to do this - console.log("[logging]", "loaded graph node: ", node); - - // This fires for every node on each load so only log once - delete ext.loadedGraphNode; - }, - nodeCreated(node, app) { - // Fires every time a node is constructed - // You can modify widgets/add handlers/etc here - console.log("[logging]", "node created: ", node); - - // This fires for every node so only log once - delete ext.nodeCreated; - } -}; - -app.registerExtension(ext); diff --git a/web/index.html b/web/index.html index 5ebf03c01..16fcbe6a2 100644 --- a/web/index.html +++ b/web/index.html @@ -1,49 +1,50 @@ - - - - - ComfyUI - - - - - - - - - - - - - ComfyUI - - - New user: - - - - - OR - - - Existing user: - - Select a user - - - - - - - - - - + + + + + ComfyUI + + + + + + + + + + + + + ComfyUI + + + New user: + + + + + OR + + + Existing user: + + Select a user + + + + + + + + + + diff --git a/web/jsconfig.json b/web/jsconfig.json deleted file mode 100644 index cd55a0cc7..000000000 --- a/web/jsconfig.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "compilerOptions": { - "baseUrl": ".", - "paths": { - "/*": ["./*"] - }, - "lib": ["DOM", "ES2022", "DOM.Iterable"], - "target": "ES2015", - "module": "es2020" - }, - "include": ["."] -} diff --git a/web/lib/litegraph.core.js b/web/lib/litegraph.core.js deleted file mode 100644 index 427a62b59..000000000 --- a/web/lib/litegraph.core.js +++ /dev/null @@ -1,14424 +0,0 @@ -//packer version - - -(function(global) { - // ************************************************************* - // LiteGraph CLASS ******* - // ************************************************************* - - /** - * The Global Scope. It contains all the registered node classes. - * - * @class LiteGraph - * @constructor - */ - - var LiteGraph = (global.LiteGraph = { - VERSION: 0.4, - - CANVAS_GRID_SIZE: 10, - - NODE_TITLE_HEIGHT: 30, - NODE_TITLE_TEXT_Y: 20, - NODE_SLOT_HEIGHT: 20, - NODE_WIDGET_HEIGHT: 20, - NODE_WIDTH: 140, - NODE_MIN_WIDTH: 50, - NODE_COLLAPSED_RADIUS: 10, - NODE_COLLAPSED_WIDTH: 80, - NODE_TITLE_COLOR: "#999", - NODE_SELECTED_TITLE_COLOR: "#FFF", - NODE_TEXT_SIZE: 14, - NODE_TEXT_COLOR: "#AAA", - NODE_SUBTEXT_SIZE: 12, - NODE_DEFAULT_COLOR: "#333", - NODE_DEFAULT_BGCOLOR: "#353535", - NODE_DEFAULT_BOXCOLOR: "#666", - NODE_DEFAULT_SHAPE: "box", - NODE_BOX_OUTLINE_COLOR: "#FFF", - DEFAULT_SHADOW_COLOR: "rgba(0,0,0,0.5)", - DEFAULT_GROUP_FONT: 24, - - WIDGET_BGCOLOR: "#222", - WIDGET_OUTLINE_COLOR: "#666", - WIDGET_TEXT_COLOR: "#DDD", - WIDGET_SECONDARY_TEXT_COLOR: "#999", - - LINK_COLOR: "#9A9", - EVENT_LINK_COLOR: "#A86", - CONNECTING_LINK_COLOR: "#AFA", - - MAX_NUMBER_OF_NODES: 10000, //avoid infinite loops - DEFAULT_POSITION: [100, 100], //default node position - VALID_SHAPES: ["default", "box", "round", "card"], //,"circle" - - //shapes are used for nodes but also for slots - BOX_SHAPE: 1, - ROUND_SHAPE: 2, - CIRCLE_SHAPE: 3, - CARD_SHAPE: 4, - ARROW_SHAPE: 5, - GRID_SHAPE: 6, // intended for slot arrays - - //enums - INPUT: 1, - OUTPUT: 2, - - EVENT: -1, //for outputs - ACTION: -1, //for inputs - - NODE_MODES: ["Always", "On Event", "Never", "On Trigger"], // helper, will add "On Request" and more in the future - NODE_MODES_COLORS:["#666","#422","#333","#224","#626"], // use with node_box_coloured_by_mode - ALWAYS: 0, - ON_EVENT: 1, - NEVER: 2, - ON_TRIGGER: 3, - - UP: 1, - DOWN: 2, - LEFT: 3, - RIGHT: 4, - CENTER: 5, - - LINK_RENDER_MODES: ["Straight", "Linear", "Spline"], // helper - STRAIGHT_LINK: 0, - LINEAR_LINK: 1, - SPLINE_LINK: 2, - - NORMAL_TITLE: 0, - NO_TITLE: 1, - TRANSPARENT_TITLE: 2, - AUTOHIDE_TITLE: 3, - VERTICAL_LAYOUT: "vertical", // arrange nodes vertically - - proxy: null, //used to redirect calls - node_images_path: "", - - debug: false, - catch_exceptions: true, - throw_errors: true, - allow_scripts: false, //if set to true some nodes like Formula would be allowed to evaluate code that comes from unsafe sources (like node configuration), which could lead to exploits - registered_node_types: {}, //nodetypes by string - node_types_by_file_extension: {}, //used for dropping files in the canvas - Nodes: {}, //node types by classname - Globals: {}, //used to store vars between graphs - - searchbox_extras: {}, //used to add extra features to the search box - auto_sort_node_types: false, // [true!] If set to true, will automatically sort node types / categories in the context menus - - node_box_coloured_when_on: false, // [true!] this make the nodes box (top left circle) coloured when triggered (execute/action), visual feedback - node_box_coloured_by_mode: false, // [true!] nodebox based on node mode, visual feedback - - dialog_close_on_mouse_leave: false, // [false on mobile] better true if not touch device, TODO add an helper/listener to close if false - dialog_close_on_mouse_leave_delay: 500, - - shift_click_do_break_link_from: false, // [false!] prefer false if results too easy to break links - implement with ALT or TODO custom keys - click_do_break_link_to: false, // [false!]prefer false, way too easy to break links - - search_hide_on_mouse_leave: true, // [false on mobile] better true if not touch device, TODO add an helper/listener to close if false - search_filter_enabled: false, // [true!] enable filtering slots type in the search widget, !requires auto_load_slot_types or manual set registered_slot_[in/out]_types and slot_types_[in/out] - search_show_all_on_open: true, // [true!] opens the results list when opening the search widget - - auto_load_slot_types: false, // [if want false, use true, run, get vars values to be statically set, than disable] nodes types and nodeclass association with node types need to be calculated, if dont want this, calculate once and set registered_slot_[in/out]_types and slot_types_[in/out] - - // set these values if not using auto_load_slot_types - registered_slot_in_types: {}, // slot types for nodeclass - registered_slot_out_types: {}, // slot types for nodeclass - slot_types_in: [], // slot types IN - slot_types_out: [], // slot types OUT - slot_types_default_in: [], // specify for each IN slot type a(/many) default node(s), use single string, array, or object (with node, title, parameters, ..) like for search - slot_types_default_out: [], // specify for each OUT slot type a(/many) default node(s), use single string, array, or object (with node, title, parameters, ..) like for search - - alt_drag_do_clone_nodes: false, // [true!] very handy, ALT click to clone and drag the new node - - do_add_triggers_slots: false, // [true!] will create and connect event slots when using action/events connections, !WILL CHANGE node mode when using onTrigger (enable mode colors), onExecuted does not need this - - allow_multi_output_for_events: true, // [false!] being events, it is strongly reccomended to use them sequentially, one by one - - middle_click_slot_add_default_node: false, //[true!] allows to create and connect a ndoe clicking with the third button (wheel) - - release_link_on_empty_shows_menu: false, //[true!] dragging a link to empty space will open a menu, add from list, search or defaults - - pointerevents_method: "pointer", // "mouse"|"pointer" use mouse for retrocompatibility issues? (none found @ now) - // TODO implement pointercancel, gotpointercapture, lostpointercapture, (pointerover, pointerout if necessary) - - ctrl_shift_v_paste_connect_unselected_outputs: true, //[true!] allows ctrl + shift + v to paste nodes with the outputs of the unselected nodes connected with the inputs of the newly pasted nodes - - // if true, all newly created nodes/links will use string UUIDs for their id fields instead of integers. - // use this if you must have node IDs that are unique across all graphs and subgraphs. - use_uuids: false, - - /** - * Register a node class so it can be listed when the user wants to create a new one - * @method registerNodeType - * @param {String} type name of the node and path - * @param {Class} base_class class containing the structure of a node - */ - - registerNodeType: function(type, base_class) { - if (!base_class.prototype) { - throw "Cannot register a simple object, it must be a class with a prototype"; - } - base_class.type = type; - - if (LiteGraph.debug) { - console.log("Node registered: " + type); - } - - const classname = base_class.name; - - const pos = type.lastIndexOf("/"); - base_class.category = type.substring(0, pos); - - if (!base_class.title) { - base_class.title = classname; - } - - //extend class - for (var i in LGraphNode.prototype) { - if (!base_class.prototype[i]) { - base_class.prototype[i] = LGraphNode.prototype[i]; - } - } - - const prev = this.registered_node_types[type]; - if(prev) { - console.log("replacing node type: " + type); - } - if( !Object.prototype.hasOwnProperty.call( base_class.prototype, "shape") ) { - Object.defineProperty(base_class.prototype, "shape", { - set: function(v) { - switch (v) { - case "default": - delete this._shape; - break; - case "box": - this._shape = LiteGraph.BOX_SHAPE; - break; - case "round": - this._shape = LiteGraph.ROUND_SHAPE; - break; - case "circle": - this._shape = LiteGraph.CIRCLE_SHAPE; - break; - case "card": - this._shape = LiteGraph.CARD_SHAPE; - break; - default: - this._shape = v; - } - }, - get: function() { - return this._shape; - }, - enumerable: true, - configurable: true - }); - - - //used to know which nodes to create when dragging files to the canvas - if (base_class.supported_extensions) { - for (let i in base_class.supported_extensions) { - const ext = base_class.supported_extensions[i]; - if(ext && ext.constructor === String) { - this.node_types_by_file_extension[ ext.toLowerCase() ] = base_class; - } - } - } - } - - this.registered_node_types[type] = base_class; - if (base_class.constructor.name) { - this.Nodes[classname] = base_class; - } - if (LiteGraph.onNodeTypeRegistered) { - LiteGraph.onNodeTypeRegistered(type, base_class); - } - if (prev && LiteGraph.onNodeTypeReplaced) { - LiteGraph.onNodeTypeReplaced(type, base_class, prev); - } - - //warnings - if (base_class.prototype.onPropertyChange) { - console.warn( - "LiteGraph node class " + - type + - " has onPropertyChange method, it must be called onPropertyChanged with d at the end" - ); - } - - // TODO one would want to know input and ouput :: this would allow through registerNodeAndSlotType to get all the slots types - if (this.auto_load_slot_types) { - new base_class(base_class.title || "tmpnode"); - } - }, - - /** - * removes a node type from the system - * @method unregisterNodeType - * @param {String|Object} type name of the node or the node constructor itself - */ - unregisterNodeType: function(type) { - const base_class = - type.constructor === String - ? this.registered_node_types[type] - : type; - if (!base_class) { - throw "node type not found: " + type; - } - delete this.registered_node_types[base_class.type]; - if (base_class.constructor.name) { - delete this.Nodes[base_class.constructor.name]; - } - }, - - /** - * Save a slot type and his node - * @method registerSlotType - * @param {String|Object} type name of the node or the node constructor itself - * @param {String} slot_type name of the slot type (variable type), eg. string, number, array, boolean, .. - */ - registerNodeAndSlotType: function(type, slot_type, out){ - out = out || false; - const base_class = - type.constructor === String && - this.registered_node_types[type] !== "anonymous" - ? this.registered_node_types[type] - : type; - - const class_type = base_class.constructor.type; - - let allTypes = []; - if (typeof slot_type === "string") { - allTypes = slot_type.split(","); - } else if (slot_type == this.EVENT || slot_type == this.ACTION) { - allTypes = ["_event_"]; - } else { - allTypes = ["*"]; - } - - for (let i = 0; i < allTypes.length; ++i) { - let slotType = allTypes[i]; - if (slotType === "") { - slotType = "*"; - } - const registerTo = out - ? "registered_slot_out_types" - : "registered_slot_in_types"; - if (this[registerTo][slotType] === undefined) { - this[registerTo][slotType] = { nodes: [] }; - } - if (!this[registerTo][slotType].nodes.includes(class_type)) { - this[registerTo][slotType].nodes.push(class_type); - } - - // check if is a new type - if (!out) { - if (!this.slot_types_in.includes(slotType.toLowerCase())) { - this.slot_types_in.push(slotType.toLowerCase()); - this.slot_types_in.sort(); - } - } else { - if (!this.slot_types_out.includes(slotType.toLowerCase())) { - this.slot_types_out.push(slotType.toLowerCase()); - this.slot_types_out.sort(); - } - } - } - }, - - /** - * Create a new nodetype by passing a function, it wraps it with a proper class and generates inputs according to the parameters of the function. - * Useful to wrap simple methods that do not require properties, and that only process some input to generate an output. - * @method wrapFunctionAsNode - * @param {String} name node name with namespace (p.e.: 'math/sum') - * @param {Function} func - * @param {Array} param_types [optional] an array containing the type of every parameter, otherwise parameters will accept any type - * @param {String} return_type [optional] string with the return type, otherwise it will be generic - * @param {Object} properties [optional] properties to be configurable - */ - wrapFunctionAsNode: function( - name, - func, - param_types, - return_type, - properties - ) { - var params = Array(func.length); - var code = ""; - var names = LiteGraph.getParameterNames(func); - for (var i = 0; i < names.length; ++i) { - code += - "this.addInput('" + - names[i] + - "'," + - (param_types && param_types[i] - ? "'" + param_types[i] + "'" - : "0") + - ");\n"; - } - code += - "this.addOutput('out'," + - (return_type ? "'" + return_type + "'" : 0) + - ");\n"; - if (properties) { - code += - "this.properties = " + JSON.stringify(properties) + ";\n"; - } - var classobj = Function(code); - classobj.title = name.split("/").pop(); - classobj.desc = "Generated from " + func.name; - classobj.prototype.onExecute = function onExecute() { - for (var i = 0; i < params.length; ++i) { - params[i] = this.getInputData(i); - } - var r = func.apply(this, params); - this.setOutputData(0, r); - }; - this.registerNodeType(name, classobj); - }, - - /** - * Removes all previously registered node's types - */ - clearRegisteredTypes: function() { - this.registered_node_types = {}; - this.node_types_by_file_extension = {}; - this.Nodes = {}; - this.searchbox_extras = {}; - }, - - /** - * Adds this method to all nodetypes, existing and to be created - * (You can add it to LGraphNode.prototype but then existing node types wont have it) - * @method addNodeMethod - * @param {Function} func - */ - addNodeMethod: function(name, func) { - LGraphNode.prototype[name] = func; - for (var i in this.registered_node_types) { - var type = this.registered_node_types[i]; - if (type.prototype[name]) { - type.prototype["_" + name] = type.prototype[name]; - } //keep old in case of replacing - type.prototype[name] = func; - } - }, - - /** - * Create a node of a given type with a name. The node is not attached to any graph yet. - * @method createNode - * @param {String} type full name of the node class. p.e. "math/sin" - * @param {String} name a name to distinguish from other nodes - * @param {Object} options to set options - */ - - createNode: function(type, title, options) { - var base_class = this.registered_node_types[type]; - if (!base_class) { - if (LiteGraph.debug) { - console.log( - 'GraphNode type "' + type + '" not registered.' - ); - } - return null; - } - - var prototype = base_class.prototype || base_class; - - title = title || base_class.title || type; - - var node = null; - - if (LiteGraph.catch_exceptions) { - try { - node = new base_class(title); - } catch (err) { - console.error(err); - return null; - } - } else { - node = new base_class(title); - } - - node.type = type; - - if (!node.title && title) { - node.title = title; - } - if (!node.properties) { - node.properties = {}; - } - if (!node.properties_info) { - node.properties_info = []; - } - if (!node.flags) { - node.flags = {}; - } - if (!node.size) { - node.size = node.computeSize(); - //call onresize? - } - if (!node.pos) { - node.pos = LiteGraph.DEFAULT_POSITION.concat(); - } - if (!node.mode) { - node.mode = LiteGraph.ALWAYS; - } - - //extra options - if (options) { - for (var i in options) { - node[i] = options[i]; - } - } - - // callback - if ( node.onNodeCreated ) { - node.onNodeCreated(); - } - - return node; - }, - - /** - * Returns a registered node type with a given name - * @method getNodeType - * @param {String} type full name of the node class. p.e. "math/sin" - * @return {Class} the node class - */ - getNodeType: function(type) { - return this.registered_node_types[type]; - }, - - /** - * Returns a list of node types matching one category - * @method getNodeType - * @param {String} category category name - * @return {Array} array with all the node classes - */ - - getNodeTypesInCategory: function(category, filter) { - var r = []; - for (var i in this.registered_node_types) { - var type = this.registered_node_types[i]; - if (type.filter != filter) { - continue; - } - - if (category == "") { - if (type.category == null) { - r.push(type); - } - } else if (type.category == category) { - r.push(type); - } - } - - if (this.auto_sort_node_types) { - r.sort(function(a,b){return a.title.localeCompare(b.title)}); - } - - return r; - }, - - /** - * Returns a list with all the node type categories - * @method getNodeTypesCategories - * @param {String} filter only nodes with ctor.filter equal can be shown - * @return {Array} array with all the names of the categories - */ - getNodeTypesCategories: function( filter ) { - var categories = { "": 1 }; - for (var i in this.registered_node_types) { - var type = this.registered_node_types[i]; - if ( type.category && !type.skip_list ) - { - if(type.filter != filter) - continue; - categories[type.category] = 1; - } - } - var result = []; - for (var i in categories) { - result.push(i); - } - return this.auto_sort_node_types ? result.sort() : result; - }, - - //debug purposes: reloads all the js scripts that matches a wildcard - reloadNodes: function(folder_wildcard) { - var tmp = document.getElementsByTagName("script"); - //weird, this array changes by its own, so we use a copy - var script_files = []; - for (var i=0; i < tmp.length; i++) { - script_files.push(tmp[i]); - } - - var docHeadObj = document.getElementsByTagName("head")[0]; - folder_wildcard = document.location.href + folder_wildcard; - - for (var i=0; i < script_files.length; i++) { - var src = script_files[i].src; - if ( - !src || - src.substr(0, folder_wildcard.length) != folder_wildcard - ) { - continue; - } - - try { - if (LiteGraph.debug) { - console.log("Reloading: " + src); - } - var dynamicScript = document.createElement("script"); - dynamicScript.type = "text/javascript"; - dynamicScript.src = src; - docHeadObj.appendChild(dynamicScript); - docHeadObj.removeChild(script_files[i]); - } catch (err) { - if (LiteGraph.throw_errors) { - throw err; - } - if (LiteGraph.debug) { - console.log("Error while reloading " + src); - } - } - } - - if (LiteGraph.debug) { - console.log("Nodes reloaded"); - } - }, - - //separated just to improve if it doesn't work - cloneObject: function(obj, target) { - if (obj == null) { - return null; - } - var r = JSON.parse(JSON.stringify(obj)); - if (!target) { - return r; - } - - for (var i in r) { - target[i] = r[i]; - } - return target; - }, - - /* - * https://gist.github.com/jed/982883?permalink_comment_id=852670#gistcomment-852670 - */ - uuidv4: function() { - return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,a=>(a^Math.random()*16>>a/4).toString(16)); - }, - - /** - * Returns if the types of two slots are compatible (taking into account wildcards, etc) - * @method isValidConnection - * @param {String} type_a - * @param {String} type_b - * @return {Boolean} true if they can be connected - */ - isValidConnection: function(type_a, type_b) { - if (type_a=="" || type_a==="*") type_a = 0; - if (type_b=="" || type_b==="*") type_b = 0; - if ( - !type_a //generic output - || !type_b // generic input - || type_a == type_b //same type (is valid for triggers) - || (type_a == LiteGraph.EVENT && type_b == LiteGraph.ACTION) - ) { - return true; - } - - // Enforce string type to handle toLowerCase call (-1 number not ok) - type_a = String(type_a); - type_b = String(type_b); - type_a = type_a.toLowerCase(); - type_b = type_b.toLowerCase(); - - // For nodes supporting multiple connection types - if (type_a.indexOf(",") == -1 && type_b.indexOf(",") == -1) { - return type_a == type_b; - } - - // Check all permutations to see if one is valid - var supported_types_a = type_a.split(","); - var supported_types_b = type_b.split(","); - for (var i = 0; i < supported_types_a.length; ++i) { - for (var j = 0; j < supported_types_b.length; ++j) { - if(this.isValidConnection(supported_types_a[i],supported_types_b[j])){ - //if (supported_types_a[i] == supported_types_b[j]) { - return true; - } - } - } - - return false; - }, - - /** - * Register a string in the search box so when the user types it it will recommend this node - * @method registerSearchboxExtra - * @param {String} node_type the node recommended - * @param {String} description text to show next to it - * @param {Object} data it could contain info of how the node should be configured - * @return {Boolean} true if they can be connected - */ - registerSearchboxExtra: function(node_type, description, data) { - this.searchbox_extras[description.toLowerCase()] = { - type: node_type, - desc: description, - data: data - }; - }, - - /** - * Wrapper to load files (from url using fetch or from file using FileReader) - * @method fetchFile - * @param {String|File|Blob} url the url of the file (or the file itself) - * @param {String} type an string to know how to fetch it: "text","arraybuffer","json","blob" - * @param {Function} on_complete callback(data) - * @param {Function} on_error in case of an error - * @return {FileReader|Promise} returns the object used to - */ - fetchFile: function( url, type, on_complete, on_error ) { - var that = this; - if(!url) - return null; - - type = type || "text"; - if( url.constructor === String ) - { - if (url.substr(0, 4) == "http" && LiteGraph.proxy) { - url = LiteGraph.proxy + url.substr(url.indexOf(":") + 3); - } - return fetch(url) - .then(function(response) { - if(!response.ok) - throw new Error("File not found"); //it will be catch below - if(type == "arraybuffer") - return response.arrayBuffer(); - else if(type == "text" || type == "string") - return response.text(); - else if(type == "json") - return response.json(); - else if(type == "blob") - return response.blob(); - }) - .then(function(data) { - if(on_complete) - on_complete(data); - }) - .catch(function(error) { - console.error("error fetching file:",url); - if(on_error) - on_error(error); - }); - } - else if( url.constructor === File || url.constructor === Blob) - { - var reader = new FileReader(); - reader.onload = function(e) - { - var v = e.target.result; - if( type == "json" ) - v = JSON.parse(v); - if(on_complete) - on_complete(v); - } - if(type == "arraybuffer") - return reader.readAsArrayBuffer(url); - else if(type == "text" || type == "json") - return reader.readAsText(url); - else if(type == "blob") - return reader.readAsBinaryString(url); - } - return null; - } - }); - - //timer that works everywhere - if (typeof performance != "undefined") { - LiteGraph.getTime = performance.now.bind(performance); - } else if (typeof Date != "undefined" && Date.now) { - LiteGraph.getTime = Date.now.bind(Date); - } else if (typeof process != "undefined") { - LiteGraph.getTime = function() { - var t = process.hrtime(); - return t[0] * 0.001 + t[1] * 1e-6; - }; - } else { - LiteGraph.getTime = function getTime() { - return new Date().getTime(); - }; - } - - //********************************************************************************* - // LGraph CLASS - //********************************************************************************* - - /** - * LGraph is the class that contain a full graph. We instantiate one and add nodes to it, and then we can run the execution loop. - * supported callbacks: - + onNodeAdded: when a new node is added to the graph - + onNodeRemoved: when a node inside this graph is removed - + onNodeConnectionChange: some connection has changed in the graph (connected or disconnected) - * - * @class LGraph - * @constructor - * @param {Object} o data from previous serialization [optional] - */ - - function LGraph(o) { - if (LiteGraph.debug) { - console.log("Graph created"); - } - this.list_of_graphcanvas = null; - this.clear(); - - if (o) { - this.configure(o); - } - } - - global.LGraph = LiteGraph.LGraph = LGraph; - - //default supported types - LGraph.supported_types = ["number", "string", "boolean"]; - - //used to know which types of connections support this graph (some graphs do not allow certain types) - LGraph.prototype.getSupportedTypes = function() { - return this.supported_types || LGraph.supported_types; - }; - - LGraph.STATUS_STOPPED = 1; - LGraph.STATUS_RUNNING = 2; - - /** - * Removes all nodes from this graph - * @method clear - */ - - LGraph.prototype.clear = function() { - this.stop(); - this.status = LGraph.STATUS_STOPPED; - - this.last_node_id = 0; - this.last_link_id = 0; - - this._version = -1; //used to detect changes - - //safe clear - if (this._nodes) { - for (var i = 0; i < this._nodes.length; ++i) { - var node = this._nodes[i]; - if (node.onRemoved) { - node.onRemoved(); - } - } - } - - //nodes - this._nodes = []; - this._nodes_by_id = {}; - this._nodes_in_order = []; //nodes sorted in execution order - this._nodes_executable = null; //nodes that contain onExecute sorted in execution order - - //other scene stuff - this._groups = []; - - //links - this.links = {}; //container with all the links - - //iterations - this.iteration = 0; - - //custom data - this.config = {}; - this.vars = {}; - this.extra = {}; //to store custom data - - //timing - this.globaltime = 0; - this.runningtime = 0; - this.fixedtime = 0; - this.fixedtime_lapse = 0.01; - this.elapsed_time = 0.01; - this.last_update_time = 0; - this.starttime = 0; - - this.catch_errors = true; - - this.nodes_executing = []; - this.nodes_actioning = []; - this.nodes_executedAction = []; - - //subgraph_data - this.inputs = {}; - this.outputs = {}; - - //notify canvas to redraw - this.change(); - - this.sendActionToCanvas("clear"); - }; - - /** - * Attach Canvas to this graph - * @method attachCanvas - * @param {GraphCanvas} graph_canvas - */ - - LGraph.prototype.attachCanvas = function(graphcanvas) { - if (graphcanvas.constructor != LGraphCanvas) { - throw "attachCanvas expects a LGraphCanvas instance"; - } - if (graphcanvas.graph && graphcanvas.graph != this) { - graphcanvas.graph.detachCanvas(graphcanvas); - } - - graphcanvas.graph = this; - - if (!this.list_of_graphcanvas) { - this.list_of_graphcanvas = []; - } - this.list_of_graphcanvas.push(graphcanvas); - }; - - /** - * Detach Canvas from this graph - * @method detachCanvas - * @param {GraphCanvas} graph_canvas - */ - LGraph.prototype.detachCanvas = function(graphcanvas) { - if (!this.list_of_graphcanvas) { - return; - } - - var pos = this.list_of_graphcanvas.indexOf(graphcanvas); - if (pos == -1) { - return; - } - graphcanvas.graph = null; - this.list_of_graphcanvas.splice(pos, 1); - }; - - /** - * Starts running this graph every interval milliseconds. - * @method start - * @param {number} interval amount of milliseconds between executions, if 0 then it renders to the monitor refresh rate - */ - - LGraph.prototype.start = function(interval) { - if (this.status == LGraph.STATUS_RUNNING) { - return; - } - this.status = LGraph.STATUS_RUNNING; - - if (this.onPlayEvent) { - this.onPlayEvent(); - } - - this.sendEventToAllNodes("onStart"); - - //launch - this.starttime = LiteGraph.getTime(); - this.last_update_time = this.starttime; - interval = interval || 0; - var that = this; - - //execute once per frame - if ( interval == 0 && typeof window != "undefined" && window.requestAnimationFrame ) { - function on_frame() { - if (that.execution_timer_id != -1) { - return; - } - window.requestAnimationFrame(on_frame); - if(that.onBeforeStep) - that.onBeforeStep(); - that.runStep(1, !that.catch_errors); - if(that.onAfterStep) - that.onAfterStep(); - } - this.execution_timer_id = -1; - on_frame(); - } else { //execute every 'interval' ms - this.execution_timer_id = setInterval(function() { - //execute - if(that.onBeforeStep) - that.onBeforeStep(); - that.runStep(1, !that.catch_errors); - if(that.onAfterStep) - that.onAfterStep(); - }, interval); - } - }; - - /** - * Stops the execution loop of the graph - * @method stop execution - */ - - LGraph.prototype.stop = function() { - if (this.status == LGraph.STATUS_STOPPED) { - return; - } - - this.status = LGraph.STATUS_STOPPED; - - if (this.onStopEvent) { - this.onStopEvent(); - } - - if (this.execution_timer_id != null) { - if (this.execution_timer_id != -1) { - clearInterval(this.execution_timer_id); - } - this.execution_timer_id = null; - } - - this.sendEventToAllNodes("onStop"); - }; - - /** - * Run N steps (cycles) of the graph - * @method runStep - * @param {number} num number of steps to run, default is 1 - * @param {Boolean} do_not_catch_errors [optional] if you want to try/catch errors - * @param {number} limit max number of nodes to execute (used to execute from start to a node) - */ - - LGraph.prototype.runStep = function(num, do_not_catch_errors, limit ) { - num = num || 1; - - var start = LiteGraph.getTime(); - this.globaltime = 0.001 * (start - this.starttime); - - var nodes = this._nodes_executable - ? this._nodes_executable - : this._nodes; - if (!nodes) { - return; - } - - limit = limit || nodes.length; - - if (do_not_catch_errors) { - //iterations - for (var i = 0; i < num; i++) { - for (var j = 0; j < limit; ++j) { - var node = nodes[j]; - if (node.mode == LiteGraph.ALWAYS && node.onExecute) { - //wrap node.onExecute(); - node.doExecute(); - } - } - - this.fixedtime += this.fixedtime_lapse; - if (this.onExecuteStep) { - this.onExecuteStep(); - } - } - - if (this.onAfterExecute) { - this.onAfterExecute(); - } - } else { - try { - //iterations - for (var i = 0; i < num; i++) { - for (var j = 0; j < limit; ++j) { - var node = nodes[j]; - if (node.mode == LiteGraph.ALWAYS && node.onExecute) { - node.onExecute(); - } - } - - this.fixedtime += this.fixedtime_lapse; - if (this.onExecuteStep) { - this.onExecuteStep(); - } - } - - if (this.onAfterExecute) { - this.onAfterExecute(); - } - this.errors_in_execution = false; - } catch (err) { - this.errors_in_execution = true; - if (LiteGraph.throw_errors) { - throw err; - } - if (LiteGraph.debug) { - console.log("Error during execution: " + err); - } - this.stop(); - } - } - - var now = LiteGraph.getTime(); - var elapsed = now - start; - if (elapsed == 0) { - elapsed = 1; - } - this.execution_time = 0.001 * elapsed; - this.globaltime += 0.001 * elapsed; - this.iteration += 1; - this.elapsed_time = (now - this.last_update_time) * 0.001; - this.last_update_time = now; - this.nodes_executing = []; - this.nodes_actioning = []; - this.nodes_executedAction = []; - }; - - /** - * Updates the graph execution order according to relevance of the nodes (nodes with only outputs have more relevance than - * nodes with only inputs. - * @method updateExecutionOrder - */ - LGraph.prototype.updateExecutionOrder = function() { - this._nodes_in_order = this.computeExecutionOrder(false); - this._nodes_executable = []; - for (var i = 0; i < this._nodes_in_order.length; ++i) { - if (this._nodes_in_order[i].onExecute) { - this._nodes_executable.push(this._nodes_in_order[i]); - } - } - }; - - //This is more internal, it computes the executable nodes in order and returns it - LGraph.prototype.computeExecutionOrder = function( - only_onExecute, - set_level - ) { - var L = []; - var S = []; - var M = {}; - var visited_links = {}; //to avoid repeating links - var remaining_links = {}; //to a - - //search for the nodes without inputs (starting nodes) - for (var i = 0, l = this._nodes.length; i < l; ++i) { - var node = this._nodes[i]; - if (only_onExecute && !node.onExecute) { - continue; - } - - M[node.id] = node; //add to pending nodes - - var num = 0; //num of input connections - if (node.inputs) { - for (var j = 0, l2 = node.inputs.length; j < l2; j++) { - if (node.inputs[j] && node.inputs[j].link != null) { - num += 1; - } - } - } - - if (num == 0) { - //is a starting node - S.push(node); - if (set_level) { - node._level = 1; - } - } //num of input links - else { - if (set_level) { - node._level = 0; - } - remaining_links[node.id] = num; - } - } - - while (true) { - if (S.length == 0) { - break; - } - - //get an starting node - var node = S.shift(); - L.push(node); //add to ordered list - delete M[node.id]; //remove from the pending nodes - - if (!node.outputs) { - continue; - } - - //for every output - for (var i = 0; i < node.outputs.length; i++) { - var output = node.outputs[i]; - //not connected - if ( - output == null || - output.links == null || - output.links.length == 0 - ) { - continue; - } - - //for every connection - for (var j = 0; j < output.links.length; j++) { - var link_id = output.links[j]; - var link = this.links[link_id]; - if (!link) { - continue; - } - - //already visited link (ignore it) - if (visited_links[link.id]) { - continue; - } - - var target_node = this.getNodeById(link.target_id); - if (target_node == null) { - visited_links[link.id] = true; - continue; - } - - if ( - set_level && - (!target_node._level || - target_node._level <= node._level) - ) { - target_node._level = node._level + 1; - } - - visited_links[link.id] = true; //mark as visited - remaining_links[target_node.id] -= 1; //reduce the number of links remaining - if (remaining_links[target_node.id] == 0) { - S.push(target_node); - } //if no more links, then add to starters array - } - } - } - - //the remaining ones (loops) - for (var i in M) { - L.push(M[i]); - } - - if (L.length != this._nodes.length && LiteGraph.debug) { - console.warn("something went wrong, nodes missing"); - } - - var l = L.length; - - //save order number in the node - for (var i = 0; i < l; ++i) { - L[i].order = i; - } - - //sort now by priority - L = L.sort(function(A, B) { - var Ap = A.constructor.priority || A.priority || 0; - var Bp = B.constructor.priority || B.priority || 0; - if (Ap == Bp) { - //if same priority, sort by order - return A.order - B.order; - } - return Ap - Bp; //sort by priority - }); - - //save order number in the node, again... - for (var i = 0; i < l; ++i) { - L[i].order = i; - } - - return L; - }; - - /** - * Returns all the nodes that could affect this one (ancestors) by crawling all the inputs recursively. - * It doesn't include the node itself - * @method getAncestors - * @return {Array} an array with all the LGraphNodes that affect this node, in order of execution - */ - LGraph.prototype.getAncestors = function(node) { - var ancestors = []; - var pending = [node]; - var visited = {}; - - while (pending.length) { - var current = pending.shift(); - if (!current.inputs) { - continue; - } - if (!visited[current.id] && current != node) { - visited[current.id] = true; - ancestors.push(current); - } - - for (var i = 0; i < current.inputs.length; ++i) { - var input = current.getInputNode(i); - if (input && ancestors.indexOf(input) == -1) { - pending.push(input); - } - } - } - - ancestors.sort(function(a, b) { - return a.order - b.order; - }); - return ancestors; - }; - - /** - * Positions every node in a more readable manner - * @method arrange - */ - LGraph.prototype.arrange = function (margin, layout) { - margin = margin || 100; - - const nodes = this.computeExecutionOrder(false, true); - const columns = []; - for (let i = 0; i < nodes.length; ++i) { - const node = nodes[i]; - const col = node._level || 1; - if (!columns[col]) { - columns[col] = []; - } - columns[col].push(node); - } - - let x = margin; - - for (let i = 0; i < columns.length; ++i) { - const column = columns[i]; - if (!column) { - continue; - } - let max_size = 100; - let y = margin + LiteGraph.NODE_TITLE_HEIGHT; - for (let j = 0; j < column.length; ++j) { - const node = column[j]; - node.pos[0] = (layout == LiteGraph.VERTICAL_LAYOUT) ? y : x; - node.pos[1] = (layout == LiteGraph.VERTICAL_LAYOUT) ? x : y; - const max_size_index = (layout == LiteGraph.VERTICAL_LAYOUT) ? 1 : 0; - if (node.size[max_size_index] > max_size) { - max_size = node.size[max_size_index]; - } - const node_size_index = (layout == LiteGraph.VERTICAL_LAYOUT) ? 0 : 1; - y += node.size[node_size_index] + margin + LiteGraph.NODE_TITLE_HEIGHT; - } - x += max_size + margin; - } - - this.setDirtyCanvas(true, true); - }; - - /** - * Returns the amount of time the graph has been running in milliseconds - * @method getTime - * @return {number} number of milliseconds the graph has been running - */ - LGraph.prototype.getTime = function() { - return this.globaltime; - }; - - /** - * Returns the amount of time accumulated using the fixedtime_lapse var. This is used in context where the time increments should be constant - * @method getFixedTime - * @return {number} number of milliseconds the graph has been running - */ - - LGraph.prototype.getFixedTime = function() { - return this.fixedtime; - }; - - /** - * Returns the amount of time it took to compute the latest iteration. Take into account that this number could be not correct - * if the nodes are using graphical actions - * @method getElapsedTime - * @return {number} number of milliseconds it took the last cycle - */ - - LGraph.prototype.getElapsedTime = function() { - return this.elapsed_time; - }; - - /** - * Sends an event to all the nodes, useful to trigger stuff - * @method sendEventToAllNodes - * @param {String} eventname the name of the event (function to be called) - * @param {Array} params parameters in array format - */ - LGraph.prototype.sendEventToAllNodes = function(eventname, params, mode) { - mode = mode || LiteGraph.ALWAYS; - - var nodes = this._nodes_in_order ? this._nodes_in_order : this._nodes; - if (!nodes) { - return; - } - - for (var j = 0, l = nodes.length; j < l; ++j) { - var node = nodes[j]; - - if ( - node.constructor === LiteGraph.Subgraph && - eventname != "onExecute" - ) { - if (node.mode == mode) { - node.sendEventToAllNodes(eventname, params, mode); - } - continue; - } - - if (!node[eventname] || node.mode != mode) { - continue; - } - if (params === undefined) { - node[eventname](); - } else if (params && params.constructor === Array) { - node[eventname].apply(node, params); - } else { - node[eventname](params); - } - } - }; - - LGraph.prototype.sendActionToCanvas = function(action, params) { - if (!this.list_of_graphcanvas) { - return; - } - - for (var i = 0; i < this.list_of_graphcanvas.length; ++i) { - var c = this.list_of_graphcanvas[i]; - if (c[action]) { - c[action].apply(c, params); - } - } - }; - - /** - * Adds a new node instance to this graph - * @method add - * @param {LGraphNode} node the instance of the node - */ - - LGraph.prototype.add = function(node, skip_compute_order) { - if (!node) { - return; - } - - //groups - if (node.constructor === LGraphGroup) { - this._groups.push(node); - this.setDirtyCanvas(true); - this.change(); - node.graph = this; - this._version++; - return; - } - - //nodes - if (node.id != -1 && this._nodes_by_id[node.id] != null) { - console.warn( - "LiteGraph: there is already a node with this ID, changing it" - ); - if (LiteGraph.use_uuids) { - node.id = LiteGraph.uuidv4(); - } - else { - node.id = ++this.last_node_id; - } - } - - if (this._nodes.length >= LiteGraph.MAX_NUMBER_OF_NODES) { - throw "LiteGraph: max number of nodes in a graph reached"; - } - - //give him an id - if (LiteGraph.use_uuids) { - if (node.id == null || node.id == -1) - node.id = LiteGraph.uuidv4(); - } - else { - if (node.id == null || node.id == -1) { - node.id = ++this.last_node_id; - } else if (this.last_node_id < node.id) { - this.last_node_id = node.id; - } - } - - node.graph = this; - this._version++; - - this._nodes.push(node); - this._nodes_by_id[node.id] = node; - - if (node.onAdded) { - node.onAdded(this); - } - - if (this.config.align_to_grid) { - node.alignToGrid(); - } - - if (!skip_compute_order) { - this.updateExecutionOrder(); - } - - if (this.onNodeAdded) { - this.onNodeAdded(node); - } - - this.setDirtyCanvas(true); - this.change(); - - return node; //to chain actions - }; - - /** - * Removes a node from the graph - * @method remove - * @param {LGraphNode} node the instance of the node - */ - - LGraph.prototype.remove = function(node) { - if (node.constructor === LiteGraph.LGraphGroup) { - var index = this._groups.indexOf(node); - if (index != -1) { - this._groups.splice(index, 1); - } - node.graph = null; - this._version++; - this.setDirtyCanvas(true, true); - this.change(); - return; - } - - if (this._nodes_by_id[node.id] == null) { - return; - } //not found - - if (node.ignore_remove) { - return; - } //cannot be removed - - this.beforeChange(); //sure? - almost sure is wrong - - //disconnect inputs - if (node.inputs) { - for (var i = 0; i < node.inputs.length; i++) { - var slot = node.inputs[i]; - if (slot.link != null) { - node.disconnectInput(i); - } - } - } - - //disconnect outputs - if (node.outputs) { - for (var i = 0; i < node.outputs.length; i++) { - var slot = node.outputs[i]; - if (slot.links != null && slot.links.length) { - node.disconnectOutput(i); - } - } - } - - //node.id = -1; //why? - - //callback - if (node.onRemoved) { - node.onRemoved(); - } - - node.graph = null; - this._version++; - - //remove from canvas render - if (this.list_of_graphcanvas) { - for (var i = 0; i < this.list_of_graphcanvas.length; ++i) { - var canvas = this.list_of_graphcanvas[i]; - if (canvas.selected_nodes[node.id]) { - delete canvas.selected_nodes[node.id]; - } - if (canvas.node_dragged == node) { - canvas.node_dragged = null; - } - } - } - - //remove from containers - var pos = this._nodes.indexOf(node); - if (pos != -1) { - this._nodes.splice(pos, 1); - } - delete this._nodes_by_id[node.id]; - - if (this.onNodeRemoved) { - this.onNodeRemoved(node); - } - - //close panels - this.sendActionToCanvas("checkPanels"); - - this.setDirtyCanvas(true, true); - this.afterChange(); //sure? - almost sure is wrong - this.change(); - - this.updateExecutionOrder(); - }; - - /** - * Returns a node by its id. - * @method getNodeById - * @param {Number} id - */ - - LGraph.prototype.getNodeById = function(id) { - if (id == null) { - return null; - } - return this._nodes_by_id[id]; - }; - - /** - * Returns a list of nodes that matches a class - * @method findNodesByClass - * @param {Class} classObject the class itself (not an string) - * @return {Array} a list with all the nodes of this type - */ - LGraph.prototype.findNodesByClass = function(classObject, result) { - result = result || []; - result.length = 0; - for (var i = 0, l = this._nodes.length; i < l; ++i) { - if (this._nodes[i].constructor === classObject) { - result.push(this._nodes[i]); - } - } - return result; - }; - - /** - * Returns a list of nodes that matches a type - * @method findNodesByType - * @param {String} type the name of the node type - * @return {Array} a list with all the nodes of this type - */ - LGraph.prototype.findNodesByType = function(type, result) { - var type = type.toLowerCase(); - result = result || []; - result.length = 0; - for (var i = 0, l = this._nodes.length; i < l; ++i) { - if (this._nodes[i].type.toLowerCase() == type) { - result.push(this._nodes[i]); - } - } - return result; - }; - - /** - * Returns the first node that matches a name in its title - * @method findNodeByTitle - * @param {String} name the name of the node to search - * @return {Node} the node or null - */ - LGraph.prototype.findNodeByTitle = function(title) { - for (var i = 0, l = this._nodes.length; i < l; ++i) { - if (this._nodes[i].title == title) { - return this._nodes[i]; - } - } - return null; - }; - - /** - * Returns a list of nodes that matches a name - * @method findNodesByTitle - * @param {String} name the name of the node to search - * @return {Array} a list with all the nodes with this name - */ - LGraph.prototype.findNodesByTitle = function(title) { - var result = []; - for (var i = 0, l = this._nodes.length; i < l; ++i) { - if (this._nodes[i].title == title) { - result.push(this._nodes[i]); - } - } - return result; - }; - - /** - * Returns the top-most node in this position of the canvas - * @method getNodeOnPos - * @param {number} x the x coordinate in canvas space - * @param {number} y the y coordinate in canvas space - * @param {Array} nodes_list a list with all the nodes to search from, by default is all the nodes in the graph - * @return {LGraphNode} the node at this position or null - */ - LGraph.prototype.getNodeOnPos = function(x, y, nodes_list, margin) { - nodes_list = nodes_list || this._nodes; - var nRet = null; - for (var i = nodes_list.length - 1; i >= 0; i--) { - var n = nodes_list[i]; - var skip_title = n.constructor.title_mode == LiteGraph.NO_TITLE; - if (n.isPointInside(x, y, margin, skip_title)) { - // check for lesser interest nodes (TODO check for overlapping, use the top) - /*if (typeof n == "LGraphGroup"){ - nRet = n; - }else{*/ - return n; - /*}*/ - } - } - return nRet; - }; - - /** - * Returns the top-most group in that position - * @method getGroupOnPos - * @param {number} x the x coordinate in canvas space - * @param {number} y the y coordinate in canvas space - * @return {LGraphGroup} the group or null - */ - LGraph.prototype.getGroupOnPos = function(x, y) { - for (var i = this._groups.length - 1; i >= 0; i--) { - var g = this._groups[i]; - if (g.isPointInside(x, y, 2, true)) { - return g; - } - } - return null; - }; - - /** - * Checks that the node type matches the node type registered, used when replacing a nodetype by a newer version during execution - * this replaces the ones using the old version with the new version - * @method checkNodeTypes - */ - LGraph.prototype.checkNodeTypes = function() { - var changes = false; - for (var i = 0; i < this._nodes.length; i++) { - var node = this._nodes[i]; - var ctor = LiteGraph.registered_node_types[node.type]; - if (node.constructor == ctor) { - continue; - } - console.log("node being replaced by newer version: " + node.type); - var newnode = LiteGraph.createNode(node.type); - changes = true; - this._nodes[i] = newnode; - newnode.configure(node.serialize()); - newnode.graph = this; - this._nodes_by_id[newnode.id] = newnode; - if (node.inputs) { - newnode.inputs = node.inputs.concat(); - } - if (node.outputs) { - newnode.outputs = node.outputs.concat(); - } - } - this.updateExecutionOrder(); - }; - - // ********** GLOBALS ***************** - - LGraph.prototype.onAction = function(action, param, options) { - this._input_nodes = this.findNodesByClass( - LiteGraph.GraphInput, - this._input_nodes - ); - for (var i = 0; i < this._input_nodes.length; ++i) { - var node = this._input_nodes[i]; - if (node.properties.name != action) { - continue; - } - //wrap node.onAction(action, param); - node.actionDo(action, param, options); - break; - } - }; - - LGraph.prototype.trigger = function(action, param) { - if (this.onTrigger) { - this.onTrigger(action, param); - } - }; - - /** - * Tell this graph it has a global graph input of this type - * @method addGlobalInput - * @param {String} name - * @param {String} type - * @param {*} value [optional] - */ - LGraph.prototype.addInput = function(name, type, value) { - var input = this.inputs[name]; - if (input) { - //already exist - return; - } - - this.beforeChange(); - this.inputs[name] = { name: name, type: type, value: value }; - this._version++; - this.afterChange(); - - if (this.onInputAdded) { - this.onInputAdded(name, type); - } - - if (this.onInputsOutputsChange) { - this.onInputsOutputsChange(); - } - }; - - /** - * Assign a data to the global graph input - * @method setGlobalInputData - * @param {String} name - * @param {*} data - */ - LGraph.prototype.setInputData = function(name, data) { - var input = this.inputs[name]; - if (!input) { - return; - } - input.value = data; - }; - - /** - * Returns the current value of a global graph input - * @method getInputData - * @param {String} name - * @return {*} the data - */ - LGraph.prototype.getInputData = function(name) { - var input = this.inputs[name]; - if (!input) { - return null; - } - return input.value; - }; - - /** - * Changes the name of a global graph input - * @method renameInput - * @param {String} old_name - * @param {String} new_name - */ - LGraph.prototype.renameInput = function(old_name, name) { - if (name == old_name) { - return; - } - - if (!this.inputs[old_name]) { - return false; - } - - if (this.inputs[name]) { - console.error("there is already one input with that name"); - return false; - } - - this.inputs[name] = this.inputs[old_name]; - delete this.inputs[old_name]; - this._version++; - - if (this.onInputRenamed) { - this.onInputRenamed(old_name, name); - } - - if (this.onInputsOutputsChange) { - this.onInputsOutputsChange(); - } - }; - - /** - * Changes the type of a global graph input - * @method changeInputType - * @param {String} name - * @param {String} type - */ - LGraph.prototype.changeInputType = function(name, type) { - if (!this.inputs[name]) { - return false; - } - - if ( - this.inputs[name].type && - String(this.inputs[name].type).toLowerCase() == - String(type).toLowerCase() - ) { - return; - } - - this.inputs[name].type = type; - this._version++; - if (this.onInputTypeChanged) { - this.onInputTypeChanged(name, type); - } - }; - - /** - * Removes a global graph input - * @method removeInput - * @param {String} name - * @param {String} type - */ - LGraph.prototype.removeInput = function(name) { - if (!this.inputs[name]) { - return false; - } - - delete this.inputs[name]; - this._version++; - - if (this.onInputRemoved) { - this.onInputRemoved(name); - } - - if (this.onInputsOutputsChange) { - this.onInputsOutputsChange(); - } - return true; - }; - - /** - * Creates a global graph output - * @method addOutput - * @param {String} name - * @param {String} type - * @param {*} value - */ - LGraph.prototype.addOutput = function(name, type, value) { - this.outputs[name] = { name: name, type: type, value: value }; - this._version++; - - if (this.onOutputAdded) { - this.onOutputAdded(name, type); - } - - if (this.onInputsOutputsChange) { - this.onInputsOutputsChange(); - } - }; - - /** - * Assign a data to the global output - * @method setOutputData - * @param {String} name - * @param {String} value - */ - LGraph.prototype.setOutputData = function(name, value) { - var output = this.outputs[name]; - if (!output) { - return; - } - output.value = value; - }; - - /** - * Returns the current value of a global graph output - * @method getOutputData - * @param {String} name - * @return {*} the data - */ - LGraph.prototype.getOutputData = function(name) { - var output = this.outputs[name]; - if (!output) { - return null; - } - return output.value; - }; - - /** - * Renames a global graph output - * @method renameOutput - * @param {String} old_name - * @param {String} new_name - */ - LGraph.prototype.renameOutput = function(old_name, name) { - if (!this.outputs[old_name]) { - return false; - } - - if (this.outputs[name]) { - console.error("there is already one output with that name"); - return false; - } - - this.outputs[name] = this.outputs[old_name]; - delete this.outputs[old_name]; - this._version++; - - if (this.onOutputRenamed) { - this.onOutputRenamed(old_name, name); - } - - if (this.onInputsOutputsChange) { - this.onInputsOutputsChange(); - } - }; - - /** - * Changes the type of a global graph output - * @method changeOutputType - * @param {String} name - * @param {String} type - */ - LGraph.prototype.changeOutputType = function(name, type) { - if (!this.outputs[name]) { - return false; - } - - if ( - this.outputs[name].type && - String(this.outputs[name].type).toLowerCase() == - String(type).toLowerCase() - ) { - return; - } - - this.outputs[name].type = type; - this._version++; - if (this.onOutputTypeChanged) { - this.onOutputTypeChanged(name, type); - } - }; - - /** - * Removes a global graph output - * @method removeOutput - * @param {String} name - */ - LGraph.prototype.removeOutput = function(name) { - if (!this.outputs[name]) { - return false; - } - delete this.outputs[name]; - this._version++; - - if (this.onOutputRemoved) { - this.onOutputRemoved(name); - } - - if (this.onInputsOutputsChange) { - this.onInputsOutputsChange(); - } - return true; - }; - - LGraph.prototype.triggerInput = function(name, value) { - var nodes = this.findNodesByTitle(name); - for (var i = 0; i < nodes.length; ++i) { - nodes[i].onTrigger(value); - } - }; - - LGraph.prototype.setCallback = function(name, func) { - var nodes = this.findNodesByTitle(name); - for (var i = 0; i < nodes.length; ++i) { - nodes[i].setTrigger(func); - } - }; - - //used for undo, called before any change is made to the graph - LGraph.prototype.beforeChange = function(info) { - if (this.onBeforeChange) { - this.onBeforeChange(this,info); - } - this.sendActionToCanvas("onBeforeChange", this); - }; - - //used to resend actions, called after any change is made to the graph - LGraph.prototype.afterChange = function(info) { - if (this.onAfterChange) { - this.onAfterChange(this,info); - } - this.sendActionToCanvas("onAfterChange", this); - }; - - LGraph.prototype.connectionChange = function(node, link_info) { - this.updateExecutionOrder(); - if (this.onConnectionChange) { - this.onConnectionChange(node); - } - this._version++; - this.sendActionToCanvas("onConnectionChange"); - }; - - /** - * returns if the graph is in live mode - * @method isLive - */ - - LGraph.prototype.isLive = function() { - if (!this.list_of_graphcanvas) { - return false; - } - - for (var i = 0; i < this.list_of_graphcanvas.length; ++i) { - var c = this.list_of_graphcanvas[i]; - if (c.live_mode) { - return true; - } - } - return false; - }; - - /** - * clears the triggered slot animation in all links (stop visual animation) - * @method clearTriggeredSlots - */ - LGraph.prototype.clearTriggeredSlots = function() { - for (var i in this.links) { - var link_info = this.links[i]; - if (!link_info) { - continue; - } - if (link_info._last_time) { - link_info._last_time = 0; - } - } - }; - - /* Called when something visually changed (not the graph!) */ - LGraph.prototype.change = function() { - if (LiteGraph.debug) { - console.log("Graph changed"); - } - this.sendActionToCanvas("setDirty", [true, true]); - if (this.on_change) { - this.on_change(this); - } - }; - - LGraph.prototype.setDirtyCanvas = function(fg, bg) { - this.sendActionToCanvas("setDirty", [fg, bg]); - }; - - /** - * Destroys a link - * @method removeLink - * @param {Number} link_id - */ - LGraph.prototype.removeLink = function(link_id) { - var link = this.links[link_id]; - if (!link) { - return; - } - var node = this.getNodeById(link.target_id); - if (node) { - node.disconnectInput(link.target_slot); - } - }; - - //save and recover app state *************************************** - /** - * Creates a Object containing all the info about this graph, it can be serialized - * @method serialize - * @return {Object} value of the node - */ - LGraph.prototype.serialize = function() { - var nodes_info = []; - for (var i = 0, l = this._nodes.length; i < l; ++i) { - nodes_info.push(this._nodes[i].serialize()); - } - - //pack link info into a non-verbose format - var links = []; - for (var i in this.links) { - //links is an OBJECT - var link = this.links[i]; - if (!link.serialize) { - //weird bug I havent solved yet - console.warn( - "weird LLink bug, link info is not a LLink but a regular object" - ); - var link2 = new LLink(); - for (var j in link) { - link2[j] = link[j]; - } - this.links[i] = link2; - link = link2; - } - - links.push(link.serialize()); - } - - var groups_info = []; - for (var i = 0; i < this._groups.length; ++i) { - groups_info.push(this._groups[i].serialize()); - } - - var data = { - last_node_id: this.last_node_id, - last_link_id: this.last_link_id, - nodes: nodes_info, - links: links, - groups: groups_info, - config: this.config, - extra: this.extra, - version: LiteGraph.VERSION - }; - - if(this.onSerialize) - this.onSerialize(data); - - return data; - }; - - /** - * Configure a graph from a JSON string - * @method configure - * @param {String} str configure a graph from a JSON string - * @param {Boolean} returns if there was any error parsing - */ - LGraph.prototype.configure = function(data, keep_old) { - if (!data) { - return; - } - - if (!keep_old) { - this.clear(); - } - - var nodes = data.nodes; - - //decode links info (they are very verbose) - if (data.links && data.links.constructor === Array) { - var links = []; - for (var i = 0; i < data.links.length; ++i) { - var link_data = data.links[i]; - if(!link_data) //weird bug - { - console.warn("serialized graph link data contains errors, skipping."); - continue; - } - var link = new LLink(); - link.configure(link_data); - links[link.id] = link; - } - data.links = links; - } - - //copy all stored fields - for (var i in data) { - if(i == "nodes" || i == "groups" ) //links must be accepted - continue; - this[i] = data[i]; - } - - var error = false; - - //create nodes - this._nodes = []; - if (nodes) { - for (var i = 0, l = nodes.length; i < l; ++i) { - var n_info = nodes[i]; //stored info - var node = LiteGraph.createNode(n_info.type, n_info.title); - if (!node) { - if (LiteGraph.debug) { - console.log( - "Node not found or has errors: " + n_info.type - ); - } - - //in case of error we create a replacement node to avoid losing info - node = new LGraphNode(); - node.last_serialization = n_info; - node.has_errors = true; - error = true; - //continue; - } - - node.id = n_info.id; //id it or it will create a new id - this.add(node, true); //add before configure, otherwise configure cannot create links - } - - //configure nodes afterwards so they can reach each other - for (var i = 0, l = nodes.length; i < l; ++i) { - var n_info = nodes[i]; - var node = this.getNodeById(n_info.id); - if (node) { - node.configure(n_info); - } - } - } - - //groups - this._groups.length = 0; - if (data.groups) { - for (var i = 0; i < data.groups.length; ++i) { - var group = new LiteGraph.LGraphGroup(); - group.configure(data.groups[i]); - this.add(group); - } - } - - this.updateExecutionOrder(); - - this.extra = data.extra || {}; - - if(this.onConfigure) - this.onConfigure(data); - - this._version++; - this.setDirtyCanvas(true, true); - return error; - }; - - LGraph.prototype.load = function(url, callback) { - var that = this; - - //from file - if(url.constructor === File || url.constructor === Blob) - { - var reader = new FileReader(); - reader.addEventListener('load', function(event) { - var data = JSON.parse(event.target.result); - that.configure(data); - if(callback) - callback(); - }); - - reader.readAsText(url); - return; - } - - //is a string, then an URL - var req = new XMLHttpRequest(); - req.open("GET", url, true); - req.send(null); - req.onload = function(oEvent) { - if (req.status !== 200) { - console.error("Error loading graph:", req.status, req.response); - return; - } - var data = JSON.parse( req.response ); - that.configure(data); - if(callback) - callback(); - }; - req.onerror = function(err) { - console.error("Error loading graph:", err); - }; - }; - - LGraph.prototype.onNodeTrace = function(node, msg, color) { - //TODO - }; - - //this is the class in charge of storing link information - function LLink(id, type, origin_id, origin_slot, target_id, target_slot) { - this.id = id; - this.type = type; - this.origin_id = origin_id; - this.origin_slot = origin_slot; - this.target_id = target_id; - this.target_slot = target_slot; - - this._data = null; - this._pos = new Float32Array(2); //center - } - - LLink.prototype.configure = function(o) { - if (o.constructor === Array) { - this.id = o[0]; - this.origin_id = o[1]; - this.origin_slot = o[2]; - this.target_id = o[3]; - this.target_slot = o[4]; - this.type = o[5]; - } else { - this.id = o.id; - this.type = o.type; - this.origin_id = o.origin_id; - this.origin_slot = o.origin_slot; - this.target_id = o.target_id; - this.target_slot = o.target_slot; - } - }; - - LLink.prototype.serialize = function() { - return [ - this.id, - this.origin_id, - this.origin_slot, - this.target_id, - this.target_slot, - this.type - ]; - }; - - LiteGraph.LLink = LLink; - - // ************************************************************* - // Node CLASS ******* - // ************************************************************* - - /* - title: string - pos: [x,y] - size: [x,y] - - input|output: every connection - + { name:string, type:string, pos: [x,y]=Optional, direction: "input"|"output", links: Array }); - - general properties: - + clip_area: if you render outside the node, it will be clipped - + unsafe_execution: not allowed for safe execution - + skip_repeated_outputs: when adding new outputs, it wont show if there is one already connected - + resizable: if set to false it wont be resizable with the mouse - + horizontal: slots are distributed horizontally - + widgets_start_y: widgets start at y distance from the top of the node - - flags object: - + collapsed: if it is collapsed - - supported callbacks: - + onAdded: when added to graph (warning: this is called BEFORE the node is configured when loading) - + onRemoved: when removed from graph - + onStart: when the graph starts playing - + onStop: when the graph stops playing - + onDrawForeground: render the inside widgets inside the node - + onDrawBackground: render the background area inside the node (only in edit mode) - + onMouseDown - + onMouseMove - + onMouseUp - + onMouseEnter - + onMouseLeave - + onExecute: execute the node - + onPropertyChanged: when a property is changed in the panel (return true to skip default behaviour) - + onGetInputs: returns an array of possible inputs - + onGetOutputs: returns an array of possible outputs - + onBounding: in case this node has a bigger bounding than the node itself (the callback receives the bounding as [x,y,w,h]) - + onDblClick: double clicked in the node - + onInputDblClick: input slot double clicked (can be used to automatically create a node connected) - + onOutputDblClick: output slot double clicked (can be used to automatically create a node connected) - + onConfigure: called after the node has been configured - + onSerialize: to add extra info when serializing (the callback receives the object that should be filled with the data) - + onSelected - + onDeselected - + onDropItem : DOM item dropped over the node - + onDropFile : file dropped over the node - + onConnectInput : if returns false the incoming connection will be canceled - + onConnectionsChange : a connection changed (new one or removed) (LiteGraph.INPUT or LiteGraph.OUTPUT, slot, true if connected, link_info, input_info ) - + onAction: action slot triggered - + getExtraMenuOptions: to add option to context menu -*/ - - /** - * Base Class for all the node type classes - * @class LGraphNode - * @param {String} name a name for the node - */ - - function LGraphNode(title) { - this._ctor(title); - } - - global.LGraphNode = LiteGraph.LGraphNode = LGraphNode; - - LGraphNode.prototype._ctor = function(title) { - this.title = title || "Unnamed"; - this.size = [LiteGraph.NODE_WIDTH, 60]; - this.graph = null; - - this._pos = new Float32Array(10, 10); - - Object.defineProperty(this, "pos", { - set: function(v) { - if (!v || v.length < 2) { - return; - } - this._pos[0] = v[0]; - this._pos[1] = v[1]; - }, - get: function() { - return this._pos; - }, - enumerable: true - }); - - if (LiteGraph.use_uuids) { - this.id = LiteGraph.uuidv4(); - } - else { - this.id = -1; //not know till not added - } - this.type = null; - - //inputs available: array of inputs - this.inputs = []; - this.outputs = []; - this.connections = []; - - //local data - this.properties = {}; //for the values - this.properties_info = []; //for the info - - this.flags = {}; - }; - - /** - * configure a node from an object containing the serialized info - * @method configure - */ - LGraphNode.prototype.configure = function(info) { - if (this.graph) { - this.graph._version++; - } - for (var j in info) { - if (j == "properties") { - //i don't want to clone properties, I want to reuse the old container - for (var k in info.properties) { - this.properties[k] = info.properties[k]; - if (this.onPropertyChanged) { - this.onPropertyChanged( k, info.properties[k] ); - } - } - continue; - } - - if (info[j] == null) { - continue; - } else if (typeof info[j] == "object") { - //object - if (this[j] && this[j].configure) { - this[j].configure(info[j]); - } else { - this[j] = LiteGraph.cloneObject(info[j], this[j]); - } - } //value - else { - this[j] = info[j]; - } - } - - if (!info.title) { - this.title = this.constructor.title; - } - - if (this.inputs) { - for (var i = 0; i < this.inputs.length; ++i) { - var input = this.inputs[i]; - var link_info = this.graph ? this.graph.links[input.link] : null; - if (this.onConnectionsChange) - this.onConnectionsChange( LiteGraph.INPUT, i, true, link_info, input ); //link_info has been created now, so its updated - - if( this.onInputAdded ) - this.onInputAdded(input); - - } - } - - if (this.outputs) { - for (var i = 0; i < this.outputs.length; ++i) { - var output = this.outputs[i]; - if (!output.links) { - continue; - } - for (var j = 0; j < output.links.length; ++j) { - var link_info = this.graph ? this.graph.links[output.links[j]] : null; - if (this.onConnectionsChange) - this.onConnectionsChange( LiteGraph.OUTPUT, i, true, link_info, output ); //link_info has been created now, so its updated - } - - if( this.onOutputAdded ) - this.onOutputAdded(output); - } - } - - if( this.widgets ) - { - for (var i = 0; i < this.widgets.length; ++i) - { - var w = this.widgets[i]; - if(!w) - continue; - if(w.options && w.options.property && (this.properties[ w.options.property ] != undefined)) - w.value = JSON.parse( JSON.stringify( this.properties[ w.options.property ] ) ); - } - if (info.widgets_values) { - for (var i = 0; i < info.widgets_values.length; ++i) { - if (this.widgets[i]) { - this.widgets[i].value = info.widgets_values[i]; - } - } - } - } - - if (this.onConfigure) { - this.onConfigure(info); - } - }; - - /** - * serialize the content - * @method serialize - */ - - LGraphNode.prototype.serialize = function() { - //create serialization object - var o = { - id: this.id, - type: this.type, - pos: this.pos, - size: this.size, - flags: LiteGraph.cloneObject(this.flags), - order: this.order, - mode: this.mode - }; - - //special case for when there were errors - if (this.constructor === LGraphNode && this.last_serialization) { - return this.last_serialization; - } - - if (this.inputs) { - o.inputs = this.inputs; - } - - if (this.outputs) { - //clear outputs last data (because data in connections is never serialized but stored inside the outputs info) - for (var i = 0; i < this.outputs.length; i++) { - delete this.outputs[i]._data; - } - o.outputs = this.outputs; - } - - if (this.title && this.title != this.constructor.title) { - o.title = this.title; - } - - if (this.properties) { - o.properties = LiteGraph.cloneObject(this.properties); - } - - if (this.widgets && this.serialize_widgets) { - o.widgets_values = []; - for (var i = 0; i < this.widgets.length; ++i) { - if(this.widgets[i]) - o.widgets_values[i] = this.widgets[i].value; - else - o.widgets_values[i] = null; - } - } - - if (!o.type) { - o.type = this.constructor.type; - } - - if (this.color) { - o.color = this.color; - } - if (this.bgcolor) { - o.bgcolor = this.bgcolor; - } - if (this.boxcolor) { - o.boxcolor = this.boxcolor; - } - if (this.shape) { - o.shape = this.shape; - } - - if (this.onSerialize) { - if (this.onSerialize(o)) { - console.warn( - "node onSerialize shouldnt return anything, data should be stored in the object pass in the first parameter" - ); - } - } - - return o; - }; - - /* Creates a clone of this node */ - LGraphNode.prototype.clone = function() { - var node = LiteGraph.createNode(this.type); - if (!node) { - return null; - } - - //we clone it because serialize returns shared containers - var data = LiteGraph.cloneObject(this.serialize()); - - //remove links - if (data.inputs) { - for (var i = 0; i < data.inputs.length; ++i) { - data.inputs[i].link = null; - } - } - - if (data.outputs) { - for (var i = 0; i < data.outputs.length; ++i) { - if (data.outputs[i].links) { - data.outputs[i].links.length = 0; - } - } - } - - delete data["id"]; - - if (LiteGraph.use_uuids) { - data["id"] = LiteGraph.uuidv4() - } - - //remove links - node.configure(data); - - return node; - }; - - /** - * serialize and stringify - * @method toString - */ - - LGraphNode.prototype.toString = function() { - return JSON.stringify(this.serialize()); - }; - //LGraphNode.prototype.deserialize = function(info) {} //this cannot be done from within, must be done in LiteGraph - - /** - * get the title string - * @method getTitle - */ - - LGraphNode.prototype.getTitle = function() { - return this.title || this.constructor.title; - }; - - /** - * sets the value of a property - * @method setProperty - * @param {String} name - * @param {*} value - */ - LGraphNode.prototype.setProperty = function(name, value) { - if (!this.properties) { - this.properties = {}; - } - if( value === this.properties[name] ) - return; - var prev_value = this.properties[name]; - this.properties[name] = value; - if (this.onPropertyChanged) { - if( this.onPropertyChanged(name, value, prev_value) === false ) //abort change - this.properties[name] = prev_value; - } - if(this.widgets) //widgets could be linked to properties - for(var i = 0; i < this.widgets.length; ++i) - { - var w = this.widgets[i]; - if(!w) - continue; - if(w.options.property == name) - { - w.value = value; - break; - } - } - }; - - // Execution ************************* - /** - * sets the output data - * @method setOutputData - * @param {number} slot - * @param {*} data - */ - LGraphNode.prototype.setOutputData = function(slot, data) { - if (!this.outputs) { - return; - } - - //this maybe slow and a niche case - //if(slot && slot.constructor === String) - // slot = this.findOutputSlot(slot); - - if (slot == -1 || slot >= this.outputs.length) { - return; - } - - var output_info = this.outputs[slot]; - if (!output_info) { - return; - } - - //store data in the output itself in case we want to debug - output_info._data = data; - - //if there are connections, pass the data to the connections - if (this.outputs[slot].links) { - for (var i = 0; i < this.outputs[slot].links.length; i++) { - var link_id = this.outputs[slot].links[i]; - var link = this.graph.links[link_id]; - if(link) - link.data = data; - } - } - }; - - /** - * sets the output data type, useful when you want to be able to overwrite the data type - * @method setOutputDataType - * @param {number} slot - * @param {String} datatype - */ - LGraphNode.prototype.setOutputDataType = function(slot, type) { - if (!this.outputs) { - return; - } - if (slot == -1 || slot >= this.outputs.length) { - return; - } - var output_info = this.outputs[slot]; - if (!output_info) { - return; - } - //store data in the output itself in case we want to debug - output_info.type = type; - - //if there are connections, pass the data to the connections - if (this.outputs[slot].links) { - for (var i = 0; i < this.outputs[slot].links.length; i++) { - var link_id = this.outputs[slot].links[i]; - this.graph.links[link_id].type = type; - } - } - }; - - /** - * Retrieves the input data (data traveling through the connection) from one slot - * @method getInputData - * @param {number} slot - * @param {boolean} force_update if set to true it will force the connected node of this slot to output data into this link - * @return {*} data or if it is not connected returns undefined - */ - LGraphNode.prototype.getInputData = function(slot, force_update) { - if (!this.inputs) { - return; - } //undefined; - - if (slot >= this.inputs.length || this.inputs[slot].link == null) { - return; - } - - var link_id = this.inputs[slot].link; - var link = this.graph.links[link_id]; - if (!link) { - //bug: weird case but it happens sometimes - return null; - } - - if (!force_update) { - return link.data; - } - - //special case: used to extract data from the incoming connection before the graph has been executed - var node = this.graph.getNodeById(link.origin_id); - if (!node) { - return link.data; - } - - if (node.updateOutputData) { - node.updateOutputData(link.origin_slot); - } else if (node.onExecute) { - node.onExecute(); - } - - return link.data; - }; - - /** - * Retrieves the input data type (in case this supports multiple input types) - * @method getInputDataType - * @param {number} slot - * @return {String} datatype in string format - */ - LGraphNode.prototype.getInputDataType = function(slot) { - if (!this.inputs) { - return null; - } //undefined; - - if (slot >= this.inputs.length || this.inputs[slot].link == null) { - return null; - } - var link_id = this.inputs[slot].link; - var link = this.graph.links[link_id]; - if (!link) { - //bug: weird case but it happens sometimes - return null; - } - var node = this.graph.getNodeById(link.origin_id); - if (!node) { - return link.type; - } - var output_info = node.outputs[link.origin_slot]; - if (output_info) { - return output_info.type; - } - return null; - }; - - /** - * Retrieves the input data from one slot using its name instead of slot number - * @method getInputDataByName - * @param {String} slot_name - * @param {boolean} force_update if set to true it will force the connected node of this slot to output data into this link - * @return {*} data or if it is not connected returns null - */ - LGraphNode.prototype.getInputDataByName = function( - slot_name, - force_update - ) { - var slot = this.findInputSlot(slot_name); - if (slot == -1) { - return null; - } - return this.getInputData(slot, force_update); - }; - - /** - * tells you if there is a connection in one input slot - * @method isInputConnected - * @param {number} slot - * @return {boolean} - */ - LGraphNode.prototype.isInputConnected = function(slot) { - if (!this.inputs) { - return false; - } - return slot < this.inputs.length && this.inputs[slot].link != null; - }; - - /** - * tells you info about an input connection (which node, type, etc) - * @method getInputInfo - * @param {number} slot - * @return {Object} object or null { link: id, name: string, type: string or 0 } - */ - LGraphNode.prototype.getInputInfo = function(slot) { - if (!this.inputs) { - return null; - } - if (slot < this.inputs.length) { - return this.inputs[slot]; - } - return null; - }; - - /** - * Returns the link info in the connection of an input slot - * @method getInputLink - * @param {number} slot - * @return {LLink} object or null - */ - LGraphNode.prototype.getInputLink = function(slot) { - if (!this.inputs) { - return null; - } - if (slot < this.inputs.length) { - var slot_info = this.inputs[slot]; - return this.graph.links[ slot_info.link ]; - } - return null; - }; - - /** - * returns the node connected in the input slot - * @method getInputNode - * @param {number} slot - * @return {LGraphNode} node or null - */ - LGraphNode.prototype.getInputNode = function(slot) { - if (!this.inputs) { - return null; - } - if (slot >= this.inputs.length) { - return null; - } - var input = this.inputs[slot]; - if (!input || input.link === null) { - return null; - } - var link_info = this.graph.links[input.link]; - if (!link_info) { - return null; - } - return this.graph.getNodeById(link_info.origin_id); - }; - - /** - * returns the value of an input with this name, otherwise checks if there is a property with that name - * @method getInputOrProperty - * @param {string} name - * @return {*} value - */ - LGraphNode.prototype.getInputOrProperty = function(name) { - if (!this.inputs || !this.inputs.length) { - return this.properties ? this.properties[name] : null; - } - - for (var i = 0, l = this.inputs.length; i < l; ++i) { - var input_info = this.inputs[i]; - if (name == input_info.name && input_info.link != null) { - var link = this.graph.links[input_info.link]; - if (link) { - return link.data; - } - } - } - return this.properties[name]; - }; - - /** - * tells you the last output data that went in that slot - * @method getOutputData - * @param {number} slot - * @return {Object} object or null - */ - LGraphNode.prototype.getOutputData = function(slot) { - if (!this.outputs) { - return null; - } - if (slot >= this.outputs.length) { - return null; - } - - var info = this.outputs[slot]; - return info._data; - }; - - /** - * tells you info about an output connection (which node, type, etc) - * @method getOutputInfo - * @param {number} slot - * @return {Object} object or null { name: string, type: string, links: [ ids of links in number ] } - */ - LGraphNode.prototype.getOutputInfo = function(slot) { - if (!this.outputs) { - return null; - } - if (slot < this.outputs.length) { - return this.outputs[slot]; - } - return null; - }; - - /** - * tells you if there is a connection in one output slot - * @method isOutputConnected - * @param {number} slot - * @return {boolean} - */ - LGraphNode.prototype.isOutputConnected = function(slot) { - if (!this.outputs) { - return false; - } - return ( - slot < this.outputs.length && - this.outputs[slot].links && - this.outputs[slot].links.length - ); - }; - - /** - * tells you if there is any connection in the output slots - * @method isAnyOutputConnected - * @return {boolean} - */ - LGraphNode.prototype.isAnyOutputConnected = function() { - if (!this.outputs) { - return false; - } - for (var i = 0; i < this.outputs.length; ++i) { - if (this.outputs[i].links && this.outputs[i].links.length) { - return true; - } - } - return false; - }; - - /** - * retrieves all the nodes connected to this output slot - * @method getOutputNodes - * @param {number} slot - * @return {array} - */ - LGraphNode.prototype.getOutputNodes = function(slot) { - if (!this.outputs || this.outputs.length == 0) { - return null; - } - - if (slot >= this.outputs.length) { - return null; - } - - var output = this.outputs[slot]; - if (!output.links || output.links.length == 0) { - return null; - } - - var r = []; - for (var i = 0; i < output.links.length; i++) { - var link_id = output.links[i]; - var link = this.graph.links[link_id]; - if (link) { - var target_node = this.graph.getNodeById(link.target_id); - if (target_node) { - r.push(target_node); - } - } - } - return r; - }; - - LGraphNode.prototype.addOnTriggerInput = function(){ - var trigS = this.findInputSlot("onTrigger"); - if (trigS == -1){ //!trigS || - var input = this.addInput("onTrigger", LiteGraph.EVENT, {optional: true, nameLocked: true}); - return this.findInputSlot("onTrigger"); - } - return trigS; - } - - LGraphNode.prototype.addOnExecutedOutput = function(){ - var trigS = this.findOutputSlot("onExecuted"); - if (trigS == -1){ //!trigS || - var output = this.addOutput("onExecuted", LiteGraph.ACTION, {optional: true, nameLocked: true}); - return this.findOutputSlot("onExecuted"); - } - return trigS; - } - - LGraphNode.prototype.onAfterExecuteNode = function(param, options){ - var trigS = this.findOutputSlot("onExecuted"); - if (trigS != -1){ - - //console.debug(this.id+":"+this.order+" triggering slot onAfterExecute"); - //console.debug(param); - //console.debug(options); - this.triggerSlot(trigS, param, null, options); - - } - } - - LGraphNode.prototype.changeMode = function(modeTo){ - switch(modeTo){ - case LiteGraph.ON_EVENT: - // this.addOnExecutedOutput(); - break; - - case LiteGraph.ON_TRIGGER: - this.addOnTriggerInput(); - this.addOnExecutedOutput(); - break; - - case LiteGraph.NEVER: - break; - - case LiteGraph.ALWAYS: - break; - - case LiteGraph.ON_REQUEST: - break; - - default: - return false; - break; - } - this.mode = modeTo; - return true; - }; - - /** - * Triggers the node code execution, place a boolean/counter to mark the node as being executed - * @method execute - * @param {*} param - * @param {*} options - */ - LGraphNode.prototype.doExecute = function(param, options) { - options = options || {}; - if (this.onExecute){ - - // enable this to give the event an ID - if (!options.action_call) options.action_call = this.id+"_exec_"+Math.floor(Math.random()*9999); - - this.graph.nodes_executing[this.id] = true; //.push(this.id); - - this.onExecute(param, options); - - this.graph.nodes_executing[this.id] = false; //.pop(); - - // save execution/action ref - this.exec_version = this.graph.iteration; - if(options && options.action_call){ - this.action_call = options.action_call; // if (param) - this.graph.nodes_executedAction[this.id] = options.action_call; - } - } - this.execute_triggered = 2; // the nFrames it will be used (-- each step), means "how old" is the event - if(this.onAfterExecuteNode) this.onAfterExecuteNode(param, options); // callback - }; - - /** - * Triggers an action, wrapped by logics to control execution flow - * @method actionDo - * @param {String} action name - * @param {*} param - */ - LGraphNode.prototype.actionDo = function(action, param, options) { - options = options || {}; - if (this.onAction){ - - // enable this to give the event an ID - if (!options.action_call) options.action_call = this.id+"_"+(action?action:"action")+"_"+Math.floor(Math.random()*9999); - - this.graph.nodes_actioning[this.id] = (action?action:"actioning"); //.push(this.id); - - this.onAction(action, param, options); - - this.graph.nodes_actioning[this.id] = false; //.pop(); - - // save execution/action ref - if(options && options.action_call){ - this.action_call = options.action_call; // if (param) - this.graph.nodes_executedAction[this.id] = options.action_call; - } - } - this.action_triggered = 2; // the nFrames it will be used (-- each step), means "how old" is the event - if(this.onAfterExecuteNode) this.onAfterExecuteNode(param, options); - }; - - /** - * Triggers an event in this node, this will trigger any output with the same name - * @method trigger - * @param {String} event name ( "on_play", ... ) if action is equivalent to false then the event is send to all - * @param {*} param - */ - LGraphNode.prototype.trigger = function(action, param, options) { - if (!this.outputs || !this.outputs.length) { - return; - } - - if (this.graph) - this.graph._last_trigger_time = LiteGraph.getTime(); - - for (var i = 0; i < this.outputs.length; ++i) { - var output = this.outputs[i]; - if ( !output || output.type !== LiteGraph.EVENT || (action && output.name != action) ) - continue; - this.triggerSlot(i, param, null, options); - } - }; - - /** - * Triggers a slot event in this node: cycle output slots and launch execute/action on connected nodes - * @method triggerSlot - * @param {Number} slot the index of the output slot - * @param {*} param - * @param {Number} link_id [optional] in case you want to trigger and specific output link in a slot - */ - LGraphNode.prototype.triggerSlot = function(slot, param, link_id, options) { - options = options || {}; - if (!this.outputs) { - return; - } - - if(slot == null) - { - console.error("slot must be a number"); - return; - } - - if(slot.constructor !== Number) - console.warn("slot must be a number, use node.trigger('name') if you want to use a string"); - - var output = this.outputs[slot]; - if (!output) { - return; - } - - var links = output.links; - if (!links || !links.length) { - return; - } - - if (this.graph) { - this.graph._last_trigger_time = LiteGraph.getTime(); - } - - //for every link attached here - for (var k = 0; k < links.length; ++k) { - var id = links[k]; - if (link_id != null && link_id != id) { - //to skip links - continue; - } - var link_info = this.graph.links[links[k]]; - if (!link_info) { - //not connected - continue; - } - link_info._last_time = LiteGraph.getTime(); - var node = this.graph.getNodeById(link_info.target_id); - if (!node) { - //node not found? - continue; - } - - //used to mark events in graph - var target_connection = node.inputs[link_info.target_slot]; - - if (node.mode === LiteGraph.ON_TRIGGER) - { - // generate unique trigger ID if not present - if (!options.action_call) options.action_call = this.id+"_trigg_"+Math.floor(Math.random()*9999); - if (node.onExecute) { - // -- wrapping node.onExecute(param); -- - node.doExecute(param, options); - } - } - else if (node.onAction) { - // generate unique action ID if not present - if (!options.action_call) options.action_call = this.id+"_act_"+Math.floor(Math.random()*9999); - //pass the action name - var target_connection = node.inputs[link_info.target_slot]; - // wrap node.onAction(target_connection.name, param); - node.actionDo(target_connection.name, param, options); - } - } - }; - - /** - * clears the trigger slot animation - * @method clearTriggeredSlot - * @param {Number} slot the index of the output slot - * @param {Number} link_id [optional] in case you want to trigger and specific output link in a slot - */ - LGraphNode.prototype.clearTriggeredSlot = function(slot, link_id) { - if (!this.outputs) { - return; - } - - var output = this.outputs[slot]; - if (!output) { - return; - } - - var links = output.links; - if (!links || !links.length) { - return; - } - - //for every link attached here - for (var k = 0; k < links.length; ++k) { - var id = links[k]; - if (link_id != null && link_id != id) { - //to skip links - continue; - } - var link_info = this.graph.links[links[k]]; - if (!link_info) { - //not connected - continue; - } - link_info._last_time = 0; - } - }; - - /** - * changes node size and triggers callback - * @method setSize - * @param {vec2} size - */ - LGraphNode.prototype.setSize = function(size) - { - this.size = size; - if(this.onResize) - this.onResize(this.size); - } - - /** - * add a new property to this node - * @method addProperty - * @param {string} name - * @param {*} default_value - * @param {string} type string defining the output type ("vec3","number",...) - * @param {Object} extra_info this can be used to have special properties of the property (like values, etc) - */ - LGraphNode.prototype.addProperty = function( - name, - default_value, - type, - extra_info - ) { - var o = { name: name, type: type, default_value: default_value }; - if (extra_info) { - for (var i in extra_info) { - o[i] = extra_info[i]; - } - } - if (!this.properties_info) { - this.properties_info = []; - } - this.properties_info.push(o); - if (!this.properties) { - this.properties = {}; - } - this.properties[name] = default_value; - return o; - }; - - //connections - - /** - * add a new output slot to use in this node - * @method addOutput - * @param {string} name - * @param {string} type string defining the output type ("vec3","number",...) - * @param {Object} extra_info this can be used to have special properties of an output (label, special color, position, etc) - */ - LGraphNode.prototype.addOutput = function(name, type, extra_info) { - var output = { name: name, type: type, links: null }; - if (extra_info) { - for (var i in extra_info) { - output[i] = extra_info[i]; - } - } - - if (!this.outputs) { - this.outputs = []; - } - this.outputs.push(output); - if (this.onOutputAdded) { - this.onOutputAdded(output); - } - - if (LiteGraph.auto_load_slot_types) LiteGraph.registerNodeAndSlotType(this,type,true); - - this.setSize( this.computeSize() ); - this.setDirtyCanvas(true, true); - return output; - }; - - /** - * add a new output slot to use in this node - * @method addOutputs - * @param {Array} array of triplets like [[name,type,extra_info],[...]] - */ - LGraphNode.prototype.addOutputs = function(array) { - for (var i = 0; i < array.length; ++i) { - var info = array[i]; - var o = { name: info[0], type: info[1], link: null }; - if (array[2]) { - for (var j in info[2]) { - o[j] = info[2][j]; - } - } - - if (!this.outputs) { - this.outputs = []; - } - this.outputs.push(o); - if (this.onOutputAdded) { - this.onOutputAdded(o); - } - - if (LiteGraph.auto_load_slot_types) LiteGraph.registerNodeAndSlotType(this,info[1],true); - - } - - this.setSize( this.computeSize() ); - this.setDirtyCanvas(true, true); - }; - - /** - * remove an existing output slot - * @method removeOutput - * @param {number} slot - */ - LGraphNode.prototype.removeOutput = function(slot) { - this.disconnectOutput(slot); - this.outputs.splice(slot, 1); - for (var i = slot; i < this.outputs.length; ++i) { - if (!this.outputs[i] || !this.outputs[i].links) { - continue; - } - var links = this.outputs[i].links; - for (var j = 0; j < links.length; ++j) { - var link = this.graph.links[links[j]]; - if (!link) { - continue; - } - link.origin_slot -= 1; - } - } - - this.setSize( this.computeSize() ); - if (this.onOutputRemoved) { - this.onOutputRemoved(slot); - } - this.setDirtyCanvas(true, true); - }; - - /** - * add a new input slot to use in this node - * @method addInput - * @param {string} name - * @param {string} type string defining the input type ("vec3","number",...), it its a generic one use 0 - * @param {Object} extra_info this can be used to have special properties of an input (label, color, position, etc) - */ - LGraphNode.prototype.addInput = function(name, type, extra_info) { - type = type || 0; - var input = { name: name, type: type, link: null }; - if (extra_info) { - for (var i in extra_info) { - input[i] = extra_info[i]; - } - } - - if (!this.inputs) { - this.inputs = []; - } - - this.inputs.push(input); - this.setSize( this.computeSize() ); - - if (this.onInputAdded) { - this.onInputAdded(input); - } - - LiteGraph.registerNodeAndSlotType(this,type); - - this.setDirtyCanvas(true, true); - return input; - }; - - /** - * add several new input slots in this node - * @method addInputs - * @param {Array} array of triplets like [[name,type,extra_info],[...]] - */ - LGraphNode.prototype.addInputs = function(array) { - for (var i = 0; i < array.length; ++i) { - var info = array[i]; - var o = { name: info[0], type: info[1], link: null }; - if (array[2]) { - for (var j in info[2]) { - o[j] = info[2][j]; - } - } - - if (!this.inputs) { - this.inputs = []; - } - this.inputs.push(o); - if (this.onInputAdded) { - this.onInputAdded(o); - } - - LiteGraph.registerNodeAndSlotType(this,info[1]); - } - - this.setSize( this.computeSize() ); - this.setDirtyCanvas(true, true); - }; - - /** - * remove an existing input slot - * @method removeInput - * @param {number} slot - */ - LGraphNode.prototype.removeInput = function(slot) { - this.disconnectInput(slot); - var slot_info = this.inputs.splice(slot, 1); - for (var i = slot; i < this.inputs.length; ++i) { - if (!this.inputs[i]) { - continue; - } - var link = this.graph.links[this.inputs[i].link]; - if (!link) { - continue; - } - link.target_slot -= 1; - } - this.setSize( this.computeSize() ); - if (this.onInputRemoved) { - this.onInputRemoved(slot, slot_info[0] ); - } - this.setDirtyCanvas(true, true); - }; - - /** - * add an special connection to this node (used for special kinds of graphs) - * @method addConnection - * @param {string} name - * @param {string} type string defining the input type ("vec3","number",...) - * @param {[x,y]} pos position of the connection inside the node - * @param {string} direction if is input or output - */ - LGraphNode.prototype.addConnection = function(name, type, pos, direction) { - var o = { - name: name, - type: type, - pos: pos, - direction: direction, - links: null - }; - this.connections.push(o); - return o; - }; - - /** - * computes the minimum size of a node according to its inputs and output slots - * @method computeSize - * @param {vec2} minHeight - * @return {vec2} the total size - */ - LGraphNode.prototype.computeSize = function(out) { - if (this.constructor.size) { - return this.constructor.size.concat(); - } - - var rows = Math.max( - this.inputs ? this.inputs.length : 1, - this.outputs ? this.outputs.length : 1 - ); - var size = out || new Float32Array([0, 0]); - rows = Math.max(rows, 1); - var font_size = LiteGraph.NODE_TEXT_SIZE; //although it should be graphcanvas.inner_text_font size - - var title_width = compute_text_size(this.title); - var input_width = 0; - var output_width = 0; - - if (this.inputs) { - for (var i = 0, l = this.inputs.length; i < l; ++i) { - var input = this.inputs[i]; - var text = input.label || input.name || ""; - var text_width = compute_text_size(text); - if (input_width < text_width) { - input_width = text_width; - } - } - } - - if (this.outputs) { - for (var i = 0, l = this.outputs.length; i < l; ++i) { - var output = this.outputs[i]; - var text = output.label || output.name || ""; - var text_width = compute_text_size(text); - if (output_width < text_width) { - output_width = text_width; - } - } - } - - size[0] = Math.max(input_width + output_width + 10, title_width); - size[0] = Math.max(size[0], LiteGraph.NODE_WIDTH); - if (this.widgets && this.widgets.length) { - size[0] = Math.max(size[0], LiteGraph.NODE_WIDTH * 1.5); - } - - size[1] = (this.constructor.slot_start_y || 0) + rows * LiteGraph.NODE_SLOT_HEIGHT; - - var widgets_height = 0; - if (this.widgets && this.widgets.length) { - for (var i = 0, l = this.widgets.length; i < l; ++i) { - if (this.widgets[i].computeSize) - widgets_height += this.widgets[i].computeSize(size[0])[1] + 4; - else - widgets_height += LiteGraph.NODE_WIDGET_HEIGHT + 4; - } - widgets_height += 8; - } - - //compute height using widgets height - if( this.widgets_up ) - size[1] = Math.max( size[1], widgets_height ); - else if( this.widgets_start_y != null ) - size[1] = Math.max( size[1], widgets_height + this.widgets_start_y ); - else - size[1] += widgets_height; - - function compute_text_size(text) { - if (!text) { - return 0; - } - return font_size * text.length * 0.6; - } - - if ( - this.constructor.min_height && - size[1] < this.constructor.min_height - ) { - size[1] = this.constructor.min_height; - } - - size[1] += 6; //margin - - return size; - }; - - LGraphNode.prototype.inResizeCorner = function(canvasX, canvasY) { - var rows = this.outputs ? this.outputs.length : 1; - var outputs_offset = (this.constructor.slot_start_y || 0) + rows * LiteGraph.NODE_SLOT_HEIGHT; - return isInsideRectangle(canvasX, - canvasY, - this.pos[0] + this.size[0] - 15, - this.pos[1] + Math.max(this.size[1] - 15, outputs_offset), - 20, - 20 - ); - } - - /** - * returns all the info available about a property of this node. - * - * @method getPropertyInfo - * @param {String} property name of the property - * @return {Object} the object with all the available info - */ - LGraphNode.prototype.getPropertyInfo = function( property ) - { - var info = null; - - //there are several ways to define info about a property - //legacy mode - if (this.properties_info) { - for (var i = 0; i < this.properties_info.length; ++i) { - if (this.properties_info[i].name == property) { - info = this.properties_info[i]; - break; - } - } - } - //litescene mode using the constructor - if(this.constructor["@" + property]) - info = this.constructor["@" + property]; - - if(this.constructor.widgets_info && this.constructor.widgets_info[property]) - info = this.constructor.widgets_info[property]; - - //litescene mode using the constructor - if (!info && this.onGetPropertyInfo) { - info = this.onGetPropertyInfo(property); - } - - if (!info) - info = {}; - if(!info.type) - info.type = typeof this.properties[property]; - if(info.widget == "combo") - info.type = "enum"; - - return info; - } - - /** - * Defines a widget inside the node, it will be rendered on top of the node, you can control lots of properties - * - * @method addWidget - * @param {String} type the widget type (could be "number","string","combo" - * @param {String} name the text to show on the widget - * @param {String} value the default value - * @param {Function|String} callback function to call when it changes (optionally, it can be the name of the property to modify) - * @param {Object} options the object that contains special properties of this widget - * @return {Object} the created widget object - */ - LGraphNode.prototype.addWidget = function( type, name, value, callback, options ) - { - if (!this.widgets) { - this.widgets = []; - } - - if(!options && callback && callback.constructor === Object) - { - options = callback; - callback = null; - } - - if(options && options.constructor === String) //options can be the property name - options = { property: options }; - - if(callback && callback.constructor === String) //callback can be the property name - { - if(!options) - options = {}; - options.property = callback; - callback = null; - } - - if(callback && callback.constructor !== Function) - { - console.warn("addWidget: callback must be a function"); - callback = null; - } - - var w = { - type: type.toLowerCase(), - name: name, - value: value, - callback: callback, - options: options || {} - }; - - if (w.options.y !== undefined) { - w.y = w.options.y; - } - - if (!callback && !w.options.callback && !w.options.property) { - console.warn("LiteGraph addWidget(...) without a callback or property assigned"); - } - if (type == "combo" && !w.options.values) { - throw "LiteGraph addWidget('combo',...) requires to pass values in options: { values:['red','blue'] }"; - } - this.widgets.push(w); - this.setSize( this.computeSize() ); - return w; - }; - - LGraphNode.prototype.addCustomWidget = function(custom_widget) { - if (!this.widgets) { - this.widgets = []; - } - this.widgets.push(custom_widget); - return custom_widget; - }; - - /** - * returns the bounding of the object, used for rendering purposes - * @method getBounding - * @param out {Float32Array[4]?} [optional] a place to store the output, to free garbage - * @param compute_outer {boolean?} [optional] set to true to include the shadow and connection points in the bounding calculation - * @return {Float32Array[4]} the bounding box in format of [topleft_cornerx, topleft_cornery, width, height] - */ - LGraphNode.prototype.getBounding = function(out, compute_outer) { - out = out || new Float32Array(4); - const nodePos = this.pos; - const isCollapsed = this.flags.collapsed; - const nodeSize = this.size; - - let left_offset = 0; - // 1 offset due to how nodes are rendered - let right_offset = 1 ; - let top_offset = 0; - let bottom_offset = 0; - - if (compute_outer) { - // 4 offset for collapsed node connection points - left_offset = 4; - // 6 offset for right shadow and collapsed node connection points - right_offset = 6 + left_offset; - // 4 offset for collapsed nodes top connection points - top_offset = 4; - // 5 offset for bottom shadow and collapsed node connection points - bottom_offset = 5 + top_offset; - } - - out[0] = nodePos[0] - left_offset; - out[1] = nodePos[1] - LiteGraph.NODE_TITLE_HEIGHT - top_offset; - out[2] = isCollapsed ? - (this._collapsed_width || LiteGraph.NODE_COLLAPSED_WIDTH) + right_offset : - nodeSize[0] + right_offset; - out[3] = isCollapsed ? - LiteGraph.NODE_TITLE_HEIGHT + bottom_offset : - nodeSize[1] + LiteGraph.NODE_TITLE_HEIGHT + bottom_offset; - - if (this.onBounding) { - this.onBounding(out); - } - return out; - }; - - /** - * checks if a point is inside the shape of a node - * @method isPointInside - * @param {number} x - * @param {number} y - * @return {boolean} - */ - LGraphNode.prototype.isPointInside = function(x, y, margin, skip_title) { - margin = margin || 0; - - var margin_top = this.graph && this.graph.isLive() ? 0 : LiteGraph.NODE_TITLE_HEIGHT; - if (skip_title) { - margin_top = 0; - } - if (this.flags && this.flags.collapsed) { - //if ( distance([x,y], [this.pos[0] + this.size[0]*0.5, this.pos[1] + this.size[1]*0.5]) < LiteGraph.NODE_COLLAPSED_RADIUS) - if ( - isInsideRectangle( - x, - y, - this.pos[0] - margin, - this.pos[1] - LiteGraph.NODE_TITLE_HEIGHT - margin, - (this._collapsed_width || LiteGraph.NODE_COLLAPSED_WIDTH) + - 2 * margin, - LiteGraph.NODE_TITLE_HEIGHT + 2 * margin - ) - ) { - return true; - } - } else if ( - this.pos[0] - 4 - margin < x && - this.pos[0] + this.size[0] + 4 + margin > x && - this.pos[1] - margin_top - margin < y && - this.pos[1] + this.size[1] + margin > y - ) { - return true; - } - return false; - }; - - /** - * checks if a point is inside a node slot, and returns info about which slot - * @method getSlotInPosition - * @param {number} x - * @param {number} y - * @return {Object} if found the object contains { input|output: slot object, slot: number, link_pos: [x,y] } - */ - LGraphNode.prototype.getSlotInPosition = function(x, y) { - //search for inputs - var link_pos = new Float32Array(2); - if (this.inputs) { - for (var i = 0, l = this.inputs.length; i < l; ++i) { - var input = this.inputs[i]; - this.getConnectionPos(true, i, link_pos); - if ( - isInsideRectangle( - x, - y, - link_pos[0] - 10, - link_pos[1] - 5, - 20, - 10 - ) - ) { - return { input: input, slot: i, link_pos: link_pos }; - } - } - } - - if (this.outputs) { - for (var i = 0, l = this.outputs.length; i < l; ++i) { - var output = this.outputs[i]; - this.getConnectionPos(false, i, link_pos); - if ( - isInsideRectangle( - x, - y, - link_pos[0] - 10, - link_pos[1] - 5, - 20, - 10 - ) - ) { - return { output: output, slot: i, link_pos: link_pos }; - } - } - } - - return null; - }; - - /** - * returns the input slot with a given name (used for dynamic slots), -1 if not found - * @method findInputSlot - * @param {string} name the name of the slot - * @param {boolean} returnObj if the obj itself wanted - * @return {number_or_object} the slot (-1 if not found) - */ - LGraphNode.prototype.findInputSlot = function(name, returnObj) { - if (!this.inputs) { - return -1; - } - for (var i = 0, l = this.inputs.length; i < l; ++i) { - if (name == this.inputs[i].name) { - return !returnObj ? i : this.inputs[i]; - } - } - return -1; - }; - - /** - * returns the output slot with a given name (used for dynamic slots), -1 if not found - * @method findOutputSlot - * @param {string} name the name of the slot - * @param {boolean} returnObj if the obj itself wanted - * @return {number_or_object} the slot (-1 if not found) - */ - LGraphNode.prototype.findOutputSlot = function(name, returnObj) { - returnObj = returnObj || false; - if (!this.outputs) { - return -1; - } - for (var i = 0, l = this.outputs.length; i < l; ++i) { - if (name == this.outputs[i].name) { - return !returnObj ? i : this.outputs[i]; - } - } - return -1; - }; - - // TODO refactor: USE SINGLE findInput/findOutput functions! :: merge options - - /** - * returns the first free input slot - * @method findInputSlotFree - * @param {object} options - * @return {number_or_object} the slot (-1 if not found) - */ - LGraphNode.prototype.findInputSlotFree = function(optsIn) { - var optsIn = optsIn || {}; - var optsDef = {returnObj: false - ,typesNotAccepted: [] - }; - var opts = Object.assign(optsDef,optsIn); - if (!this.inputs) { - return -1; - } - for (var i = 0, l = this.inputs.length; i < l; ++i) { - if (this.inputs[i].link && this.inputs[i].link != null) { - continue; - } - if (opts.typesNotAccepted && opts.typesNotAccepted.includes && opts.typesNotAccepted.includes(this.inputs[i].type)){ - continue; - } - return !opts.returnObj ? i : this.inputs[i]; - } - return -1; - }; - - /** - * returns the first output slot free - * @method findOutputSlotFree - * @param {object} options - * @return {number_or_object} the slot (-1 if not found) - */ - LGraphNode.prototype.findOutputSlotFree = function(optsIn) { - var optsIn = optsIn || {}; - var optsDef = { returnObj: false - ,typesNotAccepted: [] - }; - var opts = Object.assign(optsDef,optsIn); - if (!this.outputs) { - return -1; - } - for (var i = 0, l = this.outputs.length; i < l; ++i) { - if (this.outputs[i].links && this.outputs[i].links != null) { - continue; - } - if (opts.typesNotAccepted && opts.typesNotAccepted.includes && opts.typesNotAccepted.includes(this.outputs[i].type)){ - continue; - } - return !opts.returnObj ? i : this.outputs[i]; - } - return -1; - }; - - /** - * findSlotByType for INPUTS - */ - LGraphNode.prototype.findInputSlotByType = function(type, returnObj, preferFreeSlot, doNotUseOccupied) { - return this.findSlotByType(true, type, returnObj, preferFreeSlot, doNotUseOccupied); - }; - - /** - * findSlotByType for OUTPUTS - */ - LGraphNode.prototype.findOutputSlotByType = function(type, returnObj, preferFreeSlot, doNotUseOccupied) { - return this.findSlotByType(false, type, returnObj, preferFreeSlot, doNotUseOccupied); - }; - - /** - * returns the output (or input) slot with a given type, -1 if not found - * @method findSlotByType - * @param {boolean} input uise inputs instead of outputs - * @param {string} type the type of the slot - * @param {boolean} returnObj if the obj itself wanted - * @param {boolean} preferFreeSlot if we want a free slot (if not found, will return the first of the type anyway) - * @return {number_or_object} the slot (-1 if not found) - */ - LGraphNode.prototype.findSlotByType = function(input, type, returnObj, preferFreeSlot, doNotUseOccupied) { - input = input || false; - returnObj = returnObj || false; - preferFreeSlot = preferFreeSlot || false; - doNotUseOccupied = doNotUseOccupied || false; - var aSlots = input ? this.inputs : this.outputs; - if (!aSlots) { - return -1; - } - // !! empty string type is considered 0, * !! - if (type == "" || type == "*") type = 0; - for (var i = 0, l = aSlots.length; i < l; ++i) { - var tFound = false; - var aSource = (type+"").toLowerCase().split(","); - var aDest = aSlots[i].type=="0"||aSlots[i].type=="*"?"0":aSlots[i].type; - aDest = (aDest+"").toLowerCase().split(","); - for(var sI=0;sI= 0 && target_slot !== null){ - //console.debug("CONNbyTYPE type "+target_slotType+" for "+target_slot) - return this.connect(slot, target_node, target_slot); - }else{ - //console.log("type "+target_slotType+" not found or not free?") - if (opts.createEventInCase && target_slotType == LiteGraph.EVENT){ - // WILL CREATE THE onTrigger IN SLOT - //console.debug("connect WILL CREATE THE onTrigger "+target_slotType+" to "+target_node); - return this.connect(slot, target_node, -1); - } - // connect to the first general output slot if not found a specific type and - if (opts.generalTypeInCase){ - var target_slot = target_node.findInputSlotByType(0, false, true, true); - //console.debug("connect TO a general type (*, 0), if not found the specific type ",target_slotType," to ",target_node,"RES_SLOT:",target_slot); - if (target_slot >= 0){ - return this.connect(slot, target_node, target_slot); - } - } - // connect to the first free input slot if not found a specific type and this output is general - if (opts.firstFreeIfOutputGeneralInCase && (target_slotType == 0 || target_slotType == "*" || target_slotType == "")){ - var target_slot = target_node.findInputSlotFree({typesNotAccepted: [LiteGraph.EVENT] }); - //console.debug("connect TO TheFirstFREE ",target_slotType," to ",target_node,"RES_SLOT:",target_slot); - if (target_slot >= 0){ - return this.connect(slot, target_node, target_slot); - } - } - - console.debug("no way to connect type: ",target_slotType," to targetNODE ",target_node); - //TODO filter - - return null; - } - } - - /** - * connect this node input to the output of another node BY TYPE - * @method connectByType - * @param {number_or_string} slot (could be the number of the slot or the string with the name of the slot) - * @param {LGraphNode} node the target node - * @param {string} target_type the output slot type of the target node - * @return {Object} the link_info is created, otherwise null - */ - LGraphNode.prototype.connectByTypeOutput = function(slot, source_node, source_slotType, optsIn) { - var optsIn = optsIn || {}; - var optsDef = { createEventInCase: true - ,firstFreeIfInputGeneralInCase: true - ,generalTypeInCase: true - }; - var opts = Object.assign(optsDef,optsIn); - if (source_node && source_node.constructor === Number) { - source_node = this.graph.getNodeById(source_node); - } - var source_slot = source_node.findOutputSlotByType(source_slotType, false, true); - if (source_slot >= 0 && source_slot !== null){ - //console.debug("CONNbyTYPE OUT! type "+source_slotType+" for "+source_slot) - return source_node.connect(source_slot, this, slot); - }else{ - - // connect to the first general output slot if not found a specific type and - if (opts.generalTypeInCase){ - var source_slot = source_node.findOutputSlotByType(0, false, true, true); - if (source_slot >= 0){ - return source_node.connect(source_slot, this, slot); - } - } - - if (opts.createEventInCase && source_slotType == LiteGraph.EVENT){ - // WILL CREATE THE onExecuted OUT SLOT - if (LiteGraph.do_add_triggers_slots){ - var source_slot = source_node.addOnExecutedOutput(); - return source_node.connect(source_slot, this, slot); - } - } - // connect to the first free output slot if not found a specific type and this input is general - if (opts.firstFreeIfInputGeneralInCase && (source_slotType == 0 || source_slotType == "*" || source_slotType == "")){ - var source_slot = source_node.findOutputSlotFree({typesNotAccepted: [LiteGraph.EVENT] }); - if (source_slot >= 0){ - return source_node.connect(source_slot, this, slot); - } - } - - console.debug("no way to connect byOUT type: ",source_slotType," to sourceNODE ",source_node); - //TODO filter - - //console.log("type OUT! "+source_slotType+" not found or not free?") - return null; - } - } - - /** - * connect this node output to the input of another node - * @method connect - * @param {number_or_string} slot (could be the number of the slot or the string with the name of the slot) - * @param {LGraphNode} node the target node - * @param {number_or_string} target_slot the input slot of the target node (could be the number of the slot or the string with the name of the slot, or -1 to connect a trigger) - * @return {Object} the link_info is created, otherwise null - */ - LGraphNode.prototype.connect = function(slot, target_node, target_slot) { - target_slot = target_slot || 0; - - if (!this.graph) { - //could be connected before adding it to a graph - console.log( - "Connect: Error, node doesn't belong to any graph. Nodes must be added first to a graph before connecting them." - ); //due to link ids being associated with graphs - return null; - } - - //seek for the output slot - if (slot.constructor === String) { - slot = this.findOutputSlot(slot); - if (slot == -1) { - if (LiteGraph.debug) { - console.log("Connect: Error, no slot of name " + slot); - } - return null; - } - } else if (!this.outputs || slot >= this.outputs.length) { - if (LiteGraph.debug) { - console.log("Connect: Error, slot number not found"); - } - return null; - } - - if (target_node && target_node.constructor === Number) { - target_node = this.graph.getNodeById(target_node); - } - if (!target_node) { - throw "target node is null"; - } - - //avoid loopback - if (target_node == this) { - return null; - } - - //you can specify the slot by name - if (target_slot.constructor === String) { - target_slot = target_node.findInputSlot(target_slot); - if (target_slot == -1) { - if (LiteGraph.debug) { - console.log( - "Connect: Error, no slot of name " + target_slot - ); - } - return null; - } - } else if (target_slot === LiteGraph.EVENT) { - - if (LiteGraph.do_add_triggers_slots){ - //search for first slot with event? :: NO this is done outside - //console.log("Connect: Creating triggerEvent"); - // force mode - target_node.changeMode(LiteGraph.ON_TRIGGER); - target_slot = target_node.findInputSlot("onTrigger"); - }else{ - return null; // -- break -- - } - } else if ( - !target_node.inputs || - target_slot >= target_node.inputs.length - ) { - if (LiteGraph.debug) { - console.log("Connect: Error, slot number not found"); - } - return null; - } - - var changed = false; - - var input = target_node.inputs[target_slot]; - var link_info = null; - var output = this.outputs[slot]; - - if (!this.outputs[slot]){ - /*console.debug("Invalid slot passed: "+slot); - console.debug(this.outputs);*/ - return null; - } - - // allow target node to change slot - if (target_node.onBeforeConnectInput) { - // This way node can choose another slot (or make a new one?) - target_slot = target_node.onBeforeConnectInput(target_slot); //callback - } - - //check target_slot and check connection types - if (target_slot===false || target_slot===null || !LiteGraph.isValidConnection(output.type, input.type)) - { - this.setDirtyCanvas(false, true); - if(changed) - this.graph.connectionChange(this, link_info); - return null; - }else{ - //console.debug("valid connection",output.type, input.type); - } - - //allows nodes to block connection, callback - if (target_node.onConnectInput) { - if ( target_node.onConnectInput(target_slot, output.type, output, this, slot) === false ) { - return null; - } - } - if (this.onConnectOutput) { // callback - if ( this.onConnectOutput(slot, input.type, input, target_node, target_slot) === false ) { - return null; - } - } - - //if there is something already plugged there, disconnect - if (target_node.inputs[target_slot] && target_node.inputs[target_slot].link != null) { - this.graph.beforeChange(); - target_node.disconnectInput(target_slot, {doProcessChange: false}); - changed = true; - } - if (output.links !== null && output.links.length){ - switch(output.type){ - case LiteGraph.EVENT: - if (!LiteGraph.allow_multi_output_for_events){ - this.graph.beforeChange(); - this.disconnectOutput(slot, false, {doProcessChange: false}); // Input(target_slot, {doProcessChange: false}); - changed = true; - } - break; - default: - break; - } - } - - var nextId - if (LiteGraph.use_uuids) - nextId = LiteGraph.uuidv4(); - else - nextId = ++this.graph.last_link_id; - - //create link class - link_info = new LLink( - nextId, - input.type || output.type, - this.id, - slot, - target_node.id, - target_slot - ); - - //add to graph links list - this.graph.links[link_info.id] = link_info; - - //connect in output - if (output.links == null) { - output.links = []; - } - output.links.push(link_info.id); - //connect in input - target_node.inputs[target_slot].link = link_info.id; - if (this.graph) { - this.graph._version++; - } - if (this.onConnectionsChange) { - this.onConnectionsChange( - LiteGraph.OUTPUT, - slot, - true, - link_info, - output - ); - } //link_info has been created now, so its updated - if (target_node.onConnectionsChange) { - target_node.onConnectionsChange( - LiteGraph.INPUT, - target_slot, - true, - link_info, - input - ); - } - if (this.graph && this.graph.onNodeConnectionChange) { - this.graph.onNodeConnectionChange( - LiteGraph.INPUT, - target_node, - target_slot, - this, - slot - ); - this.graph.onNodeConnectionChange( - LiteGraph.OUTPUT, - this, - slot, - target_node, - target_slot - ); - } - - this.setDirtyCanvas(false, true); - this.graph.afterChange(); - this.graph.connectionChange(this, link_info); - - return link_info; - }; - - /** - * disconnect one output to an specific node - * @method disconnectOutput - * @param {number_or_string} slot (could be the number of the slot or the string with the name of the slot) - * @param {LGraphNode} target_node the target node to which this slot is connected [Optional, if not target_node is specified all nodes will be disconnected] - * @return {boolean} if it was disconnected successfully - */ - LGraphNode.prototype.disconnectOutput = function(slot, target_node) { - if (slot.constructor === String) { - slot = this.findOutputSlot(slot); - if (slot == -1) { - if (LiteGraph.debug) { - console.log("Connect: Error, no slot of name " + slot); - } - return false; - } - } else if (!this.outputs || slot >= this.outputs.length) { - if (LiteGraph.debug) { - console.log("Connect: Error, slot number not found"); - } - return false; - } - - //get output slot - var output = this.outputs[slot]; - if (!output || !output.links || output.links.length == 0) { - return false; - } - - //one of the output links in this slot - if (target_node) { - if (target_node.constructor === Number) { - target_node = this.graph.getNodeById(target_node); - } - if (!target_node) { - throw "Target Node not found"; - } - - for (var i = 0, l = output.links.length; i < l; i++) { - var link_id = output.links[i]; - var link_info = this.graph.links[link_id]; - - //is the link we are searching for... - if (link_info.target_id == target_node.id) { - output.links.splice(i, 1); //remove here - var input = target_node.inputs[link_info.target_slot]; - input.link = null; //remove there - delete this.graph.links[link_id]; //remove the link from the links pool - if (this.graph) { - this.graph._version++; - } - if (target_node.onConnectionsChange) { - target_node.onConnectionsChange( - LiteGraph.INPUT, - link_info.target_slot, - false, - link_info, - input - ); - } //link_info hasn't been modified so its ok - if (this.onConnectionsChange) { - this.onConnectionsChange( - LiteGraph.OUTPUT, - slot, - false, - link_info, - output - ); - } - if (this.graph && this.graph.onNodeConnectionChange) { - this.graph.onNodeConnectionChange( - LiteGraph.OUTPUT, - this, - slot - ); - } - if (this.graph && this.graph.onNodeConnectionChange) { - this.graph.onNodeConnectionChange( - LiteGraph.OUTPUT, - this, - slot - ); - this.graph.onNodeConnectionChange( - LiteGraph.INPUT, - target_node, - link_info.target_slot - ); - } - break; - } - } - } //all the links in this output slot - else { - for (var i = 0, l = output.links.length; i < l; i++) { - var link_id = output.links[i]; - var link_info = this.graph.links[link_id]; - if (!link_info) { - //bug: it happens sometimes - continue; - } - - var target_node = this.graph.getNodeById(link_info.target_id); - var input = null; - if (this.graph) { - this.graph._version++; - } - if (target_node) { - input = target_node.inputs[link_info.target_slot]; - input.link = null; //remove other side link - if (target_node.onConnectionsChange) { - target_node.onConnectionsChange( - LiteGraph.INPUT, - link_info.target_slot, - false, - link_info, - input - ); - } //link_info hasn't been modified so its ok - if (this.graph && this.graph.onNodeConnectionChange) { - this.graph.onNodeConnectionChange( - LiteGraph.INPUT, - target_node, - link_info.target_slot - ); - } - } - delete this.graph.links[link_id]; //remove the link from the links pool - if (this.onConnectionsChange) { - this.onConnectionsChange( - LiteGraph.OUTPUT, - slot, - false, - link_info, - output - ); - } - if (this.graph && this.graph.onNodeConnectionChange) { - this.graph.onNodeConnectionChange( - LiteGraph.OUTPUT, - this, - slot - ); - this.graph.onNodeConnectionChange( - LiteGraph.INPUT, - target_node, - link_info.target_slot - ); - } - } - output.links = null; - } - - this.setDirtyCanvas(false, true); - this.graph.connectionChange(this); - return true; - }; - - /** - * disconnect one input - * @method disconnectInput - * @param {number_or_string} slot (could be the number of the slot or the string with the name of the slot) - * @return {boolean} if it was disconnected successfully - */ - LGraphNode.prototype.disconnectInput = function(slot) { - //seek for the output slot - if (slot.constructor === String) { - slot = this.findInputSlot(slot); - if (slot == -1) { - if (LiteGraph.debug) { - console.log("Connect: Error, no slot of name " + slot); - } - return false; - } - } else if (!this.inputs || slot >= this.inputs.length) { - if (LiteGraph.debug) { - console.log("Connect: Error, slot number not found"); - } - return false; - } - - var input = this.inputs[slot]; - if (!input) { - return false; - } - - var link_id = this.inputs[slot].link; - if(link_id != null) - { - this.inputs[slot].link = null; - - //remove other side - var link_info = this.graph.links[link_id]; - if (link_info) { - var target_node = this.graph.getNodeById(link_info.origin_id); - if (!target_node) { - return false; - } - - var output = target_node.outputs[link_info.origin_slot]; - if (!output || !output.links || output.links.length == 0) { - return false; - } - - //search in the inputs list for this link - for (var i = 0, l = output.links.length; i < l; i++) { - if (output.links[i] == link_id) { - output.links.splice(i, 1); - break; - } - } - - delete this.graph.links[link_id]; //remove from the pool - if (this.graph) { - this.graph._version++; - } - if (this.onConnectionsChange) { - this.onConnectionsChange( - LiteGraph.INPUT, - slot, - false, - link_info, - input - ); - } - if (target_node.onConnectionsChange) { - target_node.onConnectionsChange( - LiteGraph.OUTPUT, - i, - false, - link_info, - output - ); - } - if (this.graph && this.graph.onNodeConnectionChange) { - this.graph.onNodeConnectionChange( - LiteGraph.OUTPUT, - target_node, - i - ); - this.graph.onNodeConnectionChange(LiteGraph.INPUT, this, slot); - } - } - } //link != null - - this.setDirtyCanvas(false, true); - if(this.graph) - this.graph.connectionChange(this); - return true; - }; - - /** - * returns the center of a connection point in canvas coords - * @method getConnectionPos - * @param {boolean} is_input true if if a input slot, false if it is an output - * @param {number_or_string} slot (could be the number of the slot or the string with the name of the slot) - * @param {vec2} out [optional] a place to store the output, to free garbage - * @return {[x,y]} the position - **/ - LGraphNode.prototype.getConnectionPos = function( - is_input, - slot_number, - out - ) { - out = out || new Float32Array(2); - var num_slots = 0; - if (is_input && this.inputs) { - num_slots = this.inputs.length; - } - if (!is_input && this.outputs) { - num_slots = this.outputs.length; - } - - var offset = LiteGraph.NODE_SLOT_HEIGHT * 0.5; - - if (this.flags.collapsed) { - var w = this._collapsed_width || LiteGraph.NODE_COLLAPSED_WIDTH; - if (this.horizontal) { - out[0] = this.pos[0] + w * 0.5; - if (is_input) { - out[1] = this.pos[1] - LiteGraph.NODE_TITLE_HEIGHT; - } else { - out[1] = this.pos[1]; - } - } else { - if (is_input) { - out[0] = this.pos[0]; - } else { - out[0] = this.pos[0] + w; - } - out[1] = this.pos[1] - LiteGraph.NODE_TITLE_HEIGHT * 0.5; - } - return out; - } - - //weird feature that never got finished - if (is_input && slot_number == -1) { - out[0] = this.pos[0] + LiteGraph.NODE_TITLE_HEIGHT * 0.5; - out[1] = this.pos[1] + LiteGraph.NODE_TITLE_HEIGHT * 0.5; - return out; - } - - //hard-coded pos - if ( - is_input && - num_slots > slot_number && - this.inputs[slot_number].pos - ) { - out[0] = this.pos[0] + this.inputs[slot_number].pos[0]; - out[1] = this.pos[1] + this.inputs[slot_number].pos[1]; - return out; - } else if ( - !is_input && - num_slots > slot_number && - this.outputs[slot_number].pos - ) { - out[0] = this.pos[0] + this.outputs[slot_number].pos[0]; - out[1] = this.pos[1] + this.outputs[slot_number].pos[1]; - return out; - } - - //horizontal distributed slots - if (this.horizontal) { - out[0] = - this.pos[0] + (slot_number + 0.5) * (this.size[0] / num_slots); - if (is_input) { - out[1] = this.pos[1] - LiteGraph.NODE_TITLE_HEIGHT; - } else { - out[1] = this.pos[1] + this.size[1]; - } - return out; - } - - //default vertical slots - if (is_input) { - out[0] = this.pos[0] + offset; - } else { - out[0] = this.pos[0] + this.size[0] + 1 - offset; - } - out[1] = - this.pos[1] + - (slot_number + 0.7) * LiteGraph.NODE_SLOT_HEIGHT + - (this.constructor.slot_start_y || 0); - return out; - }; - - /* Force align to grid */ - LGraphNode.prototype.alignToGrid = function() { - this.pos[0] = - LiteGraph.CANVAS_GRID_SIZE * - Math.round(this.pos[0] / LiteGraph.CANVAS_GRID_SIZE); - this.pos[1] = - LiteGraph.CANVAS_GRID_SIZE * - Math.round(this.pos[1] / LiteGraph.CANVAS_GRID_SIZE); - }; - - /* Console output */ - LGraphNode.prototype.trace = function(msg) { - if (!this.console) { - this.console = []; - } - - this.console.push(msg); - if (this.console.length > LGraphNode.MAX_CONSOLE) { - this.console.shift(); - } - - if(this.graph.onNodeTrace) - this.graph.onNodeTrace(this, msg); - }; - - /* Forces to redraw or the main canvas (LGraphNode) or the bg canvas (links) */ - LGraphNode.prototype.setDirtyCanvas = function( - dirty_foreground, - dirty_background - ) { - if (!this.graph) { - return; - } - this.graph.sendActionToCanvas("setDirty", [ - dirty_foreground, - dirty_background - ]); - }; - - LGraphNode.prototype.loadImage = function(url) { - var img = new Image(); - img.src = LiteGraph.node_images_path + url; - img.ready = false; - - var that = this; - img.onload = function() { - this.ready = true; - that.setDirtyCanvas(true); - }; - return img; - }; - - //safe LGraphNode action execution (not sure if safe) - /* -LGraphNode.prototype.executeAction = function(action) -{ - if(action == "") return false; - - if( action.indexOf(";") != -1 || action.indexOf("}") != -1) - { - this.trace("Error: Action contains unsafe characters"); - return false; - } - - var tokens = action.split("("); - var func_name = tokens[0]; - if( typeof(this[func_name]) != "function") - { - this.trace("Error: Action not found on node: " + func_name); - return false; - } - - var code = action; - - try - { - var _foo = eval; - eval = null; - (new Function("with(this) { " + code + "}")).call(this); - eval = _foo; - } - catch (err) - { - this.trace("Error executing action {" + action + "} :" + err); - return false; - } - - return true; -} -*/ - - /* Allows to get onMouseMove and onMouseUp events even if the mouse is out of focus */ - LGraphNode.prototype.captureInput = function(v) { - if (!this.graph || !this.graph.list_of_graphcanvas) { - return; - } - - var list = this.graph.list_of_graphcanvas; - - for (var i = 0; i < list.length; ++i) { - var c = list[i]; - //releasing somebody elses capture?! - if (!v && c.node_capturing_input != this) { - continue; - } - - //change - c.node_capturing_input = v ? this : null; - } - }; - - /** - * Collapse the node to make it smaller on the canvas - * @method collapse - **/ - LGraphNode.prototype.collapse = function(force) { - this.graph._version++; - if (this.constructor.collapsable === false && !force) { - return; - } - if (!this.flags.collapsed) { - this.flags.collapsed = true; - } else { - this.flags.collapsed = false; - } - this.setDirtyCanvas(true, true); - }; - - /** - * Forces the node to do not move or realign on Z - * @method pin - **/ - - LGraphNode.prototype.pin = function(v) { - this.graph._version++; - if (v === undefined) { - this.flags.pinned = !this.flags.pinned; - } else { - this.flags.pinned = v; - } - }; - - LGraphNode.prototype.localToScreen = function(x, y, graphcanvas) { - return [ - (x + this.pos[0]) * graphcanvas.scale + graphcanvas.offset[0], - (y + this.pos[1]) * graphcanvas.scale + graphcanvas.offset[1] - ]; - }; - - function LGraphGroup(title) { - this._ctor(title); - } - - global.LGraphGroup = LiteGraph.LGraphGroup = LGraphGroup; - - LGraphGroup.prototype._ctor = function(title) { - this.title = title || "Group"; - this.font_size = 24; - this.color = LGraphCanvas.node_colors.pale_blue - ? LGraphCanvas.node_colors.pale_blue.groupcolor - : "#AAA"; - this._bounding = new Float32Array([10, 10, 140, 80]); - this._pos = this._bounding.subarray(0, 2); - this._size = this._bounding.subarray(2, 4); - this._nodes = []; - this.graph = null; - - Object.defineProperty(this, "pos", { - set: function(v) { - if (!v || v.length < 2) { - return; - } - this._pos[0] = v[0]; - this._pos[1] = v[1]; - }, - get: function() { - return this._pos; - }, - enumerable: true - }); - - Object.defineProperty(this, "size", { - set: function(v) { - if (!v || v.length < 2) { - return; - } - this._size[0] = Math.max(140, v[0]); - this._size[1] = Math.max(80, v[1]); - }, - get: function() { - return this._size; - }, - enumerable: true - }); - }; - - LGraphGroup.prototype.configure = function(o) { - this.title = o.title; - this._bounding.set(o.bounding); - this.color = o.color; - if (o.font_size) { - this.font_size = o.font_size; - } - }; - - LGraphGroup.prototype.serialize = function() { - var b = this._bounding; - return { - title: this.title, - bounding: [ - Math.round(b[0]), - Math.round(b[1]), - Math.round(b[2]), - Math.round(b[3]) - ], - color: this.color, - font_size: this.font_size - }; - }; - - LGraphGroup.prototype.move = function(deltax, deltay, ignore_nodes) { - this._pos[0] += deltax; - this._pos[1] += deltay; - if (ignore_nodes) { - return; - } - for (var i = 0; i < this._nodes.length; ++i) { - var node = this._nodes[i]; - node.pos[0] += deltax; - node.pos[1] += deltay; - } - }; - - LGraphGroup.prototype.recomputeInsideNodes = function() { - this._nodes.length = 0; - var nodes = this.graph._nodes; - var node_bounding = new Float32Array(4); - - for (var i = 0; i < nodes.length; ++i) { - var node = nodes[i]; - node.getBounding(node_bounding); - if (!overlapBounding(this._bounding, node_bounding)) { - continue; - } //out of the visible area - this._nodes.push(node); - } - }; - - LGraphGroup.prototype.isPointInside = LGraphNode.prototype.isPointInside; - LGraphGroup.prototype.setDirtyCanvas = LGraphNode.prototype.setDirtyCanvas; - - //**************************************** - - //Scale and Offset - function DragAndScale(element, skip_events) { - this.offset = new Float32Array([0, 0]); - this.scale = 1; - this.max_scale = 10; - this.min_scale = 0.1; - this.onredraw = null; - this.enabled = true; - this.last_mouse = [0, 0]; - this.element = null; - this.visible_area = new Float32Array(4); - - if (element) { - this.element = element; - if (!skip_events) { - this.bindEvents(element); - } - } - } - - LiteGraph.DragAndScale = DragAndScale; - - DragAndScale.prototype.bindEvents = function(element) { - this.last_mouse = new Float32Array(2); - - this._binded_mouse_callback = this.onMouse.bind(this); - - LiteGraph.pointerListenerAdd(element,"down", this._binded_mouse_callback); - LiteGraph.pointerListenerAdd(element,"move", this._binded_mouse_callback); - LiteGraph.pointerListenerAdd(element,"up", this._binded_mouse_callback); - - element.addEventListener( - "mousewheel", - this._binded_mouse_callback, - false - ); - element.addEventListener("wheel", this._binded_mouse_callback, false); - }; - - DragAndScale.prototype.computeVisibleArea = function( viewport ) { - if (!this.element) { - this.visible_area[0] = this.visible_area[1] = this.visible_area[2] = this.visible_area[3] = 0; - return; - } - var width = this.element.width; - var height = this.element.height; - var startx = -this.offset[0]; - var starty = -this.offset[1]; - if( viewport ) - { - startx += viewport[0] / this.scale; - starty += viewport[1] / this.scale; - width = viewport[2]; - height = viewport[3]; - } - var endx = startx + width / this.scale; - var endy = starty + height / this.scale; - this.visible_area[0] = startx; - this.visible_area[1] = starty; - this.visible_area[2] = endx - startx; - this.visible_area[3] = endy - starty; - }; - - DragAndScale.prototype.onMouse = function(e) { - if (!this.enabled) { - return; - } - - var canvas = this.element; - var rect = canvas.getBoundingClientRect(); - var x = e.clientX - rect.left; - var y = e.clientY - rect.top; - e.canvasx = x; - e.canvasy = y; - e.dragging = this.dragging; - - var is_inside = !this.viewport || ( this.viewport && x >= this.viewport[0] && x < (this.viewport[0] + this.viewport[2]) && y >= this.viewport[1] && y < (this.viewport[1] + this.viewport[3]) ); - - //console.log("pointerevents: DragAndScale onMouse "+e.type+" "+is_inside); - - var ignore = false; - if (this.onmouse) { - ignore = this.onmouse(e); - } - - if (e.type == LiteGraph.pointerevents_method+"down" && is_inside) { - this.dragging = true; - LiteGraph.pointerListenerRemove(canvas,"move",this._binded_mouse_callback); - LiteGraph.pointerListenerAdd(document,"move",this._binded_mouse_callback); - LiteGraph.pointerListenerAdd(document,"up",this._binded_mouse_callback); - } else if (e.type == LiteGraph.pointerevents_method+"move") { - if (!ignore) { - var deltax = x - this.last_mouse[0]; - var deltay = y - this.last_mouse[1]; - if (this.dragging) { - this.mouseDrag(deltax, deltay); - } - } - } else if (e.type == LiteGraph.pointerevents_method+"up") { - this.dragging = false; - LiteGraph.pointerListenerRemove(document,"move",this._binded_mouse_callback); - LiteGraph.pointerListenerRemove(document,"up",this._binded_mouse_callback); - LiteGraph.pointerListenerAdd(canvas,"move",this._binded_mouse_callback); - } else if ( is_inside && - (e.type == "mousewheel" || - e.type == "wheel" || - e.type == "DOMMouseScroll") - ) { - e.eventType = "mousewheel"; - if (e.type == "wheel") { - e.wheel = -e.deltaY; - } else { - e.wheel = - e.wheelDeltaY != null ? e.wheelDeltaY : e.detail * -60; - } - - //from stack overflow - e.delta = e.wheelDelta - ? e.wheelDelta / 40 - : e.deltaY - ? -e.deltaY / 3 - : 0; - this.changeDeltaScale(1.0 + e.delta * 0.05); - } - - this.last_mouse[0] = x; - this.last_mouse[1] = y; - - if(is_inside) - { - e.preventDefault(); - e.stopPropagation(); - return false; - } - }; - - DragAndScale.prototype.toCanvasContext = function(ctx) { - ctx.scale(this.scale, this.scale); - ctx.translate(this.offset[0], this.offset[1]); - }; - - DragAndScale.prototype.convertOffsetToCanvas = function(pos) { - //return [pos[0] / this.scale - this.offset[0], pos[1] / this.scale - this.offset[1]]; - return [ - (pos[0] + this.offset[0]) * this.scale, - (pos[1] + this.offset[1]) * this.scale - ]; - }; - - DragAndScale.prototype.convertCanvasToOffset = function(pos, out) { - out = out || [0, 0]; - out[0] = pos[0] / this.scale - this.offset[0]; - out[1] = pos[1] / this.scale - this.offset[1]; - return out; - }; - - DragAndScale.prototype.mouseDrag = function(x, y) { - this.offset[0] += x / this.scale; - this.offset[1] += y / this.scale; - - if (this.onredraw) { - this.onredraw(this); - } - }; - - DragAndScale.prototype.changeScale = function(value, zooming_center) { - if (value < this.min_scale) { - value = this.min_scale; - } else if (value > this.max_scale) { - value = this.max_scale; - } - - if (value == this.scale) { - return; - } - - if (!this.element) { - return; - } - - var rect = this.element.getBoundingClientRect(); - if (!rect) { - return; - } - - zooming_center = zooming_center || [ - rect.width * 0.5, - rect.height * 0.5 - ]; - var center = this.convertCanvasToOffset(zooming_center); - this.scale = value; - if (Math.abs(this.scale - 1) < 0.01) { - this.scale = 1; - } - - var new_center = this.convertCanvasToOffset(zooming_center); - var delta_offset = [ - new_center[0] - center[0], - new_center[1] - center[1] - ]; - - this.offset[0] += delta_offset[0]; - this.offset[1] += delta_offset[1]; - - if (this.onredraw) { - this.onredraw(this); - } - }; - - DragAndScale.prototype.changeDeltaScale = function(value, zooming_center) { - this.changeScale(this.scale * value, zooming_center); - }; - - DragAndScale.prototype.reset = function() { - this.scale = 1; - this.offset[0] = 0; - this.offset[1] = 0; - }; - - //********************************************************************************* - // LGraphCanvas: LGraph renderer CLASS - //********************************************************************************* - - /** - * This class is in charge of rendering one graph inside a canvas. And provides all the interaction required. - * Valid callbacks are: onNodeSelected, onNodeDeselected, onShowNodePanel, onNodeDblClicked - * - * @class LGraphCanvas - * @constructor - * @param {HTMLCanvas} canvas the canvas where you want to render (it accepts a selector in string format or the canvas element itself) - * @param {LGraph} graph [optional] - * @param {Object} options [optional] { skip_rendering, autoresize, viewport } - */ - function LGraphCanvas(canvas, graph, options) { - this.options = options = options || {}; - - //if(graph === undefined) - // throw ("No graph assigned"); - this.background_image = LGraphCanvas.DEFAULT_BACKGROUND_IMAGE; - - if (canvas && canvas.constructor === String) { - canvas = document.querySelector(canvas); - } - - this.ds = new DragAndScale(); - this.zoom_modify_alpha = true; //otherwise it generates ugly patterns when scaling down too much - - this.title_text_font = "" + LiteGraph.NODE_TEXT_SIZE + "px Arial"; - this.inner_text_font = - "normal " + LiteGraph.NODE_SUBTEXT_SIZE + "px Arial"; - this.node_title_color = LiteGraph.NODE_TITLE_COLOR; - this.default_link_color = LiteGraph.LINK_COLOR; - this.default_connection_color = { - input_off: "#778", - input_on: "#7F7", //"#BBD" - output_off: "#778", - output_on: "#7F7" //"#BBD" - }; - this.default_connection_color_byType = { - /*number: "#7F7", - string: "#77F", - boolean: "#F77",*/ - } - this.default_connection_color_byTypeOff = { - /*number: "#474", - string: "#447", - boolean: "#744",*/ - }; - - this.highquality_render = true; - this.use_gradients = false; //set to true to render titlebar with gradients - this.editor_alpha = 1; //used for transition - this.pause_rendering = false; - this.clear_background = true; - this.clear_background_color = "#222"; - - this.read_only = false; //if set to true users cannot modify the graph - this.render_only_selected = true; - this.live_mode = false; - this.show_info = true; - this.allow_dragcanvas = true; - this.allow_dragnodes = true; - this.allow_interaction = true; //allow to control widgets, buttons, collapse, etc - this.multi_select = false; //allow selecting multi nodes without pressing extra keys - this.allow_searchbox = true; - this.allow_reconnect_links = true; //allows to change a connection with having to redo it again - this.align_to_grid = false; //snap to grid - - this.drag_mode = false; - this.dragging_rectangle = null; - - this.filter = null; //allows to filter to only accept some type of nodes in a graph - - this.set_canvas_dirty_on_mouse_event = true; //forces to redraw the canvas if the mouse does anything - this.always_render_background = false; - this.render_shadows = true; - this.render_canvas_border = true; - this.render_connections_shadows = false; //too much cpu - this.render_connections_border = true; - this.render_curved_connections = false; - this.render_connection_arrows = false; - this.render_collapsed_slots = true; - this.render_execution_order = false; - this.render_title_colored = true; - this.render_link_tooltip = true; - - this.links_render_mode = LiteGraph.SPLINE_LINK; - - this.mouse = [0, 0]; //mouse in canvas coordinates, where 0,0 is the top-left corner of the blue rectangle - this.graph_mouse = [0, 0]; //mouse in graph coordinates, where 0,0 is the top-left corner of the blue rectangle - this.canvas_mouse = this.graph_mouse; //LEGACY: REMOVE THIS, USE GRAPH_MOUSE INSTEAD - - //to personalize the search box - this.onSearchBox = null; - this.onSearchBoxSelection = null; - - //callbacks - this.onMouse = null; - this.onDrawBackground = null; //to render background objects (behind nodes and connections) in the canvas affected by transform - this.onDrawForeground = null; //to render foreground objects (above nodes and connections) in the canvas affected by transform - this.onDrawOverlay = null; //to render foreground objects not affected by transform (for GUIs) - this.onDrawLinkTooltip = null; //called when rendering a tooltip - this.onNodeMoved = null; //called after moving a node - this.onSelectionChange = null; //called if the selection changes - this.onConnectingChange = null; //called before any link changes - this.onBeforeChange = null; //called before modifying the graph - this.onAfterChange = null; //called after modifying the graph - - this.connections_width = 3; - this.round_radius = 8; - - this.current_node = null; - this.node_widget = null; //used for widgets - this.over_link_center = null; - this.last_mouse_position = [0, 0]; - this.visible_area = this.ds.visible_area; - this.visible_links = []; - - this.viewport = options.viewport || null; //to constraint render area to a portion of the canvas - - //link canvas and graph - if (graph) { - graph.attachCanvas(this); - } - - this.setCanvas(canvas,options.skip_events); - this.clear(); - - if (!options.skip_render) { - this.startRendering(); - } - - this.autoresize = options.autoresize; - } - - global.LGraphCanvas = LiteGraph.LGraphCanvas = LGraphCanvas; - - LGraphCanvas.DEFAULT_BACKGROUND_IMAGE = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAQBJREFUeNrs1rEKwjAUhlETUkj3vP9rdmr1Ysammk2w5wdxuLgcMHyptfawuZX4pJSWZTnfnu/lnIe/jNNxHHGNn//HNbbv+4dr6V+11uF527arU7+u63qfa/bnmh8sWLBgwYJlqRf8MEptXPBXJXa37BSl3ixYsGDBMliwFLyCV/DeLIMFCxYsWLBMwSt4Be/NggXLYMGCBUvBK3iNruC9WbBgwYJlsGApeAWv4L1ZBgsWLFiwYJmCV/AK3psFC5bBggULloJX8BpdwXuzYMGCBctgwVLwCl7Be7MMFixYsGDBsu8FH1FaSmExVfAxBa/gvVmwYMGCZbBg/W4vAQYA5tRF9QYlv/QAAAAASUVORK5CYII="; - - LGraphCanvas.link_type_colors = { - "-1": LiteGraph.EVENT_LINK_COLOR, - number: "#AAA", - node: "#DCA" - }; - LGraphCanvas.gradients = {}; //cache of gradients - - /** - * clears all the data inside - * - * @method clear - */ - LGraphCanvas.prototype.clear = function() { - this.frame = 0; - this.last_draw_time = 0; - this.render_time = 0; - this.fps = 0; - - //this.scale = 1; - //this.offset = [0,0]; - - this.dragging_rectangle = null; - - this.selected_nodes = {}; - this.selected_group = null; - - this.visible_nodes = []; - this.node_dragged = null; - this.node_over = null; - this.node_capturing_input = null; - this.connecting_node = null; - this.highlighted_links = {}; - - this.dragging_canvas = false; - - this.dirty_canvas = true; - this.dirty_bgcanvas = true; - this.dirty_area = null; - - this.node_in_panel = null; - this.node_widget = null; - - this.last_mouse = [0, 0]; - this.last_mouseclick = 0; - this.pointer_is_down = false; - this.pointer_is_double = false; - this.visible_area.set([0, 0, 0, 0]); - - if (this.onClear) { - this.onClear(); - } - }; - - /** - * assigns a graph, you can reassign graphs to the same canvas - * - * @method setGraph - * @param {LGraph} graph - */ - LGraphCanvas.prototype.setGraph = function(graph, skip_clear) { - if (this.graph == graph) { - return; - } - - if (!skip_clear) { - this.clear(); - } - - if (!graph && this.graph) { - this.graph.detachCanvas(this); - return; - } - - graph.attachCanvas(this); - - //remove the graph stack in case a subgraph was open - if (this._graph_stack) - this._graph_stack = null; - - this.setDirty(true, true); - }; - - /** - * returns the top level graph (in case there are subgraphs open on the canvas) - * - * @method getTopGraph - * @return {LGraph} graph - */ - LGraphCanvas.prototype.getTopGraph = function() - { - if(this._graph_stack.length) - return this._graph_stack[0]; - return this.graph; - } - - /** - * opens a graph contained inside a node in the current graph - * - * @method openSubgraph - * @param {LGraph} graph - */ - LGraphCanvas.prototype.openSubgraph = function(graph) { - if (!graph) { - throw "graph cannot be null"; - } - - if (this.graph == graph) { - throw "graph cannot be the same"; - } - - this.clear(); - - if (this.graph) { - if (!this._graph_stack) { - this._graph_stack = []; - } - this._graph_stack.push(this.graph); - } - - graph.attachCanvas(this); - this.checkPanels(); - this.setDirty(true, true); - }; - - /** - * closes a subgraph contained inside a node - * - * @method closeSubgraph - * @param {LGraph} assigns a graph - */ - LGraphCanvas.prototype.closeSubgraph = function() { - if (!this._graph_stack || this._graph_stack.length == 0) { - return; - } - var subgraph_node = this.graph._subgraph_node; - var graph = this._graph_stack.pop(); - this.selected_nodes = {}; - this.highlighted_links = {}; - graph.attachCanvas(this); - this.setDirty(true, true); - if (subgraph_node) { - this.centerOnNode(subgraph_node); - this.selectNodes([subgraph_node]); - } - // when close sub graph back to offset [0, 0] scale 1 - this.ds.offset = [0, 0] - this.ds.scale = 1 - }; - - /** - * returns the visually active graph (in case there are more in the stack) - * @method getCurrentGraph - * @return {LGraph} the active graph - */ - LGraphCanvas.prototype.getCurrentGraph = function() { - return this.graph; - }; - - /** - * assigns a canvas - * - * @method setCanvas - * @param {Canvas} assigns a canvas (also accepts the ID of the element (not a selector) - */ - LGraphCanvas.prototype.setCanvas = function(canvas, skip_events) { - var that = this; - - if (canvas) { - if (canvas.constructor === String) { - canvas = document.getElementById(canvas); - if (!canvas) { - throw "Error creating LiteGraph canvas: Canvas not found"; - } - } - } - - if (canvas === this.canvas) { - return; - } - - if (!canvas && this.canvas) { - //maybe detach events from old_canvas - if (!skip_events) { - this.unbindEvents(); - } - } - - this.canvas = canvas; - this.ds.element = canvas; - - if (!canvas) { - return; - } - - //this.canvas.tabindex = "1000"; - canvas.className += " lgraphcanvas"; - canvas.data = this; - canvas.tabindex = "1"; //to allow key events - - //bg canvas: used for non changing stuff - this.bgcanvas = null; - if (!this.bgcanvas) { - this.bgcanvas = document.createElement("canvas"); - this.bgcanvas.width = this.canvas.width; - this.bgcanvas.height = this.canvas.height; - } - - if (canvas.getContext == null) { - if (canvas.localName != "canvas") { - throw "Element supplied for LGraphCanvas must be a element, you passed a " + - canvas.localName; - } - throw "This browser doesn't support Canvas"; - } - - var ctx = (this.ctx = canvas.getContext("2d")); - if (ctx == null) { - if (!canvas.webgl_enabled) { - console.warn( - "This canvas seems to be WebGL, enabling WebGL renderer" - ); - } - this.enableWebGL(); - } - - //input: (move and up could be unbinded) - // why here? this._mousemove_callback = this.processMouseMove.bind(this); - // why here? this._mouseup_callback = this.processMouseUp.bind(this); - - if (!skip_events) { - this.bindEvents(); - } - }; - - //used in some events to capture them - LGraphCanvas.prototype._doNothing = function doNothing(e) { - //console.log("pointerevents: _doNothing "+e.type); - e.preventDefault(); - return false; - }; - LGraphCanvas.prototype._doReturnTrue = function doNothing(e) { - e.preventDefault(); - return true; - }; - - /** - * binds mouse, keyboard, touch and drag events to the canvas - * @method bindEvents - **/ - LGraphCanvas.prototype.bindEvents = function() { - if (this._events_binded) { - console.warn("LGraphCanvas: events already binded"); - return; - } - - //console.log("pointerevents: bindEvents"); - - var canvas = this.canvas; - - var ref_window = this.getCanvasWindow(); - var document = ref_window.document; //hack used when moving canvas between windows - - this._mousedown_callback = this.processMouseDown.bind(this); - this._mousewheel_callback = this.processMouseWheel.bind(this); - // why mousemove and mouseup were not binded here? - this._mousemove_callback = this.processMouseMove.bind(this); - this._mouseup_callback = this.processMouseUp.bind(this); - - //touch events -- TODO IMPLEMENT - //this._touch_callback = this.touchHandler.bind(this); - - LiteGraph.pointerListenerAdd(canvas,"down", this._mousedown_callback, true); //down do not need to store the binded - canvas.addEventListener("mousewheel", this._mousewheel_callback, false); - - LiteGraph.pointerListenerAdd(canvas,"up", this._mouseup_callback, true); // CHECK: ??? binded or not - LiteGraph.pointerListenerAdd(canvas,"move", this._mousemove_callback); - - canvas.addEventListener("contextmenu", this._doNothing); - canvas.addEventListener( - "DOMMouseScroll", - this._mousewheel_callback, - false - ); - - //touch events -- THIS WAY DOES NOT WORK, finish implementing pointerevents, than clean the touchevents - /*if( 'touchstart' in document.documentElement ) - { - canvas.addEventListener("touchstart", this._touch_callback, true); - canvas.addEventListener("touchmove", this._touch_callback, true); - canvas.addEventListener("touchend", this._touch_callback, true); - canvas.addEventListener("touchcancel", this._touch_callback, true); - }*/ - - //Keyboard ****************** - this._key_callback = this.processKey.bind(this); - - canvas.addEventListener("keydown", this._key_callback, true); - document.addEventListener("keyup", this._key_callback, true); //in document, otherwise it doesn't fire keyup - - //Dropping Stuff over nodes ************************************ - this._ondrop_callback = this.processDrop.bind(this); - - canvas.addEventListener("dragover", this._doNothing, false); - canvas.addEventListener("dragend", this._doNothing, false); - canvas.addEventListener("drop", this._ondrop_callback, false); - canvas.addEventListener("dragenter", this._doReturnTrue, false); - - this._events_binded = true; - }; - - /** - * unbinds mouse events from the canvas - * @method unbindEvents - **/ - LGraphCanvas.prototype.unbindEvents = function() { - if (!this._events_binded) { - console.warn("LGraphCanvas: no events binded"); - return; - } - - //console.log("pointerevents: unbindEvents"); - - var ref_window = this.getCanvasWindow(); - var document = ref_window.document; - - LiteGraph.pointerListenerRemove(this.canvas,"move", this._mousedown_callback); - LiteGraph.pointerListenerRemove(this.canvas,"up", this._mousedown_callback); - LiteGraph.pointerListenerRemove(this.canvas,"down", this._mousedown_callback); - this.canvas.removeEventListener( - "mousewheel", - this._mousewheel_callback - ); - this.canvas.removeEventListener( - "DOMMouseScroll", - this._mousewheel_callback - ); - this.canvas.removeEventListener("keydown", this._key_callback); - document.removeEventListener("keyup", this._key_callback); - this.canvas.removeEventListener("contextmenu", this._doNothing); - this.canvas.removeEventListener("drop", this._ondrop_callback); - this.canvas.removeEventListener("dragenter", this._doReturnTrue); - - //touch events -- THIS WAY DOES NOT WORK, finish implementing pointerevents, than clean the touchevents - /*this.canvas.removeEventListener("touchstart", this._touch_callback ); - this.canvas.removeEventListener("touchmove", this._touch_callback ); - this.canvas.removeEventListener("touchend", this._touch_callback ); - this.canvas.removeEventListener("touchcancel", this._touch_callback );*/ - - this._mousedown_callback = null; - this._mousewheel_callback = null; - this._key_callback = null; - this._ondrop_callback = null; - - this._events_binded = false; - }; - - LGraphCanvas.getFileExtension = function(url) { - var question = url.indexOf("?"); - if (question != -1) { - url = url.substr(0, question); - } - var point = url.lastIndexOf("."); - if (point == -1) { - return ""; - } - return url.substr(point + 1).toLowerCase(); - }; - - /** - * this function allows to render the canvas using WebGL instead of Canvas2D - * this is useful if you plant to render 3D objects inside your nodes, it uses litegl.js for webgl and canvas2DtoWebGL to emulate the Canvas2D calls in webGL - * @method enableWebGL - **/ - LGraphCanvas.prototype.enableWebGL = function() { - if (typeof GL === "undefined") { - throw "litegl.js must be included to use a WebGL canvas"; - } - if (typeof enableWebGLCanvas === "undefined") { - throw "webglCanvas.js must be included to use this feature"; - } - - this.gl = this.ctx = enableWebGLCanvas(this.canvas); - this.ctx.webgl = true; - this.bgcanvas = this.canvas; - this.bgctx = this.gl; - this.canvas.webgl_enabled = true; - - /* - GL.create({ canvas: this.bgcanvas }); - this.bgctx = enableWebGLCanvas( this.bgcanvas ); - window.gl = this.gl; - */ - }; - - /** - * marks as dirty the canvas, this way it will be rendered again - * - * @class LGraphCanvas - * @method setDirty - * @param {bool} fgcanvas if the foreground canvas is dirty (the one containing the nodes) - * @param {bool} bgcanvas if the background canvas is dirty (the one containing the wires) - */ - LGraphCanvas.prototype.setDirty = function(fgcanvas, bgcanvas) { - if (fgcanvas) { - this.dirty_canvas = true; - } - if (bgcanvas) { - this.dirty_bgcanvas = true; - } - }; - - /** - * Used to attach the canvas in a popup - * - * @method getCanvasWindow - * @return {window} returns the window where the canvas is attached (the DOM root node) - */ - LGraphCanvas.prototype.getCanvasWindow = function() { - if (!this.canvas) { - return window; - } - var doc = this.canvas.ownerDocument; - return doc.defaultView || doc.parentWindow; - }; - - /** - * starts rendering the content of the canvas when needed - * - * @method startRendering - */ - LGraphCanvas.prototype.startRendering = function() { - if (this.is_rendering) { - return; - } //already rendering - - this.is_rendering = true; - renderFrame.call(this); - - function renderFrame() { - if (!this.pause_rendering) { - this.draw(); - } - - var window = this.getCanvasWindow(); - if (this.is_rendering) { - window.requestAnimationFrame(renderFrame.bind(this)); - } - } - }; - - /** - * stops rendering the content of the canvas (to save resources) - * - * @method stopRendering - */ - LGraphCanvas.prototype.stopRendering = function() { - this.is_rendering = false; - /* - if(this.rendering_timer_id) - { - clearInterval(this.rendering_timer_id); - this.rendering_timer_id = null; - } - */ - }; - - /* LiteGraphCanvas input */ - - //used to block future mouse events (because of im gui) - LGraphCanvas.prototype.blockClick = function() - { - this.block_click = true; - this.last_mouseclick = 0; - } - - LGraphCanvas.prototype.processMouseDown = function(e) { - - if( this.set_canvas_dirty_on_mouse_event ) - this.dirty_canvas = true; - - if (!this.graph) { - return; - } - - this.adjustMouseEvent(e); - - var ref_window = this.getCanvasWindow(); - var document = ref_window.document; - LGraphCanvas.active_canvas = this; - var that = this; - - var x = e.clientX; - var y = e.clientY; - //console.log(y,this.viewport); - //console.log("pointerevents: processMouseDown pointerId:"+e.pointerId+" which:"+e.which+" isPrimary:"+e.isPrimary+" :: x y "+x+" "+y); - - this.ds.viewport = this.viewport; - var is_inside = !this.viewport || ( this.viewport && x >= this.viewport[0] && x < (this.viewport[0] + this.viewport[2]) && y >= this.viewport[1] && y < (this.viewport[1] + this.viewport[3]) ); - - //move mouse move event to the window in case it drags outside of the canvas - if(!this.options.skip_events) - { - LiteGraph.pointerListenerRemove(this.canvas,"move", this._mousemove_callback); - LiteGraph.pointerListenerAdd(ref_window.document,"move", this._mousemove_callback,true); //catch for the entire window - LiteGraph.pointerListenerAdd(ref_window.document,"up", this._mouseup_callback,true); - } - - if(!is_inside){ - return; - } - - var node = this.graph.getNodeOnPos( e.canvasX, e.canvasY, this.visible_nodes, 5 ); - var skip_dragging = false; - var skip_action = false; - var now = LiteGraph.getTime(); - var is_primary = (e.isPrimary === undefined || !e.isPrimary); - var is_double_click = (now - this.last_mouseclick < 300); - this.mouse[0] = e.clientX; - this.mouse[1] = e.clientY; - this.graph_mouse[0] = e.canvasX; - this.graph_mouse[1] = e.canvasY; - this.last_click_position = [this.mouse[0],this.mouse[1]]; - - if (this.pointer_is_down && is_primary ){ - this.pointer_is_double = true; - //console.log("pointerevents: pointer_is_double start"); - }else{ - this.pointer_is_double = false; - } - this.pointer_is_down = true; - - - this.canvas.focus(); - - LiteGraph.closeAllContextMenus(ref_window); - - if (this.onMouse) - { - if (this.onMouse(e) == true) - return; - } - - //left button mouse / single finger - if (e.which == 1 && !this.pointer_is_double) - { - if (e.ctrlKey) - { - this.dragging_rectangle = new Float32Array(4); - this.dragging_rectangle[0] = e.canvasX; - this.dragging_rectangle[1] = e.canvasY; - this.dragging_rectangle[2] = 1; - this.dragging_rectangle[3] = 1; - skip_action = true; - } - - // clone node ALT dragging - if (LiteGraph.alt_drag_do_clone_nodes && e.altKey && node && this.allow_interaction && !skip_action && !this.read_only) - { - if (cloned = node.clone()){ - cloned.pos[0] += 5; - cloned.pos[1] += 5; - this.graph.add(cloned,false,{doCalcSize: false}); - node = cloned; - skip_action = true; - if (!block_drag_node) { - if (this.allow_dragnodes) { - this.graph.beforeChange(); - this.node_dragged = node; - } - if (!this.selected_nodes[node.id]) { - this.processNodeSelected(node, e); - } - } - } - } - - var clicking_canvas_bg = false; - - //when clicked on top of a node - //and it is not interactive - if (node && (this.allow_interaction || node.flags.allow_interaction) && !skip_action && !this.read_only) { - if (!this.live_mode && !node.flags.pinned) { - this.bringToFront(node); - } //if it wasn't selected? - - //not dragging mouse to connect two slots - if ( this.allow_interaction && !this.connecting_node && !node.flags.collapsed && !this.live_mode ) { - //Search for corner for resize - if ( !skip_action && - node.resizable !== false && node.inResizeCorner(e.canvasX, e.canvasY) - ) { - this.graph.beforeChange(); - this.resizing_node = node; - this.canvas.style.cursor = "se-resize"; - skip_action = true; - } else { - //search for outputs - if (node.outputs) { - for ( var i = 0, l = node.outputs.length; i < l; ++i ) { - var output = node.outputs[i]; - var link_pos = node.getConnectionPos(false, i); - if ( - isInsideRectangle( - e.canvasX, - e.canvasY, - link_pos[0] - 15, - link_pos[1] - 10, - 30, - 20 - ) - ) { - this.connecting_node = node; - this.connecting_output = output; - this.connecting_output.slot_index = i; - this.connecting_pos = node.getConnectionPos( false, i ); - this.connecting_slot = i; - - if (LiteGraph.shift_click_do_break_link_from){ - if (e.shiftKey) { - node.disconnectOutput(i); - } - } - - if (is_double_click) { - if (node.onOutputDblClick) { - node.onOutputDblClick(i, e); - } - } else { - if (node.onOutputClick) { - node.onOutputClick(i, e); - } - } - - skip_action = true; - break; - } - } - } - - //search for inputs - if (node.inputs) { - for ( var i = 0, l = node.inputs.length; i < l; ++i ) { - var input = node.inputs[i]; - var link_pos = node.getConnectionPos(true, i); - if ( - isInsideRectangle( - e.canvasX, - e.canvasY, - link_pos[0] - 15, - link_pos[1] - 10, - 30, - 20 - ) - ) { - if (is_double_click) { - if (node.onInputDblClick) { - node.onInputDblClick(i, e); - } - } else { - if (node.onInputClick) { - node.onInputClick(i, e); - } - } - - if (input.link !== null) { - var link_info = this.graph.links[ - input.link - ]; //before disconnecting - if (LiteGraph.click_do_break_link_to){ - node.disconnectInput(i); - this.dirty_bgcanvas = true; - skip_action = true; - }else{ - // do same action as has not node ? - } - - if ( - this.allow_reconnect_links || - //this.move_destination_link_without_shift || - e.shiftKey - ) { - if (!LiteGraph.click_do_break_link_to){ - node.disconnectInput(i); - } - this.connecting_node = this.graph._nodes_by_id[ - link_info.origin_id - ]; - this.connecting_slot = - link_info.origin_slot; - this.connecting_output = this.connecting_node.outputs[ - this.connecting_slot - ]; - this.connecting_pos = this.connecting_node.getConnectionPos( false, this.connecting_slot ); - - this.dirty_bgcanvas = true; - skip_action = true; - } - - - }else{ - // has not node - } - - if (!skip_action){ - // connect from in to out, from to to from - this.connecting_node = node; - this.connecting_input = input; - this.connecting_input.slot_index = i; - this.connecting_pos = node.getConnectionPos( true, i ); - this.connecting_slot = i; - - this.dirty_bgcanvas = true; - skip_action = true; - } - } - } - } - } //not resizing - } - - //it wasn't clicked on the links boxes - if (!skip_action) { - var block_drag_node = false; - if(node && node.flags && node.flags.pinned) { - block_drag_node = true; - } - var pos = [e.canvasX - node.pos[0], e.canvasY - node.pos[1]]; - - //widgets - var widget = this.processNodeWidgets( node, this.graph_mouse, e ); - if (widget) { - block_drag_node = true; - this.node_widget = [node, widget]; - } - - //double clicking - if (this.allow_interaction && is_double_click && this.selected_nodes[node.id]) { - //double click node - if (node.onDblClick) { - node.onDblClick( e, pos, this ); - } - this.processNodeDblClicked(node); - block_drag_node = true; - } - - //if do not capture mouse - if ( node.onMouseDown && node.onMouseDown( e, pos, this ) ) { - block_drag_node = true; - } else { - //open subgraph button - if(node.subgraph && !node.skip_subgraph_button) - { - if ( !node.flags.collapsed && pos[0] > node.size[0] - LiteGraph.NODE_TITLE_HEIGHT && pos[1] < 0 ) { - var that = this; - setTimeout(function() { - that.openSubgraph(node.subgraph); - }, 10); - } - } - - if (this.live_mode) { - clicking_canvas_bg = true; - block_drag_node = true; - } - } - - if (!block_drag_node) { - if (this.allow_dragnodes) { - this.graph.beforeChange(); - this.node_dragged = node; - } - this.processNodeSelected(node, e); - } else { // double-click - /** - * Don't call the function if the block is already selected. - * Otherwise, it could cause the block to be unselected while its panel is open. - */ - if (!node.is_selected) this.processNodeSelected(node, e); - } - - this.dirty_canvas = true; - } - } //clicked outside of nodes - else { - if (!skip_action){ - //search for link connector - if(!this.read_only) { - for (var i = 0; i < this.visible_links.length; ++i) { - var link = this.visible_links[i]; - var center = link._pos; - if ( - !center || - e.canvasX < center[0] - 4 || - e.canvasX > center[0] + 4 || - e.canvasY < center[1] - 4 || - e.canvasY > center[1] + 4 - ) { - continue; - } - //link clicked - this.showLinkMenu(link, e); - this.over_link_center = null; //clear tooltip - break; - } - } - - this.selected_group = this.graph.getGroupOnPos( e.canvasX, e.canvasY ); - this.selected_group_resizing = false; - if (this.selected_group && !this.read_only ) { - if (e.ctrlKey) { - this.dragging_rectangle = null; - } - - var dist = distance( [e.canvasX, e.canvasY], [ this.selected_group.pos[0] + this.selected_group.size[0], this.selected_group.pos[1] + this.selected_group.size[1] ] ); - if (dist * this.ds.scale < 10) { - this.selected_group_resizing = true; - } else { - this.selected_group.recomputeInsideNodes(); - } - } - - if (is_double_click && !this.read_only && this.allow_searchbox) { - this.showSearchBox(e); - e.preventDefault(); - e.stopPropagation(); - } - - clicking_canvas_bg = true; - } - } - - if (!skip_action && clicking_canvas_bg && this.allow_dragcanvas) { - //console.log("pointerevents: dragging_canvas start"); - this.dragging_canvas = true; - } - - } else if (e.which == 2) { - //middle button - - if (LiteGraph.middle_click_slot_add_default_node){ - if (node && this.allow_interaction && !skip_action && !this.read_only){ - //not dragging mouse to connect two slots - if ( - !this.connecting_node && - !node.flags.collapsed && - !this.live_mode - ) { - var mClikSlot = false; - var mClikSlot_index = false; - var mClikSlot_isOut = false; - //search for outputs - if (node.outputs) { - for ( var i = 0, l = node.outputs.length; i < l; ++i ) { - var output = node.outputs[i]; - var link_pos = node.getConnectionPos(false, i); - if (isInsideRectangle(e.canvasX,e.canvasY,link_pos[0] - 15,link_pos[1] - 10,30,20)) { - mClikSlot = output; - mClikSlot_index = i; - mClikSlot_isOut = true; - break; - } - } - } - - //search for inputs - if (node.inputs) { - for ( var i = 0, l = node.inputs.length; i < l; ++i ) { - var input = node.inputs[i]; - var link_pos = node.getConnectionPos(true, i); - if (isInsideRectangle(e.canvasX,e.canvasY,link_pos[0] - 15,link_pos[1] - 10,30,20)) { - mClikSlot = input; - mClikSlot_index = i; - mClikSlot_isOut = false; - break; - } - } - } - //console.log("middleClickSlots? "+mClikSlot+" & "+(mClikSlot_index!==false)); - if (mClikSlot && mClikSlot_index!==false){ - - var alphaPosY = 0.5-((mClikSlot_index+1)/((mClikSlot_isOut?node.outputs.length:node.inputs.length))); - var node_bounding = node.getBounding(); - // estimate a position: this is a bad semi-bad-working mess .. REFACTOR with a correct autoplacement that knows about the others slots and nodes - var posRef = [ (!mClikSlot_isOut?node_bounding[0]:node_bounding[0]+node_bounding[2])// + node_bounding[0]/this.canvas.width*150 - ,e.canvasY-80// + node_bounding[0]/this.canvas.width*66 // vertical "derive" - ]; - var nodeCreated = this.createDefaultNodeForSlot({ nodeFrom: !mClikSlot_isOut?null:node - ,slotFrom: !mClikSlot_isOut?null:mClikSlot_index - ,nodeTo: !mClikSlot_isOut?node:null - ,slotTo: !mClikSlot_isOut?mClikSlot_index:null - ,position: posRef //,e: e - ,nodeType: "AUTO" //nodeNewType - ,posAdd:[!mClikSlot_isOut?-30:30, -alphaPosY*130] //-alphaPosY*30] - ,posSizeFix:[!mClikSlot_isOut?-1:0, 0] //-alphaPosY*2*/ - }); - skip_action = true; - } - } - } - } - - if (!skip_action && this.allow_dragcanvas) { - //console.log("pointerevents: dragging_canvas start from middle button"); - this.dragging_canvas = true; - } - - - } else if (e.which == 3 || this.pointer_is_double) { - - //right button - if (this.allow_interaction && !skip_action && !this.read_only){ - - // is it hover a node ? - if (node){ - if(Object.keys(this.selected_nodes).length - && (this.selected_nodes[node.id] || e.shiftKey || e.ctrlKey || e.metaKey) - ){ - // is multiselected or using shift to include the now node - if (!this.selected_nodes[node.id]) this.selectNodes([node],true); // add this if not present - }else{ - // update selection - this.selectNodes([node]); - } - } - - // show menu on this node - this.processContextMenu(node, e); - } - - } - - //TODO - //if(this.node_selected != prev_selected) - // this.onNodeSelectionChange(this.node_selected); - - this.last_mouse[0] = e.clientX; - this.last_mouse[1] = e.clientY; - this.last_mouseclick = LiteGraph.getTime(); - this.last_mouse_dragging = true; - - /* - if( (this.dirty_canvas || this.dirty_bgcanvas) && this.rendering_timer_id == null) - this.draw(); - */ - - this.graph.change(); - - //this is to ensure to defocus(blur) if a text input element is on focus - if ( - !ref_window.document.activeElement || - (ref_window.document.activeElement.nodeName.toLowerCase() != - "input" && - ref_window.document.activeElement.nodeName.toLowerCase() != - "textarea") - ) { - e.preventDefault(); - } - e.stopPropagation(); - - if (this.onMouseDown) { - this.onMouseDown(e); - } - - return false; - }; - - /** - * Called when a mouse move event has to be processed - * @method processMouseMove - **/ - LGraphCanvas.prototype.processMouseMove = function(e) { - if (this.autoresize) { - this.resize(); - } - - if( this.set_canvas_dirty_on_mouse_event ) - this.dirty_canvas = true; - - if (!this.graph) { - return; - } - - LGraphCanvas.active_canvas = this; - this.adjustMouseEvent(e); - var mouse = [e.clientX, e.clientY]; - this.mouse[0] = mouse[0]; - this.mouse[1] = mouse[1]; - var delta = [ - mouse[0] - this.last_mouse[0], - mouse[1] - this.last_mouse[1] - ]; - this.last_mouse = mouse; - this.graph_mouse[0] = e.canvasX; - this.graph_mouse[1] = e.canvasY; - - //console.log("pointerevents: processMouseMove "+e.pointerId+" "+e.isPrimary); - - if(this.block_click) - { - //console.log("pointerevents: processMouseMove block_click"); - e.preventDefault(); - return false; - } - - e.dragging = this.last_mouse_dragging; - - if (this.node_widget) { - this.processNodeWidgets( - this.node_widget[0], - this.graph_mouse, - e, - this.node_widget[1] - ); - this.dirty_canvas = true; - } - - //get node over - var node = this.graph.getNodeOnPos(e.canvasX,e.canvasY,this.visible_nodes); - - if (this.dragging_rectangle) - { - this.dragging_rectangle[2] = e.canvasX - this.dragging_rectangle[0]; - this.dragging_rectangle[3] = e.canvasY - this.dragging_rectangle[1]; - this.dirty_canvas = true; - } - else if (this.selected_group && !this.read_only) - { - //moving/resizing a group - if (this.selected_group_resizing) { - this.selected_group.size = [ - e.canvasX - this.selected_group.pos[0], - e.canvasY - this.selected_group.pos[1] - ]; - } else { - var deltax = delta[0] / this.ds.scale; - var deltay = delta[1] / this.ds.scale; - this.selected_group.move(deltax, deltay, e.ctrlKey); - if (this.selected_group._nodes.length) { - this.dirty_canvas = true; - } - } - this.dirty_bgcanvas = true; - } else if (this.dragging_canvas) { - ////console.log("pointerevents: processMouseMove is dragging_canvas"); - this.ds.offset[0] += delta[0] / this.ds.scale; - this.ds.offset[1] += delta[1] / this.ds.scale; - this.dirty_canvas = true; - this.dirty_bgcanvas = true; - } else if ((this.allow_interaction || (node && node.flags.allow_interaction)) && !this.read_only) { - if (this.connecting_node) { - this.dirty_canvas = true; - } - - //remove mouseover flag - for (var i = 0, l = this.graph._nodes.length; i < l; ++i) { - if (this.graph._nodes[i].mouseOver && node != this.graph._nodes[i] ) { - //mouse leave - this.graph._nodes[i].mouseOver = false; - if (this.node_over && this.node_over.onMouseLeave) { - this.node_over.onMouseLeave(e); - } - this.node_over = null; - this.dirty_canvas = true; - } - } - - //mouse over a node - if (node) { - - if(node.redraw_on_mouse) - this.dirty_canvas = true; - - //this.canvas.style.cursor = "move"; - if (!node.mouseOver) { - //mouse enter - node.mouseOver = true; - this.node_over = node; - this.dirty_canvas = true; - - if (node.onMouseEnter) { - node.onMouseEnter(e); - } - } - - //in case the node wants to do something - if (node.onMouseMove) { - node.onMouseMove( e, [e.canvasX - node.pos[0], e.canvasY - node.pos[1]], this ); - } - - //if dragging a link - if (this.connecting_node) { - - if (this.connecting_output){ - - var pos = this._highlight_input || [0, 0]; //to store the output of isOverNodeInput - - //on top of input - if (this.isOverNodeBox(node, e.canvasX, e.canvasY)) { - //mouse on top of the corner box, don't know what to do - } else { - //check if I have a slot below de mouse - var slot = this.isOverNodeInput( node, e.canvasX, e.canvasY, pos ); - if (slot != -1 && node.inputs[slot]) { - var slot_type = node.inputs[slot].type; - if ( LiteGraph.isValidConnection( this.connecting_output.type, slot_type ) ) { - this._highlight_input = pos; - this._highlight_input_slot = node.inputs[slot]; // XXX CHECK THIS - } - } else { - this._highlight_input = null; - this._highlight_input_slot = null; // XXX CHECK THIS - } - } - - }else if(this.connecting_input){ - - var pos = this._highlight_output || [0, 0]; //to store the output of isOverNodeOutput - - //on top of output - if (this.isOverNodeBox(node, e.canvasX, e.canvasY)) { - //mouse on top of the corner box, don't know what to do - } else { - //check if I have a slot below de mouse - var slot = this.isOverNodeOutput( node, e.canvasX, e.canvasY, pos ); - if (slot != -1 && node.outputs[slot]) { - var slot_type = node.outputs[slot].type; - if ( LiteGraph.isValidConnection( this.connecting_input.type, slot_type ) ) { - this._highlight_output = pos; - } - } else { - this._highlight_output = null; - } - } - } - } - - //Search for corner - if (this.canvas) { - if (node.inResizeCorner(e.canvasX, e.canvasY)) { - this.canvas.style.cursor = "se-resize"; - } else { - this.canvas.style.cursor = "crosshair"; - } - } - } else { //not over a node - - //search for link connector - var over_link = null; - for (var i = 0; i < this.visible_links.length; ++i) { - var link = this.visible_links[i]; - var center = link._pos; - if ( - !center || - e.canvasX < center[0] - 4 || - e.canvasX > center[0] + 4 || - e.canvasY < center[1] - 4 || - e.canvasY > center[1] + 4 - ) { - continue; - } - over_link = link; - break; - } - if( over_link != this.over_link_center ) - { - this.over_link_center = over_link; - this.dirty_canvas = true; - } - - if (this.canvas) { - this.canvas.style.cursor = ""; - } - } //end - - //send event to node if capturing input (used with widgets that allow drag outside of the area of the node) - if ( this.node_capturing_input && this.node_capturing_input != node && this.node_capturing_input.onMouseMove ) { - this.node_capturing_input.onMouseMove(e,[e.canvasX - this.node_capturing_input.pos[0],e.canvasY - this.node_capturing_input.pos[1]], this); - } - - //node being dragged - if (this.node_dragged && !this.live_mode) { - //console.log("draggin!",this.selected_nodes); - for (var i in this.selected_nodes) { - var n = this.selected_nodes[i]; - n.pos[0] += delta[0] / this.ds.scale; - n.pos[1] += delta[1] / this.ds.scale; - if (!n.is_selected) this.processNodeSelected(n, e); /* - * Don't call the function if the block is already selected. - * Otherwise, it could cause the block to be unselected while dragging. - */ - } - - this.dirty_canvas = true; - this.dirty_bgcanvas = true; - } - - if (this.resizing_node && !this.live_mode) { - //convert mouse to node space - var desired_size = [ e.canvasX - this.resizing_node.pos[0], e.canvasY - this.resizing_node.pos[1] ]; - var min_size = this.resizing_node.computeSize(); - desired_size[0] = Math.max( min_size[0], desired_size[0] ); - desired_size[1] = Math.max( min_size[1], desired_size[1] ); - this.resizing_node.setSize( desired_size ); - - this.canvas.style.cursor = "se-resize"; - this.dirty_canvas = true; - this.dirty_bgcanvas = true; - } - } - - e.preventDefault(); - return false; - }; - - /** - * Called when a mouse up event has to be processed - * @method processMouseUp - **/ - LGraphCanvas.prototype.processMouseUp = function(e) { - - var is_primary = ( e.isPrimary === undefined || e.isPrimary ); - - //early exit for extra pointer - if(!is_primary){ - /*e.stopPropagation(); - e.preventDefault();*/ - //console.log("pointerevents: processMouseUp pointerN_stop "+e.pointerId+" "+e.isPrimary); - return false; - } - - //console.log("pointerevents: processMouseUp "+e.pointerId+" "+e.isPrimary+" :: "+e.clientX+" "+e.clientY); - - if( this.set_canvas_dirty_on_mouse_event ) - this.dirty_canvas = true; - - if (!this.graph) - return; - - var window = this.getCanvasWindow(); - var document = window.document; - LGraphCanvas.active_canvas = this; - - //restore the mousemove event back to the canvas - if(!this.options.skip_events) - { - //console.log("pointerevents: processMouseUp adjustEventListener"); - LiteGraph.pointerListenerRemove(document,"move", this._mousemove_callback,true); - LiteGraph.pointerListenerAdd(this.canvas,"move", this._mousemove_callback,true); - LiteGraph.pointerListenerRemove(document,"up", this._mouseup_callback,true); - } - - this.adjustMouseEvent(e); - var now = LiteGraph.getTime(); - e.click_time = now - this.last_mouseclick; - this.last_mouse_dragging = false; - this.last_click_position = null; - - if(this.block_click) - { - //console.log("pointerevents: processMouseUp block_clicks"); - this.block_click = false; //used to avoid sending twice a click in a immediate button - } - - //console.log("pointerevents: processMouseUp which: "+e.which); - - if (e.which == 1) { - - if( this.node_widget ) - { - this.processNodeWidgets( this.node_widget[0], this.graph_mouse, e ); - } - - //left button - this.node_widget = null; - - if (this.selected_group) { - var diffx = - this.selected_group.pos[0] - - Math.round(this.selected_group.pos[0]); - var diffy = - this.selected_group.pos[1] - - Math.round(this.selected_group.pos[1]); - this.selected_group.move(diffx, diffy, e.ctrlKey); - this.selected_group.pos[0] = Math.round( - this.selected_group.pos[0] - ); - this.selected_group.pos[1] = Math.round( - this.selected_group.pos[1] - ); - if (this.selected_group._nodes.length) { - this.dirty_canvas = true; - } - this.selected_group = null; - } - this.selected_group_resizing = false; - - var node = this.graph.getNodeOnPos( - e.canvasX, - e.canvasY, - this.visible_nodes - ); - - if (this.dragging_rectangle) { - if (this.graph) { - var nodes = this.graph._nodes; - var node_bounding = new Float32Array(4); - - //compute bounding and flip if left to right - var w = Math.abs(this.dragging_rectangle[2]); - var h = Math.abs(this.dragging_rectangle[3]); - var startx = - this.dragging_rectangle[2] < 0 - ? this.dragging_rectangle[0] - w - : this.dragging_rectangle[0]; - var starty = - this.dragging_rectangle[3] < 0 - ? this.dragging_rectangle[1] - h - : this.dragging_rectangle[1]; - this.dragging_rectangle[0] = startx; - this.dragging_rectangle[1] = starty; - this.dragging_rectangle[2] = w; - this.dragging_rectangle[3] = h; - - // test dragging rect size, if minimun simulate a click - if (!node || (w > 10 && h > 10 )){ - //test against all nodes (not visible because the rectangle maybe start outside - var to_select = []; - for (var i = 0; i < nodes.length; ++i) { - var nodeX = nodes[i]; - nodeX.getBounding(node_bounding); - if ( - !overlapBounding( - this.dragging_rectangle, - node_bounding - ) - ) { - continue; - } //out of the visible area - to_select.push(nodeX); - } - if (to_select.length) { - this.selectNodes(to_select,e.shiftKey); // add to selection with shift - } - }else{ - // will select of update selection - this.selectNodes([node],e.shiftKey||e.ctrlKey); // add to selection add to selection with ctrlKey or shiftKey - } - - } - this.dragging_rectangle = null; - } else if (this.connecting_node) { - //dragging a connection - this.dirty_canvas = true; - this.dirty_bgcanvas = true; - - var connInOrOut = this.connecting_output || this.connecting_input; - var connType = connInOrOut.type; - - //node below mouse - if (node) { - - /* no need to condition on event type.. just another type - if ( - connType == LiteGraph.EVENT && - this.isOverNodeBox(node, e.canvasX, e.canvasY) - ) { - - this.connecting_node.connect( - this.connecting_slot, - node, - LiteGraph.EVENT - ); - - } else {*/ - - //slot below mouse? connect - - if (this.connecting_output){ - - var slot = this.isOverNodeInput( - node, - e.canvasX, - e.canvasY - ); - if (slot != -1) { - this.connecting_node.connect(this.connecting_slot, node, slot); - } else { - //not on top of an input - // look for a good slot - this.connecting_node.connectByType(this.connecting_slot,node,connType); - } - - }else if (this.connecting_input){ - - var slot = this.isOverNodeOutput( - node, - e.canvasX, - e.canvasY - ); - - if (slot != -1) { - node.connect(slot, this.connecting_node, this.connecting_slot); // this is inverted has output-input nature like - } else { - //not on top of an input - // look for a good slot - this.connecting_node.connectByTypeOutput(this.connecting_slot,node,connType); - } - - } - - - //} - - }else{ - - // add menu when releasing link in empty space - if (LiteGraph.release_link_on_empty_shows_menu){ - if (e.shiftKey && this.allow_searchbox){ - if(this.connecting_output){ - this.showSearchBox(e,{node_from: this.connecting_node, slot_from: this.connecting_output, type_filter_in: this.connecting_output.type}); - }else if(this.connecting_input){ - this.showSearchBox(e,{node_to: this.connecting_node, slot_from: this.connecting_input, type_filter_out: this.connecting_input.type}); - } - }else{ - if(this.connecting_output){ - this.showConnectionMenu({nodeFrom: this.connecting_node, slotFrom: this.connecting_output, e: e}); - }else if(this.connecting_input){ - this.showConnectionMenu({nodeTo: this.connecting_node, slotTo: this.connecting_input, e: e}); - } - } - } - } - - this.connecting_output = null; - this.connecting_input = null; - this.connecting_pos = null; - this.connecting_node = null; - this.connecting_slot = -1; - } //not dragging connection - else if (this.resizing_node) { - this.dirty_canvas = true; - this.dirty_bgcanvas = true; - this.graph.afterChange(this.resizing_node); - this.resizing_node = null; - } else if (this.node_dragged) { - //node being dragged? - var node = this.node_dragged; - if ( - node && - e.click_time < 300 && - isInsideRectangle( e.canvasX, e.canvasY, node.pos[0], node.pos[1] - LiteGraph.NODE_TITLE_HEIGHT, LiteGraph.NODE_TITLE_HEIGHT, LiteGraph.NODE_TITLE_HEIGHT ) - ) { - node.collapse(); - } - - this.dirty_canvas = true; - this.dirty_bgcanvas = true; - this.node_dragged.pos[0] = Math.round(this.node_dragged.pos[0]); - this.node_dragged.pos[1] = Math.round(this.node_dragged.pos[1]); - if (this.graph.config.align_to_grid || this.align_to_grid ) { - this.node_dragged.alignToGrid(); - } - if( this.onNodeMoved ) - this.onNodeMoved( this.node_dragged ); - this.graph.afterChange(this.node_dragged); - this.node_dragged = null; - } //no node being dragged - else { - //get node over - var node = this.graph.getNodeOnPos( - e.canvasX, - e.canvasY, - this.visible_nodes - ); - - if (!node && e.click_time < 300) { - this.deselectAllNodes(); - } - - this.dirty_canvas = true; - this.dragging_canvas = false; - - if (this.node_over && this.node_over.onMouseUp) { - this.node_over.onMouseUp( e, [ e.canvasX - this.node_over.pos[0], e.canvasY - this.node_over.pos[1] ], this ); - } - if ( - this.node_capturing_input && - this.node_capturing_input.onMouseUp - ) { - this.node_capturing_input.onMouseUp(e, [ - e.canvasX - this.node_capturing_input.pos[0], - e.canvasY - this.node_capturing_input.pos[1] - ]); - } - } - } else if (e.which == 2) { - //middle button - //trace("middle"); - this.dirty_canvas = true; - this.dragging_canvas = false; - } else if (e.which == 3) { - //right button - //trace("right"); - this.dirty_canvas = true; - this.dragging_canvas = false; - } - - /* - if((this.dirty_canvas || this.dirty_bgcanvas) && this.rendering_timer_id == null) - this.draw(); - */ - - if (is_primary) - { - this.pointer_is_down = false; - this.pointer_is_double = false; - } - - this.graph.change(); - - //console.log("pointerevents: processMouseUp stopPropagation"); - e.stopPropagation(); - e.preventDefault(); - return false; - }; - - /** - * Called when a mouse wheel event has to be processed - * @method processMouseWheel - **/ - LGraphCanvas.prototype.processMouseWheel = function(e) { - if (!this.graph || !this.allow_dragcanvas) { - return; - } - - var delta = e.wheelDeltaY != null ? e.wheelDeltaY : e.detail * -60; - - this.adjustMouseEvent(e); - - var x = e.clientX; - var y = e.clientY; - var is_inside = !this.viewport || ( this.viewport && x >= this.viewport[0] && x < (this.viewport[0] + this.viewport[2]) && y >= this.viewport[1] && y < (this.viewport[1] + this.viewport[3]) ); - if(!is_inside) - return; - - var scale = this.ds.scale; - - if (delta > 0) { - scale *= 1.1; - } else if (delta < 0) { - scale *= 1 / 1.1; - } - - //this.setZoom( scale, [ e.clientX, e.clientY ] ); - this.ds.changeScale(scale, [e.clientX, e.clientY]); - - this.graph.change(); - - e.preventDefault(); - return false; // prevent default - }; - - /** - * returns true if a position (in graph space) is on top of a node little corner box - * @method isOverNodeBox - **/ - LGraphCanvas.prototype.isOverNodeBox = function(node, canvasx, canvasy) { - var title_height = LiteGraph.NODE_TITLE_HEIGHT; - if ( - isInsideRectangle( - canvasx, - canvasy, - node.pos[0] + 2, - node.pos[1] + 2 - title_height, - title_height - 4, - title_height - 4 - ) - ) { - return true; - } - return false; - }; - - /** - * returns the INDEX if a position (in graph space) is on top of a node input slot - * @method isOverNodeInput - **/ - LGraphCanvas.prototype.isOverNodeInput = function( - node, - canvasx, - canvasy, - slot_pos - ) { - if (node.inputs) { - for (var i = 0, l = node.inputs.length; i < l; ++i) { - var input = node.inputs[i]; - var link_pos = node.getConnectionPos(true, i); - var is_inside = false; - if (node.horizontal) { - is_inside = isInsideRectangle( - canvasx, - canvasy, - link_pos[0] - 5, - link_pos[1] - 10, - 10, - 20 - ); - } else { - is_inside = isInsideRectangle( - canvasx, - canvasy, - link_pos[0] - 10, - link_pos[1] - 5, - 40, - 10 - ); - } - if (is_inside) { - if (slot_pos) { - slot_pos[0] = link_pos[0]; - slot_pos[1] = link_pos[1]; - } - return i; - } - } - } - return -1; - }; - - /** - * returns the INDEX if a position (in graph space) is on top of a node output slot - * @method isOverNodeOuput - **/ - LGraphCanvas.prototype.isOverNodeOutput = function( - node, - canvasx, - canvasy, - slot_pos - ) { - if (node.outputs) { - for (var i = 0, l = node.outputs.length; i < l; ++i) { - var output = node.outputs[i]; - var link_pos = node.getConnectionPos(false, i); - var is_inside = false; - if (node.horizontal) { - is_inside = isInsideRectangle( - canvasx, - canvasy, - link_pos[0] - 5, - link_pos[1] - 10, - 10, - 20 - ); - } else { - is_inside = isInsideRectangle( - canvasx, - canvasy, - link_pos[0] - 10, - link_pos[1] - 5, - 40, - 10 - ); - } - if (is_inside) { - if (slot_pos) { - slot_pos[0] = link_pos[0]; - slot_pos[1] = link_pos[1]; - } - return i; - } - } - } - return -1; - }; - - /** - * process a key event - * @method processKey - **/ - LGraphCanvas.prototype.processKey = function(e) { - if (!this.graph) { - return; - } - - var block_default = false; - //console.log(e); //debug - - if (e.target.localName == "input") { - return; - } - - if (e.type == "keydown") { - if (e.keyCode == 32) { - //space - this.dragging_canvas = true; - block_default = true; - } - - if (e.keyCode == 27) { - //esc - if(this.node_panel) this.node_panel.close(); - if(this.options_panel) this.options_panel.close(); - block_default = true; - } - - //select all Control A - if (e.keyCode == 65 && e.ctrlKey) { - this.selectNodes(); - block_default = true; - } - - if ((e.keyCode === 67) && (e.metaKey || e.ctrlKey) && !e.shiftKey) { - //copy - if (this.selected_nodes) { - this.copyToClipboard(); - block_default = true; - } - } - - if ((e.keyCode === 86) && (e.metaKey || e.ctrlKey)) { - //paste - this.pasteFromClipboard(e.shiftKey); - } - - //delete or backspace - if (e.keyCode == 46 || e.keyCode == 8) { - if ( - e.target.localName != "input" && - e.target.localName != "textarea" - ) { - this.deleteSelectedNodes(); - block_default = true; - } - } - - //collapse - //... - - //TODO - if (this.selected_nodes) { - for (var i in this.selected_nodes) { - if (this.selected_nodes[i].onKeyDown) { - this.selected_nodes[i].onKeyDown(e); - } - } - } - } else if (e.type == "keyup") { - if (e.keyCode == 32) { - // space - this.dragging_canvas = false; - } - - if (this.selected_nodes) { - for (var i in this.selected_nodes) { - if (this.selected_nodes[i].onKeyUp) { - this.selected_nodes[i].onKeyUp(e); - } - } - } - } - - this.graph.change(); - - if (block_default) { - e.preventDefault(); - e.stopImmediatePropagation(); - return false; - } - }; - - LGraphCanvas.prototype.copyToClipboard = function(nodes) { - var clipboard_info = { - nodes: [], - links: [] - }; - var index = 0; - var selected_nodes_array = []; - if (!nodes) nodes = this.selected_nodes; - for (var i in nodes) { - var node = nodes[i]; - if (node.clonable === false) - continue; - node._relative_id = index; - selected_nodes_array.push(node); - index += 1; - } - - for (var i = 0; i < selected_nodes_array.length; ++i) { - var node = selected_nodes_array[i]; - var cloned = node.clone(); - if(!cloned) - { - console.warn("node type not found: " + node.type ); - continue; - } - clipboard_info.nodes.push(cloned.serialize()); - if (node.inputs && node.inputs.length) { - for (var j = 0; j < node.inputs.length; ++j) { - var input = node.inputs[j]; - if (!input || input.link == null) { - continue; - } - var link_info = this.graph.links[input.link]; - if (!link_info) { - continue; - } - var target_node = this.graph.getNodeById( - link_info.origin_id - ); - if (!target_node) { - continue; - } - clipboard_info.links.push([ - target_node._relative_id, - link_info.origin_slot, //j, - node._relative_id, - link_info.target_slot, - target_node.id - ]); - } - } - } - localStorage.setItem( - "litegrapheditor_clipboard", - JSON.stringify(clipboard_info) - ); - }; - - LGraphCanvas.prototype.pasteFromClipboard = function(isConnectUnselected = false) { - // if ctrl + shift + v is off, return when isConnectUnselected is true (shift is pressed) to maintain old behavior - if (!LiteGraph.ctrl_shift_v_paste_connect_unselected_outputs && isConnectUnselected) { - return; - } - var data = localStorage.getItem("litegrapheditor_clipboard"); - if (!data) { - return; - } - - this.graph.beforeChange(); - - //create nodes - var clipboard_info = JSON.parse(data); - // calculate top-left node, could work without this processing but using diff with last node pos :: clipboard_info.nodes[clipboard_info.nodes.length-1].pos - var posMin = false; - var posMinIndexes = false; - for (var i = 0; i < clipboard_info.nodes.length; ++i) { - if (posMin){ - if(posMin[0]>clipboard_info.nodes[i].pos[0]){ - posMin[0] = clipboard_info.nodes[i].pos[0]; - posMinIndexes[0] = i; - } - if(posMin[1]>clipboard_info.nodes[i].pos[1]){ - posMin[1] = clipboard_info.nodes[i].pos[1]; - posMinIndexes[1] = i; - } - } - else{ - posMin = [clipboard_info.nodes[i].pos[0], clipboard_info.nodes[i].pos[1]]; - posMinIndexes = [i, i]; - } - } - var nodes = []; - for (var i = 0; i < clipboard_info.nodes.length; ++i) { - var node_data = clipboard_info.nodes[i]; - var node = LiteGraph.createNode(node_data.type); - if (node) { - node.configure(node_data); - - //paste in last known mouse position - node.pos[0] += this.graph_mouse[0] - posMin[0]; //+= 5; - node.pos[1] += this.graph_mouse[1] - posMin[1]; //+= 5; - - this.graph.add(node,{doProcessChange:false}); - - nodes.push(node); - } - } - - //create links - for (var i = 0; i < clipboard_info.links.length; ++i) { - var link_info = clipboard_info.links[i]; - var origin_node = undefined; - var origin_node_relative_id = link_info[0]; - if (origin_node_relative_id != null) { - origin_node = nodes[origin_node_relative_id]; - } else if (LiteGraph.ctrl_shift_v_paste_connect_unselected_outputs && isConnectUnselected) { - var origin_node_id = link_info[4]; - if (origin_node_id) { - origin_node = this.graph.getNodeById(origin_node_id); - } - } - var target_node = nodes[link_info[2]]; - if( origin_node && target_node ) - origin_node.connect(link_info[1], target_node, link_info[3]); - else - console.warn("Warning, nodes missing on pasting"); - } - - this.selectNodes(nodes); - - this.graph.afterChange(); - }; - - /** - * process a item drop event on top the canvas - * @method processDrop - **/ - LGraphCanvas.prototype.processDrop = function(e) { - e.preventDefault(); - this.adjustMouseEvent(e); - var x = e.clientX; - var y = e.clientY; - var is_inside = !this.viewport || ( this.viewport && x >= this.viewport[0] && x < (this.viewport[0] + this.viewport[2]) && y >= this.viewport[1] && y < (this.viewport[1] + this.viewport[3]) ); - if(!is_inside){ - return; - // --- BREAK --- - } - - var pos = [e.canvasX, e.canvasY]; - - - var node = this.graph ? this.graph.getNodeOnPos(pos[0], pos[1]) : null; - - if (!node) { - var r = null; - if (this.onDropItem) { - r = this.onDropItem(event); - } - if (!r) { - this.checkDropItem(e); - } - return; - } - - if (node.onDropFile || node.onDropData) { - var files = e.dataTransfer.files; - if (files && files.length) { - for (var i = 0; i < files.length; i++) { - var file = e.dataTransfer.files[0]; - var filename = file.name; - var ext = LGraphCanvas.getFileExtension(filename); - //console.log(file); - - if (node.onDropFile) { - node.onDropFile(file); - } - - if (node.onDropData) { - //prepare reader - var reader = new FileReader(); - reader.onload = function(event) { - //console.log(event.target); - var data = event.target.result; - node.onDropData(data, filename, file); - }; - - //read data - var type = file.type.split("/")[0]; - if (type == "text" || type == "") { - reader.readAsText(file); - } else if (type == "image") { - reader.readAsDataURL(file); - } else { - reader.readAsArrayBuffer(file); - } - } - } - } - } - - if (node.onDropItem) { - if (node.onDropItem(event)) { - return true; - } - } - - if (this.onDropItem) { - return this.onDropItem(event); - } - - return false; - }; - - //called if the graph doesn't have a default drop item behaviour - LGraphCanvas.prototype.checkDropItem = function(e) { - if (e.dataTransfer.files.length) { - var file = e.dataTransfer.files[0]; - var ext = LGraphCanvas.getFileExtension(file.name).toLowerCase(); - var nodetype = LiteGraph.node_types_by_file_extension[ext]; - if (nodetype) { - this.graph.beforeChange(); - var node = LiteGraph.createNode(nodetype.type); - node.pos = [e.canvasX, e.canvasY]; - this.graph.add(node); - if (node.onDropFile) { - node.onDropFile(file); - } - this.graph.afterChange(); - } - } - }; - - LGraphCanvas.prototype.processNodeDblClicked = function(n) { - if (this.onShowNodePanel) { - this.onShowNodePanel(n); - } - - if (this.onNodeDblClicked) { - this.onNodeDblClicked(n); - } - - this.setDirty(true); - }; - - LGraphCanvas.prototype.processNodeSelected = function(node, e) { - this.selectNode(node, e && (e.shiftKey || e.ctrlKey || this.multi_select)); - if (this.onNodeSelected) { - this.onNodeSelected(node); - } - }; - - /** - * selects a given node (or adds it to the current selection) - * @method selectNode - **/ - LGraphCanvas.prototype.selectNode = function( - node, - add_to_current_selection - ) { - if (node == null) { - this.deselectAllNodes(); - } else { - this.selectNodes([node], add_to_current_selection); - } - }; - - /** - * selects several nodes (or adds them to the current selection) - * @method selectNodes - **/ - LGraphCanvas.prototype.selectNodes = function( nodes, add_to_current_selection ) - { - if (!add_to_current_selection) { - this.deselectAllNodes(); - } - - nodes = nodes || this.graph._nodes; - if (typeof nodes == "string") nodes = [nodes]; - for (var i in nodes) { - var node = nodes[i]; - if (node.is_selected) { - this.deselectNode(node); - continue; - } - - if (!node.is_selected && node.onSelected) { - node.onSelected(); - } - node.is_selected = true; - this.selected_nodes[node.id] = node; - - if (node.inputs) { - for (var j = 0; j < node.inputs.length; ++j) { - this.highlighted_links[node.inputs[j].link] = true; - } - } - if (node.outputs) { - for (var j = 0; j < node.outputs.length; ++j) { - var out = node.outputs[j]; - if (out.links) { - for (var k = 0; k < out.links.length; ++k) { - this.highlighted_links[out.links[k]] = true; - } - } - } - } - } - - if( this.onSelectionChange ) - this.onSelectionChange( this.selected_nodes ); - - this.setDirty(true); - }; - - /** - * removes a node from the current selection - * @method deselectNode - **/ - LGraphCanvas.prototype.deselectNode = function(node) { - if (!node.is_selected) { - return; - } - if (node.onDeselected) { - node.onDeselected(); - } - node.is_selected = false; - - if (this.onNodeDeselected) { - this.onNodeDeselected(node); - } - - //remove highlighted - if (node.inputs) { - for (var i = 0; i < node.inputs.length; ++i) { - delete this.highlighted_links[node.inputs[i].link]; - } - } - if (node.outputs) { - for (var i = 0; i < node.outputs.length; ++i) { - var out = node.outputs[i]; - if (out.links) { - for (var j = 0; j < out.links.length; ++j) { - delete this.highlighted_links[out.links[j]]; - } - } - } - } - }; - - /** - * removes all nodes from the current selection - * @method deselectAllNodes - **/ - LGraphCanvas.prototype.deselectAllNodes = function() { - if (!this.graph) { - return; - } - var nodes = this.graph._nodes; - for (var i = 0, l = nodes.length; i < l; ++i) { - var node = nodes[i]; - if (!node.is_selected) { - continue; - } - if (node.onDeselected) { - node.onDeselected(); - } - node.is_selected = false; - if (this.onNodeDeselected) { - this.onNodeDeselected(node); - } - } - this.selected_nodes = {}; - this.current_node = null; - this.highlighted_links = {}; - if( this.onSelectionChange ) - this.onSelectionChange( this.selected_nodes ); - this.setDirty(true); - }; - - /** - * deletes all nodes in the current selection from the graph - * @method deleteSelectedNodes - **/ - LGraphCanvas.prototype.deleteSelectedNodes = function() { - - this.graph.beforeChange(); - - for (var i in this.selected_nodes) { - var node = this.selected_nodes[i]; - - if(node.block_delete) - continue; - - //autoconnect when possible (very basic, only takes into account first input-output) - if(node.inputs && node.inputs.length && node.outputs && node.outputs.length && LiteGraph.isValidConnection( node.inputs[0].type, node.outputs[0].type ) && node.inputs[0].link && node.outputs[0].links && node.outputs[0].links.length ) - { - var input_link = node.graph.links[ node.inputs[0].link ]; - var output_link = node.graph.links[ node.outputs[0].links[0] ]; - var input_node = node.getInputNode(0); - var output_node = node.getOutputNodes(0)[0]; - if(input_node && output_node) - input_node.connect( input_link.origin_slot, output_node, output_link.target_slot ); - } - this.graph.remove(node); - if (this.onNodeDeselected) { - this.onNodeDeselected(node); - } - } - this.selected_nodes = {}; - this.current_node = null; - this.highlighted_links = {}; - this.setDirty(true); - this.graph.afterChange(); - }; - - /** - * centers the camera on a given node - * @method centerOnNode - **/ - LGraphCanvas.prototype.centerOnNode = function(node) { - this.ds.offset[0] = - -node.pos[0] - - node.size[0] * 0.5 + - (this.canvas.width * 0.5) / this.ds.scale; - this.ds.offset[1] = - -node.pos[1] - - node.size[1] * 0.5 + - (this.canvas.height * 0.5) / this.ds.scale; - this.setDirty(true, true); - }; - - /** - * adds some useful properties to a mouse event, like the position in graph coordinates - * @method adjustMouseEvent - **/ - LGraphCanvas.prototype.adjustMouseEvent = function(e) { - var clientX_rel = 0; - var clientY_rel = 0; - - if (this.canvas) { - var b = this.canvas.getBoundingClientRect(); - clientX_rel = e.clientX - b.left; - clientY_rel = e.clientY - b.top; - } else { - clientX_rel = e.clientX; - clientY_rel = e.clientY; - } - - e.deltaX = clientX_rel - this.last_mouse_position[0]; - e.deltaY = clientY_rel- this.last_mouse_position[1]; - - this.last_mouse_position[0] = clientX_rel; - this.last_mouse_position[1] = clientY_rel; - - e.canvasX = clientX_rel / this.ds.scale - this.ds.offset[0]; - e.canvasY = clientY_rel / this.ds.scale - this.ds.offset[1]; - - //console.log("pointerevents: adjustMouseEvent "+e.clientX+":"+e.clientY+" "+clientX_rel+":"+clientY_rel+" "+e.canvasX+":"+e.canvasY); - }; - - /** - * changes the zoom level of the graph (default is 1), you can pass also a place used to pivot the zoom - * @method setZoom - **/ - LGraphCanvas.prototype.setZoom = function(value, zooming_center) { - this.ds.changeScale(value, zooming_center); - /* - if(!zooming_center && this.canvas) - zooming_center = [this.canvas.width * 0.5,this.canvas.height * 0.5]; - - var center = this.convertOffsetToCanvas( zooming_center ); - - this.ds.scale = value; - - if(this.scale > this.max_zoom) - this.scale = this.max_zoom; - else if(this.scale < this.min_zoom) - this.scale = this.min_zoom; - - var new_center = this.convertOffsetToCanvas( zooming_center ); - var delta_offset = [new_center[0] - center[0], new_center[1] - center[1]]; - - this.offset[0] += delta_offset[0]; - this.offset[1] += delta_offset[1]; - */ - - this.dirty_canvas = true; - this.dirty_bgcanvas = true; - }; - - /** - * converts a coordinate from graph coordinates to canvas2D coordinates - * @method convertOffsetToCanvas - **/ - LGraphCanvas.prototype.convertOffsetToCanvas = function(pos, out) { - return this.ds.convertOffsetToCanvas(pos, out); - }; - - /** - * converts a coordinate from Canvas2D coordinates to graph space - * @method convertCanvasToOffset - **/ - LGraphCanvas.prototype.convertCanvasToOffset = function(pos, out) { - return this.ds.convertCanvasToOffset(pos, out); - }; - - //converts event coordinates from canvas2D to graph coordinates - LGraphCanvas.prototype.convertEventToCanvasOffset = function(e) { - var rect = this.canvas.getBoundingClientRect(); - return this.convertCanvasToOffset([ - e.clientX - rect.left, - e.clientY - rect.top - ]); - }; - - /** - * brings a node to front (above all other nodes) - * @method bringToFront - **/ - LGraphCanvas.prototype.bringToFront = function(node) { - var i = this.graph._nodes.indexOf(node); - if (i == -1) { - return; - } - - this.graph._nodes.splice(i, 1); - this.graph._nodes.push(node); - }; - - /** - * sends a node to the back (below all other nodes) - * @method sendToBack - **/ - LGraphCanvas.prototype.sendToBack = function(node) { - var i = this.graph._nodes.indexOf(node); - if (i == -1) { - return; - } - - this.graph._nodes.splice(i, 1); - this.graph._nodes.unshift(node); - }; - - /* Interaction */ - - /* LGraphCanvas render */ - var temp = new Float32Array(4); - - /** - * checks which nodes are visible (inside the camera area) - * @method computeVisibleNodes - **/ - LGraphCanvas.prototype.computeVisibleNodes = function(nodes, out) { - var visible_nodes = out || []; - visible_nodes.length = 0; - nodes = nodes || this.graph._nodes; - for (var i = 0, l = nodes.length; i < l; ++i) { - var n = nodes[i]; - - //skip rendering nodes in live mode - if (this.live_mode && !n.onDrawBackground && !n.onDrawForeground) { - continue; - } - - if (!overlapBounding(this.visible_area, n.getBounding(temp, true))) { - continue; - } //out of the visible area - - visible_nodes.push(n); - } - return visible_nodes; - }; - - /** - * renders the whole canvas content, by rendering in two separated canvas, one containing the background grid and the connections, and one containing the nodes) - * @method draw - **/ - LGraphCanvas.prototype.draw = function(force_canvas, force_bgcanvas) { - if (!this.canvas || this.canvas.width == 0 || this.canvas.height == 0) { - return; - } - - //fps counting - var now = LiteGraph.getTime(); - this.render_time = (now - this.last_draw_time) * 0.001; - this.last_draw_time = now; - - if (this.graph) { - this.ds.computeVisibleArea(this.viewport); - } - - if ( - this.dirty_bgcanvas || - force_bgcanvas || - this.always_render_background || - (this.graph && - this.graph._last_trigger_time && - now - this.graph._last_trigger_time < 1000) - ) { - this.drawBackCanvas(); - } - - if (this.dirty_canvas || force_canvas) { - this.drawFrontCanvas(); - } - - this.fps = this.render_time ? 1.0 / this.render_time : 0; - this.frame += 1; - }; - - /** - * draws the front canvas (the one containing all the nodes) - * @method drawFrontCanvas - **/ - LGraphCanvas.prototype.drawFrontCanvas = function() { - this.dirty_canvas = false; - - if (!this.ctx) { - this.ctx = this.bgcanvas.getContext("2d"); - } - var ctx = this.ctx; - if (!ctx) { - //maybe is using webgl... - return; - } - - var canvas = this.canvas; - if ( ctx.start2D && !this.viewport ) { - ctx.start2D(); - ctx.restore(); - ctx.setTransform(1, 0, 0, 1, 0, 0); - } - - //clip dirty area if there is one, otherwise work in full canvas - var area = this.viewport || this.dirty_area; - if (area) { - ctx.save(); - ctx.beginPath(); - ctx.rect( area[0],area[1],area[2],area[3] ); - ctx.clip(); - } - - //clear - //canvas.width = canvas.width; - if (this.clear_background) { - if(area) - ctx.clearRect( area[0],area[1],area[2],area[3] ); - else - ctx.clearRect(0, 0, canvas.width, canvas.height); - } - - //draw bg canvas - if (this.bgcanvas == this.canvas) { - this.drawBackCanvas(); - } else { - ctx.drawImage( this.bgcanvas, 0, 0 ); - } - - //rendering - if (this.onRender) { - this.onRender(canvas, ctx); - } - - //info widget - if (this.show_info) { - this.renderInfo(ctx, area ? area[0] : 0, area ? area[1] : 0 ); - } - - if (this.graph) { - //apply transformations - ctx.save(); - this.ds.toCanvasContext(ctx); - - //draw nodes - var drawn_nodes = 0; - var visible_nodes = this.computeVisibleNodes( - null, - this.visible_nodes - ); - - for (var i = 0; i < visible_nodes.length; ++i) { - var node = visible_nodes[i]; - - //transform coords system - ctx.save(); - ctx.translate(node.pos[0], node.pos[1]); - - //Draw - this.drawNode(node, ctx); - drawn_nodes += 1; - - //Restore - ctx.restore(); - } - - //on top (debug) - if (this.render_execution_order) { - this.drawExecutionOrder(ctx); - } - - //connections ontop? - if (this.graph.config.links_ontop) { - if (!this.live_mode) { - this.drawConnections(ctx); - } - } - - //current connection (the one being dragged by the mouse) - if (this.connecting_pos != null) { - ctx.lineWidth = this.connections_width; - var link_color = null; - - var connInOrOut = this.connecting_output || this.connecting_input; - - var connType = connInOrOut.type; - var connDir = connInOrOut.dir; - if(connDir == null) - { - if (this.connecting_output) - connDir = this.connecting_node.horizontal ? LiteGraph.DOWN : LiteGraph.RIGHT; - else - connDir = this.connecting_node.horizontal ? LiteGraph.UP : LiteGraph.LEFT; - } - var connShape = connInOrOut.shape; - - switch (connType) { - case LiteGraph.EVENT: - link_color = LiteGraph.EVENT_LINK_COLOR; - break; - default: - link_color = LiteGraph.CONNECTING_LINK_COLOR; - } - - //the connection being dragged by the mouse - this.renderLink( - ctx, - this.connecting_pos, - [this.graph_mouse[0], this.graph_mouse[1]], - null, - false, - null, - link_color, - connDir, - LiteGraph.CENTER - ); - - ctx.beginPath(); - if ( - connType === LiteGraph.EVENT || - connShape === LiteGraph.BOX_SHAPE - ) { - ctx.rect( - this.connecting_pos[0] - 6 + 0.5, - this.connecting_pos[1] - 5 + 0.5, - 14, - 10 - ); - ctx.fill(); - ctx.beginPath(); - ctx.rect( - this.graph_mouse[0] - 6 + 0.5, - this.graph_mouse[1] - 5 + 0.5, - 14, - 10 - ); - } else if (connShape === LiteGraph.ARROW_SHAPE) { - ctx.moveTo(this.connecting_pos[0] + 8, this.connecting_pos[1] + 0.5); - ctx.lineTo(this.connecting_pos[0] - 4, this.connecting_pos[1] + 6 + 0.5); - ctx.lineTo(this.connecting_pos[0] - 4, this.connecting_pos[1] - 6 + 0.5); - ctx.closePath(); - } - else { - ctx.arc( - this.connecting_pos[0], - this.connecting_pos[1], - 4, - 0, - Math.PI * 2 - ); - ctx.fill(); - ctx.beginPath(); - ctx.arc( - this.graph_mouse[0], - this.graph_mouse[1], - 4, - 0, - Math.PI * 2 - ); - } - ctx.fill(); - - ctx.fillStyle = "#ffcc00"; - if (this._highlight_input) { - ctx.beginPath(); - var shape = this._highlight_input_slot.shape; - if (shape === LiteGraph.ARROW_SHAPE) { - ctx.moveTo(this._highlight_input[0] + 8, this._highlight_input[1] + 0.5); - ctx.lineTo(this._highlight_input[0] - 4, this._highlight_input[1] + 6 + 0.5); - ctx.lineTo(this._highlight_input[0] - 4, this._highlight_input[1] - 6 + 0.5); - ctx.closePath(); - } else { - ctx.arc( - this._highlight_input[0], - this._highlight_input[1], - 6, - 0, - Math.PI * 2 - ); - } - ctx.fill(); - } - if (this._highlight_output) { - ctx.beginPath(); - if (shape === LiteGraph.ARROW_SHAPE) { - ctx.moveTo(this._highlight_output[0] + 8, this._highlight_output[1] + 0.5); - ctx.lineTo(this._highlight_output[0] - 4, this._highlight_output[1] + 6 + 0.5); - ctx.lineTo(this._highlight_output[0] - 4, this._highlight_output[1] - 6 + 0.5); - ctx.closePath(); - } else { - ctx.arc( - this._highlight_output[0], - this._highlight_output[1], - 6, - 0, - Math.PI * 2 - ); - } - ctx.fill(); - } - } - - //the selection rectangle - if (this.dragging_rectangle) { - ctx.strokeStyle = "#FFF"; - ctx.strokeRect( - this.dragging_rectangle[0], - this.dragging_rectangle[1], - this.dragging_rectangle[2], - this.dragging_rectangle[3] - ); - } - - //on top of link center - if(this.over_link_center && this.render_link_tooltip) - this.drawLinkTooltip( ctx, this.over_link_center ); - else - if(this.onDrawLinkTooltip) //to remove - this.onDrawLinkTooltip(ctx,null); - - //custom info - if (this.onDrawForeground) { - this.onDrawForeground(ctx, this.visible_rect); - } - - ctx.restore(); - } - - //draws panel in the corner - if (this._graph_stack && this._graph_stack.length) { - this.drawSubgraphPanel( ctx ); - } - - - if (this.onDrawOverlay) { - this.onDrawOverlay(ctx); - } - - if (area){ - ctx.restore(); - } - - if (ctx.finish2D) { - //this is a function I use in webgl renderer - ctx.finish2D(); - } - }; - - /** - * draws the panel in the corner that shows subgraph properties - * @method drawSubgraphPanel - **/ - LGraphCanvas.prototype.drawSubgraphPanel = function (ctx) { - var subgraph = this.graph; - var subnode = subgraph._subgraph_node; - if (!subnode) { - console.warn("subgraph without subnode"); - return; - } - this.drawSubgraphPanelLeft(subgraph, subnode, ctx) - this.drawSubgraphPanelRight(subgraph, subnode, ctx) - } - - LGraphCanvas.prototype.drawSubgraphPanelLeft = function (subgraph, subnode, ctx) { - var num = subnode.inputs ? subnode.inputs.length : 0; - var w = 200; - var h = Math.floor(LiteGraph.NODE_SLOT_HEIGHT * 1.6); - - ctx.fillStyle = "#111"; - ctx.globalAlpha = 0.8; - ctx.beginPath(); - ctx.roundRect(10, 10, w, (num + 1) * h + 50, [8]); - ctx.fill(); - ctx.globalAlpha = 1; - - ctx.fillStyle = "#888"; - ctx.font = "14px Arial"; - ctx.textAlign = "left"; - ctx.fillText("Graph Inputs", 20, 34); - // var pos = this.mouse; - - if (this.drawButton(w - 20, 20, 20, 20, "X", "#151515")) { - this.closeSubgraph(); - return; - } - - var y = 50; - ctx.font = "14px Arial"; - if (subnode.inputs) - for (var i = 0; i < subnode.inputs.length; ++i) { - var input = subnode.inputs[i]; - if (input.not_subgraph_input) - continue; - - //input button clicked - if (this.drawButton(20, y + 2, w - 20, h - 2)) { - var type = subnode.constructor.input_node_type || "graph/input"; - this.graph.beforeChange(); - var newnode = LiteGraph.createNode(type); - if (newnode) { - subgraph.add(newnode); - this.block_click = false; - this.last_click_position = null; - this.selectNodes([newnode]); - this.node_dragged = newnode; - this.dragging_canvas = false; - newnode.setProperty("name", input.name); - newnode.setProperty("type", input.type); - this.node_dragged.pos[0] = this.graph_mouse[0] - 5; - this.node_dragged.pos[1] = this.graph_mouse[1] - 5; - this.graph.afterChange(); - } - else - console.error("graph input node not found:", type); - } - ctx.fillStyle = "#9C9"; - ctx.beginPath(); - ctx.arc(w - 16, y + h * 0.5, 5, 0, 2 * Math.PI); - ctx.fill(); - ctx.fillStyle = "#AAA"; - ctx.fillText(input.name, 30, y + h * 0.75); - // var tw = ctx.measureText(input.name); - ctx.fillStyle = "#777"; - ctx.fillText(input.type, 130, y + h * 0.75); - y += h; - } - //add + button - if (this.drawButton(20, y + 2, w - 20, h - 2, "+", "#151515", "#222")) { - this.showSubgraphPropertiesDialog(subnode); - } - } - LGraphCanvas.prototype.drawSubgraphPanelRight = function (subgraph, subnode, ctx) { - var num = subnode.outputs ? subnode.outputs.length : 0; - var canvas_w = this.bgcanvas.width - var w = 200; - var h = Math.floor(LiteGraph.NODE_SLOT_HEIGHT * 1.6); - - ctx.fillStyle = "#111"; - ctx.globalAlpha = 0.8; - ctx.beginPath(); - ctx.roundRect(canvas_w - w - 10, 10, w, (num + 1) * h + 50, [8]); - ctx.fill(); - ctx.globalAlpha = 1; - - ctx.fillStyle = "#888"; - ctx.font = "14px Arial"; - ctx.textAlign = "left"; - var title_text = "Graph Outputs" - var tw = ctx.measureText(title_text).width - ctx.fillText(title_text, (canvas_w - tw) - 20, 34); - // var pos = this.mouse; - if (this.drawButton(canvas_w - w, 20, 20, 20, "X", "#151515")) { - this.closeSubgraph(); - return; - } - - var y = 50; - ctx.font = "14px Arial"; - if (subnode.outputs) - for (var i = 0; i < subnode.outputs.length; ++i) { - var output = subnode.outputs[i]; - if (output.not_subgraph_input) - continue; - - //output button clicked - if (this.drawButton(canvas_w - w, y + 2, w - 20, h - 2)) { - var type = subnode.constructor.output_node_type || "graph/output"; - this.graph.beforeChange(); - var newnode = LiteGraph.createNode(type); - if (newnode) { - subgraph.add(newnode); - this.block_click = false; - this.last_click_position = null; - this.selectNodes([newnode]); - this.node_dragged = newnode; - this.dragging_canvas = false; - newnode.setProperty("name", output.name); - newnode.setProperty("type", output.type); - this.node_dragged.pos[0] = this.graph_mouse[0] - 5; - this.node_dragged.pos[1] = this.graph_mouse[1] - 5; - this.graph.afterChange(); - } - else - console.error("graph input node not found:", type); - } - ctx.fillStyle = "#9C9"; - ctx.beginPath(); - ctx.arc(canvas_w - w + 16, y + h * 0.5, 5, 0, 2 * Math.PI); - ctx.fill(); - ctx.fillStyle = "#AAA"; - ctx.fillText(output.name, canvas_w - w + 30, y + h * 0.75); - // var tw = ctx.measureText(input.name); - ctx.fillStyle = "#777"; - ctx.fillText(output.type, canvas_w - w + 130, y + h * 0.75); - y += h; - } - //add + button - if (this.drawButton(canvas_w - w, y + 2, w - 20, h - 2, "+", "#151515", "#222")) { - this.showSubgraphPropertiesDialogRight(subnode); - } - } - //Draws a button into the canvas overlay and computes if it was clicked using the immediate gui paradigm - LGraphCanvas.prototype.drawButton = function( x,y,w,h, text, bgcolor, hovercolor, textcolor ) - { - var ctx = this.ctx; - bgcolor = bgcolor || LiteGraph.NODE_DEFAULT_COLOR; - hovercolor = hovercolor || "#555"; - textcolor = textcolor || LiteGraph.NODE_TEXT_COLOR; - var pos = this.ds.convertOffsetToCanvas(this.graph_mouse); - var hover = LiteGraph.isInsideRectangle( pos[0], pos[1], x,y,w,h ); - pos = this.last_click_position ? [this.last_click_position[0], this.last_click_position[1]] : null; - if(pos) { - var rect = this.canvas.getBoundingClientRect(); - pos[0] -= rect.left; - pos[1] -= rect.top; - } - var clicked = pos && LiteGraph.isInsideRectangle( pos[0], pos[1], x,y,w,h ); - - ctx.fillStyle = hover ? hovercolor : bgcolor; - if(clicked) - ctx.fillStyle = "#AAA"; - ctx.beginPath(); - ctx.roundRect(x,y,w,h,[4] ); - ctx.fill(); - - if(text != null) - { - if(text.constructor == String) - { - ctx.fillStyle = textcolor; - ctx.textAlign = "center"; - ctx.font = ((h * 0.65)|0) + "px Arial"; - ctx.fillText( text, x + w * 0.5,y + h * 0.75 ); - ctx.textAlign = "left"; - } - } - - var was_clicked = clicked && !this.block_click; - if(clicked) - this.blockClick(); - return was_clicked; - } - - LGraphCanvas.prototype.isAreaClicked = function( x,y,w,h, hold_click ) - { - var pos = this.mouse; - var hover = LiteGraph.isInsideRectangle( pos[0], pos[1], x,y,w,h ); - pos = this.last_click_position; - var clicked = pos && LiteGraph.isInsideRectangle( pos[0], pos[1], x,y,w,h ); - var was_clicked = clicked && !this.block_click; - if(clicked && hold_click) - this.blockClick(); - return was_clicked; - } - - /** - * draws some useful stats in the corner of the canvas - * @method renderInfo - **/ - LGraphCanvas.prototype.renderInfo = function(ctx, x, y) { - x = x || 10; - y = y || this.canvas.offsetHeight - 80; - - ctx.save(); - ctx.translate(x, y); - - ctx.font = "10px Arial"; - ctx.fillStyle = "#888"; - ctx.textAlign = "left"; - if (this.graph) { - ctx.fillText( "T: " + this.graph.globaltime.toFixed(2) + "s", 5, 13 * 1 ); - ctx.fillText("I: " + this.graph.iteration, 5, 13 * 2 ); - ctx.fillText("N: " + this.graph._nodes.length + " [" + this.visible_nodes.length + "]", 5, 13 * 3 ); - ctx.fillText("V: " + this.graph._version, 5, 13 * 4); - ctx.fillText("FPS:" + this.fps.toFixed(2), 5, 13 * 5); - } else { - ctx.fillText("No graph selected", 5, 13 * 1); - } - ctx.restore(); - }; - - /** - * draws the back canvas (the one containing the background and the connections) - * @method drawBackCanvas - **/ - LGraphCanvas.prototype.drawBackCanvas = function() { - var canvas = this.bgcanvas; - if ( - canvas.width != this.canvas.width || - canvas.height != this.canvas.height - ) { - canvas.width = this.canvas.width; - canvas.height = this.canvas.height; - } - - if (!this.bgctx) { - this.bgctx = this.bgcanvas.getContext("2d"); - } - var ctx = this.bgctx; - if (ctx.start) { - ctx.start(); - } - - var viewport = this.viewport || [0,0,ctx.canvas.width,ctx.canvas.height]; - - //clear - if (this.clear_background) { - ctx.clearRect( viewport[0], viewport[1], viewport[2], viewport[3] ); - } - - //show subgraph stack header - if (this._graph_stack && this._graph_stack.length) { - ctx.save(); - var parent_graph = this._graph_stack[this._graph_stack.length - 1]; - var subgraph_node = this.graph._subgraph_node; - ctx.strokeStyle = subgraph_node.bgcolor; - ctx.lineWidth = 10; - ctx.strokeRect(1, 1, canvas.width - 2, canvas.height - 2); - ctx.lineWidth = 1; - ctx.font = "40px Arial"; - ctx.textAlign = "center"; - ctx.fillStyle = subgraph_node.bgcolor || "#AAA"; - var title = ""; - for (var i = 1; i < this._graph_stack.length; ++i) { - title += - this._graph_stack[i]._subgraph_node.getTitle() + " >> "; - } - ctx.fillText( - title + subgraph_node.getTitle(), - canvas.width * 0.5, - 40 - ); - ctx.restore(); - } - - var bg_already_painted = false; - if (this.onRenderBackground) { - bg_already_painted = this.onRenderBackground(canvas, ctx); - } - - //reset in case of error - if ( !this.viewport ) - { - ctx.restore(); - ctx.setTransform(1, 0, 0, 1, 0, 0); - } - this.visible_links.length = 0; - - if (this.graph) { - //apply transformations - ctx.save(); - this.ds.toCanvasContext(ctx); - - //render BG - if ( this.ds.scale < 1.5 && !bg_already_painted && this.clear_background_color ) - { - ctx.fillStyle = this.clear_background_color; - ctx.fillRect( - this.visible_area[0], - this.visible_area[1], - this.visible_area[2], - this.visible_area[3] - ); - } - - if ( - this.background_image && - this.ds.scale > 0.5 && - !bg_already_painted - ) { - if (this.zoom_modify_alpha) { - ctx.globalAlpha = - (1.0 - 0.5 / this.ds.scale) * this.editor_alpha; - } else { - ctx.globalAlpha = this.editor_alpha; - } - ctx.imageSmoothingEnabled = ctx.imageSmoothingEnabled = false; // ctx.mozImageSmoothingEnabled = - if ( - !this._bg_img || - this._bg_img.name != this.background_image - ) { - this._bg_img = new Image(); - this._bg_img.name = this.background_image; - this._bg_img.src = this.background_image; - var that = this; - this._bg_img.onload = function() { - that.draw(true, true); - }; - } - - var pattern = null; - if (this._pattern == null && this._bg_img.width > 0) { - pattern = ctx.createPattern(this._bg_img, "repeat"); - this._pattern_img = this._bg_img; - this._pattern = pattern; - } else { - pattern = this._pattern; - } - if (pattern) { - ctx.fillStyle = pattern; - ctx.fillRect( - this.visible_area[0], - this.visible_area[1], - this.visible_area[2], - this.visible_area[3] - ); - ctx.fillStyle = "transparent"; - } - - ctx.globalAlpha = 1.0; - ctx.imageSmoothingEnabled = ctx.imageSmoothingEnabled = true; //= ctx.mozImageSmoothingEnabled - } - - //groups - if (this.graph._groups.length && !this.live_mode) { - this.drawGroups(canvas, ctx); - } - - if (this.onDrawBackground) { - this.onDrawBackground(ctx, this.visible_area); - } - if (this.onBackgroundRender) { - //LEGACY - console.error( - "WARNING! onBackgroundRender deprecated, now is named onDrawBackground " - ); - this.onBackgroundRender = null; - } - - //DEBUG: show clipping area - //ctx.fillStyle = "red"; - //ctx.fillRect( this.visible_area[0] + 10, this.visible_area[1] + 10, this.visible_area[2] - 20, this.visible_area[3] - 20); - - //bg - if (this.render_canvas_border) { - ctx.strokeStyle = "#235"; - ctx.strokeRect(0, 0, canvas.width, canvas.height); - } - - if (this.render_connections_shadows) { - ctx.shadowColor = "#000"; - ctx.shadowOffsetX = 0; - ctx.shadowOffsetY = 0; - ctx.shadowBlur = 6; - } else { - ctx.shadowColor = "rgba(0,0,0,0)"; - } - - //draw connections - if (!this.live_mode) { - this.drawConnections(ctx); - } - - ctx.shadowColor = "rgba(0,0,0,0)"; - - //restore state - ctx.restore(); - } - - if (ctx.finish) { - ctx.finish(); - } - - this.dirty_bgcanvas = false; - this.dirty_canvas = true; //to force to repaint the front canvas with the bgcanvas - }; - - var temp_vec2 = new Float32Array(2); - - /** - * draws the given node inside the canvas - * @method drawNode - **/ - LGraphCanvas.prototype.drawNode = function(node, ctx) { - var glow = false; - this.current_node = node; - - var color = node.color || node.constructor.color || LiteGraph.NODE_DEFAULT_COLOR; - var bgcolor = node.bgcolor || node.constructor.bgcolor || LiteGraph.NODE_DEFAULT_BGCOLOR; - - //shadow and glow - if (node.mouseOver) { - glow = true; - } - - var low_quality = this.ds.scale < 0.6; //zoomed out - - //only render if it forces it to do it - if (this.live_mode) { - if (!node.flags.collapsed) { - ctx.shadowColor = "transparent"; - if (node.onDrawForeground) { - node.onDrawForeground(ctx, this, this.canvas); - } - } - return; - } - - var editor_alpha = this.editor_alpha; - ctx.globalAlpha = editor_alpha; - - if (this.render_shadows && !low_quality) { - ctx.shadowColor = LiteGraph.DEFAULT_SHADOW_COLOR; - ctx.shadowOffsetX = 2 * this.ds.scale; - ctx.shadowOffsetY = 2 * this.ds.scale; - ctx.shadowBlur = 3 * this.ds.scale; - } else { - ctx.shadowColor = "transparent"; - } - - //custom draw collapsed method (draw after shadows because they are affected) - if ( - node.flags.collapsed && - node.onDrawCollapsed && - node.onDrawCollapsed(ctx, this) == true - ) { - return; - } - - //clip if required (mask) - var shape = node._shape || LiteGraph.BOX_SHAPE; - var size = temp_vec2; - temp_vec2.set(node.size); - var horizontal = node.horizontal; // || node.flags.horizontal; - - if (node.flags.collapsed) { - ctx.font = this.inner_text_font; - var title = node.getTitle ? node.getTitle() : node.title; - if (title != null) { - node._collapsed_width = Math.min( - node.size[0], - ctx.measureText(title).width + - LiteGraph.NODE_TITLE_HEIGHT * 2 - ); //LiteGraph.NODE_COLLAPSED_WIDTH; - size[0] = node._collapsed_width; - size[1] = 0; - } - } - - if (node.clip_area) { - //Start clipping - ctx.save(); - ctx.beginPath(); - if (shape == LiteGraph.BOX_SHAPE) { - ctx.rect(0, 0, size[0], size[1]); - } else if (shape == LiteGraph.ROUND_SHAPE) { - ctx.roundRect(0, 0, size[0], size[1], [10]); - } else if (shape == LiteGraph.CIRCLE_SHAPE) { - ctx.arc( - size[0] * 0.5, - size[1] * 0.5, - size[0] * 0.5, - 0, - Math.PI * 2 - ); - } - ctx.clip(); - } - - //draw shape - if (node.has_errors) { - bgcolor = "red"; - } - this.drawNodeShape( - node, - ctx, - size, - color, - bgcolor, - node.is_selected, - node.mouseOver - ); - ctx.shadowColor = "transparent"; - - //draw foreground - if (node.onDrawForeground) { - node.onDrawForeground(ctx, this, this.canvas); - } - - //connection slots - ctx.textAlign = horizontal ? "center" : "left"; - ctx.font = this.inner_text_font; - - var render_text = !low_quality; - - var out_slot = this.connecting_output; - var in_slot = this.connecting_input; - ctx.lineWidth = 1; - - var max_y = 0; - var slot_pos = new Float32Array(2); //to reuse - - //render inputs and outputs - if (!node.flags.collapsed) { - //input connection slots - if (node.inputs) { - for (var i = 0; i < node.inputs.length; i++) { - var slot = node.inputs[i]; - - var slot_type = slot.type; - var slot_shape = slot.shape; - - ctx.globalAlpha = editor_alpha; - //change opacity of incompatible slots when dragging a connection - if ( this.connecting_output && !LiteGraph.isValidConnection( slot.type , out_slot.type) ) { - ctx.globalAlpha = 0.4 * editor_alpha; - } - - ctx.fillStyle = - slot.link != null - ? slot.color_on || - this.default_connection_color_byType[slot_type] || - this.default_connection_color.input_on - : slot.color_off || - this.default_connection_color_byTypeOff[slot_type] || - this.default_connection_color_byType[slot_type] || - this.default_connection_color.input_off; - - var pos = node.getConnectionPos(true, i, slot_pos); - pos[0] -= node.pos[0]; - pos[1] -= node.pos[1]; - if (max_y < pos[1] + LiteGraph.NODE_SLOT_HEIGHT * 0.5) { - max_y = pos[1] + LiteGraph.NODE_SLOT_HEIGHT * 0.5; - } - - ctx.beginPath(); - - if (slot_type == "array"){ - slot_shape = LiteGraph.GRID_SHAPE; // place in addInput? addOutput instead? - } - - var doStroke = true; - - if ( - slot.type === LiteGraph.EVENT || - slot.shape === LiteGraph.BOX_SHAPE - ) { - if (horizontal) { - ctx.rect( - pos[0] - 5 + 0.5, - pos[1] - 8 + 0.5, - 10, - 14 - ); - } else { - ctx.rect( - pos[0] - 6 + 0.5, - pos[1] - 5 + 0.5, - 14, - 10 - ); - } - } else if (slot_shape === LiteGraph.ARROW_SHAPE) { - ctx.moveTo(pos[0] + 8, pos[1] + 0.5); - ctx.lineTo(pos[0] - 4, pos[1] + 6 + 0.5); - ctx.lineTo(pos[0] - 4, pos[1] - 6 + 0.5); - ctx.closePath(); - } else if (slot_shape === LiteGraph.GRID_SHAPE) { - ctx.rect(pos[0] - 4, pos[1] - 4, 2, 2); - ctx.rect(pos[0] - 1, pos[1] - 4, 2, 2); - ctx.rect(pos[0] + 2, pos[1] - 4, 2, 2); - ctx.rect(pos[0] - 4, pos[1] - 1, 2, 2); - ctx.rect(pos[0] - 1, pos[1] - 1, 2, 2); - ctx.rect(pos[0] + 2, pos[1] - 1, 2, 2); - ctx.rect(pos[0] - 4, pos[1] + 2, 2, 2); - ctx.rect(pos[0] - 1, pos[1] + 2, 2, 2); - ctx.rect(pos[0] + 2, pos[1] + 2, 2, 2); - doStroke = false; - } else { - if(low_quality) - ctx.rect(pos[0] - 4, pos[1] - 4, 8, 8 ); //faster - else - ctx.arc(pos[0], pos[1], 4, 0, Math.PI * 2); - } - ctx.fill(); - - //render name - if (render_text) { - var text = slot.label != null ? slot.label : slot.name; - if (text) { - ctx.fillStyle = LiteGraph.NODE_TEXT_COLOR; - if (horizontal || slot.dir == LiteGraph.UP) { - ctx.fillText(text, pos[0], pos[1] - 10); - } else { - ctx.fillText(text, pos[0] + 10, pos[1] + 5); - } - } - } - } - } - - //output connection slots - - ctx.textAlign = horizontal ? "center" : "right"; - ctx.strokeStyle = "black"; - if (node.outputs) { - for (var i = 0; i < node.outputs.length; i++) { - var slot = node.outputs[i]; - - var slot_type = slot.type; - var slot_shape = slot.shape; - - //change opacity of incompatible slots when dragging a connection - if (this.connecting_input && !LiteGraph.isValidConnection( slot_type , in_slot.type) ) { - ctx.globalAlpha = 0.4 * editor_alpha; - } - - var pos = node.getConnectionPos(false, i, slot_pos); - pos[0] -= node.pos[0]; - pos[1] -= node.pos[1]; - if (max_y < pos[1] + LiteGraph.NODE_SLOT_HEIGHT * 0.5) { - max_y = pos[1] + LiteGraph.NODE_SLOT_HEIGHT * 0.5; - } - - ctx.fillStyle = - slot.links && slot.links.length - ? slot.color_on || - this.default_connection_color_byType[slot_type] || - this.default_connection_color.output_on - : slot.color_off || - this.default_connection_color_byTypeOff[slot_type] || - this.default_connection_color_byType[slot_type] || - this.default_connection_color.output_off; - ctx.beginPath(); - //ctx.rect( node.size[0] - 14,i*14,10,10); - - if (slot_type == "array"){ - slot_shape = LiteGraph.GRID_SHAPE; - } - - var doStroke = true; - - if ( - slot_type === LiteGraph.EVENT || - slot_shape === LiteGraph.BOX_SHAPE - ) { - if (horizontal) { - ctx.rect( - pos[0] - 5 + 0.5, - pos[1] - 8 + 0.5, - 10, - 14 - ); - } else { - ctx.rect( - pos[0] - 6 + 0.5, - pos[1] - 5 + 0.5, - 14, - 10 - ); - } - } else if (slot_shape === LiteGraph.ARROW_SHAPE) { - ctx.moveTo(pos[0] + 8, pos[1] + 0.5); - ctx.lineTo(pos[0] - 4, pos[1] + 6 + 0.5); - ctx.lineTo(pos[0] - 4, pos[1] - 6 + 0.5); - ctx.closePath(); - } else if (slot_shape === LiteGraph.GRID_SHAPE) { - ctx.rect(pos[0] - 4, pos[1] - 4, 2, 2); - ctx.rect(pos[0] - 1, pos[1] - 4, 2, 2); - ctx.rect(pos[0] + 2, pos[1] - 4, 2, 2); - ctx.rect(pos[0] - 4, pos[1] - 1, 2, 2); - ctx.rect(pos[0] - 1, pos[1] - 1, 2, 2); - ctx.rect(pos[0] + 2, pos[1] - 1, 2, 2); - ctx.rect(pos[0] - 4, pos[1] + 2, 2, 2); - ctx.rect(pos[0] - 1, pos[1] + 2, 2, 2); - ctx.rect(pos[0] + 2, pos[1] + 2, 2, 2); - doStroke = false; - } else { - if(low_quality) - ctx.rect(pos[0] - 4, pos[1] - 4, 8, 8 ); - else - ctx.arc(pos[0], pos[1], 4, 0, Math.PI * 2); - } - - //trigger - //if(slot.node_id != null && slot.slot == -1) - // ctx.fillStyle = "#F85"; - - //if(slot.links != null && slot.links.length) - ctx.fill(); - if(!low_quality && doStroke) - ctx.stroke(); - - //render output name - if (render_text) { - var text = slot.label != null ? slot.label : slot.name; - if (text) { - ctx.fillStyle = LiteGraph.NODE_TEXT_COLOR; - if (horizontal || slot.dir == LiteGraph.DOWN) { - ctx.fillText(text, pos[0], pos[1] - 8); - } else { - ctx.fillText(text, pos[0] - 10, pos[1] + 5); - } - } - } - } - } - - ctx.textAlign = "left"; - ctx.globalAlpha = 1; - - if (node.widgets) { - var widgets_y = max_y; - if (horizontal || node.widgets_up) { - widgets_y = 2; - } - if( node.widgets_start_y != null ) - widgets_y = node.widgets_start_y; - this.drawNodeWidgets( - node, - widgets_y, - ctx, - this.node_widget && this.node_widget[0] == node - ? this.node_widget[1] - : null - ); - } - } else if (this.render_collapsed_slots) { - //if collapsed - var input_slot = null; - var output_slot = null; - - //get first connected slot to render - if (node.inputs) { - for (var i = 0; i < node.inputs.length; i++) { - var slot = node.inputs[i]; - if (slot.link == null) { - continue; - } - input_slot = slot; - break; - } - } - if (node.outputs) { - for (var i = 0; i < node.outputs.length; i++) { - var slot = node.outputs[i]; - if (!slot.links || !slot.links.length) { - continue; - } - output_slot = slot; - } - } - - if (input_slot) { - var x = 0; - var y = LiteGraph.NODE_TITLE_HEIGHT * -0.5; //center - if (horizontal) { - x = node._collapsed_width * 0.5; - y = -LiteGraph.NODE_TITLE_HEIGHT; - } - ctx.fillStyle = "#686"; - ctx.beginPath(); - if ( - slot.type === LiteGraph.EVENT || - slot.shape === LiteGraph.BOX_SHAPE - ) { - ctx.rect(x - 7 + 0.5, y - 4, 14, 8); - } else if (slot.shape === LiteGraph.ARROW_SHAPE) { - ctx.moveTo(x + 8, y); - ctx.lineTo(x + -4, y - 4); - ctx.lineTo(x + -4, y + 4); - ctx.closePath(); - } else { - ctx.arc(x, y, 4, 0, Math.PI * 2); - } - ctx.fill(); - } - - if (output_slot) { - var x = node._collapsed_width; - var y = LiteGraph.NODE_TITLE_HEIGHT * -0.5; //center - if (horizontal) { - x = node._collapsed_width * 0.5; - y = 0; - } - ctx.fillStyle = "#686"; - ctx.strokeStyle = "black"; - ctx.beginPath(); - if ( - slot.type === LiteGraph.EVENT || - slot.shape === LiteGraph.BOX_SHAPE - ) { - ctx.rect(x - 7 + 0.5, y - 4, 14, 8); - } else if (slot.shape === LiteGraph.ARROW_SHAPE) { - ctx.moveTo(x + 6, y); - ctx.lineTo(x - 6, y - 4); - ctx.lineTo(x - 6, y + 4); - ctx.closePath(); - } else { - ctx.arc(x, y, 4, 0, Math.PI * 2); - } - ctx.fill(); - //ctx.stroke(); - } - } - - if (node.clip_area) { - ctx.restore(); - } - - ctx.globalAlpha = 1.0; - }; - - //used by this.over_link_center - LGraphCanvas.prototype.drawLinkTooltip = function( ctx, link ) - { - var pos = link._pos; - ctx.fillStyle = "black"; - ctx.beginPath(); - ctx.arc( pos[0], pos[1], 3, 0, Math.PI * 2 ); - ctx.fill(); - - if(link.data == null) - return; - - if(this.onDrawLinkTooltip) - if( this.onDrawLinkTooltip(ctx,link,this) == true ) - return; - - var data = link.data; - var text = null; - - if( data.constructor === Number ) - text = data.toFixed(2); - else if( data.constructor === String ) - text = "\"" + data + "\""; - else if( data.constructor === Boolean ) - text = String(data); - else if (data.toToolTip) - text = data.toToolTip(); - else - text = "[" + data.constructor.name + "]"; - - if(text == null) - return; - text = text.substr(0,30); //avoid weird - - ctx.font = "14px Courier New"; - var info = ctx.measureText(text); - var w = info.width + 20; - var h = 24; - ctx.shadowColor = "black"; - ctx.shadowOffsetX = 2; - ctx.shadowOffsetY = 2; - ctx.shadowBlur = 3; - ctx.fillStyle = "#454"; - ctx.beginPath(); - ctx.roundRect( pos[0] - w*0.5, pos[1] - 15 - h, w, h, [3]); - ctx.moveTo( pos[0] - 10, pos[1] - 15 ); - ctx.lineTo( pos[0] + 10, pos[1] - 15 ); - ctx.lineTo( pos[0], pos[1] - 5 ); - ctx.fill(); - ctx.shadowColor = "transparent"; - ctx.textAlign = "center"; - ctx.fillStyle = "#CEC"; - ctx.fillText(text, pos[0], pos[1] - 15 - h * 0.3); - } - - /** - * draws the shape of the given node in the canvas - * @method drawNodeShape - **/ - var tmp_area = new Float32Array(4); - - LGraphCanvas.prototype.drawNodeShape = function( - node, - ctx, - size, - fgcolor, - bgcolor, - selected, - mouse_over - ) { - //bg rect - ctx.strokeStyle = fgcolor; - ctx.fillStyle = bgcolor; - - var title_height = LiteGraph.NODE_TITLE_HEIGHT; - var low_quality = this.ds.scale < 0.5; - - //render node area depending on shape - var shape = - node._shape || node.constructor.shape || LiteGraph.ROUND_SHAPE; - - var title_mode = node.constructor.title_mode; - - var render_title = true; - if (title_mode == LiteGraph.TRANSPARENT_TITLE || title_mode == LiteGraph.NO_TITLE) { - render_title = false; - } else if (title_mode == LiteGraph.AUTOHIDE_TITLE && mouse_over) { - render_title = true; - } - - var area = tmp_area; - area[0] = 0; //x - area[1] = render_title ? -title_height : 0; //y - area[2] = size[0] + 1; //w - area[3] = render_title ? size[1] + title_height : size[1]; //h - - var old_alpha = ctx.globalAlpha; - - //full node shape - //if(node.flags.collapsed) - { - ctx.beginPath(); - if (shape == LiteGraph.BOX_SHAPE || low_quality) { - ctx.fillRect(area[0], area[1], area[2], area[3]); - } else if ( - shape == LiteGraph.ROUND_SHAPE || - shape == LiteGraph.CARD_SHAPE - ) { - ctx.roundRect( - area[0], - area[1], - area[2], - area[3], - shape == LiteGraph.CARD_SHAPE ? [this.round_radius,this.round_radius,0,0] : [this.round_radius] - ); - } else if (shape == LiteGraph.CIRCLE_SHAPE) { - ctx.arc( - size[0] * 0.5, - size[1] * 0.5, - size[0] * 0.5, - 0, - Math.PI * 2 - ); - } - ctx.fill(); - - //separator - if(!node.flags.collapsed && render_title) - { - ctx.shadowColor = "transparent"; - ctx.fillStyle = "rgba(0,0,0,0.2)"; - ctx.fillRect(0, -1, area[2], 2); - } - } - ctx.shadowColor = "transparent"; - - if (node.onDrawBackground) { - node.onDrawBackground(ctx, this, this.canvas, this.graph_mouse ); - } - - //title bg (remember, it is rendered ABOVE the node) - if (render_title || title_mode == LiteGraph.TRANSPARENT_TITLE) { - //title bar - if (node.onDrawTitleBar) { - node.onDrawTitleBar( ctx, title_height, size, this.ds.scale, fgcolor ); - } else if ( - title_mode != LiteGraph.TRANSPARENT_TITLE && - (node.constructor.title_color || this.render_title_colored) - ) { - var title_color = node.constructor.title_color || fgcolor; - - if (node.flags.collapsed) { - ctx.shadowColor = LiteGraph.DEFAULT_SHADOW_COLOR; - } - - //* gradient test - if (this.use_gradients) { - var grad = LGraphCanvas.gradients[title_color]; - if (!grad) { - grad = LGraphCanvas.gradients[ title_color ] = ctx.createLinearGradient(0, 0, 400, 0); - grad.addColorStop(0, title_color); // TODO refactor: validate color !! prevent DOMException - grad.addColorStop(1, "#000"); - } - ctx.fillStyle = grad; - } else { - ctx.fillStyle = title_color; - } - - //ctx.globalAlpha = 0.5 * old_alpha; - ctx.beginPath(); - if (shape == LiteGraph.BOX_SHAPE || low_quality) { - ctx.rect(0, -title_height, size[0] + 1, title_height); - } else if ( shape == LiteGraph.ROUND_SHAPE || shape == LiteGraph.CARD_SHAPE ) { - ctx.roundRect( - 0, - -title_height, - size[0] + 1, - title_height, - node.flags.collapsed ? [this.round_radius] : [this.round_radius,this.round_radius,0,0] - ); - } - ctx.fill(); - ctx.shadowColor = "transparent"; - } - - var colState = false; - if (LiteGraph.node_box_coloured_by_mode){ - if(LiteGraph.NODE_MODES_COLORS[node.mode]){ - colState = LiteGraph.NODE_MODES_COLORS[node.mode]; - } - } - if (LiteGraph.node_box_coloured_when_on){ - colState = node.action_triggered ? "#FFF" : (node.execute_triggered ? "#AAA" : colState); - } - - //title box - var box_size = 10; - if (node.onDrawTitleBox) { - node.onDrawTitleBox(ctx, title_height, size, this.ds.scale); - } else if ( - shape == LiteGraph.ROUND_SHAPE || - shape == LiteGraph.CIRCLE_SHAPE || - shape == LiteGraph.CARD_SHAPE - ) { - if (low_quality) { - ctx.fillStyle = "black"; - ctx.beginPath(); - ctx.arc( - title_height * 0.5, - title_height * -0.5, - box_size * 0.5 + 1, - 0, - Math.PI * 2 - ); - ctx.fill(); - } - - ctx.fillStyle = node.boxcolor || colState || LiteGraph.NODE_DEFAULT_BOXCOLOR; - if(low_quality) - ctx.fillRect( title_height * 0.5 - box_size *0.5, title_height * -0.5 - box_size *0.5, box_size , box_size ); - else - { - ctx.beginPath(); - ctx.arc( - title_height * 0.5, - title_height * -0.5, - box_size * 0.5, - 0, - Math.PI * 2 - ); - ctx.fill(); - } - } else { - if (low_quality) { - ctx.fillStyle = "black"; - ctx.fillRect( - (title_height - box_size) * 0.5 - 1, - (title_height + box_size) * -0.5 - 1, - box_size + 2, - box_size + 2 - ); - } - ctx.fillStyle = node.boxcolor || colState || LiteGraph.NODE_DEFAULT_BOXCOLOR; - ctx.fillRect( - (title_height - box_size) * 0.5, - (title_height + box_size) * -0.5, - box_size, - box_size - ); - } - ctx.globalAlpha = old_alpha; - - //title text - if (node.onDrawTitleText) { - node.onDrawTitleText( - ctx, - title_height, - size, - this.ds.scale, - this.title_text_font, - selected - ); - } - if (!low_quality) { - ctx.font = this.title_text_font; - var title = String(node.getTitle()); - if (title) { - if (selected) { - ctx.fillStyle = LiteGraph.NODE_SELECTED_TITLE_COLOR; - } else { - ctx.fillStyle = - node.constructor.title_text_color || - this.node_title_color; - } - if (node.flags.collapsed) { - ctx.textAlign = "left"; - var measure = ctx.measureText(title); - ctx.fillText( - title.substr(0,20), //avoid urls too long - title_height,// + measure.width * 0.5, - LiteGraph.NODE_TITLE_TEXT_Y - title_height - ); - ctx.textAlign = "left"; - } else { - ctx.textAlign = "left"; - ctx.fillText( - title, - title_height, - LiteGraph.NODE_TITLE_TEXT_Y - title_height - ); - } - } - } - - //subgraph box - if (!node.flags.collapsed && node.subgraph && !node.skip_subgraph_button) { - var w = LiteGraph.NODE_TITLE_HEIGHT; - var x = node.size[0] - w; - var over = LiteGraph.isInsideRectangle( this.graph_mouse[0] - node.pos[0], this.graph_mouse[1] - node.pos[1], x+2, -w+2, w-4, w-4 ); - ctx.fillStyle = over ? "#888" : "#555"; - if( shape == LiteGraph.BOX_SHAPE || low_quality) - ctx.fillRect(x+2, -w+2, w-4, w-4); - else - { - ctx.beginPath(); - ctx.roundRect(x+2, -w+2, w-4, w-4,[4]); - ctx.fill(); - } - ctx.fillStyle = "#333"; - ctx.beginPath(); - ctx.moveTo(x + w * 0.2, -w * 0.6); - ctx.lineTo(x + w * 0.8, -w * 0.6); - ctx.lineTo(x + w * 0.5, -w * 0.3); - ctx.fill(); - } - - //custom title render - if (node.onDrawTitle) { - node.onDrawTitle(ctx); - } - } - - //render selection marker - if (selected) { - if (node.onBounding) { - node.onBounding(area); - } - - if (title_mode == LiteGraph.TRANSPARENT_TITLE) { - area[1] -= title_height; - area[3] += title_height; - } - ctx.lineWidth = 1; - ctx.globalAlpha = 0.8; - ctx.beginPath(); - if (shape == LiteGraph.BOX_SHAPE) { - ctx.rect( - -6 + area[0], - -6 + area[1], - 12 + area[2], - 12 + area[3] - ); - } else if ( - shape == LiteGraph.ROUND_SHAPE || - (shape == LiteGraph.CARD_SHAPE && node.flags.collapsed) - ) { - ctx.roundRect( - -6 + area[0], - -6 + area[1], - 12 + area[2], - 12 + area[3], - [this.round_radius * 2] - ); - } else if (shape == LiteGraph.CARD_SHAPE) { - ctx.roundRect( - -6 + area[0], - -6 + area[1], - 12 + area[2], - 12 + area[3], - [this.round_radius * 2,2,this.round_radius * 2,2] - ); - } else if (shape == LiteGraph.CIRCLE_SHAPE) { - ctx.arc( - size[0] * 0.5, - size[1] * 0.5, - size[0] * 0.5 + 6, - 0, - Math.PI * 2 - ); - } - ctx.strokeStyle = LiteGraph.NODE_BOX_OUTLINE_COLOR; - ctx.stroke(); - ctx.strokeStyle = fgcolor; - ctx.globalAlpha = 1; - } - - // these counter helps in conditioning drawing based on if the node has been executed or an action occurred - if (node.execute_triggered>0) node.execute_triggered--; - if (node.action_triggered>0) node.action_triggered--; - }; - - var margin_area = new Float32Array(4); - var link_bounding = new Float32Array(4); - var tempA = new Float32Array(2); - var tempB = new Float32Array(2); - - /** - * draws every connection visible in the canvas - * OPTIMIZE THIS: pre-catch connections position instead of recomputing them every time - * @method drawConnections - **/ - LGraphCanvas.prototype.drawConnections = function(ctx) { - var now = LiteGraph.getTime(); - var visible_area = this.visible_area; - margin_area[0] = visible_area[0] - 20; - margin_area[1] = visible_area[1] - 20; - margin_area[2] = visible_area[2] + 40; - margin_area[3] = visible_area[3] + 40; - - //draw connections - ctx.lineWidth = this.connections_width; - - ctx.fillStyle = "#AAA"; - ctx.strokeStyle = "#AAA"; - ctx.globalAlpha = this.editor_alpha; - //for every node - var nodes = this.graph._nodes; - for (var n = 0, l = nodes.length; n < l; ++n) { - var node = nodes[n]; - //for every input (we render just inputs because it is easier as every slot can only have one input) - if (!node.inputs || !node.inputs.length) { - continue; - } - - for (var i = 0; i < node.inputs.length; ++i) { - var input = node.inputs[i]; - if (!input || input.link == null) { - continue; - } - var link_id = input.link; - var link = this.graph.links[link_id]; - if (!link) { - continue; - } - - //find link info - var start_node = this.graph.getNodeById(link.origin_id); - if (start_node == null) { - continue; - } - var start_node_slot = link.origin_slot; - var start_node_slotpos = null; - if (start_node_slot == -1) { - start_node_slotpos = [ - start_node.pos[0] + 10, - start_node.pos[1] + 10 - ]; - } else { - start_node_slotpos = start_node.getConnectionPos( - false, - start_node_slot, - tempA - ); - } - var end_node_slotpos = node.getConnectionPos(true, i, tempB); - - //compute link bounding - link_bounding[0] = start_node_slotpos[0]; - link_bounding[1] = start_node_slotpos[1]; - link_bounding[2] = end_node_slotpos[0] - start_node_slotpos[0]; - link_bounding[3] = end_node_slotpos[1] - start_node_slotpos[1]; - if (link_bounding[2] < 0) { - link_bounding[0] += link_bounding[2]; - link_bounding[2] = Math.abs(link_bounding[2]); - } - if (link_bounding[3] < 0) { - link_bounding[1] += link_bounding[3]; - link_bounding[3] = Math.abs(link_bounding[3]); - } - - //skip links outside of the visible area of the canvas - if (!overlapBounding(link_bounding, margin_area)) { - continue; - } - - var start_slot = start_node.outputs[start_node_slot]; - var end_slot = node.inputs[i]; - if (!start_slot || !end_slot) { - continue; - } - var start_dir = - start_slot.dir || - (start_node.horizontal ? LiteGraph.DOWN : LiteGraph.RIGHT); - var end_dir = - end_slot.dir || - (node.horizontal ? LiteGraph.UP : LiteGraph.LEFT); - - this.renderLink( - ctx, - start_node_slotpos, - end_node_slotpos, - link, - false, - 0, - null, - start_dir, - end_dir - ); - - //event triggered rendered on top - if (link && link._last_time && now - link._last_time < 1000) { - var f = 2.0 - (now - link._last_time) * 0.002; - var tmp = ctx.globalAlpha; - ctx.globalAlpha = tmp * f; - this.renderLink( - ctx, - start_node_slotpos, - end_node_slotpos, - link, - true, - f, - "white", - start_dir, - end_dir - ); - ctx.globalAlpha = tmp; - } - } - } - ctx.globalAlpha = 1; - }; - - /** - * draws a link between two points - * @method renderLink - * @param {vec2} a start pos - * @param {vec2} b end pos - * @param {Object} link the link object with all the link info - * @param {boolean} skip_border ignore the shadow of the link - * @param {boolean} flow show flow animation (for events) - * @param {string} color the color for the link - * @param {number} start_dir the direction enum - * @param {number} end_dir the direction enum - * @param {number} num_sublines number of sublines (useful to represent vec3 or rgb) - **/ - LGraphCanvas.prototype.renderLink = function( - ctx, - a, - b, - link, - skip_border, - flow, - color, - start_dir, - end_dir, - num_sublines - ) { - if (link) { - this.visible_links.push(link); - } - - //choose color - if (!color && link) { - color = link.color || LGraphCanvas.link_type_colors[link.type]; - } - if (!color) { - color = this.default_link_color; - } - if (link != null && this.highlighted_links[link.id]) { - color = "#FFF"; - } - - start_dir = start_dir || LiteGraph.RIGHT; - end_dir = end_dir || LiteGraph.LEFT; - - var dist = distance(a, b); - - if (this.render_connections_border && this.ds.scale > 0.6) { - ctx.lineWidth = this.connections_width + 4; - } - ctx.lineJoin = "round"; - num_sublines = num_sublines || 1; - if (num_sublines > 1) { - ctx.lineWidth = 0.5; - } - - //begin line shape - ctx.beginPath(); - for (var i = 0; i < num_sublines; i += 1) { - var offsety = (i - (num_sublines - 1) * 0.5) * 5; - - if (this.links_render_mode == LiteGraph.SPLINE_LINK) { - ctx.moveTo(a[0], a[1] + offsety); - var start_offset_x = 0; - var start_offset_y = 0; - var end_offset_x = 0; - var end_offset_y = 0; - switch (start_dir) { - case LiteGraph.LEFT: - start_offset_x = dist * -0.25; - break; - case LiteGraph.RIGHT: - start_offset_x = dist * 0.25; - break; - case LiteGraph.UP: - start_offset_y = dist * -0.25; - break; - case LiteGraph.DOWN: - start_offset_y = dist * 0.25; - break; - } - switch (end_dir) { - case LiteGraph.LEFT: - end_offset_x = dist * -0.25; - break; - case LiteGraph.RIGHT: - end_offset_x = dist * 0.25; - break; - case LiteGraph.UP: - end_offset_y = dist * -0.25; - break; - case LiteGraph.DOWN: - end_offset_y = dist * 0.25; - break; - } - ctx.bezierCurveTo( - a[0] + start_offset_x, - a[1] + start_offset_y + offsety, - b[0] + end_offset_x, - b[1] + end_offset_y + offsety, - b[0], - b[1] + offsety - ); - } else if (this.links_render_mode == LiteGraph.LINEAR_LINK) { - ctx.moveTo(a[0], a[1] + offsety); - var start_offset_x = 0; - var start_offset_y = 0; - var end_offset_x = 0; - var end_offset_y = 0; - switch (start_dir) { - case LiteGraph.LEFT: - start_offset_x = -1; - break; - case LiteGraph.RIGHT: - start_offset_x = 1; - break; - case LiteGraph.UP: - start_offset_y = -1; - break; - case LiteGraph.DOWN: - start_offset_y = 1; - break; - } - switch (end_dir) { - case LiteGraph.LEFT: - end_offset_x = -1; - break; - case LiteGraph.RIGHT: - end_offset_x = 1; - break; - case LiteGraph.UP: - end_offset_y = -1; - break; - case LiteGraph.DOWN: - end_offset_y = 1; - break; - } - var l = 15; - ctx.lineTo( - a[0] + start_offset_x * l, - a[1] + start_offset_y * l + offsety - ); - ctx.lineTo( - b[0] + end_offset_x * l, - b[1] + end_offset_y * l + offsety - ); - ctx.lineTo(b[0], b[1] + offsety); - } else if (this.links_render_mode == LiteGraph.STRAIGHT_LINK) { - ctx.moveTo(a[0], a[1]); - var start_x = a[0]; - var start_y = a[1]; - var end_x = b[0]; - var end_y = b[1]; - if (start_dir == LiteGraph.RIGHT) { - start_x += 10; - } else { - start_y += 10; - } - if (end_dir == LiteGraph.LEFT) { - end_x -= 10; - } else { - end_y -= 10; - } - ctx.lineTo(start_x, start_y); - ctx.lineTo((start_x + end_x) * 0.5, start_y); - ctx.lineTo((start_x + end_x) * 0.5, end_y); - ctx.lineTo(end_x, end_y); - ctx.lineTo(b[0], b[1]); - } else { - return; - } //unknown - } - - //rendering the outline of the connection can be a little bit slow - if ( - this.render_connections_border && - this.ds.scale > 0.6 && - !skip_border - ) { - ctx.strokeStyle = "rgba(0,0,0,0.5)"; - ctx.stroke(); - } - - ctx.lineWidth = this.connections_width; - ctx.fillStyle = ctx.strokeStyle = color; - ctx.stroke(); - //end line shape - - var pos = this.computeConnectionPoint(a, b, 0.5, start_dir, end_dir); - if (link && link._pos) { - link._pos[0] = pos[0]; - link._pos[1] = pos[1]; - } - - //render arrow in the middle - if ( - this.ds.scale >= 0.6 && - this.highquality_render && - end_dir != LiteGraph.CENTER - ) { - //render arrow - if (this.render_connection_arrows) { - //compute two points in the connection - var posA = this.computeConnectionPoint( - a, - b, - 0.25, - start_dir, - end_dir - ); - var posB = this.computeConnectionPoint( - a, - b, - 0.26, - start_dir, - end_dir - ); - var posC = this.computeConnectionPoint( - a, - b, - 0.75, - start_dir, - end_dir - ); - var posD = this.computeConnectionPoint( - a, - b, - 0.76, - start_dir, - end_dir - ); - - //compute the angle between them so the arrow points in the right direction - var angleA = 0; - var angleB = 0; - if (this.render_curved_connections) { - angleA = -Math.atan2(posB[0] - posA[0], posB[1] - posA[1]); - angleB = -Math.atan2(posD[0] - posC[0], posD[1] - posC[1]); - } else { - angleB = angleA = b[1] > a[1] ? 0 : Math.PI; - } - - //render arrow - ctx.save(); - ctx.translate(posA[0], posA[1]); - ctx.rotate(angleA); - ctx.beginPath(); - ctx.moveTo(-5, -3); - ctx.lineTo(0, +7); - ctx.lineTo(+5, -3); - ctx.fill(); - ctx.restore(); - ctx.save(); - ctx.translate(posC[0], posC[1]); - ctx.rotate(angleB); - ctx.beginPath(); - ctx.moveTo(-5, -3); - ctx.lineTo(0, +7); - ctx.lineTo(+5, -3); - ctx.fill(); - ctx.restore(); - } - - //circle - ctx.beginPath(); - ctx.arc(pos[0], pos[1], 5, 0, Math.PI * 2); - ctx.fill(); - } - - //render flowing points - if (flow) { - ctx.fillStyle = color; - for (var i = 0; i < 5; ++i) { - var f = (LiteGraph.getTime() * 0.001 + i * 0.2) % 1; - var pos = this.computeConnectionPoint( - a, - b, - f, - start_dir, - end_dir - ); - ctx.beginPath(); - ctx.arc(pos[0], pos[1], 5, 0, 2 * Math.PI); - ctx.fill(); - } - } - }; - - //returns the link center point based on curvature - LGraphCanvas.prototype.computeConnectionPoint = function( - a, - b, - t, - start_dir, - end_dir - ) { - start_dir = start_dir || LiteGraph.RIGHT; - end_dir = end_dir || LiteGraph.LEFT; - - var dist = distance(a, b); - var p0 = a; - var p1 = [a[0], a[1]]; - var p2 = [b[0], b[1]]; - var p3 = b; - - switch (start_dir) { - case LiteGraph.LEFT: - p1[0] += dist * -0.25; - break; - case LiteGraph.RIGHT: - p1[0] += dist * 0.25; - break; - case LiteGraph.UP: - p1[1] += dist * -0.25; - break; - case LiteGraph.DOWN: - p1[1] += dist * 0.25; - break; - } - switch (end_dir) { - case LiteGraph.LEFT: - p2[0] += dist * -0.25; - break; - case LiteGraph.RIGHT: - p2[0] += dist * 0.25; - break; - case LiteGraph.UP: - p2[1] += dist * -0.25; - break; - case LiteGraph.DOWN: - p2[1] += dist * 0.25; - break; - } - - var c1 = (1 - t) * (1 - t) * (1 - t); - var c2 = 3 * ((1 - t) * (1 - t)) * t; - var c3 = 3 * (1 - t) * (t * t); - var c4 = t * t * t; - - var x = c1 * p0[0] + c2 * p1[0] + c3 * p2[0] + c4 * p3[0]; - var y = c1 * p0[1] + c2 * p1[1] + c3 * p2[1] + c4 * p3[1]; - return [x, y]; - }; - - LGraphCanvas.prototype.drawExecutionOrder = function(ctx) { - ctx.shadowColor = "transparent"; - ctx.globalAlpha = 0.25; - - ctx.textAlign = "center"; - ctx.strokeStyle = "white"; - ctx.globalAlpha = 0.75; - - var visible_nodes = this.visible_nodes; - for (var i = 0; i < visible_nodes.length; ++i) { - var node = visible_nodes[i]; - ctx.fillStyle = "black"; - ctx.fillRect( - node.pos[0] - LiteGraph.NODE_TITLE_HEIGHT, - node.pos[1] - LiteGraph.NODE_TITLE_HEIGHT, - LiteGraph.NODE_TITLE_HEIGHT, - LiteGraph.NODE_TITLE_HEIGHT - ); - if (node.order == 0) { - ctx.strokeRect( - node.pos[0] - LiteGraph.NODE_TITLE_HEIGHT + 0.5, - node.pos[1] - LiteGraph.NODE_TITLE_HEIGHT + 0.5, - LiteGraph.NODE_TITLE_HEIGHT, - LiteGraph.NODE_TITLE_HEIGHT - ); - } - ctx.fillStyle = "#FFF"; - ctx.fillText( - node.order, - node.pos[0] + LiteGraph.NODE_TITLE_HEIGHT * -0.5, - node.pos[1] - 6 - ); - } - ctx.globalAlpha = 1; - }; - - /** - * draws the widgets stored inside a node - * @method drawNodeWidgets - **/ - LGraphCanvas.prototype.drawNodeWidgets = function( - node, - posY, - ctx, - active_widget - ) { - if (!node.widgets || !node.widgets.length) { - return 0; - } - var width = node.size[0]; - var widgets = node.widgets; - posY += 2; - var H = LiteGraph.NODE_WIDGET_HEIGHT; - var show_text = this.ds.scale > 0.5; - ctx.save(); - ctx.globalAlpha = this.editor_alpha; - var outline_color = LiteGraph.WIDGET_OUTLINE_COLOR; - var background_color = LiteGraph.WIDGET_BGCOLOR; - var text_color = LiteGraph.WIDGET_TEXT_COLOR; - var secondary_text_color = LiteGraph.WIDGET_SECONDARY_TEXT_COLOR; - var margin = 15; - - for (var i = 0; i < widgets.length; ++i) { - var w = widgets[i]; - var y = posY; - if (w.y) { - y = w.y; - } - w.last_y = y; - ctx.strokeStyle = outline_color; - ctx.fillStyle = "#222"; - ctx.textAlign = "left"; - //ctx.lineWidth = 2; - if(w.disabled) - ctx.globalAlpha *= 0.5; - var widget_width = w.width || width; - - switch (w.type) { - case "button": - ctx.fillStyle = background_color; - if (w.clicked) { - ctx.fillStyle = "#AAA"; - w.clicked = false; - this.dirty_canvas = true; - } - ctx.fillRect(margin, y, widget_width - margin * 2, H); - if(show_text && !w.disabled) - ctx.strokeRect( margin, y, widget_width - margin * 2, H ); - if (show_text) { - ctx.textAlign = "center"; - ctx.fillStyle = text_color; - ctx.fillText(w.label || w.name, widget_width * 0.5, y + H * 0.7); - } - break; - case "toggle": - ctx.textAlign = "left"; - ctx.strokeStyle = outline_color; - ctx.fillStyle = background_color; - ctx.beginPath(); - if (show_text) - ctx.roundRect(margin, y, widget_width - margin * 2, H, [H * 0.5]); - else - ctx.rect(margin, y, widget_width - margin * 2, H ); - ctx.fill(); - if(show_text && !w.disabled) - ctx.stroke(); - ctx.fillStyle = w.value ? "#89A" : "#333"; - ctx.beginPath(); - ctx.arc( widget_width - margin * 2, y + H * 0.5, H * 0.36, 0, Math.PI * 2 ); - ctx.fill(); - if (show_text) { - ctx.fillStyle = secondary_text_color; - const label = w.label || w.name; - if (label != null) { - ctx.fillText(label, margin * 2, y + H * 0.7); - } - ctx.fillStyle = w.value ? text_color : secondary_text_color; - ctx.textAlign = "right"; - ctx.fillText( - w.value - ? w.options.on || "true" - : w.options.off || "false", - widget_width - 40, - y + H * 0.7 - ); - } - break; - case "slider": - ctx.fillStyle = background_color; - ctx.fillRect(margin, y, widget_width - margin * 2, H); - var range = w.options.max - w.options.min; - var nvalue = (w.value - w.options.min) / range; - if(nvalue < 0.0) nvalue = 0.0; - if(nvalue > 1.0) nvalue = 1.0; - ctx.fillStyle = w.options.hasOwnProperty("slider_color") ? w.options.slider_color : (active_widget == w ? "#89A" : "#678"); - ctx.fillRect(margin, y, nvalue * (widget_width - margin * 2), H); - if(show_text && !w.disabled) - ctx.strokeRect(margin, y, widget_width - margin * 2, H); - if (w.marker) { - var marker_nvalue = (w.marker - w.options.min) / range; - if(marker_nvalue < 0.0) marker_nvalue = 0.0; - if(marker_nvalue > 1.0) marker_nvalue = 1.0; - ctx.fillStyle = w.options.hasOwnProperty("marker_color") ? w.options.marker_color : "#AA9"; - ctx.fillRect( margin + marker_nvalue * (widget_width - margin * 2), y, 2, H ); - } - if (show_text) { - ctx.textAlign = "center"; - ctx.fillStyle = text_color; - ctx.fillText( - w.label || w.name + " " + Number(w.value).toFixed( - w.options.precision != null - ? w.options.precision - : 3 - ), - widget_width * 0.5, - y + H * 0.7 - ); - } - break; - case "number": - case "combo": - ctx.textAlign = "left"; - ctx.strokeStyle = outline_color; - ctx.fillStyle = background_color; - ctx.beginPath(); - if(show_text) - ctx.roundRect(margin, y, widget_width - margin * 2, H, [H * 0.5] ); - else - ctx.rect(margin, y, widget_width - margin * 2, H ); - ctx.fill(); - if (show_text) { - if(!w.disabled) - ctx.stroke(); - ctx.fillStyle = text_color; - if(!w.disabled) - { - ctx.beginPath(); - ctx.moveTo(margin + 16, y + 5); - ctx.lineTo(margin + 6, y + H * 0.5); - ctx.lineTo(margin + 16, y + H - 5); - ctx.fill(); - ctx.beginPath(); - ctx.moveTo(widget_width - margin - 16, y + 5); - ctx.lineTo(widget_width - margin - 6, y + H * 0.5); - ctx.lineTo(widget_width - margin - 16, y + H - 5); - ctx.fill(); - } - ctx.fillStyle = secondary_text_color; - ctx.fillText(w.label || w.name, margin * 2 + 5, y + H * 0.7); - ctx.fillStyle = text_color; - ctx.textAlign = "right"; - if (w.type == "number") { - ctx.fillText( - Number(w.value).toFixed( - w.options.precision !== undefined - ? w.options.precision - : 3 - ), - widget_width - margin * 2 - 20, - y + H * 0.7 - ); - } else { - var v = w.value; - if( w.options.values ) - { - var values = w.options.values; - if( values.constructor === Function ) - values = values(); - if(values && values.constructor !== Array) - v = values[ w.value ]; - } - ctx.fillText( - v, - widget_width - margin * 2 - 20, - y + H * 0.7 - ); - } - } - break; - case "string": - case "text": - ctx.textAlign = "left"; - ctx.strokeStyle = outline_color; - ctx.fillStyle = background_color; - ctx.beginPath(); - if (show_text) - ctx.roundRect(margin, y, widget_width - margin * 2, H, [H * 0.5]); - else - ctx.rect( margin, y, widget_width - margin * 2, H ); - ctx.fill(); - if (show_text) { - if(!w.disabled) - ctx.stroke(); - ctx.save(); - ctx.beginPath(); - ctx.rect(margin, y, widget_width - margin * 2, H); - ctx.clip(); - - //ctx.stroke(); - ctx.fillStyle = secondary_text_color; - const label = w.label || w.name; - if (label != null) { - ctx.fillText(label, margin * 2, y + H * 0.7); - } - ctx.fillStyle = text_color; - ctx.textAlign = "right"; - ctx.fillText(String(w.value).substr(0,30), widget_width - margin * 2, y + H * 0.7); //30 chars max - ctx.restore(); - } - break; - default: - if (w.draw) { - w.draw(ctx, node, widget_width, y, H); - } - break; - } - posY += (w.computeSize ? w.computeSize(widget_width)[1] : H) + 4; - ctx.globalAlpha = this.editor_alpha; - - } - ctx.restore(); - ctx.textAlign = "left"; - }; - - /** - * process an event on widgets - * @method processNodeWidgets - **/ - LGraphCanvas.prototype.processNodeWidgets = function( - node, - pos, - event, - active_widget - ) { - if (!node.widgets || !node.widgets.length || (!this.allow_interaction && !node.flags.allow_interaction)) { - return null; - } - - var x = pos[0] - node.pos[0]; - var y = pos[1] - node.pos[1]; - var width = node.size[0]; - var that = this; - var ref_window = this.getCanvasWindow(); - - for (var i = 0; i < node.widgets.length; ++i) { - var w = node.widgets[i]; - if(!w || w.disabled) - continue; - var widget_height = w.computeSize ? w.computeSize(width)[1] : LiteGraph.NODE_WIDGET_HEIGHT; - var widget_width = w.width || width; - //outside - if ( w != active_widget && - (x < 6 || x > widget_width - 12 || y < w.last_y || y > w.last_y + widget_height || w.last_y === undefined) ) - continue; - - var old_value = w.value; - - //if ( w == active_widget || (x > 6 && x < widget_width - 12 && y > w.last_y && y < w.last_y + widget_height) ) { - //inside widget - switch (w.type) { - case "button": - if (event.type === LiteGraph.pointerevents_method+"down") { - if (w.callback) { - setTimeout(function() { - w.callback(w, that, node, pos, event); - }, 20); - } - w.clicked = true; - this.dirty_canvas = true; - } - break; - case "slider": - var old_value = w.value; - var nvalue = clamp((x - 15) / (widget_width - 30), 0, 1); - if(w.options.read_only) break; - w.value = w.options.min + (w.options.max - w.options.min) * nvalue; - if (old_value != w.value) { - setTimeout(function() { - inner_value_change(w, w.value); - }, 20); - } - this.dirty_canvas = true; - break; - case "number": - case "combo": - var old_value = w.value; - var delta = x < 40 ? -1 : x > widget_width - 40 ? 1 : 0; - var allow_scroll = true; - if (delta) { - if (x > -3 && x < widget_width + 3) { - allow_scroll = false; - } - } - if (allow_scroll && event.type == LiteGraph.pointerevents_method+"move" && w.type == "number") { - if(event.deltaX) - w.value += event.deltaX * 0.1 * (w.options.step || 1); - if ( w.options.min != null && w.value < w.options.min ) { - w.value = w.options.min; - } - if ( w.options.max != null && w.value > w.options.max ) { - w.value = w.options.max; - } - } else if (event.type == LiteGraph.pointerevents_method+"down") { - var values = w.options.values; - if (values && values.constructor === Function) { - values = w.options.values(w, node); - } - var values_list = null; - - if( w.type != "number") - values_list = values.constructor === Array ? values : Object.keys(values); - - var delta = x < 40 ? -1 : x > widget_width - 40 ? 1 : 0; - if (w.type == "number") { - w.value += delta * 0.1 * (w.options.step || 1); - if ( w.options.min != null && w.value < w.options.min ) { - w.value = w.options.min; - } - if ( w.options.max != null && w.value > w.options.max ) { - w.value = w.options.max; - } - } else if (delta) { //clicked in arrow, used for combos - var index = -1; - this.last_mouseclick = 0; //avoids dobl click event - if(values.constructor === Object) - index = values_list.indexOf( String( w.value ) ) + delta; - else - index = values_list.indexOf( w.value ) + delta; - if (index >= values_list.length) { - index = values_list.length - 1; - } - if (index < 0) { - index = 0; - } - if( values.constructor === Array ) - w.value = values[index]; - else - w.value = index; - } else { //combo clicked - var text_values = values != values_list ? Object.values(values) : values; - var menu = new LiteGraph.ContextMenu(text_values, { - scale: Math.max(1, this.ds.scale), - event: event, - className: "dark", - callback: inner_clicked.bind(w) - }, - ref_window); - function inner_clicked(v, option, event) { - if(values != values_list) - v = text_values.indexOf(v); - this.value = v; - inner_value_change(this, v); - that.dirty_canvas = true; - return false; - } - } - } //end mousedown - else if(event.type == LiteGraph.pointerevents_method+"up" && w.type == "number") - { - var delta = x < 40 ? -1 : x > widget_width - 40 ? 1 : 0; - if (event.click_time < 200 && delta == 0) { - this.prompt("Value",w.value,function(v) { - // check if v is a valid equation or a number - if (/^[0-9+\-*/()\s]+|\d+\.\d+$/.test(v)) { - try {//solve the equation if possible - v = eval(v); - } catch (e) { } - } - this.value = Number(v); - inner_value_change(this, this.value); - }.bind(w), - event); - } - } - - if( old_value != w.value ) - setTimeout( - function() { - inner_value_change(this, this.value); - }.bind(w), - 20 - ); - this.dirty_canvas = true; - break; - case "toggle": - if (event.type == LiteGraph.pointerevents_method+"down") { - w.value = !w.value; - setTimeout(function() { - inner_value_change(w, w.value); - }, 20); - } - break; - case "string": - case "text": - if (event.type == LiteGraph.pointerevents_method+"down") { - this.prompt("Value",w.value,function(v) { - inner_value_change(this, v); - }.bind(w), - event,w.options ? w.options.multiline : false ); - } - break; - default: - if (w.mouse) { - this.dirty_canvas = w.mouse(event, [x, y], node); - } - break; - } //end switch - - //value changed - if( old_value != w.value ) - { - if(node.onWidgetChanged) - node.onWidgetChanged( w.name,w.value,old_value,w ); - node.graph._version++; - } - - return w; - }//end for - - function inner_value_change(widget, value) { - if(widget.type == "number"){ - value = Number(value); - } - widget.value = value; - if ( widget.options && widget.options.property && node.properties[widget.options.property] !== undefined ) { - node.setProperty( widget.options.property, value ); - } - if (widget.callback) { - widget.callback(widget.value, that, node, pos, event); - } - } - - return null; - }; - - /** - * draws every group area in the background - * @method drawGroups - **/ - LGraphCanvas.prototype.drawGroups = function(canvas, ctx) { - if (!this.graph) { - return; - } - - var groups = this.graph._groups; - - ctx.save(); - ctx.globalAlpha = 0.5 * this.editor_alpha; - - for (var i = 0; i < groups.length; ++i) { - var group = groups[i]; - - if (!overlapBounding(this.visible_area, group._bounding)) { - continue; - } //out of the visible area - - ctx.fillStyle = group.color || "#335"; - ctx.strokeStyle = group.color || "#335"; - var pos = group._pos; - var size = group._size; - ctx.globalAlpha = 0.25 * this.editor_alpha; - ctx.beginPath(); - ctx.rect(pos[0] + 0.5, pos[1] + 0.5, size[0], size[1]); - ctx.fill(); - ctx.globalAlpha = this.editor_alpha; - ctx.stroke(); - - ctx.beginPath(); - ctx.moveTo(pos[0] + size[0], pos[1] + size[1]); - ctx.lineTo(pos[0] + size[0] - 10, pos[1] + size[1]); - ctx.lineTo(pos[0] + size[0], pos[1] + size[1] - 10); - ctx.fill(); - - var font_size = - group.font_size || LiteGraph.DEFAULT_GROUP_FONT_SIZE; - ctx.font = font_size + "px Arial"; - ctx.textAlign = "left"; - ctx.fillText(group.title, pos[0] + 4, pos[1] + font_size); - } - - ctx.restore(); - }; - - LGraphCanvas.prototype.adjustNodesSize = function() { - var nodes = this.graph._nodes; - for (var i = 0; i < nodes.length; ++i) { - nodes[i].size = nodes[i].computeSize(); - } - this.setDirty(true, true); - }; - - /** - * resizes the canvas to a given size, if no size is passed, then it tries to fill the parentNode - * @method resize - **/ - LGraphCanvas.prototype.resize = function(width, height) { - if (!width && !height) { - var parent = this.canvas.parentNode; - width = parent.offsetWidth; - height = parent.offsetHeight; - } - - if (this.canvas.width == width && this.canvas.height == height) { - return; - } - - this.canvas.width = width; - this.canvas.height = height; - this.bgcanvas.width = this.canvas.width; - this.bgcanvas.height = this.canvas.height; - this.setDirty(true, true); - }; - - /** - * switches to live mode (node shapes are not rendered, only the content) - * this feature was designed when graphs where meant to create user interfaces - * @method switchLiveMode - **/ - LGraphCanvas.prototype.switchLiveMode = function(transition) { - if (!transition) { - this.live_mode = !this.live_mode; - this.dirty_canvas = true; - this.dirty_bgcanvas = true; - return; - } - - var self = this; - var delta = this.live_mode ? 1.1 : 0.9; - if (this.live_mode) { - this.live_mode = false; - this.editor_alpha = 0.1; - } - - var t = setInterval(function() { - self.editor_alpha *= delta; - self.dirty_canvas = true; - self.dirty_bgcanvas = true; - - if (delta < 1 && self.editor_alpha < 0.01) { - clearInterval(t); - if (delta < 1) { - self.live_mode = true; - } - } - if (delta > 1 && self.editor_alpha > 0.99) { - clearInterval(t); - self.editor_alpha = 1; - } - }, 1); - }; - - LGraphCanvas.prototype.onNodeSelectionChange = function(node) { - return; //disabled - }; - - /* this is an implementation for touch not in production and not ready - */ - /*LGraphCanvas.prototype.touchHandler = function(event) { - //alert("foo"); - var touches = event.changedTouches, - first = touches[0], - type = ""; - - switch (event.type) { - case "touchstart": - type = "mousedown"; - break; - case "touchmove": - type = "mousemove"; - break; - case "touchend": - type = "mouseup"; - break; - default: - return; - } - - //initMouseEvent(type, canBubble, cancelable, view, clickCount, - // screenX, screenY, clientX, clientY, ctrlKey, - // altKey, shiftKey, metaKey, button, relatedTarget); - - // this is eventually a Dom object, get the LGraphCanvas back - if(typeof this.getCanvasWindow == "undefined"){ - var window = this.lgraphcanvas.getCanvasWindow(); - }else{ - var window = this.getCanvasWindow(); - } - - var document = window.document; - - var simulatedEvent = document.createEvent("MouseEvent"); - simulatedEvent.initMouseEvent( - type, - true, - true, - window, - 1, - first.screenX, - first.screenY, - first.clientX, - first.clientY, - false, - false, - false, - false, - 0, //left - null - ); - first.target.dispatchEvent(simulatedEvent); - event.preventDefault(); - };*/ - - /* CONTEXT MENU ********************/ - - LGraphCanvas.onGroupAdd = function(info, entry, mouse_event) { - var canvas = LGraphCanvas.active_canvas; - var ref_window = canvas.getCanvasWindow(); - - var group = new LiteGraph.LGraphGroup(); - group.pos = canvas.convertEventToCanvasOffset(mouse_event); - canvas.graph.add(group); - }; - - /** - * Determines the furthest nodes in each direction - * @param nodes {LGraphNode[]} the nodes to from which boundary nodes will be extracted - * @return {{left: LGraphNode, top: LGraphNode, right: LGraphNode, bottom: LGraphNode}} - */ - LGraphCanvas.getBoundaryNodes = function(nodes) { - let top = null; - let right = null; - let bottom = null; - let left = null; - for (const nID in nodes) { - const node = nodes[nID]; - const [x, y] = node.pos; - const [width, height] = node.size; - - if (top === null || y < top.pos[1]) { - top = node; - } - if (right === null || x + width > right.pos[0] + right.size[0]) { - right = node; - } - if (bottom === null || y + height > bottom.pos[1] + bottom.size[1]) { - bottom = node; - } - if (left === null || x < left.pos[0]) { - left = node; - } - } - - return { - "top": top, - "right": right, - "bottom": bottom, - "left": left - }; - } - /** - * Determines the furthest nodes in each direction for the currently selected nodes - * @return {{left: LGraphNode, top: LGraphNode, right: LGraphNode, bottom: LGraphNode}} - */ - LGraphCanvas.prototype.boundaryNodesForSelection = function() { - return LGraphCanvas.getBoundaryNodes(Object.values(this.selected_nodes)); - } - - /** - * - * @param {LGraphNode[]} nodes a list of nodes - * @param {"top"|"bottom"|"left"|"right"} direction Direction to align the nodes - * @param {LGraphNode?} align_to Node to align to (if null, align to the furthest node in the given direction) - */ - LGraphCanvas.alignNodes = function (nodes, direction, align_to) { - if (!nodes) { - return; - } - - const canvas = LGraphCanvas.active_canvas; - let boundaryNodes = [] - if (align_to === undefined) { - boundaryNodes = LGraphCanvas.getBoundaryNodes(nodes) - } else { - boundaryNodes = { - "top": align_to, - "right": align_to, - "bottom": align_to, - "left": align_to - } - } - - for (const [_, node] of Object.entries(canvas.selected_nodes)) { - switch (direction) { - case "right": - node.pos[0] = boundaryNodes["right"].pos[0] + boundaryNodes["right"].size[0] - node.size[0]; - break; - case "left": - node.pos[0] = boundaryNodes["left"].pos[0]; - break; - case "top": - node.pos[1] = boundaryNodes["top"].pos[1]; - break; - case "bottom": - node.pos[1] = boundaryNodes["bottom"].pos[1] + boundaryNodes["bottom"].size[1] - node.size[1]; - break; - } - } - - canvas.dirty_canvas = true; - canvas.dirty_bgcanvas = true; - }; - - LGraphCanvas.onNodeAlign = function(value, options, event, prev_menu, node) { - new LiteGraph.ContextMenu(["Top", "Bottom", "Left", "Right"], { - event: event, - callback: inner_clicked, - parentMenu: prev_menu, - }); - - function inner_clicked(value) { - LGraphCanvas.alignNodes(LGraphCanvas.active_canvas.selected_nodes, value.toLowerCase(), node); - } - } - - LGraphCanvas.onGroupAlign = function(value, options, event, prev_menu) { - new LiteGraph.ContextMenu(["Top", "Bottom", "Left", "Right"], { - event: event, - callback: inner_clicked, - parentMenu: prev_menu, - }); - - function inner_clicked(value) { - LGraphCanvas.alignNodes(LGraphCanvas.active_canvas.selected_nodes, value.toLowerCase()); - } - } - - LGraphCanvas.onMenuAdd = function (node, options, e, prev_menu, callback) { - - var canvas = LGraphCanvas.active_canvas; - var ref_window = canvas.getCanvasWindow(); - var graph = canvas.graph; - if (!graph) - return; - - function inner_onMenuAdded(base_category ,prev_menu){ - - var categories = LiteGraph.getNodeTypesCategories(canvas.filter || graph.filter).filter(function(category){return category.startsWith(base_category)}); - var entries = []; - - categories.map(function(category){ - - if (!category) - return; - - var base_category_regex = new RegExp('^(' + base_category + ')'); - var category_name = category.replace(base_category_regex,"").split('/')[0]; - var category_path = base_category === '' ? category_name + '/' : base_category + category_name + '/'; - - var name = category_name; - if(name.indexOf("::") != -1) //in case it has a namespace like "shader::math/rand" it hides the namespace - name = name.split("::")[1]; - - var index = entries.findIndex(function(entry){return entry.value === category_path}); - if (index === -1) { - entries.push({ value: category_path, content: name, has_submenu: true, callback : function(value, event, mouseEvent, contextMenu){ - inner_onMenuAdded(value.value, contextMenu) - }}); - } - - }); - - var nodes = LiteGraph.getNodeTypesInCategory(base_category.slice(0, -1), canvas.filter || graph.filter ); - nodes.map(function(node){ - - if (node.skip_list) - return; - - var entry = { value: node.type, content: node.title, has_submenu: false , callback : function(value, event, mouseEvent, contextMenu){ - - var first_event = contextMenu.getFirstEvent(); - canvas.graph.beforeChange(); - var node = LiteGraph.createNode(value.value); - if (node) { - node.pos = canvas.convertEventToCanvasOffset(first_event); - canvas.graph.add(node); - } - if(callback) - callback(node); - canvas.graph.afterChange(); - - } - } - - entries.push(entry); - - }); - - new LiteGraph.ContextMenu( entries, { event: e, parentMenu: prev_menu }, ref_window ); - - } - - inner_onMenuAdded('',prev_menu); - return false; - - }; - - LGraphCanvas.onMenuCollapseAll = function() {}; - - LGraphCanvas.onMenuNodeEdit = function() {}; - - LGraphCanvas.showMenuNodeOptionalInputs = function( - v, - options, - e, - prev_menu, - node - ) { - if (!node) { - return; - } - - var that = this; - var canvas = LGraphCanvas.active_canvas; - var ref_window = canvas.getCanvasWindow(); - - var options = node.optional_inputs; - if (node.onGetInputs) { - options = node.onGetInputs(); - } - - var entries = []; - if (options) { - for (var i=0; i < options.length; i++) { - var entry = options[i]; - if (!entry) { - entries.push(null); - continue; - } - var label = entry[0]; - if(!entry[2]) - entry[2] = {}; - - if (entry[2].label) { - label = entry[2].label; - } - - entry[2].removable = true; - var data = { content: label, value: entry }; - if (entry[1] == LiteGraph.ACTION) { - data.className = "event"; - } - entries.push(data); - } - } - - if (node.onMenuNodeInputs) { - var retEntries = node.onMenuNodeInputs(entries); - if(retEntries) entries = retEntries; - } - - if (!entries.length) { - console.log("no input entries"); - return; - } - - var menu = new LiteGraph.ContextMenu( - entries, - { - event: e, - callback: inner_clicked, - parentMenu: prev_menu, - node: node - }, - ref_window - ); - - function inner_clicked(v, e, prev) { - if (!node) { - return; - } - - if (v.callback) { - v.callback.call(that, node, v, e, prev); - } - - if (v.value) { - node.graph.beforeChange(); - node.addInput(v.value[0], v.value[1], v.value[2]); - - if (node.onNodeInputAdd) { // callback to the node when adding a slot - node.onNodeInputAdd(v.value); - } - node.setDirtyCanvas(true, true); - node.graph.afterChange(); - } - } - - return false; - }; - - LGraphCanvas.showMenuNodeOptionalOutputs = function( - v, - options, - e, - prev_menu, - node - ) { - if (!node) { - return; - } - - var that = this; - var canvas = LGraphCanvas.active_canvas; - var ref_window = canvas.getCanvasWindow(); - - var options = node.optional_outputs; - if (node.onGetOutputs) { - options = node.onGetOutputs(); - } - - var entries = []; - if (options) { - for (var i=0; i < options.length; i++) { - var entry = options[i]; - if (!entry) { - //separator? - entries.push(null); - continue; - } - - if ( - node.flags && - node.flags.skip_repeated_outputs && - node.findOutputSlot(entry[0]) != -1 - ) { - continue; - } //skip the ones already on - var label = entry[0]; - if(!entry[2]) - entry[2] = {}; - if (entry[2].label) { - label = entry[2].label; - } - entry[2].removable = true; - var data = { content: label, value: entry }; - if (entry[1] == LiteGraph.EVENT) { - data.className = "event"; - } - entries.push(data); - } - } - - if (this.onMenuNodeOutputs) { - entries = this.onMenuNodeOutputs(entries); - } - if (LiteGraph.do_add_triggers_slots){ //canvas.allow_addOutSlot_onExecuted - if (node.findOutputSlot("onExecuted") == -1){ - entries.push({content: "On Executed", value: ["onExecuted", LiteGraph.EVENT, {nameLocked: true}], className: "event"}); //, opts: {} - } - } - // add callback for modifing the menu elements onMenuNodeOutputs - if (node.onMenuNodeOutputs) { - var retEntries = node.onMenuNodeOutputs(entries); - if(retEntries) entries = retEntries; - } - - if (!entries.length) { - return; - } - - var menu = new LiteGraph.ContextMenu( - entries, - { - event: e, - callback: inner_clicked, - parentMenu: prev_menu, - node: node - }, - ref_window - ); - - function inner_clicked(v, e, prev) { - if (!node) { - return; - } - - if (v.callback) { - v.callback.call(that, node, v, e, prev); - } - - if (!v.value) { - return; - } - - var value = v.value[1]; - - if ( - value && - (value.constructor === Object || value.constructor === Array) - ) { - //submenu why? - var entries = []; - for (var i in value) { - entries.push({ content: i, value: value[i] }); - } - new LiteGraph.ContextMenu(entries, { - event: e, - callback: inner_clicked, - parentMenu: prev_menu, - node: node - }); - return false; - } else { - node.graph.beforeChange(); - node.addOutput(v.value[0], v.value[1], v.value[2]); - - if (node.onNodeOutputAdd) { // a callback to the node when adding a slot - node.onNodeOutputAdd(v.value); - } - node.setDirtyCanvas(true, true); - node.graph.afterChange(); - } - } - - return false; - }; - - LGraphCanvas.onShowMenuNodeProperties = function( - value, - options, - e, - prev_menu, - node - ) { - if (!node || !node.properties) { - return; - } - - var that = this; - var canvas = LGraphCanvas.active_canvas; - var ref_window = canvas.getCanvasWindow(); - - var entries = []; - for (var i in node.properties) { - var value = node.properties[i] !== undefined ? node.properties[i] : " "; - if( typeof value == "object" ) - value = JSON.stringify(value); - var info = node.getPropertyInfo(i); - if(info.type == "enum" || info.type == "combo") - value = LGraphCanvas.getPropertyPrintableValue( value, info.values ); - - //value could contain invalid html characters, clean that - value = LGraphCanvas.decodeHTML(value); - entries.push({ - content: - "" + - (info.label ? info.label : i) + - "" + - "" + - value + - "", - value: i - }); - } - if (!entries.length) { - return; - } - - var menu = new LiteGraph.ContextMenu( - entries, - { - event: e, - callback: inner_clicked, - parentMenu: prev_menu, - allow_html: true, - node: node - }, - ref_window - ); - - function inner_clicked(v, options, e, prev) { - if (!node) { - return; - } - var rect = this.getBoundingClientRect(); - canvas.showEditPropertyValue(node, v.value, { - position: [rect.left, rect.top] - }); - } - - return false; - }; - - LGraphCanvas.decodeHTML = function(str) { - var e = document.createElement("div"); - e.innerText = str; - return e.innerHTML; - }; - - LGraphCanvas.onMenuResizeNode = function(value, options, e, menu, node) { - if (!node) { - return; - } - - var fApplyMultiNode = function(node){ - node.size = node.computeSize(); - if (node.onResize) - node.onResize(node.size); - } - - var graphcanvas = LGraphCanvas.active_canvas; - if (!graphcanvas.selected_nodes || Object.keys(graphcanvas.selected_nodes).length <= 1){ - fApplyMultiNode(node); - }else{ - for (var i in graphcanvas.selected_nodes) { - fApplyMultiNode(graphcanvas.selected_nodes[i]); - } - } - - node.setDirtyCanvas(true, true); - }; - - LGraphCanvas.prototype.showLinkMenu = function(link, e) { - var that = this; - // console.log(link); - var node_left = that.graph.getNodeById( link.origin_id ); - var node_right = that.graph.getNodeById( link.target_id ); - var fromType = false; - if (node_left && node_left.outputs && node_left.outputs[link.origin_slot]) fromType = node_left.outputs[link.origin_slot].type; - var destType = false; - if (node_right && node_right.outputs && node_right.outputs[link.target_slot]) destType = node_right.inputs[link.target_slot].type; - - var options = ["Add Node",null,"Delete",null]; - - - var menu = new LiteGraph.ContextMenu(options, { - event: e, - title: link.data != null ? link.data.constructor.name : null, - callback: inner_clicked - }); - - function inner_clicked(v,options,e) { - switch (v) { - case "Add Node": - LGraphCanvas.onMenuAdd(null, null, e, menu, function(node){ - // console.debug("node autoconnect"); - if(!node.inputs || !node.inputs.length || !node.outputs || !node.outputs.length){ - return; - } - // leave the connection type checking inside connectByType - if (node_left.connectByType( link.origin_slot, node, fromType )){ - node.connectByType( link.target_slot, node_right, destType ); - node.pos[0] -= node.size[0] * 0.5; - } - }); - break; - - case "Delete": - that.graph.removeLink(link.id); - break; - default: - /*var nodeCreated = createDefaultNodeForSlot({ nodeFrom: node_left - ,slotFrom: link.origin_slot - ,nodeTo: node - ,slotTo: link.target_slot - ,e: e - ,nodeType: "AUTO" - }); - if(nodeCreated) console.log("new node in beetween "+v+" created");*/ - } - } - - return false; - }; - - LGraphCanvas.prototype.createDefaultNodeForSlot = function(optPass) { // addNodeMenu for connection - var optPass = optPass || {}; - var opts = Object.assign({ nodeFrom: null // input - ,slotFrom: null // input - ,nodeTo: null // output - ,slotTo: null // output - ,position: [] // pass the event coords - ,nodeType: null // choose a nodetype to add, AUTO to set at first good - ,posAdd:[0,0] // adjust x,y - ,posSizeFix:[0,0] // alpha, adjust the position x,y based on the new node size w,h - } - ,optPass - ); - var that = this; - - var isFrom = opts.nodeFrom && opts.slotFrom!==null; - var isTo = !isFrom && opts.nodeTo && opts.slotTo!==null; - - if (!isFrom && !isTo){ - console.warn("No data passed to createDefaultNodeForSlot "+opts.nodeFrom+" "+opts.slotFrom+" "+opts.nodeTo+" "+opts.slotTo); - return false; - } - if (!opts.nodeType){ - console.warn("No type to createDefaultNodeForSlot"); - return false; - } - - var nodeX = isFrom ? opts.nodeFrom : opts.nodeTo; - var slotX = isFrom ? opts.slotFrom : opts.slotTo; - - var iSlotConn = false; - switch (typeof slotX){ - case "string": - iSlotConn = isFrom ? nodeX.findOutputSlot(slotX,false) : nodeX.findInputSlot(slotX,false); - slotX = isFrom ? nodeX.outputs[slotX] : nodeX.inputs[slotX]; - break; - case "object": - // ok slotX - iSlotConn = isFrom ? nodeX.findOutputSlot(slotX.name) : nodeX.findInputSlot(slotX.name); - break; - case "number": - iSlotConn = slotX; - slotX = isFrom ? nodeX.outputs[slotX] : nodeX.inputs[slotX]; - break; - case "undefined": - default: - // bad ? - //iSlotConn = 0; - console.warn("Cant get slot information "+slotX); - return false; - } - - if (slotX===false || iSlotConn===false){ - console.warn("createDefaultNodeForSlot bad slotX "+slotX+" "+iSlotConn); - } - - // check for defaults nodes for this slottype - var fromSlotType = slotX.type==LiteGraph.EVENT?"_event_":slotX.type; - var slotTypesDefault = isFrom ? LiteGraph.slot_types_default_out : LiteGraph.slot_types_default_in; - if(slotTypesDefault && slotTypesDefault[fromSlotType]){ - if (slotX.link !== null) { - // is connected - }else{ - // is not not connected - } - nodeNewType = false; - if(typeof slotTypesDefault[fromSlotType] == "object" || typeof slotTypesDefault[fromSlotType] == "array"){ - for(var typeX in slotTypesDefault[fromSlotType]){ - if (opts.nodeType == slotTypesDefault[fromSlotType][typeX] || opts.nodeType == "AUTO"){ - nodeNewType = slotTypesDefault[fromSlotType][typeX]; - // console.log("opts.nodeType == slotTypesDefault[fromSlotType][typeX] :: "+opts.nodeType); - break; // -------- - } - } - }else{ - if (opts.nodeType == slotTypesDefault[fromSlotType] || opts.nodeType == "AUTO") nodeNewType = slotTypesDefault[fromSlotType]; - } - if (nodeNewType) { - var nodeNewOpts = false; - if (typeof nodeNewType == "object" && nodeNewType.node){ - nodeNewOpts = nodeNewType; - nodeNewType = nodeNewType.node; - } - - //that.graph.beforeChange(); - - var newNode = LiteGraph.createNode(nodeNewType); - if(newNode){ - // if is object pass options - if (nodeNewOpts){ - if (nodeNewOpts.properties) { - for (var i in nodeNewOpts.properties) { - newNode.addProperty( i, nodeNewOpts.properties[i] ); - } - } - if (nodeNewOpts.inputs) { - newNode.inputs = []; - for (var i in nodeNewOpts.inputs) { - newNode.addOutput( - nodeNewOpts.inputs[i][0], - nodeNewOpts.inputs[i][1] - ); - } - } - if (nodeNewOpts.outputs) { - newNode.outputs = []; - for (var i in nodeNewOpts.outputs) { - newNode.addOutput( - nodeNewOpts.outputs[i][0], - nodeNewOpts.outputs[i][1] - ); - } - } - if (nodeNewOpts.title) { - newNode.title = nodeNewOpts.title; - } - if (nodeNewOpts.json) { - newNode.configure(nodeNewOpts.json); - } - - } - - // add the node - that.graph.add(newNode); - newNode.pos = [ opts.position[0]+opts.posAdd[0]+(opts.posSizeFix[0]?opts.posSizeFix[0]*newNode.size[0]:0) - ,opts.position[1]+opts.posAdd[1]+(opts.posSizeFix[1]?opts.posSizeFix[1]*newNode.size[1]:0)]; //that.last_click_position; //[e.canvasX+30, e.canvasX+5];*/ - - //that.graph.afterChange(); - - // connect the two! - if (isFrom){ - opts.nodeFrom.connectByType( iSlotConn, newNode, fromSlotType ); - }else{ - opts.nodeTo.connectByTypeOutput( iSlotConn, newNode, fromSlotType ); - } - - // if connecting in between - if (isFrom && isTo){ - // TODO - } - - return true; - - }else{ - console.log("failed creating "+nodeNewType); - } - } - } - return false; - } - - LGraphCanvas.prototype.showConnectionMenu = function(optPass) { // addNodeMenu for connection - var optPass = optPass || {}; - var opts = Object.assign({ nodeFrom: null // input - ,slotFrom: null // input - ,nodeTo: null // output - ,slotTo: null // output - ,e: null - } - ,optPass - ); - var that = this; - - var isFrom = opts.nodeFrom && opts.slotFrom; - var isTo = !isFrom && opts.nodeTo && opts.slotTo; - - if (!isFrom && !isTo){ - console.warn("No data passed to showConnectionMenu"); - return false; - } - - var nodeX = isFrom ? opts.nodeFrom : opts.nodeTo; - var slotX = isFrom ? opts.slotFrom : opts.slotTo; - - var iSlotConn = false; - switch (typeof slotX){ - case "string": - iSlotConn = isFrom ? nodeX.findOutputSlot(slotX,false) : nodeX.findInputSlot(slotX,false); - slotX = isFrom ? nodeX.outputs[slotX] : nodeX.inputs[slotX]; - break; - case "object": - // ok slotX - iSlotConn = isFrom ? nodeX.findOutputSlot(slotX.name) : nodeX.findInputSlot(slotX.name); - break; - case "number": - iSlotConn = slotX; - slotX = isFrom ? nodeX.outputs[slotX] : nodeX.inputs[slotX]; - break; - default: - // bad ? - //iSlotConn = 0; - console.warn("Cant get slot information "+slotX); - return false; - } - - var options = ["Add Node",null]; - - if (that.allow_searchbox){ - options.push("Search"); - options.push(null); - } - - // get defaults nodes for this slottype - var fromSlotType = slotX.type==LiteGraph.EVENT?"_event_":slotX.type; - var slotTypesDefault = isFrom ? LiteGraph.slot_types_default_out : LiteGraph.slot_types_default_in; - if(slotTypesDefault && slotTypesDefault[fromSlotType]){ - if(typeof slotTypesDefault[fromSlotType] == "object" || typeof slotTypesDefault[fromSlotType] == "array"){ - for(var typeX in slotTypesDefault[fromSlotType]){ - options.push(slotTypesDefault[fromSlotType][typeX]); - } - }else{ - options.push(slotTypesDefault[fromSlotType]); - } - } - - // build menu - var menu = new LiteGraph.ContextMenu(options, { - event: opts.e, - title: (slotX && slotX.name!="" ? (slotX.name + (fromSlotType?" | ":"")) : "")+(slotX && fromSlotType ? fromSlotType : ""), - callback: inner_clicked - }); - - // callback - function inner_clicked(v,options,e) { - //console.log("Process showConnectionMenu selection"); - switch (v) { - case "Add Node": - LGraphCanvas.onMenuAdd(null, null, e, menu, function(node){ - if (isFrom){ - opts.nodeFrom.connectByType( iSlotConn, node, fromSlotType ); - }else{ - opts.nodeTo.connectByTypeOutput( iSlotConn, node, fromSlotType ); - } - }); - break; - case "Search": - if(isFrom){ - that.showSearchBox(e,{node_from: opts.nodeFrom, slot_from: slotX, type_filter_in: fromSlotType}); - }else{ - that.showSearchBox(e,{node_to: opts.nodeTo, slot_from: slotX, type_filter_out: fromSlotType}); - } - break; - default: - // check for defaults nodes for this slottype - var nodeCreated = that.createDefaultNodeForSlot(Object.assign(opts,{ position: [opts.e.canvasX, opts.e.canvasY] - ,nodeType: v - })); - if (nodeCreated){ - // new node created - //console.log("node "+v+" created") - }else{ - // failed or v is not in defaults - } - break; - } - } - - return false; - }; - - // TODO refactor :: this is used fot title but not for properties! - LGraphCanvas.onShowPropertyEditor = function(item, options, e, menu, node) { - var input_html = ""; - var property = item.property || "title"; - var value = node[property]; - - // TODO refactor :: use createDialog ? - - var dialog = document.createElement("div"); - dialog.is_modified = false; - dialog.className = "graphdialog"; - dialog.innerHTML = - "OK"; - dialog.close = function() { - if (dialog.parentNode) { - dialog.parentNode.removeChild(dialog); - } - }; - var title = dialog.querySelector(".name"); - title.innerText = property; - var input = dialog.querySelector(".value"); - if (input) { - input.value = value; - input.addEventListener("blur", function(e) { - this.focus(); - }); - input.addEventListener("keydown", function(e) { - dialog.is_modified = true; - if (e.keyCode == 27) { - //ESC - dialog.close(); - } else if (e.keyCode == 13) { - inner(); // save - } else if (e.keyCode != 13 && e.target.localName != "textarea") { - return; - } - e.preventDefault(); - e.stopPropagation(); - }); - } - - var graphcanvas = LGraphCanvas.active_canvas; - var canvas = graphcanvas.canvas; - - var rect = canvas.getBoundingClientRect(); - var offsetx = -20; - var offsety = -20; - if (rect) { - offsetx -= rect.left; - offsety -= rect.top; - } - - if (event) { - dialog.style.left = event.clientX + offsetx + "px"; - dialog.style.top = event.clientY + offsety + "px"; - } else { - dialog.style.left = canvas.width * 0.5 + offsetx + "px"; - dialog.style.top = canvas.height * 0.5 + offsety + "px"; - } - - var button = dialog.querySelector("button"); - button.addEventListener("click", inner); - canvas.parentNode.appendChild(dialog); - - if(input) input.focus(); - - var dialogCloseTimer = null; - dialog.addEventListener("mouseleave", function(e) { - if(LiteGraph.dialog_close_on_mouse_leave) - if (!dialog.is_modified && LiteGraph.dialog_close_on_mouse_leave) - dialogCloseTimer = setTimeout(dialog.close, LiteGraph.dialog_close_on_mouse_leave_delay); //dialog.close(); - }); - dialog.addEventListener("mouseenter", function(e) { - if(LiteGraph.dialog_close_on_mouse_leave) - if(dialogCloseTimer) clearTimeout(dialogCloseTimer); - }); - - function inner() { - if(input) setValue(input.value); - } - - function setValue(value) { - if (item.type == "Number") { - value = Number(value); - } else if (item.type == "Boolean") { - value = Boolean(value); - } - node[property] = value; - if (dialog.parentNode) { - dialog.parentNode.removeChild(dialog); - } - node.setDirtyCanvas(true, true); - } - }; - - // refactor: there are different dialogs, some uses createDialog some dont - LGraphCanvas.prototype.prompt = function(title, value, callback, event, multiline) { - var that = this; - var input_html = ""; - title = title || ""; - - var dialog = document.createElement("div"); - dialog.is_modified = false; - dialog.className = "graphdialog rounded"; - if(multiline) - dialog.innerHTML = " OK"; - else - dialog.innerHTML = " OK"; - dialog.close = function() { - that.prompt_box = null; - if (dialog.parentNode) { - dialog.parentNode.removeChild(dialog); - } - }; - - var graphcanvas = LGraphCanvas.active_canvas; - var canvas = graphcanvas.canvas; - canvas.parentNode.appendChild(dialog); - - if (this.ds.scale > 1) { - dialog.style.transform = "scale(" + this.ds.scale + ")"; - } - - var dialogCloseTimer = null; - var prevent_timeout = false; - LiteGraph.pointerListenerAdd(dialog,"leave", function(e) { - if (prevent_timeout) - return; - if(LiteGraph.dialog_close_on_mouse_leave) - if (!dialog.is_modified && LiteGraph.dialog_close_on_mouse_leave) - dialogCloseTimer = setTimeout(dialog.close, LiteGraph.dialog_close_on_mouse_leave_delay); //dialog.close(); - }); - LiteGraph.pointerListenerAdd(dialog,"enter", function(e) { - if(LiteGraph.dialog_close_on_mouse_leave) - if(dialogCloseTimer) clearTimeout(dialogCloseTimer); - }); - var selInDia = dialog.querySelectorAll("select"); - if (selInDia){ - // if filtering, check focus changed to comboboxes and prevent closing - selInDia.forEach(function(selIn) { - selIn.addEventListener("click", function(e) { - prevent_timeout++; - }); - selIn.addEventListener("blur", function(e) { - prevent_timeout = 0; - }); - selIn.addEventListener("change", function(e) { - prevent_timeout = -1; - }); - }); - } - - if (that.prompt_box) { - that.prompt_box.close(); - } - that.prompt_box = dialog; - - var first = null; - var timeout = null; - var selected = null; - - var name_element = dialog.querySelector(".name"); - name_element.innerText = title; - var value_element = dialog.querySelector(".value"); - value_element.value = value; - value_element.select(); - - var input = value_element; - input.addEventListener("keydown", function(e) { - dialog.is_modified = true; - if (e.keyCode == 27) { - //ESC - dialog.close(); - } else if (e.keyCode == 13 && e.target.localName != "textarea") { - if (callback) { - callback(this.value); - } - dialog.close(); - } else { - return; - } - e.preventDefault(); - e.stopPropagation(); - }); - - var button = dialog.querySelector("button"); - button.addEventListener("click", function(e) { - if (callback) { - callback(input.value); - } - that.setDirty(true); - dialog.close(); - }); - - var rect = canvas.getBoundingClientRect(); - var offsetx = -20; - var offsety = -20; - if (rect) { - offsetx -= rect.left; - offsety -= rect.top; - } - - if (event) { - dialog.style.left = event.clientX + offsetx + "px"; - dialog.style.top = event.clientY + offsety + "px"; - } else { - dialog.style.left = canvas.width * 0.5 + offsetx + "px"; - dialog.style.top = canvas.height * 0.5 + offsety + "px"; - } - - setTimeout(function() { - input.focus(); - }, 10); - - return dialog; - }; - - LGraphCanvas.search_limit = -1; - LGraphCanvas.prototype.showSearchBox = function(event, options) { - // proposed defaults - var def_options = { slot_from: null - ,node_from: null - ,node_to: null - ,do_type_filter: LiteGraph.search_filter_enabled // TODO check for registered_slot_[in/out]_types not empty // this will be checked for functionality enabled : filter on slot type, in and out - ,type_filter_in: false // these are default: pass to set initially set values - ,type_filter_out: false - ,show_general_if_none_on_typefilter: true - ,show_general_after_typefiltered: true - ,hide_on_mouse_leave: LiteGraph.search_hide_on_mouse_leave - ,show_all_if_empty: true - ,show_all_on_open: LiteGraph.search_show_all_on_open - }; - options = Object.assign(def_options, options || {}); - - //console.log(options); - - var that = this; - var input_html = ""; - var graphcanvas = LGraphCanvas.active_canvas; - var canvas = graphcanvas.canvas; - var root_document = canvas.ownerDocument || document; - - var dialog = document.createElement("div"); - dialog.className = "litegraph litesearchbox graphdialog rounded"; - dialog.innerHTML = "Search "; - if (options.do_type_filter){ - dialog.innerHTML += ""; - dialog.innerHTML += ""; - } - dialog.innerHTML += ""; - - if( root_document.fullscreenElement ) - root_document.fullscreenElement.appendChild(dialog); - else - { - root_document.body.appendChild(dialog); - root_document.body.style.overflow = "hidden"; - } - // dialog element has been appended - - if (options.do_type_filter){ - var selIn = dialog.querySelector(".slot_in_type_filter"); - var selOut = dialog.querySelector(".slot_out_type_filter"); - } - - dialog.close = function() { - that.search_box = null; - this.blur(); - canvas.focus(); - root_document.body.style.overflow = ""; - - setTimeout(function() { - that.canvas.focus(); - }, 20); //important, if canvas loses focus keys wont be captured - if (dialog.parentNode) { - dialog.parentNode.removeChild(dialog); - } - }; - - if (this.ds.scale > 1) { - dialog.style.transform = "scale(" + this.ds.scale + ")"; - } - - // hide on mouse leave - if(options.hide_on_mouse_leave){ - var prevent_timeout = false; - var timeout_close = null; - LiteGraph.pointerListenerAdd(dialog,"enter", function(e) { - if (timeout_close) { - clearTimeout(timeout_close); - timeout_close = null; - } - }); - LiteGraph.pointerListenerAdd(dialog,"leave", function(e) { - if (prevent_timeout){ - return; - } - timeout_close = setTimeout(function() { - dialog.close(); - }, typeof options.hide_on_mouse_leave === "number" ? options.hide_on_mouse_leave : 500); - }); - // if filtering, check focus changed to comboboxes and prevent closing - if (options.do_type_filter){ - selIn.addEventListener("click", function(e) { - prevent_timeout++; - }); - selIn.addEventListener("blur", function(e) { - prevent_timeout = 0; - }); - selIn.addEventListener("change", function(e) { - prevent_timeout = -1; - }); - selOut.addEventListener("click", function(e) { - prevent_timeout++; - }); - selOut.addEventListener("blur", function(e) { - prevent_timeout = 0; - }); - selOut.addEventListener("change", function(e) { - prevent_timeout = -1; - }); - } - } - - if (that.search_box) { - that.search_box.close(); - } - that.search_box = dialog; - - var helper = dialog.querySelector(".helper"); - - var first = null; - var timeout = null; - var selected = null; - - var input = dialog.querySelector("input"); - if (input) { - input.addEventListener("blur", function(e) { - this.focus(); - }); - input.addEventListener("keydown", function(e) { - if (e.keyCode == 38) { - //UP - changeSelection(false); - } else if (e.keyCode == 40) { - //DOWN - changeSelection(true); - } else if (e.keyCode == 27) { - //ESC - dialog.close(); - } else if (e.keyCode == 13) { - if (selected) { - select(unescape(selected.dataset["type"])); - } else if (first) { - select(first); - } else { - dialog.close(); - } - } else { - if (timeout) { - clearInterval(timeout); - } - timeout = setTimeout(refreshHelper, 10); - return; - } - e.preventDefault(); - e.stopPropagation(); - e.stopImmediatePropagation(); - return true; - }); - } - - // if should filter on type, load and fill selected and choose elements if passed - if (options.do_type_filter){ - if (selIn){ - var aSlots = LiteGraph.slot_types_in; - var nSlots = aSlots.length; // this for object :: Object.keys(aSlots).length; - - if (options.type_filter_in == LiteGraph.EVENT || options.type_filter_in == LiteGraph.ACTION) - options.type_filter_in = "_event_"; - /* this will filter on * .. but better do it manually in case - else if(options.type_filter_in === "" || options.type_filter_in === 0) - options.type_filter_in = "*";*/ - - for (var iK=0; iK (rect.height - 200)) - helper.style.maxHeight = (rect.height - event.layerY - 20) + "px"; - - /* - var offsetx = -20; - var offsety = -20; - if (rect) { - offsetx -= rect.left; - offsety -= rect.top; - } - - if (event) { - dialog.style.left = event.clientX + offsetx + "px"; - dialog.style.top = event.clientY + offsety + "px"; - } else { - dialog.style.left = canvas.width * 0.5 + offsetx + "px"; - dialog.style.top = canvas.height * 0.5 + offsety + "px"; - } - canvas.parentNode.appendChild(dialog); - */ - - input.focus(); - if (options.show_all_on_open) refreshHelper(); - - function select(name) { - if (name) { - if (that.onSearchBoxSelection) { - that.onSearchBoxSelection(name, event, graphcanvas); - } else { - var extra = LiteGraph.searchbox_extras[name.toLowerCase()]; - if (extra) { - name = extra.type; - } - - graphcanvas.graph.beforeChange(); - var node = LiteGraph.createNode(name); - if (node) { - node.pos = graphcanvas.convertEventToCanvasOffset( - event - ); - graphcanvas.graph.add(node, false); - } - - if (extra && extra.data) { - if (extra.data.properties) { - for (var i in extra.data.properties) { - node.addProperty( i, extra.data.properties[i] ); - } - } - if (extra.data.inputs) { - node.inputs = []; - for (var i in extra.data.inputs) { - node.addOutput( - extra.data.inputs[i][0], - extra.data.inputs[i][1] - ); - } - } - if (extra.data.outputs) { - node.outputs = []; - for (var i in extra.data.outputs) { - node.addOutput( - extra.data.outputs[i][0], - extra.data.outputs[i][1] - ); - } - } - if (extra.data.title) { - node.title = extra.data.title; - } - if (extra.data.json) { - node.configure(extra.data.json); - } - - } - - // join node after inserting - if (options.node_from){ - var iS = false; - switch (typeof options.slot_from){ - case "string": - iS = options.node_from.findOutputSlot(options.slot_from); - break; - case "object": - if (options.slot_from.name){ - iS = options.node_from.findOutputSlot(options.slot_from.name); - }else{ - iS = -1; - } - if (iS==-1 && typeof options.slot_from.slot_index !== "undefined") iS = options.slot_from.slot_index; - break; - case "number": - iS = options.slot_from; - break; - default: - iS = 0; // try with first if no name set - } - if (typeof options.node_from.outputs[iS] !== "undefined"){ - if (iS!==false && iS>-1){ - options.node_from.connectByType( iS, node, options.node_from.outputs[iS].type ); - } - }else{ - // console.warn("cant find slot " + options.slot_from); - } - } - if (options.node_to){ - var iS = false; - switch (typeof options.slot_from){ - case "string": - iS = options.node_to.findInputSlot(options.slot_from); - break; - case "object": - if (options.slot_from.name){ - iS = options.node_to.findInputSlot(options.slot_from.name); - }else{ - iS = -1; - } - if (iS==-1 && typeof options.slot_from.slot_index !== "undefined") iS = options.slot_from.slot_index; - break; - case "number": - iS = options.slot_from; - break; - default: - iS = 0; // try with first if no name set - } - if (typeof options.node_to.inputs[iS] !== "undefined"){ - if (iS!==false && iS>-1){ - // try connection - options.node_to.connectByTypeOutput(iS,node,options.node_to.inputs[iS].type); - } - }else{ - // console.warn("cant find slot_nodeTO " + options.slot_from); - } - } - - graphcanvas.graph.afterChange(); - } - } - - dialog.close(); - } - - function changeSelection(forward) { - var prev = selected; - if (selected) { - selected.classList.remove("selected"); - } - if (!selected) { - selected = forward - ? helper.childNodes[0] - : helper.childNodes[helper.childNodes.length]; - } else { - selected = forward - ? selected.nextSibling - : selected.previousSibling; - if (!selected) { - selected = prev; - } - } - if (!selected) { - return; - } - selected.classList.add("selected"); - selected.scrollIntoView({block: "end", behavior: "smooth"}); - } - - function refreshHelper() { - timeout = null; - var str = input.value; - first = null; - helper.innerHTML = ""; - if (!str && !options.show_all_if_empty) { - return; - } - - if (that.onSearchBox) { - var list = that.onSearchBox(helper, str, graphcanvas); - if (list) { - for (var i = 0; i < list.length; ++i) { - addResult(list[i]); - } - } - } else { - var c = 0; - str = str.toLowerCase(); - var filter = graphcanvas.filter || graphcanvas.graph.filter; - - // filter by type preprocess - if(options.do_type_filter && that.search_box){ - var sIn = that.search_box.querySelector(".slot_in_type_filter"); - var sOut = that.search_box.querySelector(".slot_out_type_filter"); - }else{ - var sIn = false; - var sOut = false; - } - - //extras - for (var i in LiteGraph.searchbox_extras) { - var extra = LiteGraph.searchbox_extras[i]; - if ((!options.show_all_if_empty || str) && extra.desc.toLowerCase().indexOf(str) === -1) { - continue; - } - var ctor = LiteGraph.registered_node_types[ extra.type ]; - if( ctor && ctor.filter != filter ) - continue; - if( ! inner_test_filter(extra.type) ) - continue; - addResult( extra.desc, "searchbox_extra" ); - if ( LGraphCanvas.search_limit !== -1 && c++ > LGraphCanvas.search_limit ) { - break; - } - } - - var filtered = null; - if (Array.prototype.filter) { //filter supported - var keys = Object.keys( LiteGraph.registered_node_types ); //types - var filtered = keys.filter( inner_test_filter ); - } else { - filtered = []; - for (var i in LiteGraph.registered_node_types) { - if( inner_test_filter(i) ) - filtered.push(i); - } - } - - for (var i = 0; i < filtered.length; i++) { - addResult(filtered[i]); - if ( LGraphCanvas.search_limit !== -1 && c++ > LGraphCanvas.search_limit ) { - break; - } - } - - // add general type if filtering - if (options.show_general_after_typefiltered - && (sIn.value || sOut.value) - ){ - filtered_extra = []; - for (var i in LiteGraph.registered_node_types) { - if( inner_test_filter(i, {inTypeOverride: sIn&&sIn.value?"*":false, outTypeOverride: sOut&&sOut.value?"*":false}) ) - filtered_extra.push(i); - } - for (var i = 0; i < filtered_extra.length; i++) { - addResult(filtered_extra[i], "generic_type"); - if ( LGraphCanvas.search_limit !== -1 && c++ > LGraphCanvas.search_limit ) { - break; - } - } - } - - // check il filtering gave no results - if ((sIn.value || sOut.value) && - ( (helper.childNodes.length == 0 && options.show_general_if_none_on_typefilter) ) - ){ - filtered_extra = []; - for (var i in LiteGraph.registered_node_types) { - if( inner_test_filter(i, {skipFilter: true}) ) - filtered_extra.push(i); - } - for (var i = 0; i < filtered_extra.length; i++) { - addResult(filtered_extra[i], "not_in_filter"); - if ( LGraphCanvas.search_limit !== -1 && c++ > LGraphCanvas.search_limit ) { - break; - } - } - } - - function inner_test_filter( type, optsIn ) - { - var optsIn = optsIn || {}; - var optsDef = { skipFilter: false - ,inTypeOverride: false - ,outTypeOverride: false - }; - var opts = Object.assign(optsDef,optsIn); - var ctor = LiteGraph.registered_node_types[ type ]; - if(filter && ctor.filter != filter ) - return false; - if ((!options.show_all_if_empty || str) && type.toLowerCase().indexOf(str) === -1 && (!ctor.title || ctor.title.toLowerCase().indexOf(str) === -1)) - return false; - - // filter by slot IN, OUT types - if(options.do_type_filter && !opts.skipFilter){ - var sType = type; - - var sV = sIn.value; - if (opts.inTypeOverride!==false) sV = opts.inTypeOverride; - //if (sV.toLowerCase() == "_event_") sV = LiteGraph.EVENT; // -1 - - if(sIn && sV){ - //console.log("will check filter against "+sV); - if (LiteGraph.registered_slot_in_types[sV] && LiteGraph.registered_slot_in_types[sV].nodes){ // type is stored - //console.debug("check "+sType+" in "+LiteGraph.registered_slot_in_types[sV].nodes); - var doesInc = LiteGraph.registered_slot_in_types[sV].nodes.includes(sType); - if (doesInc!==false){ - //console.log(sType+" HAS "+sV); - }else{ - /*console.debug(LiteGraph.registered_slot_in_types[sV]); - console.log(+" DONT includes "+type);*/ - return false; - } - } - } - - var sV = sOut.value; - if (opts.outTypeOverride!==false) sV = opts.outTypeOverride; - //if (sV.toLowerCase() == "_event_") sV = LiteGraph.EVENT; // -1 - - if(sOut && sV){ - //console.log("search will check filter against "+sV); - if (LiteGraph.registered_slot_out_types[sV] && LiteGraph.registered_slot_out_types[sV].nodes){ // type is stored - //console.debug("check "+sType+" in "+LiteGraph.registered_slot_out_types[sV].nodes); - var doesInc = LiteGraph.registered_slot_out_types[sV].nodes.includes(sType); - if (doesInc!==false){ - //console.log(sType+" HAS "+sV); - }else{ - /*console.debug(LiteGraph.registered_slot_out_types[sV]); - console.log(+" DONT includes "+type);*/ - return false; - } - } - } - } - return true; - } - } - - function addResult(type, className) { - var help = document.createElement("div"); - if (!first) { - first = type; - } - - const nodeType = LiteGraph.registered_node_types[type]; - if (nodeType?.title) { - help.innerText = nodeType?.title; - const typeEl = document.createElement("span"); - typeEl.className = "litegraph lite-search-item-type"; - typeEl.textContent = type; - help.append(typeEl); - } else { - help.innerText = type; - } - - help.dataset["type"] = escape(type); - help.className = "litegraph lite-search-item"; - if (className) { - help.className += " " + className; - } - help.addEventListener("click", function(e) { - select(unescape(this.dataset["type"])); - }); - helper.appendChild(help); - } - } - - return dialog; - }; - - LGraphCanvas.prototype.showEditPropertyValue = function( node, property, options ) { - if (!node || node.properties[property] === undefined) { - return; - } - - options = options || {}; - var that = this; - - var info = node.getPropertyInfo(property); - var type = info.type; - - var input_html = ""; - - if (type == "string" || type == "number" || type == "array" || type == "object") { - input_html = ""; - } else if ( (type == "enum" || type == "combo") && info.values) { - input_html = ""; - for (var i in info.values) { - var v = i; - if( info.values.constructor === Array ) - v = info.values[i]; - - input_html += - "" + - info.values[i] + - ""; - } - input_html += ""; - } else if (type == "boolean" || type == "toggle") { - input_html = - ""; - } else { - console.warn("unknown type: " + type); - return; - } - - var dialog = this.createDialog( - "" + - (info.label ? info.label : property) + - "" + - input_html + - "OK", - options - ); - - var input = false; - if ((type == "enum" || type == "combo") && info.values) { - input = dialog.querySelector("select"); - input.addEventListener("change", function(e) { - dialog.modified(); - setValue(e.target.value); - //var index = e.target.value; - //setValue( e.options[e.selectedIndex].value ); - }); - } else if (type == "boolean" || type == "toggle") { - input = dialog.querySelector("input"); - if (input) { - input.addEventListener("click", function(e) { - dialog.modified(); - setValue(!!input.checked); - }); - } - } else { - input = dialog.querySelector("input"); - if (input) { - input.addEventListener("blur", function(e) { - this.focus(); - }); - - var v = node.properties[property] !== undefined ? node.properties[property] : ""; - if (type !== 'string') { - v = JSON.stringify(v); - } - - input.value = v; - input.addEventListener("keydown", function(e) { - if (e.keyCode == 27) { - //ESC - dialog.close(); - } else if (e.keyCode == 13) { - // ENTER - inner(); // save - } else if (e.keyCode != 13) { - dialog.modified(); - return; - } - e.preventDefault(); - e.stopPropagation(); - }); - } - } - if (input) input.focus(); - - var button = dialog.querySelector("button"); - button.addEventListener("click", inner); - - function inner() { - setValue(input.value); - } - - function setValue(value) { - - if(info && info.values && info.values.constructor === Object && info.values[value] != undefined ) - value = info.values[value]; - - if (typeof node.properties[property] == "number") { - value = Number(value); - } - if (type == "array" || type == "object") { - value = JSON.parse(value); - } - node.properties[property] = value; - if (node.graph) { - node.graph._version++; - } - if (node.onPropertyChanged) { - node.onPropertyChanged(property, value); - } - if(options.onclose) - options.onclose(); - dialog.close(); - node.setDirtyCanvas(true, true); - } - - return dialog; - }; - - // TODO refactor, theer are different dialog, some uses createDialog, some dont - LGraphCanvas.prototype.createDialog = function(html, options) { - var def_options = { checkForInput: false, closeOnLeave: true, closeOnLeave_checkModified: true }; - options = Object.assign(def_options, options || {}); - - var dialog = document.createElement("div"); - dialog.className = "graphdialog"; - dialog.innerHTML = html; - dialog.is_modified = false; - - var rect = this.canvas.getBoundingClientRect(); - var offsetx = -20; - var offsety = -20; - if (rect) { - offsetx -= rect.left; - offsety -= rect.top; - } - - if (options.position) { - offsetx += options.position[0]; - offsety += options.position[1]; - } else if (options.event) { - offsetx += options.event.clientX; - offsety += options.event.clientY; - } //centered - else { - offsetx += this.canvas.width * 0.5; - offsety += this.canvas.height * 0.5; - } - - dialog.style.left = offsetx + "px"; - dialog.style.top = offsety + "px"; - - this.canvas.parentNode.appendChild(dialog); - - // acheck for input and use default behaviour: save on enter, close on esc - if (options.checkForInput){ - var aI = []; - var focused = false; - if (aI = dialog.querySelectorAll("input")){ - aI.forEach(function(iX) { - iX.addEventListener("keydown",function(e){ - dialog.modified(); - if (e.keyCode == 27) { - dialog.close(); - } else if (e.keyCode != 13) { - return; - } - // set value ? - e.preventDefault(); - e.stopPropagation(); - }); - if (!focused) iX.focus(); - }); - } - } - - dialog.modified = function(){ - dialog.is_modified = true; - } - dialog.close = function() { - if (dialog.parentNode) { - dialog.parentNode.removeChild(dialog); - } - }; - - var dialogCloseTimer = null; - var prevent_timeout = false; - dialog.addEventListener("mouseleave", function(e) { - if (prevent_timeout) - return; - if(options.closeOnLeave || LiteGraph.dialog_close_on_mouse_leave) - if (!dialog.is_modified && LiteGraph.dialog_close_on_mouse_leave) - dialogCloseTimer = setTimeout(dialog.close, LiteGraph.dialog_close_on_mouse_leave_delay); //dialog.close(); - }); - dialog.addEventListener("mouseenter", function(e) { - if(options.closeOnLeave || LiteGraph.dialog_close_on_mouse_leave) - if(dialogCloseTimer) clearTimeout(dialogCloseTimer); - }); - var selInDia = dialog.querySelectorAll("select"); - if (selInDia){ - // if filtering, check focus changed to comboboxes and prevent closing - selInDia.forEach(function(selIn) { - selIn.addEventListener("click", function(e) { - prevent_timeout++; - }); - selIn.addEventListener("blur", function(e) { - prevent_timeout = 0; - }); - selIn.addEventListener("change", function(e) { - prevent_timeout = -1; - }); - }); - } - - return dialog; - }; - - LGraphCanvas.prototype.createPanel = function(title, options) { - options = options || {}; - - var ref_window = options.window || window; - var root = document.createElement("div"); - root.className = "litegraph dialog"; - root.innerHTML = ""; - root.header = root.querySelector(".dialog-header"); - - if(options.width) - root.style.width = options.width + (options.width.constructor === Number ? "px" : ""); - if(options.height) - root.style.height = options.height + (options.height.constructor === Number ? "px" : ""); - if(options.closable) - { - var close = document.createElement("span"); - close.innerHTML = "✕"; - close.classList.add("close"); - close.addEventListener("click",function(){ - root.close(); - }); - root.header.appendChild(close); - } - root.title_element = root.querySelector(".dialog-title"); - root.title_element.innerText = title; - root.content = root.querySelector(".dialog-content"); - root.alt_content = root.querySelector(".dialog-alt-content"); - root.footer = root.querySelector(".dialog-footer"); - - root.close = function() - { - if (root.onClose && typeof root.onClose == "function"){ - root.onClose(); - } - if(root.parentNode) - root.parentNode.removeChild(root); - /* XXX CHECK THIS */ - if(this.parentNode){ - this.parentNode.removeChild(this); - } - /* XXX this was not working, was fixed with an IF, check this */ - } - - // function to swap panel content - root.toggleAltContent = function(force){ - if (typeof force != "undefined"){ - var vTo = force ? "block" : "none"; - var vAlt = force ? "none" : "block"; - }else{ - var vTo = root.alt_content.style.display != "block" ? "block" : "none"; - var vAlt = root.alt_content.style.display != "block" ? "none" : "block"; - } - root.alt_content.style.display = vTo; - root.content.style.display = vAlt; - } - - root.toggleFooterVisibility = function(force){ - if (typeof force != "undefined"){ - var vTo = force ? "block" : "none"; - }else{ - var vTo = root.footer.style.display != "block" ? "block" : "none"; - } - root.footer.style.display = vTo; - } - - root.clear = function() - { - this.content.innerHTML = ""; - } - - root.addHTML = function(code, classname, on_footer) - { - var elem = document.createElement("div"); - if(classname) - elem.className = classname; - elem.innerHTML = code; - if(on_footer) - root.footer.appendChild(elem); - else - root.content.appendChild(elem); - return elem; - } - - root.addButton = function( name, callback, options ) - { - var elem = document.createElement("button"); - elem.innerText = name; - elem.options = options; - elem.classList.add("btn"); - elem.addEventListener("click",callback); - root.footer.appendChild(elem); - return elem; - } - - root.addSeparator = function() - { - var elem = document.createElement("div"); - elem.className = "separator"; - root.content.appendChild(elem); - } - - root.addWidget = function( type, name, value, options, callback ) - { - options = options || {}; - var str_value = String(value); - type = type.toLowerCase(); - if(type == "number") - str_value = value.toFixed(3); - - var elem = document.createElement("div"); - elem.className = "property"; - elem.innerHTML = ""; - elem.querySelector(".property_name").innerText = options.label || name; - var value_element = elem.querySelector(".property_value"); - value_element.innerText = str_value; - elem.dataset["property"] = name; - elem.dataset["type"] = options.type || type; - elem.options = options; - elem.value = value; - - if( type == "code" ) - elem.addEventListener("click", function(e){ root.inner_showCodePad( this.dataset["property"] ); }); - else if (type == "boolean") - { - elem.classList.add("boolean"); - if(value) - elem.classList.add("bool-on"); - elem.addEventListener("click", function(){ - //var v = node.properties[this.dataset["property"]]; - //node.setProperty(this.dataset["property"],!v); this.innerText = v ? "true" : "false"; - var propname = this.dataset["property"]; - this.value = !this.value; - this.classList.toggle("bool-on"); - this.querySelector(".property_value").innerText = this.value ? "true" : "false"; - innerChange(propname, this.value ); - }); - } - else if (type == "string" || type == "number") - { - value_element.setAttribute("contenteditable",true); - value_element.addEventListener("keydown", function(e){ - if(e.code == "Enter" && (type != "string" || !e.shiftKey)) // allow for multiline - { - e.preventDefault(); - this.blur(); - } - }); - value_element.addEventListener("blur", function(){ - var v = this.innerText; - var propname = this.parentNode.dataset["property"]; - var proptype = this.parentNode.dataset["type"]; - if( proptype == "number") - v = Number(v); - innerChange(propname, v); - }); - } - else if (type == "enum" || type == "combo") { - var str_value = LGraphCanvas.getPropertyPrintableValue( value, options.values ); - value_element.innerText = str_value; - - value_element.addEventListener("click", function(event){ - var values = options.values || []; - var propname = this.parentNode.dataset["property"]; - var elem_that = this; - var menu = new LiteGraph.ContextMenu(values,{ - event: event, - className: "dark", - callback: inner_clicked - }, - ref_window); - function inner_clicked(v, option, event) { - //node.setProperty(propname,v); - //graphcanvas.dirty_canvas = true; - elem_that.innerText = v; - innerChange(propname,v); - return false; - } - }); - } - - root.content.appendChild(elem); - - function innerChange(name, value) - { - //console.log("change",name,value); - //that.dirty_canvas = true; - if(options.callback) - options.callback(name,value,options); - if(callback) - callback(name,value,options); - } - - return elem; - } - - if (root.onOpen && typeof root.onOpen == "function") root.onOpen(); - - return root; - }; - - LGraphCanvas.getPropertyPrintableValue = function(value, values) - { - if(!values) - return String(value); - - if(values.constructor === Array) - { - return String(value); - } - - if(values.constructor === Object) - { - var desc_value = ""; - for(var k in values) - { - if(values[k] != value) - continue; - desc_value = k; - break; - } - return String(value) + " ("+desc_value+")"; - } - } - - LGraphCanvas.prototype.closePanels = function(){ - var panel = document.querySelector("#node-panel"); - if(panel) - panel.close(); - var panel = document.querySelector("#option-panel"); - if(panel) - panel.close(); - } - - LGraphCanvas.prototype.showShowGraphOptionsPanel = function(refOpts, obEv, refMenu, refMenu2){ - if(this.constructor && this.constructor.name == "HTMLDivElement"){ - // assume coming from the menu event click - if (!obEv || !obEv.event || !obEv.event.target || !obEv.event.target.lgraphcanvas){ - console.warn("Canvas not found"); // need a ref to canvas obj - /*console.debug(event); - console.debug(event.target);*/ - return; - } - var graphcanvas = obEv.event.target.lgraphcanvas; - }else{ - // assume called internally - var graphcanvas = this; - } - graphcanvas.closePanels(); - var ref_window = graphcanvas.getCanvasWindow(); - panel = graphcanvas.createPanel("Options",{ - closable: true - ,window: ref_window - ,onOpen: function(){ - graphcanvas.OPTIONPANEL_IS_OPEN = true; - } - ,onClose: function(){ - graphcanvas.OPTIONPANEL_IS_OPEN = false; - graphcanvas.options_panel = null; - } - }); - graphcanvas.options_panel = panel; - panel.id = "option-panel"; - panel.classList.add("settings"); - - function inner_refresh(){ - - panel.content.innerHTML = ""; //clear - - var fUpdate = function(name, value, options){ - switch(name){ - /*case "Render mode": - // Case "".. - if (options.values && options.key){ - var kV = Object.values(options.values).indexOf(value); - if (kV>=0 && options.values[kV]){ - console.debug("update graph options: "+options.key+": "+kV); - graphcanvas[options.key] = kV; - //console.debug(graphcanvas); - break; - } - } - console.warn("unexpected options"); - console.debug(options); - break;*/ - default: - //console.debug("want to update graph options: "+name+": "+value); - if (options && options.key){ - name = options.key; - } - if (options.values){ - value = Object.values(options.values).indexOf(value); - } - //console.debug("update graph option: "+name+": "+value); - graphcanvas[name] = value; - break; - } - }; - - // panel.addWidget( "string", "Graph name", "", {}, fUpdate); // implement - - var aProps = LiteGraph.availableCanvasOptions; - aProps.sort(); - for(var pI in aProps){ - var pX = aProps[pI]; - panel.addWidget( "boolean", pX, graphcanvas[pX], {key: pX, on: "True", off: "False"}, fUpdate); - } - - var aLinks = [ graphcanvas.links_render_mode ]; - panel.addWidget( "combo", "Render mode", LiteGraph.LINK_RENDER_MODES[graphcanvas.links_render_mode], {key: "links_render_mode", values: LiteGraph.LINK_RENDER_MODES}, fUpdate); - - panel.addSeparator(); - - panel.footer.innerHTML = ""; // clear - - } - inner_refresh(); - - graphcanvas.canvas.parentNode.appendChild( panel ); - } - - LGraphCanvas.prototype.showShowNodePanel = function( node ) - { - this.SELECTED_NODE = node; - this.closePanels(); - var ref_window = this.getCanvasWindow(); - var that = this; - var graphcanvas = this; - var panel = this.createPanel(node.title || "",{ - closable: true - ,window: ref_window - ,onOpen: function(){ - graphcanvas.NODEPANEL_IS_OPEN = true; - } - ,onClose: function(){ - graphcanvas.NODEPANEL_IS_OPEN = false; - graphcanvas.node_panel = null; - } - }); - graphcanvas.node_panel = panel; - panel.id = "node-panel"; - panel.node = node; - panel.classList.add("settings"); - - function inner_refresh() - { - panel.content.innerHTML = ""; //clear - panel.addHTML(""+node.type+""+(node.constructor.desc || "")+""); - - panel.addHTML("Properties"); - - var fUpdate = function(name,value){ - graphcanvas.graph.beforeChange(node); - switch(name){ - case "Title": - node.title = value; - break; - case "Mode": - var kV = Object.values(LiteGraph.NODE_MODES).indexOf(value); - if (kV>=0 && LiteGraph.NODE_MODES[kV]){ - node.changeMode(kV); - }else{ - console.warn("unexpected mode: "+value); - } - break; - case "Color": - if (LGraphCanvas.node_colors[value]){ - node.color = LGraphCanvas.node_colors[value].color; - node.bgcolor = LGraphCanvas.node_colors[value].bgcolor; - }else{ - console.warn("unexpected color: "+value); - } - break; - default: - node.setProperty(name,value); - break; - } - graphcanvas.graph.afterChange(); - graphcanvas.dirty_canvas = true; - }; - - panel.addWidget( "string", "Title", node.title, {}, fUpdate); - - panel.addWidget( "combo", "Mode", LiteGraph.NODE_MODES[node.mode], {values: LiteGraph.NODE_MODES}, fUpdate); - - var nodeCol = ""; - if (node.color !== undefined){ - nodeCol = Object.keys(LGraphCanvas.node_colors).filter(function(nK){ return LGraphCanvas.node_colors[nK].color == node.color; }); - } - - panel.addWidget( "combo", "Color", nodeCol, {values: Object.keys(LGraphCanvas.node_colors)}, fUpdate); - - for(var pName in node.properties) - { - var value = node.properties[pName]; - var info = node.getPropertyInfo(pName); - var type = info.type || "string"; - - //in case the user wants control over the side panel widget - if( node.onAddPropertyToPanel && node.onAddPropertyToPanel(pName,panel) ) - continue; - - panel.addWidget( info.widget || info.type, pName, value, info, fUpdate); - } - - panel.addSeparator(); - - if(node.onShowCustomPanelInfo) - node.onShowCustomPanelInfo(panel); - - panel.footer.innerHTML = ""; // clear - panel.addButton("Delete",function(){ - if(node.block_delete) - return; - node.graph.remove(node); - panel.close(); - }).classList.add("delete"); - } - - panel.inner_showCodePad = function( propname ) - { - panel.classList.remove("settings"); - panel.classList.add("centered"); - - - /*if(window.CodeFlask) //disabled for now - { - panel.content.innerHTML = ""; - var flask = new CodeFlask( "div.code", { language: 'js' }); - flask.updateCode(node.properties[propname]); - flask.onUpdate( function(code) { - node.setProperty(propname, code); - }); - } - else - {*/ - panel.alt_content.innerHTML = ""; - var textarea = panel.alt_content.querySelector("textarea"); - var fDoneWith = function(){ - panel.toggleAltContent(false); //if(node_prop_div) node_prop_div.style.display = "block"; // panel.close(); - panel.toggleFooterVisibility(true); - textarea.parentNode.removeChild(textarea); - panel.classList.add("settings"); - panel.classList.remove("centered"); - inner_refresh(); - } - textarea.value = node.properties[propname]; - textarea.addEventListener("keydown", function(e){ - if(e.code == "Enter" && e.ctrlKey ) - { - node.setProperty(propname, textarea.value); - fDoneWith(); - } - }); - panel.toggleAltContent(true); - panel.toggleFooterVisibility(false); - textarea.style.height = "calc(100% - 40px)"; - /*}*/ - var assign = panel.addButton( "Assign", function(){ - node.setProperty(propname, textarea.value); - fDoneWith(); - }); - panel.alt_content.appendChild(assign); //panel.content.appendChild(assign); - var button = panel.addButton( "Close", fDoneWith); - button.style.float = "right"; - panel.alt_content.appendChild(button); // panel.content.appendChild(button); - } - - inner_refresh(); - - this.canvas.parentNode.appendChild( panel ); - } - - LGraphCanvas.prototype.showSubgraphPropertiesDialog = function(node) - { - console.log("showing subgraph properties dialog"); - - var old_panel = this.canvas.parentNode.querySelector(".subgraph_dialog"); - if(old_panel) - old_panel.close(); - - var panel = this.createPanel("Subgraph Inputs",{closable:true, width: 500}); - panel.node = node; - panel.classList.add("subgraph_dialog"); - - function inner_refresh() - { - panel.clear(); - - //show currents - if(node.inputs) - for(var i = 0; i < node.inputs.length; ++i) - { - var input = node.inputs[i]; - if(input.not_subgraph_input) - continue; - var html = "✕ "; - var elem = panel.addHTML(html,"subgraph_property"); - elem.dataset["name"] = input.name; - elem.dataset["slot"] = i; - elem.querySelector(".name").innerText = input.name; - elem.querySelector(".type").innerText = input.type; - elem.querySelector("button").addEventListener("click",function(e){ - node.removeInput( Number( this.parentNode.dataset["slot"] ) ); - inner_refresh(); - }); - } - } - - //add extra - var html = " + NameType+"; - var elem = panel.addHTML(html,"subgraph_property extra", true); - elem.querySelector("button").addEventListener("click", function(e){ - var elem = this.parentNode; - var name = elem.querySelector(".name").value; - var type = elem.querySelector(".type").value; - if(!name || node.findInputSlot(name) != -1) - return; - node.addInput(name,type); - elem.querySelector(".name").value = ""; - elem.querySelector(".type").value = ""; - inner_refresh(); - }); - - inner_refresh(); - this.canvas.parentNode.appendChild(panel); - return panel; - } - LGraphCanvas.prototype.showSubgraphPropertiesDialogRight = function (node) { - - // console.log("showing subgraph properties dialog"); - var that = this; - // old_panel if old_panel is exist close it - var old_panel = this.canvas.parentNode.querySelector(".subgraph_dialog"); - if (old_panel) - old_panel.close(); - // new panel - var panel = this.createPanel("Subgraph Outputs", { closable: true, width: 500 }); - panel.node = node; - panel.classList.add("subgraph_dialog"); - - function inner_refresh() { - panel.clear(); - //show currents - if (node.outputs) - for (var i = 0; i < node.outputs.length; ++i) { - var input = node.outputs[i]; - if (input.not_subgraph_output) - continue; - var html = "✕ "; - var elem = panel.addHTML(html, "subgraph_property"); - elem.dataset["name"] = input.name; - elem.dataset["slot"] = i; - elem.querySelector(".name").innerText = input.name; - elem.querySelector(".type").innerText = input.type; - elem.querySelector("button").addEventListener("click", function (e) { - node.removeOutput(Number(this.parentNode.dataset["slot"])); - inner_refresh(); - }); - } - } - - //add extra - var html = " + NameType+"; - var elem = panel.addHTML(html, "subgraph_property extra", true); - elem.querySelector(".name").addEventListener("keydown", function (e) { - if (e.keyCode == 13) { - addOutput.apply(this) - } - }) - elem.querySelector("button").addEventListener("click", function (e) { - addOutput.apply(this) - }); - function addOutput() { - var elem = this.parentNode; - var name = elem.querySelector(".name").value; - var type = elem.querySelector(".type").value; - if (!name || node.findOutputSlot(name) != -1) - return; - node.addOutput(name, type); - elem.querySelector(".name").value = ""; - elem.querySelector(".type").value = ""; - inner_refresh(); - } - - inner_refresh(); - this.canvas.parentNode.appendChild(panel); - return panel; - } - LGraphCanvas.prototype.checkPanels = function() - { - if(!this.canvas) - return; - var panels = this.canvas.parentNode.querySelectorAll(".litegraph.dialog"); - for(var i = 0; i < panels.length; ++i) - { - var panel = panels[i]; - if( !panel.node ) - continue; - if( !panel.node.graph || panel.graph != this.graph ) - panel.close(); - } - } - - LGraphCanvas.onMenuNodeCollapse = function(value, options, e, menu, node) { - node.graph.beforeChange(/*?*/); - - var fApplyMultiNode = function(node){ - node.collapse(); - } - - var graphcanvas = LGraphCanvas.active_canvas; - if (!graphcanvas.selected_nodes || Object.keys(graphcanvas.selected_nodes).length <= 1){ - fApplyMultiNode(node); - }else{ - for (var i in graphcanvas.selected_nodes) { - fApplyMultiNode(graphcanvas.selected_nodes[i]); - } - } - - node.graph.afterChange(/*?*/); - }; - - LGraphCanvas.onMenuNodePin = function(value, options, e, menu, node) { - node.pin(); - }; - - LGraphCanvas.onMenuNodeMode = function(value, options, e, menu, node) { - new LiteGraph.ContextMenu( - LiteGraph.NODE_MODES, - { event: e, callback: inner_clicked, parentMenu: menu, node: node } - ); - - function inner_clicked(v) { - if (!node) { - return; - } - var kV = Object.values(LiteGraph.NODE_MODES).indexOf(v); - var fApplyMultiNode = function(node){ - if (kV>=0 && LiteGraph.NODE_MODES[kV]) - node.changeMode(kV); - else{ - console.warn("unexpected mode: "+v); - node.changeMode(LiteGraph.ALWAYS); - } - } - - var graphcanvas = LGraphCanvas.active_canvas; - if (!graphcanvas.selected_nodes || Object.keys(graphcanvas.selected_nodes).length <= 1){ - fApplyMultiNode(node); - }else{ - for (var i in graphcanvas.selected_nodes) { - fApplyMultiNode(graphcanvas.selected_nodes[i]); - } - } - } - - return false; - }; - - LGraphCanvas.onMenuNodeColors = function(value, options, e, menu, node) { - if (!node) { - throw "no node for color"; - } - - var values = []; - values.push({ - value: null, - content: - "No color" - }); - - for (var i in LGraphCanvas.node_colors) { - var color = LGraphCanvas.node_colors[i]; - var value = { - value: i, - content: - "" + - i + - "" - }; - values.push(value); - } - new LiteGraph.ContextMenu(values, { - event: e, - callback: inner_clicked, - parentMenu: menu, - node: node - }); - - function inner_clicked(v) { - if (!node) { - return; - } - - var color = v.value ? LGraphCanvas.node_colors[v.value] : null; - - var fApplyColor = function(node){ - if (color) { - if (node.constructor === LiteGraph.LGraphGroup) { - node.color = color.groupcolor; - } else { - node.color = color.color; - node.bgcolor = color.bgcolor; - } - } else { - delete node.color; - delete node.bgcolor; - } - } - - var graphcanvas = LGraphCanvas.active_canvas; - if (!graphcanvas.selected_nodes || Object.keys(graphcanvas.selected_nodes).length <= 1){ - fApplyColor(node); - }else{ - for (var i in graphcanvas.selected_nodes) { - fApplyColor(graphcanvas.selected_nodes[i]); - } - } - node.setDirtyCanvas(true, true); - } - - return false; - }; - - LGraphCanvas.onMenuNodeShapes = function(value, options, e, menu, node) { - if (!node) { - throw "no node passed"; - } - - new LiteGraph.ContextMenu(LiteGraph.VALID_SHAPES, { - event: e, - callback: inner_clicked, - parentMenu: menu, - node: node - }); - - function inner_clicked(v) { - if (!node) { - return; - } - node.graph.beforeChange(/*?*/); //node - - var fApplyMultiNode = function(node){ - node.shape = v; - } - - var graphcanvas = LGraphCanvas.active_canvas; - if (!graphcanvas.selected_nodes || Object.keys(graphcanvas.selected_nodes).length <= 1){ - fApplyMultiNode(node); - }else{ - for (var i in graphcanvas.selected_nodes) { - fApplyMultiNode(graphcanvas.selected_nodes[i]); - } - } - - node.graph.afterChange(/*?*/); //node - node.setDirtyCanvas(true); - } - - return false; - }; - - LGraphCanvas.onMenuNodeRemove = function(value, options, e, menu, node) { - if (!node) { - throw "no node passed"; - } - - var graph = node.graph; - graph.beforeChange(); - - - var fApplyMultiNode = function(node){ - if (node.removable === false) { - return; - } - graph.remove(node); - } - - var graphcanvas = LGraphCanvas.active_canvas; - if (!graphcanvas.selected_nodes || Object.keys(graphcanvas.selected_nodes).length <= 1){ - fApplyMultiNode(node); - }else{ - for (var i in graphcanvas.selected_nodes) { - fApplyMultiNode(graphcanvas.selected_nodes[i]); - } - } - - graph.afterChange(); - node.setDirtyCanvas(true, true); - }; - - LGraphCanvas.onMenuNodeToSubgraph = function(value, options, e, menu, node) { - var graph = node.graph; - var graphcanvas = LGraphCanvas.active_canvas; - if(!graphcanvas) //?? - return; - - var nodes_list = Object.values( graphcanvas.selected_nodes || {} ); - if( !nodes_list.length ) - nodes_list = [ node ]; - - var subgraph_node = LiteGraph.createNode("graph/subgraph"); - subgraph_node.pos = node.pos.concat(); - graph.add(subgraph_node); - - subgraph_node.buildFromNodes( nodes_list ); - - graphcanvas.deselectAllNodes(); - node.setDirtyCanvas(true, true); - }; - - LGraphCanvas.onMenuNodeClone = function(value, options, e, menu, node) { - - node.graph.beforeChange(); - - var newSelected = {}; - - var fApplyMultiNode = function(node){ - if (node.clonable === false) { - return; - } - var newnode = node.clone(); - if (!newnode) { - return; - } - newnode.pos = [node.pos[0] + 5, node.pos[1] + 5]; - node.graph.add(newnode); - newSelected[newnode.id] = newnode; - } - - var graphcanvas = LGraphCanvas.active_canvas; - if (!graphcanvas.selected_nodes || Object.keys(graphcanvas.selected_nodes).length <= 1){ - fApplyMultiNode(node); - }else{ - for (var i in graphcanvas.selected_nodes) { - fApplyMultiNode(graphcanvas.selected_nodes[i]); - } - } - - if(Object.keys(newSelected).length){ - graphcanvas.selectNodes(newSelected); - } - - node.graph.afterChange(); - - node.setDirtyCanvas(true, true); - }; - - LGraphCanvas.node_colors = { - red: { color: "#322", bgcolor: "#533", groupcolor: "#A88" }, - brown: { color: "#332922", bgcolor: "#593930", groupcolor: "#b06634" }, - green: { color: "#232", bgcolor: "#353", groupcolor: "#8A8" }, - blue: { color: "#223", bgcolor: "#335", groupcolor: "#88A" }, - pale_blue: { - color: "#2a363b", - bgcolor: "#3f5159", - groupcolor: "#3f789e" - }, - cyan: { color: "#233", bgcolor: "#355", groupcolor: "#8AA" }, - purple: { color: "#323", bgcolor: "#535", groupcolor: "#a1309b" }, - yellow: { color: "#432", bgcolor: "#653", groupcolor: "#b58b2a" }, - black: { color: "#222", bgcolor: "#000", groupcolor: "#444" } - }; - - LGraphCanvas.prototype.getCanvasMenuOptions = function() { - var options = null; - var that = this; - if (this.getMenuOptions) { - options = this.getMenuOptions(); - } else { - options = [ - { - content: "Add Node", - has_submenu: true, - callback: LGraphCanvas.onMenuAdd - }, - { content: "Add Group", callback: LGraphCanvas.onGroupAdd }, - //{ content: "Arrange", callback: that.graph.arrange }, - //{content:"Collapse All", callback: LGraphCanvas.onMenuCollapseAll } - ]; - /*if (LiteGraph.showCanvasOptions){ - options.push({ content: "Options", callback: that.showShowGraphOptionsPanel }); - }*/ - - if (Object.keys(this.selected_nodes).length > 1) { - options.push({ - content: "Align", - has_submenu: true, - callback: LGraphCanvas.onGroupAlign, - }) - } - - if (this._graph_stack && this._graph_stack.length > 0) { - options.push(null, { - content: "Close subgraph", - callback: this.closeSubgraph.bind(this) - }); - } - } - - if (this.getExtraMenuOptions) { - var extra = this.getExtraMenuOptions(this, options); - if (extra) { - options = options.concat(extra); - } - } - - return options; - }; - - //called by processContextMenu to extract the menu list - LGraphCanvas.prototype.getNodeMenuOptions = function(node) { - var options = null; - - if (node.getMenuOptions) { - options = node.getMenuOptions(this); - } else { - options = [ - { - content: "Inputs", - has_submenu: true, - disabled: true, - callback: LGraphCanvas.showMenuNodeOptionalInputs - }, - { - content: "Outputs", - has_submenu: true, - disabled: true, - callback: LGraphCanvas.showMenuNodeOptionalOutputs - }, - null, - { - content: "Properties", - has_submenu: true, - callback: LGraphCanvas.onShowMenuNodeProperties - }, - { - content: "Properties Panel", - callback: function(item, options, e, menu, node) { LGraphCanvas.active_canvas.showShowNodePanel(node) } - }, - null, - { - content: "Title", - callback: LGraphCanvas.onShowPropertyEditor - }, - { - content: "Mode", - has_submenu: true, - callback: LGraphCanvas.onMenuNodeMode - }]; - if(node.resizable !== false){ - options.push({ - content: "Resize", callback: LGraphCanvas.onMenuResizeNode - }); - } - options.push( - { - content: "Collapse", - callback: LGraphCanvas.onMenuNodeCollapse - }, - { content: "Pin", callback: LGraphCanvas.onMenuNodePin }, - { - content: "Colors", - has_submenu: true, - callback: LGraphCanvas.onMenuNodeColors - }, - { - content: "Shapes", - has_submenu: true, - callback: LGraphCanvas.onMenuNodeShapes - }, - null - ); - } - - if (node.onGetInputs) { - var inputs = node.onGetInputs(); - if (inputs && inputs.length) { - options[0].disabled = false; - } - } - - if (node.onGetOutputs) { - var outputs = node.onGetOutputs(); - if (outputs && outputs.length) { - options[1].disabled = false; - } - } - - if (node.getExtraMenuOptions) { - var extra = node.getExtraMenuOptions(this, options); - if (extra) { - extra.push(null); - options = extra.concat(options); - } - } - - if (node.clonable !== false) { - options.push({ - content: "Clone", - callback: LGraphCanvas.onMenuNodeClone - }); - } - - if(0) //TODO - options.push({ - content: "To Subgraph", - callback: LGraphCanvas.onMenuNodeToSubgraph - }); - - if (Object.keys(this.selected_nodes).length > 1) { - options.push({ - content: "Align Selected To", - has_submenu: true, - callback: LGraphCanvas.onNodeAlign, - }) - } - - options.push(null, { - content: "Remove", - disabled: !(node.removable !== false && !node.block_delete ), - callback: LGraphCanvas.onMenuNodeRemove - }); - - if (node.graph && node.graph.onGetNodeMenuOptions) { - node.graph.onGetNodeMenuOptions(options, node); - } - - return options; - }; - - LGraphCanvas.prototype.getGroupMenuOptions = function(node) { - var o = [ - { content: "Title", callback: LGraphCanvas.onShowPropertyEditor }, - { - content: "Color", - has_submenu: true, - callback: LGraphCanvas.onMenuNodeColors - }, - { - content: "Font size", - property: "font_size", - type: "Number", - callback: LGraphCanvas.onShowPropertyEditor - }, - null, - { content: "Remove", callback: LGraphCanvas.onMenuNodeRemove } - ]; - - return o; - }; - - LGraphCanvas.prototype.processContextMenu = function(node, event) { - var that = this; - var canvas = LGraphCanvas.active_canvas; - var ref_window = canvas.getCanvasWindow(); - - var menu_info = null; - var options = { - event: event, - callback: inner_option_clicked, - extra: node - }; - - if(node) - options.title = node.type; - - //check if mouse is in input - var slot = null; - if (node) { - slot = node.getSlotInPosition(event.canvasX, event.canvasY); - LGraphCanvas.active_node = node; - } - - if (slot) { - //on slot - menu_info = []; - if (node.getSlotMenuOptions) { - menu_info = node.getSlotMenuOptions(slot); - } else { - if ( - slot && - slot.output && - slot.output.links && - slot.output.links.length - ) { - menu_info.push({ content: "Disconnect Links", slot: slot }); - } - var _slot = slot.input || slot.output; - if (_slot.removable){ - menu_info.push( - _slot.locked - ? "Cannot remove" - : { content: "Remove Slot", slot: slot } - ); - } - if (!_slot.nameLocked){ - menu_info.push({ content: "Rename Slot", slot: slot }); - } - - } - options.title = - (slot.input ? slot.input.type : slot.output.type) || "*"; - if (slot.input && slot.input.type == LiteGraph.ACTION) { - options.title = "Action"; - } - if (slot.output && slot.output.type == LiteGraph.EVENT) { - options.title = "Event"; - } - } else { - if (node) { - //on node - menu_info = this.getNodeMenuOptions(node); - } else { - menu_info = this.getCanvasMenuOptions(); - var group = this.graph.getGroupOnPos( - event.canvasX, - event.canvasY - ); - if (group) { - //on group - menu_info.push(null, { - content: "Edit Group", - has_submenu: true, - submenu: { - title: "Group", - extra: group, - options: this.getGroupMenuOptions(group) - } - }); - } - } - } - - //show menu - if (!menu_info) { - return; - } - - var menu = new LiteGraph.ContextMenu(menu_info, options, ref_window); - - function inner_option_clicked(v, options, e) { - if (!v) { - return; - } - - if (v.content == "Remove Slot") { - var info = v.slot; - node.graph.beforeChange(); - if (info.input) { - node.removeInput(info.slot); - } else if (info.output) { - node.removeOutput(info.slot); - } - node.graph.afterChange(); - return; - } else if (v.content == "Disconnect Links") { - var info = v.slot; - node.graph.beforeChange(); - if (info.output) { - node.disconnectOutput(info.slot); - } else if (info.input) { - node.disconnectInput(info.slot); - } - node.graph.afterChange(); - return; - } else if (v.content == "Rename Slot") { - var info = v.slot; - var slot_info = info.input - ? node.getInputInfo(info.slot) - : node.getOutputInfo(info.slot); - var dialog = that.createDialog( - "NameOK", - options - ); - var input = dialog.querySelector("input"); - if (input && slot_info) { - input.value = slot_info.label || ""; - } - var inner = function(){ - node.graph.beforeChange(); - if (input.value) { - if (slot_info) { - slot_info.label = input.value; - } - that.setDirty(true); - } - dialog.close(); - node.graph.afterChange(); - } - dialog.querySelector("button").addEventListener("click", inner); - input.addEventListener("keydown", function(e) { - dialog.is_modified = true; - if (e.keyCode == 27) { - //ESC - dialog.close(); - } else if (e.keyCode == 13) { - inner(); // save - } else if (e.keyCode != 13 && e.target.localName != "textarea") { - return; - } - e.preventDefault(); - e.stopPropagation(); - }); - input.focus(); - } - - //if(v.callback) - // return v.callback.call(that, node, options, e, menu, that, event ); - } - }; - - //API ************************************************* - //like rect but rounded corners - if (typeof(window) != "undefined" && window.CanvasRenderingContext2D && !window.CanvasRenderingContext2D.prototype.roundRect) { - window.CanvasRenderingContext2D.prototype.roundRect = function( - x, - y, - w, - h, - radius, - radius_low - ) { - var top_left_radius = 0; - var top_right_radius = 0; - var bottom_left_radius = 0; - var bottom_right_radius = 0; - - if ( radius === 0 ) - { - this.rect(x,y,w,h); - return; - } - - if(radius_low === undefined) - radius_low = radius; - - //make it compatible with official one - if(radius != null && radius.constructor === Array) - { - if(radius.length == 1) - top_left_radius = top_right_radius = bottom_left_radius = bottom_right_radius = radius[0]; - else if(radius.length == 2) - { - top_left_radius = bottom_right_radius = radius[0]; - top_right_radius = bottom_left_radius = radius[1]; - } - else if(radius.length == 4) - { - top_left_radius = radius[0]; - top_right_radius = radius[1]; - bottom_left_radius = radius[2]; - bottom_right_radius = radius[3]; - } - else - return; - } - else //old using numbers - { - top_left_radius = radius || 0; - top_right_radius = radius || 0; - bottom_left_radius = radius_low || 0; - bottom_right_radius = radius_low || 0; - } - - //top right - this.moveTo(x + top_left_radius, y); - this.lineTo(x + w - top_right_radius, y); - this.quadraticCurveTo(x + w, y, x + w, y + top_right_radius); - - //bottom right - this.lineTo(x + w, y + h - bottom_right_radius); - this.quadraticCurveTo( - x + w, - y + h, - x + w - bottom_right_radius, - y + h - ); - - //bottom left - this.lineTo(x + bottom_right_radius, y + h); - this.quadraticCurveTo(x, y + h, x, y + h - bottom_left_radius); - - //top left - this.lineTo(x, y + bottom_left_radius); - this.quadraticCurveTo(x, y, x + top_left_radius, y); - }; - }//if - - function compareObjects(a, b) { - for (var i in a) { - if (a[i] != b[i]) { - return false; - } - } - return true; - } - LiteGraph.compareObjects = compareObjects; - - function distance(a, b) { - return Math.sqrt( - (b[0] - a[0]) * (b[0] - a[0]) + (b[1] - a[1]) * (b[1] - a[1]) - ); - } - LiteGraph.distance = distance; - - function colorToString(c) { - return ( - "rgba(" + - Math.round(c[0] * 255).toFixed() + - "," + - Math.round(c[1] * 255).toFixed() + - "," + - Math.round(c[2] * 255).toFixed() + - "," + - (c.length == 4 ? c[3].toFixed(2) : "1.0") + - ")" - ); - } - LiteGraph.colorToString = colorToString; - - function isInsideRectangle(x, y, left, top, width, height) { - if (left < x && left + width > x && top < y && top + height > y) { - return true; - } - return false; - } - LiteGraph.isInsideRectangle = isInsideRectangle; - - //[minx,miny,maxx,maxy] - function growBounding(bounding, x, y) { - if (x < bounding[0]) { - bounding[0] = x; - } else if (x > bounding[2]) { - bounding[2] = x; - } - - if (y < bounding[1]) { - bounding[1] = y; - } else if (y > bounding[3]) { - bounding[3] = y; - } - } - LiteGraph.growBounding = growBounding; - - //point inside bounding box - function isInsideBounding(p, bb) { - if ( - p[0] < bb[0][0] || - p[1] < bb[0][1] || - p[0] > bb[1][0] || - p[1] > bb[1][1] - ) { - return false; - } - return true; - } - LiteGraph.isInsideBounding = isInsideBounding; - - //bounding overlap, format: [ startx, starty, width, height ] - function overlapBounding(a, b) { - var A_end_x = a[0] + a[2]; - var A_end_y = a[1] + a[3]; - var B_end_x = b[0] + b[2]; - var B_end_y = b[1] + b[3]; - - if ( - a[0] > B_end_x || - a[1] > B_end_y || - A_end_x < b[0] || - A_end_y < b[1] - ) { - return false; - } - return true; - } - LiteGraph.overlapBounding = overlapBounding; - - //Convert a hex value to its decimal value - the inputted hex must be in the - // format of a hex triplet - the kind we use for HTML colours. The function - // will return an array with three values. - function hex2num(hex) { - if (hex.charAt(0) == "#") { - hex = hex.slice(1); - } //Remove the '#' char - if there is one. - hex = hex.toUpperCase(); - var hex_alphabets = "0123456789ABCDEF"; - var value = new Array(3); - var k = 0; - var int1, int2; - for (var i = 0; i < 6; i += 2) { - int1 = hex_alphabets.indexOf(hex.charAt(i)); - int2 = hex_alphabets.indexOf(hex.charAt(i + 1)); - value[k] = int1 * 16 + int2; - k++; - } - return value; - } - - LiteGraph.hex2num = hex2num; - - //Give a array with three values as the argument and the function will return - // the corresponding hex triplet. - function num2hex(triplet) { - var hex_alphabets = "0123456789ABCDEF"; - var hex = "#"; - var int1, int2; - for (var i = 0; i < 3; i++) { - int1 = triplet[i] / 16; - int2 = triplet[i] % 16; - - hex += hex_alphabets.charAt(int1) + hex_alphabets.charAt(int2); - } - return hex; - } - - LiteGraph.num2hex = num2hex; - - /* LiteGraph GUI elements used for canvas editing *************************************/ - - /** - * ContextMenu from LiteGUI - * - * @class ContextMenu - * @constructor - * @param {Array} values (allows object { title: "Nice text", callback: function ... }) - * @param {Object} options [optional] Some options:\ - * - title: title to show on top of the menu - * - callback: function to call when an option is clicked, it receives the item information - * - ignore_item_callbacks: ignores the callback inside the item, it just calls the options.callback - * - event: you can pass a MouseEvent, this way the ContextMenu appears in that position - */ - function ContextMenu(values, options) { - options = options || {}; - this.options = options; - var that = this; - - //to link a menu with its parent - if (options.parentMenu) { - if (options.parentMenu.constructor !== this.constructor) { - console.error( - "parentMenu must be of class ContextMenu, ignoring it" - ); - options.parentMenu = null; - } else { - this.parentMenu = options.parentMenu; - this.parentMenu.lock = true; - this.parentMenu.current_submenu = this; - } - } - - var eventClass = null; - if(options.event) //use strings because comparing classes between windows doesnt work - eventClass = options.event.constructor.name; - if ( eventClass !== "MouseEvent" && - eventClass !== "CustomEvent" && - eventClass !== "PointerEvent" - ) { - console.error( - "Event passed to ContextMenu is not of type MouseEvent or CustomEvent. Ignoring it. ("+eventClass+")" - ); - options.event = null; - } - - var root = document.createElement("div"); - root.className = "litegraph litecontextmenu litemenubar-panel"; - if (options.className) { - root.className += " " + options.className; - } - root.style.minWidth = 100; - root.style.minHeight = 100; - root.style.pointerEvents = "none"; - setTimeout(function() { - root.style.pointerEvents = "auto"; - }, 100); //delay so the mouse up event is not caught by this element - - //this prevents the default context browser menu to open in case this menu was created when pressing right button - LiteGraph.pointerListenerAdd(root,"up", - function(e) { - //console.log("pointerevents: ContextMenu up root prevent"); - e.preventDefault(); - return true; - }, - true - ); - root.addEventListener( - "contextmenu", - function(e) { - if (e.button != 2) { - //right button - return false; - } - e.preventDefault(); - return false; - }, - true - ); - - LiteGraph.pointerListenerAdd(root,"down", - function(e) { - //console.log("pointerevents: ContextMenu down"); - if (e.button == 2) { - that.close(); - e.preventDefault(); - return true; - } - }, - true - ); - - function on_mouse_wheel(e) { - var pos = parseInt(root.style.top); - root.style.top = - (pos + e.deltaY * options.scroll_speed).toFixed() + "px"; - e.preventDefault(); - return true; - } - - if (!options.scroll_speed) { - options.scroll_speed = 0.1; - } - - root.addEventListener("wheel", on_mouse_wheel, true); - root.addEventListener("mousewheel", on_mouse_wheel, true); - - this.root = root; - - //title - if (options.title) { - var element = document.createElement("div"); - element.className = "litemenu-title"; - element.innerHTML = options.title; - root.appendChild(element); - } - - //entries - var num = 0; - for (var i=0; i < values.length; i++) { - var name = values.constructor == Array ? values[i] : i; - if (name != null && name.constructor !== String) { - name = name.content === undefined ? String(name) : name.content; - } - var value = values[i]; - this.addItem(name, value, options); - num++; - } - - //close on leave? touch enabled devices won't work TODO use a global device detector and condition on that - /*LiteGraph.pointerListenerAdd(root,"leave", function(e) { - console.log("pointerevents: ContextMenu leave"); - if (that.lock) { - return; - } - if (root.closing_timer) { - clearTimeout(root.closing_timer); - } - root.closing_timer = setTimeout(that.close.bind(that, e), 500); - //that.close(e); - });*/ - - LiteGraph.pointerListenerAdd(root,"enter", function(e) { - //console.log("pointerevents: ContextMenu enter"); - if (root.closing_timer) { - clearTimeout(root.closing_timer); - } - }); - - //insert before checking position - var root_document = document; - if (options.event) { - root_document = options.event.target.ownerDocument; - } - - if (!root_document) { - root_document = document; - } - - if( root_document.fullscreenElement ) - root_document.fullscreenElement.appendChild(root); - else - root_document.body.appendChild(root); - - //compute best position - var left = options.left || 0; - var top = options.top || 0; - if (options.event) { - left = options.event.clientX - 10; - top = options.event.clientY - 10; - if (options.title) { - top -= 20; - } - - if (options.parentMenu) { - var rect = options.parentMenu.root.getBoundingClientRect(); - left = rect.left + rect.width; - } - - var body_rect = document.body.getBoundingClientRect(); - var root_rect = root.getBoundingClientRect(); - if(body_rect.height == 0) - console.error("document.body height is 0. That is dangerous, set html,body { height: 100%; }"); - - if (body_rect.width && left > body_rect.width - root_rect.width - 10) { - left = body_rect.width - root_rect.width - 10; - } - if (body_rect.height && top > body_rect.height - root_rect.height - 10) { - top = body_rect.height - root_rect.height - 10; - } - } - - root.style.left = left + "px"; - root.style.top = top + "px"; - - if (options.scale) { - root.style.transform = "scale(" + options.scale + ")"; - } - } - - ContextMenu.prototype.addItem = function(name, value, options) { - var that = this; - options = options || {}; - - var element = document.createElement("div"); - element.className = "litemenu-entry submenu"; - - var disabled = false; - - if (value === null) { - element.classList.add("separator"); - //element.innerHTML = "" - //continue; - } else { - element.innerHTML = value && value.title ? value.title : name; - element.value = value; - - if (value) { - if (value.disabled) { - disabled = true; - element.classList.add("disabled"); - } - if (value.submenu || value.has_submenu) { - element.classList.add("has_submenu"); - } - } - - if (typeof value == "function") { - element.dataset["value"] = name; - element.onclick_callback = value; - } else { - element.dataset["value"] = value; - } - - if (value.className) { - element.className += " " + value.className; - } - } - - this.root.appendChild(element); - if (!disabled) { - element.addEventListener("click", inner_onclick); - } - if (!disabled && options.autoopen) { - LiteGraph.pointerListenerAdd(element,"enter",inner_over); - } - - function inner_over(e) { - var value = this.value; - if (!value || !value.has_submenu) { - return; - } - //if it is a submenu, autoopen like the item was clicked - inner_onclick.call(this, e); - } - - //menu option clicked - function inner_onclick(e) { - var value = this.value; - var close_parent = true; - - if (that.current_submenu) { - that.current_submenu.close(e); - } - - //global callback - if (options.callback) { - var r = options.callback.call( - this, - value, - options, - e, - that, - options.node - ); - if (r === true) { - close_parent = false; - } - } - - //special cases - if (value) { - if ( - value.callback && - !options.ignore_item_callbacks && - value.disabled !== true - ) { - //item callback - var r = value.callback.call( - this, - value, - options, - e, - that, - options.extra - ); - if (r === true) { - close_parent = false; - } - } - if (value.submenu) { - if (!value.submenu.options) { - throw "ContextMenu submenu needs options"; - } - var submenu = new that.constructor(value.submenu.options, { - callback: value.submenu.callback, - event: e, - parentMenu: that, - ignore_item_callbacks: - value.submenu.ignore_item_callbacks, - title: value.submenu.title, - extra: value.submenu.extra, - autoopen: options.autoopen - }); - close_parent = false; - } - } - - if (close_parent && !that.lock) { - that.close(); - } - } - - return element; - }; - - ContextMenu.prototype.close = function(e, ignore_parent_menu) { - if (this.root.parentNode) { - this.root.parentNode.removeChild(this.root); - } - if (this.parentMenu && !ignore_parent_menu) { - this.parentMenu.lock = false; - this.parentMenu.current_submenu = null; - if (e === undefined) { - this.parentMenu.close(); - } else if ( - e && - !ContextMenu.isCursorOverElement(e, this.parentMenu.root) - ) { - ContextMenu.trigger(this.parentMenu.root, LiteGraph.pointerevents_method+"leave", e); - } - } - if (this.current_submenu) { - this.current_submenu.close(e, true); - } - - if (this.root.closing_timer) { - clearTimeout(this.root.closing_timer); - } - - // TODO implement : LiteGraph.contextMenuClosed(); :: keep track of opened / closed / current ContextMenu - // on key press, allow filtering/selecting the context menu elements - }; - - //this code is used to trigger events easily (used in the context menu mouseleave - ContextMenu.trigger = function(element, event_name, params, origin) { - var evt = document.createEvent("CustomEvent"); - evt.initCustomEvent(event_name, true, true, params); //canBubble, cancelable, detail - evt.srcElement = origin; - if (element.dispatchEvent) { - element.dispatchEvent(evt); - } else if (element.__events) { - element.__events.dispatchEvent(evt); - } - //else nothing seems binded here so nothing to do - return evt; - }; - - //returns the top most menu - ContextMenu.prototype.getTopMenu = function() { - if (this.options.parentMenu) { - return this.options.parentMenu.getTopMenu(); - } - return this; - }; - - ContextMenu.prototype.getFirstEvent = function() { - if (this.options.parentMenu) { - return this.options.parentMenu.getFirstEvent(); - } - return this.options.event; - }; - - ContextMenu.isCursorOverElement = function(event, element) { - var left = event.clientX; - var top = event.clientY; - var rect = element.getBoundingClientRect(); - if (!rect) { - return false; - } - if ( - top > rect.top && - top < rect.top + rect.height && - left > rect.left && - left < rect.left + rect.width - ) { - return true; - } - return false; - }; - - LiteGraph.ContextMenu = ContextMenu; - - LiteGraph.closeAllContextMenus = function(ref_window) { - ref_window = ref_window || window; - - var elements = ref_window.document.querySelectorAll(".litecontextmenu"); - if (!elements.length) { - return; - } - - var result = []; - for (var i = 0; i < elements.length; i++) { - result.push(elements[i]); - } - - for (var i=0; i < result.length; i++) { - if (result[i].close) { - result[i].close(); - } else if (result[i].parentNode) { - result[i].parentNode.removeChild(result[i]); - } - } - }; - - LiteGraph.extendClass = function(target, origin) { - for (var i in origin) { - //copy class properties - if (target.hasOwnProperty(i)) { - continue; - } - target[i] = origin[i]; - } - - if (origin.prototype) { - //copy prototype properties - for (var i in origin.prototype) { - //only enumerable - if (!origin.prototype.hasOwnProperty(i)) { - continue; - } - - if (target.prototype.hasOwnProperty(i)) { - //avoid overwriting existing ones - continue; - } - - //copy getters - if (origin.prototype.__lookupGetter__(i)) { - target.prototype.__defineGetter__( - i, - origin.prototype.__lookupGetter__(i) - ); - } else { - target.prototype[i] = origin.prototype[i]; - } - - //and setters - if (origin.prototype.__lookupSetter__(i)) { - target.prototype.__defineSetter__( - i, - origin.prototype.__lookupSetter__(i) - ); - } - } - } - }; - - //used by some widgets to render a curve editor - function CurveEditor( points ) - { - this.points = points; - this.selected = -1; - this.nearest = -1; - this.size = null; //stores last size used - this.must_update = true; - this.margin = 5; - } - - CurveEditor.sampleCurve = function(f,points) - { - if(!points) - return; - for(var i = 0; i < points.length - 1; ++i) - { - var p = points[i]; - var pn = points[i+1]; - if(pn[0] < f) - continue; - var r = (pn[0] - p[0]); - if( Math.abs(r) < 0.00001 ) - return p[1]; - var local_f = (f - p[0]) / r; - return p[1] * (1.0 - local_f) + pn[1] * local_f; - } - return 0; - } - - CurveEditor.prototype.draw = function( ctx, size, graphcanvas, background_color, line_color, inactive ) - { - var points = this.points; - if(!points) - return; - this.size = size; - var w = size[0] - this.margin * 2; - var h = size[1] - this.margin * 2; - - line_color = line_color || "#666"; - - ctx.save(); - ctx.translate(this.margin,this.margin); - - if(background_color) - { - ctx.fillStyle = "#111"; - ctx.fillRect(0,0,w,h); - ctx.fillStyle = "#222"; - ctx.fillRect(w*0.5,0,1,h); - ctx.strokeStyle = "#333"; - ctx.strokeRect(0,0,w,h); - } - ctx.strokeStyle = line_color; - if(inactive) - ctx.globalAlpha = 0.5; - ctx.beginPath(); - for(var i = 0; i < points.length; ++i) - { - var p = points[i]; - ctx.lineTo( p[0] * w, (1.0 - p[1]) * h ); - } - ctx.stroke(); - ctx.globalAlpha = 1; - if(!inactive) - for(var i = 0; i < points.length; ++i) - { - var p = points[i]; - ctx.fillStyle = this.selected == i ? "#FFF" : (this.nearest == i ? "#DDD" : "#AAA"); - ctx.beginPath(); - ctx.arc( p[0] * w, (1.0 - p[1]) * h, 2, 0, Math.PI * 2 ); - ctx.fill(); - } - ctx.restore(); - } - - //localpos is mouse in curve editor space - CurveEditor.prototype.onMouseDown = function( localpos, graphcanvas ) - { - var points = this.points; - if(!points) - return; - if( localpos[1] < 0 ) - return; - - //this.captureInput(true); - var w = this.size[0] - this.margin * 2; - var h = this.size[1] - this.margin * 2; - var x = localpos[0] - this.margin; - var y = localpos[1] - this.margin; - var pos = [x,y]; - var max_dist = 30 / graphcanvas.ds.scale; - //search closer one - this.selected = this.getCloserPoint(pos, max_dist); - //create one - if(this.selected == -1) - { - var point = [x / w, 1 - y / h]; - points.push(point); - points.sort(function(a,b){ return a[0] - b[0]; }); - this.selected = points.indexOf(point); - this.must_update = true; - } - if(this.selected != -1) - return true; - } - - CurveEditor.prototype.onMouseMove = function( localpos, graphcanvas ) - { - var points = this.points; - if(!points) - return; - var s = this.selected; - if(s < 0) - return; - var x = (localpos[0] - this.margin) / (this.size[0] - this.margin * 2 ); - var y = (localpos[1] - this.margin) / (this.size[1] - this.margin * 2 ); - var curvepos = [(localpos[0] - this.margin),(localpos[1] - this.margin)]; - var max_dist = 30 / graphcanvas.ds.scale; - this._nearest = this.getCloserPoint(curvepos, max_dist); - var point = points[s]; - if(point) - { - var is_edge_point = s == 0 || s == points.length - 1; - if( !is_edge_point && (localpos[0] < -10 || localpos[0] > this.size[0] + 10 || localpos[1] < -10 || localpos[1] > this.size[1] + 10) ) - { - points.splice(s,1); - this.selected = -1; - return; - } - if( !is_edge_point ) //not edges - point[0] = clamp(x, 0, 1); - else - point[0] = s == 0 ? 0 : 1; - point[1] = 1.0 - clamp(y, 0, 1); - points.sort(function(a,b){ return a[0] - b[0]; }); - this.selected = points.indexOf(point); - this.must_update = true; - } - } - - CurveEditor.prototype.onMouseUp = function( localpos, graphcanvas ) - { - this.selected = -1; - return false; - } - - CurveEditor.prototype.getCloserPoint = function(pos, max_dist) - { - var points = this.points; - if(!points) - return -1; - max_dist = max_dist || 30; - var w = (this.size[0] - this.margin * 2); - var h = (this.size[1] - this.margin * 2); - var num = points.length; - var p2 = [0,0]; - var min_dist = 1000000; - var closest = -1; - var last_valid = -1; - for(var i = 0; i < num; ++i) - { - var p = points[i]; - p2[0] = p[0] * w; - p2[1] = (1.0 - p[1]) * h; - if(p2[0] < pos[0]) - last_valid = i; - var dist = vec2.distance(pos,p2); - if(dist > min_dist || dist > max_dist) - continue; - closest = i; - min_dist = dist; - } - return closest; - } - - LiteGraph.CurveEditor = CurveEditor; - - //used to create nodes from wrapping functions - LiteGraph.getParameterNames = function(func) { - return (func + "") - .replace(/[/][/].*$/gm, "") // strip single-line comments - .replace(/\s+/g, "") // strip white space - .replace(/[/][*][^/*]*[*][/]/g, "") // strip multi-line comments /**/ - .split("){", 1)[0] - .replace(/^[^(]*[(]/, "") // extract the parameters - .replace(/=[^,]+/g, "") // strip any ES6 defaults - .split(",") - .filter(Boolean); // split & filter [""] - }; - - /* helper for interaction: pointer, touch, mouse Listeners - used by LGraphCanvas DragAndScale ContextMenu*/ - LiteGraph.pointerListenerAdd = function(oDOM, sEvIn, fCall, capture=false) { - if (!oDOM || !oDOM.addEventListener || !sEvIn || typeof fCall!=="function"){ - //console.log("cant pointerListenerAdd "+oDOM+", "+sEvent+", "+fCall); - return; // -- break -- - } - - var sMethod = LiteGraph.pointerevents_method; - var sEvent = sEvIn; - - // UNDER CONSTRUCTION - // convert pointerevents to touch event when not available - if (sMethod=="pointer" && !window.PointerEvent){ - console.warn("sMethod=='pointer' && !window.PointerEvent"); - console.log("Converting pointer["+sEvent+"] : down move up cancel enter TO touchstart touchmove touchend, etc .."); - switch(sEvent){ - case "down":{ - sMethod = "touch"; - sEvent = "start"; - break; - } - case "move":{ - sMethod = "touch"; - //sEvent = "move"; - break; - } - case "up":{ - sMethod = "touch"; - sEvent = "end"; - break; - } - case "cancel":{ - sMethod = "touch"; - //sEvent = "cancel"; - break; - } - case "enter":{ - console.log("debug: Should I send a move event?"); // ??? - break; - } - // case "over": case "out": not used at now - default:{ - console.warn("PointerEvent not available in this browser ? The event "+sEvent+" would not be called"); - } - } - } - - switch(sEvent){ - //both pointer and move events - case "down": case "up": case "move": case "over": case "out": case "enter": - { - oDOM.addEventListener(sMethod+sEvent, fCall, capture); - } - // only pointerevents - case "leave": case "cancel": case "gotpointercapture": case "lostpointercapture": - { - if (sMethod!="mouse"){ - return oDOM.addEventListener(sMethod+sEvent, fCall, capture); - } - } - // not "pointer" || "mouse" - default: - return oDOM.addEventListener(sEvent, fCall, capture); - } - } - LiteGraph.pointerListenerRemove = function(oDOM, sEvent, fCall, capture=false) { - if (!oDOM || !oDOM.removeEventListener || !sEvent || typeof fCall!=="function"){ - //console.log("cant pointerListenerRemove "+oDOM+", "+sEvent+", "+fCall); - return; // -- break -- - } - switch(sEvent){ - //both pointer and move events - case "down": case "up": case "move": case "over": case "out": case "enter": - { - if (LiteGraph.pointerevents_method=="pointer" || LiteGraph.pointerevents_method=="mouse"){ - oDOM.removeEventListener(LiteGraph.pointerevents_method+sEvent, fCall, capture); - } - } - // only pointerevents - case "leave": case "cancel": case "gotpointercapture": case "lostpointercapture": - { - if (LiteGraph.pointerevents_method=="pointer"){ - return oDOM.removeEventListener(LiteGraph.pointerevents_method+sEvent, fCall, capture); - } - } - // not "pointer" || "mouse" - default: - return oDOM.removeEventListener(sEvent, fCall, capture); - } - } - - function clamp(v, a, b) { - return a > v ? a : b < v ? b : v; - }; - global.clamp = clamp; - - if (typeof window != "undefined" && !window["requestAnimationFrame"]) { - window.requestAnimationFrame = - window.webkitRequestAnimationFrame || - window.mozRequestAnimationFrame || - function(callback) { - window.setTimeout(callback, 1000 / 60); - }; - } -})(this); - -if (typeof exports != "undefined") { - exports.LiteGraph = this.LiteGraph; - exports.LGraph = this.LGraph; - exports.LLink = this.LLink; - exports.LGraphNode = this.LGraphNode; - exports.LGraphGroup = this.LGraphGroup; - exports.DragAndScale = this.DragAndScale; - exports.LGraphCanvas = this.LGraphCanvas; - exports.ContextMenu = this.ContextMenu; -} - - diff --git a/web/lib/litegraph.css b/web/lib/litegraph.css deleted file mode 100644 index 5524e24ba..000000000 --- a/web/lib/litegraph.css +++ /dev/null @@ -1,693 +0,0 @@ -/* this CSS contains only the basic CSS needed to run the app and use it */ - -.lgraphcanvas { - /*cursor: crosshair;*/ - user-select: none; - -moz-user-select: none; - -webkit-user-select: none; - outline: none; - font-family: Tahoma, sans-serif; -} - -.lgraphcanvas * { - box-sizing: border-box; -} - -.litegraph.litecontextmenu { - font-family: Tahoma, sans-serif; - position: fixed; - top: 100px; - left: 100px; - min-width: 100px; - color: #aaf; - padding: 0; - box-shadow: 0 0 10px black !important; - background-color: #2e2e2e !important; - z-index: 10; -} - -.litegraph.litecontextmenu.dark { - background-color: #000 !important; -} - -.litegraph.litecontextmenu .litemenu-title img { - margin-top: 2px; - margin-left: 2px; - margin-right: 4px; -} - -.litegraph.litecontextmenu .litemenu-entry { - margin: 2px; - padding: 2px; -} - -.litegraph.litecontextmenu .litemenu-entry.submenu { - background-color: #2e2e2e !important; -} - -.litegraph.litecontextmenu.dark .litemenu-entry.submenu { - background-color: #000 !important; -} - -.litegraph .litemenubar ul { - font-family: Tahoma, sans-serif; - margin: 0; - padding: 0; -} - -.litegraph .litemenubar li { - font-size: 14px; - color: #999; - display: inline-block; - min-width: 50px; - padding-left: 10px; - padding-right: 10px; - user-select: none; - -moz-user-select: none; - -webkit-user-select: none; - cursor: pointer; -} - -.litegraph .litemenubar li:hover { - background-color: #777; - color: #eee; -} - -.litegraph .litegraph .litemenubar-panel { - position: absolute; - top: 5px; - left: 5px; - min-width: 100px; - background-color: #444; - box-shadow: 0 0 3px black; - padding: 4px; - border-bottom: 2px solid #aaf; - z-index: 10; -} - -.litegraph .litemenu-entry, -.litemenu-title { - font-size: 12px; - color: #aaa; - padding: 0 0 0 4px; - margin: 2px; - padding-left: 2px; - -moz-user-select: none; - -webkit-user-select: none; - user-select: none; - cursor: pointer; -} - -.litegraph .litemenu-entry .icon { - display: inline-block; - width: 12px; - height: 12px; - margin: 2px; - vertical-align: top; -} - -.litegraph .litemenu-entry.checked .icon { - background-color: #aaf; -} - -.litegraph .litemenu-entry .more { - float: right; - padding-right: 5px; -} - -.litegraph .litemenu-entry.disabled { - opacity: 0.5; - cursor: default; -} - -.litegraph .litemenu-entry.separator { - display: block; - border-top: 1px solid #333; - border-bottom: 1px solid #666; - width: 100%; - height: 0px; - margin: 3px 0 2px 0; - background-color: transparent; - padding: 0 !important; - cursor: default !important; -} - -.litegraph .litemenu-entry.has_submenu { - border-right: 2px solid cyan; -} - -.litegraph .litemenu-title { - color: #dde; - background-color: #111; - margin: 0; - padding: 2px; - cursor: default; -} - -.litegraph .litemenu-entry:hover:not(.disabled):not(.separator) { - background-color: #444 !important; - color: #eee; - transition: all 0.2s; -} - -.litegraph .litemenu-entry .property_name { - display: inline-block; - text-align: left; - min-width: 80px; - min-height: 1.2em; -} - -.litegraph .litemenu-entry .property_value { - display: inline-block; - background-color: rgba(0, 0, 0, 0.5); - text-align: right; - min-width: 80px; - min-height: 1.2em; - vertical-align: middle; - padding-right: 10px; -} - -.litegraph.litesearchbox { - font-family: Tahoma, sans-serif; - position: absolute; - background-color: rgba(0, 0, 0, 0.5); - padding-top: 4px; -} - -.litegraph.litesearchbox input, -.litegraph.litesearchbox select { - margin-top: 3px; - min-width: 60px; - min-height: 1.5em; - background-color: black; - border: 0; - color: white; - padding-left: 10px; - margin-right: 5px; - max-width: 300px; -} - -.litegraph.litesearchbox .name { - display: inline-block; - min-width: 60px; - min-height: 1.5em; - padding-left: 10px; -} - -.litegraph.litesearchbox .helper { - overflow: auto; - max-height: 200px; - margin-top: 2px; -} - -.litegraph.lite-search-item { - font-family: Tahoma, sans-serif; - background-color: rgba(0, 0, 0, 0.5); - color: white; - padding-top: 2px; -} - -.litegraph.lite-search-item.not_in_filter{ - /*background-color: rgba(50, 50, 50, 0.5);*/ - /*color: #999;*/ - color: #B99; - font-style: italic; -} - -.litegraph.lite-search-item.generic_type{ - /*background-color: rgba(50, 50, 50, 0.5);*/ - /*color: #DD9;*/ - color: #999; - font-style: italic; -} - -.litegraph.lite-search-item:hover, -.litegraph.lite-search-item.selected { - cursor: pointer; - background-color: white; - color: black; -} - -.litegraph.lite-search-item-type { - display: inline-block; - background: rgba(0,0,0,0.2); - margin-left: 5px; - font-size: 14px; - padding: 2px 5px; - position: relative; - top: -2px; - opacity: 0.8; - border-radius: 4px; - } - -/* DIALOGs ******/ - -.litegraph .dialog { - position: absolute; - top: 50%; - left: 50%; - margin-top: -150px; - margin-left: -200px; - - background-color: #2A2A2A; - - min-width: 400px; - min-height: 200px; - box-shadow: 0 0 4px #111; - border-radius: 6px; -} - -.litegraph .dialog.settings { - left: 10px; - top: 10px; - height: calc( 100% - 20px ); - margin: auto; - max-width: 50%; -} - -.litegraph .dialog.centered { - top: 50px; - left: 50%; - position: absolute; - transform: translateX(-50%); - min-width: 600px; - min-height: 300px; - height: calc( 100% - 100px ); - margin: auto; -} - -.litegraph .dialog .close { - float: right; - margin: 4px; - margin-right: 10px; - cursor: pointer; - font-size: 1.4em; -} - -.litegraph .dialog .close:hover { - color: white; -} - -.litegraph .dialog .dialog-header { - color: #AAA; - border-bottom: 1px solid #161616; -} - -.litegraph .dialog .dialog-header { height: 40px; } -.litegraph .dialog .dialog-footer { height: 50px; padding: 10px; border-top: 1px solid #1a1a1a;} - -.litegraph .dialog .dialog-header .dialog-title { - font: 20px "Arial"; - margin: 4px; - padding: 4px 10px; - display: inline-block; -} - -.litegraph .dialog .dialog-content, .litegraph .dialog .dialog-alt-content { - height: calc(100% - 90px); - width: 100%; - min-height: 100px; - display: inline-block; - color: #AAA; - /*background-color: black;*/ - overflow: auto; -} - -.litegraph .dialog .dialog-content h3 { - margin: 10px; -} - -.litegraph .dialog .dialog-content .connections { - flex-direction: row; -} - -.litegraph .dialog .dialog-content .connections .connections_side { - width: calc(50% - 5px); - min-height: 100px; - background-color: black; - display: flex; -} - -.litegraph .dialog .node_type { - font-size: 1.2em; - display: block; - margin: 10px; -} - -.litegraph .dialog .node_desc { - opacity: 0.5; - display: block; - margin: 10px; -} - -.litegraph .dialog .separator { - display: block; - width: calc( 100% - 4px ); - height: 1px; - border-top: 1px solid #000; - border-bottom: 1px solid #333; - margin: 10px 2px; - padding: 0; -} - -.litegraph .dialog .property { - margin-bottom: 2px; - padding: 4px; -} - -.litegraph .dialog .property:hover { - background: #545454; -} - -.litegraph .dialog .property_name { - color: #737373; - display: inline-block; - text-align: left; - vertical-align: top; - width: 160px; - padding-left: 4px; - overflow: hidden; - margin-right: 6px; -} - -.litegraph .dialog .property:hover .property_name { - color: white; -} - -.litegraph .dialog .property_value { - display: inline-block; - text-align: right; - color: #AAA; - background-color: #1A1A1A; - /*width: calc( 100% - 122px );*/ - max-width: calc( 100% - 162px ); - min-width: 200px; - max-height: 300px; - min-height: 20px; - padding: 4px; - padding-right: 12px; - overflow: hidden; - cursor: pointer; - border-radius: 3px; -} - -.litegraph .dialog .property_value:hover { - color: white; -} - -.litegraph .dialog .property.boolean .property_value { - padding-right: 30px; - color: #A88; - /*width: auto; - float: right;*/ -} - -.litegraph .dialog .property.boolean.bool-on .property_name{ - color: #8A8; -} -.litegraph .dialog .property.boolean.bool-on .property_value{ - color: #8A8; -} - -.litegraph .dialog .btn { - border: 0; - border-radius: 4px; - padding: 4px 20px; - margin-left: 0px; - background-color: #060606; - color: #8e8e8e; -} - -.litegraph .dialog .btn:hover { - background-color: #111; - color: #FFF; -} - -.litegraph .dialog .btn.delete:hover { - background-color: #F33; - color: black; -} - -.litegraph .subgraph_property { - padding: 4px; -} - -.litegraph .subgraph_property:hover { - background-color: #333; -} - -.litegraph .subgraph_property.extra { - margin-top: 8px; -} - -.litegraph .subgraph_property span.name { - font-size: 1.3em; - padding-left: 4px; -} - -.litegraph .subgraph_property span.type { - opacity: 0.5; - margin-right: 20px; - padding-left: 4px; -} - -.litegraph .subgraph_property span.label { - display: inline-block; - width: 60px; - padding: 0px 10px; -} - -.litegraph .subgraph_property input { - width: 140px; - color: #999; - background-color: #1A1A1A; - border-radius: 4px; - border: 0; - margin-right: 10px; - padding: 4px; - padding-left: 10px; -} - -.litegraph .subgraph_property button { - background-color: #1c1c1c; - color: #aaa; - border: 0; - border-radius: 2px; - padding: 4px 10px; - cursor: pointer; -} - -.litegraph .subgraph_property.extra { - color: #ccc; -} - -.litegraph .subgraph_property.extra input { - background-color: #111; -} - -.litegraph .bullet_icon { - margin-left: 10px; - border-radius: 10px; - width: 12px; - height: 12px; - background-color: #666; - display: inline-block; - margin-top: 2px; - margin-right: 4px; - transition: background-color 0.1s ease 0s; - -moz-transition: background-color 0.1s ease 0s; -} - -.litegraph .bullet_icon:hover { - background-color: #698; - cursor: pointer; -} - -/* OLD */ - -.graphcontextmenu { - padding: 4px; - min-width: 100px; -} - -.graphcontextmenu-title { - color: #dde; - background-color: #222; - margin: 0; - padding: 2px; - cursor: default; -} - -.graphmenu-entry { - box-sizing: border-box; - margin: 2px; - padding-left: 20px; - user-select: none; - -moz-user-select: none; - -webkit-user-select: none; - transition: all linear 0.3s; -} - -.graphmenu-entry.event, -.litemenu-entry.event { - border-left: 8px solid orange; - padding-left: 12px; -} - -.graphmenu-entry.disabled { - opacity: 0.3; -} - -.graphmenu-entry.submenu { - border-right: 2px solid #eee; -} - -.graphmenu-entry:hover { - background-color: #555; -} - -.graphmenu-entry.separator { - background-color: #111; - border-bottom: 1px solid #666; - height: 1px; - width: calc(100% - 20px); - -moz-width: calc(100% - 20px); - -webkit-width: calc(100% - 20px); -} - -.graphmenu-entry .property_name { - display: inline-block; - text-align: left; - min-width: 80px; - min-height: 1.2em; -} - -.graphmenu-entry .property_value, -.litemenu-entry .property_value { - display: inline-block; - background-color: rgba(0, 0, 0, 0.5); - text-align: right; - min-width: 80px; - min-height: 1.2em; - vertical-align: middle; - padding-right: 10px; -} - -.graphdialog { - position: absolute; - top: 10px; - left: 10px; - min-height: 2em; - background-color: #333; - font-size: 1.2em; - box-shadow: 0 0 10px black !important; - z-index: 10; -} - -.graphdialog.rounded { - border-radius: 12px; - padding-right: 2px; -} - -.graphdialog .name { - display: inline-block; - min-width: 60px; - min-height: 1.5em; - padding-left: 10px; -} - -.graphdialog input, -.graphdialog textarea, -.graphdialog select { - margin: 3px; - min-width: 60px; - min-height: 1.5em; - background-color: black; - border: 0; - color: white; - padding-left: 10px; - outline: none; -} - -.graphdialog textarea { - min-height: 150px; -} - -.graphdialog button { - margin-top: 3px; - vertical-align: top; - background-color: #999; - border: 0; -} - -.graphdialog button.rounded, -.graphdialog input.rounded { - border-radius: 0 12px 12px 0; -} - -.graphdialog .helper { - overflow: auto; - max-height: 200px; -} - -.graphdialog .help-item { - padding-left: 10px; -} - -.graphdialog .help-item:hover, -.graphdialog .help-item.selected { - cursor: pointer; - background-color: white; - color: black; -} - -.litegraph .dialog { - min-height: 0; -} -.litegraph .dialog .dialog-content { -display: block; -} -.litegraph .dialog .dialog-content .subgraph_property { -padding: 5px; -} -.litegraph .dialog .dialog-footer { -margin: 0; -} -.litegraph .dialog .dialog-footer .subgraph_property { -margin-top: 0; -display: flex; -align-items: center; -padding: 5px; -} -.litegraph .dialog .dialog-footer .subgraph_property .name { -flex: 1; -} -.litegraph .graphdialog { -display: flex; -align-items: center; -border-radius: 20px; -padding: 4px 10px; -position: fixed; -} -.litegraph .graphdialog .name { -padding: 0; -min-height: 0; -font-size: 16px; -vertical-align: middle; -} -.litegraph .graphdialog .value { -font-size: 16px; -min-height: 0; -margin: 0 10px; -padding: 2px 5px; -} -.litegraph .graphdialog input[type="checkbox"] { -width: 16px; -height: 16px; -} -.litegraph .graphdialog button { -padding: 4px 18px; -border-radius: 20px; -cursor: pointer; -} - diff --git a/web/lib/litegraph.extensions.js b/web/lib/litegraph.extensions.js deleted file mode 100644 index 32853fe49..000000000 --- a/web/lib/litegraph.extensions.js +++ /dev/null @@ -1,21 +0,0 @@ -/** - * Changes the background color of the canvas. - * - * @method updateBackground - * @param {image} String - * @param {clearBackgroundColor} String - * @ - */ -LGraphCanvas.prototype.updateBackground = function (image, clearBackgroundColor) { - this._bg_img = new Image(); - this._bg_img.name = image; - this._bg_img.src = image; - this._bg_img.onload = () => { - this.draw(true, true); - }; - this.background_image = image; - - this.clear_background = true; - this.clear_background_color = clearBackgroundColor; - this._pattern = null -} diff --git a/web/lib/materialdesignicons.min.css b/web/materialdesignicons.min.css similarity index 100% rename from web/lib/materialdesignicons.min.css rename to web/materialdesignicons.min.css diff --git a/web/scripts/api.js b/web/scripts/api.js index 03c3fb607..2594a0464 100644 --- a/web/scripts/api.js +++ b/web/scripts/api.js @@ -1,482 +1,2 @@ -class ComfyApi extends EventTarget { - #registered = new Set(); - - constructor() { - super(); - this.api_host = location.host; - this.api_base = location.pathname.split('/').slice(0, -1).join('/'); - this.initialClientId = sessionStorage.getItem("clientId"); - } - - apiURL(route) { - return this.api_base + route; - } - - fetchApi(route, options) { - if (!options) { - options = {}; - } - if (!options.headers) { - options.headers = {}; - } - options.headers["Comfy-User"] = this.user; - return fetch(this.apiURL(route), options); - } - - addEventListener(type, callback, options) { - super.addEventListener(type, callback, options); - this.#registered.add(type); - } - - /** - * Poll status for colab and other things that don't support websockets. - */ - #pollQueue() { - setInterval(async () => { - try { - const resp = await this.fetchApi("/prompt"); - const status = await resp.json(); - this.dispatchEvent(new CustomEvent("status", { detail: status })); - } catch (error) { - this.dispatchEvent(new CustomEvent("status", { detail: null })); - } - }, 1000); - } - - /** - * Creates and connects a WebSocket for realtime updates - * @param {boolean} isReconnect If the socket is connection is a reconnect attempt - */ - #createSocket(isReconnect) { - if (this.socket) { - return; - } - - let opened = false; - let existingSession = window.name; - if (existingSession) { - existingSession = "?clientId=" + existingSession; - } - this.socket = new WebSocket( - `ws${window.location.protocol === "https:" ? "s" : ""}://${this.api_host}${this.api_base}/ws${existingSession}` - ); - this.socket.binaryType = "arraybuffer"; - - this.socket.addEventListener("open", () => { - opened = true; - if (isReconnect) { - this.dispatchEvent(new CustomEvent("reconnected")); - } - }); - - this.socket.addEventListener("error", () => { - if (this.socket) this.socket.close(); - if (!isReconnect && !opened) { - this.#pollQueue(); - } - }); - - this.socket.addEventListener("close", () => { - setTimeout(() => { - this.socket = null; - this.#createSocket(true); - }, 300); - if (opened) { - this.dispatchEvent(new CustomEvent("status", { detail: null })); - this.dispatchEvent(new CustomEvent("reconnecting")); - } - }); - - this.socket.addEventListener("message", (event) => { - try { - if (event.data instanceof ArrayBuffer) { - const view = new DataView(event.data); - const eventType = view.getUint32(0); - const buffer = event.data.slice(4); - switch (eventType) { - case 1: - const view2 = new DataView(event.data); - const imageType = view2.getUint32(0) - let imageMime - switch (imageType) { - case 1: - default: - imageMime = "image/jpeg"; - break; - case 2: - imageMime = "image/png" - } - const imageBlob = new Blob([buffer.slice(4)], { type: imageMime }); - this.dispatchEvent(new CustomEvent("b_preview", { detail: imageBlob })); - break; - default: - throw new Error(`Unknown binary websocket message of type ${eventType}`); - } - } - else { - const msg = JSON.parse(event.data); - switch (msg.type) { - case "status": - if (msg.data.sid) { - this.clientId = msg.data.sid; - window.name = this.clientId; // use window name so it isnt reused when duplicating tabs - sessionStorage.setItem("clientId", this.clientId); // store in session storage so duplicate tab can load correct workflow - } - this.dispatchEvent(new CustomEvent("status", { detail: msg.data.status })); - break; - case "progress": - this.dispatchEvent(new CustomEvent("progress", { detail: msg.data })); - break; - case "executing": - this.dispatchEvent(new CustomEvent("executing", { detail: msg.data.node })); - break; - case "executed": - this.dispatchEvent(new CustomEvent("executed", { detail: msg.data })); - break; - case "execution_start": - this.dispatchEvent(new CustomEvent("execution_start", { detail: msg.data })); - break; - case "execution_success": - this.dispatchEvent(new CustomEvent("execution_success", { detail: msg.data })); - break; - case "execution_error": - this.dispatchEvent(new CustomEvent("execution_error", { detail: msg.data })); - break; - case "execution_cached": - this.dispatchEvent(new CustomEvent("execution_cached", { detail: msg.data })); - break; - default: - if (this.#registered.has(msg.type)) { - this.dispatchEvent(new CustomEvent(msg.type, { detail: msg.data })); - } else { - throw new Error(`Unknown message type ${msg.type}`); - } - } - } - } catch (error) { - console.warn("Unhandled message:", event.data, error); - } - }); - } - - /** - * Initialises sockets and realtime updates - */ - init() { - this.#createSocket(); - } - - /** - * Gets a list of extension urls - * @returns An array of script urls to import - */ - async getExtensions() { - const resp = await this.fetchApi("/extensions", { cache: "no-store" }); - return await resp.json(); - } - - /** - * Gets a list of embedding names - * @returns An array of script urls to import - */ - async getEmbeddings() { - const resp = await this.fetchApi("/embeddings", { cache: "no-store" }); - return await resp.json(); - } - - /** - * Loads node object definitions for the graph - * @returns The node definitions - */ - async getNodeDefs() { - const resp = await this.fetchApi("/object_info", { cache: "no-store" }); - return await resp.json(); - } - - /** - * - * @param {number} number The index at which to queue the prompt, passing -1 will insert the prompt at the front of the queue - * @param {object} prompt The prompt data to queue - */ - async queuePrompt(number, { output, workflow }) { - const body = { - client_id: this.clientId, - prompt: output, - extra_data: { extra_pnginfo: { workflow } }, - }; - - if (number === -1) { - body.front = true; - } else if (number != 0) { - body.number = number; - } - - const res = await this.fetchApi("/prompt", { - method: "POST", - headers: { - "Content-Type": "application/json", - }, - body: JSON.stringify(body), - }); - - if (res.status !== 200) { - throw { - response: await res.json(), - }; - } - - return await res.json(); - } - - /** - * Loads a list of items (queue or history) - * @param {string} type The type of items to load, queue or history - * @returns The items of the specified type grouped by their status - */ - async getItems(type) { - if (type === "queue") { - return this.getQueue(); - } - return this.getHistory(); - } - - /** - * Gets the current state of the queue - * @returns The currently running and queued items - */ - async getQueue() { - try { - const res = await this.fetchApi("/queue"); - const data = await res.json(); - return { - // Running action uses a different endpoint for cancelling - Running: data.queue_running.map((prompt) => ({ - prompt, - remove: { name: "Cancel", cb: () => api.interrupt() }, - })), - Pending: data.queue_pending.map((prompt) => ({ prompt })), - }; - } catch (error) { - console.error(error); - return { Running: [], Pending: [] }; - } - } - - /** - * Gets the prompt execution history - * @returns Prompt history including node outputs - */ - async getHistory(max_items=200) { - try { - const res = await this.fetchApi(`/history?max_items=${max_items}`); - return { History: Object.values(await res.json()) }; - } catch (error) { - console.error(error); - return { History: [] }; - } - } - - /** - * Gets system & device stats - * @returns System stats such as python version, OS, per device info - */ - async getSystemStats() { - const res = await this.fetchApi("/system_stats"); - return await res.json(); - } - - /** - * Sends a POST request to the API - * @param {*} type The endpoint to post to - * @param {*} body Optional POST data - */ - async #postItem(type, body) { - try { - await this.fetchApi("/" + type, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, - body: body ? JSON.stringify(body) : undefined, - }); - } catch (error) { - console.error(error); - } - } - - /** - * Deletes an item from the specified list - * @param {string} type The type of item to delete, queue or history - * @param {number} id The id of the item to delete - */ - async deleteItem(type, id) { - await this.#postItem(type, { delete: [id] }); - } - - /** - * Clears the specified list - * @param {string} type The type of list to clear, queue or history - */ - async clearItems(type) { - await this.#postItem(type, { clear: true }); - } - - /** - * Interrupts the execution of the running prompt - */ - async interrupt() { - await this.#postItem("interrupt", null); - } - - /** - * Gets user configuration data and where data should be stored - * @returns { Promise<{ storage: "server" | "browser", users?: Promise, migrated?: boolean }> } - */ - async getUserConfig() { - return (await this.fetchApi("/users")).json(); - } - - /** - * Creates a new user - * @param { string } username - * @returns The fetch response - */ - createUser(username) { - return this.fetchApi("/users", { - method: "POST", - headers: { - "Content-Type": "application/json", - }, - body: JSON.stringify({ username }), - }); - } - - /** - * Gets all setting values for the current user - * @returns { Promise } A dictionary of id -> value - */ - async getSettings() { - return (await this.fetchApi("/settings")).json(); - } - - /** - * Gets a setting for the current user - * @param { string } id The id of the setting to fetch - * @returns { Promise } The setting value - */ - async getSetting(id) { - return (await this.fetchApi(`/settings/${encodeURIComponent(id)}`)).json(); - } - - /** - * Stores a dictionary of settings for the current user - * @param { Record } settings Dictionary of setting id -> value to save - * @returns { Promise } - */ - async storeSettings(settings) { - return this.fetchApi(`/settings`, { - method: "POST", - body: JSON.stringify(settings) - }); - } - - /** - * Stores a setting for the current user - * @param { string } id The id of the setting to update - * @param { unknown } value The value of the setting - * @returns { Promise } - */ - async storeSetting(id, value) { - return this.fetchApi(`/settings/${encodeURIComponent(id)}`, { - method: "POST", - body: JSON.stringify(value) - }); - } - - /** - * Gets a user data file for the current user - * @param { string } file The name of the userdata file to load - * @param { RequestInit } [options] - * @returns { Promise } The fetch response object - */ - async getUserData(file, options) { - return this.fetchApi(`/userdata/${encodeURIComponent(file)}`, options); - } - - /** - * Stores a user data file for the current user - * @param { string } file The name of the userdata file to save - * @param { unknown } data The data to save to the file - * @param { RequestInit & { overwrite?: boolean, stringify?: boolean, throwOnError?: boolean } } [options] - * @returns { Promise } - */ - async storeUserData(file, data, options = { overwrite: true, stringify: true, throwOnError: true }) { - const resp = await this.fetchApi(`/userdata/${encodeURIComponent(file)}?overwrite=${options?.overwrite}`, { - method: "POST", - body: options?.stringify ? JSON.stringify(data) : data, - ...options, - }); - if (resp.status !== 200 && options?.throwOnError !== false) { - throw new Error(`Error storing user data file '${file}': ${resp.status} ${(await resp).statusText}`); - } - return resp; - } - - /** - * Deletes a user data file for the current user - * @param { string } file The name of the userdata file to delete - */ - async deleteUserData(file) { - const resp = await this.fetchApi(`/userdata/${encodeURIComponent(file)}`, { - method: "DELETE", - }); - if (resp.status !== 204) { - throw new Error(`Error removing user data file '${file}': ${resp.status} ${(resp).statusText}`); - } - } - - /** - * Move a user data file for the current user - * @param { string } source The userdata file to move - * @param { string } dest The destination for the file - */ - async moveUserData(source, dest, options = { overwrite: false }) { - const resp = await this.fetchApi(`/userdata/${encodeURIComponent(source)}/move/${encodeURIComponent(dest)}?overwrite=${options?.overwrite}`, { - method: "POST", - }); - return resp; - } - - /** - * @overload - * Lists user data files for the current user - * @param { string } dir The directory in which to list files - * @param { boolean } [recurse] If the listing should be recursive - * @param { true } [split] If the paths should be split based on the os path separator - * @returns { Promise> } The list of split file paths in the format [fullPath, ...splitPath] - */ - /** - * @overload - * Lists user data files for the current user - * @param { string } dir The directory in which to list files - * @param { boolean } [recurse] If the listing should be recursive - * @param { false | undefined } [split] If the paths should be split based on the os path separator - * @returns { Promise> } The list of files - */ - async listUserData(dir, recurse, split) { - const resp = await this.fetchApi( - `/userdata?${new URLSearchParams({ - recurse, - dir, - split, - })}` - ); - if (resp.status === 404) return []; - if (resp.status !== 200) { - throw new Error(`Error getting user data list '${dir}': ${resp.status} ${resp.statusText}`); - } - return resp.json(); - } -} - -export const api = new ComfyApi(); +// Shim for scripts\api.ts +export const api = window.comfyAPI.api.api; diff --git a/web/scripts/app.js b/web/scripts/app.js index 8b4478a32..8d3e87896 100644 --- a/web/scripts/app.js +++ b/web/scripts/app.js @@ -1,2459 +1,4 @@ -import { ComfyLogging } from "./logging.js"; -import { ComfyWidgets, initWidgets } from "./widgets.js"; -import { ComfyUI, $el } from "./ui.js"; -import { api } from "./api.js"; -import { defaultGraph } from "./defaultGraph.js"; -import { getPngMetadata, getWebpMetadata, getFlacMetadata, importA1111, getLatentMetadata } from "./pnginfo.js"; -import { addDomClippingSetting } from "./domWidget.js"; -import { createImageHost, calculateImageGrid } from "./ui/imagePreview.js"; -import { ComfyAppMenu } from "./ui/menu/index.js"; -import { getStorageValue, setStorageValue } from "./utils.js"; -import { ComfyWorkflowManager } from "./workflows.js"; -export const ANIM_PREVIEW_WIDGET = "$$comfy_animation_preview"; - -function sanitizeNodeName(string) { - let entityMap = { - '&': '', - '<': '', - '>': '', - '"': '', - "'": '', - '`': '', - '=': '' - }; - return String(string).replace(/[&<>"'`=]/g, function fromEntityMap (s) { - return entityMap[s]; - }); -} - -/** - * @typedef {import("types/comfy").ComfyExtension} ComfyExtension - */ - -export class ComfyApp { - /** - * List of entries to queue - * @type {{number: number, batchCount: number}[]} - */ - #queueItems = []; - /** - * If the queue is currently being processed - * @type {boolean} - */ - #processingQueue = false; - - /** - * Content Clipboard - * @type {serialized node object} - */ - static clipspace = null; - static clipspace_invalidate_handler = null; - static open_maskeditor = null; - static clipspace_return_node = null; - - constructor() { - this.ui = new ComfyUI(this); - this.logging = new ComfyLogging(this); - this.workflowManager = new ComfyWorkflowManager(this); - this.bodyTop = $el("div.comfyui-body-top", { parent: document.body }); - this.bodyLeft = $el("div.comfyui-body-left", { parent: document.body }); - this.bodyRight = $el("div.comfyui-body-right", { parent: document.body }); - this.bodyBottom = $el("div.comfyui-body-bottom", { parent: document.body }); - this.menu = new ComfyAppMenu(this); - - /** - * List of extensions that are registered with the app - * @type {ComfyExtension[]} - */ - this.extensions = []; - - /** - * Stores the execution output data for each node - * @type {Record} - */ - this._nodeOutputs = {}; - - /** - * Stores the preview image data for each node - * @type {Record} - */ - this.nodePreviewImages = {}; - - /** - * If the shift key on the keyboard is pressed - * @type {boolean} - */ - this.shiftDown = false; - } - - get nodeOutputs() { - return this._nodeOutputs; - } - - set nodeOutputs(value) { - this._nodeOutputs = value; - this.#invokeExtensions("onNodeOutputsUpdated", value); - } - - getPreviewFormatParam() { - let preview_format = this.ui.settings.getSettingValue("Comfy.PreviewFormat"); - if(preview_format) - return `&preview=${preview_format}`; - else - return ""; - } - - getRandParam() { - return "&rand=" + Math.random(); - } - - static isImageNode(node) { - return node.imgs || (node && node.widgets && node.widgets.findIndex(obj => obj.name === 'image') >= 0); - } - - static onClipspaceEditorSave() { - if(ComfyApp.clipspace_return_node) { - ComfyApp.pasteFromClipspace(ComfyApp.clipspace_return_node); - } - } - - static onClipspaceEditorClosed() { - ComfyApp.clipspace_return_node = null; - } - - static copyToClipspace(node) { - var widgets = null; - if(node.widgets) { - widgets = node.widgets.map(({ type, name, value }) => ({ type, name, value })); - } - - var imgs = undefined; - var orig_imgs = undefined; - if(node.imgs != undefined) { - imgs = []; - orig_imgs = []; - - for (let i = 0; i < node.imgs.length; i++) { - imgs[i] = new Image(); - imgs[i].src = node.imgs[i].src; - orig_imgs[i] = imgs[i]; - } - } - - var selectedIndex = 0; - if(node.imageIndex) { - selectedIndex = node.imageIndex; - } - - ComfyApp.clipspace = { - 'widgets': widgets, - 'imgs': imgs, - 'original_imgs': orig_imgs, - 'images': node.images, - 'selectedIndex': selectedIndex, - 'img_paste_mode': 'selected' // reset to default im_paste_mode state on copy action - }; - - ComfyApp.clipspace_return_node = null; - - if(ComfyApp.clipspace_invalidate_handler) { - ComfyApp.clipspace_invalidate_handler(); - } - } - - static pasteFromClipspace(node) { - if(ComfyApp.clipspace) { - // image paste - if(ComfyApp.clipspace.imgs && node.imgs) { - if(node.images && ComfyApp.clipspace.images) { - if(ComfyApp.clipspace['img_paste_mode'] == 'selected') { - node.images = [ComfyApp.clipspace.images[ComfyApp.clipspace['selectedIndex']]]; - } - else { - node.images = ComfyApp.clipspace.images; - } - - if(app.nodeOutputs[node.id + ""]) - app.nodeOutputs[node.id + ""].images = node.images; - } - - if(ComfyApp.clipspace.imgs) { - // deep-copy to cut link with clipspace - if(ComfyApp.clipspace['img_paste_mode'] == 'selected') { - const img = new Image(); - img.src = ComfyApp.clipspace.imgs[ComfyApp.clipspace['selectedIndex']].src; - node.imgs = [img]; - node.imageIndex = 0; - } - else { - const imgs = []; - for(let i=0; i obj.name === 'image'); - if(index >= 0) { - if(node.widgets[index].type != 'image' && typeof node.widgets[index].value == "string" && clip_image.filename) { - node.widgets[index].value = (clip_image.subfolder?clip_image.subfolder+'/':'') + clip_image.filename + (clip_image.type?` [${clip_image.type}]`:''); - } - else { - node.widgets[index].value = clip_image; - } - } - } - if(ComfyApp.clipspace.widgets) { - ComfyApp.clipspace.widgets.forEach(({ type, name, value }) => { - const prop = Object.values(node.widgets).find(obj => obj.type === type && obj.name === name); - if (prop && prop.type != 'button') { - if(prop.type != 'image' && typeof prop.value == "string" && value.filename) { - prop.value = (value.subfolder?value.subfolder+'/':'') + value.filename + (value.type?` [${value.type}]`:''); - } - else { - prop.value = value; - prop.callback(value); - } - } - }); - } - } - - app.graph.setDirtyCanvas(true); - } - } - - /** - * Invoke an extension callback - * @param {keyof ComfyExtension} method The extension callback to execute - * @param {any[]} args Any arguments to pass to the callback - * @returns - */ - #invokeExtensions(method, ...args) { - let results = []; - for (const ext of this.extensions) { - if (method in ext) { - try { - results.push(ext[method](...args, this)); - } catch (error) { - console.error( - `Error calling extension '${ext.name}' method '${method}'`, - { error }, - { extension: ext }, - { args } - ); - } - } - } - return results; - } - - /** - * Invoke an async extension callback - * Each callback will be invoked concurrently - * @param {string} method The extension callback to execute - * @param {...any} args Any arguments to pass to the callback - * @returns - */ - async #invokeExtensionsAsync(method, ...args) { - return await Promise.all( - this.extensions.map(async (ext) => { - if (method in ext) { - try { - return await ext[method](...args, this); - } catch (error) { - console.error( - `Error calling extension '${ext.name}' method '${method}'`, - { error }, - { extension: ext }, - { args } - ); - } - } - }) - ); - } - - #addRestoreWorkflowView() { - const serialize = LGraph.prototype.serialize; - const self = this; - LGraph.prototype.serialize = function() { - const workflow = serialize.apply(this, arguments); - - // Store the drag & scale info in the serialized workflow if the setting is enabled - if (self.enableWorkflowViewRestore.value) { - if (!workflow.extra) { - workflow.extra = {}; - } - workflow.extra.ds = { - scale: self.canvas.ds.scale, - offset: self.canvas.ds.offset, - }; - } else if (workflow.extra?.ds) { - // Clear any old view data - delete workflow.extra.ds; - } - - return workflow; - } - this.enableWorkflowViewRestore = this.ui.settings.addSetting({ - id: "Comfy.EnableWorkflowViewRestore", - name: "Save and restore canvas position and zoom level in workflows", - type: "boolean", - defaultValue: true - }); - } - - /** - * Adds special context menu handling for nodes - * e.g. this adds Open Image functionality for nodes that show images - * @param {*} node The node to add the menu handler - */ - #addNodeContextMenuHandler(node) { - function getCopyImageOption(img) { - if (typeof window.ClipboardItem === "undefined") return []; - return [ - { - content: "Copy Image", - callback: async () => { - const url = new URL(img.src); - url.searchParams.delete("preview"); - - const writeImage = async (blob) => { - await navigator.clipboard.write([ - new ClipboardItem({ - [blob.type]: blob, - }), - ]); - }; - - try { - const data = await fetch(url); - const blob = await data.blob(); - try { - await writeImage(blob); - } catch (error) { - // Chrome seems to only support PNG on write, convert and try again - if (blob.type !== "image/png") { - const canvas = $el("canvas", { - width: img.naturalWidth, - height: img.naturalHeight, - }); - const ctx = canvas.getContext("2d"); - let image; - if (typeof window.createImageBitmap === "undefined") { - image = new Image(); - const p = new Promise((resolve, reject) => { - image.onload = resolve; - image.onerror = reject; - }).finally(() => { - URL.revokeObjectURL(image.src); - }); - image.src = URL.createObjectURL(blob); - await p; - } else { - image = await createImageBitmap(blob); - } - try { - ctx.drawImage(image, 0, 0); - canvas.toBlob(writeImage, "image/png"); - } finally { - if (typeof image.close === "function") { - image.close(); - } - } - - return; - } - throw error; - } - } catch (error) { - alert("Error copying image: " + (error.message ?? error)); - } - }, - }, - ]; - } - - node.prototype.getExtraMenuOptions = function (_, options) { - if (this.imgs) { - // If this node has images then we add an open in new tab item - let img; - if (this.imageIndex != null) { - // An image is selected so select that - img = this.imgs[this.imageIndex]; - } else if (this.overIndex != null) { - // No image is selected but one is hovered - img = this.imgs[this.overIndex]; - } - if (img) { - options.unshift( - { - content: "Open Image", - callback: () => { - let url = new URL(img.src); - url.searchParams.delete("preview"); - window.open(url, "_blank"); - }, - }, - ...getCopyImageOption(img), - { - content: "Save Image", - callback: () => { - const a = document.createElement("a"); - let url = new URL(img.src); - url.searchParams.delete("preview"); - a.href = url; - a.setAttribute("download", new URLSearchParams(url.search).get("filename")); - document.body.append(a); - a.click(); - requestAnimationFrame(() => a.remove()); - }, - } - ); - } - } - - options.push({ - content: "Bypass", - callback: (obj) => { - if (this.mode === 4) this.mode = 0; - else this.mode = 4; - this.graph.change(); - }, - }); - - // prevent conflict of clipspace content - if (!ComfyApp.clipspace_return_node) { - options.push({ - content: "Copy (Clipspace)", - callback: (obj) => { - ComfyApp.copyToClipspace(this); - }, - }); - - if (ComfyApp.clipspace != null) { - options.push({ - content: "Paste (Clipspace)", - callback: () => { - ComfyApp.pasteFromClipspace(this); - }, - }); - } - - if (ComfyApp.isImageNode(this)) { - options.push({ - content: "Open in MaskEditor", - callback: (obj) => { - ComfyApp.copyToClipspace(this); - ComfyApp.clipspace_return_node = this; - ComfyApp.open_maskeditor(); - }, - }); - } - } - }; - } - - #addNodeKeyHandler(node) { - const app = this; - const origNodeOnKeyDown = node.prototype.onKeyDown; - - node.prototype.onKeyDown = function(e) { - if (origNodeOnKeyDown && origNodeOnKeyDown.apply(this, e) === false) { - return false; - } - - if (this.flags.collapsed || !this.imgs || this.imageIndex === null) { - return; - } - - let handled = false; - - if (e.key === "ArrowLeft" || e.key === "ArrowRight") { - if (e.key === "ArrowLeft") { - this.imageIndex -= 1; - } else if (e.key === "ArrowRight") { - this.imageIndex += 1; - } - this.imageIndex %= this.imgs.length; - - if (this.imageIndex < 0) { - this.imageIndex = this.imgs.length + this.imageIndex; - } - handled = true; - } else if (e.key === "Escape") { - this.imageIndex = null; - handled = true; - } - - if (handled === true) { - e.preventDefault(); - e.stopImmediatePropagation(); - return false; - } - } - } - - /** - * Adds Custom drawing logic for nodes - * e.g. Draws images and handles thumbnail navigation on nodes that output images - * @param {*} node The node to add the draw handler - */ - #addDrawBackgroundHandler(node) { - const app = this; - - function getImageTop(node) { - let shiftY; - if (node.imageOffset != null) { - shiftY = node.imageOffset; - } else { - if (node.widgets?.length) { - const w = node.widgets[node.widgets.length - 1]; - shiftY = w.last_y; - if (w.computeSize) { - shiftY += w.computeSize()[1] + 4; - } - else if(w.computedHeight) { - shiftY += w.computedHeight; - } - else { - shiftY += LiteGraph.NODE_WIDGET_HEIGHT + 4; - } - } else { - shiftY = node.computeSize()[1]; - } - } - return shiftY; - } - - node.prototype.setSizeForImage = function (force) { - if(!force && this.animatedImages) return; - - if (this.inputHeight || this.freeWidgetSpace > 210) { - this.setSize(this.size); - return; - } - const minHeight = getImageTop(this) + 220; - if (this.size[1] < minHeight) { - this.setSize([this.size[0], minHeight]); - } - }; - - node.prototype.onDrawBackground = function (ctx) { - if (!this.flags.collapsed) { - let imgURLs = [] - let imagesChanged = false - - const output = app.nodeOutputs[this.id + ""]; - if (output?.images) { - this.animatedImages = output?.animated?.find(Boolean); - if (this.images !== output.images) { - this.images = output.images; - imagesChanged = true; - imgURLs = imgURLs.concat( - output.images.map((params) => { - return api.apiURL( - "/view?" + - new URLSearchParams(params).toString() + - (this.animatedImages ? "" : app.getPreviewFormatParam()) + app.getRandParam() - ); - }) - ); - } - } - - const preview = app.nodePreviewImages[this.id + ""] - if (this.preview !== preview) { - this.preview = preview - imagesChanged = true; - if (preview != null) { - imgURLs.push(preview); - } - } - - if (imagesChanged) { - this.imageIndex = null; - if (imgURLs.length > 0) { - Promise.all( - imgURLs.map((src) => { - return new Promise((r) => { - const img = new Image(); - img.onload = () => r(img); - img.onerror = () => r(null); - img.src = src - }); - }) - ).then((imgs) => { - if ((!output || this.images === output.images) && (!preview || this.preview === preview)) { - this.imgs = imgs.filter(Boolean); - this.setSizeForImage?.(); - app.graph.setDirtyCanvas(true); - } - }); - } - else { - this.imgs = null; - } - } - - function calculateGrid(w, h, n) { - let columns, rows, cellsize; - - if (w > h) { - cellsize = h; - columns = Math.ceil(w / cellsize); - rows = Math.ceil(n / columns); - } else { - cellsize = w; - rows = Math.ceil(h / cellsize); - columns = Math.ceil(n / rows); - } - - while (columns * rows < n) { - cellsize++; - if (w >= h) { - columns = Math.ceil(w / cellsize); - rows = Math.ceil(n / columns); - } else { - rows = Math.ceil(h / cellsize); - columns = Math.ceil(n / rows); - } - } - - const cell_size = Math.min(w/columns, h/rows); - return {cell_size, columns, rows}; - } - - function is_all_same_aspect_ratio(imgs) { - // assume: imgs.length >= 2 - let ratio = imgs[0].naturalWidth/imgs[0].naturalHeight; - - for(let i=1; i w.name === ANIM_PREVIEW_WIDGET); - - if(this.animatedImages) { - // Instead of using the canvas we'll use a IMG - if(widgetIdx > -1) { - // Replace content - const widget = this.widgets[widgetIdx]; - widget.options.host.updateImages(this.imgs); - } else { - const host = createImageHost(this); - this.setSizeForImage(true); - const widget = this.addDOMWidget(ANIM_PREVIEW_WIDGET, "img", host.el, { - host, - getHeight: host.getHeight, - onDraw: host.onDraw, - hideOnZoom: false - }); - widget.serializeValue = () => undefined; - widget.options.host.updateImages(this.imgs); - } - return; - } - - if (widgetIdx > -1) { - this.widgets[widgetIdx].onRemove?.(); - this.widgets.splice(widgetIdx, 1); - } - - const canvas = app.graph.list_of_graphcanvas[0]; - const mouse = canvas.graph_mouse; - if (!canvas.pointer_is_down && this.pointerDown) { - if (mouse[0] === this.pointerDown.pos[0] && mouse[1] === this.pointerDown.pos[1]) { - this.imageIndex = this.pointerDown.index; - } - this.pointerDown = null; - } - - let imageIndex = this.imageIndex; - const numImages = this.imgs.length; - if (numImages === 1 && !imageIndex) { - this.imageIndex = imageIndex = 0; - } - - const top = getImageTop(this); - var shiftY = top; - - let dw = this.size[0]; - let dh = this.size[1]; - dh -= shiftY; - - if (imageIndex == null) { - var cellWidth, cellHeight, shiftX, cell_padding, cols; - - const compact_mode = is_all_same_aspect_ratio(this.imgs); - if(!compact_mode) { - // use rectangle cell style and border line - cell_padding = 2; - const { cell_size, columns, rows } = calculateGrid(dw, dh, numImages); - cols = columns; - - cellWidth = cell_size; - cellHeight = cell_size; - shiftX = (dw-cell_size*cols)/2; - shiftY = (dh-cell_size*rows)/2 + top; - } - else { - cell_padding = 0; - ({ cellWidth, cellHeight, cols, shiftX } = calculateImageGrid(this.imgs, dw, dh)); - } - - let anyHovered = false; - this.imageRects = []; - for (let i = 0; i < numImages; i++) { - const img = this.imgs[i]; - const row = Math.floor(i / cols); - const col = i % cols; - const x = col * cellWidth + shiftX; - const y = row * cellHeight + shiftY; - if (!anyHovered) { - anyHovered = LiteGraph.isInsideRectangle( - mouse[0], - mouse[1], - x + this.pos[0], - y + this.pos[1], - cellWidth, - cellHeight - ); - if (anyHovered) { - this.overIndex = i; - let value = 110; - if (canvas.pointer_is_down) { - if (!this.pointerDown || this.pointerDown.index !== i) { - this.pointerDown = { index: i, pos: [...mouse] }; - } - value = 125; - } - ctx.filter = `contrast(${value}%) brightness(${value}%)`; - canvas.canvas.style.cursor = "pointer"; - } - } - this.imageRects.push([x, y, cellWidth, cellHeight]); - - let wratio = cellWidth/img.width; - let hratio = cellHeight/img.height; - var ratio = Math.min(wratio, hratio); - - let imgHeight = ratio * img.height; - let imgY = row * cellHeight + shiftY + (cellHeight - imgHeight)/2; - let imgWidth = ratio * img.width; - let imgX = col * cellWidth + shiftX + (cellWidth - imgWidth)/2; - - ctx.drawImage(img, imgX+cell_padding, imgY+cell_padding, imgWidth-cell_padding*2, imgHeight-cell_padding*2); - if(!compact_mode) { - // rectangle cell and border line style - ctx.strokeStyle = "#8F8F8F"; - ctx.lineWidth = 1; - ctx.strokeRect(x+cell_padding, y+cell_padding, cellWidth-cell_padding*2, cellHeight-cell_padding*2); - } - - ctx.filter = "none"; - } - - if (!anyHovered) { - this.pointerDown = null; - this.overIndex = null; - } - } else { - // Draw individual - let w = this.imgs[imageIndex].naturalWidth; - let h = this.imgs[imageIndex].naturalHeight; - - const scaleX = dw / w; - const scaleY = dh / h; - const scale = Math.min(scaleX, scaleY, 1); - - w *= scale; - h *= scale; - - let x = (dw - w) / 2; - let y = (dh - h) / 2 + shiftY; - ctx.drawImage(this.imgs[imageIndex], x, y, w, h); - - const drawButton = (x, y, sz, text) => { - const hovered = LiteGraph.isInsideRectangle(mouse[0], mouse[1], x + this.pos[0], y + this.pos[1], sz, sz); - let fill = "#333"; - let textFill = "#fff"; - let isClicking = false; - if (hovered) { - canvas.canvas.style.cursor = "pointer"; - if (canvas.pointer_is_down) { - fill = "#1e90ff"; - isClicking = true; - } else { - fill = "#eee"; - textFill = "#000"; - } - } else { - this.pointerWasDown = null; - } - - ctx.fillStyle = fill; - ctx.beginPath(); - ctx.roundRect(x, y, sz, sz, [4]); - ctx.fill(); - ctx.fillStyle = textFill; - ctx.font = "12px Arial"; - ctx.textAlign = "center"; - ctx.fillText(text, x + 15, y + 20); - - return isClicking; - }; - - if (numImages > 1) { - if (drawButton(dw - 40, dh + top - 40, 30, `${this.imageIndex + 1}/${numImages}`)) { - let i = this.imageIndex + 1 >= numImages ? 0 : this.imageIndex + 1; - if (!this.pointerDown || !this.pointerDown.index === i) { - this.pointerDown = { index: i, pos: [...mouse] }; - } - } - - if (drawButton(dw - 40, top + 10, 30, `x`)) { - if (!this.pointerDown || !this.pointerDown.index === null) { - this.pointerDown = { index: null, pos: [...mouse] }; - } - } - } - } - } - } - }; - } - - /** - * Adds a handler allowing drag+drop of files onto the window to load workflows - */ - #addDropHandler() { - // Get prompt from dropped PNG or json - document.addEventListener("drop", async (event) => { - event.preventDefault(); - event.stopPropagation(); - - const n = this.dragOverNode; - this.dragOverNode = null; - // Node handles file drop, we dont use the built in onDropFile handler as its buggy - // If you drag multiple files it will call it multiple times with the same file - if (n && n.onDragDrop && (await n.onDragDrop(event))) { - return; - } - // Dragging from Chrome->Firefox there is a file but its a bmp, so ignore that - if (event.dataTransfer.files.length && event.dataTransfer.files[0].type !== "image/bmp") { - await this.handleFile(event.dataTransfer.files[0]); - } else { - // Try loading the first URI in the transfer list - const validTypes = ["text/uri-list", "text/x-moz-url"]; - const match = [...event.dataTransfer.types].find((t) => validTypes.find(v => t === v)); - if (match) { - const uri = event.dataTransfer.getData(match)?.split("\n")?.[0]; - if (uri) { - await this.handleFile(await (await fetch(uri)).blob()); - } - } - } - }); - - // Always clear over node on drag leave - this.canvasEl.addEventListener("dragleave", async () => { - if (this.dragOverNode) { - this.dragOverNode = null; - this.graph.setDirtyCanvas(false, true); - } - }); - - // Add handler for dropping onto a specific node - this.canvasEl.addEventListener( - "dragover", - (e) => { - this.canvas.adjustMouseEvent(e); - const node = this.graph.getNodeOnPos(e.canvasX, e.canvasY); - if (node) { - if (node.onDragOver && node.onDragOver(e)) { - this.dragOverNode = node; - - // dragover event is fired very frequently, run this on an animation frame - requestAnimationFrame(() => { - this.graph.setDirtyCanvas(false, true); - }); - return; - } - } - this.dragOverNode = null; - }, - false - ); - } - - /** - * Adds a handler on paste that extracts and loads images or workflows from pasted JSON data - */ - #addPasteHandler() { - document.addEventListener("paste", async (e) => { - // ctrl+shift+v is used to paste nodes with connections - // this is handled by litegraph - if(this.shiftDown) return; - - let data = (e.clipboardData || window.clipboardData); - const items = data.items; - - // Look for image paste data - for (const item of items) { - if (item.type.startsWith('image/')) { - var imageNode = null; - - // If an image node is selected, paste into it - if (this.canvas.current_node && - this.canvas.current_node.is_selected && - ComfyApp.isImageNode(this.canvas.current_node)) { - imageNode = this.canvas.current_node; - } - - // No image node selected: add a new one - if (!imageNode) { - const newNode = LiteGraph.createNode("LoadImage"); - newNode.pos = [...this.canvas.graph_mouse]; - imageNode = this.graph.add(newNode); - this.graph.change(); - } - const blob = item.getAsFile(); - imageNode.pasteFile(blob); - return; - } - } - - // No image found. Look for node data - data = data.getData("text/plain"); - let workflow; - try { - data = data.slice(data.indexOf("{")); - workflow = JSON.parse(data); - } catch (err) { - try { - data = data.slice(data.indexOf("workflow\n")); - data = data.slice(data.indexOf("{")); - workflow = JSON.parse(data); - } catch (error) {} - } - - if (workflow && workflow.version && workflow.nodes && workflow.extra) { - await this.loadGraphData(workflow); - } - else { - if (e.target.type === "text" || e.target.type === "textarea") { - return; - } - - // Litegraph default paste - this.canvas.pasteFromClipboard(); - } - - - }); - } - - - /** - * Adds a handler on copy that serializes selected nodes to JSON - */ - #addCopyHandler() { - document.addEventListener("copy", (e) => { - if (e.target.type === "text" || e.target.type === "textarea") { - // Default system copy - return; - } - - // copy nodes and clear clipboard - if (e.target.className === "litegraph" && this.canvas.selected_nodes) { - this.canvas.copyToClipboard(); - e.clipboardData.setData('text', ' '); //clearData doesn't remove images from clipboard - e.preventDefault(); - e.stopImmediatePropagation(); - return false; - } - }); - } - - - /** - * Handle mouse - * - * Move group by header - */ - #addProcessMouseHandler() { - const self = this; - - const origProcessMouseDown = LGraphCanvas.prototype.processMouseDown; - LGraphCanvas.prototype.processMouseDown = function(e) { - // prepare for ctrl+shift drag: zoom start - if(e.ctrlKey && e.shiftKey && e.buttons) { - self.zoom_drag_start = [e.x, e.y, this.ds.scale]; - return; - } - - const res = origProcessMouseDown.apply(this, arguments); - - this.selected_group_moving = false; - - if (this.selected_group && !this.selected_group_resizing) { - var font_size = - this.selected_group.font_size || LiteGraph.DEFAULT_GROUP_FONT_SIZE; - var height = font_size * 1.4; - - // Move group by header - if (LiteGraph.isInsideRectangle(e.canvasX, e.canvasY, this.selected_group.pos[0], this.selected_group.pos[1], this.selected_group.size[0], height)) { - this.selected_group_moving = true; - } - } - - return res; - } - - const origProcessMouseMove = LGraphCanvas.prototype.processMouseMove; - LGraphCanvas.prototype.processMouseMove = function(e) { - // handle ctrl+shift drag - if(e.ctrlKey && e.shiftKey && self.zoom_drag_start) { - // stop canvas zoom action - if(!e.buttons) { - self.zoom_drag_start = null; - return; - } - - // calculate delta - let deltaY = e.y - self.zoom_drag_start[1]; - let startScale = self.zoom_drag_start[2]; - - let scale = startScale - deltaY/100; - - this.ds.changeScale(scale, [this.ds.element.width/2, this.ds.element.height/2]); - this.graph.change(); - - return; - } - - const orig_selected_group = this.selected_group; - - if (this.selected_group && !this.selected_group_resizing && !this.selected_group_moving) { - this.selected_group = null; - } - - const res = origProcessMouseMove.apply(this, arguments); - - if (orig_selected_group && !this.selected_group_resizing && !this.selected_group_moving) { - this.selected_group = orig_selected_group; - } - - return res; - }; - } - - /** - * Handle keypress - * - * Ctrl + M mute/unmute selected nodes - */ - #addProcessKeyHandler() { - const self = this; - const origProcessKey = LGraphCanvas.prototype.processKey; - LGraphCanvas.prototype.processKey = function(e) { - if (!this.graph) { - return; - } - - var block_default = false; - - if (e.target.localName == "input") { - return; - } - - if (e.type == "keydown" && !e.repeat) { - - // Ctrl + M mute/unmute - if (e.key === 'm' && (e.metaKey || e.ctrlKey)) { - if (this.selected_nodes) { - for (var i in this.selected_nodes) { - if (this.selected_nodes[i].mode === 2) { // never - this.selected_nodes[i].mode = 0; // always - } else { - this.selected_nodes[i].mode = 2; // never - } - } - } - block_default = true; - } - - // Ctrl + B bypass - if (e.key === 'b' && (e.metaKey || e.ctrlKey)) { - if (this.selected_nodes) { - for (var i in this.selected_nodes) { - if (this.selected_nodes[i].mode === 4) { // never - this.selected_nodes[i].mode = 0; // always - } else { - this.selected_nodes[i].mode = 4; // never - } - } - } - block_default = true; - } - - // Alt + C collapse/uncollapse - if (e.key === 'c' && e.altKey) { - if (this.selected_nodes) { - for (var i in this.selected_nodes) { - this.selected_nodes[i].collapse() - } - } - block_default = true; - } - - // Ctrl+C Copy - if ((e.key === 'c') && (e.metaKey || e.ctrlKey)) { - // Trigger onCopy - return true; - } - - // Ctrl+V Paste - if ((e.key === 'v' || e.key == 'V') && (e.metaKey || e.ctrlKey) && !e.shiftKey) { - // Trigger onPaste - return true; - } - - if((e.key === '+') && e.altKey) { - block_default = true; - let scale = this.ds.scale * 1.1; - this.ds.changeScale(scale, [this.ds.element.width/2, this.ds.element.height/2]); - this.graph.change(); - } - - if((e.key === '-') && e.altKey) { - block_default = true; - let scale = this.ds.scale * 1 / 1.1; - this.ds.changeScale(scale, [this.ds.element.width/2, this.ds.element.height/2]); - this.graph.change(); - } - } - - this.graph.change(); - - if (block_default) { - e.preventDefault(); - e.stopImmediatePropagation(); - return false; - } - - // Fall through to Litegraph defaults - return origProcessKey.apply(this, arguments); - }; - } - - /** - * Draws group header bar - */ - #addDrawGroupsHandler() { - const self = this; - - const origDrawGroups = LGraphCanvas.prototype.drawGroups; - LGraphCanvas.prototype.drawGroups = function(canvas, ctx) { - if (!this.graph) { - return; - } - - var groups = this.graph._groups; - - ctx.save(); - ctx.globalAlpha = 0.7 * this.editor_alpha; - - for (var i = 0; i < groups.length; ++i) { - var group = groups[i]; - - if (!LiteGraph.overlapBounding(this.visible_area, group._bounding)) { - continue; - } //out of the visible area - - ctx.fillStyle = group.color || "#335"; - ctx.strokeStyle = group.color || "#335"; - var pos = group._pos; - var size = group._size; - ctx.globalAlpha = 0.25 * this.editor_alpha; - ctx.beginPath(); - var font_size = - group.font_size || LiteGraph.DEFAULT_GROUP_FONT_SIZE; - ctx.rect(pos[0] + 0.5, pos[1] + 0.5, size[0], font_size * 1.4); - ctx.fill(); - ctx.globalAlpha = this.editor_alpha; - } - - ctx.restore(); - - const res = origDrawGroups.apply(this, arguments); - return res; - } - } - - /** - * Draws node highlights (executing, drag drop) and progress bar - */ - #addDrawNodeHandler() { - const origDrawNodeShape = LGraphCanvas.prototype.drawNodeShape; - const self = this; - - LGraphCanvas.prototype.drawNodeShape = function (node, ctx, size, fgcolor, bgcolor, selected, mouse_over) { - const res = origDrawNodeShape.apply(this, arguments); - - const nodeErrors = self.lastNodeErrors?.[node.id]; - - let color = null; - let lineWidth = 1; - if (node.id === +self.runningNodeId) { - color = "#0f0"; - } else if (self.dragOverNode && node.id === self.dragOverNode.id) { - color = "dodgerblue"; - } - else if (nodeErrors?.errors) { - color = "red"; - lineWidth = 2; - } - else if (self.lastExecutionError && +self.lastExecutionError.node_id === node.id) { - color = "#f0f"; - lineWidth = 2; - } - - if (color) { - const shape = node._shape || node.constructor.shape || LiteGraph.ROUND_SHAPE; - ctx.lineWidth = lineWidth; - ctx.globalAlpha = 0.8; - ctx.beginPath(); - if (shape == LiteGraph.BOX_SHAPE) - ctx.rect(-6, -6 - LiteGraph.NODE_TITLE_HEIGHT, 12 + size[0] + 1, 12 + size[1] + LiteGraph.NODE_TITLE_HEIGHT); - else if (shape == LiteGraph.ROUND_SHAPE || (shape == LiteGraph.CARD_SHAPE && node.flags.collapsed)) - ctx.roundRect( - -6, - -6 - LiteGraph.NODE_TITLE_HEIGHT, - 12 + size[0] + 1, - 12 + size[1] + LiteGraph.NODE_TITLE_HEIGHT, - this.round_radius * 2 - ); - else if (shape == LiteGraph.CARD_SHAPE) - ctx.roundRect( - -6, - -6 - LiteGraph.NODE_TITLE_HEIGHT, - 12 + size[0] + 1, - 12 + size[1] + LiteGraph.NODE_TITLE_HEIGHT, - [this.round_radius * 2, this.round_radius * 2, 2, 2] - ); - else if (shape == LiteGraph.CIRCLE_SHAPE) - ctx.arc(size[0] * 0.5, size[1] * 0.5, size[0] * 0.5 + 6, 0, Math.PI * 2); - ctx.strokeStyle = color; - ctx.stroke(); - ctx.strokeStyle = fgcolor; - ctx.globalAlpha = 1; - } - - if (self.progress && node.id === +self.runningNodeId) { - ctx.fillStyle = "green"; - ctx.fillRect(0, 0, size[0] * (self.progress.value / self.progress.max), 6); - ctx.fillStyle = bgcolor; - } - - // Highlight inputs that failed validation - if (nodeErrors) { - ctx.lineWidth = 2; - ctx.strokeStyle = "red"; - for (const error of nodeErrors.errors) { - if (error.extra_info && error.extra_info.input_name) { - const inputIndex = node.findInputSlot(error.extra_info.input_name) - if (inputIndex !== -1) { - let pos = node.getConnectionPos(true, inputIndex); - ctx.beginPath(); - ctx.arc(pos[0] - node.pos[0], pos[1] - node.pos[1], 12, 0, 2 * Math.PI, false) - ctx.stroke(); - } - } - } - } - - return res; - }; - - const origDrawNode = LGraphCanvas.prototype.drawNode; - LGraphCanvas.prototype.drawNode = function (node, ctx) { - var editor_alpha = this.editor_alpha; - var old_color = node.bgcolor; - - if (node.mode === 2) { // never - this.editor_alpha = 0.4; - } - - if (node.mode === 4) { // never - node.bgcolor = "#FF00FF"; - this.editor_alpha = 0.2; - } - - const res = origDrawNode.apply(this, arguments); - - this.editor_alpha = editor_alpha; - node.bgcolor = old_color; - - return res; - }; - } - - /** - * Handles updates from the API socket - */ - #addApiUpdateHandlers() { - api.addEventListener("status", ({ detail }) => { - this.ui.setStatus(detail); - }); - - api.addEventListener("reconnecting", () => { - this.ui.dialog.show("Reconnecting..."); - }); - - api.addEventListener("reconnected", () => { - this.ui.dialog.close(); - }); - - api.addEventListener("progress", ({ detail }) => { - if (this.workflowManager.activePrompt?.workflow - && this.workflowManager.activePrompt.workflow !== this.workflowManager.activeWorkflow) return; - this.progress = detail; - this.graph.setDirtyCanvas(true, false); - }); - - api.addEventListener("executing", ({ detail }) => { - if (this.workflowManager.activePrompt ?.workflow - && this.workflowManager.activePrompt.workflow !== this.workflowManager.activeWorkflow) return; - this.progress = null; - this.runningNodeId = detail; - this.graph.setDirtyCanvas(true, false); - delete this.nodePreviewImages[this.runningNodeId] - }); - - api.addEventListener("executed", ({ detail }) => { - if (this.workflowManager.activePrompt ?.workflow - && this.workflowManager.activePrompt.workflow !== this.workflowManager.activeWorkflow) return; - const output = this.nodeOutputs[detail.node]; - if (detail.merge && output) { - for (const k in detail.output ?? {}) { - const v = output[k]; - if (v instanceof Array) { - output[k] = v.concat(detail.output[k]); - } else { - output[k] = detail.output[k]; - } - } - } else { - this.nodeOutputs[detail.node] = detail.output; - } - const node = this.graph.getNodeById(detail.node); - if (node) { - if (node.onExecuted) - node.onExecuted(detail.output); - } - }); - - api.addEventListener("execution_start", ({ detail }) => { - this.runningNodeId = null; - this.lastExecutionError = null - this.graph._nodes.forEach((node) => { - if (node.onExecutionStart) - node.onExecutionStart() - }) - }); - - api.addEventListener("execution_error", ({ detail }) => { - this.lastExecutionError = detail; - const formattedError = this.#formatExecutionError(detail); - this.ui.dialog.show(formattedError); - this.canvas.draw(true, true); - }); - - api.addEventListener("b_preview", ({ detail }) => { - const id = this.runningNodeId - if (id == null) - return; - - const blob = detail - const blobUrl = URL.createObjectURL(blob) - this.nodePreviewImages[id] = [blobUrl] - }); - - api.init(); - } - - #addKeyboardHandler() { - window.addEventListener("keydown", (e) => { - this.shiftDown = e.shiftKey; - }); - window.addEventListener("keyup", (e) => { - this.shiftDown = e.shiftKey; - }); - } - - #addConfigureHandler() { - const app = this; - const configure = LGraph.prototype.configure; - // Flag that the graph is configuring to prevent nodes from running checks while its still loading - LGraph.prototype.configure = function () { - app.configuringGraph = true; - try { - return configure.apply(this, arguments); - } finally { - app.configuringGraph = false; - } - }; - } - - #addAfterConfigureHandler() { - const app = this; - const onConfigure = app.graph.onConfigure; - app.graph.onConfigure = function () { - // Fire callbacks before the onConfigure, this is used by widget inputs to setup the config - for (const node of app.graph._nodes) { - node.onGraphConfigured?.(); - } - - const r = onConfigure?.apply(this, arguments); - - // Fire after onConfigure, used by primitves to generate widget using input nodes config - for (const node of app.graph._nodes) { - node.onAfterGraphConfigured?.(); - } - - return r; - }; - } - - /** - * Loads all extensions from the API into the window in parallel - */ - async #loadExtensions() { - const extensions = await api.getExtensions(); - this.logging.addEntry("Comfy.App", "debug", { Extensions: extensions }); - - const extensionPromises = extensions.map(async ext => { - try { - await import(api.apiURL(ext)); - } catch (error) { - console.error("Error loading extension", ext, error); - } - }); - - await Promise.all(extensionPromises); - try { - this.menu.workflows.registerExtension(this); - } catch (error) { - console.error(error); - } - } - - async #migrateSettings() { - this.isNewUserSession = true; - // Store all current settings - const settings = Object.keys(this.ui.settings).reduce((p, n) => { - const v = localStorage[`Comfy.Settings.${n}`]; - if (v) { - try { - p[n] = JSON.parse(v); - } catch (error) {} - } - return p; - }, {}); - - await api.storeSettings(settings); - } - - async #setUser() { - const userConfig = await api.getUserConfig(); - this.storageLocation = userConfig.storage; - if (typeof userConfig.migrated == "boolean") { - // Single user mode migrated true/false for if the default user is created - if (!userConfig.migrated && this.storageLocation === "server") { - // Default user not created yet - await this.#migrateSettings(); - } - return; - } - - this.multiUserServer = true; - let user = localStorage["Comfy.userId"]; - const users = userConfig.users ?? {}; - if (!user || !users[user]) { - // This will rarely be hit so move the loading to on demand - const { UserSelectionScreen } = await import("./ui/userSelection.js"); - - this.ui.menuContainer.style.display = "none"; - const { userId, username, created } = await new UserSelectionScreen().show(users, user); - this.ui.menuContainer.style.display = ""; - - user = userId; - localStorage["Comfy.userName"] = username; - localStorage["Comfy.userId"] = user; - - if (created) { - api.user = user; - await this.#migrateSettings(); - } - } - - api.user = user; - - this.ui.settings.addSetting({ - id: "Comfy.SwitchUser", - name: "Switch User", - type: (name) => { - let currentUser = localStorage["Comfy.userName"]; - if (currentUser) { - currentUser = ` (${currentUser})`; - } - return $el("tr", [ - $el("td", [ - $el("label", { - textContent: name, - }), - ]), - $el("td", [ - $el("button", { - textContent: name + (currentUser ?? ""), - onclick: () => { - delete localStorage["Comfy.userId"]; - delete localStorage["Comfy.userName"]; - window.location.reload(); - }, - }), - ]), - ]); - }, - }); - } - - /** - * Set up the app on the page - */ - async setup() { - await this.#setUser(); - - // Create and mount the LiteGraph in the DOM - const mainCanvas = document.createElement("canvas") - mainCanvas.style.touchAction = "none" - const canvasEl = (this.canvasEl = Object.assign(mainCanvas, { id: "graph-canvas" })); - canvasEl.tabIndex = "1"; - document.body.append(canvasEl); - this.resizeCanvas(); - - await Promise.all([this.workflowManager.loadWorkflows(), this.ui.settings.load()]); - await this.#loadExtensions(); - - addDomClippingSetting(); - this.#addProcessMouseHandler(); - this.#addProcessKeyHandler(); - this.#addConfigureHandler(); - this.#addApiUpdateHandlers(); - this.#addRestoreWorkflowView(); - - this.graph = new LGraph(); - - this.#addAfterConfigureHandler(); - - this.canvas = new LGraphCanvas(canvasEl, this.graph); - this.ctx = canvasEl.getContext("2d"); - - LiteGraph.release_link_on_empty_shows_menu = true; - LiteGraph.alt_drag_do_clone_nodes = true; - - this.graph.start(); - - // Ensure the canvas fills the window - this.resizeCanvas(); - window.addEventListener("resize", () => this.resizeCanvas()); - const ro = new ResizeObserver(() => this.resizeCanvas()); - ro.observe(this.bodyTop); - ro.observe(this.bodyLeft); - ro.observe(this.bodyRight); - ro.observe(this.bodyBottom); - - await this.#invokeExtensionsAsync("init"); - await this.registerNodes(); - initWidgets(this); - - // Load previous workflow - let restored = false; - try { - const loadWorkflow = async (json) => { - if (json) { - const workflow = JSON.parse(json); - const workflowName = getStorageValue("Comfy.PreviousWorkflow"); - await this.loadGraphData(workflow, true, true, workflowName); - return true; - } - }; - const clientId = api.initialClientId ?? api.clientId; - restored = - (clientId && (await loadWorkflow(sessionStorage.getItem(`workflow:${clientId}`)))) || - (await loadWorkflow(localStorage.getItem("workflow"))); - } catch (err) { - console.error("Error loading previous workflow", err); - } - - // We failed to restore a workflow so load the default - if (!restored) { - await this.loadGraphData(); - } - - // Save current workflow automatically - setInterval(() => { - const workflow = JSON.stringify(this.graph.serialize()); - localStorage.setItem("workflow", workflow); - if (api.clientId) { - sessionStorage.setItem(`workflow:${api.clientId}`, workflow); - } - }, 1000); - - this.#addDrawNodeHandler(); - this.#addDrawGroupsHandler(); - this.#addDropHandler(); - this.#addCopyHandler(); - this.#addPasteHandler(); - this.#addKeyboardHandler(); - - await this.#invokeExtensionsAsync("setup"); - } - - resizeCanvas() { - // Limit minimal scale to 1, see https://github.com/comfyanonymous/ComfyUI/pull/845 - const scale = Math.max(window.devicePixelRatio, 1); - - // Clear fixed width and height while calculating rect so it uses 100% instead - this.canvasEl.height = this.canvasEl.width = ""; - const { width, height } = this.canvasEl.getBoundingClientRect(); - this.canvasEl.width = Math.round(width * scale); - this.canvasEl.height = Math.round(height * scale); - this.canvasEl.getContext("2d").scale(scale, scale); - this.canvas?.draw(true, true); - } - - /** - * Registers nodes with the graph - */ - async registerNodes() { - const app = this; - // Load node definitions from the backend - const defs = await api.getNodeDefs(); - await this.registerNodesFromDefs(defs); - await this.#invokeExtensionsAsync("registerCustomNodes"); - } - - getWidgetType(inputData, inputName) { - const type = inputData[0]; - - if (Array.isArray(type)) { - return "COMBO"; - } else if (`${type}:${inputName}` in this.widgets) { - return `${type}:${inputName}`; - } else if (type in this.widgets) { - return type; - } else { - return null; - } - } - - async registerNodeDef(nodeId, nodeData) { - const self = this; - const node = Object.assign( - function ComfyNode() { - var inputs = nodeData["input"]["required"]; - if (nodeData["input"]["optional"] != undefined) { - inputs = Object.assign({}, nodeData["input"]["required"], nodeData["input"]["optional"]); - } - const config = { minWidth: 1, minHeight: 1 }; - for (const inputName in inputs) { - const inputData = inputs[inputName]; - const type = inputData[0]; - - let widgetCreated = true; - const widgetType = self.getWidgetType(inputData, inputName); - if(widgetType) { - if(widgetType === "COMBO") { - Object.assign(config, self.widgets.COMBO(this, inputName, inputData, app) || {}); - } else { - Object.assign(config, self.widgets[widgetType](this, inputName, inputData, app) || {}); - } - } else { - // Node connection inputs - this.addInput(inputName, type); - widgetCreated = false; - } - - if(widgetCreated && inputData[1]?.forceInput && config?.widget) { - if (!config.widget.options) config.widget.options = {}; - config.widget.options.forceInput = inputData[1].forceInput; - } - if(widgetCreated && inputData[1]?.defaultInput && config?.widget) { - if (!config.widget.options) config.widget.options = {}; - config.widget.options.defaultInput = inputData[1].defaultInput; - } - } - - for (const o in nodeData["output"]) { - let output = nodeData["output"][o]; - if(output instanceof Array) output = "COMBO"; - const outputName = nodeData["output_name"][o] || output; - const outputShape = nodeData["output_is_list"][o] ? LiteGraph.GRID_SHAPE : LiteGraph.CIRCLE_SHAPE ; - this.addOutput(outputName, output, { shape: outputShape }); - } - - const s = this.computeSize(); - s[0] = Math.max(config.minWidth, s[0] * 1.5); - s[1] = Math.max(config.minHeight, s[1]); - this.size = s; - this.serialize_widgets = true; - - app.#invokeExtensionsAsync("nodeCreated", this); - }, - { - title: nodeData.display_name || nodeData.name, - comfyClass: nodeData.name, - nodeData - } - ); - node.prototype.comfyClass = nodeData.name; - - this.#addNodeContextMenuHandler(node); - this.#addDrawBackgroundHandler(node, app); - this.#addNodeKeyHandler(node); - - await this.#invokeExtensionsAsync("beforeRegisterNodeDef", node, nodeData); - LiteGraph.registerNodeType(nodeId, node); - node.category = nodeData.category; - } - - async registerNodesFromDefs(defs) { - await this.#invokeExtensionsAsync("addCustomNodeDefs", defs); - - // Generate list of known widgets - this.widgets = Object.assign( - {}, - ComfyWidgets, - ...(await this.#invokeExtensionsAsync("getCustomWidgets")).filter(Boolean) - ); - - // Register a node for each definition - for (const nodeId in defs) { - this.registerNodeDef(nodeId, defs[nodeId]); - } - } - - loadTemplateData(templateData) { - if (!templateData?.templates) { - return; - } - - const old = localStorage.getItem("litegrapheditor_clipboard"); - - var maxY, nodeBottom, node; - - for (const template of templateData.templates) { - if (!template?.data) { - continue; - } - - localStorage.setItem("litegrapheditor_clipboard", template.data); - app.canvas.pasteFromClipboard(); - - // Move mouse position down to paste the next template below - - maxY = false; - - for (const i in app.canvas.selected_nodes) { - node = app.canvas.selected_nodes[i]; - - nodeBottom = node.pos[1] + node.size[1]; - - if (maxY === false || nodeBottom > maxY) { - maxY = nodeBottom; - } - } - - app.canvas.graph_mouse[1] = maxY + 50; - } - - localStorage.setItem("litegrapheditor_clipboard", old); - } - - showMissingNodesError(missingNodeTypes, hasAddedNodes = true) { - let seenTypes = new Set(); - - this.ui.dialog.show( - $el("div.comfy-missing-nodes", [ - $el("span", { textContent: "When loading the graph, the following node types were not found: " }), - $el( - "ul", - Array.from(new Set(missingNodeTypes)).map((t) => { - let children = []; - if (typeof t === "object") { - if(seenTypes.has(t.type)) return null; - seenTypes.add(t.type); - children.push($el("span", { textContent: t.type })); - if (t.hint) { - children.push($el("span", { textContent: t.hint })); - } - if (t.action) { - children.push($el("button", { onclick: t.action.callback, textContent: t.action.text })); - } - } else { - if(seenTypes.has(t)) return null; - seenTypes.add(t); - children.push($el("span", { textContent: t })); - } - return $el("li", children); - }).filter(Boolean) - ), - ...(hasAddedNodes - ? [$el("span", { textContent: "Nodes that have failed to load will show as red on the graph." })] - : []), - ]) - ); - this.logging.addEntry("Comfy.App", "warn", { - MissingNodes: missingNodeTypes, - }); - } - - async changeWorkflow(callback, workflow = null) { - try { - this.workflowManager.activeWorkflow?.changeTracker?.store() - } catch (error) { - console.error(error); - } - await callback(); - try { - this.workflowManager.setWorkflow(workflow); - this.workflowManager.activeWorkflow?.track() - } catch (error) { - console.error(error); - } - } - - /** - * Populates the graph with the specified workflow data - * @param {*} graphData A serialized graph object - * @param { boolean } clean If the graph state, e.g. images, should be cleared - * @param { boolean } restore_view If the graph position should be restored - * @param { import("./workflows.js").ComfyWorkflowInstance | null } workflow The workflow - */ - async loadGraphData(graphData, clean = true, restore_view = true, workflow = null) { - if (clean !== false) { - this.clean(); - } - - let reset_invalid_values = false; - if (!graphData) { - graphData = defaultGraph; - reset_invalid_values = true; - } - - if (typeof structuredClone === "undefined") - { - graphData = JSON.parse(JSON.stringify(graphData)); - }else - { - graphData = structuredClone(graphData); - } - - try { - this.workflowManager.setWorkflow(workflow); - } catch (error) { - console.error(error); - } - - const missingNodeTypes = []; - await this.#invokeExtensionsAsync("beforeConfigureGraph", graphData, missingNodeTypes); - for (let n of graphData.nodes) { - // Patch T2IAdapterLoader to ControlNetLoader since they are the same node now - if (n.type == "T2IAdapterLoader") n.type = "ControlNetLoader"; - if (n.type == "ConditioningAverage ") n.type = "ConditioningAverage"; //typo fix - if (n.type == "SDV_img2vid_Conditioning") n.type = "SVD_img2vid_Conditioning"; //typo fix - - // Find missing node types - if (!(n.type in LiteGraph.registered_node_types)) { - missingNodeTypes.push(n.type); - n.type = sanitizeNodeName(n.type); - } - } - - try { - this.graph.configure(graphData); - if (restore_view && this.enableWorkflowViewRestore.value && graphData.extra?.ds) { - this.canvas.ds.offset = graphData.extra.ds.offset; - this.canvas.ds.scale = graphData.extra.ds.scale; - } - - try { - this.workflowManager.activeWorkflow?.track() - } catch (error) { - } - } catch (error) { - let errorHint = []; - // Try extracting filename to see if it was caused by an extension script - const filename = error.fileName || (error.stack || "").match(/(\/extensions\/.*\.js)/)?.[1]; - const pos = (filename || "").indexOf("/extensions/"); - if (pos > -1) { - errorHint.push( - $el("span", { textContent: "This may be due to the following script:" }), - $el("br"), - $el("span", { - style: { - fontWeight: "bold", - }, - textContent: filename.substring(pos), - }) - ); - } - - // Show dialog to let the user know something went wrong loading the data - this.ui.dialog.show( - $el("div", [ - $el("p", { textContent: "Loading aborted due to error reloading workflow data" }), - $el("pre", { - style: { padding: "5px", backgroundColor: "rgba(255,0,0,0.2)" }, - textContent: error.toString(), - }), - $el("pre", { - style: { - padding: "5px", - color: "#ccc", - fontSize: "10px", - maxHeight: "50vh", - overflow: "auto", - backgroundColor: "rgba(0,0,0,0.2)", - }, - textContent: error.stack || "No stacktrace available", - }), - ...errorHint, - ]).outerHTML - ); - - return; - } - - for (const node of this.graph._nodes) { - const size = node.computeSize(); - size[0] = Math.max(node.size[0], size[0]); - size[1] = Math.max(node.size[1], size[1]); - node.size = size; - - if (node.widgets) { - // If you break something in the backend and want to patch workflows in the frontend - // This is the place to do this - for (let widget of node.widgets) { - if (node.type == "KSampler" || node.type == "KSamplerAdvanced") { - if (widget.name == "sampler_name") { - if (widget.value.startsWith("sample_")) { - widget.value = widget.value.slice(7); - } - if (widget.value === "euler_pp" || widget.value === "euler_ancestral_pp") { - widget.value = widget.value.slice(0, -3); - for (let w of node.widgets) { - if (w.name == "cfg") { - w.value *= 2.0; - } - } - } - } - } - if (node.type == "KSampler" || node.type == "KSamplerAdvanced" || node.type == "PrimitiveNode") { - if (widget.name == "control_after_generate") { - if (widget.value === true) { - widget.value = "randomize"; - } else if (widget.value === false) { - widget.value = "fixed"; - } - } - } - if (reset_invalid_values) { - if (widget.type == "combo") { - if (!widget.options.values.includes(widget.value) && widget.options.values.length > 0) { - widget.value = widget.options.values[0]; - } - } - } - } - } - - this.#invokeExtensions("loadedGraphNode", node); - } - - if (missingNodeTypes.length) { - this.showMissingNodesError(missingNodeTypes); - } - await this.#invokeExtensionsAsync("afterConfigureGraph", missingNodeTypes); - requestAnimationFrame(() => { - this.graph.setDirtyCanvas(true, true); - }); - } - - /** - * Converts the current graph workflow for sending to the API - * @returns The workflow and node links - */ - async graphToPrompt(graph = this.graph, clean = true) { - for (const outerNode of graph.computeExecutionOrder(false)) { - if (outerNode.widgets) { - for (const widget of outerNode.widgets) { - // Allow widgets to run callbacks before a prompt has been queued - // e.g. random seed before every gen - widget.beforeQueued?.(); - } - } - - const innerNodes = outerNode.getInnerNodes ? outerNode.getInnerNodes() : [outerNode]; - for (const node of innerNodes) { - if (node.isVirtualNode) { - // Don't serialize frontend only nodes but let them make changes - if (node.applyToGraph) { - node.applyToGraph(); - } - } - } - } - - const workflow = graph.serialize(); - const output = {}; - // Process nodes in order of execution - for (const outerNode of graph.computeExecutionOrder(false)) { - const skipNode = outerNode.mode === 2 || outerNode.mode === 4; - const innerNodes = (!skipNode && outerNode.getInnerNodes) ? outerNode.getInnerNodes() : [outerNode]; - for (const node of innerNodes) { - if (node.isVirtualNode) { - continue; - } - - if (node.mode === 2 || node.mode === 4) { - // Don't serialize muted nodes - continue; - } - - const inputs = {}; - const widgets = node.widgets; - - // Store all widget values - if (widgets) { - for (const i in widgets) { - const widget = widgets[i]; - if (!widget.options || widget.options.serialize !== false) { - inputs[widget.name] = widget.serializeValue ? await widget.serializeValue(node, i) : widget.value; - } - } - } - - // Store all node links - for (let i in node.inputs) { - let parent = node.getInputNode(i); - if (parent) { - let link = node.getInputLink(i); - while (parent.mode === 4 || parent.isVirtualNode) { - let found = false; - if (parent.isVirtualNode) { - link = parent.getInputLink(link.origin_slot); - if (link) { - parent = parent.getInputNode(link.target_slot); - if (parent) { - found = true; - } - } - } else if (link && parent.mode === 4) { - let all_inputs = [link.origin_slot]; - if (parent.inputs) { - all_inputs = all_inputs.concat(Object.keys(parent.inputs)) - for (let parent_input in all_inputs) { - parent_input = all_inputs[parent_input]; - if (parent.inputs[parent_input]?.type === node.inputs[i].type) { - link = parent.getInputLink(parent_input); - if (link) { - parent = parent.getInputNode(parent_input); - } - found = true; - break; - } - } - } - } - - if (!found) { - break; - } - } - - if (link) { - if (parent?.updateLink) { - link = parent.updateLink(link); - } - if (link) { - inputs[node.inputs[i].name] = [String(link.origin_id), parseInt(link.origin_slot)]; - } - } - } - } - - let node_data = { - inputs, - class_type: node.comfyClass, - }; - - if (this.ui.settings.getSettingValue("Comfy.DevMode")) { - // Ignored by the backend. - node_data["_meta"] = { - title: node.title, - } - } - - output[String(node.id)] = node_data; - } - } - - // Remove inputs connected to removed nodes - if(clean) { - for (const o in output) { - for (const i in output[o].inputs) { - if (Array.isArray(output[o].inputs[i]) - && output[o].inputs[i].length === 2 - && !output[output[o].inputs[i][0]]) { - delete output[o].inputs[i]; - } - } - } - } - - return { workflow, output }; - } - - #formatPromptError(error) { - if (error == null) { - return "(unknown error)" - } - else if (typeof error === "string") { - return error; - } - else if (error.stack && error.message) { - return error.toString() - } - else if (error.response) { - let message = error.response.error.message; - if (error.response.error.details) - message += ": " + error.response.error.details; - for (const [nodeID, nodeError] of Object.entries(error.response.node_errors)) { - message += "\n" + nodeError.class_type + ":" - for (const errorReason of nodeError.errors) { - message += "\n - " + errorReason.message + ": " + errorReason.details - } - } - return message - } - return "(unknown error)" - } - - #formatExecutionError(error) { - if (error == null) { - return "(unknown error)" - } - - const traceback = error.traceback.join("") - const nodeId = error.node_id - const nodeType = error.node_type - - return `Error occurred when executing ${nodeType}:\n\n${error.exception_message}\n\n${traceback}` - } - - async queuePrompt(number, batchCount = 1) { - this.#queueItems.push({ number, batchCount }); - - // Only have one action process the items so each one gets a unique seed correctly - if (this.#processingQueue) { - return; - } - - this.#processingQueue = true; - this.lastNodeErrors = null; - - try { - while (this.#queueItems.length) { - ({ number, batchCount } = this.#queueItems.pop()); - - for (let i = 0; i < batchCount; i++) { - const p = await this.graphToPrompt(); - - try { - const res = await api.queuePrompt(number, p); - this.lastNodeErrors = res.node_errors; - if (this.lastNodeErrors.length > 0) { - this.canvas.draw(true, true); - } else { - try { - this.workflowManager.storePrompt({ - id: res.prompt_id, - nodes: Object.keys(p.output) - }); - } catch (error) { - } - } - } catch (error) { - const formattedError = this.#formatPromptError(error) - this.ui.dialog.show(formattedError); - if (error.response) { - this.lastNodeErrors = error.response.node_errors; - this.canvas.draw(true, true); - } - break; - } - - for (const n of p.workflow.nodes) { - const node = graph.getNodeById(n.id); - if (node.widgets) { - for (const widget of node.widgets) { - // Allow widgets to run callbacks after a prompt has been queued - // e.g. random seed after every gen - if (widget.afterQueued) { - widget.afterQueued(); - } - } - } - } - - this.canvas.draw(true, true); - await this.ui.queue.update(); - } - } - } finally { - this.#processingQueue = false; - } - api.dispatchEvent(new CustomEvent("promptQueued", { detail: { number, batchCount } })); - return !this.lastNodeErrors; - } - - showErrorOnFileLoad(file) { - this.ui.dialog.show( - $el("div", [ - $el("p", {textContent: `Unable to find workflow in ${file.name}`}) - ]).outerHTML - ); - } - - /** - * Loads workflow data from the specified file - * @param {File} file - */ - async handleFile(file) { - const removeExt = f => { - if(!f) return f; - const p = f.lastIndexOf("."); - if(p === -1) return f; - return f.substring(0, p); - }; - - const fileName = removeExt(file.name); - if (file.type === "image/png") { - const pngInfo = await getPngMetadata(file); - if (pngInfo?.workflow) { - await this.loadGraphData(JSON.parse(pngInfo.workflow), true, true, fileName); - } else if (pngInfo?.prompt) { - this.loadApiJson(JSON.parse(pngInfo.prompt), fileName); - } else if (pngInfo?.parameters) { - this.changeWorkflow(() => { - importA1111(this.graph, pngInfo.parameters); - }, fileName) - } else { - this.showErrorOnFileLoad(file); - } - } else if (file.type === "image/webp") { - const pngInfo = await getWebpMetadata(file); - // Support loading workflows from that webp custom node. - const workflow = pngInfo?.workflow || pngInfo?.Workflow; - const prompt = pngInfo?.prompt || pngInfo?.Prompt; - - if (workflow) { - this.loadGraphData(JSON.parse(workflow), true, true, fileName); - } else if (prompt) { - this.loadApiJson(JSON.parse(prompt), fileName); - } else { - this.showErrorOnFileLoad(file); - } - } else if (file.type === "audio/flac" || file.type === "audio/x-flac") { - const pngInfo = await getFlacMetadata(file); - // Support loading workflows from that webp custom node. - const workflow = pngInfo?.workflow; - const prompt = pngInfo?.prompt; - - if (workflow) { - this.loadGraphData(JSON.parse(workflow), true, true, fileName); - } else if (prompt) { - this.loadApiJson(JSON.parse(prompt), fileName); - } else { - this.showErrorOnFileLoad(file); - } - } else if (file.type === "application/json" || file.name?.endsWith(".json")) { - const reader = new FileReader(); - reader.onload = async () => { - const jsonContent = JSON.parse(reader.result); - if (jsonContent?.templates) { - this.loadTemplateData(jsonContent); - } else if(this.isApiJson(jsonContent)) { - this.loadApiJson(jsonContent, fileName); - } else { - await this.loadGraphData(jsonContent, true, true, fileName); - } - }; - reader.readAsText(file); - } else if (file.name?.endsWith(".latent") || file.name?.endsWith(".safetensors")) { - const info = await getLatentMetadata(file); - if (info.workflow) { - await this.loadGraphData(JSON.parse(info.workflow), true, true, fileName); - } else if (info.prompt) { - this.loadApiJson(JSON.parse(info.prompt)); - } else { - this.showErrorOnFileLoad(file); - } - } else { - this.showErrorOnFileLoad(file); - } - } - - isApiJson(data) { - return Object.values(data).every((v) => v.class_type); - } - - loadApiJson(apiData, fileName) { - const missingNodeTypes = Object.values(apiData).filter((n) => !LiteGraph.registered_node_types[n.class_type]); - if (missingNodeTypes.length) { - this.showMissingNodesError(missingNodeTypes.map(t => t.class_type), false); - return; - } - - const ids = Object.keys(apiData); - app.graph.clear(); - for (const id of ids) { - const data = apiData[id]; - const node = LiteGraph.createNode(data.class_type); - node.id = isNaN(+id) ? id : +id; - node.title = data._meta?.title ?? node.title - app.graph.add(node); - } - - this.changeWorkflow(() => { - for (const id of ids) { - const data = apiData[id]; - const node = app.graph.getNodeById(id); - for (const input in data.inputs ?? {}) { - const value = data.inputs[input]; - if (value instanceof Array) { - const [fromId, fromSlot] = value; - const fromNode = app.graph.getNodeById(fromId); - let toSlot = node.inputs?.findIndex((inp) => inp.name === input); - if (toSlot == null || toSlot === -1) { - try { - // Target has no matching input, most likely a converted widget - const widget = node.widgets?.find((w) => w.name === input); - if (widget && node.convertWidgetToInput?.(widget)) { - toSlot = node.inputs?.length - 1; - } - } catch (error) {} - } - if (toSlot != null || toSlot !== -1) { - fromNode.connect(fromSlot, node, toSlot); - } - } else { - const widget = node.widgets?.find((w) => w.name === input); - if (widget) { - widget.value = value; - widget.callback?.(value); - } - } - } - } - app.graph.arrange(); - }, fileName); - } - - /** - * Registers a Comfy web extension with the app - * @param {ComfyExtension} extension - */ - registerExtension(extension) { - if (!extension.name) { - throw new Error("Extensions must have a 'name' property."); - } - if (this.extensions.find((ext) => ext.name === extension.name)) { - throw new Error(`Extension named '${extension.name}' already registered.`); - } - this.extensions.push(extension); - } - - /** - * Refresh combo list on whole nodes - */ - async refreshComboInNodes() { - const defs = await api.getNodeDefs(); - - for (const nodeId in defs) { - this.registerNodeDef(nodeId, defs[nodeId]); - } - - for(let nodeNum in this.graph._nodes) { - const node = this.graph._nodes[nodeNum]; - const def = defs[node.type]; - - // Allow primitive nodes to handle refresh - node.refreshComboInNode?.(defs); - - if(!def) - continue; - - for(const widgetNum in node.widgets) { - const widget = node.widgets[widgetNum] - if(widget.type == "combo" && def["input"]["required"][widget.name] !== undefined) { - widget.options.values = def["input"]["required"][widget.name][0]; - - if(widget.name != 'image' && !widget.options.values.includes(widget.value)) { - widget.value = widget.options.values[0]; - widget.callback(widget.value); - } - } - } - } - - await this.#invokeExtensionsAsync("refreshComboInNodes", defs); - } - - resetView() { - app.canvas.ds.scale = 1; - app.canvas.ds.offset = [0, 0] - app.graph.setDirtyCanvas(true, true); - } - - /** - * Clean current state - */ - clean() { - this.nodeOutputs = {}; - this.nodePreviewImages = {} - this.lastNodeErrors = null; - this.lastExecutionError = null; - this.runningNodeId = null; - } -} - -export const app = new ComfyApp(); +// Shim for scripts\app.ts +export const ANIM_PREVIEW_WIDGET = window.comfyAPI.app.ANIM_PREVIEW_WIDGET; +export const ComfyApp = window.comfyAPI.app.ComfyApp; +export const app = window.comfyAPI.app.app; diff --git a/web/scripts/changeTracker.js b/web/scripts/changeTracker.js index d7798dbe9..2844f25c3 100644 --- a/web/scripts/changeTracker.js +++ b/web/scripts/changeTracker.js @@ -1,255 +1,2 @@ -// @ts-check - -import { api } from "./api.js"; -import { clone } from "./utils.js"; - -export class ChangeTracker { - static MAX_HISTORY = 50; - #app; - undo = []; - redo = []; - activeState = null; - isOurLoad = false; - /** @type { import("./workflows").ComfyWorkflow | null } */ - workflow; - - ds; - nodeOutputs; - - get app() { - return this.#app ?? this.workflow.manager.app; - } - - constructor(workflow) { - this.workflow = workflow; - } - - #setApp(app) { - this.#app = app; - } - - store() { - this.ds = { scale: this.app.canvas.ds.scale, offset: [...this.app.canvas.ds.offset] }; - } - - restore() { - if (this.ds) { - this.app.canvas.ds.scale = this.ds.scale; - this.app.canvas.ds.offset = this.ds.offset; - } - if (this.nodeOutputs) { - this.app.nodeOutputs = this.nodeOutputs; - } - } - - checkState() { - if (!this.app.graph) return; - - const currentState = this.app.graph.serialize(); - if (!this.activeState) { - this.activeState = clone(currentState); - return; - } - if (!ChangeTracker.graphEqual(this.activeState, currentState)) { - this.undo.push(this.activeState); - if (this.undo.length > ChangeTracker.MAX_HISTORY) { - this.undo.shift(); - } - this.activeState = clone(currentState); - this.redo.length = 0; - this.workflow.unsaved = true; - api.dispatchEvent(new CustomEvent("graphChanged", { detail: this.activeState })); - } - } - - async updateState(source, target) { - const prevState = source.pop(); - if (prevState) { - target.push(this.activeState); - this.isOurLoad = true; - await this.app.loadGraphData(prevState, false, false, this.workflow); - this.activeState = prevState; - } - } - - async undoRedo(e) { - if (e.ctrlKey || e.metaKey) { - if (e.key === "y") { - this.updateState(this.redo, this.undo); - return true; - } else if (e.key === "z") { - this.updateState(this.undo, this.redo); - return true; - } - } - } - - /** @param { import("./app.js").ComfyApp } app */ - static init(app) { - const changeTracker = () => app.workflowManager.activeWorkflow?.changeTracker ?? globalTracker; - globalTracker.#setApp(app); - - const loadGraphData = app.loadGraphData; - app.loadGraphData = async function () { - const v = await loadGraphData.apply(this, arguments); - const ct = changeTracker(); - if (ct.isOurLoad) { - ct.isOurLoad = false; - } else { - ct.checkState(); - } - return v; - }; - - let keyIgnored = false; - window.addEventListener( - "keydown", - (e) => { - const activeEl = document.activeElement; - requestAnimationFrame(async () => { - let bindInputEl; - // If we are auto queue in change mode then we do want to trigger on inputs - if (!app.ui.autoQueueEnabled || app.ui.autoQueueMode === "instant") { - if (activeEl?.tagName === "INPUT" || activeEl?.["type"] === "textarea") { - // Ignore events on inputs, they have their native history - return; - } - bindInputEl = activeEl; - } - - keyIgnored = e.key === "Control" || e.key === "Shift" || e.key === "Alt" || e.key === "Meta"; - if (keyIgnored) return; - - // Check if this is a ctrl+z ctrl+y - if (await changeTracker().undoRedo(e)) return; - - // If our active element is some type of input then handle changes after they're done - if (ChangeTracker.bindInput(bindInputEl)) return; - changeTracker().checkState(); - }); - }, - true - ); - - window.addEventListener("keyup", (e) => { - if (keyIgnored) { - keyIgnored = false; - changeTracker().checkState(); - } - }); - - // Handle clicking DOM elements (e.g. widgets) - window.addEventListener("mouseup", () => { - changeTracker().checkState(); - }); - - // Handle prompt queue event for dynamic widget changes - api.addEventListener("promptQueued", () => { - changeTracker().checkState(); - }); - - // Handle litegraph clicks - const processMouseUp = LGraphCanvas.prototype.processMouseUp; - LGraphCanvas.prototype.processMouseUp = function (e) { - const v = processMouseUp.apply(this, arguments); - changeTracker().checkState(); - return v; - }; - const processMouseDown = LGraphCanvas.prototype.processMouseDown; - LGraphCanvas.prototype.processMouseDown = function (e) { - const v = processMouseDown.apply(this, arguments); - changeTracker().checkState(); - return v; - }; - - // Handle litegraph context menu for COMBO widgets - const close = LiteGraph.ContextMenu.prototype.close; - LiteGraph.ContextMenu.prototype.close = function (e) { - const v = close.apply(this, arguments); - changeTracker().checkState(); - return v; - }; - - // Detects nodes being added via the node search dialog - const onNodeAdded = LiteGraph.LGraph.prototype.onNodeAdded; - LiteGraph.LGraph.prototype.onNodeAdded = function () { - const v = onNodeAdded?.apply(this, arguments); - if (!app?.configuringGraph) { - const ct = changeTracker(); - if (!ct.isOurLoad) { - ct.checkState(); - } - } - return v; - }; - - // Store node outputs - api.addEventListener("executed", ({ detail }) => { - const prompt = app.workflowManager.queuedPrompts[detail.prompt_id]; - if (!prompt?.workflow) return; - const nodeOutputs = (prompt.workflow.changeTracker.nodeOutputs ??= {}); - const output = nodeOutputs[detail.node]; - if (detail.merge && output) { - for (const k in detail.output ?? {}) { - const v = output[k]; - if (v instanceof Array) { - output[k] = v.concat(detail.output[k]); - } else { - output[k] = detail.output[k]; - } - } - } else { - nodeOutputs[detail.node] = detail.output; - } - }); - } - - static bindInput(app, activeEl) { - if (activeEl && activeEl.tagName !== "CANVAS" && activeEl.tagName !== "BODY") { - for (const evt of ["change", "input", "blur"]) { - if (`on${evt}` in activeEl) { - const listener = () => { - app.workflowManager.activeWorkflow.changeTracker.checkState(); - activeEl.removeEventListener(evt, listener); - }; - activeEl.addEventListener(evt, listener); - return true; - } - } - } - } - - static graphEqual(a, b, path = "") { - if (a === b) return true; - - if (typeof a == "object" && a && typeof b == "object" && b) { - const keys = Object.getOwnPropertyNames(a); - - if (keys.length != Object.getOwnPropertyNames(b).length) { - return false; - } - - for (const key of keys) { - let av = a[key]; - let bv = b[key]; - if (!path && key === "nodes") { - // Nodes need to be sorted as the order changes when selecting nodes - av = [...av].sort((a, b) => a.id - b.id); - bv = [...bv].sort((a, b) => a.id - b.id); - } else if (path === "extra.ds") { - // Ignore view changes - continue; - } - if (!ChangeTracker.graphEqual(av, bv, path + (path ? "." : "") + key)) { - return false; - } - } - - return true; - } - - return false; - } -} - -const globalTracker = new ChangeTracker({}); \ No newline at end of file +// Shim for scripts\changeTracker.ts +export const ChangeTracker = window.comfyAPI.changeTracker.ChangeTracker; diff --git a/web/scripts/defaultGraph.js b/web/scripts/defaultGraph.js index 9b3cb4a7e..13a187af5 100644 --- a/web/scripts/defaultGraph.js +++ b/web/scripts/defaultGraph.js @@ -1,119 +1,2 @@ -export const defaultGraph = { - last_node_id: 9, - last_link_id: 9, - nodes: [ - { - id: 7, - type: "CLIPTextEncode", - pos: [413, 389], - size: { 0: 425.27801513671875, 1: 180.6060791015625 }, - flags: {}, - order: 3, - mode: 0, - inputs: [{ name: "clip", type: "CLIP", link: 5 }], - outputs: [{ name: "CONDITIONING", type: "CONDITIONING", links: [6], slot_index: 0 }], - properties: {}, - widgets_values: ["text, watermark"], - }, - { - id: 6, - type: "CLIPTextEncode", - pos: [415, 186], - size: { 0: 422.84503173828125, 1: 164.31304931640625 }, - flags: {}, - order: 2, - mode: 0, - inputs: [{ name: "clip", type: "CLIP", link: 3 }], - outputs: [{ name: "CONDITIONING", type: "CONDITIONING", links: [4], slot_index: 0 }], - properties: {}, - widgets_values: ["beautiful scenery nature glass bottle landscape, , purple galaxy bottle,"], - }, - { - id: 5, - type: "EmptyLatentImage", - pos: [473, 609], - size: { 0: 315, 1: 106 }, - flags: {}, - order: 1, - mode: 0, - outputs: [{ name: "LATENT", type: "LATENT", links: [2], slot_index: 0 }], - properties: {}, - widgets_values: [512, 512, 1], - }, - { - id: 3, - type: "KSampler", - pos: [863, 186], - size: { 0: 315, 1: 262 }, - flags: {}, - order: 4, - mode: 0, - inputs: [ - { name: "model", type: "MODEL", link: 1 }, - { name: "positive", type: "CONDITIONING", link: 4 }, - { name: "negative", type: "CONDITIONING", link: 6 }, - { name: "latent_image", type: "LATENT", link: 2 }, - ], - outputs: [{ name: "LATENT", type: "LATENT", links: [7], slot_index: 0 }], - properties: {}, - widgets_values: [156680208700286, true, 20, 8, "euler", "normal", 1], - }, - { - id: 8, - type: "VAEDecode", - pos: [1209, 188], - size: { 0: 210, 1: 46 }, - flags: {}, - order: 5, - mode: 0, - inputs: [ - { name: "samples", type: "LATENT", link: 7 }, - { name: "vae", type: "VAE", link: 8 }, - ], - outputs: [{ name: "IMAGE", type: "IMAGE", links: [9], slot_index: 0 }], - properties: {}, - }, - { - id: 9, - type: "SaveImage", - pos: [1451, 189], - size: { 0: 210, 1: 26 }, - flags: {}, - order: 6, - mode: 0, - inputs: [{ name: "images", type: "IMAGE", link: 9 }], - properties: {}, - }, - { - id: 4, - type: "CheckpointLoaderSimple", - pos: [26, 474], - size: { 0: 315, 1: 98 }, - flags: {}, - order: 0, - mode: 0, - outputs: [ - { name: "MODEL", type: "MODEL", links: [1], slot_index: 0 }, - { name: "CLIP", type: "CLIP", links: [3, 5], slot_index: 1 }, - { name: "VAE", type: "VAE", links: [8], slot_index: 2 }, - ], - properties: {}, - widgets_values: ["v1-5-pruned-emaonly.ckpt"], - }, - ], - links: [ - [1, 4, 0, 3, 0, "MODEL"], - [2, 5, 0, 3, 3, "LATENT"], - [3, 4, 1, 6, 0, "CLIP"], - [4, 6, 0, 3, 1, "CONDITIONING"], - [5, 4, 1, 7, 0, "CLIP"], - [6, 7, 0, 3, 2, "CONDITIONING"], - [7, 3, 0, 8, 0, "LATENT"], - [8, 4, 2, 8, 1, "VAE"], - [9, 8, 0, 9, 0, "IMAGE"], - ], - groups: [], - config: {}, - extra: {}, - version: 0.4, -}; +// Shim for scripts\defaultGraph.ts +export const defaultGraph = window.comfyAPI.defaultGraph.defaultGraph; diff --git a/web/scripts/domWidget.js b/web/scripts/domWidget.js index d97122f9d..6156a2f4f 100644 --- a/web/scripts/domWidget.js +++ b/web/scripts/domWidget.js @@ -1,329 +1,2 @@ -import { app, ANIM_PREVIEW_WIDGET } from "./app.js"; - -const SIZE = Symbol(); - -function intersect(a, b) { - const x = Math.max(a.x, b.x); - const num1 = Math.min(a.x + a.width, b.x + b.width); - const y = Math.max(a.y, b.y); - const num2 = Math.min(a.y + a.height, b.y + b.height); - if (num1 >= x && num2 >= y) return [x, y, num1 - x, num2 - y]; - else return null; -} - -function getClipPath(node, element) { - const selectedNode = Object.values(app.canvas.selected_nodes)[0]; - if (selectedNode && selectedNode !== node) { - const elRect = element.getBoundingClientRect(); - const MARGIN = 7; - const scale = app.canvas.ds.scale; - - const bounding = selectedNode.getBounding(); - const intersection = intersect( - { x: elRect.x / scale, y: elRect.y / scale, width: elRect.width / scale, height: elRect.height / scale }, - { - x: selectedNode.pos[0] + app.canvas.ds.offset[0] - MARGIN, - y: selectedNode.pos[1] + app.canvas.ds.offset[1] - LiteGraph.NODE_TITLE_HEIGHT - MARGIN, - width: bounding[2] + MARGIN + MARGIN, - height: bounding[3] + MARGIN + MARGIN, - } - ); - - if (!intersection) { - return ""; - } - - const widgetRect = element.getBoundingClientRect(); - const clipX = elRect.left + intersection[0] - widgetRect.x / scale + "px"; - const clipY = elRect.top + intersection[1] - widgetRect.y / scale + "px"; - const clipWidth = intersection[2] + "px"; - const clipHeight = intersection[3] + "px"; - const path = `polygon(0% 0%, 0% 100%, ${clipX} 100%, ${clipX} ${clipY}, calc(${clipX} + ${clipWidth}) ${clipY}, calc(${clipX} + ${clipWidth}) calc(${clipY} + ${clipHeight}), ${clipX} calc(${clipY} + ${clipHeight}), ${clipX} 100%, 100% 100%, 100% 0%)`; - return path; - } - return ""; -} - -function computeSize(size) { - if (this.widgets?.[0]?.last_y == null) return; - - let y = this.widgets[0].last_y; - let freeSpace = size[1] - y; - - let widgetHeight = 0; - let dom = []; - for (const w of this.widgets) { - if (w.type === "converted-widget") { - // Ignore - delete w.computedHeight; - } else if (w.computeSize) { - widgetHeight += w.computeSize()[1] + 4; - } else if (w.element) { - // Extract DOM widget size info - const styles = getComputedStyle(w.element); - let minHeight = w.options.getMinHeight?.() ?? parseInt(styles.getPropertyValue("--comfy-widget-min-height")); - let maxHeight = w.options.getMaxHeight?.() ?? parseInt(styles.getPropertyValue("--comfy-widget-max-height")); - - let prefHeight = w.options.getHeight?.() ?? styles.getPropertyValue("--comfy-widget-height"); - if (prefHeight.endsWith?.("%")) { - prefHeight = size[1] * (parseFloat(prefHeight.substring(0, prefHeight.length - 1)) / 100); - } else { - prefHeight = parseInt(prefHeight); - if (isNaN(minHeight)) { - minHeight = prefHeight; - } - } - if (isNaN(minHeight)) { - minHeight = 50; - } - if (!isNaN(maxHeight)) { - if (!isNaN(prefHeight)) { - prefHeight = Math.min(prefHeight, maxHeight); - } else { - prefHeight = maxHeight; - } - } - dom.push({ - minHeight, - prefHeight, - w, - }); - } else { - widgetHeight += LiteGraph.NODE_WIDGET_HEIGHT + 4; - } - } - - freeSpace -= widgetHeight; - - // Calculate sizes with all widgets at their min height - const prefGrow = []; // Nodes that want to grow to their prefd size - const canGrow = []; // Nodes that can grow to auto size - let growBy = 0; - for (const d of dom) { - freeSpace -= d.minHeight; - if (isNaN(d.prefHeight)) { - canGrow.push(d); - d.w.computedHeight = d.minHeight; - } else { - const diff = d.prefHeight - d.minHeight; - if (diff > 0) { - prefGrow.push(d); - growBy += diff; - d.diff = diff; - } else { - d.w.computedHeight = d.minHeight; - } - } - } - - if (this.imgs && !this.widgets.find((w) => w.name === ANIM_PREVIEW_WIDGET)) { - // Allocate space for image - freeSpace -= 220; - } - - this.freeWidgetSpace = freeSpace; - - if (freeSpace < 0) { - // Not enough space for all widgets so we need to grow - size[1] -= freeSpace; - this.graph.setDirtyCanvas(true); - } else { - // Share the space between each - const growDiff = freeSpace - growBy; - if (growDiff > 0) { - // All pref sizes can be fulfilled - freeSpace = growDiff; - for (const d of prefGrow) { - d.w.computedHeight = d.prefHeight; - } - } else { - // We need to grow evenly - const shared = -growDiff / prefGrow.length; - for (const d of prefGrow) { - d.w.computedHeight = d.prefHeight - shared; - } - freeSpace = 0; - } - - if (freeSpace > 0 && canGrow.length) { - // Grow any that are auto height - const shared = freeSpace / canGrow.length; - for (const d of canGrow) { - d.w.computedHeight += shared; - } - } - } - - // Position each of the widgets - for (const w of this.widgets) { - w.y = y; - if (w.computedHeight) { - y += w.computedHeight; - } else if (w.computeSize) { - y += w.computeSize()[1] + 4; - } else { - y += LiteGraph.NODE_WIDGET_HEIGHT + 4; - } - } -} - -// Override the compute visible nodes function to allow us to hide/show DOM elements when the node goes offscreen -const elementWidgets = new Set(); -const computeVisibleNodes = LGraphCanvas.prototype.computeVisibleNodes; -LGraphCanvas.prototype.computeVisibleNodes = function () { - const visibleNodes = computeVisibleNodes.apply(this, arguments); - for (const node of app.graph._nodes) { - if (elementWidgets.has(node)) { - const hidden = visibleNodes.indexOf(node) === -1; - for (const w of node.widgets) { - if (w.element) { - w.element.hidden = hidden; - w.element.style.display = hidden ? "none" : undefined; - if (hidden) { - w.options.onHide?.(w); - } - } - } - } - } - - return visibleNodes; -}; - -let enableDomClipping = true; - -export function addDomClippingSetting() { - app.ui.settings.addSetting({ - id: "Comfy.DOMClippingEnabled", - name: "Enable DOM element clipping (enabling may reduce performance)", - type: "boolean", - defaultValue: enableDomClipping, - onChange(value) { - enableDomClipping = !!value; - }, - }); -} - -LGraphNode.prototype.addDOMWidget = function (name, type, element, options) { - options = { hideOnZoom: true, selectOn: ["focus", "click"], ...options }; - - if (!element.parentElement) { - document.body.append(element); - } - element.hidden = true; - element.style.display = "none"; - - let mouseDownHandler; - if (element.blur) { - mouseDownHandler = (event) => { - if (!element.contains(event.target)) { - element.blur(); - } - }; - document.addEventListener("mousedown", mouseDownHandler); - } - - const widget = { - type, - name, - get value() { - return options.getValue?.() ?? undefined; - }, - set value(v) { - options.setValue?.(v); - widget.callback?.(widget.value); - }, - draw: function (ctx, node, widgetWidth, y, widgetHeight) { - if (widget.computedHeight == null) { - computeSize.call(node, node.size); - } - - const hidden = - node.flags?.collapsed || - (!!options.hideOnZoom && app.canvas.ds.scale < 0.5) || - widget.computedHeight <= 0 || - widget.type === "converted-widget"|| - widget.type === "hidden"; - element.hidden = hidden; - element.style.display = hidden ? "none" : null; - if (hidden) { - widget.options.onHide?.(widget); - return; - } - - const margin = 10; - const elRect = ctx.canvas.getBoundingClientRect(); - const transform = new DOMMatrix() - .scaleSelf(elRect.width / ctx.canvas.width, elRect.height / ctx.canvas.height) - .multiplySelf(ctx.getTransform()) - .translateSelf(margin, margin + y ); - - const scale = new DOMMatrix().scaleSelf(transform.a, transform.d); - - Object.assign(element.style, { - transformOrigin: "0 0", - transform: scale, - left: `${transform.a + transform.e + elRect.left}px`, - top: `${transform.d + transform.f + elRect.top}px`, - width: `${widgetWidth - margin * 2}px`, - height: `${(widget.computedHeight ?? 50) - margin * 2}px`, - position: "absolute", - zIndex: app.graph._nodes.indexOf(node), - }); - - if (enableDomClipping) { - element.style.clipPath = getClipPath(node, element); - element.style.willChange = "clip-path"; - } - - this.options.onDraw?.(widget); - }, - element, - options, - onRemove() { - if (mouseDownHandler) { - document.removeEventListener("mousedown", mouseDownHandler); - } - element.remove(); - }, - }; - - for (const evt of options.selectOn) { - element.addEventListener(evt, () => { - app.canvas.selectNode(this); - app.canvas.bringToFront(this); - }); - } - - this.addCustomWidget(widget); - elementWidgets.add(this); - - const collapse = this.collapse; - this.collapse = function() { - collapse.apply(this, arguments); - if(this.flags?.collapsed) { - element.hidden = true; - element.style.display = "none"; - } - } - - const onRemoved = this.onRemoved; - this.onRemoved = function () { - element.remove(); - elementWidgets.delete(this); - onRemoved?.apply(this, arguments); - }; - - if (!this[SIZE]) { - this[SIZE] = true; - const onResize = this.onResize; - this.onResize = function (size) { - options.beforeResize?.call(widget, this); - computeSize.call(this, size); - onResize?.apply(this, arguments); - options.afterResize?.call(widget, this); - }; - } - - return widget; -}; +// Shim for scripts\domWidget.ts +export const addDomClippingSetting = window.comfyAPI.domWidget.addDomClippingSetting; diff --git a/web/scripts/logging.js b/web/scripts/logging.js index 875dd970b..e5486616e 100644 --- a/web/scripts/logging.js +++ b/web/scripts/logging.js @@ -1,370 +1,2 @@ -import { $el, ComfyDialog } from "./ui.js"; -import { api } from "./api.js"; - -$el("style", { - textContent: ` - .comfy-logging-logs { - display: grid; - color: var(--fg-color); - white-space: pre-wrap; - } - .comfy-logging-log { - display: contents; - } - .comfy-logging-title { - background: var(--tr-even-bg-color); - font-weight: bold; - margin-bottom: 5px; - text-align: center; - } - .comfy-logging-log div { - background: var(--row-bg); - padding: 5px; - } - `, - parent: document.body, -}); - -// Stringify function supporting max depth and removal of circular references -// https://stackoverflow.com/a/57193345 -function stringify(val, depth, replacer, space, onGetObjID) { - depth = isNaN(+depth) ? 1 : depth; - var recursMap = new WeakMap(); - function _build(val, depth, o, a, r) { - // (JSON.stringify() has it's own rules, which we respect here by using it for property iteration) - return !val || typeof val != "object" - ? val - : ((r = recursMap.has(val)), - recursMap.set(val, true), - (a = Array.isArray(val)), - r - ? (o = (onGetObjID && onGetObjID(val)) || null) - : JSON.stringify(val, function (k, v) { - if (a || depth > 0) { - if (replacer) v = replacer(k, v); - if (!k) return (a = Array.isArray(v)), (val = v); - !o && (o = a ? [] : {}); - o[k] = _build(v, a ? depth : depth - 1); - } - }), - o === void 0 ? (a ? [] : {}) : o); - } - return JSON.stringify(_build(val, depth), null, space); -} - -const jsonReplacer = (k, v, ui) => { - if (v instanceof Array && v.length === 1) { - v = v[0]; - } - if (v instanceof Date) { - v = v.toISOString(); - if (ui) { - v = v.split("T")[1]; - } - } - if (v instanceof Error) { - let err = ""; - if (v.name) err += v.name + "\n"; - if (v.message) err += v.message + "\n"; - if (v.stack) err += v.stack + "\n"; - if (!err) { - err = v.toString(); - } - v = err; - } - return v; -}; - -const fileInput = $el("input", { - type: "file", - accept: ".json", - style: { display: "none" }, - parent: document.body, -}); - -class ComfyLoggingDialog extends ComfyDialog { - constructor(logging) { - super(); - this.logging = logging; - } - - clear() { - this.logging.clear(); - this.show(); - } - - export() { - const blob = new Blob([stringify([...this.logging.entries], 20, jsonReplacer, "\t")], { - type: "application/json", - }); - const url = URL.createObjectURL(blob); - const a = $el("a", { - href: url, - download: `comfyui-logs-${Date.now()}.json`, - style: { display: "none" }, - parent: document.body, - }); - a.click(); - setTimeout(function () { - a.remove(); - window.URL.revokeObjectURL(url); - }, 0); - } - - import() { - fileInput.onchange = () => { - const reader = new FileReader(); - reader.onload = () => { - fileInput.remove(); - try { - const obj = JSON.parse(reader.result); - if (obj instanceof Array) { - this.show(obj); - } else { - throw new Error("Invalid file selected."); - } - } catch (error) { - alert("Unable to load logs: " + error.message); - } - }; - reader.readAsText(fileInput.files[0]); - }; - fileInput.click(); - } - - createButtons() { - return [ - $el("button", { - type: "button", - textContent: "Clear", - onclick: () => this.clear(), - }), - $el("button", { - type: "button", - textContent: "Export logs...", - onclick: () => this.export(), - }), - $el("button", { - type: "button", - textContent: "View exported logs...", - onclick: () => this.import(), - }), - ...super.createButtons(), - ]; - } - - getTypeColor(type) { - switch (type) { - case "error": - return "red"; - case "warn": - return "orange"; - case "debug": - return "dodgerblue"; - } - } - - show(entries) { - if (!entries) entries = this.logging.entries; - this.element.style.width = "100%"; - const cols = { - source: "Source", - type: "Type", - timestamp: "Timestamp", - message: "Message", - }; - const keys = Object.keys(cols); - const headers = Object.values(cols).map((title) => - $el("div.comfy-logging-title", { - textContent: title, - }) - ); - const rows = entries.map((entry, i) => { - return $el( - "div.comfy-logging-log", - { - $: (el) => el.style.setProperty("--row-bg", `var(--tr-${i % 2 ? "even" : "odd"}-bg-color)`), - }, - keys.map((key) => { - let v = entry[key]; - let color; - if (key === "type") { - color = this.getTypeColor(v); - } else { - v = jsonReplacer(key, v, true); - - if (typeof v === "object") { - v = stringify(v, 5, jsonReplacer, " "); - } - } - - return $el("div", { - style: { - color, - }, - textContent: v, - }); - }) - ); - }); - - const grid = $el( - "div.comfy-logging-logs", - { - style: { - gridTemplateColumns: `repeat(${headers.length}, 1fr)`, - }, - }, - [...headers, ...rows] - ); - const els = [grid]; - if (!this.logging.enabled) { - els.unshift( - $el("h3", { - style: { textAlign: "center" }, - textContent: "Logging is disabled", - }) - ); - } - super.show($el("div", els)); - } -} - -export class ComfyLogging { - /** - * @type Array<{ source: string, type: string, timestamp: Date, message: any }> - */ - entries = []; - - #enabled; - #console = {}; - - get enabled() { - return this.#enabled; - } - - set enabled(value) { - if (value === this.#enabled) return; - if (value) { - this.patchConsole(); - } else { - this.unpatchConsole(); - } - this.#enabled = value; - } - - constructor(app) { - this.app = app; - - this.dialog = new ComfyLoggingDialog(this); - this.addSetting(); - this.catchUnhandled(); - this.addInitData(); - } - - addSetting() { - const settingId = "Comfy.Logging.Enabled"; - const htmlSettingId = settingId.replaceAll(".", "-"); - const setting = this.app.ui.settings.addSetting({ - id: settingId, - name: settingId, - defaultValue: true, - onChange: (value) => { - this.enabled = value; - }, - type: (name, setter, value) => { - return $el("tr", [ - $el("td", [ - $el("label", { - textContent: "Logging", - for: htmlSettingId, - }), - ]), - $el("td", [ - $el("input", { - id: htmlSettingId, - type: "checkbox", - checked: value, - onchange: (event) => { - setter(event.target.checked); - }, - }), - $el("button", { - textContent: "View Logs", - onclick: () => { - this.app.ui.settings.element.close(); - this.dialog.show(); - }, - style: { - fontSize: "14px", - display: "block", - marginTop: "5px", - }, - }), - ]), - ]); - }, - }); - this.enabled = setting.value; - } - - patchConsole() { - // Capture common console outputs - const self = this; - for (const type of ["log", "warn", "error", "debug"]) { - const orig = console[type]; - this.#console[type] = orig; - console[type] = function () { - orig.apply(console, arguments); - self.addEntry("console", type, ...arguments); - }; - } - } - - unpatchConsole() { - // Restore original console functions - for (const type of Object.keys(this.#console)) { - console[type] = this.#console[type]; - } - this.#console = {}; - } - - catchUnhandled() { - // Capture uncaught errors - window.addEventListener("error", (e) => { - this.addEntry("window", "error", e.error ?? "Unknown error"); - return false; - }); - - window.addEventListener("unhandledrejection", (e) => { - this.addEntry("unhandledrejection", "error", e.reason ?? "Unknown error"); - }); - } - - clear() { - this.entries = []; - } - - addEntry(source, type, ...args) { - if (this.enabled) { - this.entries.push({ - source, - type, - timestamp: new Date(), - message: args, - }); - } - } - - log(source, ...args) { - this.addEntry(source, "log", ...args); - } - - async addInitData() { - if (!this.enabled) return; - const source = "ComfyUI.Logging"; - this.addEntry(source, "debug", { UserAgent: navigator.userAgent }); - const systemStats = await api.getSystemStats(); - this.addEntry(source, "debug", systemStats); - } -} +// Shim for scripts\logging.ts +export const ComfyLogging = window.comfyAPI.logging.ComfyLogging; diff --git a/web/scripts/metadata/flac.js b/web/scripts/metadata/flac.js new file mode 100644 index 000000000..8116899c0 --- /dev/null +++ b/web/scripts/metadata/flac.js @@ -0,0 +1,3 @@ +// Shim for scripts\metadata\flac.ts +export const getFromFlacBuffer = window.comfyAPI.flac.getFromFlacBuffer; +export const getFromFlacFile = window.comfyAPI.flac.getFromFlacFile; diff --git a/web/scripts/metadata/png.js b/web/scripts/metadata/png.js new file mode 100644 index 000000000..f0ef9e135 --- /dev/null +++ b/web/scripts/metadata/png.js @@ -0,0 +1,3 @@ +// Shim for scripts\metadata\png.ts +export const getFromPngBuffer = window.comfyAPI.png.getFromPngBuffer; +export const getFromPngFile = window.comfyAPI.png.getFromPngFile; diff --git a/web/scripts/pnginfo.js b/web/scripts/pnginfo.js index 4477ed7a1..e83481c9c 100644 --- a/web/scripts/pnginfo.js +++ b/web/scripts/pnginfo.js @@ -1,507 +1,6 @@ -import { api } from "./api.js"; - -export function getPngMetadata(file) { - return new Promise((r) => { - const reader = new FileReader(); - reader.onload = (event) => { - // Get the PNG data as a Uint8Array - const pngData = new Uint8Array(event.target.result); - const dataView = new DataView(pngData.buffer); - - // Check that the PNG signature is present - if (dataView.getUint32(0) !== 0x89504e47) { - console.error("Not a valid PNG file"); - r(); - return; - } - - // Start searching for chunks after the PNG signature - let offset = 8; - let txt_chunks = {}; - // Loop through the chunks in the PNG file - while (offset < pngData.length) { - // Get the length of the chunk - const length = dataView.getUint32(offset); - // Get the chunk type - const type = String.fromCharCode(...pngData.slice(offset + 4, offset + 8)); - if (type === "tEXt" || type == "comf" || type === "iTXt") { - // Get the keyword - let keyword_end = offset + 8; - while (pngData[keyword_end] !== 0) { - keyword_end++; - } - const keyword = String.fromCharCode(...pngData.slice(offset + 8, keyword_end)); - // Get the text - const contentArraySegment = pngData.slice(keyword_end + 1, offset + 8 + length); - const contentJson = new TextDecoder("utf-8").decode(contentArraySegment); - txt_chunks[keyword] = contentJson; - } - - offset += 12 + length; - } - - r(txt_chunks); - }; - - reader.readAsArrayBuffer(file); - }); -} - -function parseExifData(exifData) { - // Check for the correct TIFF header (0x4949 for little-endian or 0x4D4D for big-endian) - const isLittleEndian = String.fromCharCode(...exifData.slice(0, 2)) === "II"; - - // Function to read 16-bit and 32-bit integers from binary data - function readInt(offset, isLittleEndian, length) { - let arr = exifData.slice(offset, offset + length) - if (length === 2) { - return new DataView(arr.buffer, arr.byteOffset, arr.byteLength).getUint16(0, isLittleEndian); - } else if (length === 4) { - return new DataView(arr.buffer, arr.byteOffset, arr.byteLength).getUint32(0, isLittleEndian); - } - } - - // Read the offset to the first IFD (Image File Directory) - const ifdOffset = readInt(4, isLittleEndian, 4); - - function parseIFD(offset) { - const numEntries = readInt(offset, isLittleEndian, 2); - const result = {}; - - for (let i = 0; i < numEntries; i++) { - const entryOffset = offset + 2 + i * 12; - const tag = readInt(entryOffset, isLittleEndian, 2); - const type = readInt(entryOffset + 2, isLittleEndian, 2); - const numValues = readInt(entryOffset + 4, isLittleEndian, 4); - const valueOffset = readInt(entryOffset + 8, isLittleEndian, 4); - - // Read the value(s) based on the data type - let value; - if (type === 2) { - // ASCII string - value = String.fromCharCode(...exifData.slice(valueOffset, valueOffset + numValues - 1)); - } - - result[tag] = value; - } - - return result; - } - - // Parse the first IFD - const ifdData = parseIFD(ifdOffset); - return ifdData; -} - -function splitValues(input) { - var output = {}; - for (var key in input) { - var value = input[key]; - var splitValues = value.split(':', 2); - output[splitValues[0]] = splitValues[1]; - } - return output; -} - -export function getWebpMetadata(file) { - return new Promise((r) => { - const reader = new FileReader(); - reader.onload = (event) => { - const webp = new Uint8Array(event.target.result); - const dataView = new DataView(webp.buffer); - - // Check that the WEBP signature is present - if (dataView.getUint32(0) !== 0x52494646 || dataView.getUint32(8) !== 0x57454250) { - console.error("Not a valid WEBP file"); - r(); - return; - } - - // Start searching for chunks after the WEBP signature - let offset = 12; - let txt_chunks = {}; - // Loop through the chunks in the WEBP file - while (offset < webp.length) { - const chunk_length = dataView.getUint32(offset + 4, true); - const chunk_type = String.fromCharCode(...webp.slice(offset, offset + 4)); - if (chunk_type === "EXIF") { - if (String.fromCharCode(...webp.slice(offset + 8, offset + 8 + 6)) == "Exif\0\0") { - offset += 6; - } - let data = parseExifData(webp.slice(offset + 8, offset + 8 + chunk_length)); - for (var key in data) { - var value = data[key]; - let index = value.indexOf(':'); - txt_chunks[value.slice(0, index)] = value.slice(index + 1); - } - break; - } - - offset += 8 + chunk_length; - } - - r(txt_chunks); - }; - - reader.readAsArrayBuffer(file); - }); -} - -export function getLatentMetadata(file) { - return new Promise((r) => { - const reader = new FileReader(); - reader.onload = (event) => { - const safetensorsData = new Uint8Array(event.target.result); - const dataView = new DataView(safetensorsData.buffer); - let header_size = dataView.getUint32(0, true); - let offset = 8; - let header = JSON.parse(new TextDecoder().decode(safetensorsData.slice(offset, offset + header_size))); - r(header.__metadata__); - }; - - var slice = file.slice(0, 1024 * 1024 * 4); - reader.readAsArrayBuffer(slice); - }); -} - - -function getString(dataView, offset, length) { - let string = ''; - for (let i = 0; i < length; i++) { - string += String.fromCharCode(dataView.getUint8(offset + i)); - } - return string; -} - -// Function to parse the Vorbis Comment block -function parseVorbisComment(dataView) { - let offset = 0; - const vendorLength = dataView.getUint32(offset, true); - offset += 4; - const vendorString = getString(dataView, offset, vendorLength); - offset += vendorLength; - - const userCommentListLength = dataView.getUint32(offset, true); - offset += 4; - const comments = {}; - for (let i = 0; i < userCommentListLength; i++) { - const commentLength = dataView.getUint32(offset, true); - offset += 4; - const comment = getString(dataView, offset, commentLength); - offset += commentLength; - - const ind = comment.indexOf('=') - const key = comment.substring(0, ind); - - comments[key] = comment.substring(ind+1); - } - - return comments; -} - -// Function to read a FLAC file and parse Vorbis comments -export function getFlacMetadata(file) { - return new Promise((r) => { - const reader = new FileReader(); - reader.onload = function(event) { - const arrayBuffer = event.target.result; - const dataView = new DataView(arrayBuffer); - - // Verify the FLAC signature - const signature = String.fromCharCode(...new Uint8Array(arrayBuffer, 0, 4)); - if (signature !== 'fLaC') { - console.error('Not a valid FLAC file'); - return; - } - - // Parse metadata blocks - let offset = 4; - let vorbisComment = null; - while (offset < dataView.byteLength) { - const isLastBlock = dataView.getUint8(offset) & 0x80; - const blockType = dataView.getUint8(offset) & 0x7F; - const blockSize = dataView.getUint32(offset, false) & 0xFFFFFF; - offset += 4; - - if (blockType === 4) { // Vorbis Comment block type - vorbisComment = parseVorbisComment(new DataView(arrayBuffer, offset, blockSize)); - } - - offset += blockSize; - if (isLastBlock) break; - } - - r(vorbisComment); - }; - reader.readAsArrayBuffer(file); - }); -} - -export async function importA1111(graph, parameters) { - const p = parameters.lastIndexOf("\nSteps:"); - if (p > -1) { - const embeddings = await api.getEmbeddings(); - const opts = parameters - .substr(p) - .split("\n")[1] - .match(new RegExp("\\s*([^:]+:\\s*([^\"\\{].*?|\".*?\"|\\{.*?\\}))\\s*(,|$)", "g")) - .reduce((p, n) => { - const s = n.split(":"); - if (s[1].endsWith(',')) { - s[1] = s[1].substr(0, s[1].length -1); - } - p[s[0].trim().toLowerCase()] = s[1].trim(); - return p; - }, {}); - const p2 = parameters.lastIndexOf("\nNegative prompt:", p); - if (p2 > -1) { - let positive = parameters.substr(0, p2).trim(); - let negative = parameters.substring(p2 + 18, p).trim(); - - const ckptNode = LiteGraph.createNode("CheckpointLoaderSimple"); - const clipSkipNode = LiteGraph.createNode("CLIPSetLastLayer"); - const positiveNode = LiteGraph.createNode("CLIPTextEncode"); - const negativeNode = LiteGraph.createNode("CLIPTextEncode"); - const samplerNode = LiteGraph.createNode("KSampler"); - const imageNode = LiteGraph.createNode("EmptyLatentImage"); - const vaeNode = LiteGraph.createNode("VAEDecode"); - const vaeLoaderNode = LiteGraph.createNode("VAELoader"); - const saveNode = LiteGraph.createNode("SaveImage"); - let hrSamplerNode = null; - let hrSteps = null; - - const ceil64 = (v) => Math.ceil(v / 64) * 64; - - function getWidget(node, name) { - return node.widgets.find((w) => w.name === name); - } - - function setWidgetValue(node, name, value, isOptionPrefix) { - const w = getWidget(node, name); - if (isOptionPrefix) { - const o = w.options.values.find((w) => w.startsWith(value)); - if (o) { - w.value = o; - } else { - console.warn(`Unknown value '${value}' for widget '${name}'`, node); - w.value = value; - } - } else { - w.value = value; - } - } - - function createLoraNodes(clipNode, text, prevClip, prevModel) { - const loras = []; - text = text.replace(/]+)>/g, function (m, c) { - const s = c.split(":"); - const weight = parseFloat(s[1]); - if (isNaN(weight)) { - console.warn("Invalid LORA", m); - } else { - loras.push({ name: s[0], weight }); - } - return ""; - }); - - for (const l of loras) { - const loraNode = LiteGraph.createNode("LoraLoader"); - graph.add(loraNode); - setWidgetValue(loraNode, "lora_name", l.name, true); - setWidgetValue(loraNode, "strength_model", l.weight); - setWidgetValue(loraNode, "strength_clip", l.weight); - prevModel.node.connect(prevModel.index, loraNode, 0); - prevClip.node.connect(prevClip.index, loraNode, 1); - prevModel = { node: loraNode, index: 0 }; - prevClip = { node: loraNode, index: 1 }; - } - - prevClip.node.connect(1, clipNode, 0); - prevModel.node.connect(0, samplerNode, 0); - if (hrSamplerNode) { - prevModel.node.connect(0, hrSamplerNode, 0); - } - - return { text, prevModel, prevClip }; - } - - function replaceEmbeddings(text) { - if(!embeddings.length) return text; - return text.replaceAll( - new RegExp( - "\\b(" + embeddings.map((e) => e.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("\\b|\\b") + ")\\b", - "ig" - ), - "embedding:$1" - ); - } - - function popOpt(name) { - const v = opts[name]; - delete opts[name]; - return v; - } - - graph.clear(); - graph.add(ckptNode); - graph.add(clipSkipNode); - graph.add(positiveNode); - graph.add(negativeNode); - graph.add(samplerNode); - graph.add(imageNode); - graph.add(vaeNode); - graph.add(vaeLoaderNode); - graph.add(saveNode); - - ckptNode.connect(1, clipSkipNode, 0); - clipSkipNode.connect(0, positiveNode, 0); - clipSkipNode.connect(0, negativeNode, 0); - ckptNode.connect(0, samplerNode, 0); - positiveNode.connect(0, samplerNode, 1); - negativeNode.connect(0, samplerNode, 2); - imageNode.connect(0, samplerNode, 3); - vaeNode.connect(0, saveNode, 0); - samplerNode.connect(0, vaeNode, 0); - vaeLoaderNode.connect(0, vaeNode, 1); - - const handlers = { - model(v) { - setWidgetValue(ckptNode, "ckpt_name", v, true); - }, - "vae"(v) { - setWidgetValue(vaeLoaderNode, "vae_name", v, true); - }, - "cfg scale"(v) { - setWidgetValue(samplerNode, "cfg", +v); - }, - "clip skip"(v) { - setWidgetValue(clipSkipNode, "stop_at_clip_layer", -v); - }, - sampler(v) { - let name = v.toLowerCase().replace("++", "pp").replaceAll(" ", "_"); - if (name.includes("karras")) { - name = name.replace("karras", "").replace(/_+$/, ""); - setWidgetValue(samplerNode, "scheduler", "karras"); - } else { - setWidgetValue(samplerNode, "scheduler", "normal"); - } - const w = getWidget(samplerNode, "sampler_name"); - const o = w.options.values.find((w) => w === name || w === "sample_" + name); - if (o) { - setWidgetValue(samplerNode, "sampler_name", o); - } - }, - size(v) { - const wxh = v.split("x"); - const w = ceil64(+wxh[0]); - const h = ceil64(+wxh[1]); - const hrUp = popOpt("hires upscale"); - const hrSz = popOpt("hires resize"); - hrSteps = popOpt("hires steps"); - let hrMethod = popOpt("hires upscaler"); - - setWidgetValue(imageNode, "width", w); - setWidgetValue(imageNode, "height", h); - - if (hrUp || hrSz) { - let uw, uh; - if (hrUp) { - uw = w * hrUp; - uh = h * hrUp; - } else { - const s = hrSz.split("x"); - uw = +s[0]; - uh = +s[1]; - } - - let upscaleNode; - let latentNode; - - if (hrMethod.startsWith("Latent")) { - latentNode = upscaleNode = LiteGraph.createNode("LatentUpscale"); - graph.add(upscaleNode); - samplerNode.connect(0, upscaleNode, 0); - - switch (hrMethod) { - case "Latent (nearest-exact)": - hrMethod = "nearest-exact"; - break; - } - setWidgetValue(upscaleNode, "upscale_method", hrMethod, true); - } else { - const decode = LiteGraph.createNode("VAEDecodeTiled"); - graph.add(decode); - samplerNode.connect(0, decode, 0); - vaeLoaderNode.connect(0, decode, 1); - - const upscaleLoaderNode = LiteGraph.createNode("UpscaleModelLoader"); - graph.add(upscaleLoaderNode); - setWidgetValue(upscaleLoaderNode, "model_name", hrMethod, true); - - const modelUpscaleNode = LiteGraph.createNode("ImageUpscaleWithModel"); - graph.add(modelUpscaleNode); - decode.connect(0, modelUpscaleNode, 1); - upscaleLoaderNode.connect(0, modelUpscaleNode, 0); - - upscaleNode = LiteGraph.createNode("ImageScale"); - graph.add(upscaleNode); - modelUpscaleNode.connect(0, upscaleNode, 0); - - const vaeEncodeNode = (latentNode = LiteGraph.createNode("VAEEncodeTiled")); - graph.add(vaeEncodeNode); - upscaleNode.connect(0, vaeEncodeNode, 0); - vaeLoaderNode.connect(0, vaeEncodeNode, 1); - } - - setWidgetValue(upscaleNode, "width", ceil64(uw)); - setWidgetValue(upscaleNode, "height", ceil64(uh)); - - hrSamplerNode = LiteGraph.createNode("KSampler"); - graph.add(hrSamplerNode); - ckptNode.connect(0, hrSamplerNode, 0); - positiveNode.connect(0, hrSamplerNode, 1); - negativeNode.connect(0, hrSamplerNode, 2); - latentNode.connect(0, hrSamplerNode, 3); - hrSamplerNode.connect(0, vaeNode, 0); - } - }, - steps(v) { - setWidgetValue(samplerNode, "steps", +v); - }, - seed(v) { - setWidgetValue(samplerNode, "seed", +v); - }, - }; - - for (const opt in opts) { - if (opt in handlers) { - handlers[opt](popOpt(opt)); - } - } - - if (hrSamplerNode) { - setWidgetValue(hrSamplerNode, "steps", hrSteps? +hrSteps : getWidget(samplerNode, "steps").value); - setWidgetValue(hrSamplerNode, "cfg", getWidget(samplerNode, "cfg").value); - setWidgetValue(hrSamplerNode, "scheduler", getWidget(samplerNode, "scheduler").value); - setWidgetValue(hrSamplerNode, "sampler_name", getWidget(samplerNode, "sampler_name").value); - setWidgetValue(hrSamplerNode, "denoise", +(popOpt("denoising strength") || "1")); - } - - let n = createLoraNodes(positiveNode, positive, { node: clipSkipNode, index: 0 }, { node: ckptNode, index: 0 }); - positive = n.text; - n = createLoraNodes(negativeNode, negative, n.prevClip, n.prevModel); - negative = n.text; - - setWidgetValue(positiveNode, "text", replaceEmbeddings(positive)); - setWidgetValue(negativeNode, "text", replaceEmbeddings(negative)); - - graph.arrange(); - - for (const opt of ["model hash", "ensd", "version", "vae hash", "ti hashes", "lora hashes", "hashes"]) { - delete opts[opt]; - } - - console.warn("Unhandled parameters:", opts); - } - } -} +// Shim for scripts\pnginfo.ts +export const getPngMetadata = window.comfyAPI.pnginfo.getPngMetadata; +export const getFlacMetadata = window.comfyAPI.pnginfo.getFlacMetadata; +export const getWebpMetadata = window.comfyAPI.pnginfo.getWebpMetadata; +export const getLatentMetadata = window.comfyAPI.pnginfo.getLatentMetadata; +export const importA1111 = window.comfyAPI.pnginfo.importA1111; diff --git a/web/scripts/ui.js b/web/scripts/ui.js index 2c47412c9..007e21d5f 100644 --- a/web/scripts/ui.js +++ b/web/scripts/ui.js @@ -1,660 +1,4 @@ -import { api } from "./api.js"; -import { ComfyDialog as _ComfyDialog } from "./ui/dialog.js"; -import { toggleSwitch } from "./ui/toggleSwitch.js"; -import { ComfySettingsDialog } from "./ui/settings.js"; - -export const ComfyDialog = _ComfyDialog; - -/** - * @template { string | (keyof HTMLElementTagNameMap) } K - * @typedef { K extends keyof HTMLElementTagNameMap ? HTMLElementTagNameMap[K] : HTMLElement } ElementType - */ - -/** - * @template { string | (keyof HTMLElementTagNameMap) } K - * @param { K } tag HTML Element Tag and optional classes e.g. div.class1.class2 - * @param { string | Element | Element[] | ({ - * parent?: Element, - * $?: (el: ElementType) => void, - * dataset?: DOMStringMap, - * style?: Partial, - * for?: string - * } & Omit>, "style">) | undefined } [propsOrChildren] - * @param { string | Element | Element[] | undefined } [children] - * @returns { ElementType } - */ -export function $el(tag, propsOrChildren, children) { - const split = tag.split("."); - const element = document.createElement(split.shift()); - if (split.length > 0) { - element.classList.add(...split); - } - - if (propsOrChildren) { - if (typeof propsOrChildren === "string") { - propsOrChildren = { textContent: propsOrChildren }; - } else if (propsOrChildren instanceof Element) { - propsOrChildren = [propsOrChildren]; - } - if (Array.isArray(propsOrChildren)) { - element.append(...propsOrChildren); - } else { - const {parent, $: cb, dataset, style} = propsOrChildren; - delete propsOrChildren.parent; - delete propsOrChildren.$; - delete propsOrChildren.dataset; - delete propsOrChildren.style; - - if (Object.hasOwn(propsOrChildren, "for")) { - element.setAttribute("for", propsOrChildren.for) - } - - if (style) { - Object.assign(element.style, style); - } - - if (dataset) { - Object.assign(element.dataset, dataset); - } - - Object.assign(element, propsOrChildren); - if (children) { - element.append(...(children instanceof Array ? children.filter(Boolean) : [children])); - } - - if (parent) { - parent.append(element); - } - - if (cb) { - cb(element); - } - } - } - return element; -} - -function dragElement(dragEl, settings) { - var posDiffX = 0, - posDiffY = 0, - posStartX = 0, - posStartY = 0, - newPosX = 0, - newPosY = 0; - if (dragEl.getElementsByClassName("drag-handle")[0]) { - // if present, the handle is where you move the DIV from: - dragEl.getElementsByClassName("drag-handle")[0].onmousedown = dragMouseDown; - } else { - // otherwise, move the DIV from anywhere inside the DIV: - dragEl.onmousedown = dragMouseDown; - } - - // When the element resizes (e.g. view queue) ensure it is still in the windows bounds - const resizeObserver = new ResizeObserver(() => { - ensureInBounds(); - }).observe(dragEl); - - function ensureInBounds() { - try { - newPosX = Math.min(document.body.clientWidth - dragEl.clientWidth, Math.max(0, dragEl.offsetLeft)); - newPosY = Math.min(document.body.clientHeight - dragEl.clientHeight, Math.max(0, dragEl.offsetTop)); - - positionElement(); - } - catch(exception){ - // robust - } - } - - function positionElement() { - if(dragEl.style.display === "none") return; - - const halfWidth = document.body.clientWidth / 2; - const anchorRight = newPosX + dragEl.clientWidth / 2 > halfWidth; - - // set the element's new position: - if (anchorRight) { - dragEl.style.left = "unset"; - dragEl.style.right = document.body.clientWidth - newPosX - dragEl.clientWidth + "px"; - } else { - dragEl.style.left = newPosX + "px"; - dragEl.style.right = "unset"; - } - - dragEl.style.top = newPosY + "px"; - dragEl.style.bottom = "unset"; - - if (savePos) { - localStorage.setItem( - "Comfy.MenuPosition", - JSON.stringify({ - x: dragEl.offsetLeft, - y: dragEl.offsetTop, - }) - ); - } - } - - function restorePos() { - let pos = localStorage.getItem("Comfy.MenuPosition"); - if (pos) { - pos = JSON.parse(pos); - newPosX = pos.x; - newPosY = pos.y; - positionElement(); - ensureInBounds(); - } - } - - let savePos = undefined; - settings.addSetting({ - id: "Comfy.MenuPosition", - name: "Save menu position", - type: "boolean", - defaultValue: savePos, - onChange(value) { - if (savePos === undefined && value) { - restorePos(); - } - savePos = value; - }, - }); - - function dragMouseDown(e) { - e = e || window.event; - e.preventDefault(); - // get the mouse cursor position at startup: - posStartX = e.clientX; - posStartY = e.clientY; - document.onmouseup = closeDragElement; - // call a function whenever the cursor moves: - document.onmousemove = elementDrag; - } - - function elementDrag(e) { - e = e || window.event; - e.preventDefault(); - - dragEl.classList.add("comfy-menu-manual-pos"); - - // calculate the new cursor position: - posDiffX = e.clientX - posStartX; - posDiffY = e.clientY - posStartY; - posStartX = e.clientX; - posStartY = e.clientY; - - newPosX = Math.min(document.body.clientWidth - dragEl.clientWidth, Math.max(0, dragEl.offsetLeft + posDiffX)); - newPosY = Math.min(document.body.clientHeight - dragEl.clientHeight, Math.max(0, dragEl.offsetTop + posDiffY)); - - positionElement(); - } - - window.addEventListener("resize", () => { - ensureInBounds(); - }); - - function closeDragElement() { - // stop moving when mouse button is released: - document.onmouseup = null; - document.onmousemove = null; - } - - return restorePos; -} - -class ComfyList { - #type; - #text; - #reverse; - - constructor(text, type, reverse) { - this.#text = text; - this.#type = type || text.toLowerCase(); - this.#reverse = reverse || false; - this.element = $el("div.comfy-list"); - this.element.style.display = "none"; - } - - get visible() { - return this.element.style.display !== "none"; - } - - async load() { - const items = await api.getItems(this.#type); - this.element.replaceChildren( - ...Object.keys(items).flatMap((section) => [ - $el("h4", { - textContent: section, - }), - $el("div.comfy-list-items", [ - ...(this.#reverse ? items[section].reverse() : items[section]).map((item) => { - // Allow items to specify a custom remove action (e.g. for interrupt current prompt) - const removeAction = item.remove || { - name: "Delete", - cb: () => api.deleteItem(this.#type, item.prompt[1]), - }; - return $el("div", {textContent: item.prompt[0] + ": "}, [ - $el("button", { - textContent: "Load", - onclick: async () => { - await app.loadGraphData(item.prompt[3].extra_pnginfo.workflow, true, false); - if (item.outputs) { - app.nodeOutputs = item.outputs; - } - }, - }), - $el("button", { - textContent: removeAction.name, - onclick: async () => { - await removeAction.cb(); - await this.update(); - }, - }), - ]); - }), - ]), - ]), - $el("div.comfy-list-actions", [ - $el("button", { - textContent: "Clear " + this.#text, - onclick: async () => { - await api.clearItems(this.#type); - await this.load(); - }, - }), - $el("button", {textContent: "Refresh", onclick: () => this.load()}), - ]) - ); - } - - async update() { - if (this.visible) { - await this.load(); - } - } - - async show() { - this.element.style.display = "block"; - this.button.textContent = "Close"; - - await this.load(); - } - - hide() { - this.element.style.display = "none"; - this.button.textContent = "View " + this.#text; - } - - toggle() { - if (this.visible) { - this.hide(); - return false; - } else { - this.show(); - return true; - } - } -} - -export class ComfyUI { - constructor(app) { - this.app = app; - this.dialog = new ComfyDialog(); - this.settings = new ComfySettingsDialog(app); - - this.batchCount = 1; - this.lastQueueSize = 0; - this.queue = new ComfyList("Queue"); - this.history = new ComfyList("History", "history", true); - - api.addEventListener("status", () => { - this.queue.update(); - this.history.update(); - }); - - const confirmClear = this.settings.addSetting({ - id: "Comfy.ConfirmClear", - name: "Require confirmation when clearing workflow", - type: "boolean", - defaultValue: true, - }); - - const promptFilename = this.settings.addSetting({ - id: "Comfy.PromptFilename", - name: "Prompt for filename when saving workflow", - type: "boolean", - defaultValue: true, - }); - - /** - * file format for preview - * - * format;quality - * - * ex) - * webp;50 -> webp, quality 50 - * jpeg;80 -> rgb, jpeg, quality 80 - * - * @type {string} - */ - const previewImage = this.settings.addSetting({ - id: "Comfy.PreviewFormat", - name: "When displaying a preview in the image widget, convert it to a lightweight image, e.g. webp, jpeg, webp;50, etc.", - type: "text", - defaultValue: "", - }); - - this.settings.addSetting({ - id: "Comfy.DisableSliders", - name: "Disable sliders.", - type: "boolean", - defaultValue: false, - }); - - this.settings.addSetting({ - id: "Comfy.DisableFloatRounding", - name: "Disable rounding floats (requires page reload).", - type: "boolean", - defaultValue: false, - }); - - this.settings.addSetting({ - id: "Comfy.FloatRoundingPrecision", - name: "Decimal places [0 = auto] (requires page reload).", - type: "slider", - attrs: { - min: 0, - max: 6, - step: 1, - }, - defaultValue: 0, - }); - - const fileInput = $el("input", { - id: "comfy-file-input", - type: "file", - accept: ".json,image/png,.latent,.safetensors,image/webp,audio/flac", - style: {display: "none"}, - parent: document.body, - onchange: () => { - app.handleFile(fileInput.files[0]); - }, - }); - - this.loadFile = () => fileInput.click(); - - const autoQueueModeEl = toggleSwitch( - "autoQueueMode", - [ - { text: "instant", tooltip: "A new prompt will be queued as soon as the queue reaches 0" }, - { text: "change", tooltip: "A new prompt will be queued when the queue is at 0 and the graph is/has changed" }, - ], - { - onChange: (value) => { - this.autoQueueMode = value.item.value; - }, - } - ); - autoQueueModeEl.style.display = "none"; - - api.addEventListener("graphChanged", () => { - if (this.autoQueueMode === "change" && this.autoQueueEnabled === true) { - if (this.lastQueueSize === 0) { - this.graphHasChanged = false; - app.queuePrompt(0, this.batchCount); - } else { - this.graphHasChanged = true; - } - } - }); - - this.menuHamburger = $el( - "div.comfy-menu-hamburger", - { - parent: document.body, - onclick: () => { - this.menuContainer.style.display = "block"; - this.menuHamburger.style.display = "none"; - }, - }, - [$el("div"), $el("div"), $el("div")] - ); - - this.menuContainer = $el("div.comfy-menu", { parent: document.body }, [ - $el("div.drag-handle.comfy-menu-header", { - style: { - overflow: "hidden", - position: "relative", - width: "100%", - cursor: "default" - } - }, [ - $el("span.drag-handle"), - $el("span.comfy-menu-queue-size", { $: (q) => (this.queueSize = q) }), - $el("div.comfy-menu-actions", [ - $el("button.comfy-settings-btn", { - textContent: "⚙️", - onclick: () => this.settings.show(), - }), - $el("button.comfy-close-menu-btn", { - textContent: "\u00d7", - onclick: () => { - this.menuContainer.style.display = "none"; - this.menuHamburger.style.display = "flex"; - }, - }), - ]), - ]), - $el("button.comfy-queue-btn", { - id: "queue-button", - textContent: "Queue Prompt", - onclick: () => app.queuePrompt(0, this.batchCount), - }), - $el("div", {}, [ - $el("label", {innerHTML: "Extra options"}, [ - $el("input", { - type: "checkbox", - onchange: (i) => { - document.getElementById("extraOptions").style.display = i.srcElement.checked ? "block" : "none"; - this.batchCount = i.srcElement.checked ? document.getElementById("batchCountInputRange").value : 1; - document.getElementById("autoQueueCheckbox").checked = false; - this.autoQueueEnabled = false; - }, - }), - ]), - ]), - $el("div", {id: "extraOptions", style: {width: "100%", display: "none"}}, [ - $el("div",[ - - $el("label", {innerHTML: "Batch count"}), - $el("input", { - id: "batchCountInputNumber", - type: "number", - value: this.batchCount, - min: "1", - style: {width: "35%", "margin-left": "0.4em"}, - oninput: (i) => { - this.batchCount = i.target.value; - document.getElementById("batchCountInputRange").value = this.batchCount; - }, - }), - $el("input", { - id: "batchCountInputRange", - type: "range", - min: "1", - max: "100", - value: this.batchCount, - oninput: (i) => { - this.batchCount = i.srcElement.value; - document.getElementById("batchCountInputNumber").value = i.srcElement.value; - }, - }), - ]), - $el("div",[ - $el("label",{ - for:"autoQueueCheckbox", - innerHTML: "Auto Queue" - }), - $el("input", { - id: "autoQueueCheckbox", - type: "checkbox", - checked: false, - title: "Automatically queue prompt when the queue size hits 0", - onchange: (e) => { - this.autoQueueEnabled = e.target.checked; - autoQueueModeEl.style.display = this.autoQueueEnabled ? "" : "none"; - } - }), - autoQueueModeEl - ]) - ]), - $el("div.comfy-menu-btns", [ - $el("button", { - id: "queue-front-button", - textContent: "Queue Front", - onclick: () => app.queuePrompt(-1, this.batchCount) - }), - $el("button", { - $: (b) => (this.queue.button = b), - id: "comfy-view-queue-button", - textContent: "View Queue", - onclick: () => { - this.history.hide(); - this.queue.toggle(); - }, - }), - $el("button", { - $: (b) => (this.history.button = b), - id: "comfy-view-history-button", - textContent: "View History", - onclick: () => { - this.queue.hide(); - this.history.toggle(); - }, - }), - ]), - this.queue.element, - this.history.element, - $el("button", { - id: "comfy-save-button", - textContent: "Save", - onclick: () => { - let filename = "workflow.json"; - if (promptFilename.value) { - filename = prompt("Save workflow as:", filename); - if (!filename) return; - if (!filename.toLowerCase().endsWith(".json")) { - filename += ".json"; - } - } - app.graphToPrompt().then(p=>{ - const json = JSON.stringify(p.workflow, null, 2); // convert the data to a JSON string - const blob = new Blob([json], {type: "application/json"}); - const url = URL.createObjectURL(blob); - const a = $el("a", { - href: url, - download: filename, - style: {display: "none"}, - parent: document.body, - }); - a.click(); - setTimeout(function () { - a.remove(); - window.URL.revokeObjectURL(url); - }, 0); - }); - }, - }), - $el("button", { - id: "comfy-dev-save-api-button", - textContent: "Save (API Format)", - style: {width: "100%", display: "none"}, - onclick: () => { - let filename = "workflow_api.json"; - if (promptFilename.value) { - filename = prompt("Save workflow (API) as:", filename); - if (!filename) return; - if (!filename.toLowerCase().endsWith(".json")) { - filename += ".json"; - } - } - app.graphToPrompt().then(p=>{ - const json = JSON.stringify(p.output, null, 2); // convert the data to a JSON string - const blob = new Blob([json], {type: "application/json"}); - const url = URL.createObjectURL(blob); - const a = $el("a", { - href: url, - download: filename, - style: {display: "none"}, - parent: document.body, - }); - a.click(); - setTimeout(function () { - a.remove(); - window.URL.revokeObjectURL(url); - }, 0); - }); - }, - }), - $el("button", {id: "comfy-load-button", textContent: "Load", onclick: () => fileInput.click()}), - $el("button", { - id: "comfy-refresh-button", - textContent: "Refresh", - onclick: () => app.refreshComboInNodes() - }), - $el("button", {id: "comfy-clipspace-button", textContent: "Clipspace", onclick: () => app.openClipspace()}), - $el("button", { - id: "comfy-clear-button", textContent: "Clear", onclick: () => { - if (!confirmClear.value || confirm("Clear workflow?")) { - app.clean(); - app.graph.clear(); - app.resetView(); - } - } - }), - $el("button", { - id: "comfy-load-default-button", textContent: "Load Default", onclick: async () => { - if (!confirmClear.value || confirm("Load default workflow?")) { - app.resetView(); - await app.loadGraphData() - } - } - }), - $el("button", { - id: "comfy-reset-view-button", textContent: "Reset View", onclick: async () => { - app.resetView(); - } - }), - ]); - - const devMode = this.settings.addSetting({ - id: "Comfy.DevMode", - name: "Enable Dev mode Options", - type: "boolean", - defaultValue: false, - onChange: function(value) { document.getElementById("comfy-dev-save-api-button").style.display = value ? "flex" : "none"}, - }); - - this.restoreMenuPosition = dragElement(this.menuContainer, this.settings); - - this.setStatus({exec_info: {queue_remaining: "X"}}); - } - - setStatus(status) { - this.queueSize.textContent = "Queue size: " + (status ? status.exec_info.queue_remaining : "ERR"); - if (status) { - if ( - this.lastQueueSize != 0 && - status.exec_info.queue_remaining == 0 && - this.autoQueueEnabled && - (this.autoQueueMode === "instant" || this.graphHasChanged) && - !app.lastExecutionError - ) { - app.queuePrompt(0, this.batchCount); - status.exec_info.queue_remaining += this.batchCount; - this.graphHasChanged = false; - } - this.lastQueueSize = status.exec_info.queue_remaining; - } - } -} +// Shim for scripts\ui.ts +export const ComfyDialog = window.comfyAPI.ui.ComfyDialog; +export const $el = window.comfyAPI.ui.$el; +export const ComfyUI = window.comfyAPI.ui.ComfyUI; diff --git a/web/scripts/ui/components/asyncDialog.js b/web/scripts/ui/components/asyncDialog.js index 434ce4b30..c36676236 100644 --- a/web/scripts/ui/components/asyncDialog.js +++ b/web/scripts/ui/components/asyncDialog.js @@ -1,64 +1,2 @@ -import { ComfyDialog } from "../dialog.js"; -import { $el } from "../../ui.js"; - -export class ComfyAsyncDialog extends ComfyDialog { - #resolve; - - constructor(actions) { - super( - "dialog.comfy-dialog.comfyui-dialog", - actions?.map((opt) => { - if (typeof opt === "string") { - opt = { text: opt }; - } - return $el("button.comfyui-button", { - type: "button", - textContent: opt.text, - onclick: () => this.close(opt.value ?? opt.text), - }); - }) - ); - } - - show(html) { - this.element.addEventListener("close", () => { - this.close(); - }); - - super.show(html); - - return new Promise((resolve) => { - this.#resolve = resolve; - }); - } - - showModal(html) { - this.element.addEventListener("close", () => { - this.close(); - }); - - super.show(html); - this.element.showModal(); - - return new Promise((resolve) => { - this.#resolve = resolve; - }); - } - - close(result = null) { - this.#resolve(result); - this.element.close(); - super.close(); - } - - static async prompt({ title = null, message, actions }) { - const dialog = new ComfyAsyncDialog(actions); - const content = [$el("span", message)]; - if (title) { - content.unshift($el("h3", title)); - } - const res = await dialog.showModal(content); - dialog.element.remove(); - return res; - } -} +// Shim for scripts\ui\components\asyncDialog.ts +export const ComfyAsyncDialog = window.comfyAPI.asyncDialog.ComfyAsyncDialog; diff --git a/web/scripts/ui/components/button.js b/web/scripts/ui/components/button.js index 25e5aeebd..83def00bc 100644 --- a/web/scripts/ui/components/button.js +++ b/web/scripts/ui/components/button.js @@ -1,163 +1,2 @@ -// @ts-check - -import { $el } from "../../ui.js"; -import { applyClasses, toggleElement } from "../utils.js"; -import { prop } from "../../utils.js"; - -/** - * @typedef {{ - * icon?: string; - * overIcon?: string; - * iconSize?: number; - * content?: string | HTMLElement; - * tooltip?: string; - * enabled?: boolean; - * action?: (e: Event, btn: ComfyButton) => void, - * classList?: import("../utils.js").ClassList, - * visibilitySetting?: { id: string, showValue: any }, - * app?: import("../../app.js").ComfyApp - * }} ComfyButtonProps - */ -export class ComfyButton { - #over = 0; - #popupOpen = false; - isOver = false; - iconElement = $el("i.mdi"); - contentElement = $el("span"); - /** - * @type {import("./popup.js").ComfyPopup} - */ - popup; - - /** - * @param {ComfyButtonProps} opts - */ - constructor({ - icon, - overIcon, - iconSize, - content, - tooltip, - action, - classList = "comfyui-button", - visibilitySetting, - app, - enabled = true, - }) { - this.element = $el("button", { - onmouseenter: () => { - this.isOver = true; - if(this.overIcon) { - this.updateIcon(); - } - }, - onmouseleave: () => { - this.isOver = false; - if(this.overIcon) { - this.updateIcon(); - } - } - - }, [this.iconElement, this.contentElement]); - - this.icon = prop(this, "icon", icon, toggleElement(this.iconElement, { onShow: this.updateIcon })); - this.overIcon = prop(this, "overIcon", overIcon, () => { - if(this.isOver) { - this.updateIcon(); - } - }); - this.iconSize = prop(this, "iconSize", iconSize, this.updateIcon); - this.content = prop( - this, - "content", - content, - toggleElement(this.contentElement, { - onShow: (el, v) => { - if (typeof v === "string") { - el.textContent = v; - } else { - el.replaceChildren(v); - } - }, - }) - ); - - this.tooltip = prop(this, "tooltip", tooltip, (v) => { - if (v) { - this.element.title = v; - } else { - this.element.removeAttribute("title"); - } - }); - this.classList = prop(this, "classList", classList, this.updateClasses); - this.hidden = prop(this, "hidden", false, this.updateClasses); - this.enabled = prop(this, "enabled", enabled, () => { - this.updateClasses(); - this.element.disabled = !this.enabled; - }); - this.action = prop(this, "action", action); - this.element.addEventListener("click", (e) => { - if (this.popup) { - // we are either a touch device or triggered by click not hover - if (!this.#over) { - this.popup.toggle(); - } - } - this.action?.(e, this); - }); - - if (visibilitySetting?.id) { - const settingUpdated = () => { - this.hidden = app.ui.settings.getSettingValue(visibilitySetting.id) !== visibilitySetting.showValue; - }; - app.ui.settings.addEventListener(visibilitySetting.id + ".change", settingUpdated); - settingUpdated(); - } - } - - updateIcon = () => (this.iconElement.className = `mdi mdi-${(this.isOver && this.overIcon) || this.icon}${this.iconSize ? " mdi-" + this.iconSize + "px" : ""}`); - updateClasses = () => { - const internalClasses = []; - if (this.hidden) { - internalClasses.push("hidden"); - } - if (!this.enabled) { - internalClasses.push("disabled"); - } - if (this.popup) { - if (this.#popupOpen) { - internalClasses.push("popup-open"); - } else { - internalClasses.push("popup-closed"); - } - } - applyClasses(this.element, this.classList, ...internalClasses); - }; - - /** - * - * @param { import("./popup.js").ComfyPopup } popup - * @param { "click" | "hover" } mode - */ - withPopup(popup, mode = "click") { - this.popup = popup; - - if (mode === "hover") { - for (const el of [this.element, this.popup.element]) { - el.addEventListener("mouseenter", () => { - this.popup.open = !!++this.#over; - }); - el.addEventListener("mouseleave", () => { - this.popup.open = !!--this.#over; - }); - } - } - - popup.addEventListener("change", () => { - this.#popupOpen = popup.open; - this.updateClasses(); - }); - - return this; - } -} +// Shim for scripts\ui\components\button.ts +export const ComfyButton = window.comfyAPI.button.ComfyButton; diff --git a/web/scripts/ui/components/buttonGroup.js b/web/scripts/ui/components/buttonGroup.js index 573572fd0..e1faa20ad 100644 --- a/web/scripts/ui/components/buttonGroup.js +++ b/web/scripts/ui/components/buttonGroup.js @@ -1,45 +1,2 @@ -// @ts-check - -import { $el } from "../../ui.js"; -import { ComfyButton } from "./button.js"; -import { prop } from "../../utils.js"; - -export class ComfyButtonGroup { - element = $el("div.comfyui-button-group"); - - /** @param {Array} buttons */ - constructor(...buttons) { - this.buttons = prop(this, "buttons", buttons, () => this.update()); - } - - /** - * @param {ComfyButton} button - * @param {number} index - */ - insert(button, index) { - this.buttons.splice(index, 0, button); - this.update(); - } - - /** @param {ComfyButton} button */ - append(button) { - this.buttons.push(button); - this.update(); - } - - /** @param {ComfyButton|number} indexOrButton */ - remove(indexOrButton) { - if (typeof indexOrButton !== "number") { - indexOrButton = this.buttons.indexOf(indexOrButton); - } - if (indexOrButton > -1) { - const r = this.buttons.splice(indexOrButton, 1); - this.update(); - return r; - } - } - - update() { - this.element.replaceChildren(...this.buttons.map((b) => b["element"] ?? b)); - } -} +// Shim for scripts\ui\components\buttonGroup.ts +export const ComfyButtonGroup = window.comfyAPI.buttonGroup.ComfyButtonGroup; diff --git a/web/scripts/ui/components/popup.js b/web/scripts/ui/components/popup.js index ee59b35d9..323c33c39 100644 --- a/web/scripts/ui/components/popup.js +++ b/web/scripts/ui/components/popup.js @@ -1,128 +1,2 @@ -// @ts-check - -import { prop } from "../../utils.js"; -import { $el } from "../../ui.js"; -import { applyClasses } from "../utils.js"; - -export class ComfyPopup extends EventTarget { - element = $el("div.comfyui-popup"); - - /** - * @param {{ - * target: HTMLElement, - * container?: HTMLElement, - * classList?: import("../utils.js").ClassList, - * ignoreTarget?: boolean, - * closeOnEscape?: boolean, - * position?: "absolute" | "relative", - * horizontal?: "left" | "right" - * }} param0 - * @param {...HTMLElement} children - */ - constructor( - { - target, - container = document.body, - classList = "", - ignoreTarget = true, - closeOnEscape = true, - position = "absolute", - horizontal = "left", - }, - ...children - ) { - super(); - this.target = target; - this.ignoreTarget = ignoreTarget; - this.container = container; - this.position = position; - this.closeOnEscape = closeOnEscape; - this.horizontal = horizontal; - - container.append(this.element); - - this.children = prop(this, "children", children, () => { - this.element.replaceChildren(...this.children); - this.update(); - }); - this.classList = prop(this, "classList", classList, () => applyClasses(this.element, this.classList, "comfyui-popup", horizontal)); - this.open = prop(this, "open", false, (v, o) => { - if (v === o) return; - if (v) { - this.#show(); - } else { - this.#hide(); - } - }); - } - - toggle() { - this.open = !this.open; - } - - #hide() { - this.element.classList.remove("open"); - window.removeEventListener("resize", this.update); - window.removeEventListener("click", this.#clickHandler, { capture: true }); - window.removeEventListener("keydown", this.#escHandler, { capture: true }); - - this.dispatchEvent(new CustomEvent("close")); - this.dispatchEvent(new CustomEvent("change")); - } - - #show() { - this.element.classList.add("open"); - this.update(); - - window.addEventListener("resize", this.update); - window.addEventListener("click", this.#clickHandler, { capture: true }); - if (this.closeOnEscape) { - window.addEventListener("keydown", this.#escHandler, { capture: true }); - } - - this.dispatchEvent(new CustomEvent("open")); - this.dispatchEvent(new CustomEvent("change")); - } - - #escHandler = (e) => { - if (e.key === "Escape") { - this.open = false; - e.preventDefault(); - e.stopImmediatePropagation(); - } - }; - - #clickHandler = (e) => { - /** @type {any} */ - const target = e.target; - if (!this.element.contains(target) && this.ignoreTarget && !this.target.contains(target)) { - this.open = false; - } - }; - - update = () => { - const rect = this.target.getBoundingClientRect(); - this.element.style.setProperty("--bottom", "unset"); - if (this.position === "absolute") { - if (this.horizontal === "left") { - this.element.style.setProperty("--left", rect.left + "px"); - } else { - this.element.style.setProperty("--left", rect.right - this.element.clientWidth + "px"); - } - this.element.style.setProperty("--top", rect.bottom + "px"); - this.element.style.setProperty("--limit", rect.bottom + "px"); - } else { - this.element.style.setProperty("--left", 0 + "px"); - this.element.style.setProperty("--top", rect.height + "px"); - this.element.style.setProperty("--limit", rect.height + "px"); - } - - const thisRect = this.element.getBoundingClientRect(); - if (thisRect.height < 30) { - // Move up instead - this.element.style.setProperty("--top", "unset"); - this.element.style.setProperty("--bottom", rect.height + 5 + "px"); - this.element.style.setProperty("--limit", rect.height + 5 + "px"); - } - }; -} +// Shim for scripts\ui\components\popup.ts +export const ComfyPopup = window.comfyAPI.popup.ComfyPopup; diff --git a/web/scripts/ui/components/splitButton.js b/web/scripts/ui/components/splitButton.js index 2b4e6d9f8..8f8340b8d 100644 --- a/web/scripts/ui/components/splitButton.js +++ b/web/scripts/ui/components/splitButton.js @@ -1,43 +1,2 @@ -// @ts-check - -import { $el } from "../../ui.js"; -import { ComfyButton } from "./button.js"; -import { prop } from "../../utils.js"; -import { ComfyPopup } from "./popup.js"; - -export class ComfySplitButton { - /** - * @param {{ - * primary: ComfyButton, - * mode?: "hover" | "click", - * horizontal?: "left" | "right", - * position?: "relative" | "absolute" - * }} param0 - * @param {Array | Array} items - */ - constructor({ primary, mode, horizontal = "left", position = "relative" }, ...items) { - this.arrow = new ComfyButton({ - icon: "chevron-down", - }); - this.element = $el("div.comfyui-split-button" + (mode === "hover" ? ".hover" : ""), [ - $el("div.comfyui-split-primary", primary.element), - $el("div.comfyui-split-arrow", this.arrow.element), - ]); - this.popup = new ComfyPopup({ - target: this.element, - container: position === "relative" ? this.element : document.body, - classList: "comfyui-split-button-popup" + (mode === "hover" ? " hover" : ""), - closeOnEscape: mode === "click", - position, - horizontal, - }); - - this.arrow.withPopup(this.popup, mode); - - this.items = prop(this, "items", items, () => this.update()); - } - - update() { - this.popup.element.replaceChildren(...this.items.map((b) => b.element ?? b)); - } -} +// Shim for scripts\ui\components\splitButton.ts +export const ComfySplitButton = window.comfyAPI.splitButton.ComfySplitButton; diff --git a/web/scripts/ui/dialog.js b/web/scripts/ui/dialog.js index 803a97a2b..a185bc01b 100644 --- a/web/scripts/ui/dialog.js +++ b/web/scripts/ui/dialog.js @@ -1,38 +1,2 @@ -import { $el } from "../ui.js"; - -export class ComfyDialog extends EventTarget { - #buttons; - - constructor(type = "div", buttons = null) { - super(); - this.#buttons = buttons; - this.element = $el(type + ".comfy-modal", { parent: document.body }, [ - $el("div.comfy-modal-content", [$el("p", { $: (p) => (this.textElement = p) }), ...this.createButtons()]), - ]); - } - - createButtons() { - return ( - this.#buttons ?? [ - $el("button", { - type: "button", - textContent: "Close", - onclick: () => this.close(), - }), - ] - ); - } - - close() { - this.element.style.display = "none"; - } - - show(html) { - if (typeof html === "string") { - this.textElement.innerHTML = html; - } else { - this.textElement.replaceChildren(...(html instanceof Array ? html : [html])); - } - this.element.style.display = "flex"; - } -} +// Shim for scripts\ui\dialog.ts +export const ComfyDialog = window.comfyAPI.dialog.ComfyDialog; diff --git a/web/scripts/ui/draggableList.js b/web/scripts/ui/draggableList.js index d53594886..192651e04 100644 --- a/web/scripts/ui/draggableList.js +++ b/web/scripts/ui/draggableList.js @@ -1,287 +1,2 @@ -// @ts-check -/* - Original implementation: - https://github.com/TahaSh/drag-to-reorder - MIT License - - Copyright (c) 2023 Taha Shashtari - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all - copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - SOFTWARE. -*/ - -import { $el } from "../ui.js"; - -$el("style", { - parent: document.head, - textContent: ` - .draggable-item { - position: relative; - will-change: transform; - user-select: none; - } - .draggable-item.is-idle { - transition: 0.25s ease transform; - } - .draggable-item.is-draggable { - z-index: 10; - } - ` -}); - -export class DraggableList extends EventTarget { - listContainer; - draggableItem; - pointerStartX; - pointerStartY; - scrollYMax; - itemsGap = 0; - items = []; - itemSelector; - handleClass = "drag-handle"; - off = []; - offDrag = []; - - constructor(element, itemSelector) { - super(); - this.listContainer = element; - this.itemSelector = itemSelector; - - if (!this.listContainer) return; - - this.off.push(this.on(this.listContainer, "mousedown", this.dragStart)); - this.off.push(this.on(this.listContainer, "touchstart", this.dragStart)); - this.off.push(this.on(document, "mouseup", this.dragEnd)); - this.off.push(this.on(document, "touchend", this.dragEnd)); - } - - getAllItems() { - if (!this.items?.length) { - this.items = Array.from(this.listContainer.querySelectorAll(this.itemSelector)); - this.items.forEach((element) => { - element.classList.add("is-idle"); - }); - } - return this.items; - } - - getIdleItems() { - return this.getAllItems().filter((item) => item.classList.contains("is-idle")); - } - - isItemAbove(item) { - return item.hasAttribute("data-is-above"); - } - - isItemToggled(item) { - return item.hasAttribute("data-is-toggled"); - } - - on(source, event, listener, options) { - listener = listener.bind(this); - source.addEventListener(event, listener, options); - return () => source.removeEventListener(event, listener); - } - - dragStart(e) { - if (e.target.classList.contains(this.handleClass)) { - this.draggableItem = e.target.closest(this.itemSelector); - } - - if (!this.draggableItem) return; - - this.pointerStartX = e.clientX || e.touches[0].clientX; - this.pointerStartY = e.clientY || e.touches[0].clientY; - this.scrollYMax = this.listContainer.scrollHeight - this.listContainer.clientHeight; - - this.setItemsGap(); - this.initDraggableItem(); - this.initItemsState(); - - this.offDrag.push(this.on(document, "mousemove", this.drag)); - this.offDrag.push(this.on(document, "touchmove", this.drag, { passive: false })); - - this.dispatchEvent( - new CustomEvent("dragstart", { - detail: { element: this.draggableItem, position: this.getAllItems().indexOf(this.draggableItem) }, - }) - ); - } - - setItemsGap() { - if (this.getIdleItems().length <= 1) { - this.itemsGap = 0; - return; - } - - const item1 = this.getIdleItems()[0]; - const item2 = this.getIdleItems()[1]; - - const item1Rect = item1.getBoundingClientRect(); - const item2Rect = item2.getBoundingClientRect(); - - this.itemsGap = Math.abs(item1Rect.bottom - item2Rect.top); - } - - initItemsState() { - this.getIdleItems().forEach((item, i) => { - if (this.getAllItems().indexOf(this.draggableItem) > i) { - item.dataset.isAbove = ""; - } - }); - } - - initDraggableItem() { - this.draggableItem.classList.remove("is-idle"); - this.draggableItem.classList.add("is-draggable"); - } - - drag(e) { - if (!this.draggableItem) return; - - e.preventDefault(); - - const clientX = e.clientX || e.touches[0].clientX; - const clientY = e.clientY || e.touches[0].clientY; - - const listRect = this.listContainer.getBoundingClientRect(); - - if (clientY > listRect.bottom) { - if (this.listContainer.scrollTop < this.scrollYMax) { - this.listContainer.scrollBy(0, 10); - this.pointerStartY -= 10; - } - } else if (clientY < listRect.top && this.listContainer.scrollTop > 0) { - this.pointerStartY += 10; - this.listContainer.scrollBy(0, -10); - } - - const pointerOffsetX = clientX - this.pointerStartX; - const pointerOffsetY = clientY - this.pointerStartY; - - this.updateIdleItemsStateAndPosition(); - this.draggableItem.style.transform = `translate(${pointerOffsetX}px, ${pointerOffsetY}px)`; - } - - updateIdleItemsStateAndPosition() { - const draggableItemRect = this.draggableItem.getBoundingClientRect(); - const draggableItemY = draggableItemRect.top + draggableItemRect.height / 2; - - // Update state - this.getIdleItems().forEach((item) => { - const itemRect = item.getBoundingClientRect(); - const itemY = itemRect.top + itemRect.height / 2; - if (this.isItemAbove(item)) { - if (draggableItemY <= itemY) { - item.dataset.isToggled = ""; - } else { - delete item.dataset.isToggled; - } - } else { - if (draggableItemY >= itemY) { - item.dataset.isToggled = ""; - } else { - delete item.dataset.isToggled; - } - } - }); - - // Update position - this.getIdleItems().forEach((item) => { - if (this.isItemToggled(item)) { - const direction = this.isItemAbove(item) ? 1 : -1; - item.style.transform = `translateY(${direction * (draggableItemRect.height + this.itemsGap)}px)`; - } else { - item.style.transform = ""; - } - }); - } - - dragEnd() { - if (!this.draggableItem) return; - - this.applyNewItemsOrder(); - this.cleanup(); - } - - applyNewItemsOrder() { - const reorderedItems = []; - - let oldPosition = -1; - this.getAllItems().forEach((item, index) => { - if (item === this.draggableItem) { - oldPosition = index; - return; - } - if (!this.isItemToggled(item)) { - reorderedItems[index] = item; - return; - } - const newIndex = this.isItemAbove(item) ? index + 1 : index - 1; - reorderedItems[newIndex] = item; - }); - - for (let index = 0; index < this.getAllItems().length; index++) { - const item = reorderedItems[index]; - if (typeof item === "undefined") { - reorderedItems[index] = this.draggableItem; - } - } - - reorderedItems.forEach((item) => { - this.listContainer.appendChild(item); - }); - - this.items = reorderedItems; - - this.dispatchEvent( - new CustomEvent("dragend", { - detail: { element: this.draggableItem, oldPosition, newPosition: reorderedItems.indexOf(this.draggableItem) }, - }) - ); - } - - cleanup() { - this.itemsGap = 0; - this.items = []; - this.unsetDraggableItem(); - this.unsetItemState(); - - this.offDrag.forEach((f) => f()); - this.offDrag = []; - } - - unsetDraggableItem() { - this.draggableItem.style = null; - this.draggableItem.classList.remove("is-draggable"); - this.draggableItem.classList.add("is-idle"); - this.draggableItem = null; - } - - unsetItemState() { - this.getIdleItems().forEach((item, i) => { - delete item.dataset.isAbove; - delete item.dataset.isToggled; - item.style.transform = ""; - }); - } - - dispose() { - this.off.forEach((f) => f()); - } -} +// Shim for scripts\ui\draggableList.ts +export const DraggableList = window.comfyAPI.draggableList.DraggableList; diff --git a/web/scripts/ui/imagePreview.js b/web/scripts/ui/imagePreview.js index 2a7f66b8f..2c2d7e842 100644 --- a/web/scripts/ui/imagePreview.js +++ b/web/scripts/ui/imagePreview.js @@ -1,97 +1,3 @@ -import { $el } from "../ui.js"; - -export function calculateImageGrid(imgs, dw, dh) { - let best = 0; - let w = imgs[0].naturalWidth; - let h = imgs[0].naturalHeight; - const numImages = imgs.length; - - let cellWidth, cellHeight, cols, rows, shiftX; - // compact style - for (let c = 1; c <= numImages; c++) { - const r = Math.ceil(numImages / c); - const cW = dw / c; - const cH = dh / r; - const scaleX = cW / w; - const scaleY = cH / h; - - const scale = Math.min(scaleX, scaleY, 1); - const imageW = w * scale; - const imageH = h * scale; - const area = imageW * imageH * numImages; - - if (area > best) { - best = area; - cellWidth = imageW; - cellHeight = imageH; - cols = c; - rows = r; - shiftX = c * ((cW - imageW) / 2); - } - } - - return { cellWidth, cellHeight, cols, rows, shiftX }; -} - -export function createImageHost(node) { - const el = $el("div.comfy-img-preview"); - let currentImgs; - let first = true; - - function updateSize() { - let w = null; - let h = null; - - if (currentImgs) { - let elH = el.clientHeight; - if (first) { - first = false; - // On first run, if we are small then grow a bit - if (elH < 190) { - elH = 190; - } - el.style.setProperty("--comfy-widget-min-height", elH); - } else { - el.style.setProperty("--comfy-widget-min-height", null); - } - - const nw = node.size[0]; - ({ cellWidth: w, cellHeight: h } = calculateImageGrid(currentImgs, nw - 20, elH)); - w += "px"; - h += "px"; - - el.style.setProperty("--comfy-img-preview-width", w); - el.style.setProperty("--comfy-img-preview-height", h); - } - } - return { - el, - updateImages(imgs) { - if (imgs !== currentImgs) { - if (currentImgs == null) { - requestAnimationFrame(() => { - updateSize(); - }); - } - el.replaceChildren(...imgs); - currentImgs = imgs; - node.onResize(node.size); - node.graph.setDirtyCanvas(true, true); - } - }, - getHeight() { - updateSize(); - }, - onDraw() { - // Element from point uses a hittest find elements so we need to toggle pointer events - el.style.pointerEvents = "all"; - const over = document.elementFromPoint(app.canvas.mouse[0], app.canvas.mouse[1]); - el.style.pointerEvents = "none"; - - if(!over) return; - // Set the overIndex so Open Image etc work - const idx = currentImgs.indexOf(over); - node.overIndex = idx; - }, - }; -} +// Shim for scripts\ui\imagePreview.ts +export const calculateImageGrid = window.comfyAPI.imagePreview.calculateImageGrid; +export const createImageHost = window.comfyAPI.imagePreview.createImageHost; diff --git a/web/scripts/ui/menu/index.js b/web/scripts/ui/menu/index.js index 1e00b3d22..d1c06a455 100644 --- a/web/scripts/ui/menu/index.js +++ b/web/scripts/ui/menu/index.js @@ -1,302 +1,2 @@ -// @ts-check - -import { $el } from "../../ui.js"; -import { downloadBlob } from "../../utils.js"; -import { ComfyButton } from "../components/button.js"; -import { ComfyButtonGroup } from "../components/buttonGroup.js"; -import { ComfySplitButton } from "../components/splitButton.js"; -import { ComfyViewHistoryButton } from "./viewHistory.js"; -import { ComfyQueueButton } from "./queueButton.js"; -import { ComfyWorkflowsMenu } from "./workflows.js"; -import { ComfyViewQueueButton } from "./viewQueue.js"; -import { getInteruptButton } from "./interruptButton.js"; - -const collapseOnMobile = (t) => { - (t.element ?? t).classList.add("comfyui-menu-mobile-collapse"); - return t; -}; -const showOnMobile = (t) => { - (t.element ?? t).classList.add("lt-lg-show"); - return t; -}; - -export class ComfyAppMenu { - #sizeBreak = "lg"; - #lastSizeBreaks = { - lg: null, - md: null, - sm: null, - xs: null, - }; - #sizeBreaks = Object.keys(this.#lastSizeBreaks); - #cachedInnerSize = null; - #cacheTimeout = null; - - /** - * @param { import("../../app.js").ComfyApp } app - */ - constructor(app) { - this.app = app; - - this.workflows = new ComfyWorkflowsMenu(app); - const getSaveButton = (t) => - new ComfyButton({ - icon: "content-save", - tooltip: "Save the current workflow", - action: () => app.workflowManager.activeWorkflow.save(), - content: t, - }); - - this.logo = $el("h1.comfyui-logo.nlg-hide", { title: "ComfyUI" }, "ComfyUI"); - this.saveButton = new ComfySplitButton( - { - primary: getSaveButton(), - mode: "hover", - position: "absolute", - }, - getSaveButton("Save"), - new ComfyButton({ - icon: "content-save-edit", - content: "Save As", - tooltip: "Save the current graph as a new workflow", - action: () => app.workflowManager.activeWorkflow.save(true), - }), - new ComfyButton({ - icon: "download", - content: "Export", - tooltip: "Export the current workflow as JSON", - action: () => this.exportWorkflow("workflow", "workflow"), - }), - new ComfyButton({ - icon: "api", - content: "Export (API Format)", - tooltip: "Export the current workflow as JSON for use with the ComfyUI API", - action: () => this.exportWorkflow("workflow_api", "output"), - visibilitySetting: { id: "Comfy.DevMode", showValue: true }, - app, - }) - ); - this.actionsGroup = new ComfyButtonGroup( - new ComfyButton({ - icon: "refresh", - content: "Refresh", - tooltip: "Refresh widgets in nodes to find new models or files", - action: () => app.refreshComboInNodes(), - }), - new ComfyButton({ - icon: "clipboard-edit-outline", - content: "Clipspace", - tooltip: "Open Clipspace window", - action: () => app["openClipspace"](), - }), - new ComfyButton({ - icon: "fit-to-page-outline", - content: "Reset View", - tooltip: "Reset the canvas view", - action: () => app.resetView(), - }), - new ComfyButton({ - icon: "cancel", - content: "Clear", - tooltip: "Clears current workflow", - action: () => { - if (!app.ui.settings.getSettingValue("Comfy.ConfirmClear", true) || confirm("Clear workflow?")) { - app.clean(); - app.graph.clear(); - } - }, - }) - ); - this.settingsGroup = new ComfyButtonGroup( - new ComfyButton({ - icon: "cog", - content: "Settings", - tooltip: "Open settings", - action: () => { - app.ui.settings.show(); - }, - }) - ); - this.viewGroup = new ComfyButtonGroup( - new ComfyViewHistoryButton(app).element, - new ComfyViewQueueButton(app).element, - getInteruptButton("nlg-hide").element - ); - this.mobileMenuButton = new ComfyButton({ - icon: "menu", - action: (_, btn) => { - btn.icon = this.element.classList.toggle("expanded") ? "menu-open" : "menu"; - window.dispatchEvent(new Event("resize")); - }, - classList: "comfyui-button comfyui-menu-button", - }); - - this.element = $el("nav.comfyui-menu.lg", { style: { display: "none" } }, [ - this.logo, - this.workflows.element, - this.saveButton.element, - collapseOnMobile(this.actionsGroup).element, - $el("section.comfyui-menu-push"), - collapseOnMobile(this.settingsGroup).element, - collapseOnMobile(this.viewGroup).element, - - getInteruptButton("lt-lg-show").element, - new ComfyQueueButton(app).element, - showOnMobile(this.mobileMenuButton).element, - ]); - - let resizeHandler; - this.menuPositionSetting = app.ui.settings.addSetting({ - id: "Comfy.UseNewMenu", - defaultValue: "Disabled", - name: "[Beta] Use new menu and workflow management. Note: On small screens the menu will always be at the top.", - type: "combo", - options: ["Disabled", "Top", "Bottom"], - onChange: async (v) => { - if (v && v !== "Disabled") { - if (!resizeHandler) { - resizeHandler = () => { - this.calculateSizeBreak(); - }; - window.addEventListener("resize", resizeHandler); - } - this.updatePosition(v); - } else { - if (resizeHandler) { - window.removeEventListener("resize", resizeHandler); - resizeHandler = null; - } - document.body.style.removeProperty("display"); - app.ui.menuContainer.style.removeProperty("display"); - this.element.style.display = "none"; - app.ui.restoreMenuPosition(); - } - window.dispatchEvent(new Event("resize")); - }, - }); - } - - updatePosition(v) { - document.body.style.display = "grid"; - this.app.ui.menuContainer.style.display = "none"; - this.element.style.removeProperty("display"); - this.position = v; - if (v === "Bottom") { - this.app.bodyBottom.append(this.element); - } else { - this.app.bodyTop.prepend(this.element); - } - this.calculateSizeBreak(); - } - - updateSizeBreak(idx, prevIdx, direction) { - const newSize = this.#sizeBreaks[idx]; - if (newSize === this.#sizeBreak) return; - this.#cachedInnerSize = null; - clearTimeout(this.#cacheTimeout); - - this.#sizeBreak = this.#sizeBreaks[idx]; - for (let i = 0; i < this.#sizeBreaks.length; i++) { - const sz = this.#sizeBreaks[i]; - if (sz === this.#sizeBreak) { - this.element.classList.add(sz); - } else { - this.element.classList.remove(sz); - } - if (i < idx) { - this.element.classList.add("lt-" + sz); - } else { - this.element.classList.remove("lt-" + sz); - } - } - - if (idx) { - // We're on a small screen, force the menu at the top - if (this.position !== "Top") { - this.updatePosition("Top"); - } - } else if (this.position != this.menuPositionSetting.value) { - // Restore user position - this.updatePosition(this.menuPositionSetting.value); - } - - // Allow multiple updates, but prevent bouncing - if (!direction) { - direction = prevIdx - idx; - } else if (direction != prevIdx - idx) { - return; - } - this.calculateSizeBreak(direction); - } - - calculateSizeBreak(direction = 0) { - let idx = this.#sizeBreaks.indexOf(this.#sizeBreak); - const currIdx = idx; - const innerSize = this.calculateInnerSize(idx); - if (window.innerWidth >= this.#lastSizeBreaks[this.#sizeBreaks[idx - 1]]) { - if (idx > 0) { - idx--; - } - } else if (innerSize > this.element.clientWidth) { - this.#lastSizeBreaks[this.#sizeBreak] = Math.max(window.innerWidth, innerSize); - // We need to shrink - if (idx < this.#sizeBreaks.length - 1) { - idx++; - } - } - - this.updateSizeBreak(idx, currIdx, direction); - } - - calculateInnerSize(idx) { - // Cache the inner size to prevent too much calculation when resizing the window - clearTimeout(this.#cacheTimeout); - if (this.#cachedInnerSize) { - // Extend cache time - this.#cacheTimeout = setTimeout(() => (this.#cachedInnerSize = null), 100); - } else { - let innerSize = 0; - let count = 1; - for (const c of this.element.children) { - if (c.classList.contains("comfyui-menu-push")) continue; // ignore right push - if (idx && c.classList.contains("comfyui-menu-mobile-collapse")) continue; // ignore collapse items - innerSize += c.clientWidth; - count++; - } - innerSize += 8 * count; - this.#cachedInnerSize = innerSize; - this.#cacheTimeout = setTimeout(() => (this.#cachedInnerSize = null), 100); - } - return this.#cachedInnerSize; - } - - /** - * @param {string} defaultName - */ - getFilename(defaultName) { - if (this.app.ui.settings.getSettingValue("Comfy.PromptFilename", true)) { - defaultName = prompt("Save workflow as:", defaultName); - if (!defaultName) return; - if (!defaultName.toLowerCase().endsWith(".json")) { - defaultName += ".json"; - } - } - return defaultName; - } - - /** - * @param {string} [filename] - * @param { "workflow" | "output" } [promptProperty] - */ - async exportWorkflow(filename, promptProperty) { - if (this.app.workflowManager.activeWorkflow?.path) { - filename = this.app.workflowManager.activeWorkflow.name; - } - const p = await this.app.graphToPrompt(); - const json = JSON.stringify(p[promptProperty], null, 2); - const blob = new Blob([json], { type: "application/json" }); - const file = this.getFilename(filename); - if (!file) return; - downloadBlob(file, blob); - } -} +// Shim for scripts\ui\menu\index.ts +export const ComfyAppMenu = window.comfyAPI.index.ComfyAppMenu; diff --git a/web/scripts/ui/menu/interruptButton.js b/web/scripts/ui/menu/interruptButton.js index 4db3328db..23da3b44a 100644 --- a/web/scripts/ui/menu/interruptButton.js +++ b/web/scripts/ui/menu/interruptButton.js @@ -1,23 +1,2 @@ -// @ts-check - -import { api } from "../../api.js"; -import { ComfyButton } from "../components/button.js"; - -export function getInteruptButton(visibility) { - const btn = new ComfyButton({ - icon: "close", - tooltip: "Cancel current generation", - enabled: false, - action: () => { - api.interrupt(); - }, - classList: ["comfyui-button", "comfyui-interrupt-button", visibility], - }); - - api.addEventListener("status", ({ detail }) => { - const sz = detail?.exec_info?.queue_remaining; - btn.enabled = sz > 0; - }); - - return btn; -} +// Shim for scripts\ui\menu\interruptButton.ts +export const getInterruptButton = window.comfyAPI.interruptButton.getInterruptButton; diff --git a/web/scripts/ui/menu/menu.css b/web/scripts/ui/menu/menu.css deleted file mode 100644 index 1d8b9ad0a..000000000 --- a/web/scripts/ui/menu/menu.css +++ /dev/null @@ -1,710 +0,0 @@ -.relative { - position: relative; -} -.hidden { - display: none !important; -} -.mdi.rotate270::before { - transform: rotate(270deg); -} - -/* Generic */ -.comfyui-button { - display: flex; - align-items: center; - gap: 0.5em; - cursor: pointer; - border: none; - border-radius: 4px; - padding: 4px 8px; - box-sizing: border-box; - margin: 0; - transition: box-shadow 0.1s; -} - -.comfyui-button:active { - box-shadow: inset 1px 1px 10px rgba(0, 0, 0, 0.5); -} -.comfyui-button:disabled { - opacity: 0.5; - cursor: not-allowed; -} -.primary .comfyui-button, -.primary.comfyui-button { - background-color: var(--primary-bg) !important; - color: var(--primary-fg) !important; -} - -.primary .comfyui-button:not(:disabled):hover, -.primary.comfyui-button:not(:disabled):hover { - background-color: var(--primary-hover-bg) !important; - color: var(--primary-hover-fg) !important; -} - -/* Popup */ -.comfyui-popup { - position: absolute; - left: var(--left); - right: var(--right); - top: var(--top); - bottom: var(--bottom); - z-index: 2000; - max-height: calc(100vh - var(--limit) - 10px); - box-shadow: 3px 3px 5px 0px rgba(0, 0, 0, 0.3); -} - -.comfyui-popup:not(.open) { - display: none; -} - -.comfyui-popup.right.open { - border-top-left-radius: 4px; - border-bottom-right-radius: 4px; - border-bottom-left-radius: 4px; - overflow: hidden; -} -/* Split button */ -.comfyui-split-button { - position: relative; - display: flex; -} - -.comfyui-split-primary { - flex: auto; -} - -.comfyui-split-primary .comfyui-button { - border-top-right-radius: 0; - border-bottom-right-radius: 0; - border-right: 1px solid var(--comfy-menu-bg); - width: 100%; -} - -.comfyui-split-arrow .comfyui-button { - border-top-left-radius: 0; - border-bottom-left-radius: 0; - padding-left: 2px; - padding-right: 2px; -} - -.comfyui-split-button-popup { - white-space: nowrap; - background-color: var(--content-bg); - color: var(--content-fg); - display: flex; - flex-direction: column; - overflow: auto; -} - -.comfyui-split-button-popup.hover { - z-index: 2001; -} -.comfyui-split-button-popup > .comfyui-button { - border: none; - background-color: transparent; - color: var(--fg-color); - padding: 8px 12px 8px 8px; -} - -.comfyui-split-button-popup > .comfyui-button:not(:disabled):hover { - background-color: var(--comfy-input-bg); -} - -/* Button group */ -.comfyui-button-group { - display: flex; - border-radius: 4px; - overflow: hidden; -} - -.comfyui-button-group > .comfyui-button, -.comfyui-button-group > .comfyui-button-wrapper > .comfyui-button { - padding: 4px 10px; - border-radius: 0; -} - -/* Menu */ -.comfyui-menu { - width: 100vw; - background: var(--comfy-menu-bg); - color: var(--fg-color); - font-family: Arial, Helvetica, sans-serif; - font-size: 0.8em; - display: flex; - padding: 4px 8px; - align-items: center; - gap: 8px; - box-sizing: border-box; - z-index: 1000; - order: 0; - grid-column: 1/-1; - overflow: auto; - max-height: 90vh; -} - -.comfyui-menu>* { - flex-shrink: 0; -} -.comfyui-menu .mdi::before { - font-size: 18px; -} - -.comfyui-menu .comfyui-button { - background: var(--comfy-input-bg); - color: var(--fg-color); - white-space: nowrap; -} - -.comfyui-menu .comfyui-button:not(:disabled):hover { - background: var(--border-color); - color: var(--content-fg); -} - -.comfyui-menu .comfyui-split-button-popup > .comfyui-button { - border-radius: 0; - background-color: transparent; -} - -.comfyui-menu .comfyui-split-button-popup > .comfyui-button:not(:disabled):hover { - background-color: var(--comfy-input-bg); -} - -.comfyui-menu .comfyui-split-button-popup.left { - border-top-right-radius: 4px; - border-bottom-left-radius: 4px; - border-bottom-right-radius: 4px; -} - -.comfyui-menu .comfyui-button.popup-open { - background-color: var(--content-bg); - color: var(--content-fg); -} - -.comfyui-menu-push { - margin-left: -0.8em; - flex: auto; -} - -.comfyui-logo { - font-size: 1.2em; - margin: 0; - user-select: none; - cursor: default; -} - -/* Workflows */ -.comfyui-workflows-button { - flex-direction: row-reverse; - max-width: 200px; - position: relative; - z-index: 0; -} - -.comfyui-workflows-button.popup-open { - border-bottom-left-radius: 0; - border-bottom-right-radius: 0; -} -.comfyui-workflows-button.unsaved { - font-style: italic; -} -.comfyui-workflows-button-progress { - position: absolute; - top: 0; - left: 0; - background-color: green; - height: 100%; - border-radius: 4px; - z-index: -1; -} - -.comfyui-workflows-button > span { - flex: auto; - text-align: left; - overflow: hidden; -} -.comfyui-workflows-button-inner { - display: flex; - align-items: center; - gap: 7px; - width: 150px; -} -.comfyui-workflows-label { - overflow: hidden; - text-overflow: ellipsis; - direction: rtl; - flex: auto; - position: relative; -} - -.comfyui-workflows-button.unsaved .comfyui-workflows-label { - padding-left: 8px; -} - -.comfyui-workflows-button.unsaved .comfyui-workflows-label:after { - content: "*"; - position: absolute; - top: 0; - left: 0; -} -.comfyui-workflows-button-inner .mdi-graph::before { - transform: rotate(-90deg); -} - -.comfyui-workflows-popup { - font-family: Arial, Helvetica, sans-serif; - font-size: 0.8em; - padding: 10px; - overflow: auto; - background-color: var(--content-bg); - color: var(--content-fg); - border-top-right-radius: 4px; - border-bottom-right-radius: 4px; - border-bottom-left-radius: 4px; - z-index: 400; -} - -.comfyui-workflows-panel { - min-height: 150px; -} - -.comfyui-workflows-panel .lds-ring { - transform: translate(-50%); - position: absolute; - left: 50%; - top: 75px; -} - -.comfyui-workflows-panel h3 { - margin: 10px 0 10px 0; - font-size: 11px; - opacity: 0.8; -} - -.comfyui-workflows-panel section header { - display: flex; - justify-content: space-between; - align-items: center; -} -.comfy-ui-workflows-search .mdi { - position: relative; - top: 2px; - pointer-events: none; -} -.comfy-ui-workflows-search input { - background-color: var(--comfy-input-bg); - color: var(--input-text); - border: none; - border-radius: 4px; - padding: 4px 10px; - margin-left: -24px; - text-indent: 18px; -} -.comfy-ui-workflows-search input:placeholder-shown { - width: 10px; -} -.comfy-ui-workflows-search input:placeholder-shown:focus { - width: auto; -} -.comfyui-workflows-actions { - display: flex; - gap: 10px; - margin-bottom: 10px; -} - -.comfyui-workflows-actions .comfyui-button { - background: var(--comfy-input-bg); - color: var(--input-text); -} - -.comfyui-workflows-actions .comfyui-button:not(:disabled):hover { - background: var(--primary-bg); - color: var(--primary-fg); -} - -.comfyui-workflows-favorites, -.comfyui-workflows-open { - border-bottom: 1px solid var(--comfy-input-bg); - padding-bottom: 5px; - margin-bottom: 5px; -} - -.comfyui-workflows-open .active { - font-weight: bold; - color: var(--primary-fg); -} - -.comfyui-workflows-favorites:empty { - display: none; -} - -.comfyui-workflows-tree { - padding: 0; - margin: 0; -} - -.comfyui-workflows-tree:empty::after { - content: "No saved workflows"; - display: block; - text-align: center; -} -.comfyui-workflows-tree > ul { - padding: 0; -} - -.comfyui-workflows-tree > ul ul { - margin: 0; - padding: 0 0 0 25px; -} - -.comfyui-workflows-tree:not(.filtered) .closed > ul { - display: none; -} - -.comfyui-workflows-tree li, -.comfyui-workflows-tree-file { - --item-height: 32px; - list-style-type: none; - height: var(--item-height); - display: flex; - align-items: center; - gap: 5px; - cursor: pointer; - user-select: none; -} - -.comfyui-workflows-tree-file.active::before, -.comfyui-workflows-tree li:hover::before, -.comfyui-workflows-tree-file:hover::before { - content: ""; - position: absolute; - width: 100%; - left: 0; - height: var(--item-height); - background-color: var(--content-hover-bg); - color: var(--content-hover-fg); - z-index: -1; -} - -.comfyui-workflows-tree-file.active::before { - background-color: var(--primary-bg); - color: var(--primary-fg); -} - -.comfyui-workflows-tree-file.running:not(:hover)::before { - content: ""; - position: absolute; - width: var(--progress, 0); - left: 0; - height: var(--item-height); - background-color: green; - z-index: -1; -} - -.comfyui-workflows-tree-file.unsaved span { - font-style: italic; -} - -.comfyui-workflows-tree-file span { - flex: auto; -} - -.comfyui-workflows-tree-file span + .comfyui-workflows-file-action { - margin-left: 10px; -} - -.comfyui-workflows-tree-file .comfyui-workflows-file-action { - background-color: transparent; - color: var(--fg-color); - padding: 2px 4px; -} - -.comfyui-workflows-tree-file.active .comfyui-workflows-file-action { - color: var(--primary-fg); -} - -.lg ~ .comfyui-workflows-popup .comfyui-workflows-tree-file:not(:hover) .comfyui-workflows-file-action { - opacity: 0; -} - -.comfyui-workflows-tree-file .comfyui-workflows-file-action:hover { - background-color: var(--primary-bg); - color: var(--primary-fg); -} - -.comfyui-workflows-tree-file .comfyui-workflows-file-action-primary { - background-color: transparent; - color: var(--fg-color); - padding: 2px 4px; - margin: 0 -4px; -} - -.comfyui-workflows-file-action-favorite .mdi-star { - color: orange; -} - -/* View List */ -.comfyui-view-list-popup { - padding: 10px; - background-color: var(--content-bg); - color: var(--content-fg); - min-width: 170px; - min-height: 435px; - display: flex; - flex-direction: column; - align-items: center; - box-sizing: border-box; -} -.comfyui-view-list-popup h3 { - margin: 0 0 5px 0; -} -.comfyui-view-list-items { - width: 100%; - background: var(--comfy-menu-bg); - border-radius: 5px; - display: flex; - justify-content: center; - flex: auto; - align-items: center; - flex-direction: column; -} -.comfyui-view-list-items section { - max-height: 400px; - overflow: auto; - width: 100%; - display: grid; - grid-template-columns: auto auto auto; - align-items: center; - justify-content: center; - gap: 5px; - padding: 5px 0; -} -.comfyui-view-list-items section + section { - border-top: 1px solid var(--border-color); - margin-top: 10px; - padding-top: 5px; -} -.comfyui-view-list-items section h5 { - grid-column: 1 / 4; - text-align: center; - margin: 5px; -} -.comfyui-view-list-items span { - text-align: center; - padding: 0 2px; -} -.comfyui-view-list-popup header { - margin-bottom: 10px; - display: flex; - gap: 5px; -} -.comfyui-view-list-popup header .comfyui-button { - border: 1px solid transparent; -} -.comfyui-view-list-popup header .comfyui-button:not(:disabled):hover { - border: 1px solid var(--comfy-menu-bg); -} -/* Queue button */ -.comfyui-queue-button .comfyui-split-primary .comfyui-button { - padding-right: 12px; -} -.comfyui-queue-count { - margin-left: 5px; - border-radius: 10px; - background-color: rgb(8, 80, 153); - padding: 2px 4px; - font-size: 10px; - min-width: 1em; - display: inline-block; -} -/* Queue options*/ -.comfyui-queue-options { - padding: 10px; - font-family: Arial, Helvetica, sans-serif; - font-size: 12px; - display: flex; - gap: 10px; -} - -.comfyui-queue-batch { - display: flex; - flex-direction: column; - border-right: 1px solid var(--comfy-menu-bg); - padding-right: 10px; - gap: 5px; -} - -.comfyui-queue-batch input { - width: 145px; -} - -.comfyui-queue-batch .comfyui-queue-batch-value { - width: 70px; -} - -.comfyui-queue-mode { - display: flex; - flex-direction: column; -} - -.comfyui-queue-mode span { - font-weight: bold; - margin-bottom: 2px; -} - -.comfyui-queue-mode label { - display: flex; - flex-direction: row-reverse; - justify-content: start; - gap: 5px; - padding: 2px 0; -} - -.comfyui-queue-mode label input { - padding: 0; - margin: 0; -} - -/** Send to workflow widget selection dialog */ -.comfy-widget-selection-dialog { - border: none; -} - -.comfy-widget-selection-dialog div { - color: var(--fg-color); - font-family: Arial, Helvetica, sans-serif; -} - -.comfy-widget-selection-dialog h2 { - margin-top: 0; -} - -.comfy-widget-selection-dialog section { - width: fit-content; - display: flex; - flex-direction: column; -} - -.comfy-widget-selection-item { - display: flex; - gap: 10px; - align-items: center; -} - -.comfy-widget-selection-item span { - margin-right: auto; -} - -.comfy-widget-selection-item span::before { - content: '#' attr(data-id); - opacity: 0.5; - margin-right: 5px; -} - -.comfy-modal .comfy-widget-selection-item button { - font-size: 1em; -} - -/***** Responsive *****/ -.lg.comfyui-menu .lt-lg-show { - display: none !important; -} -.comfyui-menu:not(.lg) .nlg-hide { - display: none !important; -} -/** Large screen */ -.lg.comfyui-menu>.comfyui-menu-mobile-collapse .comfyui-button span, -.lg.comfyui-menu>.comfyui-menu-mobile-collapse.comfyui-button span { - display: none; -} -.lg.comfyui-menu>.comfyui-menu-mobile-collapse .comfyui-popup .comfyui-button span { - display: unset; -} - -/** Non large screen */ -.lt-lg.comfyui-menu { - flex-wrap: wrap; -} - -.lt-lg.comfyui-menu > *:not(.comfyui-menu-mobile-collapse) { - order: 1; -} - -.lt-lg.comfyui-menu > .comfyui-menu-mobile-collapse { - order: 9999; - width: 100%; -} - -.comfyui-body-bottom .lt-lg.comfyui-menu > .comfyui-menu-mobile-collapse { - order: -1; -} - -.comfyui-body-bottom .lt-lg.comfyui-menu > .comfyui-menu-button { - top: unset; - bottom: 4px; -} - -.lt-lg.comfyui-menu > .comfyui-menu-mobile-collapse.comfyui-button-group { - flex-wrap: wrap; -} - -.lt-lg.comfyui-menu > .comfyui-menu-mobile-collapse .comfyui-button, -.lt-lg.comfyui-menu > .comfyui-menu-mobile-collapse.comfyui-button { - padding: 10px; -} -.lt-lg.comfyui-menu > .comfyui-menu-mobile-collapse .comfyui-button, -.lt-lg.comfyui-menu > .comfyui-menu-mobile-collapse .comfyui-button-wrapper { - width: 100%; -} - -.lt-lg.comfyui-menu > .comfyui-menu-mobile-collapse .comfyui-popup { - position: static; - background-color: var(--comfy-input-bg); - max-width: unset; - max-height: 50vh; - overflow: auto; -} - -.lt-lg.comfyui-menu:not(.expanded) > .comfyui-menu-mobile-collapse { - display: none; -} - -.lt-lg .comfyui-queue-button { - margin-right: 44px; -} - -.lt-lg .comfyui-menu-button { - position: absolute; - top: 4px; - right: 8px; -} - -.lt-lg.comfyui-menu > .comfyui-menu-mobile-collapse .comfyui-view-list-popup { - border-radius: 0; -} - -.lt-lg.comfyui-menu .comfyui-workflows-popup { - width: 100vw; -} - -/** Small */ -.lt-md .comfyui-workflows-button-inner { - width: unset !important; -} -.lt-md .comfyui-workflows-label { - display: none; -} - -/** Extra small */ -.lt-sm .comfyui-queue-button { - margin-right: 0; - width: 100%; -} -.lt-sm .comfyui-queue-button .comfyui-button { - justify-content: center; -} -.lt-sm .comfyui-interrupt-button { - margin-right: 45px; -} -.comfyui-body-bottom .lt-sm.comfyui-menu > .comfyui-menu-button{ - bottom: 41px; -} \ No newline at end of file diff --git a/web/scripts/ui/menu/queueButton.js b/web/scripts/ui/menu/queueButton.js index 608f4cc9b..38df59112 100644 --- a/web/scripts/ui/menu/queueButton.js +++ b/web/scripts/ui/menu/queueButton.js @@ -1,93 +1,2 @@ -// @ts-check - -import { ComfyButton } from "../components/button.js"; -import { $el } from "../../ui.js"; -import { api } from "../../api.js"; -import { ComfySplitButton } from "../components/splitButton.js"; -import { ComfyQueueOptions } from "./queueOptions.js"; -import { prop } from "../../utils.js"; - -export class ComfyQueueButton { - element = $el("div.comfyui-queue-button"); - #internalQueueSize = 0; - - queuePrompt = async (e) => { - this.#internalQueueSize += this.queueOptions.batchCount; - // Hold shift to queue front, event is undefined when auto-queue is enabled - await this.app.queuePrompt(e?.shiftKey ? -1 : 0, this.queueOptions.batchCount); - }; - - constructor(app) { - this.app = app; - this.queueSizeElement = $el("span.comfyui-queue-count", { - textContent: "?", - }); - - const queue = new ComfyButton({ - content: $el("div", [ - $el("span", { - textContent: "Queue", - }), - this.queueSizeElement, - ]), - icon: "play", - classList: "comfyui-button", - action: this.queuePrompt, - }); - - this.queueOptions = new ComfyQueueOptions(app); - - const btn = new ComfySplitButton( - { - primary: queue, - mode: "click", - position: "absolute", - horizontal: "right", - }, - this.queueOptions.element - ); - btn.element.classList.add("primary"); - this.element.append(btn.element); - - this.autoQueueMode = prop(this, "autoQueueMode", "", () => { - switch (this.autoQueueMode) { - case "instant": - queue.icon = "infinity"; - break; - case "change": - queue.icon = "auto-mode"; - break; - default: - queue.icon = "play"; - break; - } - }); - - this.queueOptions.addEventListener("autoQueueMode", (e) => (this.autoQueueMode = e["detail"])); - - api.addEventListener("graphChanged", () => { - if (this.autoQueueMode === "change") { - if (this.#internalQueueSize) { - this.graphHasChanged = true; - } else { - this.graphHasChanged = false; - this.queuePrompt(); - } - } - }); - - api.addEventListener("status", ({ detail }) => { - this.#internalQueueSize = detail?.exec_info?.queue_remaining; - if (this.#internalQueueSize != null) { - this.queueSizeElement.textContent = this.#internalQueueSize > 99 ? "99+" : this.#internalQueueSize + ""; - this.queueSizeElement.title = `${this.#internalQueueSize} prompts in queue`; - if (!this.#internalQueueSize && !app.lastExecutionError) { - if (this.autoQueueMode === "instant" || (this.autoQueueMode === "change" && this.graphHasChanged)) { - this.graphHasChanged = false; - this.queuePrompt(); - } - } - } - }); - } -} +// Shim for scripts\ui\menu\queueButton.ts +export const ComfyQueueButton = window.comfyAPI.queueButton.ComfyQueueButton; diff --git a/web/scripts/ui/menu/queueOptions.js b/web/scripts/ui/menu/queueOptions.js index f3d34e74e..6c1528a4c 100644 --- a/web/scripts/ui/menu/queueOptions.js +++ b/web/scripts/ui/menu/queueOptions.js @@ -1,77 +1,2 @@ -// @ts-check - -import { $el } from "../../ui.js"; -import { prop } from "../../utils.js"; - -export class ComfyQueueOptions extends EventTarget { - element = $el("div.comfyui-queue-options"); - - constructor(app) { - super(); - this.app = app; - - this.batchCountInput = $el("input", { - className: "comfyui-queue-batch-value", - type: "number", - min: "1", - value: "1", - oninput: () => (this.batchCount = +this.batchCountInput.value), - }); - - this.batchCountRange = $el("input", { - type: "range", - min: "1", - max: "100", - value: "1", - oninput: () => (this.batchCount = +this.batchCountRange.value), - }); - - this.element.append( - $el("div.comfyui-queue-batch", [ - $el( - "label", - { - textContent: "Batch count: ", - }, - this.batchCountInput - ), - this.batchCountRange, - ]) - ); - - const createOption = (text, value, checked = false) => - $el( - "label", - { textContent: text }, - $el("input", { - type: "radio", - name: "AutoQueueMode", - checked, - value, - oninput: (e) => (this.autoQueueMode = e.target["value"]), - }) - ); - - this.autoQueueEl = $el("div.comfyui-queue-mode", [ - $el("span", "Auto Queue:"), - createOption("Disabled", "", true), - createOption("Instant", "instant"), - createOption("On Change", "change"), - ]); - - this.element.append(this.autoQueueEl); - - this.batchCount = prop(this, "batchCount", 1, () => { - this.batchCountInput.value = this.batchCount + ""; - this.batchCountRange.value = this.batchCount + ""; - }); - - this.autoQueueMode = prop(this, "autoQueueMode", "Disabled", () => { - this.dispatchEvent( - new CustomEvent("autoQueueMode", { - detail: this.autoQueueMode, - }) - ); - }); - } -} +// Shim for scripts\ui\menu\queueOptions.ts +export const ComfyQueueOptions = window.comfyAPI.queueOptions.ComfyQueueOptions; diff --git a/web/scripts/ui/menu/viewHistory.js b/web/scripts/ui/menu/viewHistory.js deleted file mode 100644 index de6b343dc..000000000 --- a/web/scripts/ui/menu/viewHistory.js +++ /dev/null @@ -1,27 +0,0 @@ -// @ts-check - -import { ComfyButton } from "../components/button.js"; -import { ComfyViewList, ComfyViewListButton } from "./viewList.js"; - -export class ComfyViewHistoryButton extends ComfyViewListButton { - constructor(app) { - super(app, { - button: new ComfyButton({ - content: "View History", - icon: "history", - tooltip: "View history", - classList: "comfyui-button comfyui-history-button", - }), - list: ComfyViewHistoryList, - mode: "History", - }); - } -} - -export class ComfyViewHistoryList extends ComfyViewList { - async loadItems() { - const items = await super.loadItems(); - items["History"].reverse(); - return items; - } -} diff --git a/web/scripts/ui/menu/viewList.js b/web/scripts/ui/menu/viewList.js deleted file mode 100644 index 693ca335c..000000000 --- a/web/scripts/ui/menu/viewList.js +++ /dev/null @@ -1,203 +0,0 @@ -// @ts-check - -import { ComfyButton } from "../components/button.js"; -import { $el } from "../../ui.js"; -import { api } from "../../api.js"; -import { ComfyPopup } from "../components/popup.js"; - -export class ComfyViewListButton { - get open() { - return this.popup.open; - } - - set open(open) { - this.popup.open = open; - } - - constructor(app, { button, list, mode }) { - this.app = app; - this.button = button; - this.element = $el("div.comfyui-button-wrapper", this.button.element); - this.popup = new ComfyPopup({ - target: this.element, - container: this.element, - horizontal: "right", - }); - this.list = new (list ?? ComfyViewList)(app, mode, this.popup); - this.popup.children = [this.list.element]; - this.popup.addEventListener("open", () => { - this.list.update(); - }); - this.popup.addEventListener("close", () => { - this.list.close(); - }); - this.button.withPopup(this.popup); - - api.addEventListener("status", () => { - if (this.popup.open) { - this.popup.update(); - } - }); - } -} - -export class ComfyViewList { - popup; - - constructor(app, mode, popup) { - this.app = app; - this.mode = mode; - this.popup = popup; - this.type = mode.toLowerCase(); - - this.items = $el(`div.comfyui-${this.type}-items.comfyui-view-list-items`); - this.clear = new ComfyButton({ - icon: "cancel", - content: "Clear", - action: async () => { - this.showSpinner(false); - await api.clearItems(this.type); - await this.update(); - }, - }); - - this.refresh = new ComfyButton({ - icon: "refresh", - content: "Refresh", - action: async () => { - await this.update(false); - }, - }); - - this.element = $el(`div.comfyui-${this.type}-popup.comfyui-view-list-popup`, [ - $el("h3", mode), - $el("header", [this.clear.element, this.refresh.element]), - this.items, - ]); - - api.addEventListener("status", () => { - if (this.popup.open) { - this.update(); - } - }); - } - - async close() { - this.items.replaceChildren(); - } - - async update(resize = true) { - this.showSpinner(resize); - const res = await this.loadItems(); - let any = false; - - const names = Object.keys(res); - const sections = names - .map((section) => { - const items = res[section]; - if (items?.length) { - any = true; - } else { - return; - } - - const rows = []; - if (names.length > 1) { - rows.push($el("h5", section)); - } - rows.push(...items.flatMap((item) => this.createRow(item, section))); - return $el("section", rows); - }) - .filter(Boolean); - - if (any) { - this.items.replaceChildren(...sections); - } else { - this.items.replaceChildren($el("h5", "None")); - } - - this.popup.update(); - this.clear.enabled = this.refresh.enabled = true; - this.element.style.removeProperty("height"); - } - - showSpinner(resize = true) { - // if (!this.spinner) { - // this.spinner = createSpinner(); - // } - // if (!resize) { - // this.element.style.height = this.element.clientHeight + "px"; - // } - // this.clear.enabled = this.refresh.enabled = false; - // this.items.replaceChildren( - // $el( - // "div", - // { - // style: { - // fontSize: "18px", - // }, - // }, - // this.spinner - // ) - // ); - // this.popup.update(); - } - - async loadItems() { - return await api.getItems(this.type); - } - - getRow(item, section) { - return { - text: item.prompt[0] + "", - actions: [ - { - text: "Load", - action: async () => { - try { - await this.app.loadGraphData(item.prompt[3].extra_pnginfo.workflow); - if (item.outputs) { - this.app.nodeOutputs = item.outputs; - } - } catch (error) { - alert("Error loading workflow: " + error.message); - console.error(error); - } - }, - }, - { - text: "Delete", - action: async () => { - try { - await api.deleteItem(this.type, item.prompt[1]); - this.update(); - } catch (error) {} - }, - }, - ], - }; - } - - createRow = (item, section) => { - const row = this.getRow(item, section); - return [ - $el("span", row.text), - ...row.actions.map( - (a) => - new ComfyButton({ - content: a.text, - action: async (e, btn) => { - btn.enabled = false; - try { - await a.action(); - } catch (error) { - throw error; - } finally { - btn.enabled = true; - } - }, - }).element - ), - ]; - }; -} diff --git a/web/scripts/ui/menu/viewQueue.js b/web/scripts/ui/menu/viewQueue.js deleted file mode 100644 index 97d012986..000000000 --- a/web/scripts/ui/menu/viewQueue.js +++ /dev/null @@ -1,55 +0,0 @@ -// @ts-check - -import { ComfyButton } from "../components/button.js"; -import { ComfyViewList, ComfyViewListButton } from "./viewList.js"; -import { api } from "../../api.js"; - -export class ComfyViewQueueButton extends ComfyViewListButton { - constructor(app) { - super(app, { - button: new ComfyButton({ - content: "View Queue", - icon: "format-list-numbered", - tooltip: "View queue", - classList: "comfyui-button comfyui-queue-button", - }), - list: ComfyViewQueueList, - mode: "Queue", - }); - } -} - -export class ComfyViewQueueList extends ComfyViewList { - getRow = (item, section) => { - if (section !== "Running") { - return super.getRow(item, section); - } - return { - text: item.prompt[0] + "", - actions: [ - { - text: "Load", - action: async () => { - try { - await this.app.loadGraphData(item.prompt[3].extra_pnginfo.workflow); - if (item.outputs) { - this.app.nodeOutputs = item.outputs; - } - } catch (error) { - alert("Error loading workflow: " + error.message); - console.error(error); - } - }, - }, - { - text: "Cancel", - action: async () => { - try { - await api.interrupt(); - } catch (error) {} - }, - }, - ], - }; - } -} diff --git a/web/scripts/ui/menu/workflows.js b/web/scripts/ui/menu/workflows.js index 3b904fb4b..13754b4bb 100644 --- a/web/scripts/ui/menu/workflows.js +++ b/web/scripts/ui/menu/workflows.js @@ -1,770 +1,3 @@ -// @ts-check - -import { ComfyButton } from "../components/button.js"; -import { prop, getStorageValue, setStorageValue } from "../../utils.js"; -import { $el } from "../../ui.js"; -import { api } from "../../api.js"; -import { ComfyPopup } from "../components/popup.js"; -import { createSpinner } from "../spinner.js"; -import { ComfyWorkflow, trimJsonExt } from "../../workflows.js"; -import { ComfyAsyncDialog } from "../components/asyncDialog.js"; - -export class ComfyWorkflowsMenu { - #first = true; - element = $el("div.comfyui-workflows"); - - get open() { - return this.popup.open; - } - - set open(open) { - this.popup.open = open; - } - - /** - * @param {import("../../app.js").ComfyApp} app - */ - constructor(app) { - this.app = app; - this.#bindEvents(); - - const classList = { - "comfyui-workflows-button": true, - "comfyui-button": true, - unsaved: getStorageValue("Comfy.PreviousWorkflowUnsaved") === "true", - running: false, - }; - this.buttonProgress = $el("div.comfyui-workflows-button-progress"); - this.workflowLabel = $el("span.comfyui-workflows-label", ""); - this.button = new ComfyButton({ - content: $el("div.comfyui-workflows-button-inner", [$el("i.mdi.mdi-graph"), this.workflowLabel, this.buttonProgress]), - icon: "chevron-down", - classList, - }); - - this.element.append(this.button.element); - - this.popup = new ComfyPopup({ target: this.element, classList: "comfyui-workflows-popup" }); - this.content = new ComfyWorkflowsContent(app, this.popup); - this.popup.children = [this.content.element]; - this.popup.addEventListener("change", () => { - this.button.icon = "chevron-" + (this.popup.open ? "up" : "down"); - }); - this.button.withPopup(this.popup); - - this.unsaved = prop(this, "unsaved", classList.unsaved, (v) => { - classList.unsaved = v; - this.button.classList = classList; - setStorageValue("Comfy.PreviousWorkflowUnsaved", v); - }); - } - - #updateProgress = () => { - const prompt = this.app.workflowManager.activePrompt; - let percent = 0; - if (this.app.workflowManager.activeWorkflow === prompt?.workflow) { - const total = Object.values(prompt.nodes); - const done = total.filter(Boolean); - percent = (done.length / total.length) * 100; - } - this.buttonProgress.style.width = percent + "%"; - }; - - #updateActive = () => { - const active = this.app.workflowManager.activeWorkflow; - this.button.tooltip = active.path; - this.workflowLabel.textContent = active.name; - this.unsaved = active.unsaved; - - if (this.#first) { - this.#first = false; - this.content.load(); - } - - this.#updateProgress(); - }; - - #bindEvents() { - this.app.workflowManager.addEventListener("changeWorkflow", this.#updateActive); - this.app.workflowManager.addEventListener("rename", this.#updateActive); - this.app.workflowManager.addEventListener("delete", this.#updateActive); - - this.app.workflowManager.addEventListener("save", () => { - this.unsaved = this.app.workflowManager.activeWorkflow.unsaved; - }); - - this.app.workflowManager.addEventListener("execute", (e) => { - this.#updateProgress(); - }); - - api.addEventListener("graphChanged", () => { - this.unsaved = true; - }); - } - - #getMenuOptions(callback) { - const menu = []; - const directories = new Map(); - for (const workflow of this.app.workflowManager.workflows || []) { - const path = workflow.pathParts; - if (!path) continue; - let parent = menu; - let currentPath = ""; - for (let i = 0; i < path.length - 1; i++) { - currentPath += "/" + path[i]; - let newParent = directories.get(currentPath); - if (!newParent) { - newParent = { - title: path[i], - has_submenu: true, - submenu: { - options: [], - }, - }; - parent.push(newParent); - newParent = newParent.submenu.options; - directories.set(currentPath, newParent); - } - parent = newParent; - } - parent.push({ - title: trimJsonExt(path[path.length - 1]), - callback: () => callback(workflow), - }); - } - return menu; - } - - #getFavoriteMenuOptions(callback) { - const menu = []; - for (const workflow of this.app.workflowManager.workflows || []) { - if (workflow.isFavorite) { - menu.push({ - title: "⭐ " + workflow.name, - callback: () => callback(workflow), - }); - } - } - return menu; - } - - /** - * @param {import("../../app.js").ComfyApp} app - */ - registerExtension(app) { - const self = this; - app.registerExtension({ - name: "Comfy.Workflows", - async beforeRegisterNodeDef(nodeType) { - function getImageWidget(node) { - const inputs = { ...node.constructor?.nodeData?.input?.required, ...node.constructor?.nodeData?.input?.optional }; - for (const input in inputs) { - if (inputs[input][0] === "IMAGEUPLOAD") { - const imageWidget = node.widgets.find((w) => w.name === (inputs[input]?.[1]?.widget ?? "image")); - if (imageWidget) return imageWidget; - } - } - } - - function setWidgetImage(node, widget, img) { - const url = new URL(img.src); - const filename = url.searchParams.get("filename"); - const subfolder = url.searchParams.get("subfolder"); - const type = url.searchParams.get("type"); - const imageId = `${subfolder ? subfolder + "/" : ""}${filename} [${type}]`; - widget.value = imageId; - node.imgs = [img]; - app.graph.setDirtyCanvas(true, true); - } - - /** - * @param {HTMLImageElement} img - * @param {ComfyWorkflow} workflow - */ - async function sendToWorkflow(img, workflow) { - const openWorkflow = app.workflowManager.openWorkflows.find((w) => w.path === workflow.path); - if (openWorkflow) { - workflow = openWorkflow; - } - - await workflow.load(); - let options = []; - const nodes = app.graph.computeExecutionOrder(false); - for (const node of nodes) { - const widget = getImageWidget(node); - if (widget == null) continue; - - if (node.title?.toLowerCase().includes("input")) { - options = [{ widget, node }]; - break; - } else { - options.push({ widget, node }); - } - } - - if (!options.length) { - alert("No image nodes have been found in this workflow!"); - return; - } else if (options.length > 1) { - const dialog = new WidgetSelectionDialog(options); - const res = await dialog.show(app); - if (!res) return; - options = [res]; - } - - setWidgetImage(options[0].node, options[0].widget, img); - } - - const getExtraMenuOptions = nodeType.prototype["getExtraMenuOptions"]; - nodeType.prototype["getExtraMenuOptions"] = function (_, options) { - const r = getExtraMenuOptions?.apply?.(this, arguments); - - const setting = app.ui.settings.getSettingValue("Comfy.UseNewMenu", false); - if (setting && setting != "Disabled") { - const t = /** @type { {imageIndex?: number, overIndex?: number, imgs: string[]} } */ /** @type {any} */ (this); - let img; - if (t.imageIndex != null) { - // An image is selected so select that - img = t.imgs?.[t.imageIndex]; - } else if (t.overIndex != null) { - // No image is selected but one is hovered - img = t.img?.s[t.overIndex]; - } - - if (img) { - let pos = options.findIndex((o) => o.content === "Save Image"); - if (pos === -1) { - pos = 0; - } else { - pos++; - } - - options.splice(pos, 0, { - content: "Send to workflow", - has_submenu: true, - submenu: { - options: [ - { - callback: () => sendToWorkflow(img, app.workflowManager.activeWorkflow), - title: "[Current workflow]", - }, - ...self.#getFavoriteMenuOptions(sendToWorkflow.bind(null, img)), - null, - ...self.#getMenuOptions(sendToWorkflow.bind(null, img)), - ], - }, - }); - } - } - - return r; - }; - }, - }); - } -} - -export class ComfyWorkflowsContent { - element = $el("div.comfyui-workflows-panel"); - treeState = {}; - treeFiles = {}; - /** @type { Map } */ - openFiles = new Map(); - /** @type {WorkflowElement} */ - activeElement = null; - - /** - * @param {import("../../app.js").ComfyApp} app - * @param {ComfyPopup} popup - */ - constructor(app, popup) { - this.app = app; - this.popup = popup; - this.actions = $el("div.comfyui-workflows-actions", [ - new ComfyButton({ - content: "Default", - icon: "file-code", - iconSize: 18, - classList: "comfyui-button primary", - tooltip: "Load default workflow", - action: () => { - popup.open = false; - app.loadGraphData(); - app.resetView(); - }, - }).element, - new ComfyButton({ - content: "Browse", - icon: "folder", - iconSize: 18, - tooltip: "Browse for an image or exported workflow", - action: () => { - popup.open = false; - app.ui.loadFile(); - }, - }).element, - new ComfyButton({ - content: "Blank", - icon: "plus-thick", - iconSize: 18, - tooltip: "Create a new blank workflow", - action: () => { - app.workflowManager.setWorkflow(null); - app.clean(); - app.graph.clear(); - app.workflowManager.activeWorkflow.track(); - popup.open = false; - }, - }).element, - ]); - - this.spinner = createSpinner(); - this.element.replaceChildren(this.actions, this.spinner); - - this.popup.addEventListener("open", () => this.load()); - this.popup.addEventListener("close", () => this.element.replaceChildren(this.actions, this.spinner)); - - this.app.workflowManager.addEventListener("favorite", (e) => { - const workflow = e["detail"]; - const button = this.treeFiles[workflow.path]?.primary; - if (!button) return; // Can happen when a workflow is renamed - button.icon = this.#getFavoriteIcon(workflow); - button.overIcon = this.#getFavoriteOverIcon(workflow); - this.updateFavorites(); - }); - - for (const e of ["save", "open", "close", "changeWorkflow"]) { - // TODO: dont be lazy and just update the specific element - app.workflowManager.addEventListener(e, () => this.updateOpen()); - } - this.app.workflowManager.addEventListener("rename", () => this.load()); - this.app.workflowManager.addEventListener("execute", (e) => this.#updateActive()); - } - - async load() { - await this.app.workflowManager.loadWorkflows(); - this.updateTree(); - this.updateFavorites(); - this.updateOpen(); - this.element.replaceChildren(this.actions, this.openElement, this.favoritesElement, this.treeElement); - } - - updateOpen() { - const current = this.openElement; - this.openFiles.clear(); - - this.openElement = $el("div.comfyui-workflows-open", [ - $el("h3", "Open"), - ...this.app.workflowManager.openWorkflows.map((w) => { - const wrapper = new WorkflowElement(this, w, { - primary: { element: $el("i.mdi.mdi-18px.mdi-progress-pencil") }, - buttons: [ - this.#getRenameButton(w), - new ComfyButton({ - icon: "close", - iconSize: 18, - classList: "comfyui-button comfyui-workflows-file-action", - tooltip: "Close workflow", - action: (e) => { - e.stopImmediatePropagation(); - this.app.workflowManager.closeWorkflow(w); - }, - }), - ], - }); - if (w.unsaved) { - wrapper.element.classList.add("unsaved"); - } - if(w === this.app.workflowManager.activeWorkflow) { - wrapper.element.classList.add("active"); - } - - this.openFiles.set(w, wrapper); - return wrapper.element; - }), - ]); - - this.#updateActive(); - current?.replaceWith(this.openElement); - } - - updateFavorites() { - const current = this.favoritesElement; - const favorites = [...this.app.workflowManager.workflows.filter((w) => w.isFavorite)]; - - this.favoritesElement = $el("div.comfyui-workflows-favorites", [ - $el("h3", "Favorites"), - ...favorites - .map((w) => { - return this.#getWorkflowElement(w).element; - }) - .filter(Boolean), - ]); - - current?.replaceWith(this.favoritesElement); - } - - filterTree() { - if (!this.filterText) { - this.treeRoot.classList.remove("filtered"); - // Unfilter whole tree - for (const item of Object.values(this.treeFiles)) { - item.element.parentElement.style.removeProperty("display"); - this.showTreeParents(item.element.parentElement); - } - return; - } - this.treeRoot.classList.add("filtered"); - const searchTerms = this.filterText.toLocaleLowerCase().split(" "); - for (const item of Object.values(this.treeFiles)) { - const parts = item.workflow.pathParts; - let termIndex = 0; - let valid = false; - for (const part of parts) { - let currentIndex = 0; - do { - currentIndex = part.indexOf(searchTerms[termIndex], currentIndex); - if (currentIndex > -1) currentIndex += searchTerms[termIndex].length; - } while (currentIndex !== -1 && ++termIndex < searchTerms.length); - - if (termIndex >= searchTerms.length) { - valid = true; - break; - } - } - if (valid) { - item.element.parentElement.style.removeProperty("display"); - this.showTreeParents(item.element.parentElement); - } else { - item.element.parentElement.style.display = "none"; - this.hideTreeParents(item.element.parentElement); - } - } - } - - hideTreeParents(element) { - // Hide all parents if no children are visible - if (element.parentElement?.classList.contains("comfyui-workflows-tree") === false) { - for (let i = 1; i < element.parentElement.children.length; i++) { - const c = element.parentElement.children[i]; - if (c.style.display !== "none") { - return; - } - } - element.parentElement.style.display = "none"; - this.hideTreeParents(element.parentElement); - } - } - - showTreeParents(element) { - if (element.parentElement?.classList.contains("comfyui-workflows-tree") === false) { - element.parentElement.style.removeProperty("display"); - this.showTreeParents(element.parentElement); - } - } - - updateTree() { - const current = this.treeElement; - const nodes = {}; - let typingTimeout; - - this.treeFiles = {}; - this.treeRoot = $el("ul.comfyui-workflows-tree"); - this.treeElement = $el("section", [ - $el("header", [ - $el("h3", "Browse"), - $el("div.comfy-ui-workflows-search", [ - $el("i.mdi.mdi-18px.mdi-magnify"), - $el("input", { - placeholder: "Search", - value: this.filterText ?? "", - oninput: (e) => { - this.filterText = e.target["value"]?.trim(); - clearTimeout(typingTimeout); - typingTimeout = setTimeout(() => this.filterTree(), 250); - }, - }), - ]), - ]), - this.treeRoot, - ]); - - for (const workflow of this.app.workflowManager.workflows) { - if (!workflow.pathParts) continue; - - let currentPath = ""; - let currentRoot = this.treeRoot; - - for (let i = 0; i < workflow.pathParts.length; i++) { - currentPath += (currentPath ? "\\" : "") + workflow.pathParts[i]; - const parentNode = nodes[currentPath] ?? this.#createNode(currentPath, workflow, i, currentRoot); - - nodes[currentPath] = parentNode; - currentRoot = parentNode; - } - } - - current?.replaceWith(this.treeElement); - this.filterTree(); - } - - #expandNode(el, workflow, thisPath, i) { - const expanded = !el.classList.toggle("closed"); - if (expanded) { - let c = ""; - for (let j = 0; j <= i; j++) { - c += (c ? "\\" : "") + workflow.pathParts[j]; - this.treeState[c] = true; - } - } else { - let c = thisPath; - for (let j = i + 1; j < workflow.pathParts.length; j++) { - c += (c ? "\\" : "") + workflow.pathParts[j]; - delete this.treeState[c]; - } - delete this.treeState[thisPath]; - } - } - - #updateActive() { - this.#removeActive(); - - const active = this.app.workflowManager.activePrompt; - if (!active?.workflow) return; - - const open = this.openFiles.get(active.workflow); - if (!open) return; - - this.activeElement = open; - - const total = Object.values(active.nodes); - const done = total.filter(Boolean); - const percent = done.length / total.length; - open.element.classList.add("running"); - open.element.style.setProperty("--progress", percent * 100 + "%"); - open.primary.element.classList.remove("mdi-progress-pencil"); - open.primary.element.classList.add("mdi-play"); - } - - #removeActive() { - if (!this.activeElement) return; - this.activeElement.element.classList.remove("running"); - this.activeElement.element.style.removeProperty("--progress"); - this.activeElement.primary.element.classList.add("mdi-progress-pencil"); - this.activeElement.primary.element.classList.remove("mdi-play"); - } - - /** @param {ComfyWorkflow} workflow */ - #getFavoriteIcon(workflow) { - return workflow.isFavorite ? "star" : "file-outline"; - } - - /** @param {ComfyWorkflow} workflow */ - #getFavoriteOverIcon(workflow) { - return workflow.isFavorite ? "star-off" : "star-outline"; - } - - /** @param {ComfyWorkflow} workflow */ - #getFavoriteTooltip(workflow) { - return workflow.isFavorite ? "Remove this workflow from your favorites" : "Add this workflow to your favorites"; - } - - /** @param {ComfyWorkflow} workflow */ - #getFavoriteButton(workflow, primary) { - return new ComfyButton({ - icon: this.#getFavoriteIcon(workflow), - overIcon: this.#getFavoriteOverIcon(workflow), - iconSize: 18, - classList: "comfyui-button comfyui-workflows-file-action-favorite" + (primary ? " comfyui-workflows-file-action-primary" : ""), - tooltip: this.#getFavoriteTooltip(workflow), - action: (e) => { - e.stopImmediatePropagation(); - workflow.favorite(!workflow.isFavorite); - }, - }); - } - - /** @param {ComfyWorkflow} workflow */ - #getDeleteButton(workflow) { - const deleteButton = new ComfyButton({ - icon: "delete", - tooltip: "Delete this workflow", - classList: "comfyui-button comfyui-workflows-file-action", - iconSize: 18, - action: async (e, btn) => { - e.stopImmediatePropagation(); - - if (btn.icon === "delete-empty") { - btn.enabled = false; - await workflow.delete(); - await this.load(); - } else { - btn.icon = "delete-empty"; - btn.element.style.background = "red"; - } - }, - }); - deleteButton.element.addEventListener("mouseleave", () => { - deleteButton.icon = "delete"; - deleteButton.element.style.removeProperty("background"); - }); - return deleteButton; - } - - /** @param {ComfyWorkflow} workflow */ - #getInsertButton(workflow) { - return new ComfyButton({ - icon: "file-move-outline", - iconSize: 18, - tooltip: "Insert this workflow into the current workflow", - classList: "comfyui-button comfyui-workflows-file-action", - action: (e) => { - if (!this.app.shiftDown) { - this.popup.open = false; - } - e.stopImmediatePropagation(); - if (!this.app.shiftDown) { - this.popup.open = false; - } - workflow.insert(); - }, - }); - } - - /** @param {ComfyWorkflow} workflow */ - #getRenameButton(workflow) { - return new ComfyButton({ - icon: "pencil", - tooltip: workflow.path ? "Rename this workflow" : "This workflow can't be renamed as it hasn't been saved.", - classList: "comfyui-button comfyui-workflows-file-action", - iconSize: 18, - enabled: !!workflow.path, - action: async (e) => { - e.stopImmediatePropagation(); - const newName = prompt("Enter new name", workflow.path); - if (newName) { - await workflow.rename(newName); - } - }, - }); - } - - /** @param {ComfyWorkflow} workflow */ - #getWorkflowElement(workflow) { - return new WorkflowElement(this, workflow, { - primary: this.#getFavoriteButton(workflow, true), - buttons: [this.#getInsertButton(workflow), this.#getRenameButton(workflow), this.#getDeleteButton(workflow)], - }); - } - - /** @param {ComfyWorkflow} workflow */ - #createLeafNode(workflow) { - const fileNode = this.#getWorkflowElement(workflow); - this.treeFiles[workflow.path] = fileNode; - return fileNode; - } - - #createNode(currentPath, workflow, i, currentRoot) { - const part = workflow.pathParts[i]; - - const parentNode = $el("ul" + (this.treeState[currentPath] ? "" : ".closed"), { - $: (el) => { - el.onclick = (e) => { - this.#expandNode(el, workflow, currentPath, i); - e.stopImmediatePropagation(); - }; - }, - }); - currentRoot.append(parentNode); - - // Create a node for the current part and an inner UL for its children if it isnt a leaf node - const leaf = i === workflow.pathParts.length - 1; - let nodeElement; - if (leaf) { - nodeElement = this.#createLeafNode(workflow).element; - } else { - nodeElement = $el("li", [$el("i.mdi.mdi-18px.mdi-folder"), $el("span", part)]); - } - parentNode.append(nodeElement); - return parentNode; - } -} - -class WorkflowElement { - /** - * @param { ComfyWorkflowsContent } parent - * @param { ComfyWorkflow } workflow - */ - constructor(parent, workflow, { tagName = "li", primary, buttons }) { - this.parent = parent; - this.workflow = workflow; - this.primary = primary; - this.buttons = buttons; - - this.element = $el( - tagName + ".comfyui-workflows-tree-file", - { - onclick: () => { - workflow.load(); - this.parent.popup.open = false; - }, - title: this.workflow.path, - }, - [this.primary?.element, $el("span", workflow.name), ...buttons.map((b) => b.element)] - ); - } -} - -class WidgetSelectionDialog extends ComfyAsyncDialog { - #options; - - /** - * @param {Array<{widget: {name: string}, node: {pos: [number, number], title: string, id: string, type: string}}>} options - */ - constructor(options) { - super(); - this.#options = options; - } - - show(app) { - this.element.classList.add("comfy-widget-selection-dialog"); - return super.show( - $el("div", [ - $el("h2", "Select image target"), - $el( - "p", - "This workflow has multiple image loader nodes, you can rename a node to include 'input' in the title for it to be automatically selected, or select one below." - ), - $el( - "section", - this.#options.map((opt) => { - return $el("div.comfy-widget-selection-item", [ - $el("span", { dataset: { id: opt.node.id } }, `${opt.node.title ?? opt.node.type} ${opt.widget.name}`), - $el( - "button.comfyui-button", - { - onclick: () => { - app.canvas.ds.offset[0] = -opt.node.pos[0] + 50; - app.canvas.ds.offset[1] = -opt.node.pos[1] + 50; - app.canvas.selectNode(opt.node); - app.graph.setDirtyCanvas(true, true); - }, - }, - "Show" - ), - $el( - "button.comfyui-button.primary", - { - onclick: () => { - this.close(opt); - }, - }, - "Select" - ), - ]); - }) - ), - ]) - ); - } -} \ No newline at end of file +// Shim for scripts\ui\menu\workflows.ts +export const ComfyWorkflowsMenu = window.comfyAPI.workflows.ComfyWorkflowsMenu; +export const ComfyWorkflowsContent = window.comfyAPI.workflows.ComfyWorkflowsContent; diff --git a/web/scripts/ui/settings.js b/web/scripts/ui/settings.js index 819e4e7d6..96eb36e3a 100644 --- a/web/scripts/ui/settings.js +++ b/web/scripts/ui/settings.js @@ -1,333 +1,2 @@ -import { $el } from "../ui.js"; -import { api } from "../api.js"; -import { ComfyDialog } from "./dialog.js"; - -export class ComfySettingsDialog extends ComfyDialog { - constructor(app) { - super(); - this.app = app; - this.settingsValues = {}; - this.settingsLookup = {}; - this.element = $el( - "dialog", - { - id: "comfy-settings-dialog", - parent: document.body, - }, - [ - $el("table.comfy-modal-content.comfy-table", [ - $el( - "caption", - { textContent: "Settings" }, - $el("button.comfy-btn", { - type: "button", - textContent: "\u00d7", - onclick: () => { - this.element.close(); - }, - }) - ), - $el("tbody", { $: (tbody) => (this.textElement = tbody) }), - $el("button", { - type: "button", - textContent: "Close", - style: { - cursor: "pointer", - }, - onclick: () => { - this.element.close(); - }, - }), - ]), - ] - ); - } - - get settings() { - return Object.values(this.settingsLookup); - } - - #dispatchChange(id, value, oldValue) { - this.dispatchEvent( - new CustomEvent(id + ".change", { - detail: { - value, - oldValue - }, - }) - ); - } - - async load() { - if (this.app.storageLocation === "browser") { - this.settingsValues = localStorage; - } else { - this.settingsValues = await api.getSettings(); - } - - // Trigger onChange for any settings added before load - for (const id in this.settingsLookup) { - const value = this.settingsValues[this.getId(id)]; - this.settingsLookup[id].onChange?.(value); - this.#dispatchChange(id, value); - } - } - - getId(id) { - if (this.app.storageLocation === "browser") { - id = "Comfy.Settings." + id; - } - return id; - } - - getSettingValue(id, defaultValue) { - let value = this.settingsValues[this.getId(id)]; - if(value != null) { - if(this.app.storageLocation === "browser") { - try { - value = JSON.parse(value); - } catch (error) { - } - } - } - return value ?? defaultValue; - } - - async setSettingValueAsync(id, value) { - const json = JSON.stringify(value); - localStorage["Comfy.Settings." + id] = json; // backwards compatibility for extensions keep setting in storage - - let oldValue = this.getSettingValue(id, undefined); - this.settingsValues[this.getId(id)] = value; - - if (id in this.settingsLookup) { - this.settingsLookup[id].onChange?.(value, oldValue); - } - this.#dispatchChange(id, value, oldValue); - - await api.storeSetting(id, value); - } - - setSettingValue(id, value) { - this.setSettingValueAsync(id, value).catch((err) => { - alert(`Error saving setting '${id}'`); - console.error(err); - }); - } - - addSetting({ id, name, type, defaultValue, onChange, attrs = {}, tooltip = "", options = undefined }) { - if (!id) { - throw new Error("Settings must have an ID"); - } - - if (id in this.settingsLookup) { - throw new Error(`Setting ${id} of type ${type} must have a unique ID.`); - } - - let skipOnChange = false; - let value = this.getSettingValue(id); - if (value == null) { - if (this.app.isNewUserSession) { - // Check if we have a localStorage value but not a setting value and we are a new user - const localValue = localStorage["Comfy.Settings." + id]; - if (localValue) { - value = JSON.parse(localValue); - this.setSettingValue(id, value); // Store on the server - } - } - if (value == null) { - value = defaultValue; - } - } - - // Trigger initial setting of value - if (!skipOnChange) { - onChange?.(value, undefined); - } - - this.settingsLookup[id] = { - id, - onChange, - name, - render: () => { - if (type === "hidden") return; - - const setter = (v) => { - if (onChange) { - onChange(v, value); - } - - this.setSettingValue(id, v); - value = v; - }; - value = this.getSettingValue(id, defaultValue); - - let element; - const htmlID = id.replaceAll(".", "-"); - - const labelCell = $el("td", [ - $el("label", { - for: htmlID, - classList: [tooltip !== "" ? "comfy-tooltip-indicator" : ""], - textContent: name, - }), - ]); - - if (typeof type === "function") { - element = type(name, setter, value, attrs); - } else { - switch (type) { - case "boolean": - element = $el("tr", [ - labelCell, - $el("td", [ - $el("input", { - id: htmlID, - type: "checkbox", - checked: value, - onchange: (event) => { - const isChecked = event.target.checked; - if (onChange !== undefined) { - onChange(isChecked); - } - this.setSettingValue(id, isChecked); - }, - }), - ]), - ]); - break; - case "number": - element = $el("tr", [ - labelCell, - $el("td", [ - $el("input", { - type, - value, - id: htmlID, - oninput: (e) => { - setter(e.target.value); - }, - ...attrs, - }), - ]), - ]); - break; - case "slider": - element = $el("tr", [ - labelCell, - $el("td", [ - $el( - "div", - { - style: { - display: "grid", - gridAutoFlow: "column", - }, - }, - [ - $el("input", { - ...attrs, - value, - type: "range", - oninput: (e) => { - setter(e.target.value); - e.target.nextElementSibling.value = e.target.value; - }, - }), - $el("input", { - ...attrs, - value, - id: htmlID, - type: "number", - style: { maxWidth: "4rem" }, - oninput: (e) => { - setter(e.target.value); - e.target.previousElementSibling.value = e.target.value; - }, - }), - ] - ), - ]), - ]); - break; - case "combo": - element = $el("tr", [ - labelCell, - $el("td", [ - $el( - "select", - { - oninput: (e) => { - setter(e.target.value); - }, - }, - (typeof options === "function" ? options(value) : options || []).map((opt) => { - if (typeof opt === "string") { - opt = { text: opt }; - } - const v = opt.value ?? opt.text; - return $el("option", { - value: v, - textContent: opt.text, - selected: value + "" === v + "", - }); - }) - ), - ]), - ]); - break; - case "text": - default: - if (type !== "text") { - console.warn(`Unsupported setting type '${type}, defaulting to text`); - } - - element = $el("tr", [ - labelCell, - $el("td", [ - $el("input", { - value, - id: htmlID, - oninput: (e) => { - setter(e.target.value); - }, - ...attrs, - }), - ]), - ]); - break; - } - } - if (tooltip) { - element.title = tooltip; - } - - return element; - }, - }; - - const self = this; - return { - get value() { - return self.getSettingValue(id, defaultValue); - }, - set value(v) { - self.setSettingValue(id, v); - }, - }; - } - - show() { - this.textElement.replaceChildren( - $el( - "tr", - { - style: { display: "none" }, - }, - [$el("th"), $el("th", { style: { width: "33%" } })] - ), - ...this.settings.sort((a, b) => a.name.localeCompare(b.name)).map((s) => s.render()).filter(Boolean) - ); - this.element.showModal(); - } -} +// Shim for scripts\ui\settings.ts +export const ComfySettingsDialog = window.comfyAPI.settings.ComfySettingsDialog; diff --git a/web/scripts/ui/spinner.css b/web/scripts/ui/spinner.css deleted file mode 100644 index 56da6072e..000000000 --- a/web/scripts/ui/spinner.css +++ /dev/null @@ -1,34 +0,0 @@ -.lds-ring { - display: inline-block; - position: relative; - width: 1em; - height: 1em; -} -.lds-ring div { - box-sizing: border-box; - display: block; - position: absolute; - width: 100%; - height: 100%; - border: 0.15em solid #fff; - border-radius: 50%; - animation: lds-ring 1.2s cubic-bezier(0.5, 0, 0.5, 1) infinite; - border-color: #fff transparent transparent transparent; -} -.lds-ring div:nth-child(1) { - animation-delay: -0.45s; -} -.lds-ring div:nth-child(2) { - animation-delay: -0.3s; -} -.lds-ring div:nth-child(3) { - animation-delay: -0.15s; -} -@keyframes lds-ring { - 0% { - transform: rotate(0deg); - } - 100% { - transform: rotate(360deg); - } -} diff --git a/web/scripts/ui/spinner.js b/web/scripts/ui/spinner.js index d049786f6..4fb8be0dc 100644 --- a/web/scripts/ui/spinner.js +++ b/web/scripts/ui/spinner.js @@ -1,9 +1,2 @@ -import { addStylesheet } from "../utils.js"; - -addStylesheet(import.meta.url); - -export function createSpinner() { - const div = document.createElement("div"); - div.innerHTML = ``; - return div.firstElementChild; -} +// Shim for scripts\ui\spinner.ts +export const createSpinner = window.comfyAPI.spinner.createSpinner; diff --git a/web/scripts/ui/toggleSwitch.js b/web/scripts/ui/toggleSwitch.js index 59597ef90..d510b5583 100644 --- a/web/scripts/ui/toggleSwitch.js +++ b/web/scripts/ui/toggleSwitch.js @@ -1,60 +1,2 @@ -import { $el } from "../ui.js"; - -/** - * @typedef { { text: string, value?: string, tooltip?: string } } ToggleSwitchItem - */ -/** - * Creates a toggle switch element - * @param { string } name - * @param { Array void } [opts.onChange] - */ -export function toggleSwitch(name, items, { onChange } = {}) { - let selectedIndex; - let elements; - - function updateSelected(index) { - if (selectedIndex != null) { - elements[selectedIndex].classList.remove("comfy-toggle-selected"); - } - onChange?.({ item: items[index], prev: selectedIndex == null ? undefined : items[selectedIndex] }); - selectedIndex = index; - elements[selectedIndex].classList.add("comfy-toggle-selected"); - } - - elements = items.map((item, i) => { - if (typeof item === "string") item = { text: item }; - if (!item.value) item.value = item.text; - - const toggle = $el( - "label", - { - textContent: item.text, - title: item.tooltip ?? "", - }, - $el("input", { - name, - type: "radio", - value: item.value ?? item.text, - checked: item.selected, - onchange: () => { - updateSelected(i); - }, - }) - ); - if (item.selected) { - updateSelected(i); - } - return toggle; - }); - - const container = $el("div.comfy-toggle-switch", elements); - - if (selectedIndex == null) { - elements[0].children[0].checked = true; - updateSelected(0); - } - - return container; -} +// Shim for scripts\ui\toggleSwitch.ts +export const toggleSwitch = window.comfyAPI.toggleSwitch.toggleSwitch; diff --git a/web/scripts/ui/userSelection.js b/web/scripts/ui/userSelection.js index f9f1ca807..6c77079db 100644 --- a/web/scripts/ui/userSelection.js +++ b/web/scripts/ui/userSelection.js @@ -1,114 +1,2 @@ -import { api } from "../api.js"; -import { $el } from "../ui.js"; -import { addStylesheet } from "../utils.js"; -import { createSpinner } from "./spinner.js"; - -export class UserSelectionScreen { - async show(users, user) { - // This will rarely be hit so move the loading to on demand - await addStylesheet(import.meta.url); - const userSelection = document.getElementById("comfy-user-selection"); - userSelection.style.display = ""; - return new Promise((resolve) => { - const input = userSelection.getElementsByTagName("input")[0]; - const select = userSelection.getElementsByTagName("select")[0]; - const inputSection = input.closest("section"); - const selectSection = select.closest("section"); - const form = userSelection.getElementsByTagName("form")[0]; - const error = userSelection.getElementsByClassName("comfy-user-error")[0]; - const button = userSelection.getElementsByClassName("comfy-user-button-next")[0]; - - let inputActive = null; - input.addEventListener("focus", () => { - inputSection.classList.add("selected"); - selectSection.classList.remove("selected"); - inputActive = true; - }); - select.addEventListener("focus", () => { - inputSection.classList.remove("selected"); - selectSection.classList.add("selected"); - inputActive = false; - select.style.color = ""; - }); - select.addEventListener("blur", () => { - if (!select.value) { - select.style.color = "var(--descrip-text)"; - } - }); - - form.addEventListener("submit", async (e) => { - e.preventDefault(); - if (inputActive == null) { - error.textContent = "Please enter a username or select an existing user."; - } else if (inputActive) { - const username = input.value.trim(); - if (!username) { - error.textContent = "Please enter a username."; - return; - } - - // Create new user - input.disabled = select.disabled = input.readonly = select.readonly = true; - const spinner = createSpinner(); - button.prepend(spinner); - try { - const resp = await api.createUser(username); - if (resp.status >= 300) { - let message = "Error creating user: " + resp.status + " " + resp.statusText; - try { - const res = await resp.json(); - if(res.error) { - message = res.error; - } - } catch (error) { - } - throw new Error(message); - } - - resolve({ username, userId: await resp.json(), created: true }); - } catch (err) { - spinner.remove(); - error.textContent = err.message ?? err.statusText ?? err ?? "An unknown error occurred."; - input.disabled = select.disabled = input.readonly = select.readonly = false; - return; - } - } else if (!select.value) { - error.textContent = "Please select an existing user."; - return; - } else { - resolve({ username: users[select.value], userId: select.value, created: false }); - } - }); - - if (user) { - const name = localStorage["Comfy.userName"]; - if (name) { - input.value = name; - } - } - if (input.value) { - // Focus the input, do this separately as sometimes browsers like to fill in the value - input.focus(); - } - - const userIds = Object.keys(users ?? {}); - if (userIds.length) { - for (const u of userIds) { - $el("option", { textContent: users[u], value: u, parent: select }); - } - select.style.color = "var(--descrip-text)"; - - if (select.value) { - // Focus the select, do this separately as sometimes browsers like to fill in the value - select.focus(); - } - } else { - userSelection.classList.add("no-users"); - input.focus(); - } - }).then((r) => { - userSelection.remove(); - return r; - }); - } -} +// Shim for scripts\ui\userSelection.ts +export const UserSelectionScreen = window.comfyAPI.userSelection.UserSelectionScreen; diff --git a/web/scripts/ui/utils.js b/web/scripts/ui/utils.js index e37d8b41e..903ba54a9 100644 --- a/web/scripts/ui/utils.js +++ b/web/scripts/ui/utils.js @@ -1,56 +1,3 @@ -/** - * @typedef { string | string[] | Record } ClassList - */ - -/** - * @param { HTMLElement } element - * @param { ClassList } classList - * @param { string[] } requiredClasses - */ -export function applyClasses(element, classList, ...requiredClasses) { - classList ??= ""; - - let str; - if (typeof classList === "string") { - str = classList; - } else if (classList instanceof Array) { - str = classList.join(" "); - } else { - str = Object.entries(classList).reduce((p, c) => { - if (c[1]) { - p += (p.length ? " " : "") + c[0]; - } - return p; - }, ""); - } - element.className = str; - if (requiredClasses) { - element.classList.add(...requiredClasses); - } -} - -/** - * @param { HTMLElement } element - * @param { { onHide?: (el: HTMLElement) => void, onShow?: (el: HTMLElement, value) => void } } [param1] - * @returns - */ -export function toggleElement(element, { onHide, onShow } = {}) { - let placeholder; - let hidden; - return (value) => { - if (value) { - if (hidden) { - hidden = false; - placeholder.replaceWith(element); - } - onShow?.(element, value); - } else { - if (!placeholder) { - placeholder = document.createComment(""); - } - hidden = true; - element.replaceWith(placeholder); - onHide?.(element); - } - }; -} +// Shim for scripts\ui\utils.ts +export const applyClasses = window.comfyAPI.utils.applyClasses; +export const toggleElement = window.comfyAPI.utils.toggleElement; diff --git a/web/scripts/utils.js b/web/scripts/utils.js index cda7600f6..425d6e2eb 100644 --- a/web/scripts/utils.js +++ b/web/scripts/utils.js @@ -1,156 +1,8 @@ -import { $el } from "./ui.js"; -import { api } from "./api.js"; - -// Simple date formatter -const parts = { - d: (d) => d.getDate(), - M: (d) => d.getMonth() + 1, - h: (d) => d.getHours(), - m: (d) => d.getMinutes(), - s: (d) => d.getSeconds(), -}; -const format = - Object.keys(parts) - .map((k) => k + k + "?") - .join("|") + "|yyy?y?"; - -function formatDate(text, date) { - return text.replace(new RegExp(format, "g"), function (text) { - if (text === "yy") return (date.getFullYear() + "").substring(2); - if (text === "yyyy") return date.getFullYear(); - if (text[0] in parts) { - const p = parts[text[0]](date); - return (p + "").padStart(text.length, "0"); - } - return text; - }); -} - - -export function clone(obj) { - try { - if (typeof structuredClone !== "undefined") { - return structuredClone(obj); - } - } catch (error) { - // structuredClone is stricter than using JSON.parse/stringify so fallback to that - } - - return JSON.parse(JSON.stringify(obj)); -} - -export function applyTextReplacements(app, value) { - return value.replace(/%([^%]+)%/g, function (match, text) { - const split = text.split("."); - if (split.length !== 2) { - // Special handling for dates - if (split[0].startsWith("date:")) { - return formatDate(split[0].substring(5), new Date()); - } - - if (text !== "width" && text !== "height") { - // Dont warn on standard replacements - console.warn("Invalid replacement pattern", text); - } - return match; - } - - // Find node with matching S&R property name - let nodes = app.graph._nodes.filter((n) => n.properties?.["Node name for S&R"] === split[0]); - // If we cant, see if there is a node with that title - if (!nodes.length) { - nodes = app.graph._nodes.filter((n) => n.title === split[0]); - } - if (!nodes.length) { - console.warn("Unable to find node", split[0]); - return match; - } - - if (nodes.length > 1) { - console.warn("Multiple nodes matched", split[0], "using first match"); - } - - const node = nodes[0]; - - const widget = node.widgets?.find((w) => w.name === split[1]); - if (!widget) { - console.warn("Unable to find widget", split[1], "on node", split[0], node); - return match; - } - - return ((widget.value ?? "") + "").replaceAll(/\/|\\/g, "_"); - }); -} - -export async function addStylesheet(urlOrFile, relativeTo) { - return new Promise((res, rej) => { - let url; - if (urlOrFile.endsWith(".js")) { - url = urlOrFile.substr(0, urlOrFile.length - 2) + "css"; - } else { - url = new URL(urlOrFile, relativeTo ?? `${window.location.protocol}//${window.location.host}`).toString(); - } - $el("link", { - parent: document.head, - rel: "stylesheet", - type: "text/css", - href: url, - onload: res, - onerror: rej, - }); - }); -} - -/** - * @param { string } filename - * @param { Blob } blob - */ -export function downloadBlob(filename, blob) { - const url = URL.createObjectURL(blob); - const a = $el("a", { - href: url, - download: filename, - style: { display: "none" }, - parent: document.body, - }); - a.click(); - setTimeout(function () { - a.remove(); - window.URL.revokeObjectURL(url); - }, 0); -} - -/** - * @template T - * @param {string} name - * @param {T} [defaultValue] - * @param {(currentValue: any, previousValue: any)=>void} [onChanged] - * @returns {T} - */ -export function prop(target, name, defaultValue, onChanged) { - let currentValue; - Object.defineProperty(target, name, { - get() { - return currentValue; - }, - set(newValue) { - const prevValue = currentValue; - currentValue = newValue; - onChanged?.(currentValue, prevValue, target, name); - }, - }); - return defaultValue; -} - -export function getStorageValue(id) { - const clientId = api.clientId ?? api.initialClientId; - return (clientId && sessionStorage.getItem(`${id}:${clientId}`)) ?? localStorage.getItem(id); -} - -export function setStorageValue(id, value) { - const clientId = api.clientId ?? api.initialClientId; - if (clientId) { - sessionStorage.setItem(`${id}:${clientId}`, value); - } - localStorage.setItem(id, value); -} \ No newline at end of file +// Shim for scripts\utils.ts +export const clone = window.comfyAPI.utils.clone; +export const applyTextReplacements = window.comfyAPI.utils.applyTextReplacements; +export const addStylesheet = window.comfyAPI.utils.addStylesheet; +export const downloadBlob = window.comfyAPI.utils.downloadBlob; +export const prop = window.comfyAPI.utils.prop; +export const getStorageValue = window.comfyAPI.utils.getStorageValue; +export const setStorageValue = window.comfyAPI.utils.setStorageValue; diff --git a/web/scripts/widgets.js b/web/scripts/widgets.js index 6a6899705..a1385e07c 100644 --- a/web/scripts/widgets.js +++ b/web/scripts/widgets.js @@ -1,531 +1,6 @@ -import { api } from "./api.js" -import "./domWidget.js"; - -let controlValueRunBefore = false; -export function updateControlWidgetLabel(widget) { - let replacement = "after"; - let find = "before"; - if (controlValueRunBefore) { - [find, replacement] = [replacement, find] - } - widget.label = (widget.label ?? widget.name).replace(find, replacement); -} - -const IS_CONTROL_WIDGET = Symbol(); -const HAS_EXECUTED = Symbol(); - -function getNumberDefaults(inputData, defaultStep, precision, enable_rounding) { - let defaultVal = inputData[1]["default"]; - let { min, max, step, round} = inputData[1]; - - if (defaultVal == undefined) defaultVal = 0; - if (min == undefined) min = 0; - if (max == undefined) max = 2048; - if (step == undefined) step = defaultStep; - // precision is the number of decimal places to show. - // by default, display the the smallest number of decimal places such that changes of size step are visible. - if (precision == undefined) { - precision = Math.max(-Math.floor(Math.log10(step)),0); - } - - if (enable_rounding && (round == undefined || round === true)) { - // by default, round the value to those decimal places shown. - round = Math.round(1000000*Math.pow(0.1,precision))/1000000; - } - - return { val: defaultVal, config: { min, max, step: 10.0 * step, round, precision } }; -} - -export function addValueControlWidget(node, targetWidget, defaultValue = "randomize", values, widgetName, inputData) { - let name = inputData[1]?.control_after_generate; - if(typeof name !== "string") { - name = widgetName; - } - const widgets = addValueControlWidgets(node, targetWidget, defaultValue, { - addFilterList: false, - controlAfterGenerateName: name - }, inputData); - return widgets[0]; -} - -export function addValueControlWidgets(node, targetWidget, defaultValue = "randomize", options, inputData) { - if (!defaultValue) defaultValue = "randomize"; - if (!options) options = {}; - - const getName = (defaultName, optionName) => { - let name = defaultName; - if (options[optionName]) { - name = options[optionName]; - } else if (typeof inputData?.[1]?.[defaultName] === "string") { - name = inputData?.[1]?.[defaultName]; - } else if (inputData?.[1]?.control_prefix) { - name = inputData?.[1]?.control_prefix + " " + name - } - return name; - } - - const widgets = []; - const valueControl = node.addWidget( - "combo", - getName("control_after_generate", "controlAfterGenerateName"), - defaultValue, - function () {}, - { - values: ["fixed", "increment", "decrement", "randomize"], - serialize: false, // Don't include this in prompt. - } - ); - valueControl[IS_CONTROL_WIDGET] = true; - updateControlWidgetLabel(valueControl); - widgets.push(valueControl); - - const isCombo = targetWidget.type === "combo"; - let comboFilter; - if (isCombo) { - valueControl.options.values.push("increment-wrap"); - } - if (isCombo && options.addFilterList !== false) { - comboFilter = node.addWidget( - "string", - getName("control_filter_list", "controlFilterListName"), - "", - function () {}, - { - serialize: false, // Don't include this in prompt. - } - ); - updateControlWidgetLabel(comboFilter); - - widgets.push(comboFilter); - } - - const applyWidgetControl = () => { - var v = valueControl.value; - - if (isCombo && v !== "fixed") { - let values = targetWidget.options.values; - const filter = comboFilter?.value; - if (filter) { - let check; - if (filter.startsWith("/") && filter.endsWith("/")) { - try { - const regex = new RegExp(filter.substring(1, filter.length - 1)); - check = (item) => regex.test(item); - } catch (error) { - console.error("Error constructing RegExp filter for node " + node.id, filter, error); - } - } - if (!check) { - const lower = filter.toLocaleLowerCase(); - check = (item) => item.toLocaleLowerCase().includes(lower); - } - values = values.filter(item => check(item)); - if (!values.length && targetWidget.options.values.length) { - console.warn("Filter for node " + node.id + " has filtered out all items", filter); - } - } - let current_index = values.indexOf(targetWidget.value); - let current_length = values.length; - - switch (v) { - case "increment": - current_index += 1; - break; - case "increment-wrap": - current_index += 1; - if ( current_index >= current_length ) { - current_index = 0; - } - break; - case "decrement": - current_index -= 1; - break; - case "randomize": - current_index = Math.floor(Math.random() * current_length); - default: - break; - } - current_index = Math.max(0, current_index); - current_index = Math.min(current_length - 1, current_index); - if (current_index >= 0) { - let value = values[current_index]; - targetWidget.value = value; - targetWidget.callback(value); - } - } else { - //number - let min = targetWidget.options.min; - let max = targetWidget.options.max; - // limit to something that javascript can handle - max = Math.min(1125899906842624, max); - min = Math.max(-1125899906842624, min); - let range = (max - min) / (targetWidget.options.step / 10); - - //adjust values based on valueControl Behaviour - switch (v) { - case "fixed": - break; - case "increment": - targetWidget.value += targetWidget.options.step / 10; - break; - case "decrement": - targetWidget.value -= targetWidget.options.step / 10; - break; - case "randomize": - targetWidget.value = Math.floor(Math.random() * range) * (targetWidget.options.step / 10) + min; - default: - break; - } - /*check if values are over or under their respective - * ranges and set them to min or max.*/ - if (targetWidget.value < min) targetWidget.value = min; - - if (targetWidget.value > max) - targetWidget.value = max; - targetWidget.callback(targetWidget.value); - } - }; - - valueControl.beforeQueued = () => { - if (controlValueRunBefore) { - // Don't run on first execution - if (valueControl[HAS_EXECUTED]) { - applyWidgetControl(); - } - } - valueControl[HAS_EXECUTED] = true; - }; - - valueControl.afterQueued = () => { - if (!controlValueRunBefore) { - applyWidgetControl(); - } - }; - - return widgets; -}; - -function seedWidget(node, inputName, inputData, app, widgetName) { - const seed = createIntWidget(node, inputName, inputData, app, true); - const seedControl = addValueControlWidget(node, seed.widget, "randomize", undefined, widgetName, inputData); - - seed.widget.linkedWidgets = [seedControl]; - return seed; -} - -function createIntWidget(node, inputName, inputData, app, isSeedInput) { - const control = inputData[1]?.control_after_generate; - if (!isSeedInput && control) { - return seedWidget(node, inputName, inputData, app, typeof control === "string" ? control : undefined); - } - - let widgetType = isSlider(inputData[1]["display"], app); - const { val, config } = getNumberDefaults(inputData, 1, 0, true); - Object.assign(config, { precision: 0 }); - return { - widget: node.addWidget( - widgetType, - inputName, - val, - function (v) { - const s = this.options.step / 10; - let sh = this.options.min % s; - if (isNaN(sh)) { - sh = 0; - } - this.value = Math.round((v - sh) / s) * s + sh; - }, - config - ), - }; -} - -function addMultilineWidget(node, name, opts, app) { - const inputEl = document.createElement("textarea"); - inputEl.className = "comfy-multiline-input"; - inputEl.value = opts.defaultVal; - inputEl.placeholder = opts.placeholder || name; - - const widget = node.addDOMWidget(name, "customtext", inputEl, { - getValue() { - return inputEl.value; - }, - setValue(v) { - inputEl.value = v; - }, - }); - widget.inputEl = inputEl; - - inputEl.addEventListener("input", () => { - widget.callback?.(widget.value); - }); - - return { minWidth: 400, minHeight: 200, widget }; -} - -function isSlider(display, app) { - if (app.ui.settings.getSettingValue("Comfy.DisableSliders")) { - return "number" - } - - return (display==="slider") ? "slider" : "number" -} - -export function initWidgets(app) { - app.ui.settings.addSetting({ - id: "Comfy.WidgetControlMode", - name: "Widget Value Control Mode", - type: "combo", - defaultValue: "after", - options: ["before", "after"], - tooltip: "Controls when widget values are updated (randomize/increment/decrement), either before the prompt is queued or after.", - onChange(value) { - controlValueRunBefore = value === "before"; - for (const n of app.graph._nodes) { - if (!n.widgets) continue; - for (const w of n.widgets) { - if (w[IS_CONTROL_WIDGET]) { - updateControlWidgetLabel(w); - if (w.linkedWidgets) { - for (const l of w.linkedWidgets) { - updateControlWidgetLabel(l); - } - } - } - } - } - app.graph.setDirtyCanvas(true); - }, - }); -} - -export const ComfyWidgets = { - "INT:seed": seedWidget, - "INT:noise_seed": seedWidget, - FLOAT(node, inputName, inputData, app) { - let widgetType = isSlider(inputData[1]["display"], app); - let precision = app.ui.settings.getSettingValue("Comfy.FloatRoundingPrecision"); - let disable_rounding = app.ui.settings.getSettingValue("Comfy.DisableFloatRounding") - if (precision == 0) precision = undefined; - const { val, config } = getNumberDefaults(inputData, 0.5, precision, !disable_rounding); - return { widget: node.addWidget(widgetType, inputName, val, - function (v) { - if (config.round) { - this.value = Math.round((v + Number.EPSILON)/config.round)*config.round; - if (this.value > config.max) this.value = config.max; - if (this.value < config.min) this.value = config.min; - } else { - this.value = v; - } - }, config) }; - }, - INT(node, inputName, inputData, app) { - return createIntWidget(node, inputName, inputData, app); - }, - BOOLEAN(node, inputName, inputData) { - let defaultVal = false; - let options = {}; - if (inputData[1]) { - if (inputData[1].default) - defaultVal = inputData[1].default; - if (inputData[1].label_on) - options["on"] = inputData[1].label_on; - if (inputData[1].label_off) - options["off"] = inputData[1].label_off; - } - return { - widget: node.addWidget( - "toggle", - inputName, - defaultVal, - () => {}, - options, - ) - }; - }, - STRING(node, inputName, inputData, app) { - const defaultVal = inputData[1].default || ""; - const multiline = !!inputData[1].multiline; - - let res; - if (multiline) { - res = addMultilineWidget(node, inputName, { defaultVal, ...inputData[1] }, app); - } else { - res = { widget: node.addWidget("text", inputName, defaultVal, () => {}, {}) }; - } - - if(inputData[1].dynamicPrompts != undefined) - res.widget.dynamicPrompts = inputData[1].dynamicPrompts; - - return res; - }, - COMBO(node, inputName, inputData) { - const type = inputData[0]; - let defaultValue = type[0]; - if (inputData[1] && inputData[1].default) { - defaultValue = inputData[1].default; - } - const res = { widget: node.addWidget("combo", inputName, defaultValue, () => {}, { values: type }) }; - if (inputData[1]?.control_after_generate) { - res.widget.linkedWidgets = addValueControlWidgets(node, res.widget, undefined, undefined, inputData); - } - return res; - }, - IMAGEUPLOAD(node, inputName, inputData, app) { - const imageWidget = node.widgets.find((w) => w.name === (inputData[1]?.widget ?? "image")); - let uploadWidget; - - function showImage(name) { - const img = new Image(); - img.onload = () => { - node.imgs = [img]; - app.graph.setDirtyCanvas(true); - }; - let folder_separator = name.lastIndexOf("/"); - let subfolder = ""; - if (folder_separator > -1) { - subfolder = name.substring(0, folder_separator); - name = name.substring(folder_separator + 1); - } - img.src = api.apiURL(`/view?filename=${encodeURIComponent(name)}&type=input&subfolder=${subfolder}${app.getPreviewFormatParam()}${app.getRandParam()}`); - node.setSizeForImage?.(); - } - - var default_value = imageWidget.value; - Object.defineProperty(imageWidget, "value", { - set : function(value) { - this._real_value = value; - }, - - get : function() { - let value = ""; - if (this._real_value) { - value = this._real_value; - } else { - return default_value; - } - - if (value.filename) { - let real_value = value; - value = ""; - if (real_value.subfolder) { - value = real_value.subfolder + "/"; - } - - value += real_value.filename; - - if(real_value.type && real_value.type !== "input") - value += ` [${real_value.type}]`; - } - return value; - } - }); - - // Add our own callback to the combo widget to render an image when it changes - const cb = node.callback; - imageWidget.callback = function () { - showImage(imageWidget.value); - if (cb) { - return cb.apply(this, arguments); - } - }; - - // On load if we have a value then render the image - // The value isnt set immediately so we need to wait a moment - // No change callbacks seem to be fired on initial setting of the value - requestAnimationFrame(() => { - if (imageWidget.value) { - showImage(imageWidget.value); - } - }); - - async function uploadFile(file, updateNode, pasted = false) { - try { - // Wrap file in formdata so it includes filename - const body = new FormData(); - body.append("image", file); - if (pasted) body.append("subfolder", "pasted"); - const resp = await api.fetchApi("/upload/image", { - method: "POST", - body, - }); - - if (resp.status === 200) { - const data = await resp.json(); - // Add the file to the dropdown list and update the widget value - let path = data.name; - if (data.subfolder) path = data.subfolder + "/" + path; - - if (!imageWidget.options.values.includes(path)) { - imageWidget.options.values.push(path); - } - - if (updateNode) { - showImage(path); - imageWidget.value = path; - } - } else { - alert(resp.status + " - " + resp.statusText); - } - } catch (error) { - alert(error); - } - } - - const fileInput = document.createElement("input"); - Object.assign(fileInput, { - type: "file", - accept: "image/jpeg,image/png,image/webp", - style: "display: none", - onchange: async () => { - if (fileInput.files.length) { - await uploadFile(fileInput.files[0], true); - } - }, - }); - document.body.append(fileInput); - - // Create the button widget for selecting the files - uploadWidget = node.addWidget("button", inputName, "image", () => { - fileInput.click(); - }); - uploadWidget.label = "choose file to upload"; - uploadWidget.serialize = false; - - // Add handler to check if an image is being dragged over our node - node.onDragOver = function (e) { - if (e.dataTransfer && e.dataTransfer.items) { - const image = [...e.dataTransfer.items].find((f) => f.kind === "file"); - return !!image; - } - - return false; - }; - - // On drop upload files - node.onDragDrop = function (e) { - console.log("onDragDrop called"); - let handled = false; - for (const file of e.dataTransfer.files) { - if (file.type.startsWith("image/")) { - uploadFile(file, !handled); // Dont await these, any order is fine, only update on first one - handled = true; - } - } - - return handled; - }; - - node.pasteFile = function(file) { - if (file.type.startsWith("image/")) { - const is_pasted = (file.name === "image.png") && - (file.lastModified - Date.now() < 2000); - uploadFile(file, true, is_pasted); - return true; - } - return false; - } - - return { widget: uploadWidget }; - }, -}; +// Shim for scripts\widgets.ts +export const updateControlWidgetLabel = window.comfyAPI.widgets.updateControlWidgetLabel; +export const addValueControlWidget = window.comfyAPI.widgets.addValueControlWidget; +export const addValueControlWidgets = window.comfyAPI.widgets.addValueControlWidgets; +export const initWidgets = window.comfyAPI.widgets.initWidgets; +export const ComfyWidgets = window.comfyAPI.widgets.ComfyWidgets; diff --git a/web/scripts/workflows.js b/web/scripts/workflows.js index d38b6f5fc..c8c7ff43d 100644 --- a/web/scripts/workflows.js +++ b/web/scripts/workflows.js @@ -1,450 +1,4 @@ -// @ts-check - -import { api } from "./api.js"; -import { ChangeTracker } from "./changeTracker.js"; -import { ComfyAsyncDialog } from "./ui/components/asyncDialog.js"; -import { getStorageValue, setStorageValue } from "./utils.js"; - -function appendJsonExt(path) { - if (!path.toLowerCase().endsWith(".json")) { - path += ".json"; - } - return path; -} - -export function trimJsonExt(path) { - return path?.replace(/\.json$/, ""); -} - -export class ComfyWorkflowManager extends EventTarget { - /** @type {string | null} */ - #activePromptId = null; - #unsavedCount = 0; - #activeWorkflow; - - /** @type {Record} */ - workflowLookup = {}; - /** @type {Array} */ - workflows = []; - /** @type {Array} */ - openWorkflows = []; - /** @type {Record}>} */ - queuedPrompts = {}; - - get activeWorkflow() { - return this.#activeWorkflow ?? this.openWorkflows[0]; - } - - get activePromptId() { - return this.#activePromptId; - } - - get activePrompt() { - return this.queuedPrompts[this.#activePromptId]; - } - - /** - * @param {import("./app.js").ComfyApp} app - */ - constructor(app) { - super(); - this.app = app; - ChangeTracker.init(app); - - this.#bindExecutionEvents(); - } - - #bindExecutionEvents() { - // TODO: on reload, set active prompt based on the latest ws message - - const emit = () => this.dispatchEvent(new CustomEvent("execute", { detail: this.activePrompt })); - let executing = null; - api.addEventListener("execution_start", (e) => { - this.#activePromptId = e.detail.prompt_id; - - // This event can fire before the event is stored, so put a placeholder - this.queuedPrompts[this.#activePromptId] ??= { nodes: {} }; - emit(); - }); - api.addEventListener("execution_cached", (e) => { - if (!this.activePrompt) return; - for (const n of e.detail.nodes) { - this.activePrompt.nodes[n] = true; - } - emit(); - }); - api.addEventListener("executed", (e) => { - if (!this.activePrompt) return; - this.activePrompt.nodes[e.detail.node] = true; - emit(); - }); - api.addEventListener("executing", (e) => { - if (!this.activePrompt) return; - - if (executing) { - // Seems sometimes nodes that are cached fire executing but not executed - this.activePrompt.nodes[executing] = true; - } - executing = e.detail; - if (!executing) { - delete this.queuedPrompts[this.#activePromptId]; - this.#activePromptId = null; - } - emit(); - }); - } - - async loadWorkflows() { - try { - let favorites; - const resp = await api.getUserData("workflows/.index.json"); - let info; - if (resp.status === 200) { - info = await resp.json(); - favorites = new Set(info?.favorites ?? []); - } else { - favorites = new Set(); - } - - const workflows = (await api.listUserData("workflows", true, true)).map((w) => { - let workflow = this.workflowLookup[w[0]]; - if (!workflow) { - workflow = new ComfyWorkflow(this, w[0], w.slice(1), favorites.has(w[0])); - this.workflowLookup[workflow.path] = workflow; - } - return workflow; - }); - - this.workflows = workflows; - } catch (error) { - alert("Error loading workflows: " + (error.message ?? error)); - this.workflows = []; - } - } - - async saveWorkflowMetadata() { - await api.storeUserData("workflows/.index.json", { - favorites: [...this.workflows.filter((w) => w.isFavorite).map((w) => w.path)], - }); - } - - /** - * @param {string | ComfyWorkflow | null} workflow - */ - setWorkflow(workflow) { - if (workflow && typeof workflow === "string") { - // Selected by path, i.e. on reload of last workflow - const found = this.workflows.find((w) => w.path === workflow); - if (found) { - workflow = found; - workflow.unsaved = !workflow || getStorageValue("Comfy.PreviousWorkflowUnsaved") === "true"; - } - } - - if (!(workflow instanceof ComfyWorkflow)) { - // Still not found, either reloading a deleted workflow or blank - workflow = new ComfyWorkflow(this, workflow || "Unsaved Workflow" + (this.#unsavedCount++ ? ` (${this.#unsavedCount})` : "")); - } - - const index = this.openWorkflows.indexOf(workflow); - if (index === -1) { - // Opening a new workflow - this.openWorkflows.push(workflow); - } - - this.#activeWorkflow = workflow; - - setStorageValue("Comfy.PreviousWorkflow", this.activeWorkflow.path ?? ""); - this.dispatchEvent(new CustomEvent("changeWorkflow")); - } - - storePrompt({ nodes, id }) { - this.queuedPrompts[id] ??= {}; - this.queuedPrompts[id].nodes = { - ...nodes.reduce((p, n) => { - p[n] = false; - return p; - }, {}), - ...this.queuedPrompts[id].nodes, - }; - this.queuedPrompts[id].workflow = this.activeWorkflow; - } - - /** - * @param {ComfyWorkflow} workflow - */ - async closeWorkflow(workflow, warnIfUnsaved = true) { - if (!workflow.isOpen) { - return true; - } - if (workflow.unsaved && warnIfUnsaved) { - const res = await ComfyAsyncDialog.prompt({ - title: "Save Changes?", - message: `Do you want to save changes to "${workflow.path ?? workflow.name}" before closing?`, - actions: ["Yes", "No", "Cancel"], - }); - if (res === "Yes") { - const active = this.activeWorkflow; - if (active !== workflow) { - // We need to switch to the workflow to save it - await workflow.load(); - } - - if (!(await workflow.save())) { - // Save was canceled, restore the previous workflow - if (active !== workflow) { - await active.load(); - } - return; - } - } else if (res === "Cancel") { - return; - } - } - workflow.changeTracker = null; - this.openWorkflows.splice(this.openWorkflows.indexOf(workflow), 1); - if (this.openWorkflows.length) { - this.#activeWorkflow = this.openWorkflows[0]; - await this.#activeWorkflow.load(); - } else { - // Load default - await this.app.loadGraphData(); - } - } -} - -export class ComfyWorkflow { - #name; - #path; - #pathParts; - #isFavorite = false; - /** @type {ChangeTracker | null} */ - changeTracker = null; - unsaved = false; - - get name() { - return this.#name; - } - - get path() { - return this.#path; - } - - get pathParts() { - return this.#pathParts; - } - - get isFavorite() { - return this.#isFavorite; - } - - get isOpen() { - return !!this.changeTracker; - } - - /** - * @overload - * @param {ComfyWorkflowManager} manager - * @param {string} path - */ - /** - * @overload - * @param {ComfyWorkflowManager} manager - * @param {string} path - * @param {string[]} pathParts - * @param {boolean} isFavorite - */ - /** - * @param {ComfyWorkflowManager} manager - * @param {string} path - * @param {string[]} [pathParts] - * @param {boolean} [isFavorite] - */ - constructor(manager, path, pathParts, isFavorite) { - this.manager = manager; - if (pathParts) { - this.#updatePath(path, pathParts); - this.#isFavorite = isFavorite; - } else { - this.#name = path; - this.unsaved = true; - } - } - - /** - * @param {string} path - * @param {string[]} [pathParts] - */ - #updatePath(path, pathParts) { - this.#path = path; - - if (!pathParts) { - if (!path.includes("\\")) { - pathParts = path.split("/"); - } else { - pathParts = path.split("\\"); - } - } - - this.#pathParts = pathParts; - this.#name = trimJsonExt(pathParts[pathParts.length - 1]); - } - - async getWorkflowData() { - const resp = await api.getUserData("workflows/" + this.path); - if (resp.status !== 200) { - alert(`Error loading workflow file '${this.path}': ${resp.status} ${resp.statusText}`); - return; - } - return await resp.json(); - } - - load = async () => { - if (this.isOpen) { - await this.manager.app.loadGraphData(this.changeTracker.activeState, true, true, this); - } else { - const data = await this.getWorkflowData(); - if (!data) return; - await this.manager.app.loadGraphData(data, true, true, this); - } - }; - - async save(saveAs = false) { - if (!this.path || saveAs) { - return !!(await this.#save(null, false)); - } else { - return !!(await this.#save(this.path, true)); - } - } - - /** - * @param {boolean} value - */ - async favorite(value) { - try { - if (this.#isFavorite === value) return; - this.#isFavorite = value; - await this.manager.saveWorkflowMetadata(); - this.manager.dispatchEvent(new CustomEvent("favorite", { detail: this })); - } catch (error) { - alert("Error favoriting workflow " + this.path + "\n" + (error.message ?? error)); - } - } - - /** - * @param {string} path - */ - async rename(path) { - path = appendJsonExt(path); - let resp = await api.moveUserData("workflows/" + this.path, "workflows/" + path); - - if (resp.status === 409) { - if (!confirm(`Workflow '${path}' already exists, do you want to overwrite it?`)) return resp; - resp = await api.moveUserData("workflows/" + this.path, "workflows/" + path, { overwrite: true }); - } - - if (resp.status !== 200) { - alert(`Error renaming workflow file '${this.path}': ${resp.status} ${resp.statusText}`); - return; - } - - const isFav = this.isFavorite; - if (isFav) { - await this.favorite(false); - } - path = (await resp.json()).substring("workflows/".length); - this.#updatePath(path, null); - if (isFav) { - await this.favorite(true); - } - this.manager.dispatchEvent(new CustomEvent("rename", { detail: this })); - setStorageValue("Comfy.PreviousWorkflow", this.path ?? ""); - } - - async insert() { - const data = await this.getWorkflowData(); - if (!data) return; - - const old = localStorage.getItem("litegrapheditor_clipboard"); - const graph = new LGraph(data); - const canvas = new LGraphCanvas(null, graph, { skip_events: true, skip_render: true }); - canvas.selectNodes(); - canvas.copyToClipboard(); - this.manager.app.canvas.pasteFromClipboard(); - localStorage.setItem("litegrapheditor_clipboard", old); - } - - async delete() { - // TODO: fix delete of current workflow - should mark workflow as unsaved and when saving use old name by default - - try { - if (this.isFavorite) { - await this.favorite(false); - } - await api.deleteUserData("workflows/" + this.path); - this.unsaved = true; - this.#path = null; - this.#pathParts = null; - this.manager.workflows.splice(this.manager.workflows.indexOf(this), 1); - this.manager.dispatchEvent(new CustomEvent("delete", { detail: this })); - } catch (error) { - alert(`Error deleting workflow: ${error.message || error}`); - } - } - - track() { - if (this.changeTracker) { - this.changeTracker.restore(); - } else { - this.changeTracker = new ChangeTracker(this); - } - } - - /** - * @param {string|null} path - * @param {boolean} overwrite - */ - async #save(path, overwrite) { - if (!path) { - path = prompt("Save workflow as:", trimJsonExt(this.path) ?? this.name ?? "workflow"); - if (!path) return; - } - - path = appendJsonExt(path); - - const p = await this.manager.app.graphToPrompt(); - const json = JSON.stringify(p.workflow, null, 2); - let resp = await api.storeUserData("workflows/" + path, json, { stringify: false, throwOnError: false, overwrite }); - if (resp.status === 409) { - if (!confirm(`Workflow '${path}' already exists, do you want to overwrite it?`)) return; - resp = await api.storeUserData("workflows/" + path, json, { stringify: false }); - } - - if (resp.status !== 200) { - alert(`Error saving workflow '${this.path}': ${resp.status} ${resp.statusText}`); - return; - } - - path = (await resp.json()).substring("workflows/".length); - - if (!this.path) { - // Saved new workflow, patch this instance - this.#updatePath(path, null); - await this.manager.loadWorkflows(); - this.unsaved = false; - this.manager.dispatchEvent(new CustomEvent("rename", { detail: this })); - setStorageValue("Comfy.PreviousWorkflow", this.path ?? ""); - } else if (path !== this.path) { - // Saved as, open the new copy - await this.manager.loadWorkflows(); - const workflow = this.manager.workflowLookup[path]; - await workflow.load(); - } else { - // Normal save - this.unsaved = false; - this.manager.dispatchEvent(new CustomEvent("save", { detail: this })); - } - - return true; - } -} +// Shim for scripts\workflows.ts +export const trimJsonExt = window.comfyAPI.workflows.trimJsonExt; +export const ComfyWorkflowManager = window.comfyAPI.workflows.ComfyWorkflowManager; +export const ComfyWorkflow = window.comfyAPI.workflows.ComfyWorkflow; diff --git a/web/style.css b/web/style.css deleted file mode 100644 index 8ef1d0dd1..000000000 --- a/web/style.css +++ /dev/null @@ -1,647 +0,0 @@ -@import url("scripts/ui/menu/menu.css"); - -:root { - --fg-color: #000; - --bg-color: #fff; - --comfy-menu-bg: #353535; - --comfy-input-bg: #222; - --input-text: #ddd; - --descrip-text: #999; - --drag-text: #ccc; - --error-text: #ff4444; - --border-color: #4e4e4e; - --tr-even-bg-color: #222; - --tr-odd-bg-color: #353535; - --primary-bg: #236692; - --primary-fg: #ffffff; - --primary-hover-bg: #3485bb; - --primary-hover-fg: #ffffff; - --content-bg: #e0e0e0; - --content-fg: #000; - --content-hover-bg: #adadad; - --content-hover-fg: #000; -} - -@media (prefers-color-scheme: dark) { - :root { - --fg-color: #fff; - --bg-color: #202020; - --content-bg: #4e4e4e; - --content-fg: #fff; - --content-hover-bg: #222; - --content-hover-fg: #fff; - } -} - -body { - width: 100vw; - height: 100vh; - margin: 0; - overflow: hidden; - background-color: var(--bg-color); - color: var(--fg-color); - grid-template-columns: auto 1fr auto; - grid-template-rows: auto 1fr auto; - min-height: -webkit-fill-available; - max-height: -webkit-fill-available; - min-width: -webkit-fill-available; - max-width: -webkit-fill-available; -} - -.comfyui-body-top { - order: -5; - grid-column: 1/-1; - z-index: 10; - display: flex; - flex-direction: column; -} - -.comfyui-body-left { - order: -4; - z-index: 10; - display: flex; -} - -#graph-canvas { - width: 100%; - height: 100%; - order: -3; -} - -.comfyui-body-right { - order: -2; - z-index: 10; - display: flex; -} - -.comfyui-body-bottom { - order: -1; - grid-column: 1/-1; - z-index: 10; - display: flex; - flex-direction: column; -} - -.comfy-multiline-input { - background-color: var(--comfy-input-bg); - color: var(--input-text); - overflow: hidden; - overflow-y: auto; - padding: 2px; - resize: none; - border: none; - box-sizing: border-box; - font-size: 10px; -} - -.comfy-modal { - display: none; /* Hidden by default */ - position: fixed; /* Stay in place */ - z-index: 100; /* Sit on top */ - padding: 30px 30px 10px 30px; - background-color: var(--comfy-menu-bg); /* Modal background */ - color: var(--error-text); - box-shadow: 0 0 20px #888888; - border-radius: 10px; - top: 50%; - left: 50%; - max-width: 80vw; - max-height: 80vh; - transform: translate(-50%, -50%); - overflow: hidden; - justify-content: center; - font-family: monospace; - font-size: 15px; -} - -.comfy-modal-content { - display: flex; - flex-direction: column; -} - -.comfy-modal p { - overflow: auto; - white-space: pre-line; /* This will respect line breaks */ - margin-bottom: 20px; /* Add some margin between the text and the close button*/ -} - -.comfy-modal select, -.comfy-modal input[type=button], -.comfy-modal input[type=checkbox] { - margin: 3px 3px 3px 4px; -} - -.comfy-menu-hamburger { - position: fixed; - top: 10px; - z-index: 9999; - right: 10px; - width: 30px; - display: none; - gap: 8px; - flex-direction: column; - cursor: pointer; -} -.comfy-menu-hamburger div { - height: 3px; - width: 100%; - border-radius: 20px; - background-color: white; -} - -.comfy-menu { - font-size: 15px; - position: absolute; - top: 50%; - right: 0; - text-align: center; - z-index: 999; - width: 170px; - display: flex; - flex-direction: column; - align-items: center; - color: var(--descrip-text); - background-color: var(--comfy-menu-bg); - font-family: sans-serif; - padding: 10px; - border-radius: 0 8px 8px 8px; - box-shadow: 3px 3px 8px rgba(0, 0, 0, 0.4); -} - -.comfy-menu-header { - display: flex; -} - -.comfy-menu-actions { - display: flex; - gap: 3px; - align-items: center; - height: 20px; - position: relative; - top: -1px; - font-size: 22px; -} - -.comfy-menu .comfy-menu-actions button { - background-color: rgba(0, 0, 0, 0); - padding: 0; - border: none; - cursor: pointer; - font-size: inherit; -} - -.comfy-menu .comfy-menu-actions .comfy-settings-btn { - font-size: 0.6em; -} - -button.comfy-close-menu-btn { - font-size: 1em; - line-height: 12px; - color: #ccc; - position: relative; - top: -1px; -} - -.comfy-menu-queue-size { - flex: auto; -} - -.comfy-menu button, -.comfy-modal button { - font-size: 20px; -} - -.comfy-menu-btns { - margin-bottom: 10px; - width: 100%; -} - -.comfy-menu-btns button { - font-size: 10px; - width: 50%; - color: var(--descrip-text) !important; -} - -.comfy-menu > button { - width: 100%; -} - -.comfy-btn, -.comfy-menu > button, -.comfy-menu-btns button, -.comfy-menu .comfy-list button, -.comfy-modal button { - color: var(--input-text); - background-color: var(--comfy-input-bg); - border-radius: 8px; - border-color: var(--border-color); - border-style: solid; - margin-top: 2px; -} - -.comfy-btn:hover:not(:disabled), -.comfy-menu > button:hover, -.comfy-menu-btns button:hover, -.comfy-menu .comfy-list button:hover, -.comfy-modal button:hover, -.comfy-menu-actions button:hover { - filter: brightness(1.2); - will-change: transform; - cursor: pointer; -} - -span.drag-handle { - width: 10px; - height: 20px; - display: inline-block; - overflow: hidden; - line-height: 5px; - padding: 3px 4px; - cursor: move; - vertical-align: middle; - margin-top: -.4em; - margin-left: -.2em; - font-size: 12px; - font-family: sans-serif; - letter-spacing: 2px; - color: var(--drag-text); - text-shadow: 1px 0 1px black; -} - -span.drag-handle::after { - content: '.. .. ..'; -} - -.comfy-queue-btn { - width: 100%; -} - -.comfy-list { - color: var(--descrip-text); - background-color: var(--comfy-menu-bg); - margin-bottom: 10px; - border-color: var(--border-color); - border-style: solid; -} - -.comfy-list-items { - overflow-y: scroll; - max-height: 100px; - min-height: 25px; - background-color: var(--comfy-input-bg); - padding: 5px; -} - -.comfy-list h4 { - min-width: 160px; - margin: 0; - padding: 3px; - font-weight: normal; -} - -.comfy-list-items button { - font-size: 10px; -} - -.comfy-list-actions { - margin: 5px; - display: flex; - gap: 5px; - justify-content: center; -} - -.comfy-list-actions button { - font-size: 12px; -} - -button.comfy-queue-btn { - margin: 6px 0 !important; -} - -.comfy-modal.comfy-settings, -.comfy-modal.comfy-manage-templates { - text-align: center; - font-family: sans-serif; - color: var(--descrip-text); - z-index: 99; -} - -.comfy-modal.comfy-settings input[type="range"] { - vertical-align: middle; -} - -.comfy-modal.comfy-settings input[type="range"] + input[type="number"] { - width: 3.5em; -} - -.comfy-modal input, -.comfy-modal select { - color: var(--input-text); - background-color: var(--comfy-input-bg); - border-radius: 8px; - border-color: var(--border-color); - border-style: solid; - font-size: inherit; -} - -.comfy-tooltip-indicator { - text-decoration: underline; - text-decoration-style: dashed; -} - -@media only screen and (max-height: 850px) { - .comfy-menu { - top: 0 !important; - bottom: 0 !important; - left: auto !important; - right: 0 !important; - border-radius: 0; - } - - .comfy-menu span.drag-handle { - display: none; - } - - .comfy-menu-queue-size { - flex: unset; - } - - .comfy-menu-header { - justify-content: space-between; - } - .comfy-menu-actions { - gap: 10px; - font-size: 28px; - } -} - -/* Input popup */ - -.graphdialog { - min-height: 1em; - background-color: var(--comfy-menu-bg); -} - -.graphdialog .name { - font-size: 14px; - font-family: sans-serif; - color: var(--descrip-text); -} - -.graphdialog button { - margin-top: unset; - vertical-align: unset; - height: 1.6em; - padding-right: 8px; -} - -.graphdialog input, .graphdialog textarea, .graphdialog select { - background-color: var(--comfy-input-bg); - border: 2px solid; - border-color: var(--border-color); - color: var(--input-text); - border-radius: 12px 0 0 12px; -} - -/* Dialogs */ - -dialog { - box-shadow: 0 0 20px #888888; -} - -dialog::backdrop { - background: rgba(0, 0, 0, 0.5); -} - -.comfy-dialog.comfyui-dialog.comfy-modal { - top: 0; - left: 0; - right: 0; - bottom: 0; - transform: none; -} - -.comfy-dialog.comfy-modal { - font-family: Arial, sans-serif; - border-color: var(--bg-color); - box-shadow: none; - border: 2px solid var(--border-color); -} - -.comfy-dialog .comfy-modal-content { - flex-direction: row; - flex-wrap: wrap; - gap: 10px; - color: var(--fg-color); -} - -.comfy-dialog .comfy-modal-content h3 { - margin-top: 0; -} - -.comfy-dialog .comfy-modal-content > p { - width: 100%; -} - -.comfy-dialog .comfy-modal-content > .comfyui-button { - flex: 1; - justify-content: center; -} - -#comfy-settings-dialog { - padding: 0; - width: 41rem; -} - -#comfy-settings-dialog tr > td:first-child { - text-align: right; -} - -#comfy-settings-dialog tbody button, #comfy-settings-dialog table > button { - background-color: var(--bg-color); - border: 1px var(--border-color) solid; - border-radius: 0; - color: var(--input-text); - font-size: 1rem; - padding: 0.5rem; -} - -#comfy-settings-dialog button:hover { - background-color: var(--tr-odd-bg-color); -} - -/* General CSS for tables */ - -.comfy-table { - border-collapse: collapse; - color: var(--input-text); - font-family: Arial, sans-serif; - width: 100%; -} - -.comfy-table caption { - position: sticky; - top: 0; - background-color: var(--bg-color); - color: var(--input-text); - font-size: 1rem; - font-weight: bold; - padding: 8px; - text-align: center; - border-bottom: 1px solid var(--border-color); -} - -.comfy-table caption .comfy-btn { - position: absolute; - top: -2px; - right: 0; - bottom: 0; - cursor: pointer; - border: none; - height: 100%; - border-radius: 0; - aspect-ratio: 1/1; - user-select: none; - font-size: 20px; -} - -.comfy-table caption .comfy-btn:focus { - outline: none; -} - -.comfy-table tr:nth-child(even) { - background-color: var(--tr-even-bg-color); -} - -.comfy-table tr:nth-child(odd) { - background-color: var(--tr-odd-bg-color); -} - -.comfy-table td, -.comfy-table th { - border: 1px solid var(--border-color); - padding: 8px; -} - -/* Context menu */ - -.litegraph .dialog { - z-index: 1; - font-family: Arial, sans-serif; -} - -.litegraph .litemenu-entry.has_submenu { - position: relative; - padding-right: 20px; -} - -.litemenu-entry.has_submenu::after { - content: ">"; - position: absolute; - top: 0; - right: 2px; -} - -.litegraph.litecontextmenu, -.litegraph.litecontextmenu.dark { - z-index: 9999 !important; - background-color: var(--comfy-menu-bg) !important; - filter: brightness(95%); - will-change: transform; -} - -.litegraph.litecontextmenu .litemenu-entry:hover:not(.disabled):not(.separator) { - background-color: var(--comfy-menu-bg) !important; - filter: brightness(155%); - will-change: transform; - color: var(--input-text); -} - -.litegraph.litecontextmenu .litemenu-entry.submenu, -.litegraph.litecontextmenu.dark .litemenu-entry.submenu { - background-color: var(--comfy-menu-bg) !important; - color: var(--input-text); -} - -.litegraph.litecontextmenu input { - background-color: var(--comfy-input-bg) !important; - color: var(--input-text) !important; -} - -.comfy-context-menu-filter { - box-sizing: border-box; - border: 1px solid #999; - margin: 0 0 5px 5px; - width: calc(100% - 10px); -} - -.comfy-img-preview { - pointer-events: none; - overflow: hidden; - display: flex; - flex-wrap: wrap; - align-content: flex-start; - justify-content: center; -} - -.comfy-img-preview img { - object-fit: contain; - width: var(--comfy-img-preview-width); - height: var(--comfy-img-preview-height); -} - -.comfy-missing-nodes li button { - font-size: 12px; - margin-left: 5px; -} - -/* Search box */ - -.litegraph.litesearchbox { - z-index: 9999 !important; - background-color: var(--comfy-menu-bg) !important; - overflow: hidden; - display: block; -} - -.litegraph.litesearchbox input, -.litegraph.litesearchbox select { - background-color: var(--comfy-input-bg) !important; - color: var(--input-text); -} - -.litegraph.lite-search-item { - color: var(--input-text); - background-color: var(--comfy-input-bg); - filter: brightness(80%); - will-change: transform; - padding-left: 0.2em; -} - -.litegraph.lite-search-item.generic_type { - color: var(--input-text); - filter: brightness(50%); - will-change: transform; -} - -@media only screen and (max-width: 450px) { - #comfy-settings-dialog .comfy-table tbody { - display: grid; - } - #comfy-settings-dialog .comfy-table tr { - display: grid; - } - #comfy-settings-dialog tr > td:first-child { - text-align: center; - border-bottom: none; - padding-bottom: 0; - } - #comfy-settings-dialog tr > td:not(:first-child) { - text-align: center; - border-top: none; - } -} - -audio.comfy-audio.empty-audio-widget { - display: none; -} diff --git a/web/types/comfy.d.ts b/web/types/comfy.d.ts deleted file mode 100644 index 9a338b349..000000000 --- a/web/types/comfy.d.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { LGraphNode, IWidget } from "./litegraph"; -import { ComfyApp } from "../../scripts/app"; - -export interface ComfyExtension { - /** - * The name of the extension - */ - name: string; - /** - * Allows any initialisation, e.g. loading resources. Called after the canvas is created but before nodes are added - * @param app The ComfyUI app instance - */ - init?(app: ComfyApp): Promise; - /** - * Allows any additonal setup, called after the application is fully set up and running - * @param app The ComfyUI app instance - */ - setup?(app: ComfyApp): Promise; - /** - * Called before nodes are registered with the graph - * @param defs The collection of node definitions, add custom ones or edit existing ones - * @param app The ComfyUI app instance - */ - addCustomNodeDefs?(defs: Record, app: ComfyApp): Promise; - /** - * Allows the extension to add custom widgets - * @param app The ComfyUI app instance - * @returns An array of {[widget name]: widget data} - */ - getCustomWidgets?( - app: ComfyApp - ): Promise< - Record { widget?: IWidget; minWidth?: number; minHeight?: number }> - >; - /** - * Allows the extension to add additional handling to the node before it is registered with LGraph - * @param nodeType The node class (not an instance) - * @param nodeData The original node object info config object - * @param app The ComfyUI app instance - */ - beforeRegisterNodeDef?(nodeType: typeof LGraphNode, nodeData: ComfyObjectInfo, app: ComfyApp): Promise; - /** - * Allows the extension to register additional nodes with LGraph after standard nodes are added - * @param app The ComfyUI app instance - */ - registerCustomNodes?(app: ComfyApp): Promise; - /** - * Allows the extension to modify a node that has been reloaded onto the graph. - * If you break something in the backend and want to patch workflows in the frontend - * This is the place to do this - * @param node The node that has been loaded - * @param app The ComfyUI app instance - */ - loadedGraphNode?(node: LGraphNode, app: ComfyApp); - /** - * Allows the extension to run code after the constructor of the node - * @param node The node that has been created - * @param app The ComfyUI app instance - */ - nodeCreated?(node: LGraphNode, app: ComfyApp); -} - -export type ComfyObjectInfo = { - name: string; - display_name?: string; - description?: string; - category: string; - input?: { - required?: Record; - optional?: Record; - }; - output?: string[]; - output_name: string[]; -}; - -export type ComfyObjectInfoConfig = [string | any[]] | [string | any[], any]; diff --git a/web/types/litegraph.d.ts b/web/types/litegraph.d.ts deleted file mode 100644 index 6629e779f..000000000 --- a/web/types/litegraph.d.ts +++ /dev/null @@ -1,1506 +0,0 @@ -// Type definitions for litegraph.js 0.7.0 -// Project: litegraph.js -// Definitions by: NateScarlet - -export type Vector2 = [number, number]; -export type Vector4 = [number, number, number, number]; -export type widgetTypes = - | "number" - | "slider" - | "combo" - | "text" - | "toggle" - | "button"; -export type SlotShape = - | typeof LiteGraph.BOX_SHAPE - | typeof LiteGraph.CIRCLE_SHAPE - | typeof LiteGraph.ARROW_SHAPE - | typeof LiteGraph.SQUARE_SHAPE - | number; // For custom shapes - -/** https://github.com/jagenjo/litegraph.js/tree/master/guides#node-slots */ -export interface INodeSlot { - name: string; - type: string | -1; - label?: string; - dir?: - | typeof LiteGraph.UP - | typeof LiteGraph.RIGHT - | typeof LiteGraph.DOWN - | typeof LiteGraph.LEFT; - color_on?: string; - color_off?: string; - shape?: SlotShape; - locked?: boolean; - nameLocked?: boolean; -} - -export interface INodeInputSlot extends INodeSlot { - link: LLink["id"] | null; -} -export interface INodeOutputSlot extends INodeSlot { - links: LLink["id"][] | null; -} - -export type WidgetCallback = ( - this: T, - value: T["value"], - graphCanvas: LGraphCanvas, - node: LGraphNode, - pos: Vector2, - event?: MouseEvent -) => void; - -export interface IWidget { - name: string | null; - value: TValue; - options?: TOptions; - type?: widgetTypes; - y?: number; - property?: string; - last_y?: number; - clicked?: boolean; - marker?: boolean; - callback?: WidgetCallback; - /** Called by `LGraphCanvas.drawNodeWidgets` */ - draw?( - ctx: CanvasRenderingContext2D, - node: LGraphNode, - width: number, - posY: number, - height: number - ): void; - /** - * Called by `LGraphCanvas.processNodeWidgets` - * https://github.com/jagenjo/litegraph.js/issues/76 - */ - mouse?( - event: MouseEvent, - pos: Vector2, - node: LGraphNode - ): boolean; - /** Called by `LGraphNode.computeSize` */ - computeSize?(width: number): [number, number]; -} -export interface IButtonWidget extends IWidget { - type: "button"; -} -export interface IToggleWidget - extends IWidget { - type: "toggle"; -} -export interface ISliderWidget - extends IWidget { - type: "slider"; -} -export interface INumberWidget extends IWidget { - type: "number"; -} -export interface IComboWidget - extends IWidget< - string[], - { - values: - | string[] - | ((widget: IComboWidget, node: LGraphNode) => string[]); - } - > { - type: "combo"; -} - -export interface ITextWidget extends IWidget { - type: "text"; -} - -export interface IContextMenuItem { - content: string; - callback?: ContextMenuEventListener; - /** Used as innerHTML for extra child element */ - title?: string; - disabled?: boolean; - has_submenu?: boolean; - submenu?: { - options: ContextMenuItem[]; - } & IContextMenuOptions; - className?: string; -} -export interface IContextMenuOptions { - callback?: ContextMenuEventListener; - ignore_item_callbacks?: Boolean; - event?: MouseEvent | CustomEvent; - parentMenu?: ContextMenu; - autoopen?: boolean; - title?: string; - extra?: any; -} - -export type ContextMenuItem = IContextMenuItem | null; -export type ContextMenuEventListener = ( - value: ContextMenuItem, - options: IContextMenuOptions, - event: MouseEvent, - parentMenu: ContextMenu | undefined, - node: LGraphNode -) => boolean | void; - -export const LiteGraph: { - VERSION: number; - - CANVAS_GRID_SIZE: number; - - NODE_TITLE_HEIGHT: number; - NODE_TITLE_TEXT_Y: number; - NODE_SLOT_HEIGHT: number; - NODE_WIDGET_HEIGHT: number; - NODE_WIDTH: number; - NODE_MIN_WIDTH: number; - NODE_COLLAPSED_RADIUS: number; - NODE_COLLAPSED_WIDTH: number; - NODE_TITLE_COLOR: string; - NODE_TEXT_SIZE: number; - NODE_TEXT_COLOR: string; - NODE_SUBTEXT_SIZE: number; - NODE_DEFAULT_COLOR: string; - NODE_DEFAULT_BGCOLOR: string; - NODE_DEFAULT_BOXCOLOR: string; - NODE_DEFAULT_SHAPE: string; - DEFAULT_SHADOW_COLOR: string; - DEFAULT_GROUP_FONT: number; - - LINK_COLOR: string; - EVENT_LINK_COLOR: string; - CONNECTING_LINK_COLOR: string; - - MAX_NUMBER_OF_NODES: number; //avoid infinite loops - DEFAULT_POSITION: Vector2; //default node position - VALID_SHAPES: ["default", "box", "round", "card"]; //,"circle" - - //shapes are used for nodes but also for slots - BOX_SHAPE: 1; - ROUND_SHAPE: 2; - CIRCLE_SHAPE: 3; - CARD_SHAPE: 4; - ARROW_SHAPE: 5; - SQUARE_SHAPE: 6; - - //enums - INPUT: 1; - OUTPUT: 2; - - EVENT: -1; //for outputs - ACTION: -1; //for inputs - - ALWAYS: 0; - ON_EVENT: 1; - NEVER: 2; - ON_TRIGGER: 3; - - UP: 1; - DOWN: 2; - LEFT: 3; - RIGHT: 4; - CENTER: 5; - - STRAIGHT_LINK: 0; - LINEAR_LINK: 1; - SPLINE_LINK: 2; - - NORMAL_TITLE: 0; - NO_TITLE: 1; - TRANSPARENT_TITLE: 2; - AUTOHIDE_TITLE: 3; - - node_images_path: string; - - debug: boolean; - catch_exceptions: boolean; - throw_errors: boolean; - /** if set to true some nodes like Formula would be allowed to evaluate code that comes from unsafe sources (like node configuration), which could lead to exploits */ - allow_scripts: boolean; - /** node types by string */ - registered_node_types: Record; - /** used for dropping files in the canvas */ - node_types_by_file_extension: Record; - /** node types by class name */ - Nodes: Record; - - /** used to add extra features to the search box */ - searchbox_extras: Record< - string, - { - data: { outputs: string[][]; title: string }; - desc: string; - type: string; - } - >; - - createNode(type: string): T; - /** Register a node class so it can be listed when the user wants to create a new one */ - registerNodeType(type: string, base: { new (): LGraphNode }): void; - /** removes a node type from the system */ - unregisterNodeType(type: string): void; - /** Removes all previously registered node's types. */ - clearRegisteredTypes(): void; - /** - * Create a new node type by passing a function, it wraps it with a proper class and generates inputs according to the parameters of the function. - * Useful to wrap simple methods that do not require properties, and that only process some input to generate an output. - * @param name node name with namespace (p.e.: 'math/sum') - * @param func - * @param param_types an array containing the type of every parameter, otherwise parameters will accept any type - * @param return_type string with the return type, otherwise it will be generic - * @param properties properties to be configurable - */ - wrapFunctionAsNode( - name: string, - func: (...args: any[]) => any, - param_types?: string[], - return_type?: string, - properties?: object - ): void; - - /** - * Adds this method to all node types, existing and to be created - * (You can add it to LGraphNode.prototype but then existing node types wont have it) - */ - addNodeMethod(name: string, func: (...args: any[]) => any): void; - - /** - * Create a node of a given type with a name. The node is not attached to any graph yet. - * @param type full name of the node class. p.e. "math/sin" - * @param name a name to distinguish from other nodes - * @param options to set options - */ - createNode( - type: string, - title: string, - options: object - ): T; - - /** - * Returns a registered node type with a given name - * @param type full name of the node class. p.e. "math/sin" - */ - getNodeType(type: string): LGraphNodeConstructor; - - /** - * Returns a list of node types matching one category - * @method getNodeTypesInCategory - * @param {String} category category name - * @param {String} filter only nodes with ctor.filter equal can be shown - * @return {Array} array with all the node classes - */ - getNodeTypesInCategory( - category: string, - filter: string - ): LGraphNodeConstructor[]; - - /** - * Returns a list with all the node type categories - * @method getNodeTypesCategories - * @param {String} filter only nodes with ctor.filter equal can be shown - * @return {Array} array with all the names of the categories - */ - getNodeTypesCategories(filter: string): string[]; - - /** debug purposes: reloads all the js scripts that matches a wildcard */ - reloadNodes(folder_wildcard: string): void; - - getTime(): number; - LLink: typeof LLink; - LGraph: typeof LGraph; - DragAndScale: typeof DragAndScale; - compareObjects(a: object, b: object): boolean; - distance(a: Vector2, b: Vector2): number; - colorToString(c: string): string; - isInsideRectangle( - x: number, - y: number, - left: number, - top: number, - width: number, - height: number - ): boolean; - growBounding(bounding: Vector4, x: number, y: number): Vector4; - isInsideBounding(p: Vector2, bb: Vector4): boolean; - hex2num(hex: string): [number, number, number]; - num2hex(triplet: [number, number, number]): string; - ContextMenu: typeof ContextMenu; - extendClass(target: A, origin: B): A & B; - getParameterNames(func: string): string[]; -}; - -export type serializedLGraph< - TNode = ReturnType, - // https://github.com/jagenjo/litegraph.js/issues/74 - TLink = [number, number, number, number, number, string], - TGroup = ReturnType -> = { - last_node_id: LGraph["last_node_id"]; - last_link_id: LGraph["last_link_id"]; - nodes: TNode[]; - links: TLink[]; - groups: TGroup[]; - config: LGraph["config"]; - version: typeof LiteGraph.VERSION; -}; - -export declare class LGraph { - static supported_types: string[]; - static STATUS_STOPPED: 1; - static STATUS_RUNNING: 2; - - constructor(o?: object); - - filter: string; - catch_errors: boolean; - /** custom data */ - config: object; - elapsed_time: number; - fixedtime: number; - fixedtime_lapse: number; - globaltime: number; - inputs: any; - iteration: number; - last_link_id: number; - last_node_id: number; - last_update_time: number; - links: Record; - list_of_graphcanvas: LGraphCanvas[]; - outputs: any; - runningtime: number; - starttime: number; - status: typeof LGraph.STATUS_RUNNING | typeof LGraph.STATUS_STOPPED; - - private _nodes: LGraphNode[]; - private _groups: LGraphGroup[]; - private _nodes_by_id: Record; - /** nodes that are executable sorted in execution order */ - private _nodes_executable: - | (LGraphNode & { onExecute: NonNullable }[]) - | null; - /** nodes that contain onExecute */ - private _nodes_in_order: LGraphNode[]; - private _version: number; - - getSupportedTypes(): string[]; - /** Removes all nodes from this graph */ - clear(): void; - /** Attach Canvas to this graph */ - attachCanvas(graphCanvas: LGraphCanvas): void; - /** Detach Canvas to this graph */ - detachCanvas(graphCanvas: LGraphCanvas): void; - /** - * Starts running this graph every interval milliseconds. - * @param interval amount of milliseconds between executions, if 0 then it renders to the monitor refresh rate - */ - start(interval?: number): void; - /** Stops the execution loop of the graph */ - stop(): void; - /** - * Run N steps (cycles) of the graph - * @param num number of steps to run, default is 1 - */ - runStep(num?: number, do_not_catch_errors?: boolean): void; - /** - * Updates the graph execution order according to relevance of the nodes (nodes with only outputs have more relevance than - * nodes with only inputs. - */ - updateExecutionOrder(): void; - /** This is more internal, it computes the executable nodes in order and returns it */ - computeExecutionOrder(only_onExecute: boolean, set_level: any): T; - /** - * Returns all the nodes that could affect this one (ancestors) by crawling all the inputs recursively. - * It doesn't include the node itself - * @return an array with all the LGraphNodes that affect this node, in order of execution - */ - getAncestors(node: LGraphNode): LGraphNode[]; - /** - * Positions every node in a more readable manner - */ - arrange(margin?: number,layout?: string): void; - /** - * Returns the amount of time the graph has been running in milliseconds - * @return number of milliseconds the graph has been running - */ - getTime(): number; - - /** - * Returns the amount of time accumulated using the fixedtime_lapse var. This is used in context where the time increments should be constant - * @return number of milliseconds the graph has been running - */ - getFixedTime(): number; - - /** - * Returns the amount of time it took to compute the latest iteration. Take into account that this number could be not correct - * if the nodes are using graphical actions - * @return number of milliseconds it took the last cycle - */ - getElapsedTime(): number; - /** - * Sends an event to all the nodes, useful to trigger stuff - * @param eventName the name of the event (function to be called) - * @param params parameters in array format - */ - sendEventToAllNodes(eventName: string, params: any[], mode?: any): void; - - sendActionToCanvas(action: any, params: any[]): void; - /** - * Adds a new node instance to this graph - * @param node the instance of the node - */ - add(node: LGraphNode, skip_compute_order?: boolean): void; - /** - * Called when a new node is added - * @param node the instance of the node - */ - onNodeAdded(node: LGraphNode): void; - /** Removes a node from the graph */ - remove(node: LGraphNode): void; - /** Returns a node by its id. */ - getNodeById(id: number): LGraphNode | undefined; - /** - * Returns a list of nodes that matches a class - * @param classObject the class itself (not an string) - * @return a list with all the nodes of this type - */ - findNodesByClass( - classObject: LGraphNodeConstructor - ): T[]; - /** - * Returns a list of nodes that matches a type - * @param type the name of the node type - * @return a list with all the nodes of this type - */ - findNodesByType(type: string): T[]; - /** - * Returns the first node that matches a name in its title - * @param title the name of the node to search - * @return the node or null - */ - findNodeByTitle(title: string): T | null; - /** - * Returns a list of nodes that matches a name - * @param title the name of the node to search - * @return a list with all the nodes with this name - */ - findNodesByTitle(title: string): T[]; - /** - * Returns the top-most node in this position of the canvas - * @param x the x coordinate in canvas space - * @param y the y coordinate in canvas space - * @param nodes_list a list with all the nodes to search from, by default is all the nodes in the graph - * @return the node at this position or null - */ - getNodeOnPos( - x: number, - y: number, - node_list?: LGraphNode[], - margin?: number - ): T | null; - /** - * Returns the top-most group in that position - * @param x the x coordinate in canvas space - * @param y the y coordinate in canvas space - * @return the group or null - */ - getGroupOnPos(x: number, y: number): LGraphGroup | null; - - onAction(action: any, param: any): void; - trigger(action: any, param: any): void; - /** Tell this graph it has a global graph input of this type */ - addInput(name: string, type: string, value?: any): void; - /** Assign a data to the global graph input */ - setInputData(name: string, data: any): void; - /** Returns the current value of a global graph input */ - getInputData(name: string): T; - /** Changes the name of a global graph input */ - renameInput(old_name: string, name: string): false | undefined; - /** Changes the type of a global graph input */ - changeInputType(name: string, type: string): false | undefined; - /** Removes a global graph input */ - removeInput(name: string): boolean; - /** Creates a global graph output */ - addOutput(name: string, type: string, value: any): void; - /** Assign a data to the global output */ - setOutputData(name: string, value: string): void; - /** Returns the current value of a global graph output */ - getOutputData(name: string): T; - - /** Renames a global graph output */ - renameOutput(old_name: string, name: string): false | undefined; - /** Changes the type of a global graph output */ - changeOutputType(name: string, type: string): false | undefined; - /** Removes a global graph output */ - removeOutput(name: string): boolean; - triggerInput(name: string, value: any): void; - setCallback(name: string, func: (...args: any[]) => any): void; - beforeChange(info?: LGraphNode): void; - afterChange(info?: LGraphNode): void; - connectionChange(node: LGraphNode): void; - /** returns if the graph is in live mode */ - isLive(): boolean; - /** clears the triggered slot animation in all links (stop visual animation) */ - clearTriggeredSlots(): void; - /* Called when something visually changed (not the graph!) */ - change(): void; - setDirtyCanvas(fg: boolean, bg: boolean): void; - /** Destroys a link */ - removeLink(link_id: number): void; - /** Creates a Object containing all the info about this graph, it can be serialized */ - serialize(): T; - /** - * Configure a graph from a JSON string - * @param data configure a graph from a JSON string - * @returns if there was any error parsing - */ - configure(data: object, keep_old?: boolean): boolean | undefined; - load(url: string): void; -} - -export type SerializedLLink = [number, string, number, number, number, number]; -export declare class LLink { - id: number; - type: string; - origin_id: number; - origin_slot: number; - target_id: number; - target_slot: number; - constructor( - id: number, - type: string, - origin_id: number, - origin_slot: number, - target_id: number, - target_slot: number - ); - configure(o: LLink | SerializedLLink): void; - serialize(): SerializedLLink; -} - -export type SerializedLGraphNode = { - id: T["id"]; - type: T["type"]; - pos: T["pos"]; - size: T["size"]; - flags: T["flags"]; - mode: T["mode"]; - inputs: T["inputs"]; - outputs: T["outputs"]; - title: T["title"]; - properties: T["properties"]; - widgets_values?: IWidget["value"][]; -}; - -/** https://github.com/jagenjo/litegraph.js/blob/master/guides/README.md#lgraphnode */ -export declare class LGraphNode { - static title_color: string; - static title: string; - static type: null | string; - static widgets_up: boolean; - constructor(title?: string); - - title: string; - type: null | string; - size: Vector2; - graph: null | LGraph; - graph_version: number; - pos: Vector2; - is_selected: boolean; - mouseOver: boolean; - - id: number; - - //inputs available: array of inputs - inputs: INodeInputSlot[]; - outputs: INodeOutputSlot[]; - connections: any[]; - - //local data - properties: Record; - properties_info: any[]; - - flags: Partial<{ - collapsed: boolean - }>; - - color: string; - bgcolor: string; - boxcolor: string; - shape: - | typeof LiteGraph.BOX_SHAPE - | typeof LiteGraph.ROUND_SHAPE - | typeof LiteGraph.CIRCLE_SHAPE - | typeof LiteGraph.CARD_SHAPE - | typeof LiteGraph.ARROW_SHAPE; - - serialize_widgets: boolean; - skip_list: boolean; - - /** Used in `LGraphCanvas.onMenuNodeMode` */ - mode?: - | typeof LiteGraph.ON_EVENT - | typeof LiteGraph.ON_TRIGGER - | typeof LiteGraph.NEVER - | typeof LiteGraph.ALWAYS; - - /** If set to true widgets do not start after the slots */ - widgets_up: boolean; - /** widgets start at y distance from the top of the node */ - widgets_start_y: number; - /** if you render outside the node, it will be clipped */ - clip_area: boolean; - /** if set to false it wont be resizable with the mouse */ - resizable: boolean; - /** slots are distributed horizontally */ - horizontal: boolean; - /** if true, the node will show the bgcolor as 'red' */ - has_errors?: boolean; - - /** configure a node from an object containing the serialized info */ - configure(info: SerializedLGraphNode): void; - /** serialize the content */ - serialize(): SerializedLGraphNode; - /** Creates a clone of this node */ - clone(): this; - /** serialize and stringify */ - toString(): string; - /** get the title string */ - getTitle(): string; - /** sets the value of a property */ - setProperty(name: string, value: any): void; - /** sets the output data */ - setOutputData(slot: number, data: any): void; - /** sets the output data */ - setOutputDataType(slot: number, type: string): void; - /** - * Retrieves the input data (data traveling through the connection) from one slot - * @param slot - * @param force_update if set to true it will force the connected node of this slot to output data into this link - * @return data or if it is not connected returns undefined - */ - getInputData(slot: number, force_update?: boolean): T; - /** - * Retrieves the input data type (in case this supports multiple input types) - * @param slot - * @return datatype in string format - */ - getInputDataType(slot: number): string; - /** - * Retrieves the input data from one slot using its name instead of slot number - * @param slot_name - * @param force_update if set to true it will force the connected node of this slot to output data into this link - * @return data or if it is not connected returns null - */ - getInputDataByName(slot_name: string, force_update?: boolean): T; - /** tells you if there is a connection in one input slot */ - isInputConnected(slot: number): boolean; - /** tells you info about an input connection (which node, type, etc) */ - getInputInfo( - slot: number - ): { link: number; name: string; type: string | 0 } | null; - /** returns the node connected in the input slot */ - getInputNode(slot: number): LGraphNode | null; - /** returns the value of an input with this name, otherwise checks if there is a property with that name */ - getInputOrProperty(name: string): T; - /** tells you the last output data that went in that slot */ - getOutputData(slot: number): T | null; - /** tells you info about an output connection (which node, type, etc) */ - getOutputInfo( - slot: number - ): { name: string; type: string; links: number[] } | null; - /** tells you if there is a connection in one output slot */ - isOutputConnected(slot: number): boolean; - /** tells you if there is any connection in the output slots */ - isAnyOutputConnected(): boolean; - /** retrieves all the nodes connected to this output slot */ - getOutputNodes(slot: number): LGraphNode[]; - /** Triggers an event in this node, this will trigger any output with the same name */ - trigger(action: string, param: any): void; - /** - * Triggers an slot event in this node - * @param slot the index of the output slot - * @param param - * @param link_id in case you want to trigger and specific output link in a slot - */ - triggerSlot(slot: number, param: any, link_id?: number): void; - /** - * clears the trigger slot animation - * @param slot the index of the output slot - * @param link_id in case you want to trigger and specific output link in a slot - */ - clearTriggeredSlot(slot: number, link_id?: number): void; - /** - * add a new property to this node - * @param name - * @param default_value - * @param type string defining the output type ("vec3","number",...) - * @param extra_info this can be used to have special properties of the property (like values, etc) - */ - addProperty( - name: string, - default_value: any, - type: string, - extra_info?: object - ): T; - /** - * add a new output slot to use in this node - * @param name - * @param type string defining the output type ("vec3","number",...) - * @param extra_info this can be used to have special properties of an output (label, special color, position, etc) - */ - addOutput( - name: string, - type: string | -1, - extra_info?: Partial - ): INodeOutputSlot; - /** - * add a new output slot to use in this node - * @param array of triplets like [[name,type,extra_info],[...]] - */ - addOutputs( - array: [string, string | -1, Partial | undefined][] - ): void; - /** remove an existing output slot */ - removeOutput(slot: number): void; - /** - * add a new input slot to use in this node - * @param name - * @param type string defining the input type ("vec3","number",...), it its a generic one use 0 - * @param extra_info this can be used to have special properties of an input (label, color, position, etc) - */ - addInput( - name: string, - type: string | -1, - extra_info?: Partial - ): INodeInputSlot; - /** - * add several new input slots in this node - * @param array of triplets like [[name,type,extra_info],[...]] - */ - addInputs( - array: [string, string | -1, Partial | undefined][] - ): void; - /** remove an existing input slot */ - removeInput(slot: number): void; - /** - * add an special connection to this node (used for special kinds of graphs) - * @param name - * @param type string defining the input type ("vec3","number",...) - * @param pos position of the connection inside the node - * @param direction if is input or output - */ - addConnection( - name: string, - type: string, - pos: Vector2, - direction: string - ): { - name: string; - type: string; - pos: Vector2; - direction: string; - links: null; - }; - setValue(v: any): void; - /** computes the size of a node according to its inputs and output slots */ - computeSize(): [number, number]; - /** - * https://github.com/jagenjo/litegraph.js/blob/master/guides/README.md#node-widgets - * @return created widget - */ - addWidget( - type: T["type"], - name: string, - value: T["value"], - callback?: WidgetCallback | string, - options?: T["options"] - ): T; - - addCustomWidget(customWidget: T): T; - - /** - * returns the bounding of the object, used for rendering purposes - * @return [x, y, width, height] - */ - getBounding(): Vector4; - /** checks if a point is inside the shape of a node */ - isPointInside( - x: number, - y: number, - margin?: number, - skipTitle?: boolean - ): boolean; - /** checks if a point is inside a node slot, and returns info about which slot */ - getSlotInPosition( - x: number, - y: number - ): { - input?: INodeInputSlot; - output?: INodeOutputSlot; - slot: number; - link_pos: Vector2; - }; - /** - * returns the input slot with a given name (used for dynamic slots), -1 if not found - * @param name the name of the slot - * @return the slot (-1 if not found) - */ - findInputSlot(name: string): number; - /** - * returns the output slot with a given name (used for dynamic slots), -1 if not found - * @param name the name of the slot - * @return the slot (-1 if not found) - */ - findOutputSlot(name: string): number; - /** - * connect this node output to the input of another node - * @param slot (could be the number of the slot or the string with the name of the slot) - * @param targetNode the target node - * @param targetSlot the input slot of the target node (could be the number of the slot or the string with the name of the slot, or -1 to connect a trigger) - * @return {Object} the link_info is created, otherwise null - */ - connect( - slot: number | string, - targetNode: LGraphNode, - targetSlot: number | string - ): T | null; - /** - * disconnect one output to an specific node - * @param slot (could be the number of the slot or the string with the name of the slot) - * @param target_node the target node to which this slot is connected [Optional, if not target_node is specified all nodes will be disconnected] - * @return if it was disconnected successfully - */ - disconnectOutput(slot: number | string, targetNode?: LGraphNode): boolean; - /** - * disconnect one input - * @param slot (could be the number of the slot or the string with the name of the slot) - * @return if it was disconnected successfully - */ - disconnectInput(slot: number | string): boolean; - /** - * returns the center of a connection point in canvas coords - * @param is_input true if if a input slot, false if it is an output - * @param slot (could be the number of the slot or the string with the name of the slot) - * @param out a place to store the output, to free garbage - * @return the position - **/ - getConnectionPos( - is_input: boolean, - slot: number | string, - out?: Vector2 - ): Vector2; - /** Force align to grid */ - alignToGrid(): void; - /** Console output */ - trace(msg: string): void; - /** Forces to redraw or the main canvas (LGraphNode) or the bg canvas (links) */ - setDirtyCanvas(fg: boolean, bg: boolean): void; - loadImage(url: string): void; - /** Allows to get onMouseMove and onMouseUp events even if the mouse is out of focus */ - captureInput(v: any): void; - /** Collapse the node to make it smaller on the canvas */ - collapse(force: boolean): void; - /** Forces the node to do not move or realign on Z */ - pin(v?: boolean): void; - localToScreen(x: number, y: number, graphCanvas: LGraphCanvas): Vector2; - - // https://github.com/jagenjo/litegraph.js/blob/master/guides/README.md#custom-node-appearance - onDrawBackground?( - ctx: CanvasRenderingContext2D, - canvas: HTMLCanvasElement - ): void; - onDrawForeground?( - ctx: CanvasRenderingContext2D, - canvas: HTMLCanvasElement - ): void; - - // https://github.com/jagenjo/litegraph.js/blob/master/guides/README.md#custom-node-behaviour - onMouseDown?( - event: MouseEvent, - pos: Vector2, - graphCanvas: LGraphCanvas - ): void; - onMouseMove?( - event: MouseEvent, - pos: Vector2, - graphCanvas: LGraphCanvas - ): void; - onMouseUp?( - event: MouseEvent, - pos: Vector2, - graphCanvas: LGraphCanvas - ): void; - onMouseEnter?( - event: MouseEvent, - pos: Vector2, - graphCanvas: LGraphCanvas - ): void; - onMouseLeave?( - event: MouseEvent, - pos: Vector2, - graphCanvas: LGraphCanvas - ): void; - onKey?(event: KeyboardEvent, pos: Vector2, graphCanvas: LGraphCanvas): void; - - /** Called by `LGraphCanvas.selectNodes` */ - onSelected?(): void; - /** Called by `LGraphCanvas.deselectNode` */ - onDeselected?(): void; - /** Called by `LGraph.runStep` `LGraphNode.getInputData` */ - onExecute?(): void; - /** Called by `LGraph.serialize` */ - onSerialize?(o: SerializedLGraphNode): void; - /** Called by `LGraph.configure` */ - onConfigure?(o: SerializedLGraphNode): void; - /** - * when added to graph (warning: this is called BEFORE the node is configured when loading) - * Called by `LGraph.add` - */ - onAdded?(graph: LGraph): void; - /** - * when removed from graph - * Called by `LGraph.remove` `LGraph.clear` - */ - onRemoved?(): void; - /** - * if returns false the incoming connection will be canceled - * Called by `LGraph.connect` - * @param inputIndex target input slot number - * @param outputType type of output slot - * @param outputSlot output slot object - * @param outputNode node containing the output - * @param outputIndex index of output slot - */ - onConnectInput?( - inputIndex: number, - outputType: INodeOutputSlot["type"], - outputSlot: INodeOutputSlot, - outputNode: LGraphNode, - outputIndex: number - ): boolean; - /** - * if returns false the incoming connection will be canceled - * Called by `LGraph.connect` - * @param outputIndex target output slot number - * @param inputType type of input slot - * @param inputSlot input slot object - * @param inputNode node containing the input - * @param inputIndex index of input slot - */ - onConnectOutput?( - outputIndex: number, - inputType: INodeInputSlot["type"], - inputSlot: INodeInputSlot, - inputNode: LGraphNode, - inputIndex: number - ): boolean; - - /** - * Called just before connection (or disconnect - if input is linked). - * A convenient place to switch to another input, or create new one. - * This allow for ability to automatically add slots if needed - * @param inputIndex - * @return selected input slot index, can differ from parameter value - */ - onBeforeConnectInput?( - inputIndex: number - ): number; - - /** a connection changed (new one or removed) (LiteGraph.INPUT or LiteGraph.OUTPUT, slot, true if connected, link_info, input_info or output_info ) */ - onConnectionsChange( - type: number, - slotIndex: number, - isConnected: boolean, - link: LLink, - ioSlot: (INodeOutputSlot | INodeInputSlot) - ): void; - - /** - * if returns false, will abort the `LGraphNode.setProperty` - * Called when a property is changed - * @param property - * @param value - * @param prevValue - */ - onPropertyChanged?(property: string, value: any, prevValue: any): void | boolean; - - /** Called by `LGraphCanvas.processContextMenu` */ - getMenuOptions?(graphCanvas: LGraphCanvas): ContextMenuItem[]; - getSlotMenuOptions?(slot: INodeSlot): ContextMenuItem[]; -} - -export type LGraphNodeConstructor = { - new (): T; -}; - -export type SerializedLGraphGroup = { - title: LGraphGroup["title"]; - bounding: LGraphGroup["_bounding"]; - color: LGraphGroup["color"]; - font: LGraphGroup["font"]; -}; -export declare class LGraphGroup { - title: string; - private _bounding: Vector4; - color: string; - font: string; - - configure(o: SerializedLGraphGroup): void; - serialize(): SerializedLGraphGroup; - move(deltaX: number, deltaY: number, ignoreNodes?: boolean): void; - recomputeInsideNodes(): void; - isPointInside: LGraphNode["isPointInside"]; - setDirtyCanvas: LGraphNode["setDirtyCanvas"]; -} - -export declare class DragAndScale { - constructor(element?: HTMLElement, skipEvents?: boolean); - offset: [number, number]; - scale: number; - max_scale: number; - min_scale: number; - onredraw: Function | null; - enabled: boolean; - last_mouse: Vector2; - element: HTMLElement | null; - visible_area: Vector4; - bindEvents(element: HTMLElement): void; - computeVisibleArea(): void; - onMouse(e: MouseEvent): void; - toCanvasContext(ctx: CanvasRenderingContext2D): void; - convertOffsetToCanvas(pos: Vector2): Vector2; - convertCanvasToOffset(pos: Vector2): Vector2; - mouseDrag(x: number, y: number): void; - changeScale(value: number, zooming_center?: Vector2): void; - changeDeltaScale(value: number, zooming_center?: Vector2): void; - reset(): void; -} - -/** - * This class is in charge of rendering one graph inside a canvas. And provides all the interaction required. - * Valid callbacks are: onNodeSelected, onNodeDeselected, onShowNodePanel, onNodeDblClicked - * - * @param canvas the canvas where you want to render (it accepts a selector in string format or the canvas element itself) - * @param graph - * @param options { skip_rendering, autoresize } - */ -export declare class LGraphCanvas { - static node_colors: Record< - string, - { - color: string; - bgcolor: string; - groupcolor: string; - } - >; - static link_type_colors: Record; - static gradients: object; - static search_limit: number; - - static getFileExtension(url: string): string; - static decodeHTML(str: string): string; - - static onMenuCollapseAll(): void; - static onMenuNodeEdit(): void; - static onShowPropertyEditor( - item: any, - options: any, - e: any, - menu: any, - node: any - ): void; - /** Create menu for `Add Group` */ - static onGroupAdd: ContextMenuEventListener; - /** Create menu for `Add Node` */ - static onMenuAdd: ContextMenuEventListener; - static showMenuNodeOptionalInputs: ContextMenuEventListener; - static showMenuNodeOptionalOutputs: ContextMenuEventListener; - static onShowMenuNodeProperties: ContextMenuEventListener; - static onResizeNode: ContextMenuEventListener; - static onMenuNodeCollapse: ContextMenuEventListener; - static onMenuNodePin: ContextMenuEventListener; - static onMenuNodeMode: ContextMenuEventListener; - static onMenuNodeColors: ContextMenuEventListener; - static onMenuNodeShapes: ContextMenuEventListener; - static onMenuNodeRemove: ContextMenuEventListener; - static onMenuNodeClone: ContextMenuEventListener; - - constructor( - canvas: HTMLCanvasElement | string, - graph?: LGraph, - options?: { - skip_render?: boolean; - autoresize?: boolean; - } - ); - - static active_canvas: HTMLCanvasElement; - - allow_dragcanvas: boolean; - allow_dragnodes: boolean; - /** allow to control widgets, buttons, collapse, etc */ - allow_interaction: boolean; - /** allows to change a connection with having to redo it again */ - allow_reconnect_links: boolean; - /** allow selecting multi nodes without pressing extra keys */ - multi_select: boolean; - /** No effect */ - allow_searchbox: boolean; - always_render_background: boolean; - autoresize?: boolean; - background_image: string; - bgcanvas: HTMLCanvasElement; - bgctx: CanvasRenderingContext2D; - canvas: HTMLCanvasElement; - canvas_mouse: Vector2; - clear_background: boolean; - connecting_node: LGraphNode | null; - connections_width: number; - ctx: CanvasRenderingContext2D; - current_node: LGraphNode | null; - default_connection_color: { - input_off: string; - input_on: string; - output_off: string; - output_on: string; - }; - default_link_color: string; - dirty_area: Vector4 | null; - dirty_bgcanvas?: boolean; - dirty_canvas?: boolean; - drag_mode: boolean; - dragging_canvas: boolean; - dragging_rectangle: Vector4 | null; - ds: DragAndScale; - /** used for transition */ - editor_alpha: number; - filter: any; - fps: number; - frame: number; - graph: LGraph; - highlighted_links: Record; - highquality_render: boolean; - inner_text_font: string; - is_rendering: boolean; - last_draw_time: number; - last_mouse: Vector2; - /** - * Possible duplicated with `last_mouse` - * https://github.com/jagenjo/litegraph.js/issues/70 - */ - last_mouse_position: Vector2; - /** Timestamp of last mouse click, defaults to 0 */ - last_mouseclick: number; - links_render_mode: - | typeof LiteGraph.STRAIGHT_LINK - | typeof LiteGraph.LINEAR_LINK - | typeof LiteGraph.SPLINE_LINK; - live_mode: boolean; - node_capturing_input: LGraphNode | null; - node_dragged: LGraphNode | null; - node_in_panel: LGraphNode | null; - node_over: LGraphNode | null; - node_title_color: string; - node_widget: [LGraphNode, IWidget] | null; - /** Called by `LGraphCanvas.drawBackCanvas` */ - onDrawBackground: - | ((ctx: CanvasRenderingContext2D, visibleArea: Vector4) => void) - | null; - /** Called by `LGraphCanvas.drawFrontCanvas` */ - onDrawForeground: - | ((ctx: CanvasRenderingContext2D, visibleArea: Vector4) => void) - | null; - onDrawOverlay: ((ctx: CanvasRenderingContext2D) => void) | null; - /** Called by `LGraphCanvas.processMouseDown` */ - onMouse: ((event: MouseEvent) => boolean) | null; - /** Called by `LGraphCanvas.drawFrontCanvas` and `LGraphCanvas.drawLinkTooltip` */ - onDrawLinkTooltip: ((ctx: CanvasRenderingContext2D, link: LLink, _this: this) => void) | null; - /** Called by `LGraphCanvas.selectNodes` */ - onNodeMoved: ((node: LGraphNode) => void) | null; - /** Called by `LGraphCanvas.processNodeSelected` */ - onNodeSelected: ((node: LGraphNode) => void) | null; - /** Called by `LGraphCanvas.deselectNode` */ - onNodeDeselected: ((node: LGraphNode) => void) | null; - /** Called by `LGraphCanvas.processNodeDblClicked` */ - onShowNodePanel: ((node: LGraphNode) => void) | null; - /** Called by `LGraphCanvas.processNodeDblClicked` */ - onNodeDblClicked: ((node: LGraphNode) => void) | null; - /** Called by `LGraphCanvas.selectNodes` */ - onSelectionChange: ((nodes: Record) => void) | null; - /** Called by `LGraphCanvas.showSearchBox` */ - onSearchBox: - | (( - helper: Element, - value: string, - graphCanvas: LGraphCanvas - ) => string[]) - | null; - onSearchBoxSelection: - | ((name: string, event: MouseEvent, graphCanvas: LGraphCanvas) => void) - | null; - pause_rendering: boolean; - render_canvas_border: boolean; - render_collapsed_slots: boolean; - render_connection_arrows: boolean; - render_connections_border: boolean; - render_connections_shadows: boolean; - render_curved_connections: boolean; - render_execution_order: boolean; - render_only_selected: boolean; - render_shadows: boolean; - render_title_colored: boolean; - round_radius: number; - selected_group: null | LGraphGroup; - selected_group_resizing: boolean; - selected_nodes: Record; - show_info: boolean; - title_text_font: string; - /** set to true to render title bar with gradients */ - use_gradients: boolean; - visible_area: DragAndScale["visible_area"]; - visible_links: LLink[]; - visible_nodes: LGraphNode[]; - zoom_modify_alpha: boolean; - - /** clears all the data inside */ - clear(): void; - /** assigns a graph, you can reassign graphs to the same canvas */ - setGraph(graph: LGraph, skipClear?: boolean): void; - /** opens a graph contained inside a node in the current graph */ - openSubgraph(graph: LGraph): void; - /** closes a subgraph contained inside a node */ - closeSubgraph(): void; - /** assigns a canvas */ - setCanvas(canvas: HTMLCanvasElement, skipEvents?: boolean): void; - /** binds mouse, keyboard, touch and drag events to the canvas */ - bindEvents(): void; - /** unbinds mouse events from the canvas */ - unbindEvents(): void; - - /** - * this function allows to render the canvas using WebGL instead of Canvas2D - * this is useful if you plant to render 3D objects inside your nodes, it uses litegl.js for webgl and canvas2DtoWebGL to emulate the Canvas2D calls in webGL - **/ - enableWebGL(): void; - - /** - * marks as dirty the canvas, this way it will be rendered again - * @param fg if the foreground canvas is dirty (the one containing the nodes) - * @param bg if the background canvas is dirty (the one containing the wires) - */ - setDirty(fg: boolean, bg: boolean): void; - - /** - * Used to attach the canvas in a popup - * @return the window where the canvas is attached (the DOM root node) - */ - getCanvasWindow(): Window; - /** starts rendering the content of the canvas when needed */ - startRendering(): void; - /** stops rendering the content of the canvas (to save resources) */ - stopRendering(): void; - - processMouseDown(e: MouseEvent): boolean | undefined; - processMouseMove(e: MouseEvent): boolean | undefined; - processMouseUp(e: MouseEvent): boolean | undefined; - processMouseWheel(e: MouseEvent): boolean | undefined; - - /** returns true if a position (in graph space) is on top of a node little corner box */ - isOverNodeBox(node: LGraphNode, canvasX: number, canvasY: number): boolean; - /** returns true if a position (in graph space) is on top of a node input slot */ - isOverNodeInput( - node: LGraphNode, - canvasX: number, - canvasY: number, - slotPos: Vector2 - ): boolean; - - /** process a key event */ - processKey(e: KeyboardEvent): boolean | undefined; - - copyToClipboard(): void; - pasteFromClipboard(): void; - processDrop(e: DragEvent): void; - checkDropItem(e: DragEvent): void; - processNodeDblClicked(n: LGraphNode): void; - processNodeSelected(n: LGraphNode, e: MouseEvent): void; - processNodeDeselected(node: LGraphNode): void; - - /** selects a given node (or adds it to the current selection) */ - selectNode(node: LGraphNode, add?: boolean): void; - /** selects several nodes (or adds them to the current selection) */ - selectNodes(nodes?: LGraphNode[], add?: boolean): void; - /** removes a node from the current selection */ - deselectNode(node: LGraphNode): void; - /** removes all nodes from the current selection */ - deselectAllNodes(): void; - /** deletes all nodes in the current selection from the graph */ - deleteSelectedNodes(): void; - - /** centers the camera on a given node */ - centerOnNode(node: LGraphNode): void; - /** changes the zoom level of the graph (default is 1), you can pass also a place used to pivot the zoom */ - setZoom(value: number, center: Vector2): void; - /** brings a node to front (above all other nodes) */ - bringToFront(node: LGraphNode): void; - /** sends a node to the back (below all other nodes) */ - sendToBack(node: LGraphNode): void; - /** checks which nodes are visible (inside the camera area) */ - computeVisibleNodes(nodes: LGraphNode[]): LGraphNode[]; - /** renders the whole canvas content, by rendering in two separated canvas, one containing the background grid and the connections, and one containing the nodes) */ - draw(forceFG?: boolean, forceBG?: boolean): void; - /** draws the front canvas (the one containing all the nodes) */ - drawFrontCanvas(): void; - /** draws some useful stats in the corner of the canvas */ - renderInfo(ctx: CanvasRenderingContext2D, x: number, y: number): void; - /** draws the back canvas (the one containing the background and the connections) */ - drawBackCanvas(): void; - /** draws the given node inside the canvas */ - drawNode(node: LGraphNode, ctx: CanvasRenderingContext2D): void; - /** draws graphic for node's slot */ - drawSlotGraphic(ctx: CanvasRenderingContext2D, pos: number[], shape: SlotShape, horizontal: boolean): void; - /** draws the shape of the given node in the canvas */ - drawNodeShape( - node: LGraphNode, - ctx: CanvasRenderingContext2D, - size: [number, number], - fgColor: string, - bgColor: string, - selected: boolean, - mouseOver: boolean - ): void; - /** draws every connection visible in the canvas */ - drawConnections(ctx: CanvasRenderingContext2D): void; - /** - * draws a link between two points - * @param a start pos - * @param b end pos - * @param link the link object with all the link info - * @param skipBorder ignore the shadow of the link - * @param flow show flow animation (for events) - * @param color the color for the link - * @param startDir the direction enum - * @param endDir the direction enum - * @param numSublines number of sublines (useful to represent vec3 or rgb) - **/ - renderLink( - a: Vector2, - b: Vector2, - link: object, - skipBorder: boolean, - flow: boolean, - color?: string, - startDir?: number, - endDir?: number, - numSublines?: number - ): void; - - computeConnectionPoint( - a: Vector2, - b: Vector2, - t: number, - startDir?: number, - endDir?: number - ): void; - - drawExecutionOrder(ctx: CanvasRenderingContext2D): void; - /** draws the widgets stored inside a node */ - drawNodeWidgets( - node: LGraphNode, - posY: number, - ctx: CanvasRenderingContext2D, - activeWidget: object - ): void; - /** process an event on widgets */ - processNodeWidgets( - node: LGraphNode, - pos: Vector2, - event: Event, - activeWidget: object - ): void; - /** draws every group area in the background */ - drawGroups(canvas: any, ctx: CanvasRenderingContext2D): void; - adjustNodesSize(): void; - /** resizes the canvas to a given size, if no size is passed, then it tries to fill the parentNode */ - resize(width?: number, height?: number): void; - /** - * switches to live mode (node shapes are not rendered, only the content) - * this feature was designed when graphs where meant to create user interfaces - **/ - switchLiveMode(transition?: boolean): void; - onNodeSelectionChange(): void; - touchHandler(event: TouchEvent): void; - - showLinkMenu(link: LLink, e: any): false; - prompt( - title: string, - value: any, - callback: Function, - event: any - ): HTMLDivElement; - showSearchBox(event?: MouseEvent): void; - showEditPropertyValue(node: LGraphNode, property: any, options: any): void; - createDialog( - html: string, - options?: { position?: Vector2; event?: MouseEvent } - ): void; - - convertOffsetToCanvas: DragAndScale["convertOffsetToCanvas"]; - convertCanvasToOffset: DragAndScale["convertCanvasToOffset"]; - /** converts event coordinates from canvas2D to graph coordinates */ - convertEventToCanvasOffset(e: MouseEvent): Vector2; - /** adds some useful properties to a mouse event, like the position in graph coordinates */ - adjustMouseEvent(e: MouseEvent): void; - - getCanvasMenuOptions(): ContextMenuItem[]; - getNodeMenuOptions(node: LGraphNode): ContextMenuItem[]; - getGroupMenuOptions(): ContextMenuItem[]; - /** Called by `getCanvasMenuOptions`, replace default options */ - getMenuOptions?(): ContextMenuItem[]; - /** Called by `getCanvasMenuOptions`, append to default options */ - getExtraMenuOptions?(): ContextMenuItem[]; - /** Called when mouse right click */ - processContextMenu(node: LGraphNode, event: Event): void; -} - -declare class ContextMenu { - static trigger( - element: HTMLElement, - event_name: string, - params: any, - origin: any - ): void; - static isCursorOverElement(event: MouseEvent, element: HTMLElement): void; - static closeAllContextMenus(window: Window): void; - constructor(values: ContextMenuItem[], options?: IContextMenuOptions, window?: Window); - options: IContextMenuOptions; - parentMenu?: ContextMenu; - lock: boolean; - current_submenu?: ContextMenu; - addItem( - name: string, - value: ContextMenuItem, - options?: IContextMenuOptions - ): void; - close(e?: MouseEvent, ignore_parent_menu?: boolean): void; - getTopMenu(): void; - getFirstEvent(): void; -} - -declare global { - interface CanvasRenderingContext2D { - /** like rect but rounded corners */ - roundRect( - x: number, - y: number, - width: number, - height: number, - radius: number, - radiusLow: number - ): void; - } - - interface Math { - clamp(v: number, min: number, max: number): number; - } -}
' + func(text) + '
fred, barney, & pebbles