diff --git a/docs/user-guides/getting-started.md b/docs/user-guides/getting-started.md index 4d7f42cd..adfdf961 100644 --- a/docs/user-guides/getting-started.md +++ b/docs/user-guides/getting-started.md @@ -307,7 +307,7 @@ MuJoCo does not currently ship first-party Python typing stubs. To enable proper --- !!! tip "Tip: Scaffold a New Project" - Before diving into the generate script, run `mujoco-mojo init` in a new directory to get a working project skeleton — `simulation.py`, `run.sh`, and `reloaded.sh` — pre-wired and ready to edit. + Before diving into the generate script, run `mujoco-mojo init` in a new directory to get a working project skeleton (`simulation.py`, `run.sh`, and `reloaded.sh`) pre-wired and ready to edit. ```bash linenums="0" mujoco-mojo init diff --git a/docs/user-guides/runtime-script.md b/docs/user-guides/runtime-script.md index a6aeb1ce..b9d11cb2 100644 --- a/docs/user-guides/runtime-script.md +++ b/docs/user-guides/runtime-script.md @@ -49,7 +49,7 @@ Mojo provides high-level force abstractions like `PointToPointForce`, which auto --- - **6-DOF force and torque**. The "multi-tool" of loads—defines full spatial dynamics in either a relative frame or local to a site. + **6-DOF force and torque**. Defines full spatial dynamics in either a relative frame or local to a site. > Think of it as a `VectorForce` and `VectorTorque` combined into one robust plugin. diff --git a/src/mujoco_mojo/utils/dataframe.py b/src/mujoco_mojo/utils/dataframe.py index 8c790a8a..dcc9b220 100644 --- a/src/mujoco_mojo/utils/dataframe.py +++ b/src/mujoco_mojo/utils/dataframe.py @@ -231,18 +231,22 @@ def select_flex(self, name: FlexName) -> MojoDataFrame: self._df.select(pl.col(rf"^{SignalCategory.DEFORMABLES}/{name}/.*$")) ) - def _get_base_map(self) -> dict[str, set[str]]: + def _get_base_map( + self, extra_columns: list[str] | None = None + ) -> dict[str, set[str]]: """ Internal helper to group suffixes by their common prefixes. Example: - 'Bodies/racket:xvelr:x', 'Bodies/racket:xvelr:y' -> {'Bodies/racket:xvelr': {'x', 'y'}} + 'Bodies/racket/xvelr:x', 'Bodies/racket/xvelr:y' -> {'Bodies/racket/xvelr': {'x', 'y'}} + + extra_columns are included in discovery but are not expected to exist in self._df. """ base_map: dict[str, set[str]] = {} - for c in self._df.columns: + for c in list(self._df.columns) + (extra_columns or []): if ":" in c: - prefix, suffix = c.rsplit(":") # we may have :ke_trans, or ke_rot, etc. + prefix, suffix = c.rsplit(":", 1) base_map.setdefault(prefix, set()).add(suffix) return base_map @@ -280,12 +284,17 @@ def quaternion_columns(self) -> list[str]: expanded.extend([f"{base}:w", f"{base}:x", f"{base}:y", f"{base}:z"]) return expanded - def get_manifest(self) -> ColumnManifest: - """Returns the structured manifest used by the frontend.""" + def get_manifest(self, extra_columns: list[str] | None = None) -> ColumnManifest: + """Returns the structured manifest used by the frontend. extra_columns are appended to 'all' and included in rotatable/quat discovery.""" + bm = self._get_base_map(extra_columns) return { - "all": self._df.columns, - "rotatable_vectors": sorted(list(self.rotatable_bases)), - "available_quats": sorted(list(self.quaternion_bases)), + "all": list(self._df.columns) + (extra_columns or []), + "rotatable_vectors": sorted( + b for b, s in bm.items() if {"x", "y", "z"}.issubset(s) and "w" not in s + ), + "available_quats": sorted( + b for b, s in bm.items() if {"w", "x", "y", "z"}.issubset(s) + ), } def with_rotation(self, quat_base: str, invert: bool = True) -> MojoDataFrame: diff --git a/src/mujoco_mojo/utils/filters/__init__.py b/src/mujoco_mojo/utils/filters/__init__.py index 0c517d7e..9dee1704 100644 --- a/src/mujoco_mojo/utils/filters/__init__.py +++ b/src/mujoco_mojo/utils/filters/__init__.py @@ -2,18 +2,26 @@ AbsoluteValueFilter, AnyFilter, ClipFilter, + ComparisonFilter, DeadbandFilter, DerivativeFilter, + ExpFilter, FilterType, HighPassFilter, IntegralFilter, + LogFilter, LowPassFilter, MedianFilter, NormalizeFilter, + PowerFilter, RollingMeanFilter, + RotationFilter, + RoundFilter, SavitzkyGolayFilter, ScaleFilter, + SignFilter, TaringFilter, + TrigFilter, UnitFilter, WrapFilter, filter_adapter, @@ -23,18 +31,26 @@ "AbsoluteValueFilter", "AnyFilter", "ClipFilter", + "ComparisonFilter", "DeadbandFilter", "DerivativeFilter", + "ExpFilter", "FilterType", "HighPassFilter", "IntegralFilter", + "LogFilter", "LowPassFilter", "MedianFilter", "NormalizeFilter", + "PowerFilter", "RollingMeanFilter", + "RotationFilter", + "RoundFilter", "SavitzkyGolayFilter", "ScaleFilter", + "SignFilter", "TaringFilter", + "TrigFilter", "UnitFilter", "WrapFilter", "filter_adapter", diff --git a/src/mujoco_mojo/utils/filters/filters.py b/src/mujoco_mojo/utils/filters/filters.py index 4a880bb7..82817980 100644 --- a/src/mujoco_mojo/utils/filters/filters.py +++ b/src/mujoco_mojo/utils/filters/filters.py @@ -1,32 +1,42 @@ from __future__ import annotations +import math from abc import ABC, abstractmethod from enum import StrEnum -from typing import Annotated, Literal, Self +from typing import Annotated, ClassVar, Literal, Self import numpy as np import pint import polars as pl from pydantic import BaseModel, ConfigDict, Field, TypeAdapter, model_validator from scipy.signal import savgol_filter +from scipy.spatial.transform import Rotation as R __all__ = [ "UNIT_GROUPS", "AbsoluteValueFilter", "AnyFilter", "ClipFilter", + "ComparisonFilter", "DeadbandFilter", "DerivativeFilter", + "ExpFilter", "FilterType", "HighPassFilter", "IntegralFilter", + "LogFilter", "LowPassFilter", "MedianFilter", "NormalizeFilter", + "PowerFilter", "RollingMeanFilter", + "RotationFilter", + "RoundFilter", "SavitzkyGolayFilter", "ScaleFilter", + "SignFilter", "TaringFilter", + "TrigFilter", "UnitFilter", "WrapFilter", "filter_adapter", @@ -49,12 +59,21 @@ class FilterType(StrEnum): NORMALIZE = "normalize" SAVITZKY_GOLAY = "savitzky_golay" UNIT = "unit" + ROTATION = "rotation" + LOG = "log" + EXP = "exp" + POWER = "power" + ROUND = "round" + TRIG = "trig" + SIGN = "sign" + COMPARISON = "comparison" class BaseFilter(ABC, BaseModel): """Base class for all data transformations.""" model_config = ConfigDict(extra="forbid") + category: ClassVar[str] = "Misc" @abstractmethod def apply(self, expr: pl.Expr) -> pl.Expr: @@ -74,6 +93,8 @@ def apply_with_context( class ScaleFilter(BaseFilter): """Applies a linear transformation: (value * factor) + offset.""" + category: ClassVar[str] = "Arithmetic" + type: Literal[FilterType.SCALE] = FilterType.SCALE """The discriminator type for Pydantic.""" @@ -90,6 +111,8 @@ def apply(self, expr: pl.Expr) -> pl.Expr: class AbsoluteValueFilter(BaseFilter): """Rectifies the signal by taking the magnitude of every sample.""" + category: ClassVar[str] = "Arithmetic" + type: Literal[FilterType.ABSOLUTE_VALUE] = FilterType.ABSOLUTE_VALUE """The discriminator type for Pydantic.""" @@ -103,6 +126,8 @@ class DerivativeFilter(BaseFilter): Useful for deriving velocity from position or acceleration from velocity. """ + category: ClassVar[str] = "Calculus" + type: Literal[FilterType.DERIVATIVE] = FilterType.DERIVATIVE """The discriminator type for Pydantic.""" @@ -133,6 +158,8 @@ class IntegralFilter(BaseFilter): Useful for deriving position from velocity or calculating energy. """ + category: ClassVar[str] = "Calculus" + type: Literal[FilterType.INTEGRAL] = FilterType.INTEGRAL """The discriminator type for Pydantic.""" @@ -162,6 +189,8 @@ class LowPassFilter(BaseFilter): Effective for removing high-frequency noise while introducing slight phase lag. """ + category: ClassVar[str] = "Smoothing" + type: Literal[FilterType.LOW_PASS] = FilterType.LOW_PASS """The discriminator type for Pydantic.""" @@ -178,6 +207,8 @@ class HighPassFilter(BaseFilter): Implemented as the complement of the Exponential Moving Average. """ + category: ClassVar[str] = "Smoothing" + type: Literal[FilterType.HIGH_PASS] = FilterType.HIGH_PASS """The discriminator type for Pydantic.""" @@ -192,6 +223,8 @@ def apply(self, expr: pl.Expr) -> pl.Expr: class ClipFilter(BaseFilter): """Clamps the signal values within a specified range.""" + category: ClassVar[str] = "Bounding" + type: Literal[FilterType.CLIP] = FilterType.CLIP """The discriminator type for Pydantic.""" @@ -217,6 +250,8 @@ def apply(self, expr: pl.Expr) -> pl.Expr: class RollingMeanFilter(BaseFilter): """Applies a sliding window average to the signal.""" + category: ClassVar[str] = "Smoothing" + type: Literal[FilterType.ROLLING_MEAN] = FilterType.ROLLING_MEAN """The discriminator type for Pydantic.""" @@ -233,6 +268,8 @@ def apply(self, expr: pl.Expr) -> pl.Expr: class TaringFilter(BaseFilter): """Offsets the entire signal so that the first sample is zero.""" + category: ClassVar[str] = "Bounding" + type: Literal[FilterType.TARING] = FilterType.TARING """The discriminator type for Pydantic.""" @@ -243,6 +280,8 @@ def apply(self, expr: pl.Expr) -> pl.Expr: class DeadbandFilter(BaseFilter): """Suppresses noise around zero by forcing values below a threshold to zero.""" + category: ClassVar[str] = "Bounding" + type: Literal[FilterType.DEADBAND] = FilterType.DEADBAND """The discriminator type for Pydantic.""" @@ -259,6 +298,8 @@ class WrapFilter(BaseFilter): Ensures continuity when a signal crosses the upper or lower boundary. """ + category: ClassVar[str] = "Bounding" + type: Literal[FilterType.WRAP] = FilterType.WRAP """The discriminator type for Pydantic.""" @@ -285,6 +326,8 @@ class MedianFilter(BaseFilter): Highly effective for removing impulse noise (spikes) without blurring edges. """ + category: ClassVar[str] = "Smoothing" + type: Literal[FilterType.MEDIAN] = FilterType.MEDIAN """The discriminator type for Pydantic.""" @@ -298,6 +341,8 @@ def apply(self, expr: pl.Expr) -> pl.Expr: class NormalizeFilter(BaseFilter): """Rescales the signal to the range [0, 1].""" + category: ClassVar[str] = "Bounding" + type: Literal[FilterType.NORMALIZE] = FilterType.NORMALIZE """The discriminator type for Pydantic.""" @@ -311,6 +356,8 @@ class SavitzkyGolayFilter(BaseFilter): Preserves signal features (like peaks and transients) better than a simple moving average. """ + category: ClassVar[str] = "Smoothing" + type: Literal[FilterType.SAVITZKY_GOLAY] = FilterType.SAVITZKY_GOLAY """The discriminator type for Pydantic.""" @@ -346,7 +393,7 @@ def apply(self, expr: pl.Expr) -> pl.Expr: pass # --------------------------------------------------------------------------- -# Unit groups — single source of truth for both the frontend smart dropdown +# Unit groups - single source of truth for both the frontend smart dropdown # and the SignalUnit type annotation on UnitFilter. To add a new unit, # add it here; SignalUnit is derived automatically. Verify that pint can # parse any new string via `ureg.parse_units(...)` before committing. @@ -377,7 +424,7 @@ def apply(self, expr: pl.Expr) -> pl.Expr: ("Misc.", ["dimensionless", "pct", "count", "bit"]), ] -# Derived automatically — Literal[tuple_of_strings] is equivalent to Literal["a", "b", ...] +# Derived automatically - Literal[tuple_of_strings] is equivalent to Literal["a", "b", ...] # in Python 3.9+ because x[a, b] and x[(a, b)] make the same __getitem__ call. _ALL_UNITS: tuple[str, ...] = tuple(u for _, us in UNIT_GROUPS for u in us) SignalUnit = Literal[_ALL_UNITS] | str @@ -431,6 +478,232 @@ def apply(self, expr: pl.Expr) -> pl.Expr: return (expr * m) + b +class RotationFilter(BaseFilter): + """Rotates a 3D vector component into a reference frame using a quaternion column.""" + + type: Literal[FilterType.ROTATION] = FilterType.ROTATION + """The discriminator type for Pydantic.""" + + quat_col: str = Field("", json_schema_extra={"ui_type": "col"}) + """Base name of the quaternion column group (e.g. 'Bodies/hand/xquat').""" + + invert: bool = True + """If True, transforms world-to-local (invert the quaternion rotation).""" + + def apply(self, expr: pl.Expr) -> pl.Expr: + return expr + + def apply_with_context( + self, series: pl.Series, df: pl.DataFrame + ) -> pl.Series | None: + name = series.name + suffix = name.rsplit(":", 1)[-1] if ":" in name else "" + if suffix not in ("x", "y", "z") or not self.quat_col: + return None + base = name.rsplit(":", 1)[0] + x_col, y_col, z_col = f"{base}:x", f"{base}:y", f"{base}:z" + if not all(c in df.columns for c in (x_col, y_col, z_col)): + return None + # scipy expects (x, y, z, w) column order + q_cols = [f"{self.quat_col}:{k}" for k in ("x", "y", "z", "w")] + if not all(c in df.columns for c in q_cols): + return None + transformer = R.from_quat(df.select(q_cols).to_numpy()) + if self.invert: + transformer = transformer.inv() + v_rot = transformer.apply(df.select([x_col, y_col, z_col]).to_numpy()) + return pl.Series(name=name, values=v_rot[:, {"x": 0, "y": 1, "z": 2}[suffix]]) + + +class LogFilter(BaseFilter): + """Applies a logarithm to the signal. Defaults to natural log (base e).""" + + category: ClassVar[str] = "Arithmetic" + + type: Literal[FilterType.LOG] = FilterType.LOG + """The discriminator type for Pydantic.""" + + base: float = Field(default=math.e, gt=0) + """Logarithm base. Use e (2.718...) for natural log, 2 for log2, 10 for log10.""" + + def apply(self, expr: pl.Expr) -> pl.Expr: + return expr.log(base=self.base) + + +class ExpFilter(BaseFilter): + """Raises a base to the power of each signal sample. Defaults to e^x.""" + + category: ClassVar[str] = "Arithmetic" + + type: Literal[FilterType.EXP] = FilterType.EXP + """The discriminator type for Pydantic.""" + + base: float = Field(default=math.e, gt=0) + """The base to exponentiate. Use e (2.718...) for the natural exponential.""" + + def apply(self, expr: pl.Expr) -> pl.Expr: + if abs(self.base - math.e) < 1e-12: + return expr.exp() + return expr.map_batches( + lambda s: pl.Series(np.power(self.base, s.fill_null(0).to_numpy())), + return_dtype=pl.Float64, + ) + + +class PowerFilter(BaseFilter): + """Raises each signal sample to a fixed exponent. Supports fractional exponents (e.g. 0.5 for sqrt).""" + + category: ClassVar[str] = "Arithmetic" + + type: Literal[FilterType.POWER] = FilterType.POWER + """The discriminator type for Pydantic.""" + + exponent: float = Field(default=2.0) + """The power to raise each sample to. Use 0.5 for square root, 1/3 for cube root.""" + + def apply(self, expr: pl.Expr) -> pl.Expr: + return expr.pow(self.exponent) + + +class RoundFilter(BaseFilter): + """Quantizes the signal to a fixed number of decimal places.""" + + category: ClassVar[str] = "Bounding" + + type: Literal[FilterType.ROUND] = FilterType.ROUND + """The discriminator type for Pydantic.""" + + method: Literal["round", "floor", "ceil"] = Field( + default="round", + json_schema_extra={"ui_type": "select"}, + ) + """Rounding method: round (nearest), floor (toward -inf), or ceil (toward +inf).""" + + decimals: int = Field(default=0, ge=0) + """Number of decimal places to round to (only used when method is 'round').""" + + def apply(self, expr: pl.Expr) -> pl.Expr: + if self.method == "floor": + return expr.floor() + if self.method == "ceil": + return expr.ceil() + return expr.round(self.decimals) + + +_TRIG_FUNCS = Literal[ + "sin", + "cos", + "tan", + "asin", + "acos", + "atan", + "sinh", + "cosh", + "tanh", + "degrees", + "radians", +] + + +class TrigFilter(BaseFilter): + """Applies a trigonometric or angle-conversion function to the signal.""" + + category: ClassVar[str] = "Trigonometry" + + type: Literal[FilterType.TRIG] = FilterType.TRIG + """The discriminator type for Pydantic.""" + + func: _TRIG_FUNCS = Field( + default="sin", + json_schema_extra={"ui_type": "select"}, + ) + """The trig function to apply.""" + + def apply(self, expr: pl.Expr) -> pl.Expr: + match self.func: + case "sin": + return expr.sin() + case "cos": + return expr.cos() + case "tan": + return expr.tan() + case "asin": + return expr.arcsin() + case "acos": + return expr.arccos() + case "atan": + return expr.arctan() + case "sinh": + return expr.sinh() + case "cosh": + return expr.cosh() + case "tanh": + return expr.tanh() + case "degrees": + return expr * (180.0 / math.pi) + case "radians": + return expr * (math.pi / 180.0) + case _: + return expr + + +class SignFilter(BaseFilter): + """Returns the sign of each sample: 1 for positive, -1 for negative, 0 for zero.""" + + category: ClassVar[str] = "Comparison" + + type: Literal[FilterType.SIGN] = FilterType.SIGN + """The discriminator type for Pydantic.""" + + def apply(self, expr: pl.Expr) -> pl.Expr: + return ( + pl.when(expr > 0) + .then(pl.lit(1.0)) + .when(expr < 0) + .then(pl.lit(-1.0)) + .otherwise(pl.lit(0.0)) + ) + + +_COMPARISON_OPS = Literal["gt", "gte", "lt", "lte", "eq", "neq"] + + +class ComparisonFilter(BaseFilter): + """Compares each sample against a threshold, returning 1.0 (true) or 0.0 (false).""" + + category: ClassVar[str] = "Comparison" + + type: Literal[FilterType.COMPARISON] = FilterType.COMPARISON + """The discriminator type for Pydantic.""" + + operator: _COMPARISON_OPS = Field( + default="gt", + json_schema_extra={"ui_type": "select"}, + ) + """Comparison operator: gt (>), gte (>=), lt (<), lte (<=), eq (==), neq (!=).""" + + threshold: float = 0.0 + """The value to compare each sample against.""" + + def apply(self, expr: pl.Expr) -> pl.Expr: + match self.operator: + case "gt": + cond = expr > self.threshold + case "gte": + cond = expr >= self.threshold + case "lt": + cond = expr < self.threshold + case "lte": + cond = expr <= self.threshold + case "eq": + cond = expr == self.threshold + case "neq": + cond = expr != self.threshold + case _: + return expr + return pl.when(cond).then(pl.lit(1.0)).otherwise(pl.lit(0.0)) + + AnyFilter = Annotated[ ScaleFilter | AbsoluteValueFilter @@ -446,7 +719,15 @@ def apply(self, expr: pl.Expr) -> pl.Expr: | UnitFilter | MedianFilter | NormalizeFilter - | WrapFilter, + | WrapFilter + | RotationFilter + | LogFilter + | ExpFilter + | PowerFilter + | RoundFilter + | TrigFilter + | SignFilter + | ComparisonFilter, Field(discriminator="type"), ] diff --git a/src/mujoco_mojo/utils/layers/cli.py b/src/mujoco_mojo/utils/layers/cli.py index 988b1ef3..d050ada7 100644 --- a/src/mujoco_mojo/utils/layers/cli.py +++ b/src/mujoco_mojo/utils/layers/cli.py @@ -1064,6 +1064,7 @@ def run_dojo( Panel( f"""[bold green]MuJoCo Mojo Dojo is Live![/bold green]\n\n{connection_info}\n\n[yellow]Press CTRL+C to stop[/yellow]""", border_style="cyan", + expand=False, title="Mojo Dojo", subtitle=f"Workers: {n_proc}", ) diff --git a/src/mujoco_mojo/utils/layers/dojo/lab_executor.py b/src/mujoco_mojo/utils/layers/dojo/lab_executor.py new file mode 100644 index 00000000..8d3e1ea9 --- /dev/null +++ b/src/mujoco_mojo/utils/layers/dojo/lab_executor.py @@ -0,0 +1,290 @@ +""" +Lab graph executor. + +Takes a LiteGraph-serialised graph (from graph.serialize() in the browser) +and executes it against a Polars DataFrame, returning the output series keyed +by their Signal Out labels. + +LiteGraph link format: + links: [[link_id, from_node_id, from_slot, to_node_id, to_slot, type], ...] +""" + +from __future__ import annotations + +from collections import defaultdict, deque +from typing import Any + +import polars as pl + +from mujoco_mojo.utils.filters.filters import ( + AbsoluteValueFilter, + ClipFilter, + ComparisonFilter, + DeadbandFilter, + ExpFilter, + HighPassFilter, + LogFilter, + LowPassFilter, + MedianFilter, + NormalizeFilter, + PowerFilter, + RollingMeanFilter, + RoundFilter, + SavitzkyGolayFilter, + ScaleFilter, + SignFilter, + TaringFilter, + TrigFilter, + WrapFilter, +) + +# Map node type string → filter class (single-input filters only) +_FILTER_MAP = { + "low_pass": LowPassFilter, + "high_pass": HighPassFilter, + "scale": ScaleFilter, + "rolling_mean": RollingMeanFilter, + "median": MedianFilter, + "savitzky_golay": SavitzkyGolayFilter, + "clip": ClipFilter, + "deadband": DeadbandFilter, + "wrap": WrapFilter, + "taring": TaringFilter, + "normalize": NormalizeFilter, + "absolute_value": AbsoluteValueFilter, + "log": LogFilter, + "exp": ExpFilter, + "power": PowerFilter, + "round": RoundFilter, + "trig": TrigFilter, + "sign": SignFilter, + "comparison": ComparisonFilter, +} + + +class LabExecutor: + """ + Execute a LiteGraph filter graph against a Polars DataFrame. + + Usage:: + + executor = LabExecutor(graph_dict) + outputs = executor.execute(df) # {label: pl.Series} + """ + + def __init__(self, graph: dict[str, Any]) -> None: + self.nodes: dict[int, dict] = {n["id"]: n for n in graph.get("nodes", [])} + # links keyed by link_id → [link_id, from_node, from_slot, to_node, to_slot, type] + self.links: dict[int, list] = {lnk[0]: lnk for lnk in graph.get("links", [])} + + # ── public helpers ──────────────────────────────────────────────────────── + + @staticmethod + def _bare_type(node: dict) -> str: + """Strip the LiteGraph category prefix, e.g. 'Signal/signal_in' → 'signal_in'.""" + return node.get("type", "").split("/")[-1] + + @property + def signal_in_columns(self) -> list[str]: + """Column names used by all Signal In nodes - used for validation.""" + return [ + n.get("properties", {}).get("column", "") + for n in self.nodes.values() + if self._bare_type(n) == "signal_in" + ] + + @property + def output_labels(self) -> list[str]: + """Labels produced by all Signal Out nodes.""" + return [ + n.get("properties", {}).get("label") or f"out_{n['id']}" + for n in self.nodes.values() + if self._bare_type(n) == "signal_out" + ] + + def execute(self, df: pl.DataFrame) -> dict[str, pl.Series]: + """Run the graph and return {output_label: series}.""" + # slot_data[node_id][slot_index] = computed series + slot_data: dict[int, dict[int, pl.Series]] = defaultdict(dict) + + for nid in self._topo_sort(): + node = self.nodes[nid] + ntype = self._bare_type(node) + props = node.get("properties", {}) + + if ntype == "signal_in": + col = props.get("column", "") + series = ( + df[col].cast(pl.Float64) + if col in df.columns + else pl.Series(name=col, values=[0.0] * len(df)) + ) + slot_data[nid][0] = series + + elif ntype == "constant": + value = float(props.get("value", 0.0)) + slot_data[nid][0] = pl.Series( + name="const", values=[value] * len(df), dtype=pl.Float64 + ) + + elif ntype == "signal_out": + signal = self._get_input(node, 0, slot_data) + if signal is not None: + slot_data[nid][0] = signal + + else: + signal = self._get_input(node, 0, slot_data) + if signal is None: + continue + wrt = self._get_input(node, 1, slot_data) + slot_data[nid][0] = self._apply(ntype, props, signal, wrt, df) + + # Collect Signal Out results + outputs: dict[str, pl.Series] = {} + for nid, node in self.nodes.items(): + if self._bare_type(node) == "signal_out": + series = slot_data.get(nid, {}).get(0) + if series is not None: + label = node.get("properties", {}).get("label") or f"out_{nid}" + outputs[label] = series + return outputs + + # ── internals ───────────────────────────────────────────────────────────── + + def _topo_sort(self) -> list[int]: + in_degree: dict[int, int] = {nid: 0 for nid in self.nodes} + adj: dict[int, list[int]] = defaultdict(list) + for _, from_node, _, to_node, _, *_ in self.links.values(): + adj[from_node].append(to_node) + in_degree[to_node] += 1 + queue = deque(nid for nid, deg in in_degree.items() if deg == 0) + order: list[int] = [] + while queue: + nid = queue.popleft() + order.append(nid) + for nxt in adj[nid]: + in_degree[nxt] -= 1 + if in_degree[nxt] == 0: + queue.append(nxt) + return order + + def _get_input( + self, + node: dict, + slot: int, + slot_data: dict[int, dict[int, pl.Series]], + ) -> pl.Series | None: + inputs = node.get("inputs", []) + if slot >= len(inputs): + return None + link_id = inputs[slot].get("link") + if link_id is None or link_id not in self.links: + return None + lnk = self.links[link_id] + from_node, from_slot = lnk[1], lnk[2] + return slot_data.get(from_node, {}).get(from_slot) + + def _apply( + self, + ntype: str, + props: dict, + signal: pl.Series, + wrt: pl.Series | None, + df: pl.DataFrame, + ) -> pl.Series: + # Individual trig nodes (one node per function, no combo widget) + _TRIG_FNS = { + "sin", + "cos", + "tan", + "asin", + "acos", + "atan", + "sinh", + "cosh", + "tanh", + "degrees", + "radians", + } + if ntype in _TRIG_FNS: + filt = TrigFilter(func=ntype) # type: ignore[arg-type] + tmp = pl.DataFrame({"_s": signal.cast(pl.Float64)}) + return tmp.with_columns(filt.apply(pl.col("_s")).alias("_s"))["_s"] + + # Individual comparison nodes - signal vs signal, returns 1.0/0.0 + _CMP_OPS = {"gt", "gte", "lt", "lte", "eq", "neq"} + if ntype in _CMP_OPS: + if wrt is None: + return signal + a = signal.cast(pl.Float64) + b = wrt.cast(pl.Float64) + if ntype == "gt": + return (a > b).cast(pl.Float64) + if ntype == "gte": + return (a >= b).cast(pl.Float64) + if ntype == "lt": + return (a < b).cast(pl.Float64) + if ntype == "lte": + return (a <= b).cast(pl.Float64) + if ntype == "eq": + return (a == b).cast(pl.Float64) + return (a != b).cast(pl.Float64) + + # Two-input arithmetic (signal a op signal b) + if ntype in ("add", "subtract", "multiply", "divide"): + if wrt is None: + return signal + a = signal.cast(pl.Float64) + b = wrt.cast(pl.Float64) + if ntype == "add": + return a + b + if ntype == "subtract": + return a - b + if ntype == "multiply": + return a * b + # divide: propagate zero denominator as null (will become NaN in JSON) + tmp = pl.DataFrame({"_a": a, "_b": b}) + return tmp.select( + pl.when(pl.col("_b") != 0) + .then(pl.col("_a") / pl.col("_b")) + .otherwise(None) + .cast(pl.Float64) + ).to_series() + + # Derivative and Integral handle wrt directly + if ntype == "derivative": + if wrt is not None: + dx = ( + wrt.cast(pl.Float64) + .diff() + .fill_null(strategy="forward") + .fill_null(1) + ) + return signal.cast(pl.Float64).diff().fill_null(0) / dx + dt = float(props.get("dt", 0.001)) or 0.001 + return signal.cast(pl.Float64).diff().fill_null(0) / dt + + if ntype == "integral": + if wrt is not None: + dx = wrt.cast(pl.Float64).diff().fill_null(0) + return (signal.cast(pl.Float64) * dx).cum_sum() + dt = float(props.get("dt", 0.001)) or 0.001 + return signal.cast(pl.Float64).cum_sum() * dt + + cls = _FILTER_MAP.get(ntype) + if cls is None: + return signal + + # Strip None values so Pydantic uses field defaults + clean = {k: v for k, v in props.items() if v is not None} + try: + filt = cls(**clean) + except Exception: + return signal + + tmp = pl.DataFrame({"_s": signal.cast(pl.Float64)}) + ctx = filt.apply_with_context(tmp["_s"], df) + if ctx is not None: + return ctx + tmp = tmp.with_columns(filt.apply(pl.col("_s")).alias("_s")) + return tmp["_s"] diff --git a/src/mujoco_mojo/utils/layers/dojo/routers/mosaic.py b/src/mujoco_mojo/utils/layers/dojo/routers/mosaic.py index 03105e6f..a4113c14 100644 --- a/src/mujoco_mojo/utils/layers/dojo/routers/mosaic.py +++ b/src/mujoco_mojo/utils/layers/dojo/routers/mosaic.py @@ -12,9 +12,11 @@ from fastapi.responses import HTMLResponse from mujoco_mojo.utils.dataframe import ColumnManifest, MojoDataFrame +from mujoco_mojo.utils.defaults import TIME_COLUMN_NAME as _TIME_COLUMN_NAME from mujoco_mojo.utils.filters.filters import UNIT_GROUPS as _UNIT_GROUPS from mujoco_mojo.utils.filters.filters import AnyFilter as _AnyFilter from mujoco_mojo.utils.filters.filters import FilterType as _FilterType +from mujoco_mojo.utils.filters.filters import RotationFilter as _RotationFilter from mujoco_mojo.utils.filters.filters import filter_adapter as _filter_adapter from mujoco_mojo.utils.log import get_logger @@ -218,6 +220,8 @@ async def get_filter_schema(): def _infer_type(prop: dict) -> str: if prop.get("ui_type") == "col": return "col" + if prop.get("ui_type") == "select": + return "select" if "anyOf" in prop: non_null = [s for s in prop["anyOf"] if s.get("type") != "null"] prop = non_null[0] if non_null else {} @@ -254,6 +258,8 @@ def _infer_type(prop: dict) -> str: default = round(float(default), 8) p: dict = {"name": name, "type": _infer_type(prop), "default": default} + if p["type"] == "select" and "enum" in prop: + p["options"] = prop["enum"] if "minimum" in prop_clean: p["min"] = prop_clean["minimum"] if "maximum" in prop_clean: @@ -271,6 +277,7 @@ def _infer_type(prop: dict) -> str: "type": type_val, "label": type_val.replace("_", " ").title(), "description": description, + "category": cls.category, "params": params, } if type_val == "unit": @@ -395,10 +402,186 @@ async def delete_profile(name: str): return {"deleted": path.relative_to(d).with_suffix("").as_posix()} +# --------------------------------------------------------------------------- +# Lab · filter graph configs stored under ~/.mujoco-mojo/lab/ +# --------------------------------------------------------------------------- + +_LAB_PREFIX = "Lab" # Virtual column category shown in the Y-axis selector +_LAB_MAX_BYTES = 1024 * 1024 # 1 MB + + +def _get_lab_dir() -> Path: + d: Path = Path.home() / ".mujoco-mojo" / "lab" + d.mkdir(parents=True, exist_ok=True) + return d + + +def _sanitize_lab_name(name: str) -> str: + """ + Return a filesystem-safe relative path from the user-supplied lab name. + + Supports folder separators, e.g. 'robotics/arm_reach/baseline'. + Each segment is sanitized independently; empty segments are dropped. + """ + name = name.strip()[:256] + segments = [s.strip() for s in name.split("/") if s.strip()] + safe: list[str] = [] + for seg in segments: + seg = re.sub(r"[^\w\s\-]", "", seg) + seg = re.sub(r"\s+", "_", seg) + seg = re.sub(r"_+", "_", seg).strip("_") + if seg: + safe.append(seg[:64]) + return "/".join(safe) or "lab" + + +def _resolve_lab_path(name: str) -> Path: + d = _get_lab_dir() + path = (d / f"{_sanitize_lab_name(name)}.json").resolve() + if not path.is_relative_to(d.resolve()): + raise HTTPException(status_code=400, detail="Invalid lab name") + return path + + +def _lab_meta(path: Path, d: Path) -> dict: + """Parse a saved lab file and return metadata for the API.""" + from mujoco_mojo.utils.layers.dojo.lab_executor import LabExecutor + + try: + graph = json.loads(path.read_text(encoding="utf-8")) + exc = LabExecutor(graph) + return { + "name": path.relative_to(d).with_suffix("").as_posix(), + "modified": int(path.stat().st_mtime * 1000), + "signal_in_columns": exc.signal_in_columns, + "outputs": exc.output_labels, + } + except Exception: + return { + "name": path.relative_to(d).with_suffix("").as_posix(), + "modified": int(path.stat().st_mtime * 1000), + "signal_in_columns": [], + "outputs": [], + } + + +@router.get("/api/lab") +async def list_labs(): + """List all saved lab graphs with their input column requirements and output labels.""" + d = _get_lab_dir() + return [ + _lab_meta(f, d) + for f in sorted( + d.rglob("*.json"), key=lambda p: p.stat().st_mtime, reverse=True + ) + ] + + +@router.get("/api/lab/{name:path}") +async def get_lab(name: str): + """Return the raw LiteGraph JSON for a saved lab.""" + path = _resolve_lab_path(name) + if not path.exists(): + raise HTTPException(status_code=404, detail="Lab not found") + return json.loads(path.read_text(encoding="utf-8")) + + +@router.post("/api/lab/{name:path}") +async def save_lab(name: str, request: Request): + """Save a LiteGraph graph JSON as a named lab.""" + cl = request.headers.get("content-length") + if cl and int(cl) > _LAB_MAX_BYTES: + raise HTTPException(status_code=413, detail="Lab payload too large") + body = await request.json() + path = _resolve_lab_path(name) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(body), encoding="utf-8") + d = _get_lab_dir() + return {"name": path.relative_to(d).with_suffix("").as_posix()} + + +@router.delete("/api/lab/{name:path}") +async def delete_lab(name: str): + """Delete a saved lab.""" + path = _resolve_lab_path(name) + if not path.exists(): + raise HTTPException(status_code=404, detail="Lab not found") + path.unlink() + d = _get_lab_dir() + # Remove empty parent directories up to (but not including) the lab root. + parent = path.parent + while parent != d and parent.is_dir() and not any(parent.iterdir()): + parent.rmdir() + parent = parent.parent + return {"deleted": path.relative_to(d).with_suffix("").as_posix()} + + +def _lab_dir_mtime() -> float: + """Max mtime of any file in the lab directory; used as a cache key.""" + d = _get_lab_dir() + try: + mtimes = [f.stat().st_mtime for f in d.rglob("*.json")] + return max(mtimes) if mtimes else 0.0 + except Exception: + return 0.0 + + +@lru_cache(maxsize=32) +def _valid_lab_columns_cached(parquet_cols: frozenset, lab_mtime: float) -> list: + """ + BFS to find all valid lab virtual column names for a given parquet column set. + + Mirrors the frontend loadLabSchemas logic. Cached by column frozenset + lab dir mtime. + Returns a list of 'Lab/{name}/{output}' strings. + """ + from mujoco_mojo.utils.layers.dojo.lab_executor import LabExecutor + + d = _get_lab_dir() + labs = [] + for f in sorted(d.rglob("*.json"), key=lambda p: p.stat().st_mtime, reverse=True): + try: + graph = json.loads(f.read_text(encoding="utf-8")) + exc = LabExecutor(graph) + labs.append( + { + "name": f.relative_to(d).with_suffix("").as_posix(), + "si_cols": set(exc.signal_in_columns), + "outputs": exc.output_labels, + } + ) + except Exception: + pass + + available: set = set(parquet_cols) + valid_cols: list = [] + processed: set = set() + changed = True + while changed: + changed = False + for lab in labs: + name = lab["name"] + if name in processed: + continue + if lab["si_cols"].issubset(available): + processed.add(name) + changed = True + for out in lab["outputs"]: + col = f"{_LAB_PREFIX}/{name}/{out}" + valid_cols.append(col) + available.add(col) + return valid_cols + + +@lru_cache(maxsize=128) +def _get_mojo_df(path_str: str, mtime: float) -> MojoDataFrame: + """Zero-row MojoDataFrame for schema queries, cached by path and mtime.""" + return MojoDataFrame.from_metadata(path_str) + + @lru_cache(maxsize=128) def _get_column_manifest(path_str: str, mtime: float) -> ColumnManifest: """Retrieves all column names from the table schema.""" - return MojoDataFrame.from_metadata(path_str).mojo.get_manifest() + return _get_mojo_df(path_str, mtime).mojo.get_manifest() @lru_cache(maxsize=2048) @@ -453,12 +636,22 @@ async def get_trial_data( mtime = db_path.stat().st_mtime db_path_str = str(db_path) - # get the manifest of ALL columns in the df - column_manifest = _get_column_manifest(db_path_str, mtime) + # Parquet-only manifest (cached), then augment with valid lab virtual columns. + parquet_manifest = _get_column_manifest(db_path_str, mtime) + lab_mtime = _lab_dir_mtime() + lab_extra = _valid_lab_columns_cached(frozenset(parquet_manifest["all"]), lab_mtime) + column_manifest = ( + _get_mojo_df(db_path_str, mtime).mojo.get_manifest( + extra_columns=list(lab_extra) + ) + if lab_extra + else parquet_manifest + ) try: requested = cols.split(",") if cols else [] - available_cols = set(column_manifest["all"]) + # available_cols covers only parquet columns for actual fetch logic + available_cols = set(parquet_manifest["all"]) # determine columns to request fetch_targets = [c for c in requested if c in available_cols] @@ -474,6 +667,89 @@ async def get_trial_data( if q in available_cols and q not in fetch_targets: fetch_targets.append(q) + # ── Collect lab SI columns before building the df ───────────────────── + # Lab virtual columns are computed from the graph, not read from parquet. + # We load executors now so we can add their parquet SI deps to fetch_targets. + lab_cols = [c for c in requested if c.startswith(f"{_LAB_PREFIX}/")] + from collections import defaultdict as _dd + + by_lab: dict[str, list[tuple[str, str]]] = _dd(list) + lab_executors: dict = {} + + if lab_cols: + from mujoco_mojo.utils.layers.dojo.lab_executor import LabExecutor + + for col in lab_cols: + parts = col.split("/", 2) + if len(parts) == 3: + _, lab_name, output_label = parts + by_lab[lab_name].append((col, output_label)) + + # Load executors transitively so chained labs have their deps available. + to_load = list(by_lab.keys()) + while to_load: + name = to_load.pop() + if name in lab_executors: + continue + lab_path = _resolve_lab_path(name) + if not lab_path.exists(): + continue + try: + g = json.loads(lab_path.read_text(encoding="utf-8")) + lab_executors[name] = LabExecutor(g) + for si_col in lab_executors[name].signal_in_columns: + if si_col.startswith(f"{_LAB_PREFIX}/"): + dep_parts = si_col.split("/", 2) + if ( + len(dep_parts) == 3 + and dep_parts[1] not in lab_executors + ): + to_load.append(dep_parts[1]) + except Exception: + pass + + # Add parquet SI columns and the time column to fetch_targets. + extra_si: set[str] = set() + for executor in lab_executors.values(): + for si_col in executor.signal_in_columns: + if si_col in available_cols: + extra_si.add(si_col) + if _TIME_COLUMN_NAME in available_cols: + extra_si.add(_TIME_COLUMN_NAME) + existing_targets = set(fetch_targets) + fetch_targets.extend(c for c in extra_si if c not in existing_targets) + + # ── Pre-flight: ensure RotationFilter dependencies are fetched ──────── + # Parse filters early (errors are tolerated; full parse happens again below). + if filters: + try: + _preflight = _filter_adapter.validate_python(json.loads(filters)) + _existing = set(fetch_targets) + for _col, _flist in _preflight.items(): + for _f in _flist: + if not isinstance(_f, _RotationFilter) or not _f.quat_col: + continue + # Sibling vector components for the column being rotated + if ( + _col.endswith(":x") + or _col.endswith(":y") + or _col.endswith(":z") + ): + _base = _col.rsplit(":", 1)[0] + for _comp in ("x", "y", "z"): + _sib = f"{_base}:{_comp}" + if _sib in available_cols and _sib not in _existing: + fetch_targets.append(_sib) + _existing.add(_sib) + # Quaternion components + for _comp in ("w", "x", "y", "z"): + _qc = f"{_f.quat_col}:{_comp}" + if _qc in available_cols and _qc not in _existing: + fetch_targets.append(_qc) + _existing.add(_qc) + except Exception: + pass + # early exit for no found columns if not fetch_targets: return {"columns": column_manifest, "data": {}} @@ -488,7 +764,7 @@ async def get_trial_data( # rotate from world to rotate_by frame df = df.mojo.with_rotation(quat_base=rotate_by, invert=True) - # parse validated filter stacks (col_name → list[AnyFilter]) + # parse validated filter stacks (col_name -> list[AnyFilter]) col_filters: dict = {} filter_errors: list[str] = [] if filters: @@ -498,9 +774,78 @@ async def get_trial_data( logger.warning(f"Could not parse filters for {trial_id}: {e}") filter_errors.append(_format_filter_error(e)) - # build response data, applying per-column filters where present data: dict = {} + + # ── Execute lab virtual columns (multi-pass for chained labs) ────────── + if lab_cols and lab_executors: + exec_df = df + lab_cols_set = set(lab_cols) + + # For transitive deps not directly requested, expose all their outputs + # so downstream labs can use them as inputs via exec_df. + all_by_lab: dict[str, list[tuple[str, str]]] = dict(by_lab) + for lab_name, executor in lab_executors.items(): + if lab_name not in all_by_lab: + all_by_lab[lab_name] = [ + (f"{_LAB_PREFIX}/{lab_name}/{out}", out) + for out in executor.output_labels + ] + + remaining = dict(all_by_lab) + for _ in range(len(remaining) + 1): + if not remaining: + break + progress = False + for lab_name in list(remaining.keys()): + if lab_name not in lab_executors: + del remaining[lab_name] + progress = True + continue + executor = lab_executors[lab_name] + # Wait until all lab-virtual SI deps are present in exec_df. + if any( + c not in exec_df.columns + for c in executor.signal_in_columns + if c.startswith(f"{_LAB_PREFIX}/") + ): + continue + try: + outputs = executor.execute(exec_df) + new_series: list[pl.Series] = [] + for full_col, output_label in remaining[lab_name]: + if output_label in outputs: + s = outputs[output_label].rename(full_col) + new_series.append(s) + if full_col in lab_cols_set: + data[full_col] = s.to_list() + if new_series: + exec_df = MojoDataFrame.from_pl(exec_df.hstack(new_series)) + del remaining[lab_name] + progress = True + except Exception as exc: + logger.warning(f"Lab '{lab_name}' execution failed: {exc}") + del remaining[lab_name] + progress = True + if not progress: + break + + # ── build response data, applying per-column filters where present ──── for col in requested: + if col.startswith(f"{_LAB_PREFIX}/"): + # Lab output already in data; apply any stacked filters on top. + filter_list = col_filters.get(col) + if filter_list and col in data: + series = pl.Series(name=col, values=data[col], dtype=pl.Float64) + for f in filter_list: + ctx = f.apply_with_context(series, df) + if ctx is not None: + series = ctx + else: + tmp = pl.DataFrame({col: series}) + tmp = tmp.with_columns(f.apply(pl.col(col)).alias(col)) + series = tmp[col] + data[col] = series.to_list() + continue if col not in df.columns: continue series = df[col] diff --git a/src/mujoco_mojo/utils/layers/dojo/templates/base.html b/src/mujoco_mojo/utils/layers/dojo/templates/base.html index 0f8e3094..69e01128 100644 --- a/src/mujoco_mojo/utils/layers/dojo/templates/base.html +++ b/src/mujoco_mojo/utils/layers/dojo/templates/base.html @@ -21,14 +21,6 @@ - - - @@ -101,11 +93,6 @@ } } - + + + diff --git a/src/mujoco_mojo/utils/layers/dojo/templates/static/js/main.js b/src/mujoco_mojo/utils/layers/dojo/templates/static/js/main.js index c991af78..d3a10a40 100644 --- a/src/mujoco_mojo/utils/layers/dojo/templates/static/js/main.js +++ b/src/mujoco_mojo/utils/layers/dojo/templates/static/js/main.js @@ -30,7 +30,11 @@ isAutoRefresh: localStorage.getItem("mojo_auto") !== "false", isConnected: false, _wasConnected: null, - globalToast: { show: false, message: "", type: "info" }, + globalToast: { + show: false, + message: "", + type: "info" + }, isSyncing: false, syncProgress: 0, secondsSinceUpdate: 0, @@ -114,7 +118,7 @@ } if (connected === this._wasConnected) return; this._wasConnected = connected; - const message = connected ? "Server connection restored." : "Server connection lost."; + const message = connected ? "Server connection restored" : "Server connection lost"; const type = connected ? "success" : "error"; this.toast(message, type); this.addNotification(message, type); @@ -154,7 +158,9 @@ }, startLoadingMessages() { if (this.loadingInterval) return; - this.loadingIndex = Math.floor(Math.random() * this.loadingPhrases.length); + this.loadingIndex = Math.floor( + Math.random() * this.loadingPhrases.length + ); this.showPhrase = true; this.loadingInterval = setInterval(() => { this.showPhrase = false; @@ -203,7 +209,8 @@ try { const data = JSON.parse(event.data); if (data.type === "start") this.startSync(); - if (data.type === "progress" && data.value !== void 0) this.setSyncProgress(data.value); + if (data.type === "progress" && data.value !== void 0) + this.setSyncProgress(data.value); if (data.type === "final") { this.endSync(Date.now(), data.status?.is_complete ?? false); window.dispatchEvent( @@ -211,7 +218,10 @@ ); } } catch (err) { - console.warn("[Mojo Sync] Received invalid payload.", { raw: event.data, error: err }); + console.warn("[Mojo Sync] Received invalid payload.", { + raw: event.data, + error: err + }); } }; this.source.onerror = () => { @@ -260,10 +270,13 @@ notifTick: Date.now(), _saveNotifications() { try { - localStorage.setItem("mojo_notif", JSON.stringify({ - n: this.notifications, - u: this.unreadCount - })); + localStorage.setItem( + "mojo_notif", + JSON.stringify({ + n: this.notifications, + u: this.unreadCount + }) + ); } catch { } }, @@ -300,7 +313,9 @@ const store = Alpine.store("dojo"); setInterval(() => { if (store.lastUpdate) { - store.secondsSinceUpdate = Math.floor((Date.now() - store.lastUpdate) / 1e3); + store.secondsSinceUpdate = Math.floor( + (Date.now() - store.lastUpdate) / 1e3 + ); } }, 1e3); setInterval(() => { diff --git a/src/mujoco_mojo/utils/layers/dojo/templates/static/js/monitor.js b/src/mujoco_mojo/utils/layers/dojo/templates/static/js/monitor.js index 64dcdd36..0c00e15f 100644 --- a/src/mujoco_mojo/utils/layers/dojo/templates/static/js/monitor.js +++ b/src/mujoco_mojo/utils/layers/dojo/templates/static/js/monitor.js @@ -24,7 +24,10 @@ const resp = await fetch("/monitor/api/status"); const data = await resp.json(); if (data && !data.error) { - Alpine.store("dojo").updateSync(Date.now(), data.is_complete); + Alpine.store("dojo").updateSync( + Date.now(), + data.is_complete + ); this.handleDataUpdate(data); } } catch (e) { @@ -32,13 +35,20 @@ } finally { const store = Alpine.store("dojo"); store.startGlobalSync(); - store.setPageReady(true, this.status.is_complete); + store.setPageReady( + true, + this.status.is_complete + ); } }, handleDataUpdate(data) { const wasInit = this.hasInitialData; const prev = { ...this.prevStatus }; - this.prevStatus = { n_done: data.n_done, n_success: data.n_success, n_failed: data.n_failed }; + this.prevStatus = { + n_done: data.n_done, + n_success: data.n_success, + n_failed: data.n_failed + }; this.status = data; this.hasInitialData = true; this.refreshStats(); @@ -52,10 +62,13 @@ if (newDone === 1) { const failed = newFailed === 1; const trialId = failed ? data.failure_tns.at(-1) : data.success_tns.at(-1); - store.addNotification(`Trial ${trialId} ${failed ? "failed" : "succeeded"}`, failed ? "error" : "success"); + store.addNotification( + `Trial ${trialId} ${failed ? "failed" : "succeeded"}`, + failed ? "error" : "success" + ); } else { store.addNotification( - `${newDone} trials done \u2014 ${newDone - newFailed} ok, ${newFailed} failed`, + `${newDone} trials done - ${newDone - newFailed} ok, ${newFailed} failed`, newFailed > 0 ? "error" : "success" ); } @@ -121,7 +134,7 @@ this.hasCelebrated = true; const store = Alpine.store("dojo"); store.addNotification( - `Job complete in ${this.status.elapsed} \u2014 ${this.status.n_success} succeeded, ${this.status.n_failed} failed`, + `Job complete in ${this.status.elapsed} - ${this.status.n_success} succeeded, ${this.status.n_failed} failed`, this.status.n_failed > 0 ? "error" : "success" ); const theme = this.getHolidayTheme(); @@ -144,24 +157,47 @@ const m = now.getMonth(); const d = now.getDate(); if (m === 11 && d === 31 || m === 0 && d <= 2) { - return { name: "New Year", emojis: ["\u{1F386}", "\u2728", "\u{1F942}"], colors: ["#ffcc00", "#ffffff"] }; + return { + name: "New Year", + emojis: ["\u{1F386}", "\u2728", "\u{1F942}"], + colors: ["#ffcc00", "#ffffff"] + }; } if (m === 2 && d === 14) { return { name: "Pi Day", emojis: ["\u03C0", "\u{1F967}"], colors: ["#ff9900"] }; } if (m === 2 && d === 17) { - return { name: "St. Patrick's Day", emojis: ["\u{1F340}", "\u{1F308}"], colors: ["#22c55e", "#166534"] }; + return { + name: "St. Patrick's Day", + emojis: ["\u{1F340}", "\u{1F308}"], + colors: ["#22c55e", "#166534"] + }; } if (m === 4 && d === 4) { - return { name: "May the 4th", emojis: ["\u2694\uFE0F", "\u{1F30C}", "\u2728"], colors: ["#FFE81F", "#2dd4bf"] }; + return { + name: "May the 4th", + emojis: ["\u2694\uFE0F", "\u{1F30C}", "\u2728"], + colors: ["#FFE81F", "#2dd4bf"] + }; } if (m === 9 && d >= 25 || m === 10 && d === 1) { - return { name: "Halloween", emojis: ["\u{1F383}", "\u{1F47B}", "\u{1F987}"], colors: ["#ff6600", "#9437ff"] }; + return { + name: "Halloween", + emojis: ["\u{1F383}", "\u{1F47B}", "\u{1F987}"], + colors: ["#ff6600", "#9437ff"] + }; } if (m === 11 || m === 0 && d <= 15) { - return { name: "Winter Snow", emojis: ["\u2744\uFE0F", "\u26C4", "\u{1F328}\uFE0F"], isSnow: true }; + return { + name: "Winter Snow", + emojis: ["\u2744\uFE0F", "\u26C4", "\u{1F328}\uFE0F"], + isSnow: true + }; } - return { name: "Standard Mojo", colors: ["#06b6d4", "#3b82f6", "#22c55e"] }; + return { + name: "Standard Mojo", + colors: ["#06b6d4", "#3b82f6", "#22c55e"] + }; }, fireConfetti(theme = { name: "Standard Mojo" }) { const themeName = theme.name ?? "Standard Mojo"; @@ -188,22 +224,37 @@ scalar: isSpecial ? 5 : 1, gravity: isSnow ? 0.4 : isSpecial ? 0.4 : 1.2 }; - const interval = setInterval(() => { - const timeLeft = animationEnd - Date.now(); - if (timeLeft <= 0) { - clearInterval(interval); - return; - } - if (isSnow) { - confetti({ ...defaults, particleCount: 1, startVelocity: 0, drift: (Math.random() - 0.5) * 1.5, origin: { x: Math.random(), y: -0.2 } }); - } else { - const countMultiplier = isSpecial ? 40 : 150; - const particleCount = countMultiplier * (timeLeft / duration); - for (let i = 0; i < 3; i++) { - confetti({ ...defaults, particleCount: Math.ceil(particleCount / 3), spread: isSpecial ? 90 : 360, startVelocity: isSpecial ? 15 : 45, origin: { x: Math.random(), y: Math.random() - 0.2 } }); + const interval = setInterval( + () => { + const timeLeft = animationEnd - Date.now(); + if (timeLeft <= 0) { + clearInterval(interval); + return; } - } - }, isSpecial ? 400 : 250); + if (isSnow) { + confetti({ + ...defaults, + particleCount: 1, + startVelocity: 0, + drift: (Math.random() - 0.5) * 1.5, + origin: { x: Math.random(), y: -0.2 } + }); + } else { + const countMultiplier = isSpecial ? 40 : 150; + const particleCount = countMultiplier * (timeLeft / duration); + for (let i = 0; i < 3; i++) { + confetti({ + ...defaults, + particleCount: Math.ceil(particleCount / 3), + spread: isSpecial ? 90 : 360, + startVelocity: isSpecial ? 15 : 45, + origin: { x: Math.random(), y: Math.random() - 0.2 } + }); + } + } + }, + isSpecial ? 400 : 250 + ); } }; } diff --git a/src/mujoco_mojo/utils/layers/dojo/templates/static/js/trial-viewer.js b/src/mujoco_mojo/utils/layers/dojo/templates/static/js/trial-viewer.js index 01145f4d..dccb8622 100644 --- a/src/mujoco_mojo/utils/layers/dojo/templates/static/js/trial-viewer.js +++ b/src/mujoco_mojo/utils/layers/dojo/templates/static/js/trial-viewer.js @@ -116,9 +116,14 @@ annotations: [], shapes: [] }; + var _cm = { + editor: null, + updating: false, + debounce: null + }; function trialViewer(trialId, externalUrl) { const self = { - // Alpine magic (injected at runtime — declared here for TS) + // Alpine magic (injected at runtime - declared here for TS) ...null, // --- BASE STATE --- trialId, @@ -155,7 +160,7 @@ ], // Toast (shared mixin) ...createToastMixin(), - // Options — exposed so templates can use opts.lineMode, opts.interpLabel(...), etc. + // Options - exposed so templates can use opts.lineMode, opts.interpLabel(...), etc. opts: OPTIONS, // --- PLOT CONFIGURATION --- config: JSON.parse(JSON.stringify(DEFAULT_CONFIG)), @@ -197,6 +202,20 @@ annotationsOpen: false, annDraft: null, annEditIndex: null, + // --- FILTER LAB --- + labOpen: localStorage.getItem("mojo:lab:open") === "1", + labGraph: (() => { + try { + const s = localStorage.getItem("mojo:lab:draft"); + return s ? JSON.parse(s) : null; + } catch { + return null; + } + })(), + labName: localStorage.getItem("mojo:lab:name") ?? "", + nodePickingColumn: null, + nodeColSearch: "", + labSchemas: [], // --- SHAPES --- shapesOpen: false, placementMode: null, @@ -275,10 +294,12 @@ const colParams = new URLSearchParams(); if (requiredCols.length > 0) colParams.append("cols", requiredCols.join(",")); - if (this.config.refFrame) - colParams.append("rotate_by", this.config.refFrame); const filtersPayload = {}; - const toActiveFilters = (filters) => filters.filter((f) => f.enabled !== false).map((f) => Object.fromEntries(Object.entries(f).filter(([k]) => k !== "enabled"))); + const toActiveFilters = (filters) => filters.filter((f) => f.enabled !== false).map( + (f) => Object.fromEntries( + Object.entries(f).filter(([k]) => k !== "enabled") + ) + ); for (const col of requiredCols) { const yConfig = this.config.yAxes[col]; if (yConfig?.filters && yConfig.filters.length > 0) { @@ -358,7 +379,10 @@ if (currentId !== this.discoveryId) return; const start = Math.min(this.vsDraft.range[0], this.vsDraft.range[1]); const end = Math.max(this.vsDraft.range[0], this.vsDraft.range[1]); - const activeCols = [this.config.xAxis.col, ...Object.keys(this.config.yAxes)]; + const activeCols = [ + this.config.xAxis.col, + ...Object.keys(this.config.yAxes) + ]; const draftIds = this.allTrials.filter((id) => { const n = parseInt(id.split("_").pop() ?? ""); return n >= start && n <= end && id !== this.trialId; @@ -583,6 +607,7 @@ this.columns = response.columns.all.sort(); this.rotateableVectors = response.columns.rotatable_vectors ?? []; this.data = response.data; + void this.loadLabSchemas(); const params = new URLSearchParams(window.location.search); const shared = params.get("v"); if (shared) { @@ -595,6 +620,12 @@ this.vsDraft.enabled = this.config.vsEnabled; this.vsDraft.range = [...this.config.vsRange]; } + if (this.config.refFrame) { + const hasRotation = Object.values(this.config.yAxes).some( + (y) => y.filters.some((f) => f.type === "rotation") + ); + if (!hasRotation) this.applyRefFrame(this.config.refFrame); + } void this.$nextTick(() => { this.pushHistory(); }); @@ -693,47 +724,101 @@ Alpine.store("dojo").startGlobalSync(); Alpine.store("dojo").setPageReady(true); } - window.addEventListener("keydown", (e) => { - if (e.repeat) return; - const tag = e.target.tagName; - if (e.key === "/" && !["INPUT", "TEXTAREA"].includes(tag)) { - e.preventDefault(); - document.querySelector('input[type="number"]')?.focus(); - } - if (e.key === "Escape") { - const anyOpen = !!(this.placementMode || this.annotationsOpen || this.shapesOpen || this.xMenuOpen || this.yMenuOpen || this.refFrameMenuOpen || this.settingsOpen || this.downloadOpen || this.editorOpen || this.profilesOpen || this.vsMenuOpen || Alpine.store("dojo").overlayCount > 0 || ["INPUT", "TEXTAREA"].includes(tag)); - if (["INPUT", "TEXTAREA"].includes(tag)) - e.target.blur(); - this.placementMode = null; - this.rectStart = null; - this.cancelAnnDraft(); - this.cancelShapeDraft(); - this.annotationsOpen = false; - this.shapesOpen = false; - this.xMenuOpen = this.yMenuOpen = this.refFrameMenuOpen = false; - this.settingsOpen = this.downloadOpen = this.editorOpen = false; - this.profilesOpen = this.vsMenuOpen = false; - this.profileSearch = ""; - window.dispatchEvent(new CustomEvent("mojo:escape")); - if (anyOpen) e.stopImmediatePropagation(); - } - if (["INPUT", "TEXTAREA"].includes(tag)) return; - if (e.key === "ArrowLeft") document.getElementById("nav-prev")?.click(); - if (e.key === "ArrowRight") - document.getElementById("nav-next")?.click(); - const isZ = e.key.toLowerCase() === "z"; - const isY = e.key.toLowerCase() === "y"; - const cmdOrCtrl = e.metaKey || e.ctrlKey; - if (cmdOrCtrl && isZ) { - e.preventDefault(); - if (e.shiftKey) this.redo(); - else this.undo(); - } - if (cmdOrCtrl && isY) { - e.preventDefault(); - this.redo(); - } - }, { capture: true }); + window.addEventListener( + "keydown", + (e) => { + if (e.repeat) return; + const targetEl = e.target; + const tag = targetEl.tagName; + const isTextInput = ["INPUT", "TEXTAREA", "SELECT"].includes(tag) || targetEl.isContentEditable; + if (e.key === "/" && !isTextInput) { + e.preventDefault(); + document.querySelector( + 'input[type="number"]' + )?.focus(); + } + if (e.key === "Escape") { + const anyOpen = !!(this.placementMode || this.annotationsOpen || this.shapesOpen || this.xMenuOpen || this.yMenuOpen || this.refFrameMenuOpen || this.settingsOpen || this.downloadOpen || this.editorOpen || this.profilesOpen || this.vsMenuOpen || this.labOpen || Alpine.store("dojo").overlayCount > 0 || isTextInput); + if (isTextInput) targetEl.blur(); + this.placementMode = null; + this.rectStart = null; + this.cancelAnnDraft(); + this.cancelShapeDraft(); + this.annotationsOpen = false; + this.shapesOpen = false; + this.xMenuOpen = this.yMenuOpen = this.refFrameMenuOpen = false; + this.settingsOpen = this.downloadOpen = this.editorOpen = false; + this.profilesOpen = this.vsMenuOpen = false; + this.profileSearch = ""; + this.labOpen = false; + window.dispatchEvent(new CustomEvent("mojo:escape")); + if (anyOpen) e.stopImmediatePropagation(); + } + if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "s") { + e.preventDefault(); + if (!isTextInput) { + if (this.labOpen) { + const el = document.getElementById( + "lab-name-input" + ); + if (el) { + el.focus(); + el.setSelectionRange(el.value.length, el.value.length); + } + } else { + this.profilesOpen = true; + void this.loadProfiles(); + void this.$nextTick(() => { + const el = document.getElementById( + "profile-name-input" + ); + if (el) { + el.focus(); + el.setSelectionRange(el.value.length, el.value.length); + } + }); + } + } + } + if ((e.metaKey || e.ctrlKey) && !isTextInput) { + if (e.key === "ArrowLeft") { + e.preventDefault(); + document.getElementById("nav-prev")?.click(); + } else if (e.key === "ArrowRight") { + e.preventDefault(); + document.getElementById("nav-next")?.click(); + } + } + if (isTextInput) return; + const isZ = e.key.toLowerCase() === "z"; + const isY = e.key.toLowerCase() === "y"; + const cmdOrCtrl = e.metaKey || e.ctrlKey; + if (cmdOrCtrl && isZ) { + e.preventDefault(); + if (this.labOpen) { + e.shiftKey ? window.mojoLabRedo?.() : window.mojoLabUndo?.(); + } else { + if (e.shiftKey) this.redo(); + else this.undo(); + } + } + if (cmdOrCtrl && isY) { + e.preventDefault(); + if (this.labOpen) window.mojoLabRedo?.(); + else this.redo(); + } + if (this.labOpen && cmdOrCtrl && e.shiftKey) { + if (e.key.toLowerCase() === "a") { + e.preventDefault(); + window.mojoLabArrange?.(); + } else if (e.key.toLowerCase() === "f") { + e.preventDefault(); + window.mojoLabFitView?.(); + } + } + }, + { capture: true } + ); const resp = await fetch("/mosaic/api/trials"); const data = await resp.json(); this.allTrials = data.trials ?? []; @@ -749,39 +834,23 @@ this.$watch("vsDraft.range", () => { if (this.discoveryTimeout) clearTimeout(this.discoveryTimeout); this.discoveryTimeout = setTimeout(() => { - if (this.vsDraft.enabled) { - console.debug( - "Predictive Sync: User adjusted range, starting hydration..." - ); - void this.startBackgroundDiscovery(); - } + if (this.vsDraft.enabled) void this.startBackgroundDiscovery(); }, 500); }); - this.$watch( - "config.refFrame", - async (newValue, oldValue) => { - console.debug( - `[Mojo] Frame Change: ${oldValue ?? "world"} -> ${newValue ?? "world"}` - ); - this.notify(`Frame: ${newValue || "world"}`, "info"); - this.discoveryId++; - this.data = {}; - this.vsDatasets = {}; - const initialCols = [ - this.config.xAxis.col, - ...Object.keys(this.config.yAxes) - ]; - const response = await this.fetchTrialData(this.trialId, initialCols); - this.columns = response.columns.all.sort(); - this.rotateableVectors = response.columns.rotatable_vectors ?? []; - this.data = response.data; - void this.startBackgroundDiscovery(); - if (this.config.vsEnabled) await this.syncVsRange(); - this.saveAndRender(); - } - ); + this.$watch("config.refFrame", (newValue, oldValue) => { + if (newValue === oldValue) return; + this.notify(`Frame: ${newValue || "world"}`, "info"); + this.discoveryId++; + this.applyRefFrame(newValue); + }); this.$watch("config", async (value, oldValue) => { - if (!this.isEditingRaw) this.configRaw = JSON.stringify(value, null, 4); + if (!this.isEditingRaw) { + this.configRaw = JSON.stringify(value, null, 4); + try { + localStorage.removeItem("mojo:config:raw-draft"); + } catch { + } + } if (this.config.vsEnabled && oldValue?.vsEnabled && (value.xAxis.col !== oldValue?.xAxis?.col || Object.keys(value.yAxes).length !== Object.keys(oldValue.yAxes ?? {}).length)) { await this.syncVsRange(); } @@ -823,7 +892,8 @@ this.saveAndRender(); }); void this.startBackgroundDiscovery(); - this.configRaw = JSON.stringify(this.config, null, 4); + this.configRaw = localStorage.getItem("mojo:config:raw-draft") ?? JSON.stringify(this.config, null, 4); + this.updateFromRaw(); }, // ----------------------------------------------------------------------- // VS (comparison) mode @@ -845,7 +915,10 @@ try { const start = Math.min(this.vsDraft.range[0], this.vsDraft.range[1]); const end = Math.max(this.vsDraft.range[0], this.vsDraft.range[1]); - let activeCols = [this.config.xAxis.col, ...Object.keys(this.config.yAxes)]; + let activeCols = [ + this.config.xAxis.col, + ...Object.keys(this.config.yAxes) + ]; if (this.config.refFrame) { const families = /* @__PURE__ */ new Set(); Object.keys(this.config.yAxes).forEach((col) => { @@ -899,9 +972,39 @@ handleVsToggle() { if (!this.vsDraft.enabled) { this.config.vsEnabled = false; + this.vsDatasets = {}; this.renderPlot(); } }, + setVsPreset(delta) { + const cur = parseInt(this.trialId.split("_").pop() ?? "0"); + this.vsDraft.range = [cur - delta, cur + delta]; + }, + setVsAll() { + const nums = this.allTrials.map((t) => parseInt(t.split("_").pop() ?? "")).filter((n) => !isNaN(n)); + if (!nums.length) return; + this.vsDraft.range = [Math.min(...nums), Math.max(...nums)]; + }, + isVsPreset(delta) { + const cur = parseInt(this.trialId.split("_").pop() ?? "0"); + const [a, b] = this.vsDraft.range; + return Math.min(a, b) === cur - delta && Math.max(a, b) === cur + delta; + }, + isVsAll() { + const nums = this.allTrials.map((t) => parseInt(t.split("_").pop() ?? "")).filter((n) => !isNaN(n)); + if (!nums.length) return false; + const [a, b] = this.vsDraft.range; + return Math.min(a, b) === Math.min(...nums) && Math.max(a, b) === Math.max(...nums); + }, + vsInRangeCount() { + const lo = Math.min(this.vsDraft.range[0], this.vsDraft.range[1]); + const hi = Math.max(this.vsDraft.range[0], this.vsDraft.range[1]); + const cur = parseInt(this.trialId.split("_").pop() ?? ""); + return this.allTrials.filter((id) => { + const n = parseInt(id.split("_").pop() ?? ""); + return n >= lo && n <= hi && n !== cur; + }).length; + }, // ----------------------------------------------------------------------- // Column filtering & search // ----------------------------------------------------------------------- @@ -916,7 +1019,7 @@ }, getFilteredCols(field) { if (!this.columns || !Array.isArray(this.columns)) return []; - const base = field === "x" ? this.columns : this.selectableYColumns; + const base = field === "x" || field === "nodeCol" ? this.columns : this.selectableYColumns; const search = this[field + "Search"] ?? ""; if (!search) return this.smartSort([...base]); try { @@ -962,7 +1065,7 @@ self2[key] = (pathPart ?? "") + (suffixPart ? ":" + suffixPart : ""); }, getSegmentsAtDepth(field, depth) { - const base = field === "x" ? this.columns : this.selectableYColumns; + const base = field === "x" || field === "nodeCol" ? this.columns : this.selectableYColumns; const search = this[field + "Search"] ?? ""; const pathSearch = search.split(":")[0] ?? ""; const parts = pathSearch.split("/").filter((p) => p !== ""); @@ -977,7 +1080,7 @@ return this.smartSort([.../* @__PURE__ */ new Set([...selected, ...segments])]); }, getAvailableSuffixes(field) { - const base = field === "x" ? this.columns : this.selectableYColumns; + const base = field === "x" || field === "nodeCol" ? this.columns : this.selectableYColumns; const search = this[field + "Search"] ?? ""; const [pathPart = "", suffixPart = ""] = search.split(":"); const selected = (suffixPart ?? "").replace(/[()]/g, "").split("|").filter(Boolean).map((s) => ":" + s); @@ -1037,20 +1140,42 @@ }, validateConfig(cfg) { const errors = []; - if (cfg.xAxis?.col && !this.columns.includes(cfg.xAxis.col)) - errors.push(`X-Axis "${cfg.xAxis.col}" not found in telemetry.`); + const labsNoted = /* @__PURE__ */ new Set(); + const schemasLoaded = this.labSchemas.length > 0; + const checkCol = (col, label) => { + if (col.startsWith("Lab/")) { + if (!schemasLoaded) return; + const labName = col.slice(4).split("/")[0]; + if (labsNoted.has(labName)) return; + const lab = this.labSchemas.find((l) => l.name === labName); + if (!lab) { + labsNoted.add(labName); + errors.push(`Lab "${labName}" not found.`); + } else if (lab.missing.length > 0) { + labsNoted.add(labName); + errors.push( + `Lab "${labName}" requires: ${lab.signal_in_columns.join(", ")}; missing: ${lab.missing.join(", ")}.` + ); + } + } else if (!this.columns.includes(col)) { + errors.push(`${label} "${col}" not found in telemetry.`); + } + }; + if (cfg.xAxis?.col) checkCol(cfg.xAxis.col, "X-Axis"); if (typeof cfg.yAxes !== "object" || Array.isArray(cfg.yAxes)) { errors.push("yAxes must be a hashmap."); } else { - Object.keys(cfg.yAxes).forEach((y) => { - if (!this.columns.includes(y)) errors.push(`Y-Axis "${y}" missing.`); - }); + Object.keys(cfg.yAxes).forEach((y) => checkCol(y, "Y-Axis")); } if (cfg.vsRange && cfg.vsRange[0] > cfg.vsRange[1]) errors.push("Comparison range start cannot be greater than end."); return errors; }, updateFromRaw() { + try { + localStorage.setItem("mojo:config:raw-draft", this.configRaw); + } catch { + } try { const parsed = JSON.parse(this.configRaw); this.isValidJson = true; @@ -1058,8 +1183,13 @@ this.configErrors = this.validateConfig(parsed); this.isValidConfig = this.configErrors.length === 0; if (this.isValidConfig) { + const prevRefFrame = this.config.refFrame ?? null; this.isEditingRaw = true; this.config = { ...this.config, ...parsed }; + const nextRefFrame = this.config.refFrame ?? null; + if (nextRefFrame !== prevRefFrame) { + this.applyRefFrame(nextRefFrame); + } void this.$nextTick(() => { this.isEditingRaw = false; }); @@ -1141,6 +1271,163 @@ copyRawConfig() { void this.copyToClipboard(this.configRaw, "JSON Config copied!"); }, + initCodeMirror(hostEl) { + if (!hostEl || typeof CM === "undefined" || _cm.editor) return; + const { + EditorView, + basicSetup, + json, + jsonParseLinter, + oneDarkHighlightStyle, + EditorState, + Compartment, + linter, + lintGutter, + syntaxHighlighting, + defaultHighlightStyle + } = CM; + const self2 = this; + const savedH = localStorage.getItem("mojo:json-editor:height"); + if (savedH) hostEl.style.height = savedH; + const darkTheme = EditorView.theme({ + "&": { backgroundColor: "#020617", color: "#cbd5e1", height: "100%" }, + ".cm-scroller": { overflow: "auto", fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace", fontSize: "0.875rem", lineHeight: "1.625" }, + ".cm-content": { padding: "1rem", caretColor: "#06b6d4" }, + ".cm-cursor": { borderLeftColor: "#06b6d4" }, + ".cm-gutters": { backgroundColor: "#0f172a", color: "#475569", borderRight: "1px solid #1e293b" }, + ".cm-activeLineGutter": { backgroundColor: "rgba(15,23,42,0.6)" }, + ".cm-activeLine": { backgroundColor: "rgba(15,23,42,0.4)" }, + ".cm-selectionBackground": { backgroundColor: "#1e293b !important" }, + "&.cm-focused .cm-selectionBackground": { backgroundColor: "#1e293b !important" }, + ".cm-matchingBracket": { color: "#22d3ee", fontWeight: "bold" }, + ".cm-tooltip": { backgroundColor: "#1e293b", border: "1px solid #334155", color: "#cbd5e1" }, + ".cm-panels": { backgroundColor: "#0f172a", borderColor: "#1e293b", color: "#cbd5e1" }, + ".cm-searchMatch": { backgroundColor: "rgba(34,211,238,0.18)" }, + ".cm-searchMatch.cm-searchMatch-selected": { backgroundColor: "rgba(34,211,238,0.35)" }, + ".cm-lintRange-error": { backgroundImage: "none", textDecoration: "underline wavy #ef4444 1.5px", textUnderlineOffset: "3px" }, + ".cm-lintRange-warning": { backgroundImage: "none", textDecoration: "underline wavy #f59e0b 1.5px", textUnderlineOffset: "3px" }, + ".cm-diagnostic-error": { borderLeft: "3px solid #ef4444" } + }, { dark: true }); + const lightTheme = EditorView.theme({ + "&": { backgroundColor: "#ffffff", color: "#0f172a", height: "100%" }, + ".cm-scroller": { overflow: "auto", fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace", fontSize: "0.875rem", lineHeight: "1.625" }, + ".cm-content": { padding: "1rem", caretColor: "#0891b2" }, + ".cm-cursor": { borderLeftColor: "#0891b2" }, + ".cm-gutters": { backgroundColor: "#f8fafc", color: "#94a3b8", borderRight: "1px solid #e2e8f0" }, + ".cm-activeLineGutter": { backgroundColor: "rgba(241,245,249,0.6)" }, + ".cm-activeLine": { backgroundColor: "rgba(241,245,249,0.5)" }, + ".cm-selectionBackground": { backgroundColor: "#e2e8f0 !important" }, + "&.cm-focused .cm-selectionBackground": { backgroundColor: "#e2e8f0 !important" }, + ".cm-matchingBracket": { color: "#0891b2", fontWeight: "bold" }, + ".cm-tooltip": { backgroundColor: "#f8fafc", border: "1px solid #e2e8f0", color: "#0f172a" }, + ".cm-panels": { backgroundColor: "#f8fafc", borderColor: "#e2e8f0" }, + ".cm-searchMatch": { backgroundColor: "rgba(8,145,178,0.15)" }, + ".cm-searchMatch.cm-searchMatch-selected": { backgroundColor: "rgba(8,145,178,0.3)" }, + ".cm-lintRange-error": { backgroundImage: "none", textDecoration: "underline wavy #ef4444 1.5px", textUnderlineOffset: "3px" }, + ".cm-lintRange-warning": { backgroundImage: "none", textDecoration: "underline wavy #f59e0b 1.5px", textUnderlineOffset: "3px" }, + ".cm-diagnostic-error": { borderLeft: "3px solid #ef4444" } + }, { dark: false }); + const isDark = () => document.documentElement.classList.contains("dark"); + const themeComp = new Compartment(); + const highlightComp = new Compartment(); + const makeTheme = (dark) => dark ? darkTheme : lightTheme; + const makeHighlight = (dark) => syntaxHighlighting(dark ? oneDarkHighlightStyle : defaultHighlightStyle); + const startState = EditorState.create({ + doc: this.configRaw, + extensions: [ + basicSetup, + json(), + lintGutter(), + linter(jsonParseLinter()), + themeComp.of(makeTheme(isDark())), + highlightComp.of(makeHighlight(isDark())), + EditorView.updateListener.of((update) => { + if (update.docChanged && !_cm.updating) { + const text = update.state.doc.toString(); + _cm.updating = true; + self2.configRaw = text; + if (_cm.debounce !== null) clearTimeout(_cm.debounce); + _cm.debounce = setTimeout(() => { + self2.updateFromRaw(); + _cm.debounce = null; + }, 500); + _cm.updating = false; + } + }) + ] + }); + _cm.editor = new EditorView({ state: startState, parent: hostEl }); + const handle = document.createElement("div"); + handle.style.cssText = "height:14px;cursor:ns-resize;display:flex;align-items:center;justify-content:center;flex-shrink:0;"; + const grip = document.createElement("div"); + grip.style.cssText = "width:36px;height:4px;border-radius:2px;background:#334155;transition:background 150ms,width 150ms;pointer-events:none;"; + handle.appendChild(grip); + handle.addEventListener("mouseenter", () => { + grip.style.background = "#06b6d4"; + grip.style.width = "52px"; + }); + handle.addEventListener("mouseleave", () => { + grip.style.background = "#334155"; + grip.style.width = "36px"; + }); + hostEl.insertAdjacentElement("afterend", handle); + handle.addEventListener("mousedown", (e) => { + const startY = e.clientY; + const startH = hostEl.offsetHeight; + let prevY = startY; + document.body.style.userSelect = "none"; + document.body.style.cursor = "ns-resize"; + const onMove = (ev) => { + const dy = ev.clientY - prevY; + prevY = ev.clientY; + const newH = Math.max(128, startH + (ev.clientY - startY)); + hostEl.style.height = newH + "px"; + if (dy > 0) window.scrollBy(0, dy); + }; + const onUp = () => { + document.body.style.userSelect = ""; + document.body.style.cursor = ""; + document.removeEventListener("mousemove", onMove); + document.removeEventListener("mouseup", onUp); + try { + localStorage.setItem("mojo:json-editor:height", hostEl.style.height); + } catch { + } + }; + document.addEventListener("mousemove", onMove); + document.addEventListener("mouseup", onUp); + e.preventDefault(); + }); + handle.addEventListener("dblclick", () => { + const scroller = hostEl.querySelector(".cm-scroller"); + if (scroller) { + hostEl.style.height = scroller.scrollHeight + "px"; + try { + localStorage.setItem("mojo:json-editor:height", hostEl.style.height); + } catch { + } + } + }); + new MutationObserver(() => { + const dark = isDark(); + _cm.editor?.dispatch({ + effects: [ + themeComp.reconfigure(makeTheme(dark)), + highlightComp.reconfigure(makeHighlight(dark)) + ] + }); + }).observe(document.documentElement, { attributes: true, attributeFilter: ["class"] }); + this.$watch("configRaw", (val) => { + if (!_cm.updating && _cm.editor) { + const current = _cm.editor.state.doc.toString(); + if (current !== val) { + _cm.updating = true; + _cm.editor.dispatch({ changes: { from: 0, to: current.length, insert: val } }); + _cm.updating = false; + } + } + }); + }, resetConfig() { if (confirm( "Reset plot to factory defaults? This will clear your current view." @@ -1225,7 +1512,10 @@ }, downloadCSV() { if (!this.data || Object.keys(this.config.yAxes).length === 0) return; - const activeCols = [this.config.xAxis.col, ...Object.keys(this.config.yAxes)]; + const activeCols = [ + this.config.xAxis.col, + ...Object.keys(this.config.yAxes) + ]; const rowCount = this.data[this.config.xAxis.col]?.length ?? 0; let csv = activeCols.join(",") + "\n"; for (let i = 0; i < rowCount; i++) { @@ -1286,12 +1576,13 @@ this.config.yAxes = rest; } else { const nextIndex = Object.keys(this.config.yAxes).length; + const initFilters = this.config.refFrame ? [{ type: "rotation", quat_col: this.config.refFrame, invert: true, enabled: true }] : []; this.config.yAxes[col] = { color: this.getSignalColor(nextIndex), label: "", width: 3, opacity: 1, - filters: [], + filters: initFilters, dash: "solid", marker: "none" }; @@ -1305,6 +1596,38 @@ this.configRaw = JSON.stringify(this.config, null, 4); this.notify("Signals Cleared", "info"); }, + applyRefFrame(frame) { + for (const col of Object.keys(this.config.yAxes)) { + const yConfig = this.config.yAxes[col]; + if (!yConfig) continue; + if (frame) { + const newEntry = { + type: "rotation", + quat_col: frame, + invert: true, + enabled: true + }; + const idx = yConfig.filters.findIndex((f) => f.type === "rotation"); + if (idx >= 0) { + yConfig.filters = [ + ...yConfig.filters.slice(0, idx), + newEntry, + ...yConfig.filters.slice(idx + 1) + ]; + } else { + yConfig.filters = [newEntry, ...yConfig.filters]; + } + } else { + const idx = yConfig.filters.findIndex((f) => f.type === "rotation"); + if (idx >= 0) { + yConfig.filters = [ + ...yConfig.filters.slice(0, idx), + ...yConfig.filters.slice(idx + 1) + ]; + } + } + } + }, warpToTrial() { if (this.warpId === null || this.warpId === void 0 || this.warpId === "") return; @@ -1332,6 +1655,15 @@ getFilterSchema(filterType) { return this.filterSchemas.find((s) => s.type === filterType); }, + get groupedFilterSchemas() { + const ORDER = ["Smoothing", "Arithmetic", "Trigonometry", "Calculus", "Comparison", "Bounding", "Misc"]; + const groups = {}; + for (const s of this.filterSchemas) { + const cat = s.category ?? "Misc"; + (groups[cat] ?? (groups[cat] = [])).push(s); + } + return ORDER.filter((c) => groups[c]?.length).map((c) => ({ category: c, schemas: groups[c] })); + }, evalMathExpr(expr) { const s = String(expr ?? "").trim(); if (!s) return null; @@ -1419,6 +1751,8 @@ const schema = this.filterSchemas.find((s) => s.type === filterType); if (!schema) return; if (!temp.filters) temp.filters = []; + if (filterType === "rotation" && temp.filters.some((f) => f.type === "rotation")) + return; const entry = { type: filterType, enabled: true }; for (const p of schema.params) { entry[p.name] = p.default; @@ -1454,6 +1788,116 @@ _profileUrl(name) { return `/mosaic/api/profiles/${name.split("/").map(encodeURIComponent).join("/")}`; }, + // ── Lab ────────────────────────────────────────────────────────────────── + relTime(ms) { + const diff = Date.now() - ms; + const min = Math.floor(diff / 6e4); + if (min < 1) return "just now"; + if (min < 60) return `${min}m ago`; + const h = Math.floor(min / 60); + if (h < 24) return `${h}h ago`; + const d = Math.floor(h / 24); + return d === 1 ? "yesterday" : `${d}d ago`; + }, + async loadLabSchemas() { + try { + const resp = await fetch("/mosaic/api/lab"); + if (!resp.ok) return; + const all = await resp.json(); + const schemas = all.map((lab) => ({ + ...lab, + signal_in_columns: [...new Set(lab.signal_in_columns)].sort(), + outputs: [...new Set(lab.outputs)].sort() + })); + const baseColumns = this.columns.filter((c) => !c.startsWith("Lab/")); + const available = new Set(baseColumns); + const validLabs = /* @__PURE__ */ new Set(); + let changed = true; + while (changed) { + changed = false; + for (const lab of schemas) { + if (validLabs.has(lab.name)) continue; + if (lab.signal_in_columns.every((c) => available.has(c))) { + validLabs.add(lab.name); + lab.outputs.forEach((o) => available.add(`Lab/${lab.name}/${o}`)); + changed = true; + } + } + } + this.labSchemas = schemas.map((lab) => ({ + ...lab, + missing: lab.signal_in_columns.filter((c) => !available.has(c)), + valid: validLabs.has(lab.name) + })); + this.columns = [...available].sort(); + } catch { + } + }, + async refreshLabValidation() { + await this.loadLabSchemas(); + void this.loadProfiles(); + }, + async saveLabGraph(name, graph) { + const trimmed = name.trim(); + if (!trimmed) return; + const exists = this.labSchemas.some((s) => s.name === trimmed); + if (exists && !confirm(`Overwrite "${trimmed}"?`)) return; + const safePath = trimmed.split("/").map(encodeURIComponent).join("/"); + try { + const resp = await fetch(`/mosaic/api/lab/${safePath}`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(graph) + }); + if (!resp.ok) { + const detail = await resp.text().catch(() => resp.statusText); + this.notify(`Save failed: ${detail}`, "error"); + return; + } + localStorage.setItem("mojo:lab:name", trimmed); + this.notify(`Lab "${trimmed}" saved`, "success"); + await this.refreshLabValidation(); + const labPrefix = `Lab/${trimmed}/`; + const staleCols = Object.keys(this.data ?? {}).filter( + (c) => c.startsWith(labPrefix) + ); + if (staleCols.length > 0) { + const fresh = { ...this.data ?? {} }; + staleCols.forEach((c) => delete fresh[c]); + this.data = fresh; + const activeCols = staleCols.filter( + (c) => c in this.config.yAxes || c === this.config.xAxis?.col + ); + if (activeCols.length > 0) { + try { + const refetch = await this.fetchTrialData(this.trialId, activeCols); + this.data = { ...this.data ?? {}, ...refetch.data }; + this.saveAndRender(); + } catch { + } + } + } + } catch (err) { + this.notify(`Save failed: ${String(err)}`, "error"); + } + }, + selectNodeColumn(col) { + if (this.nodePickingColumn !== null) { + if (typeof window.mojoLabSelectNodeColumn === "function") { + window.mojoLabSelectNodeColumn(this.nodePickingColumn, col); + } + } + this.nodePickingColumn = null; + this.nodeColSearch = ""; + }, + async deleteLabGraph(name) { + const safePath = name.split("/").map(encodeURIComponent).join("/"); + await fetch(`/mosaic/api/lab/${safePath}`, { + method: "DELETE" + }); + this.notify(`Lab "${name}" deleted`, "info"); + await this.refreshLabValidation(); + }, // ----------------------------------------------------------------------- async loadProfiles() { try { @@ -1541,6 +1985,22 @@ } this.config = { ...this.config, ...loaded }; this.notify(`Profile "${name}" loaded`, "success"); + const needed = []; + if (loaded.xAxis?.col && !this.data?.[loaded.xAxis.col]) + needed.push(loaded.xAxis.col); + for (const col of Object.keys(loaded.yAxes ?? {})) { + if (!this.data?.[col]) needed.push(col); + } + if (needed.length > 0) { + const fetched = await this.fetchTrialData(this.trialId, needed); + this.data = { ...this.data ?? {}, ...fetched.data }; + } + void this.$nextTick(() => { + this.configErrors = this.validateConfig(this.config); + this.isValidConfig = this.configErrors.length === 0; + this.isValidJson = true; + this.saveAndRender(); + }); } catch (e) { this.notify( `Failed to load "${name}": ${e.message}`, diff --git a/src/mujoco_mojo/utils/layers/dojo/templates/static/ts/build.mjs b/src/mujoco_mojo/utils/layers/dojo/templates/static/ts/build.mjs index 493fa5be..6d2765b8 100644 --- a/src/mujoco_mojo/utils/layers/dojo/templates/static/ts/build.mjs +++ b/src/mujoco_mojo/utils/layers/dojo/templates/static/ts/build.mjs @@ -13,11 +13,24 @@ const entries = [ { in: 'trial-viewer.ts', out: 'trial-viewer.js' }, ]; +const vendorDir = join(__dirname, '..', 'vendored'); + const isWatch = process.argv.includes('--watch'); +const cmBundleOptions = { + entryPoints: [join(srcDir, 'cm-bundle.ts')], + outfile: join(vendorDir, 'codemirror.bundle.js'), + bundle: true, + minify: true, + target: 'es2020', + format: /** @type {'iife'} */ ('iife'), + globalName: 'CM', + platform: 'browser', +}; + if (isWatch) { - const contexts = await Promise.all( - entries.map(({ in: inFile, out: outFile }) => + const contexts = await Promise.all([ + ...entries.map(({ in: inFile, out: outFile }) => esbuild.context({ entryPoints: [join(srcDir, inFile)], outfile: join(outDir, outFile), @@ -28,12 +41,13 @@ if (isWatch) { platform: 'browser', }), ), - ); + esbuild.context(cmBundleOptions), + ]); await Promise.all(contexts.map((ctx) => ctx.watch())); console.log('Watching for changes...'); } else { - await Promise.all( - entries.map(async ({ in: inFile, out: outFile }) => { + await Promise.all([ + ...entries.map(async ({ in: inFile, out: outFile }) => { await esbuild.build({ entryPoints: [join(srcDir, inFile)], outfile: join(outDir, outFile), @@ -45,5 +59,8 @@ if (isWatch) { }); console.log(`✓ src/${inFile} → js/${outFile}`); }), - ); + esbuild.build(cmBundleOptions).then(() => { + console.log('✓ src/cm-bundle.ts → vendored/codemirror.bundle.js'); + }), + ]); } diff --git a/src/mujoco_mojo/utils/layers/dojo/templates/static/ts/package-lock.json b/src/mujoco_mojo/utils/layers/dojo/templates/static/ts/package-lock.json index f3c26246..32ec744a 100644 --- a/src/mujoco_mojo/utils/layers/dojo/templates/static/ts/package-lock.json +++ b/src/mujoco_mojo/utils/layers/dojo/templates/static/ts/package-lock.json @@ -5,6 +5,11 @@ "packages": { "": { "name": "dojo-static", + "dependencies": { + "@codemirror/lang-json": "^6.0.2", + "@codemirror/theme-one-dark": "^6.1.3", + "codemirror": "^6.0.2" + }, "devDependencies": { "@types/plotly.js": "^2.35.0", "alpinejs": "^3.14.0", @@ -12,6 +17,109 @@ "typescript": "^5.8.0" } }, + "node_modules/@codemirror/autocomplete": { + "version": "6.20.2", + "resolved": "https://registry.npmjs.org/@codemirror/autocomplete/-/autocomplete-6.20.2.tgz", + "integrity": "sha512-G5FPkgIiLjOgZMjqVjvuKQ1rGPtHogLldJr33eFJdVLtmwY+giGrlv/ewljLz6b9BSQLkjxuwBc6g6omDM+YxQ==", + "license": "MIT", + "dependencies": { + "@codemirror/language": "^6.0.0", + "@codemirror/state": "^6.0.0", + "@codemirror/view": "^6.17.0", + "@lezer/common": "^1.0.0" + } + }, + "node_modules/@codemirror/commands": { + "version": "6.10.3", + "resolved": "https://registry.npmjs.org/@codemirror/commands/-/commands-6.10.3.tgz", + "integrity": "sha512-JFRiqhKu+bvSkDLI+rUhJwSxQxYb759W5GBezE8Uc8mHLqC9aV/9aTC7yJSqCtB3F00pylrLCwnyS91Ap5ej4Q==", + "license": "MIT", + "dependencies": { + "@codemirror/language": "^6.0.0", + "@codemirror/state": "^6.6.0", + "@codemirror/view": "^6.27.0", + "@lezer/common": "^1.1.0" + } + }, + "node_modules/@codemirror/lang-json": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/@codemirror/lang-json/-/lang-json-6.0.2.tgz", + "integrity": "sha512-x2OtO+AvwEHrEwR0FyyPtfDUiloG3rnVTSZV1W8UteaLL8/MajQd8DpvUb2YVzC+/T18aSDv0H9mu+xw0EStoQ==", + "license": "MIT", + "dependencies": { + "@codemirror/language": "^6.0.0", + "@lezer/json": "^1.0.0" + } + }, + "node_modules/@codemirror/language": { + "version": "6.12.3", + "resolved": "https://registry.npmjs.org/@codemirror/language/-/language-6.12.3.tgz", + "integrity": "sha512-QwCZW6Tt1siP37Jet9Tb02Zs81TQt6qQrZR2H+eGMcFsL1zMrk2/b9CLC7/9ieP1fjIUMgviLWMmgiHoJrj+ZA==", + "license": "MIT", + "dependencies": { + "@codemirror/state": "^6.0.0", + "@codemirror/view": "^6.23.0", + "@lezer/common": "^1.5.0", + "@lezer/highlight": "^1.0.0", + "@lezer/lr": "^1.0.0", + "style-mod": "^4.0.0" + } + }, + "node_modules/@codemirror/lint": { + "version": "6.9.6", + "resolved": "https://registry.npmjs.org/@codemirror/lint/-/lint-6.9.6.tgz", + "integrity": "sha512-6Kp7r6XfCi/D/5sdXieMfg9pJU1bUEx96WITuLU6ESaKizCz0QHFMjY/TaFSbigDdEAIgi93itLBIUETP4oK+A==", + "license": "MIT", + "dependencies": { + "@codemirror/state": "^6.0.0", + "@codemirror/view": "^6.42.0", + "crelt": "^1.0.5" + } + }, + "node_modules/@codemirror/search": { + "version": "6.7.0", + "resolved": "https://registry.npmjs.org/@codemirror/search/-/search-6.7.0.tgz", + "integrity": "sha512-ZvGm99wc/s2cITtMT15LFdn8aH/aS+V+DqyGq/N5ZlV5vWtH+nILvC2nw0zX7ByNoHHDZ2IxxdW38O0tc5nVHg==", + "license": "MIT", + "dependencies": { + "@codemirror/state": "^6.0.0", + "@codemirror/view": "^6.37.0", + "crelt": "^1.0.5" + } + }, + "node_modules/@codemirror/state": { + "version": "6.6.0", + "resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.6.0.tgz", + "integrity": "sha512-4nbvra5R5EtiCzr9BTHiTLc+MLXK2QGiAVYMyi8PkQd3SR+6ixar/Q/01Fa21TBIDOZXgeWV4WppsQolSreAPQ==", + "license": "MIT", + "dependencies": { + "@marijn/find-cluster-break": "^1.0.0" + } + }, + "node_modules/@codemirror/theme-one-dark": { + "version": "6.1.3", + "resolved": "https://registry.npmjs.org/@codemirror/theme-one-dark/-/theme-one-dark-6.1.3.tgz", + "integrity": "sha512-NzBdIvEJmx6fjeremiGp3t/okrLPYT0d9orIc7AFun8oZcRk58aejkqhv6spnz4MLAevrKNPMQYXEWMg4s+sKA==", + "license": "MIT", + "dependencies": { + "@codemirror/language": "^6.0.0", + "@codemirror/state": "^6.0.0", + "@codemirror/view": "^6.0.0", + "@lezer/highlight": "^1.0.0" + } + }, + "node_modules/@codemirror/view": { + "version": "6.43.0", + "resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.43.0.tgz", + "integrity": "sha512-V7ZCLQO3Jus9hzh2jVCCPW3mO4IBMr43O37PqSUYautJSnnJF41YlgLw21x0fLJTYvJ+Vkm6Gp+qKGH9pltgXA==", + "license": "MIT", + "dependencies": { + "@codemirror/state": "^6.6.0", + "crelt": "^1.0.6", + "style-mod": "^4.1.0", + "w3c-keyname": "^2.2.4" + } + }, "node_modules/@esbuild/aix-ppc64": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", @@ -454,6 +562,47 @@ "node": ">=18" } }, + "node_modules/@lezer/common": { + "version": "1.5.2", + "resolved": "https://registry.npmjs.org/@lezer/common/-/common-1.5.2.tgz", + "integrity": "sha512-sxQE460fPZyU3sdc8lafxiPwJHBzZRy/udNFynGQky1SePYBdhkBl1kOagA9uT3pxR8K09bOrmTUqA9wb/PjSQ==", + "license": "MIT" + }, + "node_modules/@lezer/highlight": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@lezer/highlight/-/highlight-1.2.3.tgz", + "integrity": "sha512-qXdH7UqTvGfdVBINrgKhDsVTJTxactNNxLk7+UMwZhU13lMHaOBlJe9Vqp907ya56Y3+ed2tlqzys7jDkTmW0g==", + "license": "MIT", + "dependencies": { + "@lezer/common": "^1.3.0" + } + }, + "node_modules/@lezer/json": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@lezer/json/-/json-1.0.3.tgz", + "integrity": "sha512-BP9KzdF9Y35PDpv04r0VeSTKDeox5vVr3efE7eBbx3r4s3oNLfunchejZhjArmeieBH+nVOpgIiBJpEAv8ilqQ==", + "license": "MIT", + "dependencies": { + "@lezer/common": "^1.2.0", + "@lezer/highlight": "^1.0.0", + "@lezer/lr": "^1.0.0" + } + }, + "node_modules/@lezer/lr": { + "version": "1.4.10", + "resolved": "https://registry.npmjs.org/@lezer/lr/-/lr-1.4.10.tgz", + "integrity": "sha512-rnCpTIBafOx4mRp43xOxDJbFipJm/c0cia/V5TiGlhmMa+wsSdoGmUN3w5Bqrks/09Q/D4tNAmWaT8p6NRi77A==", + "license": "MIT", + "dependencies": { + "@lezer/common": "^1.0.0" + } + }, + "node_modules/@marijn/find-cluster-break": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@marijn/find-cluster-break/-/find-cluster-break-1.0.2.tgz", + "integrity": "sha512-l0h88YhZFyKdXIFNfSWpyjStDjGHwZ/U7iobcK1cQQD8sejsONdQtTVU+1wVN1PBw40PiiHB1vA5S7VTfQiP9g==", + "license": "MIT" + }, "node_modules/@types/plotly.js": { "version": "2.35.14", "resolved": "https://registry.npmjs.org/@types/plotly.js/-/plotly.js-2.35.14.tgz", @@ -488,6 +637,27 @@ "@vue/reactivity": "~3.1.1" } }, + "node_modules/codemirror": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/codemirror/-/codemirror-6.0.2.tgz", + "integrity": "sha512-VhydHotNW5w1UGK0Qj96BwSk/Zqbp9WbnyK2W/eVMv4QyF41INRGpjUhFJY7/uDNuudSc33a/PKr4iDqRduvHw==", + "license": "MIT", + "dependencies": { + "@codemirror/autocomplete": "^6.0.0", + "@codemirror/commands": "^6.0.0", + "@codemirror/language": "^6.0.0", + "@codemirror/lint": "^6.0.0", + "@codemirror/search": "^6.0.0", + "@codemirror/state": "^6.0.0", + "@codemirror/view": "^6.0.0" + } + }, + "node_modules/crelt": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/crelt/-/crelt-1.0.6.tgz", + "integrity": "sha512-VQ2MBenTq1fWZUH9DJNGti7kKv6EeAuYr3cLwxUWhIu1baTaXh4Ib5W2CqHVqib4/MqbYGJqiL3Zb8GJZr3l4g==", + "license": "MIT" + }, "node_modules/esbuild": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", @@ -530,6 +700,12 @@ "@esbuild/win32-x64": "0.25.12" } }, + "node_modules/style-mod": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/style-mod/-/style-mod-4.1.3.tgz", + "integrity": "sha512-i/n8VsZydrugj3Iuzll8+x/00GH2vnYsk1eomD8QiRrSAeW6ItbCQDtfXCeJHd0iwiNagqjQkvpvREEPtW3IoQ==", + "license": "MIT" + }, "node_modules/typescript": { "version": "5.9.3", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", @@ -543,6 +719,12 @@ "engines": { "node": ">=14.17" } + }, + "node_modules/w3c-keyname": { + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.8.tgz", + "integrity": "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==", + "license": "MIT" } } } diff --git a/src/mujoco_mojo/utils/layers/dojo/templates/static/ts/package.json b/src/mujoco_mojo/utils/layers/dojo/templates/static/ts/package.json index 85dc6e98..22f4b21a 100644 --- a/src/mujoco_mojo/utils/layers/dojo/templates/static/ts/package.json +++ b/src/mujoco_mojo/utils/layers/dojo/templates/static/ts/package.json @@ -8,9 +8,14 @@ "typecheck": "tsc --noEmit" }, "devDependencies": { - "esbuild": "^0.25.0", - "typescript": "^5.8.0", + "@types/plotly.js": "^2.35.0", "alpinejs": "^3.14.0", - "@types/plotly.js": "^2.35.0" + "esbuild": "^0.25.0", + "typescript": "^5.8.0" + }, + "dependencies": { + "@codemirror/lang-json": "^6.0.2", + "@codemirror/theme-one-dark": "^6.1.3", + "codemirror": "^6.0.2" } } diff --git a/src/mujoco_mojo/utils/layers/dojo/templates/static/ts/src/cm-bundle.ts b/src/mujoco_mojo/utils/layers/dojo/templates/static/ts/src/cm-bundle.ts new file mode 100644 index 00000000..b7b615b9 --- /dev/null +++ b/src/mujoco_mojo/utils/layers/dojo/templates/static/ts/src/cm-bundle.ts @@ -0,0 +1,7 @@ +// CodeMirror 6 bundle — exported as window.CM +export { EditorView, basicSetup } from "codemirror"; +export { json, jsonParseLinter } from "@codemirror/lang-json"; +export { oneDarkHighlightStyle } from "@codemirror/theme-one-dark"; +export { EditorState, Compartment } from "@codemirror/state"; +export { linter, lintGutter } from "@codemirror/lint"; +export { syntaxHighlighting, defaultHighlightStyle } from "@codemirror/language"; diff --git a/src/mujoco_mojo/utils/layers/dojo/templates/static/ts/src/lib/options.ts b/src/mujoco_mojo/utils/layers/dojo/templates/static/ts/src/lib/options.ts index b4478080..d9c277d7 100644 --- a/src/mujoco_mojo/utils/layers/dojo/templates/static/ts/src/lib/options.ts +++ b/src/mujoco_mojo/utils/layers/dojo/templates/static/ts/src/lib/options.ts @@ -1,5 +1,5 @@ // --------------------------------------------------------------------------- -// Option arrays — single source of truth for every select/dropdown in the UI. +// Option arrays - single source of truth for every select/dropdown in the UI. // Each array is `as const` so element types narrow to their literal values. // // Named types (DashStyle, GridMode, …) are generated from plot_config.py @@ -69,7 +69,7 @@ export const LEGEND_POS_OPTIONS: LegendPos[] = ["bottom", "right", "hidden"]; export const SCALE_OPTIONS: ScaleType[] = ["linear", "log"]; // --------------------------------------------------------------------------- -// Label-lookup helpers — derive the display string for a current config value. +// Label-lookup helpers - derive the display string for a current config value. // --------------------------------------------------------------------------- function labelOf( diff --git a/src/mujoco_mojo/utils/layers/dojo/templates/static/ts/src/models.ts b/src/mujoco_mojo/utils/layers/dojo/templates/static/ts/src/models.ts index d25db403..724be498 100644 --- a/src/mujoco_mojo/utils/layers/dojo/templates/static/ts/src/models.ts +++ b/src/mujoco_mojo/utils/layers/dojo/templates/static/ts/src/models.ts @@ -59,8 +59,9 @@ export interface TrialDataResponse { export interface FilterParamSchema { name: string; - type: "float" | "int" | "bool" | "string"; + type: "float" | "int" | "bool" | "string" | "col" | "select"; default: number | boolean | string | null; + options?: string[]; min?: number; max?: number; exclusive_min?: number; @@ -76,11 +77,12 @@ export interface FilterSchema { type: string; label: string; description: string; + category?: string; params: FilterParamSchema[]; unit_groups?: UnitGroup[]; } -// PlotConfig and related types are generated from plot_config.py — see the +// PlotConfig and related types are generated from plot_config.py - see the // re-exports at the top of this file and lib/plot-config.generated.ts. // --------------------------------------------------------------------------- diff --git a/src/mujoco_mojo/utils/layers/dojo/templates/static/ts/src/monitor.ts b/src/mujoco_mojo/utils/layers/dojo/templates/static/ts/src/monitor.ts index 3ea19ba7..cf7ed3e4 100644 --- a/src/mujoco_mojo/utils/layers/dojo/templates/static/ts/src/monitor.ts +++ b/src/mujoco_mojo/utils/layers/dojo/templates/static/ts/src/monitor.ts @@ -1,4 +1,4 @@ -import type { DojoStore, JobStatus } from './models'; +import type { DojoStore, JobStatus } from "./models"; interface StatCard { label: string; @@ -24,7 +24,7 @@ function monitor() { success_tns: [] as string[], failure_tns: [] as string[], progress: 0, - padding_style: '02d', + padding_style: "02d", } as JobStatus, prevStatus: { n_done: 0, n_success: 0, n_failed: 0 }, stats: [] as StatCard[], @@ -32,30 +32,44 @@ function monitor() { hasCelebrated: false, async init() { - window.addEventListener('mojo-data-updated', (e) => { + window.addEventListener("mojo-data-updated", (e) => { this.handleDataUpdate((e as CustomEvent).detail); }); try { - const resp = await fetch('/monitor/api/status'); + const resp = await fetch("/monitor/api/status"); const data = (await resp.json()) as JobStatus; if (data && !data.error) { - (Alpine.store('dojo') as DojoStore).updateSync(Date.now(), data.is_complete); + (Alpine.store("dojo") as DojoStore).updateSync( + Date.now(), + data.is_complete, + ); this.handleDataUpdate(data); } } catch (e) { - console.warn('Monitor bootstrap failed.', e); + console.warn("Monitor bootstrap failed.", e); } finally { - const store = Alpine.store('dojo') as DojoStore; + const store = Alpine.store("dojo") as DojoStore; store.startGlobalSync(); - store.setPageReady(true, (this.status as JobStatus & { is_complete?: boolean }).is_complete); + store.setPageReady( + true, + (this.status as JobStatus & { is_complete?: boolean }).is_complete, + ); } }, handleDataUpdate(data: JobStatus) { const wasInit = this.hasInitialData; - const prev = { ...this.prevStatus } as { n_done: number; n_success: number; n_failed: number }; - this.prevStatus = { n_done: data.n_done, n_success: data.n_success, n_failed: data.n_failed }; + const prev = { ...this.prevStatus } as { + n_done: number; + n_success: number; + n_failed: number; + }; + this.prevStatus = { + n_done: data.n_done, + n_success: data.n_success, + n_failed: data.n_failed, + }; this.status = data; this.hasInitialData = true; this.refreshStats(); @@ -66,15 +80,20 @@ function monitor() { const newDone = data.n_done - prev.n_done; if (newDone > 0) { const newFailed = data.n_failed - prev.n_failed; - const store = Alpine.store('dojo') as DojoStore; + const store = Alpine.store("dojo") as DojoStore; if (newDone === 1) { const failed = newFailed === 1; - const trialId = failed ? data.failure_tns.at(-1) : data.success_tns.at(-1); - store.addNotification(`Trial ${trialId} ${failed ? 'failed' : 'succeeded'}`, failed ? 'error' : 'success'); + const trialId = failed + ? data.failure_tns.at(-1) + : data.success_tns.at(-1); + store.addNotification( + `Trial ${trialId} ${failed ? "failed" : "succeeded"}`, + failed ? "error" : "success", + ); } else { store.addNotification( - `${newDone} trials done — ${newDone - newFailed} ok, ${newFailed} failed`, - newFailed > 0 ? 'error' : 'success', + `${newDone} trials done - ${newDone - newFailed} ok, ${newFailed} failed`, + newFailed > 0 ? "error" : "success", ); } } @@ -86,50 +105,66 @@ function monitor() { const n_trial = this.status.n_trial || 1; const progress = ((totalDone / n_trial) * 100).toFixed(1); - document.title = `${this.status.is_complete ? '✓' : `(${progress}%)`} Monitor | MuJoCo Mojo`; + document.title = `${this.status.is_complete ? "✓" : `(${progress}%)`} Monitor | MuJoCo Mojo`; - const successPerc = totalDone > 0 ? ((this.status.n_success / totalDone) * 100).toFixed(1) : 0; - const failurePerc = totalDone > 0 ? ((this.status.n_failed / totalDone) * 100).toFixed(1) : 0; + const successPerc = + totalDone > 0 + ? ((this.status.n_success / totalDone) * 100).toFixed(1) + : 0; + const failurePerc = + totalDone > 0 + ? ((this.status.n_failed / totalDone) * 100).toFixed(1) + : 0; - const lastSuccess = this.status.success_tns.length > 0 ? this.status.success_tns.slice(-1)[0] : 'None'; - const lastFailure = this.status.failure_tns.length > 0 ? this.status.failure_tns.slice(-1)[0] : 'None'; + const lastSuccess = + this.status.success_tns.length > 0 + ? this.status.success_tns.slice(-1)[0] + : "None"; + const lastFailure = + this.status.failure_tns.length > 0 + ? this.status.failure_tns.slice(-1)[0] + : "None"; this.stats = [ { - label: 'Successes', + label: "Successes", value: `${this.status.n_success} (${successPerc}%)`, - color: 'text-emerald-500', + color: "text-emerald-500", subValue: `Last Success: Trial ${lastSuccess}`, }, { - label: 'Failures', + label: "Failures", value: `${this.status.n_failed} (${failurePerc}%)`, - color: 'text-rose-500', + color: "text-rose-500", subValue: `Last Failure: Trial ${lastFailure}`, }, { - label: 'Remaining', + label: "Remaining", value: `${this.status.n_remaining} (${(100 - Number(progress)).toFixed(1)}%)`, - color: 'text-amber-500', + color: "text-amber-500", subValue: `${this.status.throughput} trials/min (${this.status.avg_duration} per trial)`, }, { - label: 'Time Elapsed', + label: "Time Elapsed", value: this.status.elapsed, - color: 'text-slate-500', + color: "text-slate-500", subValue: `Started: ${this.status.start_time}`, }, { - label: 'Total Done', + label: "Total Done", value: `${totalDone}`, - color: 'text-cyan-500', + color: "text-cyan-500", subValue: `Target: ${n_trial} trials`, }, { - label: this.status.is_complete ? 'Finished' : 'Est. Remaining', - value: this.status.is_complete ? '00:00:00' : this.status.time_remaining, - color: 'text-slate-500', - subValue: this.status.is_complete ? 'Job Complete' : `ETA: ${this.status.end_time}`, + label: this.status.is_complete ? "Finished" : "Est. Remaining", + value: this.status.is_complete + ? "00:00:00" + : this.status.time_remaining, + color: "text-slate-500", + subValue: this.status.is_complete + ? "Job Complete" + : `ETA: ${this.status.end_time}`, }, ]; }, @@ -138,24 +173,24 @@ function monitor() { if (this.hasCelebrated) return; // Use localStorage so the notification only fires once per job across all page navigations. - // The key is the job's start_time — unique per job run. + // The key is the job's start_time - unique per job run. const celebKey = `mojo_celebrated_${this.status.start_time}`; if (localStorage.getItem(celebKey)) { - this.hasCelebrated = true; // sync in-memory flag so future calls within this session are fast + this.hasCelebrated = true; // sync in-memory flag so future calls within this session are fast return; } - localStorage.setItem(celebKey, '1'); + localStorage.setItem(celebKey, "1"); this.hasCelebrated = true; - const store = Alpine.store('dojo') as DojoStore; + const store = Alpine.store("dojo") as DojoStore; store.addNotification( - `Job complete in ${this.status.elapsed} — ${this.status.n_success} succeeded, ${this.status.n_failed} failed`, - this.status.n_failed > 0 ? 'error' : 'success', + `Job complete in ${this.status.elapsed} - ${this.status.n_success} succeeded, ${this.status.n_failed} failed`, + this.status.n_failed > 0 ? "error" : "success", ); const theme = this.getHolidayTheme(); - const chime = document.getElementById('chime') as HTMLAudioElement | null; + const chime = document.getElementById("chime") as HTMLAudioElement | null; - if (!(Alpine.store('dojo') as DojoStore).isMuted) { + if (!(Alpine.store("dojo") as DojoStore).isMuted) { if (theme.audioUrl) { const holidaySound = new Audio(theme.audioUrl); holidaySound.play().catch(() => chime?.play().catch(() => {})); @@ -174,41 +209,64 @@ function monitor() { const d = now.getDate(); if ((m === 11 && d === 31) || (m === 0 && d <= 2)) { - return { name: 'New Year', emojis: ['🎆', '✨', '🥂'], colors: ['#ffcc00', '#ffffff'] }; + return { + name: "New Year", + emojis: ["🎆", "✨", "🥂"], + colors: ["#ffcc00", "#ffffff"], + }; } if (m === 2 && d === 14) { - return { name: 'Pi Day', emojis: ['π', '🥧'], colors: ['#ff9900'] }; + return { name: "Pi Day", emojis: ["π", "🥧"], colors: ["#ff9900"] }; } if (m === 2 && d === 17) { - return { name: "St. Patrick's Day", emojis: ['🍀', '🌈'], colors: ['#22c55e', '#166534'] }; + return { + name: "St. Patrick's Day", + emojis: ["🍀", "🌈"], + colors: ["#22c55e", "#166534"], + }; } if (m === 4 && d === 4) { - return { name: 'May the 4th', emojis: ['⚔️', '🌌', '✨'], colors: ['#FFE81F', '#2dd4bf'] }; + return { + name: "May the 4th", + emojis: ["⚔️", "🌌", "✨"], + colors: ["#FFE81F", "#2dd4bf"], + }; } if ((m === 9 && d >= 25) || (m === 10 && d === 1)) { - return { name: 'Halloween', emojis: ['🎃', '👻', '🦇'], colors: ['#ff6600', '#9437ff'] }; + return { + name: "Halloween", + emojis: ["🎃", "👻", "🦇"], + colors: ["#ff6600", "#9437ff"], + }; } if (m === 11 || (m === 0 && d <= 15)) { - return { name: 'Winter Snow', emojis: ['❄️', '⛄', '🌨️'], isSnow: true }; + return { + name: "Winter Snow", + emojis: ["❄️", "⛄", "🌨️"], + isSnow: true, + }; } - return { name: 'Standard Mojo', colors: ['#06b6d4', '#3b82f6', '#22c55e'] }; + return { + name: "Standard Mojo", + colors: ["#06b6d4", "#3b82f6", "#22c55e"], + }; }, - fireConfetti(theme: HolidayTheme = { name: 'Standard Mojo' }) { - const themeName = theme.name ?? 'Standard Mojo'; + fireConfetti(theme: HolidayTheme = { name: "Standard Mojo" }) { + const themeName = theme.name ?? "Standard Mojo"; const isSpecial = !!theme.emojis; const isSnow = theme.isSnow ?? false; console.log( `%c 🎊 Mojo Celebration: ${themeName} `, - 'background: #06b6d4; color: #fff; font-weight: bold; padding: 2px 4px; border-radius: 4px;', + "background: #06b6d4; color: #fff; font-weight: bold; padding: 2px 4px; border-radius: 4px;", ); const duration = 3000; const animationEnd = Date.now() + duration; - const colors = theme.colors ?? ['#06b6d4', '#3b82f6', '#22c55e']; + const colors = theme.colors ?? ["#06b6d4", "#3b82f6", "#22c55e"]; - let shapes: unknown[] = ['circle', 'square']; + let shapes: unknown[] = ["circle", "square"]; if (theme.emojis) { shapes = theme.emojis.map((emoji) => confetti.shapeFromText({ text: emoji, scalar: 5, color: colors[0] }), @@ -224,20 +282,38 @@ function monitor() { gravity: isSnow ? 0.4 : isSpecial ? 0.4 : 1.2, }; - const interval = setInterval(() => { - const timeLeft = animationEnd - Date.now(); - if (timeLeft <= 0) { clearInterval(interval); return; } + const interval = setInterval( + () => { + const timeLeft = animationEnd - Date.now(); + if (timeLeft <= 0) { + clearInterval(interval); + return; + } - if (isSnow) { - confetti({ ...defaults, particleCount: 1, startVelocity: 0, drift: (Math.random() - 0.5) * 1.5, origin: { x: Math.random(), y: -0.2 } }); - } else { - const countMultiplier = isSpecial ? 40 : 150; - const particleCount = countMultiplier * (timeLeft / duration); - for (let i = 0; i < 3; i++) { - confetti({ ...defaults, particleCount: Math.ceil(particleCount / 3), spread: isSpecial ? 90 : 360, startVelocity: isSpecial ? 15 : 45, origin: { x: Math.random(), y: Math.random() - 0.2 } }); + if (isSnow) { + confetti({ + ...defaults, + particleCount: 1, + startVelocity: 0, + drift: (Math.random() - 0.5) * 1.5, + origin: { x: Math.random(), y: -0.2 }, + }); + } else { + const countMultiplier = isSpecial ? 40 : 150; + const particleCount = countMultiplier * (timeLeft / duration); + for (let i = 0; i < 3; i++) { + confetti({ + ...defaults, + particleCount: Math.ceil(particleCount / 3), + spread: isSpecial ? 90 : 360, + startVelocity: isSpecial ? 15 : 45, + origin: { x: Math.random(), y: Math.random() - 0.2 }, + }); + } } - } - }, isSpecial ? 400 : 250); + }, + isSpecial ? 400 : 250, + ); }, }; } diff --git a/src/mujoco_mojo/utils/layers/dojo/templates/static/ts/src/store.ts b/src/mujoco_mojo/utils/layers/dojo/templates/static/ts/src/store.ts index 4fbe0a02..e6b8d62f 100644 --- a/src/mujoco_mojo/utils/layers/dojo/templates/static/ts/src/store.ts +++ b/src/mujoco_mojo/utils/layers/dojo/templates/static/ts/src/store.ts @@ -1,23 +1,27 @@ -import { formatTimeAgo, notifTimeAgo } from './lib/format'; -import type { DojoStore, NotificationEntry } from './models'; +import { formatTimeAgo, notifTimeAgo } from "./lib/format"; +import type { DojoStore, NotificationEntry } from "./models"; -// Expose time helpers as globals — HTML templates call them in x-text expressions. +// Expose time helpers as globals - HTML templates call them in x-text expressions. window.formatTimeAgo = formatTimeAgo; window.notifTimeAgo = notifTimeAgo; -document.addEventListener('alpine:init', () => { - Alpine.store('dojo', { +document.addEventListener("alpine:init", () => { + Alpine.store("dojo", { isPageReady: false, - isFullscreen: localStorage.getItem('mojo_fullscreen') === 'true', + isFullscreen: localStorage.getItem("mojo_fullscreen") === "true", overlayCount: 0, loadStartTime: Date.now(), isComplete: false, - isMuted: localStorage.getItem('mojo_muted') !== 'false', - isAutoRefresh: localStorage.getItem('mojo_auto') !== 'false', + isMuted: localStorage.getItem("mojo_muted") !== "false", + isAutoRefresh: localStorage.getItem("mojo_auto") !== "false", isConnected: false, _wasConnected: null as boolean | null, - globalToast: { show: false, message: '', type: 'info' as 'success' | 'error' | 'info' }, + globalToast: { + show: false, + message: "", + type: "info" as "success" | "error" | "info", + }, isSyncing: false, syncProgress: 0, secondsSinceUpdate: 0, @@ -28,85 +32,94 @@ document.addEventListener('alpine:init', () => { loadingIndex: 0, loadingInterval: null as ReturnType | null, loadingPhrases: [ - 'Eliminating side fumbling in the kinematic tree...', - 'Cooling off the physics engine...', - 'Lubricating spurving bearings with phenylhydrobenzamine...', - 'Was it (x, y, z, w) or (w, x, y, z)...?', - 'Synchronizing cardinal grammeters with the warm-start...', - 'Fromaging the bituminous spandrels for stability...', - 'Reducing sinusoidal depleneration in the dingle arm...', - 'Checking the prefabulated amulite for micro-cracks...', - 'Recalculating Chomondeley\'s annual grillage coefficient...', - 'Polishing the hydrocoptic marzelvanes...', - 'Resolving contact constraints (it\'s complicated)...', - 'Nubbing the regurgitative purwell to the wennel-sprocket...', - 'Ensuring nofer trunnions are within tolerance...', - 'Consulting the transcendental hopper dadoscope...', - 'Minimizing side-fumbling in the ambifacient vaneshaft...', - 'Aligning the lotus-o-delta stator windings...', - 'Preparing for the inevitable...', - 'Correcting the Lotus-o-delta offset in the kinematic tree...', - 'Tightening the roffit bars on the spamshaft...', - 'Re-aligning the hydrocoptic marzelvanes...', - 'Calibrating the metapolar pilfrometer...', - 'Evaluating the diathecial evolute of retrograde temperature...', - 'De-nubbing the superaminative wennel-sprocket...', - 'Buffering the anhydrous nagling pins...', - 'Shimming the kyptonastic boiling tank...', - 'Analyzing quasi-pietic stresses in the gremlin studs...', - 'Applying drammock oil to the nivelsheave...', - 'Synchronizing the barescent skor motion...', - 'Filtering out reminative tetraiodohexamine...', - 'Stabilizing the modial interaction of magneto-reluctance...', - 'Compensating for capacitive directance...', - 'Scrubbing the manestically placed grouting brushes...', - 'Zeroing out the transcendental hopper dadoscope...', - 'Wrangling the inertia tensor...', - 'Converting Euler angles (and regretting it)...', - 'Refining the convex hull of the collision geometry...', - 'Validating the mass-proportional damping coefficients...', - 'Buffering the unilateral phase detectors...', - 'Extending the drawn reciprocating dingle arm...', - 'Optimizing the panendermic semiboloid slots...', - 'Bleeding air from the non-reversible tremie pipe...', - 'Adjusting the differential girdlespring tension...', + "Eliminating side fumbling in the kinematic tree...", + "Cooling off the physics engine...", + "Lubricating spurving bearings with phenylhydrobenzamine...", + "Was it (x, y, z, w) or (w, x, y, z)...?", + "Synchronizing cardinal grammeters with the warm-start...", + "Fromaging the bituminous spandrels for stability...", + "Reducing sinusoidal depleneration in the dingle arm...", + "Checking the prefabulated amulite for micro-cracks...", + "Recalculating Chomondeley's annual grillage coefficient...", + "Polishing the hydrocoptic marzelvanes...", + "Resolving contact constraints (it's complicated)...", + "Nubbing the regurgitative purwell to the wennel-sprocket...", + "Ensuring nofer trunnions are within tolerance...", + "Consulting the transcendental hopper dadoscope...", + "Minimizing side-fumbling in the ambifacient vaneshaft...", + "Aligning the lotus-o-delta stator windings...", + "Preparing for the inevitable...", + "Correcting the Lotus-o-delta offset in the kinematic tree...", + "Tightening the roffit bars on the spamshaft...", + "Re-aligning the hydrocoptic marzelvanes...", + "Calibrating the metapolar pilfrometer...", + "Evaluating the diathecial evolute of retrograde temperature...", + "De-nubbing the superaminative wennel-sprocket...", + "Buffering the anhydrous nagling pins...", + "Shimming the kyptonastic boiling tank...", + "Analyzing quasi-pietic stresses in the gremlin studs...", + "Applying drammock oil to the nivelsheave...", + "Synchronizing the barescent skor motion...", + "Filtering out reminative tetraiodohexamine...", + "Stabilizing the modial interaction of magneto-reluctance...", + "Compensating for capacitive directance...", + "Scrubbing the manestically placed grouting brushes...", + "Zeroing out the transcendental hopper dadoscope...", + "Wrangling the inertia tensor...", + "Converting Euler angles (and regretting it)...", + "Refining the convex hull of the collision geometry...", + "Validating the mass-proportional damping coefficients...", + "Buffering the unilateral phase detectors...", + "Extending the drawn reciprocating dingle arm...", + "Optimizing the panendermic semiboloid slots...", + "Bleeding air from the non-reversible tremie pipe...", + "Adjusting the differential girdlespring tension...", ], init() { // Restore notification history persisted from a previous page/tab try { - const raw = localStorage.getItem('mojo_notif'); + const raw = localStorage.getItem("mojo_notif"); if (raw) { - const saved = JSON.parse(raw) as { n: NotificationEntry[]; u: number }; + const saved = JSON.parse(raw) as { + n: NotificationEntry[]; + u: number; + }; this.notifications = saved.n ?? []; this.unreadCount = saved.u ?? 0; } - } catch { /* ignore corrupt data */ } + } catch { + /* ignore corrupt data */ + } this.checkServerHealth(); setInterval(() => this.checkServerHealth(), 5000); this.startGlobalSync(); - document.addEventListener('visibilitychange', () => { + document.addEventListener("visibilitychange", () => { if (!document.hidden) this.checkServerHealth(); }); }, - toast(message: string, type: 'success' | 'error' | 'info' = 'info') { + toast(message: string, type: "success" | "error" | "info" = "info") { this.globalToast = { show: true, message, type }; - setTimeout(() => { this.globalToast = { ...this.globalToast, show: false }; }, 3500); + setTimeout(() => { + this.globalToast = { ...this.globalToast, show: false }; + }, 3500); }, _setConnected(connected: boolean) { this.isConnected = connected; if (this._wasConnected === null) { - // Initial connection — set baseline without notifying. + // Initial connection - set baseline without notifying. if (connected) this._wasConnected = true; return; } if (connected === this._wasConnected) return; this._wasConnected = connected; - const message = connected ? 'Server connection restored.' : 'Server connection lost.'; - const type = connected ? 'success' : 'error'; + const message = connected + ? "Server connection restored" + : "Server connection lost"; + const type = connected ? "success" : "error"; this.toast(message, type); this.addNotification(message, type); }, @@ -116,9 +129,9 @@ document.addEventListener('alpine:init', () => { const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), 2000); try { - const response = await fetch('/monitor/api/status', { - method: 'GET', - cache: 'no-store', + const response = await fetch("/monitor/api/status", { + method: "GET", + cache: "no-store", signal: controller.signal, }); clearTimeout(timeoutId); @@ -148,7 +161,9 @@ document.addEventListener('alpine:init', () => { startLoadingMessages() { if (this.loadingInterval) return; - this.loadingIndex = Math.floor(Math.random() * this.loadingPhrases.length); + this.loadingIndex = Math.floor( + Math.random() * this.loadingPhrases.length, + ); this.showPhrase = true; this.loadingInterval = setInterval(() => { this.showPhrase = false; @@ -172,27 +187,27 @@ document.addEventListener('alpine:init', () => { toggleFullscreen() { this.isFullscreen = !this.isFullscreen; - localStorage.setItem('mojo_fullscreen', String(this.isFullscreen)); + localStorage.setItem("mojo_fullscreen", String(this.isFullscreen)); }, exitFullscreen() { this.isFullscreen = false; - localStorage.setItem('mojo_fullscreen', 'false'); + localStorage.setItem("mojo_fullscreen", "false"); }, toggleMute() { this.isMuted = !this.isMuted; - localStorage.setItem('mojo_muted', this.isMuted.toString()); + localStorage.setItem("mojo_muted", this.isMuted.toString()); }, toggleAuto() { this.isAutoRefresh = !this.isAutoRefresh; - localStorage.setItem('mojo_auto', String(this.isAutoRefresh)); + localStorage.setItem("mojo_auto", String(this.isAutoRefresh)); if (this.isAutoRefresh) this.startGlobalSync(); else this.stopGlobalSync(); }, startGlobalSync() { if (this.source || !this.isAutoRefresh || this.isComplete) return; - this.source = new EventSource('/monitor/api/status/stream'); + this.source = new EventSource("/monitor/api/status/stream"); this.source.onopen = () => { this._setConnected(true); @@ -206,21 +221,25 @@ document.addEventListener('alpine:init', () => { value?: number; status?: { is_complete: boolean }; }; - if (data.type === 'start') this.startSync(); - if (data.type === 'progress' && data.value !== undefined) this.setSyncProgress(data.value); - if (data.type === 'final') { + if (data.type === "start") this.startSync(); + if (data.type === "progress" && data.value !== undefined) + this.setSyncProgress(data.value); + if (data.type === "final") { this.endSync(Date.now(), data.status?.is_complete ?? false); window.dispatchEvent( - new CustomEvent('mojo-data-updated', { detail: data.status }), + new CustomEvent("mojo-data-updated", { detail: data.status }), ); } } catch (err) { - console.warn('[Mojo Sync] Received invalid payload.', { raw: event.data, error: err }); + console.warn("[Mojo Sync] Received invalid payload.", { + raw: event.data, + error: err, + }); } }; this.source.onerror = () => { - console.error('[Mojo Sync] Connection lost. Attempting recovery...'); + console.error("[Mojo Sync] Connection lost. Attempting recovery..."); this.isSyncing = false; this.stopGlobalSync(); this.checkServerHealth(); @@ -252,7 +271,9 @@ document.addEventListener('alpine:init', () => { this.isComplete = isComplete; this.isSyncing = false; if (isComplete) this.stopGlobalSync(); - setTimeout(() => { this.syncProgress = 0; }, 700); + setTimeout(() => { + this.syncProgress = 0; + }, 700); }, updateSync(timestamp: number, isComplete = false) { @@ -270,18 +291,23 @@ document.addEventListener('alpine:init', () => { _saveNotifications() { try { - localStorage.setItem('mojo_notif', JSON.stringify({ - n: this.notifications, - u: this.unreadCount, - })); - } catch { /* quota exceeded — ignore */ } + localStorage.setItem( + "mojo_notif", + JSON.stringify({ + n: this.notifications, + u: this.unreadCount, + }), + ); + } catch { + /* quota exceeded - ignore */ + } }, addNotification(message: string, type: string) { (this.notifications as NotificationEntry[]).unshift({ id: Date.now() + Math.random(), message, - type: type as 'success' | 'error' | 'info', + type: type as "success" | "error" | "info", timestamp: Date.now(), read: !!(this.notifOpen as boolean), }); @@ -295,7 +321,9 @@ document.addEventListener('alpine:init', () => { openNotifications() { this.notifOpen = !this.notifOpen; if (this.notifOpen) { - (this.notifications as NotificationEntry[]).forEach((n) => { n.read = true; }); + (this.notifications as NotificationEntry[]).forEach((n) => { + n.read = true; + }); this.unreadCount = 0; this._saveNotifications(); } @@ -308,7 +336,7 @@ document.addEventListener('alpine:init', () => { }, }); - const store = Alpine.store('dojo') as DojoStore & { + const store = Alpine.store("dojo") as DojoStore & { lastUpdate: number | null; secondsSinceUpdate: number; loadStartTime: number; @@ -318,12 +346,16 @@ document.addEventListener('alpine:init', () => { setInterval(() => { if (store.lastUpdate) { - store.secondsSinceUpdate = Math.floor((Date.now() - store.lastUpdate) / 1000); + store.secondsSinceUpdate = Math.floor( + (Date.now() - store.lastUpdate) / 1000, + ); } }, 1000); // Tick every 30 s so notifTimeAgo expressions re-evaluate ("Just now" → "1m ago" etc.) - setInterval(() => { store.notifTick = Date.now(); }, 30_000); + setInterval(() => { + store.notifTick = Date.now(); + }, 30_000); if (!store.isPageReady) { store.loadStartTime = Date.now(); diff --git a/src/mujoco_mojo/utils/layers/dojo/templates/static/ts/src/trial-viewer.ts b/src/mujoco_mojo/utils/layers/dojo/templates/static/ts/src/trial-viewer.ts index 3e43c4bf..e978ffbe 100644 --- a/src/mujoco_mojo/utils/layers/dojo/templates/static/ts/src/trial-viewer.ts +++ b/src/mujoco_mojo/utils/layers/dojo/templates/static/ts/src/trial-viewer.ts @@ -15,7 +15,7 @@ import type { } from "./models"; // --------------------------------------------------------------------------- -// Tailwind offline palette — hex values matching Tailwind CSS defaults +// Tailwind offline palette - hex values matching Tailwind CSS defaults // --------------------------------------------------------------------------- const tw = { slate: { @@ -63,12 +63,22 @@ const DEFAULT_CONFIG: PlotConfig = { shapes: [], }; +// --------------------------------------------------------------------------- +// CodeMirror editor state (kept outside Alpine to avoid proxy issues) +// --------------------------------------------------------------------------- +// eslint-disable-next-line @typescript-eslint/no-explicit-any +const _cm: { editor: any; updating: boolean; debounce: ReturnType | null } = { + editor: null, + updating: false, + debounce: null, +}; + // --------------------------------------------------------------------------- // Component factory // --------------------------------------------------------------------------- function trialViewer(trialId: string, externalUrl: string) { const self = { - // Alpine magic (injected at runtime — declared here for TS) + // Alpine magic (injected at runtime - declared here for TS) ...(null as unknown as AlpineMagics), // --- BASE STATE --- @@ -109,7 +119,7 @@ function trialViewer(trialId: string, externalUrl: string) { // Toast (shared mixin) ...createToastMixin(), - // Options — exposed so templates can use opts.lineMode, opts.interpLabel(...), etc. + // Options - exposed so templates can use opts.lineMode, opts.interpLabel(...), etc. opts: OPTIONS, // --- PLOT CONFIGURATION --- @@ -162,6 +172,28 @@ function trialViewer(trialId: string, externalUrl: string) { annDraft: null as Annotation | null, annEditIndex: null as number | null, + // --- FILTER LAB --- + labOpen: localStorage.getItem("mojo:lab:open") === "1", + labGraph: (() => { + try { + const s = localStorage.getItem("mojo:lab:draft"); + return s ? (JSON.parse(s) as object) : null; + } catch { + return null; + } + })() as object | null, + labName: localStorage.getItem("mojo:lab:name") ?? "", + nodePickingColumn: null as number | null, + nodeColSearch: "" as string, + labSchemas: [] as Array<{ + name: string; + signal_in_columns: string[]; + outputs: string[]; + modified: number; + valid: boolean; + missing: string[]; + }>, + // --- SHAPES --- shapesOpen: false, placementMode: null as "vline" | "hline" | "rect" | null, @@ -249,15 +281,19 @@ function trialViewer(trialId: string, externalUrl: string) { const colParams = new URLSearchParams(); if (requiredCols.length > 0) colParams.append("cols", requiredCols.join(",")); - if (this.config.refFrame) - colParams.append("rotate_by", this.config.refFrame); // include active filter stacks for requested columns (x-axis and y-axes) const filtersPayload: Record = {}; - const toActiveFilters = (filters: { enabled?: boolean; [k: string]: unknown }[]) => + const toActiveFilters = ( + filters: { enabled?: boolean; [k: string]: unknown }[], + ) => filters .filter((f) => f.enabled !== false) - .map((f) => Object.fromEntries(Object.entries(f).filter(([k]) => k !== "enabled"))); + .map((f) => + Object.fromEntries( + Object.entries(f).filter(([k]) => k !== "enabled"), + ), + ); for (const col of requiredCols) { const yConfig = this.config.yAxes[col]; if (yConfig?.filters && yConfig.filters.length > 0) { @@ -348,7 +384,10 @@ function trialViewer(trialId: string, externalUrl: string) { const start = Math.min(this.vsDraft.range[0], this.vsDraft.range[1]); const end = Math.max(this.vsDraft.range[0], this.vsDraft.range[1]); - const activeCols = [this.config.xAxis!.col!, ...Object.keys(this.config.yAxes)]; + const activeCols = [ + this.config.xAxis!.col!, + ...Object.keys(this.config.yAxes), + ]; const draftIds = this.allTrials.filter((id) => { const n = parseInt(id.split("_").pop() ?? ""); @@ -627,6 +666,7 @@ function trialViewer(trialId: string, externalUrl: string) { this.columns = response.columns.all.sort(); this.rotateableVectors = response.columns.rotatable_vectors ?? []; this.data = response.data; + void this.loadLabSchemas(); const params = new URLSearchParams(window.location.search); const shared = params.get("v"); @@ -641,6 +681,15 @@ function trialViewer(trialId: string, externalUrl: string) { this.vsDraft.range = [...this.config.vsRange]; } + // Migrate old profiles: if refFrame is set but no series has a RotationFilter, + // inject it now (before watchers are registered so this is a silent migration). + if (this.config.refFrame) { + const hasRotation = Object.values(this.config.yAxes).some((y) => + y.filters.some((f) => f.type === "rotation"), + ); + if (!hasRotation) this.applyRefFrame(this.config.refFrame); + } + void this.$nextTick(() => { this.pushHistory(); }); @@ -778,59 +827,124 @@ function trialViewer(trialId: string, externalUrl: string) { // (e.g. @keydown.escape.window in base.html). stopImmediatePropagation() // in the Escape branch then prevents those listeners from firing when a // panel was open. - window.addEventListener("keydown", (e) => { - if (e.repeat) return; - const tag = (e.target as HTMLElement).tagName; - if (e.key === "/" && !["INPUT", "TEXTAREA"].includes(tag)) { - e.preventDefault(); - ( - document.querySelector('input[type="number"]') as HTMLElement | null - )?.focus(); - } - if (e.key === "Escape") { - const anyOpen = !!( - this.placementMode || this.annotationsOpen || this.shapesOpen || - this.xMenuOpen || this.yMenuOpen || this.refFrameMenuOpen || - this.settingsOpen || this.downloadOpen || this.editorOpen || - this.profilesOpen || this.vsMenuOpen || - (Alpine.store("dojo") as DojoStore).overlayCount > 0 || - ["INPUT", "TEXTAREA"].includes(tag) - ); - if (["INPUT", "TEXTAREA"].includes(tag)) - (e.target as HTMLElement).blur(); - this.placementMode = null; - this.rectStart = null; - this.cancelAnnDraft(); - this.cancelShapeDraft(); - this.annotationsOpen = false; - this.shapesOpen = false; - this.xMenuOpen = this.yMenuOpen = this.refFrameMenuOpen = false; - this.settingsOpen = this.downloadOpen = this.editorOpen = false; - this.profilesOpen = this.vsMenuOpen = false; - this.profileSearch = ""; - window.dispatchEvent(new CustomEvent("mojo:escape")); - // Stop immediate propagation when something was open so Alpine's - // bubble-phase @keydown.escape.window handler doesn't also fire. - if (anyOpen) e.stopImmediatePropagation(); - } - if (["INPUT", "TEXTAREA"].includes(tag)) return; - if (e.key === "ArrowLeft") document.getElementById("nav-prev")?.click(); - if (e.key === "ArrowRight") - document.getElementById("nav-next")?.click(); - - const isZ = e.key.toLowerCase() === "z"; - const isY = e.key.toLowerCase() === "y"; - const cmdOrCtrl = e.metaKey || e.ctrlKey; - if (cmdOrCtrl && isZ) { - e.preventDefault(); - if (e.shiftKey) this.redo(); - else this.undo(); - } - if (cmdOrCtrl && isY) { - e.preventDefault(); - this.redo(); - } - }, { capture: true }); + window.addEventListener( + "keydown", + (e) => { + if (e.repeat) return; + const targetEl = e.target as HTMLElement; + const tag = targetEl.tagName; + const isTextInput = + ["INPUT", "TEXTAREA", "SELECT"].includes(tag) || + targetEl.isContentEditable; + if (e.key === "/" && !isTextInput) { + e.preventDefault(); + ( + document.querySelector( + 'input[type="number"]', + ) as HTMLElement | null + )?.focus(); + } + if (e.key === "Escape") { + const anyOpen = !!( + this.placementMode || + this.annotationsOpen || + this.shapesOpen || + this.xMenuOpen || + this.yMenuOpen || + this.refFrameMenuOpen || + this.settingsOpen || + this.downloadOpen || + this.editorOpen || + this.profilesOpen || + this.vsMenuOpen || + this.labOpen || + (Alpine.store("dojo") as DojoStore).overlayCount > 0 || + isTextInput + ); + if (isTextInput) targetEl.blur(); + this.placementMode = null; + this.rectStart = null; + this.cancelAnnDraft(); + this.cancelShapeDraft(); + this.annotationsOpen = false; + this.shapesOpen = false; + this.xMenuOpen = this.yMenuOpen = this.refFrameMenuOpen = false; + this.settingsOpen = this.downloadOpen = this.editorOpen = false; + this.profilesOpen = this.vsMenuOpen = false; + this.profileSearch = ""; + this.labOpen = false; + window.dispatchEvent(new CustomEvent("mojo:escape")); + // Stop immediate propagation when something was open so Alpine's + // bubble-phase @keydown.escape.window handler doesn't also fire. + // This prevents Escape from both closing the lab and exiting fullscreen. + if (anyOpen) e.stopImmediatePropagation(); + } + if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "s") { + e.preventDefault(); + if (!isTextInput) { + if (this.labOpen) { + const el = document.getElementById( + "lab-name-input", + ) as HTMLInputElement | null; + if (el) { + el.focus(); + el.setSelectionRange(el.value.length, el.value.length); + } + } else { + this.profilesOpen = true; + void this.loadProfiles(); + void this.$nextTick(() => { + const el = document.getElementById( + "profile-name-input", + ) as HTMLInputElement | null; + if (el) { + el.focus(); + el.setSelectionRange(el.value.length, el.value.length); + } + }); + } + } + } + if ((e.metaKey || e.ctrlKey) && !isTextInput) { + if (e.key === "ArrowLeft") { + e.preventDefault(); + document.getElementById("nav-prev")?.click(); + } else if (e.key === "ArrowRight") { + e.preventDefault(); + document.getElementById("nav-next")?.click(); + } + } + if (isTextInput) return; + + const isZ = e.key.toLowerCase() === "z"; + const isY = e.key.toLowerCase() === "y"; + const cmdOrCtrl = e.metaKey || e.ctrlKey; + if (cmdOrCtrl && isZ) { + e.preventDefault(); + if (this.labOpen) { + e.shiftKey ? window.mojoLabRedo?.() : window.mojoLabUndo?.(); + } else { + if (e.shiftKey) this.redo(); + else this.undo(); + } + } + if (cmdOrCtrl && isY) { + e.preventDefault(); + if (this.labOpen) window.mojoLabRedo?.(); + else this.redo(); + } + if (this.labOpen && cmdOrCtrl && e.shiftKey) { + if (e.key.toLowerCase() === "a") { + e.preventDefault(); + window.mojoLabArrange?.(); + } else if (e.key.toLowerCase() === "f") { + e.preventDefault(); + window.mojoLabFitView?.(); + } + } + }, + { capture: true }, + ); const resp = await fetch("/mosaic/api/trials"); const data = (await resp.json()) as TrialManifest; @@ -851,41 +965,23 @@ function trialViewer(trialId: string, externalUrl: string) { this.$watch("vsDraft.range", () => { if (this.discoveryTimeout) clearTimeout(this.discoveryTimeout); this.discoveryTimeout = setTimeout(() => { - if (this.vsDraft.enabled) { - console.debug( - "Predictive Sync: User adjusted range, starting hydration...", - ); - void this.startBackgroundDiscovery(); - } + if (this.vsDraft.enabled) void this.startBackgroundDiscovery(); }, 500); }); - this.$watch( - "config.refFrame", - async (newValue: string | null, oldValue: string | null) => { - console.debug( - `[Mojo] Frame Change: ${oldValue ?? "world"} -> ${newValue ?? "world"}`, - ); - this.notify(`Frame: ${newValue || "world"}`, "info"); - this.discoveryId++; - this.data = {}; - this.vsDatasets = {}; - const initialCols = [ - this.config.xAxis!.col!, - ...Object.keys(this.config.yAxes), - ]; - const response = await this.fetchTrialData(this.trialId, initialCols); - this.columns = response.columns.all.sort(); - this.rotateableVectors = response.columns.rotatable_vectors ?? []; - this.data = response.data; - void this.startBackgroundDiscovery(); - if (this.config.vsEnabled) await this.syncVsRange(); - this.saveAndRender(); - }, - ); + this.$watch("config.refFrame", (newValue: string | null, oldValue: string | null) => { + if (newValue === oldValue) return; + this.notify(`Frame: ${newValue || "world"}`, "info"); + this.discoveryId++; + this.applyRefFrame(newValue); + // config watcher handles re-fetch and re-render when yAxes.filters change + }); this.$watch("config", async (value: PlotConfig, oldValue: PlotConfig) => { - if (!this.isEditingRaw) this.configRaw = JSON.stringify(value, null, 4); + if (!this.isEditingRaw) { + this.configRaw = JSON.stringify(value, null, 4); + try { localStorage.removeItem("mojo:config:raw-draft"); } catch {} + } if ( this.config.vsEnabled && oldValue?.vsEnabled && @@ -899,7 +995,7 @@ function trialViewer(trialId: string, externalUrl: string) { // detect filter changes by comparing against the last-fetched fingerprint rather // than oldValue, because Alpine.js $watch does not reliably deep-clone oldValue - // for nested reactive objects — both value and oldValue may point to the same data + // for nested reactive objects - both value and oldValue may point to the same data const changedFilterCols = Object.keys(value.yAxes).filter((col) => { const current = JSON.stringify( (value.yAxes[col]?.filters ?? []).filter( @@ -941,7 +1037,10 @@ function trialViewer(trialId: string, externalUrl: string) { }); void this.startBackgroundDiscovery(); - this.configRaw = JSON.stringify(this.config, null, 4); + this.configRaw = + localStorage.getItem("mojo:config:raw-draft") ?? + JSON.stringify(this.config, null, 4); + this.updateFromRaw(); }, // ----------------------------------------------------------------------- @@ -966,7 +1065,10 @@ function trialViewer(trialId: string, externalUrl: string) { try { const start = Math.min(this.vsDraft.range[0], this.vsDraft.range[1]); const end = Math.max(this.vsDraft.range[0], this.vsDraft.range[1]); - let activeCols = [this.config.xAxis!.col!, ...Object.keys(this.config.yAxes)]; + let activeCols = [ + this.config.xAxis!.col!, + ...Object.keys(this.config.yAxes), + ]; if (this.config.refFrame) { const families = new Set(); @@ -1028,10 +1130,49 @@ function trialViewer(trialId: string, externalUrl: string) { handleVsToggle() { if (!this.vsDraft.enabled) { this.config.vsEnabled = false; + this.vsDatasets = {}; this.renderPlot(); } }, + setVsPreset(delta: number) { + const cur = parseInt(this.trialId.split("_").pop() ?? "0"); + this.vsDraft.range = [cur - delta, cur + delta]; + }, + + setVsAll() { + const nums = this.allTrials + .map((t) => parseInt(t.split("_").pop() ?? "")) + .filter((n) => !isNaN(n)); + if (!nums.length) return; + this.vsDraft.range = [Math.min(...nums), Math.max(...nums)]; + }, + + isVsPreset(delta: number): boolean { + const cur = parseInt(this.trialId.split("_").pop() ?? "0"); + const [a, b] = this.vsDraft.range; + return Math.min(a, b) === cur - delta && Math.max(a, b) === cur + delta; + }, + + isVsAll(): boolean { + const nums = this.allTrials + .map((t) => parseInt(t.split("_").pop() ?? "")) + .filter((n) => !isNaN(n)); + if (!nums.length) return false; + const [a, b] = this.vsDraft.range; + return Math.min(a, b) === Math.min(...nums) && Math.max(a, b) === Math.max(...nums); + }, + + vsInRangeCount(): number { + const lo = Math.min(this.vsDraft.range[0], this.vsDraft.range[1]); + const hi = Math.max(this.vsDraft.range[0], this.vsDraft.range[1]); + const cur = parseInt(this.trialId.split("_").pop() ?? ""); + return this.allTrials.filter((id) => { + const n = parseInt(id.split("_").pop() ?? ""); + return n >= lo && n <= hi && n !== cur; + }).length; + }, + // ----------------------------------------------------------------------- // Column filtering & search // ----------------------------------------------------------------------- @@ -1047,7 +1188,10 @@ function trialViewer(trialId: string, externalUrl: string) { getFilteredCols(field: string): string[] { if (!this.columns || !Array.isArray(this.columns)) return []; - const base = field === "x" ? this.columns : this.selectableYColumns; + const base = + field === "x" || field === "nodeCol" + ? this.columns + : this.selectableYColumns; const search = (this as unknown as Record)[field + "Search"] ?? ""; if (!search) return this.smartSort([...base]); @@ -1112,7 +1256,10 @@ function trialViewer(trialId: string, externalUrl: string) { }, getSegmentsAtDepth(field: string, depth: number): string[] { - const base = field === "x" ? this.columns : this.selectableYColumns; + const base = + field === "x" || field === "nodeCol" + ? this.columns + : this.selectableYColumns; const search = (this as unknown as Record)[field + "Search"] ?? ""; const pathSearch = search.split(":")[0] ?? ""; @@ -1135,7 +1282,10 @@ function trialViewer(trialId: string, externalUrl: string) { }, getAvailableSuffixes(field: string): string[] { - const base = field === "x" ? this.columns : this.selectableYColumns; + const base = + field === "x" || field === "nodeCol" + ? this.columns + : this.selectableYColumns; const search = (this as unknown as Record)[field + "Search"] ?? ""; const [pathPart = "", suffixPart = ""] = search.split(":"); @@ -1224,14 +1374,34 @@ function trialViewer(trialId: string, externalUrl: string) { validateConfig(cfg: PlotConfig): string[] { const errors: string[] = []; - if (cfg.xAxis?.col && !this.columns.includes(cfg.xAxis.col)) - errors.push(`X-Axis "${cfg.xAxis.col}" not found in telemetry.`); + const labsNoted = new Set(); + const schemasLoaded = this.labSchemas.length > 0; + + const checkCol = (col: string, label: string) => { + if (col.startsWith("Lab/")) { + if (!schemasLoaded) return; // wait for schemas before reporting Lab issues + const labName = col.slice(4).split("/")[0]; + if (labsNoted.has(labName)) return; + const lab = this.labSchemas.find((l) => l.name === labName); + if (!lab) { + labsNoted.add(labName); + errors.push(`Lab "${labName}" not found.`); + } else if (lab.missing.length > 0) { + labsNoted.add(labName); + errors.push( + `Lab "${labName}" requires: ${lab.signal_in_columns.join(", ")}; missing: ${lab.missing.join(", ")}.`, + ); + } + } else if (!this.columns.includes(col)) { + errors.push(`${label} "${col}" not found in telemetry.`); + } + }; + + if (cfg.xAxis?.col) checkCol(cfg.xAxis.col, "X-Axis"); if (typeof cfg.yAxes !== "object" || Array.isArray(cfg.yAxes)) { errors.push("yAxes must be a hashmap."); } else { - Object.keys(cfg.yAxes).forEach((y) => { - if (!this.columns.includes(y)) errors.push(`Y-Axis "${y}" missing.`); - }); + Object.keys(cfg.yAxes).forEach((y) => checkCol(y, "Y-Axis")); } if (cfg.vsRange && cfg.vsRange[0] > cfg.vsRange[1]) errors.push("Comparison range start cannot be greater than end."); @@ -1239,6 +1409,7 @@ function trialViewer(trialId: string, externalUrl: string) { }, updateFromRaw() { + try { localStorage.setItem("mojo:config:raw-draft", this.configRaw); } catch {} try { const parsed = JSON.parse(this.configRaw) as PlotConfig; this.isValidJson = true; @@ -1246,8 +1417,16 @@ function trialViewer(trialId: string, externalUrl: string) { this.configErrors = this.validateConfig(parsed); this.isValidConfig = this.configErrors.length === 0; if (this.isValidConfig) { + const prevRefFrame = this.config.refFrame ?? null; this.isEditingRaw = true; this.config = { ...this.config, ...parsed }; + // Apply rotation filters synchronously. $watch("config.refFrame") fires + // asynchronously after the whole config object is replaced, so filters + // would be wrong during the first render if we relied solely on the watch. + const nextRefFrame = (this.config.refFrame as string | null) ?? null; + if (nextRefFrame !== prevRefFrame) { + this.applyRefFrame(nextRefFrame); + } void this.$nextTick(() => { this.isEditingRaw = false; }); @@ -1339,6 +1518,161 @@ function trialViewer(trialId: string, externalUrl: string) { void this.copyToClipboard(this.configRaw, "JSON Config copied!"); }, + initCodeMirror(hostEl: HTMLElement) { + if (!hostEl || typeof CM === "undefined" || _cm.editor) return; + const { + EditorView, basicSetup, json, jsonParseLinter, + oneDarkHighlightStyle, EditorState, Compartment, + linter, lintGutter, syntaxHighlighting, defaultHighlightStyle, + } = CM; + const self = this; + + // Restore persisted height before creating the editor so it sizes correctly. + const savedH = localStorage.getItem("mojo:json-editor:height"); + if (savedH) hostEl.style.height = savedH; + + // --- themes (base chrome only; highlight handled separately) --- + const darkTheme = EditorView.theme({ + "&": { backgroundColor: "#020617", color: "#cbd5e1", height: "100%" }, + ".cm-scroller": { overflow: "auto", fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace", fontSize: "0.875rem", lineHeight: "1.625" }, + ".cm-content": { padding: "1rem", caretColor: "#06b6d4" }, + ".cm-cursor": { borderLeftColor: "#06b6d4" }, + ".cm-gutters": { backgroundColor: "#0f172a", color: "#475569", borderRight: "1px solid #1e293b" }, + ".cm-activeLineGutter": { backgroundColor: "rgba(15,23,42,0.6)" }, + ".cm-activeLine": { backgroundColor: "rgba(15,23,42,0.4)" }, + ".cm-selectionBackground": { backgroundColor: "#1e293b !important" }, + "&.cm-focused .cm-selectionBackground": { backgroundColor: "#1e293b !important" }, + ".cm-matchingBracket": { color: "#22d3ee", fontWeight: "bold" }, + ".cm-tooltip": { backgroundColor: "#1e293b", border: "1px solid #334155", color: "#cbd5e1" }, + ".cm-panels": { backgroundColor: "#0f172a", borderColor: "#1e293b", color: "#cbd5e1" }, + ".cm-searchMatch": { backgroundColor: "rgba(34,211,238,0.18)" }, + ".cm-searchMatch.cm-searchMatch-selected": { backgroundColor: "rgba(34,211,238,0.35)" }, + ".cm-lintRange-error": { backgroundImage: "none", textDecoration: "underline wavy #ef4444 1.5px", textUnderlineOffset: "3px" }, + ".cm-lintRange-warning": { backgroundImage: "none", textDecoration: "underline wavy #f59e0b 1.5px", textUnderlineOffset: "3px" }, + ".cm-diagnostic-error": { borderLeft: "3px solid #ef4444" }, + }, { dark: true }); + + const lightTheme = EditorView.theme({ + "&": { backgroundColor: "#ffffff", color: "#0f172a", height: "100%" }, + ".cm-scroller": { overflow: "auto", fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace", fontSize: "0.875rem", lineHeight: "1.625" }, + ".cm-content": { padding: "1rem", caretColor: "#0891b2" }, + ".cm-cursor": { borderLeftColor: "#0891b2" }, + ".cm-gutters": { backgroundColor: "#f8fafc", color: "#94a3b8", borderRight: "1px solid #e2e8f0" }, + ".cm-activeLineGutter": { backgroundColor: "rgba(241,245,249,0.6)" }, + ".cm-activeLine": { backgroundColor: "rgba(241,245,249,0.5)" }, + ".cm-selectionBackground": { backgroundColor: "#e2e8f0 !important" }, + "&.cm-focused .cm-selectionBackground": { backgroundColor: "#e2e8f0 !important" }, + ".cm-matchingBracket": { color: "#0891b2", fontWeight: "bold" }, + ".cm-tooltip": { backgroundColor: "#f8fafc", border: "1px solid #e2e8f0", color: "#0f172a" }, + ".cm-panels": { backgroundColor: "#f8fafc", borderColor: "#e2e8f0" }, + ".cm-searchMatch": { backgroundColor: "rgba(8,145,178,0.15)" }, + ".cm-searchMatch.cm-searchMatch-selected": { backgroundColor: "rgba(8,145,178,0.3)" }, + ".cm-lintRange-error": { backgroundImage: "none", textDecoration: "underline wavy #ef4444 1.5px", textUnderlineOffset: "3px" }, + ".cm-lintRange-warning": { backgroundImage: "none", textDecoration: "underline wavy #f59e0b 1.5px", textUnderlineOffset: "3px" }, + ".cm-diagnostic-error": { borderLeft: "3px solid #ef4444" }, + }, { dark: false }); + + const isDark = () => document.documentElement.classList.contains("dark"); + const themeComp = new Compartment(); + const highlightComp = new Compartment(); + const makeTheme = (dark: boolean) => dark ? darkTheme : lightTheme; + const makeHighlight = (dark: boolean) => + syntaxHighlighting(dark ? oneDarkHighlightStyle : defaultHighlightStyle); + + const startState = EditorState.create({ + doc: this.configRaw, + extensions: [ + basicSetup, + json(), + lintGutter(), + linter(jsonParseLinter()), + themeComp.of(makeTheme(isDark())), + highlightComp.of(makeHighlight(isDark())), + EditorView.updateListener.of((update) => { + if (update.docChanged && !_cm.updating) { + const text = update.state.doc.toString(); + _cm.updating = true; + self.configRaw = text; + if (_cm.debounce !== null) clearTimeout(_cm.debounce); + _cm.debounce = setTimeout(() => { + self.updateFromRaw(); + _cm.debounce = null; + }, 500); + _cm.updating = false; + } + }), + ], + }); + + _cm.editor = new EditorView({ state: startState, parent: hostEl }); + + // Custom resize handle + const handle = document.createElement("div"); + handle.style.cssText = "height:14px;cursor:ns-resize;display:flex;align-items:center;justify-content:center;flex-shrink:0;"; + const grip = document.createElement("div"); + grip.style.cssText = "width:36px;height:4px;border-radius:2px;background:#334155;transition:background 150ms,width 150ms;pointer-events:none;"; + handle.appendChild(grip); + handle.addEventListener("mouseenter", () => { grip.style.background = "#06b6d4"; grip.style.width = "52px"; }); + handle.addEventListener("mouseleave", () => { grip.style.background = "#334155"; grip.style.width = "36px"; }); + hostEl.insertAdjacentElement("afterend", handle); + + handle.addEventListener("mousedown", (e) => { + const startY = e.clientY; + const startH = hostEl.offsetHeight; + let prevY = startY; + document.body.style.userSelect = "none"; + document.body.style.cursor = "ns-resize"; + const onMove = (ev: MouseEvent) => { + const dy = ev.clientY - prevY; + prevY = ev.clientY; + const newH = Math.max(128, startH + (ev.clientY - startY)); + hostEl.style.height = newH + "px"; + if (dy > 0) window.scrollBy(0, dy); + }; + const onUp = () => { + document.body.style.userSelect = ""; + document.body.style.cursor = ""; + document.removeEventListener("mousemove", onMove); + document.removeEventListener("mouseup", onUp); + try { localStorage.setItem("mojo:json-editor:height", hostEl.style.height); } catch { /* */ } + }; + document.addEventListener("mousemove", onMove); + document.addEventListener("mouseup", onUp); + e.preventDefault(); + }); + + handle.addEventListener("dblclick", () => { + const scroller = hostEl.querySelector(".cm-scroller") as HTMLElement | null; + if (scroller) { + hostEl.style.height = scroller.scrollHeight + "px"; + try { localStorage.setItem("mojo:json-editor:height", hostEl.style.height); } catch { /* */ } + } + }); + + // Swap theme when dark mode toggles. + new MutationObserver(() => { + const dark = isDark(); + _cm.editor?.dispatch({ + effects: [ + themeComp.reconfigure(makeTheme(dark)), + highlightComp.reconfigure(makeHighlight(dark)), + ], + }); + }).observe(document.documentElement, { attributes: true, attributeFilter: ["class"] }); + + // Sync external configRaw changes into CM. + this.$watch("configRaw", (val: string) => { + if (!_cm.updating && _cm.editor) { + const current = _cm.editor.state.doc.toString() as string; + if (current !== val) { + _cm.updating = true; + _cm.editor.dispatch({ changes: { from: 0, to: current.length, insert: val } }); + _cm.updating = false; + } + } + }); + }, + resetConfig() { if ( confirm( @@ -1430,7 +1764,10 @@ function trialViewer(trialId: string, externalUrl: string) { downloadCSV() { if (!this.data || Object.keys(this.config.yAxes).length === 0) return; - const activeCols = [this.config.xAxis!.col!, ...Object.keys(this.config.yAxes)]; + const activeCols = [ + this.config.xAxis!.col!, + ...Object.keys(this.config.yAxes), + ]; const rowCount = this.data[this.config.xAxis!.col!]?.length ?? 0; let csv = activeCols.join(",") + "\n"; for (let i = 0; i < rowCount; i++) { @@ -1498,12 +1835,15 @@ function trialViewer(trialId: string, externalUrl: string) { this.config.yAxes = rest; } else { const nextIndex = Object.keys(this.config.yAxes).length; + const initFilters: FilterEntry[] = this.config.refFrame + ? [{ type: "rotation", quat_col: this.config.refFrame, invert: true, enabled: true }] + : []; this.config.yAxes[col] = { color: this.getSignalColor(nextIndex), label: "", width: 3, opacity: 1, - filters: [], + filters: initFilters, dash: "solid", marker: "none", }; @@ -1519,6 +1859,40 @@ function trialViewer(trialId: string, externalUrl: string) { this.notify("Signals Cleared", "info"); }, + applyRefFrame(frame: string | null) { + for (const col of Object.keys(this.config.yAxes)) { + const yConfig = this.config.yAxes[col]; + if (!yConfig) continue; + if (frame) { + const newEntry: FilterEntry = { + type: "rotation", + quat_col: frame, + invert: true, + enabled: true, + }; + const idx = yConfig.filters.findIndex((f) => f.type === "rotation"); + if (idx >= 0) { + // Replace in-place to preserve the user's chosen position in the stack + yConfig.filters = [ + ...yConfig.filters.slice(0, idx), + newEntry, + ...yConfig.filters.slice(idx + 1), + ]; + } else { + yConfig.filters = [newEntry, ...yConfig.filters]; + } + } else { + const idx = yConfig.filters.findIndex((f) => f.type === "rotation"); + if (idx >= 0) { + yConfig.filters = [ + ...yConfig.filters.slice(0, idx), + ...yConfig.filters.slice(idx + 1), + ]; + } + } + } + }, + warpToTrial() { if ( this.warpId === null || @@ -1554,31 +1928,77 @@ function trialViewer(trialId: string, externalUrl: string) { return this.filterSchemas.find((s) => s.type === filterType); }, + get groupedFilterSchemas(): { category: string; schemas: FilterSchema[] }[] { + const ORDER = ["Smoothing", "Arithmetic", "Trigonometry", "Calculus", "Comparison", "Bounding", "Misc"]; + const groups: Record = {}; + for (const s of this.filterSchemas) { + const cat = s.category ?? "Misc"; + (groups[cat] ??= []).push(s); + } + return ORDER.filter((c) => groups[c]?.length).map((c) => ({ category: c, schemas: groups[c] })); + }, + evalMathExpr(expr: string): number | null { const s = String(expr ?? "").trim(); if (!s) return null; const n = Number(s); if (!isNaN(n)) return n; try { - // Expose a safe math context — no access to globals beyond these names. + // Expose a safe math context - no access to globals beyond these names. const fn = new Function( - "pi", "e", - "sin", "cos", "tan", "asin", "acos", "atan", "atan2", - "sqrt", "cbrt", "log", "log2", "log10", - "abs", "floor", "ceil", "round", "sign", - "pow", "exp", "max", "min", + "pi", + "e", + "sin", + "cos", + "tan", + "asin", + "acos", + "atan", + "atan2", + "sqrt", + "cbrt", + "log", + "log2", + "log10", + "abs", + "floor", + "ceil", + "round", + "sign", + "pow", + "exp", + "max", + "min", `"use strict"; return (${s})`, ); const result = fn( - Math.PI, Math.E, - Math.sin, Math.cos, Math.tan, Math.asin, Math.acos, Math.atan, Math.atan2, - Math.sqrt, Math.cbrt, Math.log, Math.log2, Math.log10, - Math.abs, Math.floor, Math.ceil, Math.round, Math.sign, - Math.pow, Math.exp, Math.max, Math.min, + Math.PI, + Math.E, + Math.sin, + Math.cos, + Math.tan, + Math.asin, + Math.acos, + Math.atan, + Math.atan2, + Math.sqrt, + Math.cbrt, + Math.log, + Math.log2, + Math.log10, + Math.abs, + Math.floor, + Math.ceil, + Math.round, + Math.sign, + Math.pow, + Math.exp, + Math.max, + Math.min, ) as unknown; if (typeof result === "number" && isFinite(result)) return result; } catch { - // invalid expression — fall through + // invalid expression - fall through } return null; }, @@ -1615,6 +2035,8 @@ function trialViewer(trialId: string, externalUrl: string) { const schema = this.filterSchemas.find((s) => s.type === filterType); if (!schema) return; if (!temp.filters) temp.filters = []; + if (filterType === "rotation" && temp.filters.some((f) => f.type === "rotation")) + return; const entry: FilterEntry = { type: filterType, enabled: true }; for (const p of schema.params) { (entry as Record)[p.name] = p.default; @@ -1661,6 +2083,134 @@ function trialViewer(trialId: string, externalUrl: string) { return `/mosaic/api/profiles/${name.split("/").map(encodeURIComponent).join("/")}`; }, + // ── Lab ────────────────────────────────────────────────────────────────── + relTime(ms: number): string { + const diff = Date.now() - ms; + const min = Math.floor(diff / 60000); + if (min < 1) return "just now"; + if (min < 60) return `${min}m ago`; + const h = Math.floor(min / 60); + if (h < 24) return `${h}h ago`; + const d = Math.floor(h / 24); + return d === 1 ? "yesterday" : `${d}d ago`; + }, + + async loadLabSchemas() { + try { + const resp = await fetch("/mosaic/api/lab"); + if (!resp.ok) return; + const all = (await resp.json()) as Omit< + (typeof this.labSchemas)[0], + "valid" | "missing" + >[]; + // Deduplicate and sort inputs/outputs for each lab. + const schemas = all.map((lab) => ({ + ...lab, + signal_in_columns: [...new Set(lab.signal_in_columns)].sort(), + outputs: [...new Set(lab.outputs)].sort(), + })); + // Iterative BFS: a lab is valid when all its inputs are already available. + // Labs that read from other valid labs' outputs need multiple passes to resolve. + const baseColumns = this.columns.filter((c) => !c.startsWith("Lab/")); + const available = new Set(baseColumns); + const validLabs = new Set(); + let changed = true; + while (changed) { + changed = false; + for (const lab of schemas) { + if (validLabs.has(lab.name)) continue; + if (lab.signal_in_columns.every((c) => available.has(c))) { + validLabs.add(lab.name); + lab.outputs.forEach((o) => available.add(`Lab/${lab.name}/${o}`)); + changed = true; + } + } + } + this.labSchemas = schemas.map((lab) => ({ + ...lab, + missing: lab.signal_in_columns.filter((c) => !available.has(c)), + valid: validLabs.has(lab.name), + })); + // Rebuild virtual Lab columns from scratch - removes stale entries from deleted labs. + this.columns = [...available].sort(); + } catch { + // Lab endpoint unavailable - silently ignore + } + }, + + async refreshLabValidation() { + await this.loadLabSchemas(); + void this.loadProfiles(); + }, + + async saveLabGraph(name: string, graph: object) { + const trimmed = name.trim(); + if (!trimmed) return; + const exists = this.labSchemas.some((s) => s.name === trimmed); + if (exists && !confirm(`Overwrite "${trimmed}"?`)) return; + const safePath = trimmed.split("/").map(encodeURIComponent).join("/"); + try { + const resp = await fetch(`/mosaic/api/lab/${safePath}`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(graph), + }); + if (!resp.ok) { + const detail = await resp.text().catch(() => resp.statusText); + this.notify(`Save failed: ${detail}`, "error"); + return; + } + localStorage.setItem("mojo:lab:name", trimmed); + this.notify(`Lab "${trimmed}" saved`, "success"); + await this.refreshLabValidation(); + // Evict stale computed data for this lab's outputs, then re-fetch anything + // currently plotted so the chart updates immediately. + const labPrefix = `Lab/${trimmed}/`; + const staleCols = Object.keys(this.data ?? {}).filter((c) => + c.startsWith(labPrefix), + ); + if (staleCols.length > 0) { + const fresh = { ...(this.data ?? {}) }; + staleCols.forEach((c) => delete fresh[c]); + this.data = fresh; + const activeCols = staleCols.filter( + (c) => c in this.config.yAxes || c === this.config.xAxis?.col, + ); + if (activeCols.length > 0) { + try { + const refetch = await this.fetchTrialData(this.trialId, activeCols); + this.data = { ...(this.data ?? {}), ...refetch.data }; + this.saveAndRender(); + } catch { + // non-critical: plot drops the stale trace until background discovery refetches + } + } + } + } catch (err) { + this.notify(`Save failed: ${String(err)}`, "error"); + } + }, + + selectNodeColumn(col: string) { + if (this.nodePickingColumn !== null) { + // Defined in _signal_lab.html - updates the LiteGraph node property + if (typeof window.mojoLabSelectNodeColumn === "function") { + window.mojoLabSelectNodeColumn(this.nodePickingColumn, col); + } + } + this.nodePickingColumn = null; + this.nodeColSearch = ""; + }, + + async deleteLabGraph(name: string) { + const safePath = name.split("/").map(encodeURIComponent).join("/"); + await fetch(`/mosaic/api/lab/${safePath}`, { + method: "DELETE", + }); + this.notify(`Lab "${name}" deleted`, "info"); + await this.refreshLabValidation(); + }, + // ----------------------------------------------------------------------- async loadProfiles() { try { @@ -1764,6 +2314,25 @@ function trialViewer(trialId: string, externalUrl: string) { this.config = { ...this.config, ...loaded }; this.notify(`Profile "${name}" loaded`, "success"); + + // Fetch data for any columns the profile introduces that aren't cached yet. + const needed: string[] = []; + if (loaded.xAxis?.col && !this.data?.[loaded.xAxis.col]) + needed.push(loaded.xAxis.col); + for (const col of Object.keys(loaded.yAxes ?? {})) { + if (!this.data?.[col]) needed.push(col); + } + if (needed.length > 0) { + const fetched = await this.fetchTrialData(this.trialId, needed); + this.data = { ...(this.data ?? {}), ...fetched.data }; + } + + void this.$nextTick(() => { + this.configErrors = this.validateConfig(this.config as PlotConfig); + this.isValidConfig = this.configErrors.length === 0; + this.isValidJson = true; + this.saveAndRender(); + }); } catch (e) { this.notify( `Failed to load "${name}": ${(e as Error).message}`, @@ -2135,103 +2704,109 @@ function trialViewer(trialId: string, externalUrl: string) { groupclick: "togglegroup", }, ...polarLayout, - annotations: isPolar ? [] : [ - ...(this.config.annotations ?? []).map((ann) => ({ - x: ann.x, - y: ann.y, - text: ann.text, - showarrow: true, - arrowhead: 2, - ax: 0, - ay: -40, - font: { - family: "monospace", - size: 12, - color: isDark ? tw.slate[50] : tw.slate[900], - }, - bgcolor: isDark ? tw.slate[800] : tw.slate[50], - bordercolor: tw.cyan[500], - borderwidth: 1, - borderpad: 4, - })), - ...(this.config.shapes ?? []) - .filter((s) => s.label) - .map((s) => { - let x = s.x0, - y = s.y0 ?? 0, - xanchor = "left", - yanchor = "bottom", - xref = "x", - yref = "y"; - if (s.type === "vline") { - y = 1; - yref = "paper"; - } else if (s.type === "hline") { - x = 1; - xref = "paper"; - xanchor = "right"; - } else if (s.type === "rect") { - x = s.x0; - y = s.y1 ?? 0; - } - return { - x, - y, - xref, - yref, - text: `${s.label}`, - showarrow: false, - xanchor, - yanchor, + annotations: isPolar + ? [] + : [ + ...(this.config.annotations ?? []).map((ann) => ({ + x: ann.x, + y: ann.y, + text: ann.text, + showarrow: true, + arrowhead: 2, + ax: 0, + ay: -40, font: { - size: 10, - color: s.color || tw.cyan[500], family: "monospace", + size: 12, + color: isDark ? tw.slate[50] : tw.slate[900], }, - bgcolor: isDark ? tw.slate[900] + "B3" : tw.slate[50] + "B3", - borderpad: 2, + bgcolor: isDark ? tw.slate[800] : tw.slate[50], + bordercolor: tw.cyan[500], + borderwidth: 1, + borderpad: 4, + })), + ...(this.config.shapes ?? []) + .filter((s) => s.label) + .map((s) => { + let x = s.x0, + y = s.y0 ?? 0, + xanchor = "left", + yanchor = "bottom", + xref = "x", + yref = "y"; + if (s.type === "vline") { + y = 1; + yref = "paper"; + } else if (s.type === "hline") { + x = 1; + xref = "paper"; + xanchor = "right"; + } else if (s.type === "rect") { + x = s.x0; + y = s.y1 ?? 0; + } + return { + x, + y, + xref, + yref, + text: `${s.label}`, + showarrow: false, + xanchor, + yanchor, + font: { + size: 10, + color: s.color || tw.cyan[500], + family: "monospace", + }, + bgcolor: isDark + ? tw.slate[900] + "B3" + : tw.slate[50] + "B3", + borderpad: 2, + }; + }), + ], + shapes: isPolar + ? [] + : (this.config.shapes ?? []).map((s) => { + const shapeColor = s.color || tw.cyan[500]; + const base = { + line: { color: shapeColor, width: 2, dash: s.dash ?? "solid" }, + layer: "below", }; + if (s.type === "vline") + return { + ...base, + type: "line", + x0: s.x0, + x1: s.x0, + y0: 0, + y1: 1, + yref: "paper", + }; + if (s.type === "hline") + return { + ...base, + type: "line", + y0: s.y0, + y1: s.y0, + x0: 0, + x1: 1, + xref: "paper", + }; + if (s.type === "rect") + return { + ...base, + type: "rect", + x0: s.x0, + x1: s.x1, + y0: s.y0, + y1: s.y1, + fillcolor: isDark ? `${shapeColor}1A` : `${shapeColor}26`, + line: { ...base.line, width: 1 }, + }; + return base; }), - ], - shapes: isPolar ? [] : (this.config.shapes ?? []).map((s) => { - const shapeColor = s.color || tw.cyan[500]; - const base = { - line: { color: shapeColor, width: 2, dash: s.dash ?? "solid" }, - layer: "below", - }; - if (s.type === "vline") - return { - ...base, - type: "line", - x0: s.x0, - x1: s.x0, - y0: 0, - y1: 1, - yref: "paper", - }; - if (s.type === "hline") - return { - ...base, - type: "line", - y0: s.y0, - y1: s.y0, - x0: 0, - x1: 1, - xref: "paper", - }; - if (s.type === "rect") - return { - ...base, - type: "rect", - x0: s.x0, - x1: s.x1, - y0: s.y0, - y1: s.y1, - fillcolor: isDark ? `${shapeColor}1A` : `${shapeColor}26`, - line: { ...base.line, width: 1 }, - }; - return base; - }), }; const config = { diff --git a/src/mujoco_mojo/utils/layers/dojo/templates/static/ts/src/types/global.d.ts b/src/mujoco_mojo/utils/layers/dojo/templates/static/ts/src/types/global.d.ts index 18c6ace7..c9edbc2e 100644 --- a/src/mujoco_mojo/utils/layers/dojo/templates/static/ts/src/types/global.d.ts +++ b/src/mujoco_mojo/utils/layers/dojo/templates/static/ts/src/types/global.d.ts @@ -1,12 +1,22 @@ -import type { Alpine as AlpineType } from 'alpinejs'; +import type { Alpine as AlpineType } from "alpinejs"; declare global { const Alpine: AlpineType; // Minimal Plotly surface used by trial-viewer const Plotly: { - react(el: string | HTMLElement, data: object[], layout: object, config?: object): Promise; - newPlot(el: string | HTMLElement, data: object[], layout: object, config?: object): Promise; + react( + el: string | HTMLElement, + data: object[], + layout: object, + config?: object, + ): Promise; + newPlot( + el: string | HTMLElement, + data: object[], + layout: object, + config?: object, + ): Promise; purge(el: string | HTMLElement): void; relayout(el: string | HTMLElement, update: object): Promise; toImage(el: string | HTMLElement, opts: object): Promise; @@ -39,9 +49,21 @@ declare global { }; const confetti: ((opts: object) => void) & { - shapeFromText(opts: { text: string; scalar?: number; color?: string }): unknown; + shapeFromText(opts: { + text: string; + scalar?: number; + color?: string; + }): unknown; }; + // CodeMirror 6 bundle (window.CM) + const CM: typeof import("codemirror") & + typeof import("@codemirror/lang-json") & + typeof import("@codemirror/theme-one-dark") & + typeof import("@codemirror/state") & + typeof import("@codemirror/lint") & + typeof import("@codemirror/language"); + // Globals exposed by the compiled bundles for Alpine x-data usage interface Window { formatTimeAgo(seconds: number): string; @@ -49,12 +71,19 @@ declare global { trialViewer(trialId: string, externalUrl: string): object; monitor(): object; mosaic(): object; + // Signal Lab - defined in _signal_lab.html, called from trial-viewer.ts + mojoLabSelectNodeColumn?(nodeId: number, col: string): void; + mojoLabUndo?(): void; + mojoLabRedo?(): void; } } // Alpine magic properties injected at runtime into component `this` export interface AlpineMagics { $nextTick(callback?: () => void): Promise; - $watch(expr: string, callback: (value: T, oldValue: T) => void): () => void; + $watch( + expr: string, + callback: (value: T, oldValue: T) => void, + ): () => void; $refs: Readonly>; } diff --git a/src/mujoco_mojo/utils/layers/dojo/templates/static/vendored/codemirror.bundle.js b/src/mujoco_mojo/utils/layers/dojo/templates/static/vendored/codemirror.bundle.js new file mode 100644 index 00000000..8f20590c --- /dev/null +++ b/src/mujoco_mojo/utils/layers/dojo/templates/static/vendored/codemirror.bundle.js @@ -0,0 +1,12 @@ +"use strict";var CM=(()=>{var cr=Object.defineProperty;var cd=Object.getOwnPropertyDescriptor;var fd=Object.getOwnPropertyNames;var ud=Object.prototype.hasOwnProperty;var dd=(n,e)=>{for(var t in e)cr(n,t,{get:e[t],enumerable:!0})},pd=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of fd(e))!ud.call(n,s)&&s!==t&&cr(n,s,{get:()=>e[s],enumerable:!(i=cd(e,s))||i.enumerable});return n};var md=n=>pd(cr({},"__esModule",{value:!0}),n);var uy={};dd(uy,{Compartment:()=>ii,EditorState:()=>$,EditorView:()=>T,basicSetup:()=>Xu,defaultHighlightStyle:()=>Ps,json:()=>rd,jsonParseLinter:()=>sd,lintGutter:()=>Yu,linter:()=>qu,oneDarkHighlightStyle:()=>hd,syntaxHighlighting:()=>fn});var ur=[],ga=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(n=ga[i])e=i+1;else return!0;if(e==t)return!1}}function da(n){return n>=127462&&n<=127487}var pa=8205;function ba(n,e,t=!0,i=!0){return(t?ya:bd)(n,e,i)}function ya(n,e,t){if(e==n.length)return e;e&&xa(n.charCodeAt(e))&&wa(n.charCodeAt(e-1))&&e--;let i=fr(n,e);for(e+=ma(i);e=0&&da(fr(n,o));)r++,o-=2;if(r%2==0)break;e+=2}else break}return e}function bd(n,e,t){for(;e>0;){let i=ya(n,e-2,t);if(i=56320&&n<57344}function wa(n){return n>=55296&&n<56320}function ma(n){return n<65536?1:2}var N=class n{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=ti(this,e,t);let s=[];return this.decompose(0,e,s,2),i.length&&i.decompose(0,i.length,s,3),this.decompose(t,this.length,s,1),Jt.from(s,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ti(this,e,t);let i=[];return this.decompose(e,t,i,0),Jt.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),s=new Bt(this),r=new Bt(e);for(let o=t,l=t;;){if(s.next(o),r.next(o),o=0,s.lineBreak!=r.lineBreak||s.done!=r.done||s.value!=r.value)return!1;if(l+=s.value.length,s.done||l>=i)return!0}}iter(e=1){return new Bt(this,e)}iterRange(e,t=this.length){return new Mn(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let s=this.line(e).from;i=this.iterRange(s,Math.max(s,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Tn(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?n.empty:e.length<=32?new Ce(e):Jt.from(Ce.split(e,[]))}},Ce=class n extends N{constructor(e,t=yd(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,s){for(let r=0;;r++){let o=this.text[r],l=s+o.length;if((t?i:l)>=e)return new pr(s,l,i,o);s=l+1,i++}}decompose(e,t,i,s){let r=e<=0&&t>=this.length?this:new n(ka(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(s&1){let o=i.pop(),l=An(r.text,o.text.slice(),0,r.length);if(l.length<=32)i.push(new n(l,o.length+r.length));else{let a=l.length>>1;i.push(new n(l.slice(0,a)),new n(l.slice(a)))}}else i.push(r)}replace(e,t,i){if(!(i instanceof n))return super.replace(e,t,i);[e,t]=ti(this,e,t);let s=An(this.text,An(i.text,ka(this.text,0,e)),t),r=this.length+i.length-(t-e);return s.length<=32?new n(s,r):Jt.from(n.split(s,[]),r)}sliceString(e,t=this.length,i=` +`){[e,t]=ti(this,e,t);let s="";for(let r=0,o=0;r<=t&&oe&&o&&(s+=i),er&&(s+=l.slice(Math.max(0,e-r),t-r)),r=a+1}return s}flatten(e){for(let t of this.text)e.push(t)}scanIdentical(){return 0}static split(e,t){let i=[],s=-1;for(let r of e)i.push(r),s+=r.length+1,i.length==32&&(t.push(new n(i,s)),i=[],s=-1);return s>-1&&t.push(new n(i,s)),t}},Jt=class n extends N{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let i of e)this.lines+=i.lines}lineInner(e,t,i,s){for(let r=0;;r++){let o=this.children[r],l=s+o.length,a=i+o.lines-1;if((t?a:l)>=e)return o.lineInner(e,t,i,s);s=l+1,i=a+1}}decompose(e,t,i,s){for(let r=0,o=0;o<=t&&r=o){let h=s&((o<=e?1:0)|(a>=t?2:0));o>=e&&a<=t&&!h?i.push(l):l.decompose(e-o,t-o,i,h)}o=a+1}}replace(e,t,i){if([e,t]=ti(this,e,t),i.lines=r&&t<=l){let a=o.replace(e-r,t-r,i),h=this.lines-o.lines+a.lines;if(a.lines>4&&a.lines>h>>6){let c=this.children.slice();return c[s]=a,new n(c,this.length-(t-e)+i.length)}return super.replace(r,l,a)}r=l+1}return super.replace(e,t,i)}sliceString(e,t=this.length,i=` +`){[e,t]=ti(this,e,t);let s="";for(let r=0,o=0;re&&r&&(s+=i),eo&&(s+=l.sliceString(e-o,t-o,i)),o=a+1}return s}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(e,t){if(!(e instanceof n))return 0;let i=0,[s,r,o,l]=t>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;s+=t,r+=t){if(s==o||r==l)return i;let a=this.children[s],h=e.children[r];if(a!=h)return i+a.scanIdentical(h,t);i+=a.length+1}}static from(e,t=e.reduce((i,s)=>i+s.length+1,-1)){let i=0;for(let d of e)i+=d.lines;if(i<32){let d=[];for(let p of e)p.flatten(d);return new Ce(d,t)}let s=Math.max(32,i>>5),r=s<<1,o=s>>1,l=[],a=0,h=-1,c=[];function f(d){let p;if(d.lines>r&&d instanceof n)for(let m of d.children)f(m);else d.lines>o&&(a>o||!a)?(u(),l.push(d)):d instanceof Ce&&a&&(p=c[c.length-1])instanceof Ce&&d.lines+p.lines<=32?(a+=d.lines,h+=d.length+1,c[c.length-1]=new Ce(p.text.concat(d.text),p.length+1+d.length)):(a+d.lines>s&&u(),a+=d.lines,h+=d.length+1,c.push(d))}function u(){a!=0&&(l.push(c.length==1?c[0]:n.from(c,h)),h=-1,a=c.length=0)}for(let d of e)f(d);return u(),l.length==1?l[0]:new n(l,t)}};N.empty=new Ce([""],0);function yd(n){let e=-1;for(let t of n)e+=t.length+1;return e}function An(n,e,t=0,i=1e9){for(let s=0,r=0,o=!0;r=t&&(a>i&&(l=l.slice(0,i-s)),s0?1:(e instanceof Ce?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let i=this.nodes.length-1,s=this.nodes[i],r=this.offsets[i],o=r>>1,l=s instanceof Ce?s.text.length:s.children.length;if(o==(t>0?l:0)){if(i==0)return this.done=!0,this.value="",this;t>0&&this.offsets[i-1]++,this.nodes.pop(),this.offsets.pop()}else if((r&1)==(t>0?0:1)){if(this.offsets[i]+=t,e==0)return this.lineBreak=!0,this.value=` +`,this;e--}else if(s instanceof Ce){let a=s.text[o+(t<0?-1:0)];if(this.offsets[i]+=t,a.length>Math.max(0,e))return this.value=e==0?a:t>0?a.slice(e):a.slice(0,a.length-e),this;e-=a.length}else{let a=s.children[o+(t<0?-1:0)];e>a.length?(e-=a.length,this.offsets[i]+=t):(t<0&&this.offsets[i]--,this.nodes.push(a),this.offsets.push(t>0?1:(a instanceof Ce?a.text.length:a.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}},Mn=class{constructor(e,t,i){this.value="",this.done=!1,this.cursor=new Bt(e,t>i?-1:1),this.pos=t>i?e.length:0,this.from=Math.min(t,i),this.to=Math.max(t,i)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let i=t<0?this.pos-this.from:this.to-this.pos;e>i&&(e=i),i-=e;let{value:s}=this.cursor.next(e);return this.pos+=(s.length+e)*t,this.value=s.length<=i?s:t<0?s.slice(s.length-i):s.slice(0,i),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}},Tn=class{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:t,lineBreak:i,value:s}=this.inner.next(e);return t&&this.afterBreak?(this.value="",this.afterBreak=!1):t?(this.done=!0,this.value=""):i?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=s,this.afterBreak=!1),this}get lineBreak(){return!1}};typeof Symbol<"u"&&(N.prototype[Symbol.iterator]=function(){return this.iter()},Bt.prototype[Symbol.iterator]=Mn.prototype[Symbol.iterator]=Tn.prototype[Symbol.iterator]=function(){return this});var pr=class{constructor(e,t,i,s){this.from=e,this.to=t,this.number=i,this.text=s}get length(){return this.to-this.from}};function ti(n,e,t){return e=Math.max(0,Math.min(n.length,e)),[e,Math.max(e,Math.min(n.length,t))]}function ee(n,e,t=!0,i=!0){return ba(n,e,t,i)}function xd(n){return n>=56320&&n<57344}function wd(n){return n>=55296&&n<56320}function ae(n,e){let t=n.charCodeAt(e);if(!wd(t)||e+1==n.length)return t;let i=n.charCodeAt(e+1);return xd(i)?(t-55296<<10)+(i-56320)+65536:t}function Ri(n){return n<=65535?String.fromCharCode(n):(n-=65536,String.fromCharCode((n>>10)+55296,(n&1023)+56320))}function Me(n){return n<65536?1:2}var mr=/\r\n?|\n/,le=(function(n){return n[n.Simple=0]="Simple",n[n.TrackDel=1]="TrackDel",n[n.TrackBefore=2]="TrackBefore",n[n.TrackAfter=3]="TrackAfter",n})(le||(le={})),ot=class n{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;te)return r+(e-s);r+=l}else{if(i!=le.Simple&&h>=e&&(i==le.TrackDel&&se||i==le.TrackBefore&&se))return null;if(h>e||h==e&&t<0&&!l)return e==s||t<0?r:r+a;r+=a}s=h}if(e>s)throw new RangeError(`Position ${e} is out of range for changeset of length ${s}`);return r}touchesRange(e,t=e){for(let i=0,s=0;i=0&&s<=t&&l>=e)return st?"cover":!0;s=l}return!1}toString(){let e="";for(let t=0;t=0?":"+s:"")}return e}toJSON(){return this.sections}static fromJSON(e){if(!Array.isArray(e)||e.length%2||e.some(t=>typeof t!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new n(e)}static create(e){return new n(e)}},me=class n extends ot{constructor(e,t){super(e),this.inserted=t}apply(e){if(this.length!=e.length)throw new RangeError("Applying change set to a document with the wrong length");return gr(this,(t,i,s,r,o)=>e=e.replace(s,s+(i-t),o),!1),e}mapDesc(e,t=!1){return br(this,e,t,!0)}invert(e){let t=this.sections.slice(),i=[];for(let s=0,r=0;s=0){t[s]=l,t[s+1]=o;let a=s>>1;for(;i.length0&&pt(i,t,r.text),r.forward(c),l+=c}let h=e[o++];for(;l>1].toJSON()))}return e}static of(e,t,i){let s=[],r=[],o=0,l=null;function a(c=!1){if(!c&&!s.length)return;ou||f<0||u>t)throw new RangeError(`Invalid change range ${f} to ${u} (in doc of length ${t})`);let p=d?typeof d=="string"?N.of(d.split(i||mr)):d:N.empty,m=p.length;if(f==u&&m==0)return;fo&&fe(s,f-o,-1),fe(s,u-f,m),pt(r,s,p),o=u}}return h(e),a(!l),l}static empty(e){return new n(e?[e,-1]:[],[])}static fromJSON(e){if(!Array.isArray(e))throw new RangeError("Invalid JSON representation of ChangeSet");let t=[],i=[];for(let s=0;sl&&typeof o!="string"))throw new RangeError("Invalid JSON representation of ChangeSet");if(r.length==1)t.push(r[0],0);else{for(;i.length=0&&t<=0&&t==n[s+1]?n[s]+=e:s>=0&&e==0&&n[s]==0?n[s+1]+=t:i?(n[s]+=e,n[s+1]+=t):n.push(e,t)}function pt(n,e,t){if(t.length==0)return;let i=e.length-2>>1;if(i>1])),!(t||o==n.sections.length||n.sections[o+1]<0);)l=n.sections[o++],a=n.sections[o++];e(s,h,r,c,f),s=h,r=c}}}function br(n,e,t,i=!1){let s=[],r=i?[]:null,o=new Rt(n),l=new Rt(e);for(let a=-1;;){if(o.done&&l.len||l.done&&o.len)throw new Error("Mismatched change set lengths");if(o.ins==-1&&l.ins==-1){let h=Math.min(o.len,l.len);fe(s,h,-1),o.forward(h),l.forward(h)}else if(l.ins>=0&&(o.ins<0||a==o.i||o.off==0&&(l.len=0&&a=0){let h=0,c=o.len;for(;c;)if(l.ins==-1){let f=Math.min(c,l.len);h+=f,c-=f,l.forward(f)}else if(l.ins==0&&l.lena||o.ins>=0&&o.len>a)&&(l||i.length>h),r.forward2(a),o.forward(a)}}}}var Rt=class{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i>1;return t>=e.length?N.empty:e[t]}textBit(e){let{inserted:t}=this.set,i=this.i-2>>1;return i>=t.length&&!e?N.empty:t[i].slice(this.off,e==null?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){this.ins==-1?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}},Qt=class n{constructor(e,t,i){this.from=e,this.to=t,this.flags=i}get anchor(){return this.flags&32?this.to:this.from}get head(){return this.flags&32?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&8?-1:this.flags&16?1:0}get bidiLevel(){let e=this.flags&7;return e==7?null:e}get goalColumn(){let e=this.flags>>6;return e==16777215?void 0:e}map(e,t=-1){let i,s;return this.empty?i=s=e.mapPos(this.from,t):(i=e.mapPos(this.from,1),s=e.mapPos(this.to,-1)),i==this.from&&s==this.to?this:new n(i,s,this.flags)}extend(e,t=e,i=0){if(e<=this.anchor&&t>=this.anchor)return x.range(e,t,void 0,void 0,i);let s=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return x.range(this.anchor,s,void 0,void 0,i)}eq(e,t=!1){return this.anchor==e.anchor&&this.head==e.head&&this.goalColumn==e.goalColumn&&(!t||!this.empty||this.assoc==e.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||typeof e.anchor!="number"||typeof e.head!="number")throw new RangeError("Invalid JSON representation for SelectionRange");return x.range(e.anchor,e.head)}static create(e,t,i){return new n(e,t,i)}},x=class n{constructor(e,t){this.ranges=e,this.mainIndex=t}map(e,t=-1){return e.empty?this:n.create(this.ranges.map(i=>i.map(e,t)),this.mainIndex)}eq(e,t=!1){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let i=0;ie.toJSON()),main:this.mainIndex}}static fromJSON(e){if(!e||!Array.isArray(e.ranges)||typeof e.main!="number"||e.main>=e.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new n(e.ranges.map(t=>Qt.fromJSON(t)),e.main)}static single(e,t=e){return new n([n.range(e,t)],0)}static create(e,t=0){if(e.length==0)throw new RangeError("A selection needs at least one range");for(let i=0,s=0;ss.from-r.from),t=e.indexOf(i);for(let s=1;sr.head?n.range(a,l):n.range(l,a))}}return new n(e,t)}};function Ta(n,e){for(let t of n.ranges)if(t.to>e)throw new RangeError("Selection points outside of document")}var Tr=0,A=class n{constructor(e,t,i,s,r){this.combine=e,this.compareInput=t,this.compare=i,this.isStatic=s,this.id=Tr++,this.default=e([]),this.extensions=typeof r=="function"?r(this):r}get reader(){return this}static define(e={}){return new n(e.combine||(t=>t),e.compareInput||((t,i)=>t===i),e.compare||(e.combine?(t,i)=>t===i:Or),!!e.static,e.enables)}of(e){return new Zt([],this,0,e)}compute(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Zt(e,this,1,t)}computeN(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Zt(e,this,2,t)}from(e,t){return t||(t=i=>i),this.compute([e],i=>t(i.field(e)))}};function Or(n,e){return n==e||n.length==e.length&&n.every((t,i)=>t===e[i])}var Zt=class{constructor(e,t,i,s){this.dependencies=e,this.facet=t,this.type=i,this.value=s,this.id=Tr++}dynamicSlot(e){var t;let i=this.value,s=this.facet.compareInput,r=this.id,o=e[r]>>1,l=this.type==2,a=!1,h=!1,c=[];for(let f of this.dependencies)f=="doc"?a=!0:f=="selection"?h=!0:(((t=e[f.id])!==null&&t!==void 0?t:1)&1)==0&&c.push(e[f.id]);return{create(f){return f.values[o]=i(f),1},update(f,u){if(a&&u.docChanged||h&&(u.docChanged||u.selection)||yr(f,c)){let d=i(f);if(l?!va(d,f.values[o],s):!s(d,f.values[o]))return f.values[o]=d,1}return 0},reconfigure:(f,u)=>{let d,p=u.config.address[r];if(p!=null){let m=Pn(u,p);if(this.dependencies.every(g=>g instanceof A?u.facet(g)===f.facet(g):g instanceof X?u.field(g,!1)==f.field(g,!1):!0)||(l?va(d=i(f),m,s):s(d=i(f),m)))return f.values[o]=m,0}else d=i(f);return f.values[o]=d,1}}}};function va(n,e,t){if(n.length!=e.length)return!1;for(let i=0;in[a.id]),s=t.map(a=>a.type),r=i.filter(a=>!(a&1)),o=n[e.id]>>1;function l(a){let h=[];for(let c=0;ci===s),e);return e.provide&&(t.provides=e.provide(t)),t}create(e){let t=e.facet(vn).find(i=>i.field==this);return(t?.create||this.createF)(e)}slot(e){let t=e[this.id]>>1;return{create:i=>(i.values[t]=this.create(i),1),update:(i,s)=>{let r=i.values[t],o=this.updateF(r,s);return this.compareF(r,o)?0:(i.values[t]=o,1)},reconfigure:(i,s)=>{let r=i.facet(vn),o=s.facet(vn),l;return(l=r.find(a=>a.field==this))&&l!=o.find(a=>a.field==this)?(i.values[t]=l.create(i),1):s.config.address[this.id]!=null?(i.values[t]=s.field(this),0):(i.values[t]=this.create(i),1)}}}init(e){return[this,vn.of({field:this,create:e})]}get extension(){return this}},Dt={lowest:4,low:3,default:2,high:1,highest:0};function Ti(n){return e=>new On(e,n)}var ze={highest:Ti(Dt.highest),high:Ti(Dt.high),default:Ti(Dt.default),low:Ti(Dt.low),lowest:Ti(Dt.lowest)},On=class{constructor(e,t){this.inner=e,this.prec=t}},ii=class n{of(e){return new Di(this,e)}reconfigure(e){return n.reconfigure.of({compartment:this,extension:e})}get(e){return e.config.compartments.get(this)}},Di=class{constructor(e,t){this.compartment=e,this.inner=t}},Dn=class n{constructor(e,t,i,s,r,o){for(this.base=e,this.compartments=t,this.dynamicSlots=i,this.address=s,this.staticValues=r,this.facets=o,this.statusTemplate=[];this.statusTemplate.length>1]}static resolve(e,t,i){let s=[],r=Object.create(null),o=new Map;for(let u of vd(e,t,o))u instanceof X?s.push(u):(r[u.facet.id]||(r[u.facet.id]=[])).push(u);let l=Object.create(null),a=[],h=[];for(let u of s)l[u.id]=h.length<<1,h.push(d=>u.slot(d));let c=i?.config.facets;for(let u in r){let d=r[u],p=d[0].facet,m=c&&c[u]||[];if(d.every(g=>g.type==0))if(l[p.id]=a.length<<1|1,Or(m,d))a.push(i.facet(p));else{let g=p.combine(d.map(b=>b.value));a.push(i&&p.compare(g,i.facet(p))?i.facet(p):g)}else{for(let g of d)g.type==0?(l[g.id]=a.length<<1|1,a.push(g.value)):(l[g.id]=h.length<<1,h.push(b=>g.dynamicSlot(b)));l[p.id]=h.length<<1,h.push(g=>kd(g,p,d))}}let f=h.map(u=>u(l));return new n(e,o,f,l,a,r)}};function vd(n,e,t){let i=[[],[],[],[],[]],s=new Map;function r(o,l){let a=s.get(o);if(a!=null){if(a<=l)return;let h=i[a].indexOf(o);h>-1&&i[a].splice(h,1),o instanceof Di&&t.delete(o.compartment)}if(s.set(o,l),Array.isArray(o))for(let h of o)r(h,l);else if(o instanceof Di){if(t.has(o.compartment))throw new RangeError("Duplicate use of compartment in extensions");let h=e.get(o.compartment)||o.inner;t.set(o.compartment,h),r(h,l)}else if(o instanceof On)r(o.inner,o.prec);else if(o instanceof X)i[l].push(o),o.provides&&r(o.provides,l);else if(o instanceof Zt)i[l].push(o),o.facet.extensions&&r(o.facet.extensions,Dt.default);else{let h=o.extension;if(!h)throw new Error(`Unrecognized extension value in extension set (${o}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);r(h,l)}}return r(n,Dt.default),i.reduce((o,l)=>o.concat(l))}function Oi(n,e){if(e&1)return 2;let t=e>>1,i=n.status[t];if(i==4)throw new Error("Cyclic dependency between fields and/or facets");if(i&2)return i;n.status[t]=4;let s=n.computeSlot(n,n.config.dynamicSlots[t]);return n.status[t]=2|s}function Pn(n,e){return e&1?n.config.staticValues[e>>1]:n.values[e>>1]}var Oa=A.define(),xr=A.define({combine:n=>n.some(e=>e),static:!0}),Da=A.define({combine:n=>n.length?n[0]:void 0,static:!0}),Pa=A.define(),Ba=A.define(),Ra=A.define(),La=A.define({combine:n=>n.length?n[0]:!1}),be=class{constructor(e,t){this.type=e,this.value=t}static define(){return new wr}},wr=class{of(e){return new be(this,e)}},kr=class{constructor(e){this.map=e}of(e){return new R(this,e)}},R=class n{constructor(e,t){this.type=e,this.value=t}map(e){let t=this.type.map(this.value,e);return t===void 0?void 0:t==this.value?this:new n(this.type,t)}is(e){return this.type==e}static define(e={}){return new kr(e.map||(t=>t))}static mapEffects(e,t){if(!e.length)return e;let i=[];for(let s of e){let r=s.map(t);r&&i.push(r)}return i}};R.reconfigure=R.define();R.appendConfig=R.define();var ie=class n{constructor(e,t,i,s,r,o){this.startState=e,this.changes=t,this.selection=i,this.effects=s,this.annotations=r,this.scrollIntoView=o,this._doc=null,this._state=null,i&&Ta(i,t.newLength),r.some(l=>l.type==n.time)||(this.annotations=r.concat(n.time.of(Date.now())))}static create(e,t,i,s,r,o){return new n(e,t,i,s,r,o)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let t of this.annotations)if(t.type==e)return t.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(e){let t=this.annotation(n.userEvent);return!!(t&&(t==e||t.length>e.length&&t.slice(0,e.length)==e&&t[e.length]=="."))}};ie.time=be.define();ie.userEvent=be.define();ie.addToHistory=be.define();ie.remote=be.define();function Sd(n,e){let t=[];for(let i=0,s=0;;){let r,o;if(i=n[i]))r=n[i++],o=n[i++];else if(s=0;s--){let r=i[s](n);r instanceof ie?n=r:Array.isArray(r)&&r.length==1&&r[0]instanceof ie?n=r[0]:n=Ia(e,ei(r),!1)}return n}function Ad(n){let e=n.startState,t=e.facet(Ra),i=n;for(let s=t.length-1;s>=0;s--){let r=t[s](n);r&&Object.keys(r).length&&(i=Ea(i,vr(e,r,n.changes.newLength),!0))}return i==n?n:ie.create(e,n.changes,n.selection,i.effects,i.annotations,i.scrollIntoView)}var Md=[];function ei(n){return n==null?Md:Array.isArray(n)?n:[n]}var K=(function(n){return n[n.Word=0]="Word",n[n.Space=1]="Space",n[n.Other=2]="Other",n})(K||(K={})),Td=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/,Sr;try{Sr=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function Od(n){if(Sr)return Sr.test(n);for(let e=0;e"\x80"&&(t.toUpperCase()!=t.toLowerCase()||Td.test(t)))return!0}return!1}function Dd(n){return e=>{if(!/\S/.test(e))return K.Space;if(Od(e))return K.Word;for(let t=0;t-1)return K.Word;return K.Other}}var $=class n{constructor(e,t,i,s,r,o){this.config=e,this.doc=t,this.selection=i,this.values=s,this.status=e.statusTemplate.slice(),this.computeSlot=r,o&&(o._state=this);for(let l=0;ls.set(h,a)),t=null),s.set(l.value.compartment,l.value.extension)):l.is(R.reconfigure)?(t=null,i=l.value):l.is(R.appendConfig)&&(t=null,i=ei(i).concat(l.value));let r;t?r=e.startState.values.slice():(t=Dn.resolve(i,s,this),r=new n(t,this.doc,this.selection,t.dynamicSlots.map(()=>null),(a,h)=>h.reconfigure(a,this),null).values);let o=e.startState.facet(xr)?e.newSelection:e.newSelection.asSingle();new n(t,e.newDoc,o,r,(l,a)=>a.update(l,e),e)}replaceSelection(e){return typeof e=="string"&&(e=this.toText(e)),this.changeByRange(t=>({changes:{from:t.from,to:t.to,insert:e},range:x.cursor(t.from+e.length)}))}changeByRange(e){let t=this.selection,i=e(t.ranges[0]),s=this.changes(i.changes),r=[i.range],o=ei(i.effects);for(let l=1;lo.spec.fromJSON(l,a)))}}return n.create({doc:e.doc,selection:x.fromJSON(e.selection),extensions:t.extensions?s.concat([t.extensions]):s})}static create(e={}){let t=Dn.resolve(e.extensions||[],new Map),i=e.doc instanceof N?e.doc:N.of((e.doc||"").split(t.staticFacet(n.lineSeparator)||mr)),s=e.selection?e.selection instanceof x?e.selection:x.single(e.selection.anchor,e.selection.head):x.single(0);return Ta(s,i.length),t.staticFacet(xr)||(s=s.asSingle()),new n(t,i,s,t.dynamicSlots.map(()=>null),(r,o)=>o.create(r),null)}get tabSize(){return this.facet(n.tabSize)}get lineBreak(){return this.facet(n.lineSeparator)||` +`}get readOnly(){return this.facet(La)}phrase(e,...t){for(let i of this.facet(n.phrases))if(Object.prototype.hasOwnProperty.call(i,e)){e=i[e];break}return t.length&&(e=e.replace(/\$(\$|\d*)/g,(i,s)=>{if(s=="$")return"$";let r=+(s||1);return!r||r>t.length?i:t[r-1]})),e}languageDataAt(e,t,i=-1){let s=[];for(let r of this.facet(Oa))for(let o of r(this,t,i))Object.prototype.hasOwnProperty.call(o,e)&&s.push(o[e]);return s}charCategorizer(e){let t=this.languageDataAt("wordChars",e);return Dd(t.length?t[0]:"")}wordAt(e){let{text:t,from:i,length:s}=this.doc.lineAt(e),r=this.charCategorizer(e),o=e-i,l=e-i;for(;o>0;){let a=ee(t,o,!1);if(r(t.slice(a,o))!=K.Word)break;o=a}for(;ln.length?n[0]:4});$.lineSeparator=Da;$.readOnly=La;$.phrases=A.define({compare(n,e){let t=Object.keys(n),i=Object.keys(e);return t.length==i.length&&t.every(s=>n[s]==e[s])}});$.languageData=Oa;$.changeFilter=Pa;$.transactionFilter=Ba;$.transactionExtender=Ra;ii.reconfigure=R.define();function he(n,e,t={}){let i={};for(let s of n)for(let r of Object.keys(s)){let o=s[r],l=i[r];if(l===void 0)i[r]=o;else if(!(l===o||o===void 0))if(Object.hasOwnProperty.call(t,r))i[r]=t[r](l,o);else throw new Error("Config merge conflict for field "+r)}for(let s in e)i[s]===void 0&&(i[s]=e[s]);return i}var Ee=class{eq(e){return this==e}range(e,t=e){return Pi.create(e,t,this)}};Ee.prototype.startSide=Ee.prototype.endSide=0;Ee.prototype.point=!1;Ee.prototype.mapMode=le.TrackDel;function Dr(n,e){return n==e||n.constructor==e.constructor&&n.eq(e)}var Pi=class n{constructor(e,t,i){this.from=e,this.to=t,this.value=i}static create(e,t,i){return new n(e,t,i)}};function Cr(n,e){return n.from-e.from||n.value.startSide-e.value.startSide}var Ar=class n{constructor(e,t,i,s){this.from=e,this.to=t,this.value=i,this.maxPoint=s}get length(){return this.to[this.to.length-1]}findIndex(e,t,i,s=0){let r=i?this.to:this.from;for(let o=s,l=r.length;;){if(o==l)return o;let a=o+l>>1,h=r[a]-e||(i?this.value[a].endSide:this.value[a].startSide)-t;if(a==o)return h>=0?o:l;h>=0?l=a:o=a+1}}between(e,t,i,s){for(let r=this.findIndex(t,-1e9,!0),o=this.findIndex(i,1e9,!1,r);rd||u==d&&h.startSide>0&&h.endSide<=0)continue;(d-u||h.endSide-h.startSide)<0||(o<0&&(o=u),h.point&&(l=Math.max(l,d-u)),i.push(h),s.push(u-o),r.push(d-o))}return{mapped:i.length?new n(s,r,i,l):null,pos:o}}},F=class n{constructor(e,t,i,s){this.chunkPos=e,this.chunk=t,this.nextLayer=i,this.maxPoint=s}static create(e,t,i,s){return new n(e,t,i,s)}get length(){let e=this.chunk.length-1;return e<0?0:Math.max(this.chunkEnd(e),this.nextLayer.length)}get size(){if(this.isEmpty)return 0;let e=this.nextLayer.size;for(let t of this.chunk)e+=t.value.length;return e}chunkEnd(e){return this.chunkPos[e]+this.chunk[e].length}update(e){let{add:t=[],sort:i=!1,filterFrom:s=0,filterTo:r=this.length}=e,o=e.filter;if(t.length==0&&!o)return this;if(i&&(t=t.slice().sort(Cr)),this.isEmpty)return t.length?n.of(t):this;let l=new Bn(this,null,-1).goto(0),a=0,h=[],c=new Ae;for(;l.value||a=0){let f=t[a++];c.addInner(f.from,f.to,f.value)||h.push(f)}else l.rangeIndex==1&&l.chunkIndexthis.chunkEnd(l.chunkIndex)||rl.to||r=r&&e<=r+o.length&&o.between(r,e-r,t-r,i)===!1)return}this.nextLayer.between(e,t,i)}}iter(e=0){return Bi.from([this]).goto(e)}get isEmpty(){return this.nextLayer==this}static iter(e,t=0){return Bi.from(e).goto(t)}static compare(e,t,i,s,r=-1){let o=e.filter(f=>f.maxPoint>0||!f.isEmpty&&f.maxPoint>=r),l=t.filter(f=>f.maxPoint>0||!f.isEmpty&&f.maxPoint>=r),a=Sa(o,l,i),h=new Pt(o,a,r),c=new Pt(l,a,r);i.iterGaps((f,u,d)=>Ca(h,f,c,u,d,s)),i.empty&&i.length==0&&Ca(h,0,c,0,0,s)}static eq(e,t,i=0,s){s==null&&(s=999999999);let r=e.filter(c=>!c.isEmpty&&t.indexOf(c)<0),o=t.filter(c=>!c.isEmpty&&e.indexOf(c)<0);if(r.length!=o.length)return!1;if(!r.length)return!0;let l=Sa(r,o),a=new Pt(r,l,0).goto(i),h=new Pt(o,l,0).goto(i);for(;;){if(a.to!=h.to||!Mr(a.active,h.active)||a.point&&(!h.point||!Dr(a.point,h.point)))return!1;if(a.to>s)return!0;a.next(),h.next()}}static spans(e,t,i,s,r=-1){let o=new Pt(e,null,r).goto(t),l=t,a=o.openStart;for(;;){let h=Math.min(o.to,i);if(o.point){let c=o.activeForPoint(o.to),f=o.pointFroml&&(s.span(l,h,o.active,a),a=o.openEnd(h));if(o.to>i)return a+(o.point&&o.to>i?1:0);l=o.to,o.next()}}static of(e,t=!1){let i=new Ae;for(let s of e instanceof Pi?[e]:t?Pd(e):e)i.add(s.from,s.to,s.value);return i.finish()}static join(e){if(!e.length)return n.empty;let t=e[e.length-1];for(let i=e.length-2;i>=0;i--)for(let s=e[i];s!=n.empty;s=s.nextLayer)t=new n(s.chunkPos,s.chunk,t,Math.max(s.maxPoint,t.maxPoint));return t}};F.empty=new F([],[],null,-1);function Pd(n){if(n.length>1)for(let e=n[0],t=1;t0)return n.slice().sort(Cr);e=i}return n}F.empty.nextLayer=F.empty;var Ae=class n{finishChunk(e){this.chunks.push(new Ar(this.from,this.to,this.value,this.maxPoint)),this.chunkPos.push(this.chunkStart),this.chunkStart=-1,this.setMaxPoint=Math.max(this.setMaxPoint,this.maxPoint),this.maxPoint=-1,e&&(this.from=[],this.to=[],this.value=[])}constructor(){this.chunks=[],this.chunkPos=[],this.chunkStart=-1,this.last=null,this.lastFrom=-1e9,this.lastTo=-1e9,this.from=[],this.to=[],this.value=[],this.maxPoint=-1,this.setMaxPoint=-1,this.nextLayer=null}add(e,t,i){this.addInner(e,t,i)||(this.nextLayer||(this.nextLayer=new n)).add(e,t,i)}addInner(e,t,i){let s=e-this.lastTo||i.startSide-this.last.endSide;if(s<=0&&(e-this.lastFrom||i.startSide-this.last.startSide)<0)throw new Error("Ranges must be added sorted by `from` position and `startSide`");return s<0?!1:(this.from.length==250&&this.finishChunk(!0),this.chunkStart<0&&(this.chunkStart=e),this.from.push(e-this.chunkStart),this.to.push(t-this.chunkStart),this.last=i,this.lastFrom=e,this.lastTo=t,this.value.push(i),i.point&&(this.maxPoint=Math.max(this.maxPoint,t-e)),!0)}addChunk(e,t){if((e-this.lastTo||t.value[0].startSide-this.last.endSide)<0)return!1;this.from.length&&this.finishChunk(!0),this.setMaxPoint=Math.max(this.setMaxPoint,t.maxPoint),this.chunks.push(t),this.chunkPos.push(e);let i=t.value.length-1;return this.last=t.value[i],this.lastFrom=t.from[i]+e,this.lastTo=t.to[i]+e,!0}finish(){return this.finishInner(F.empty)}finishInner(e){if(this.from.length&&this.finishChunk(!1),this.chunks.length==0)return e;let t=F.create(this.chunkPos,this.chunks,this.nextLayer?this.nextLayer.finishInner(e):e,this.setMaxPoint);return this.from=null,t}};function Sa(n,e,t){let i=new Map;for(let r of n)for(let o=0;o=this.minPoint)break}}setRangeIndex(e){if(e==this.layer.chunk[this.chunkIndex].value.length){if(this.chunkIndex++,this.skip)for(;this.chunkIndex=i&&s.push(new Bn(o,t,i,r));return s.length==1?s[0]:new n(s)}get startSide(){return this.value?this.value.startSide:0}goto(e,t=-1e9){for(let i of this.heap)i.goto(e,t);for(let i=this.heap.length>>1;i>=0;i--)dr(this.heap,i);return this.next(),this}forward(e,t){for(let i of this.heap)i.forward(e,t);for(let i=this.heap.length>>1;i>=0;i--)dr(this.heap,i);(this.to-e||this.value.endSide-t)<0&&this.next()}next(){if(this.heap.length==0)this.from=this.to=1e9,this.value=null,this.rank=-1;else{let e=this.heap[0];this.from=e.from,this.to=e.to,this.value=e.value,this.rank=e.rank,e.value&&e.next(),dr(this.heap,0)}}};function dr(n,e){for(let t=n[e];;){let i=(e<<1)+1;if(i>=n.length)break;let s=n[i];if(i+1=0&&(s=n[i+1],i++),t.compare(s)<0)break;n[i]=t,n[e]=s,e=i}}var Pt=class{constructor(e,t,i){this.minPoint=i,this.active=[],this.activeTo=[],this.activeRank=[],this.minActive=-1,this.point=null,this.pointFrom=0,this.pointRank=0,this.to=-1e9,this.endSide=0,this.openStart=-1,this.cursor=Bi.from(e,t,i)}goto(e,t=-1e9){return this.cursor.goto(e,t),this.active.length=this.activeTo.length=this.activeRank.length=0,this.minActive=-1,this.to=e,this.endSide=t,this.openStart=-1,this.next(),this}forward(e,t){for(;this.minActive>-1&&(this.activeTo[this.minActive]-e||this.active[this.minActive].endSide-t)<0;)this.removeActive(this.minActive);this.cursor.forward(e,t)}removeActive(e){Sn(this.active,e),Sn(this.activeTo,e),Sn(this.activeRank,e),this.minActive=Aa(this.active,this.activeTo)}addActive(e){let t=0,{value:i,to:s,rank:r}=this.cursor;for(;t0;)t++;Cn(this.active,t,i),Cn(this.activeTo,t,s),Cn(this.activeRank,t,r),e&&Cn(e,t,this.cursor.from),this.minActive=Aa(this.active,this.activeTo)}next(){let e=this.to,t=this.point;this.point=null;let i=this.openStart<0?[]:null;for(;;){let s=this.minActive;if(s>-1&&(this.activeTo[s]-this.cursor.from||this.active[s].endSide-this.cursor.startSide)<0){if(this.activeTo[s]>e){this.to=this.activeTo[s],this.endSide=this.active[s].endSide;break}this.removeActive(s),i&&Sn(i,s)}else if(this.cursor.value)if(this.cursor.from>e){this.to=this.cursor.from,this.endSide=this.cursor.startSide;break}else{let r=this.cursor.value;if(!r.point)this.addActive(i),this.cursor.next();else if(t&&this.cursor.to==this.to&&this.cursor.from=0&&i[s]=0&&!(this.activeRank[i]e||this.activeTo[i]==e&&this.active[i].endSide>=this.point.endSide)&&t.push(this.active[i]);return t.reverse()}openEnd(e){let t=0;for(let i=this.activeTo.length-1;i>=0&&this.activeTo[i]>e;i--)t++;return t}};function Ca(n,e,t,i,s,r){n.goto(e),t.goto(i);let o=i+s,l=i,a=i-e,h=!!r.boundChange;for(let c=!1;;){let f=n.to+a-t.to,u=f||n.endSide-t.endSide,d=u<0?n.to+a:t.to,p=Math.min(d,o);if(n.point||t.point?(n.point&&t.point&&Dr(n.point,t.point)&&Mr(n.activeForPoint(n.to),t.activeForPoint(t.to))||r.comparePoint(l,p,n.point,t.point),c=!1):(c&&r.boundChange(l),p>l&&!Mr(n.active,t.active)&&r.compareRange(l,p,n.active,t.active),h&&po)break;l=d,u<=0&&n.next(),u>=0&&t.next()}}function Mr(n,e){if(n.length!=e.length)return!1;for(let t=0;t=e;i--)n[i+1]=n[i];n[e]=t}function Aa(n,e){let t=-1,i=1e9;for(let s=0;s=e)return s;if(s==n.length)break;r+=n.charCodeAt(s)==9?t-r%t:1,s=ee(n,s)}return i===!0?-1:n.length}var Na=typeof Symbol>"u"?"__\u037C":Symbol.for("\u037C"),Pr=typeof Symbol>"u"?"__styleSet"+Math.floor(Math.random()*1e8):Symbol("styleSet"),Fa=typeof globalThis<"u"?globalThis:typeof window<"u"?window:{},Ie=class{constructor(e,t){this.rules=[];let{finish:i}=t||{};function s(o){return/^@/.test(o)?[o]:o.split(/,\s*/)}function r(o,l,a,h){let c=[],f=/^@(\w+)\b/.exec(o[0]),u=f&&f[1]=="keyframes";if(f&&l==null)return a.push(o[0]+";");for(let d in l){let p=l[d];if(/&/.test(d))r(d.split(/,\s*/).map(m=>o.map(g=>m.replace(/&/,g))).reduce((m,g)=>m.concat(g)),p,a);else if(p&&typeof p=="object"){if(!f)throw new RangeError("The value of a property ("+d+") should be a primitive value.");r(s(d),p,c,u)}else p!=null&&c.push(d.replace(/_.*/,"").replace(/[A-Z]/g,m=>"-"+m.toLowerCase())+": "+p+";")}(c.length||u)&&a.push((i&&!f&&!h?o.map(i):o).join(", ")+" {"+c.join(" ")+"}")}for(let o in e)r(s(o),e[o],this.rules)}getRules(){return this.rules.join(` +`)}static newName(){let e=Fa[Na]||1;return Fa[Na]=e+1,"\u037C"+e.toString(36)}static mount(e,t,i){let s=e[Pr],r=i&&i.nonce;s?r&&s.setNonce(r):s=new Br(e,r),s.mount(Array.isArray(t)?t:[t],e)}},Wa=new Map,Br=class{constructor(e,t){let i=e.ownerDocument||e,s=i.defaultView;if(!e.head&&e.adoptedStyleSheets&&s.CSSStyleSheet){let r=Wa.get(i);if(r)return e[Pr]=r;this.sheet=new s.CSSStyleSheet,Wa.set(i,this)}else this.styleTag=i.createElement("style"),t&&this.styleTag.setAttribute("nonce",t);this.modules=[],e[Pr]=this}mount(e,t){let i=this.sheet,s=0,r=0;for(let o=0;o-1&&(this.modules.splice(a,1),r--,a=-1),a==-1){if(this.modules.splice(r++,0,l),i)for(let h=0;h",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},Bd=typeof navigator<"u"&&/Mac/.test(navigator.platform),Rd=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(te=0;te<10;te++)at[48+te]=at[96+te]=String(te);var te;for(te=1;te<=24;te++)at[te+111]="F"+te;var te;for(te=65;te<=90;te++)at[te]=String.fromCharCode(te+32),ni[te]=String.fromCharCode(te);var te;for(Ln in at)ni.hasOwnProperty(Ln)||(ni[Ln]=at[Ln]);var Ln;function Ha(n){var e=Bd&&n.metaKey&&n.shiftKey&&!n.ctrlKey&&!n.altKey||Rd&&n.shiftKey&&n.key&&n.key.length==1||n.key=="Unidentified",t=!e&&n.key||(n.shiftKey?ni:at)[n.keyCode]||n.key||"Unidentified";return t=="Esc"&&(t="Escape"),t=="Del"&&(t="Delete"),t=="Left"&&(t="ArrowLeft"),t=="Up"&&(t="ArrowUp"),t=="Right"&&(t="ArrowRight"),t=="Down"&&(t="ArrowDown"),t}function H(){var n=arguments[0];typeof n=="string"&&(n=document.createElement(n));var e=1,t=arguments[1];if(t&&typeof t=="object"&&t.nodeType==null&&!Array.isArray(t)){for(var i in t)if(Object.prototype.hasOwnProperty.call(t,i)){var s=t[i];typeof s=="string"?n.setAttribute(i,s):s!=null&&(n[i]=s)}e++}for(;e2),O={mac:$a||/Mac/.test(ge.platform),windows:/Win/.test(ge.platform),linux:/Linux|X11/.test(ge.platform),ie:us,ie_version:Ah?zr.documentMode||6:$r?+$r[1]:qr?+qr[1]:0,gecko:za,gecko_version:za?+(/Firefox\/(\d+)/.exec(ge.userAgent)||[0,0])[1]:0,chrome:!!Rr,chrome_version:Rr?+Rr[1]:0,ios:$a,android:/Android\b/.test(ge.userAgent),webkit:qa,webkit_version:qa?+(/\bAppleWebKit\/(\d+)/.exec(ge.userAgent)||[0,0])[1]:0,safari:Kr,safari_version:Kr?+(/\bVersion\/(\d+(\.\d+)?)/.exec(ge.userAgent)||[0,0])[1]:0,tabSize:zr.documentElement.style.tabSize!=null?"tab-size":"-moz-tab-size"};function Fo(n,e){for(let t in n)t=="class"&&e.class?e.class+=" "+n.class:t=="style"&&e.style?e.style+=";"+n.style:e[t]=n[t];return e}var _n=Object.create(null);function Wo(n,e,t){if(n==e)return!0;n||(n=_n),e||(e=_n);let i=Object.keys(n),s=Object.keys(e);if(i.length-(t&&i.indexOf(t)>-1?1:0)!=s.length-(t&&s.indexOf(t)>-1?1:0))return!1;for(let r of i)if(r!=t&&(s.indexOf(r)==-1||n[r]!==e[r]))return!1;return!0}function Ld(n,e){for(let t=n.attributes.length-1;t>=0;t--){let i=n.attributes[t].name;e[i]==null&&n.removeAttribute(i)}for(let t in e){let i=e[t];t=="style"?n.style.cssText=i:n.getAttribute(t)!=i&&n.setAttribute(t,i)}}function Ka(n,e,t){let i=!1;if(e)for(let s in e)t&&s in t||(i=!0,s=="style"?n.style.cssText="":n.removeAttribute(s));if(t)for(let s in t)e&&e[s]==t[s]||(i=!0,s=="style"?n.style.cssText=t[s]:n.setAttribute(s,t[s]));return i}function Ed(n){let e=Object.create(null);for(let t=0;t0?3e8:-4e8:t>0?1e8:-1e8,new Nt(e,t,t,i,e.widget||null,!1)}static replace(e){let t=!!e.block,i,s;if(e.isBlockGap)i=-5e8,s=4e8;else{let{start:r,end:o}=Mh(e,t);i=(r?t?-3e8:-1:5e8)-1,s=(o?t?2e8:1:-6e8)+1}return new Nt(e,i,s,t,e.widget||null,!0)}static line(e){return new Ui(e)}static set(e,t=!1){return F.of(e,t)}hasHeight(){return this.widget?this.widget.estimatedHeight>-1:!1}};P.none=F.empty;var ji=class n extends P{constructor(e){let{start:t,end:i}=Mh(e);super(t?-1:5e8,i?1:-6e8,null,e),this.tagName=e.tagName||"span",this.attrs=e.class&&e.attributes?Fo(e.attributes,{class:e.class}):e.class?{class:e.class}:e.attributes||_n}eq(e){return this==e||e instanceof n&&this.tagName==e.tagName&&Wo(this.attrs,e.attrs)}range(e,t=e){if(e>=t)throw new RangeError("Mark decorations may not be empty");return super.range(e,t)}};ji.prototype.point=!1;var Ui=class n extends P{constructor(e){super(-2e8,-2e8,null,e)}eq(e){return e instanceof n&&this.spec.class==e.spec.class&&Wo(this.spec.attributes,e.spec.attributes)}range(e,t=e){if(t!=e)throw new RangeError("Line decoration ranges must be zero-length");return super.range(e,t)}};Ui.prototype.mapMode=le.TrackBefore;Ui.prototype.point=!0;var Nt=class n extends P{constructor(e,t,i,s,r,o){super(t,i,r,e),this.block=s,this.isReplace=o,this.mapMode=s?t<=0?le.TrackBefore:le.TrackAfter:le.TrackDel}get type(){return this.startSide!=this.endSide?ce.WidgetRange:this.startSide<=0?ce.WidgetBefore:ce.WidgetAfter}get heightRelevant(){return this.block||!!this.widget&&(this.widget.estimatedHeight>=5||this.widget.lineBreaks>0)}eq(e){return e instanceof n&&Id(this.widget,e.widget)&&this.block==e.block&&this.startSide==e.startSide&&this.endSide==e.endSide}range(e,t=e){if(this.isReplace&&(e>t||e==t&&this.startSide>0&&this.endSide<=0))throw new RangeError("Invalid range for replacement decoration");if(!this.isReplace&&t!=e)throw new RangeError("Widget decorations can only have zero-length ranges");return super.range(e,t)}};Nt.prototype.point=!0;function Mh(n,e=!1){let{inclusiveStart:t,inclusiveEnd:i}=n;return t==null&&(t=n.inclusive),i==null&&(i=n.inclusive),{start:t??e,end:i??e}}function Id(n,e){return n==e||!!(n&&e&&n.compare(e))}function hi(n,e,t,i=0){let s=t.length-1;s>=0&&t[s]+i>=n?t[s]=Math.max(t[s],e):t.push(n,e)}var Yn=class n extends Ee{constructor(e,t,i){super(),this.tagName=e,this.attributes=t,this.rank=i}eq(e){return e==this||e instanceof n&&this.tagName==e.tagName&&Wo(this.attributes,e.attributes)}static create(e){return new n(e.tagName,e.attributes||_n,e.rank==null?50:Math.max(0,Math.min(e.rank,100)))}static set(e,t=!1){return F.of(e,t)}};Yn.prototype.startSide=Yn.prototype.endSide=-1;function Gi(n){let e;return n.nodeType==11?e=n.getSelection?n:n.ownerDocument:e=n,e.getSelection()}function jr(n,e){return e?n==e||n.contains(e.nodeType!=1?e.parentNode:e):!1}function Ni(n,e){if(!e.anchorNode)return!1;try{return jr(n,e.anchorNode)}catch{return!1}}function $n(n){return n.nodeType==3?_i(n,0,n.nodeValue.length).getClientRects():n.nodeType==1?n.getClientRects():[]}function Fi(n,e,t,i){return t?ja(n,e,t,i,-1)||ja(n,e,t,i,1):!1}function bt(n){for(var e=0;;e++)if(n=n.previousSibling,!n)return e}function Xn(n){return n.nodeType==1&&/^(DIV|P|LI|UL|OL|BLOCKQUOTE|DD|DT|H\d|SECTION|PRE)$/.test(n.nodeName)}function ja(n,e,t,i,s){for(;;){if(n==t&&e==i)return!0;if(e==(s<0?0:ft(n))){if(n.nodeName=="DIV")return!1;let r=n.parentNode;if(!r||r.nodeType!=1)return!1;e=bt(n)+(s<0?0:1),n=r}else if(n.nodeType==1){if(n=n.childNodes[e+(s<0?-1:0)],n.nodeType==1&&n.contentEditable=="false")return!1;e=s<0?ft(n):0}else return!1}}function ft(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function Qn(n,e){let t=e?n.left:n.right;return{left:t,right:t,top:n.top,bottom:n.bottom}}function Nd(n){let e=n.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:n.innerWidth,top:0,bottom:n.innerHeight}}function Th(n,e){let t=e.width/n.offsetWidth,i=e.height/n.offsetHeight;return(t>.995&&t<1.005||!isFinite(t)||Math.abs(e.width-n.offsetWidth)<1)&&(t=1),(i>.995&&i<1.005||!isFinite(i)||Math.abs(e.height-n.offsetHeight)<1)&&(i=1),{scaleX:t,scaleY:i}}function Fd(n,e,t,i,s,r,o,l){let a=n.ownerDocument,h=a.defaultView||window;for(let c=n,f=!1;c&&!f;)if(c.nodeType==1){let u,d=c==a.body,p=1,m=1;if(d)u=Nd(h);else{if(/^(fixed|sticky)$/.test(getComputedStyle(c).position)&&(f=!0),c.scrollHeight<=c.clientHeight&&c.scrollWidth<=c.clientWidth){c=c.assignedSlot||c.parentNode;continue}let w=c.getBoundingClientRect();({scaleX:p,scaleY:m}=Th(c,w)),u={left:w.left,right:w.left+c.clientWidth*p,top:w.top,bottom:w.top+c.clientHeight*m}}let g=0,b=0;if(s=="nearest")e.top0&&e.bottom>u.bottom+b&&(b=e.bottom-u.bottom+o)):e.bottom>u.bottom-o&&(b=e.bottom-u.bottom+o,t<0&&e.top-b0&&e.right>u.right+g&&(g=e.right-u.right+r)):e.right>u.right-r&&(g=e.right-u.right+r,t<0&&e.leftu.bottom||e.leftu.right)&&(e={left:Math.max(e.left,u.left),right:Math.min(e.right,u.right),top:Math.max(e.top,u.top),bottom:Math.min(e.bottom,u.bottom)}),c=c.assignedSlot||c.parentNode}else if(c.nodeType==11)c=c.host;else break}function Oh(n,e=!0){let t=n.ownerDocument,i=null,s=null;for(let r=n.parentNode;r&&!(r==t.body||(!e||i)&&s);)if(r.nodeType==1)!s&&r.scrollHeight>r.clientHeight&&(s=r),e&&!i&&r.scrollWidth>r.clientWidth&&(i=r),r=r.assignedSlot||r.parentNode;else if(r.nodeType==11)r=r.host;else break;return{x:i,y:s}}var Ur=class{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}eq(e){return this.anchorNode==e.anchorNode&&this.anchorOffset==e.anchorOffset&&this.focusNode==e.focusNode&&this.focusOffset==e.focusOffset}setRange(e){let{anchorNode:t,focusNode:i}=e;this.set(t,Math.min(e.anchorOffset,t?ft(t):0),i,Math.min(e.focusOffset,i?ft(i):0))}set(e,t,i,s){this.anchorNode=e,this.anchorOffset=t,this.focusNode=i,this.focusOffset=s}},Lt=null;O.safari&&O.safari_version>=26&&(Lt=!1);function Dh(n){if(n.setActive)return n.setActive();if(Lt)return n.focus(Lt);let e=[];for(let t=n;t&&(e.push(t,t.scrollTop,t.scrollLeft),t!=t.ownerDocument);t=t.parentNode);if(n.focus(Lt==null?{get preventScroll(){return Lt={preventScroll:!0},!0}}:void 0),!Lt){Lt=!1;for(let t=0;tMath.max(0,n.document.documentElement.scrollHeight-n.innerHeight-4):n.scrollTop>Math.max(1,n.scrollHeight-n.clientHeight-4)}function Bh(n,e){for(let t=n,i=e;;){if(t.nodeType==3&&i>0)return{node:t,offset:i};if(t.nodeType==1&&i>0){if(t.contentEditable=="false")return null;t=t.childNodes[i-1],i=ft(t)}else if(t.parentNode&&!Xn(t))i=bt(t),t=t.parentNode;else return null}}function Rh(n,e){for(let t=n,i=e;;){if(t.nodeType==3&&i=t){if(l.level==i)return o;(r<0||(s!=0?s<0?l.fromt:e[r].level>l.level))&&(r=o)}}if(r<0)throw new RangeError("Index out of range");return r}};function Ih(n,e){if(n.length!=e.length)return!1;for(let t=0;t=0;m-=3)if(Je[m+1]==-d){let g=Je[m+2],b=g&2?s:g&4?g&1?r:s:0;b&&(U[f]=U[Je[m]]=b),l=m;break}}else{if(Je.length==189)break;Je[l++]=f,Je[l++]=u,Je[l++]=a}else if((p=U[f])==2||p==1){let m=p==s;a=m?0:1;for(let g=l-3;g>=0;g-=3){let b=Je[g+2];if(b&2)break;if(m)Je[g+2]|=2;else{if(b&4)break;Je[g+2]|=4}}}}}function jd(n,e,t,i){for(let s=0,r=i;s<=t.length;s++){let o=s?t[s-1].to:n,l=sa;)p==g&&(p=t[--m].from,g=m?t[m-1].to:n),U[--p]=d;a=c}else r=h,a++}}}function _r(n,e,t,i,s,r,o){let l=i%2?2:1;if(i%2==s%2)for(let a=e,h=0;aa&&o.push(new We(a,m.from,d));let g=m.direction==Ft!=!(d%2);Yr(n,g?i+1:i,s,m.inner,m.from,m.to,o),a=m.to}p=m.to}else{if(p==t||(c?U[p]!=l:U[p]==l))break;p++}u?_r(n,a,p,i+1,s,u,o):ae;){let c=!0,f=!1;if(!h||a>r[h-1].to){let m=U[a-1];m!=l&&(c=!1,f=m==16)}let u=!c&&l==1?[]:null,d=c?i:i+1,p=a;e:for(;;)if(h&&p==r[h-1].to){if(f)break e;let m=r[--h];if(!c)for(let g=m.from,b=h;;){if(g==e)break e;if(b&&r[b-1].to==g)g=r[--b].from;else{if(U[g-1]==l)break e;break}}if(u)u.push(m);else{m.toU.length;)U[U.length]=256;let i=[],s=e==Ft?0:1;return Yr(n,s,s,t,0,n.length,i),i}function Nh(n){return[new We(0,n,0)]}var Fh="";function Gd(n,e,t,i,s){var r;let o=i.head-n.from,l=We.find(e,o,(r=i.bidiLevel)!==null&&r!==void 0?r:-1,i.assoc),a=e[l],h=a.side(s,t);if(o==h){let u=l+=s?1:-1;if(u<0||u>=e.length)return null;a=e[l=u],o=a.side(!s,t),h=a.side(s,t)}let c=ee(n.text,o,a.forward(s,t));(ca.to)&&(c=h),Fh=n.text.slice(Math.min(o,c),Math.max(o,c));let f=l==(s?e.length-1:0)?null:e[l+(s?1:-1)];return f&&c==h&&f.level+(s?0:1)n.some(e=>e)}),jh=A.define({combine:n=>n.some(e=>e)}),Uh=A.define(),Wi=class n{constructor(e,t,i,s,r,o=!1){this.range=e,this.y=t,this.x=i,this.yMargin=s,this.xMargin=r,this.isSnapshot=o}map(e){return e.empty?this:new n(this.range.map(e),this.y,this.x,this.yMargin,this.xMargin,this.isSnapshot)}clip(e){return this.range.to<=e.doc.length?this:new n(x.cursor(e.doc.length),this.y,this.x,this.yMargin,this.xMargin,this.isSnapshot)}},En=R.define({map:(n,e)=>n.map(e)}),Gh=R.define();function ne(n,e,t){let i=n.facet(zh);i.length?i[0](e):window.onerror&&window.onerror(String(e),t,void 0,void 0,e)||(t?console.error(t+":",e):console.error(e))}var ht=A.define({combine:n=>n.length?n[0]:!0}),Yd=0,ri=A.define({combine(n){return n.filter((e,t)=>{for(let i=0;i{let a=[];return o&&a.push(ds.of(h=>{let c=h.plugin(l);return c?o(c):P.none})),r&&a.push(r(l)),a})}static fromClass(e,t){return n.define((i,s)=>new e(i,s),t)}},Hi=class{constructor(e){this.spec=e,this.mustUpdate=null,this.value=null}get plugin(){return this.spec&&this.spec.plugin}update(e){if(this.value){if(this.mustUpdate){let t=this.mustUpdate;if(this.mustUpdate=null,this.value.update)try{this.value.update(t)}catch(i){if(ne(t.state,i,"CodeMirror plugin crashed"),this.value.destroy)try{this.value.destroy()}catch{}this.deactivate()}}}else if(this.spec)try{this.value=this.spec.plugin.create(e,this.spec.arg)}catch(t){ne(e.state,t,"CodeMirror plugin crashed"),this.deactivate()}return this}destroy(e){var t;if(!((t=this.value)===null||t===void 0)&&t.destroy)try{this.value.destroy()}catch(i){ne(e.state,i,"CodeMirror plugin crashed")}}deactivate(){this.spec=this.value=null}},_h=A.define(),qo=A.define(),ds=A.define(),Yh=A.define(),$o=A.define(),Yi=A.define(),Xh=A.define();function Ga(n,e){let t=n.state.facet(Xh);if(!t.length)return t;let i=t.map(r=>r instanceof Function?r(n):r),s=[];return F.spans(i,e.from,e.to,{point(){},span(r,o,l,a){let h=r-e.from,c=o-e.from,f=s;for(let u=l.length-1;u>=0;u--,a--){let d=l[u].spec.bidiIsolate,p;if(d==null&&(d=_d(e.text,h,c)),a>0&&f.length&&(p=f[f.length-1]).to==h&&p.direction==d)p.to=c,f=p.inner;else{let m={from:h,to:c,direction:d,inner:[]};f.push(m),f=m.inner}}}}),s}var Qh=A.define();function Ko(n){let e=0,t=0,i=0,s=0;for(let r of n.state.facet(Qh)){let o=r(n);o&&(o.left!=null&&(e=Math.max(e,o.left)),o.right!=null&&(t=Math.max(t,o.right)),o.top!=null&&(i=Math.max(i,o.top)),o.bottom!=null&&(s=Math.max(s,o.bottom)))}return{left:e,right:t,top:i,bottom:s}}var Li=A.define(),$e=class n{constructor(e,t,i,s){this.fromA=e,this.toA=t,this.fromB=i,this.toB=s}join(e){return new n(Math.min(this.fromA,e.fromA),Math.max(this.toA,e.toA),Math.min(this.fromB,e.fromB),Math.max(this.toB,e.toB))}addToSet(e){let t=e.length,i=this;for(;t>0;t--){let s=e[t-1];if(!(s.fromA>i.toA)){if(s.toAs.push(new $e(r,o,l,a))),this.changedRanges=s}static create(e,t,i){return new n(e,t,i)}get viewportChanged(){return(this.flags&4)>0}get viewportMoved(){return(this.flags&8)>0}get heightChanged(){return(this.flags&2)>0}get geometryChanged(){return this.docChanged||(this.flags&18)>0}get focusChanged(){return(this.flags&1)>0}get docChanged(){return!this.changes.empty}get selectionSet(){return this.transactions.some(e=>e.selection)}get empty(){return this.flags==0&&this.transactions.length==0}},Xd=[],Q=class{constructor(e,t,i=0){this.dom=e,this.length=t,this.flags=i,this.parent=null,e.cmTile=this}get breakAfter(){return this.flags&1}get children(){return Xd}isWidget(){return!1}get isHidden(){return!1}isComposite(){return!1}isLine(){return!1}isText(){return!1}isBlock(){return!1}get domAttrs(){return null}sync(e){if(this.flags|=2,this.flags&4){this.flags&=-5;let t=this.domAttrs;t&&Ld(this.dom,t)}}toString(){return this.constructor.name+(this.children.length?`(${this.children})`:"")+(this.breakAfter?"#":"")}destroy(){this.parent=null}setDOM(e){this.dom=e,e.cmTile=this}get posAtStart(){return this.parent?this.parent.posBefore(this):0}get posAtEnd(){return this.posAtStart+this.length}posBefore(e,t=this.posAtStart){let i=t;for(let s of this.children){if(s==e)return i;i+=s.length+s.breakAfter}throw new RangeError("Invalid child in posBefore")}posAfter(e){return this.posBefore(e)+e.length}covers(e){return!0}coordsIn(e,t){return null}domPosFor(e,t){let i=bt(this.dom),s=this.length?e>0:t>0;return new Ze(this.parent.dom,i+(s?1:0),e==0||e==this.length)}markDirty(e){this.flags&=-3,e&&(this.flags|=4),this.parent&&this.parent.flags&2&&this.parent.markDirty(!1)}get overrideDOMText(){return null}get root(){for(let e=this;e;e=e.parent)if(e instanceof ui)return e;return null}static get(e){return e.cmTile}},fi=class extends Q{constructor(e){super(e,0),this._children=[]}isComposite(){return!0}get children(){return this._children}get lastChild(){return this.children.length?this.children[this.children.length-1]:null}append(e){this.children.push(e),e.parent=this}sync(e){if(this.flags&2)return;super.sync(e);let t=this.dom,i=null,s,r=e?.node==t?e:null,o=0;for(let l of this.children){if(l.sync(e),o+=l.length+l.breakAfter,s=i?i.nextSibling:t.firstChild,r&&s!=l.dom&&(r.written=!0),l.dom.parentNode==t)for(;s&&s!=l.dom;)s=_a(s);else t.insertBefore(l.dom,s);i=l.dom}for(s=i?i.nextSibling:t.firstChild,r&&s&&(r.written=!0);s;)s=_a(s);this.length=o}};function _a(n){let e=n.nextSibling;return n.parentNode.removeChild(n),e}var ui=class extends fi{constructor(e,t){super(t),this.view=e}owns(e){for(;e;e=e.parent)if(e==this)return!0;return!1}isBlock(){return!0}nearest(e){for(;;){if(!e)return null;let t=Q.get(e);if(t&&this.owns(t))return t;e=e.parentNode}}blockTiles(e){for(let t=[],i=this,s=0,r=0;;)if(s==i.children.length){if(!t.length)return;i=i.parent,i.breakAfter&&r++,s=t.pop()}else{let o=i.children[s++];if(o instanceof ct)t.push(s),i=o,s=0;else{let l=r+o.length,a=e(o,r);if(a!==void 0)return a;r=l+o.breakAfter}}}resolveBlock(e,t){let i,s=-1,r,o=-1;if(this.blockTiles((l,a)=>{let h=a+l.length;if(e>=a&&e<=h){if(l.isWidget()&&t>=-1&&t<=1){if(l.flags&32)return!0;l.flags&16&&(i=void 0)}(ae||e==a&&(t>1?l.length:l.covers(-1)))&&(!r||!l.isWidget()&&r.isWidget())&&(r=l,o=e-a)}}),!i&&!r)throw new Error("No tile at position "+e);return i&&t<0||!r?{tile:i,offset:s}:{tile:r,offset:o}}},ct=class n extends fi{constructor(e,t){super(e),this.wrapper=t}isBlock(){return!0}covers(e){return this.children.length?e<0?this.children[0].covers(-1):this.lastChild.covers(1):!1}get domAttrs(){return this.wrapper.attributes}static of(e,t){let i=new n(t||document.createElement(e.tagName),e);return t||(i.flags|=4),i}},di=class n extends fi{constructor(e,t){super(e),this.attrs=t}isLine(){return!0}static start(e,t,i){let s=new n(t||document.createElement("div"),e);return(!t||!i)&&(s.flags|=4),s}get domAttrs(){return this.attrs}resolveInline(e,t,i){let s=null,r=-1,o=null,l=-1;function a(c,f){for(let u=0,d=0;u=f&&(p.isComposite()?a(p,f-d):(!o||o.isHidden&&(t>0||i&&Jd(o,p)))&&(m>f||p.flags&32)?(o=p,l=f-d):(di&&(e=i);let s=e,r=e,o=0;e==0&&t<0||e==i&&t>=0?O.chrome||O.gecko||(e?(s--,o=1):r=0)?0:l.length-1];return O.safari&&!o&&a.width==0&&(a=Array.prototype.find.call(l,h=>h.width)||a),o?Qn(a,o<0):a||null}static of(e,t){let i=new n(t||document.createTextNode(e),e);return t||(i.flags|=2),i}},Wt=class n extends Q{constructor(e,t,i,s){super(e,t,s),this.widget=i}isWidget(){return!0}get isHidden(){return this.widget.isHidden}covers(e){return this.flags&48?!1:(this.flags&(e<0?64:128))>0}coordsIn(e,t){return this.coordsInWidget(e,t,!1)}coordsInWidget(e,t,i){let s=this.widget.coordsAt(this.dom,e,t);if(s)return s;if(i)return Qn(this.dom.getBoundingClientRect(),this.length?e==0:t<=0);{let r=this.dom.getClientRects(),o=null;if(!r.length)return null;let l=this.flags&16?!0:this.flags&32?!1:e>0;for(let a=l?r.length-1:0;o=r[a],!(e>0?a==0:a==r.length-1||o.top0;)if(s.isComposite())if(o){if(!e)break;i&&i.break(),e--,o=!1}else if(r==s.children.length){if(!e&&!l.length)break;i&&i.leave(s),o=!!s.breakAfter,{tile:s,index:r}=l.pop(),r++}else{let a=s.children[r],h=a.breakAfter;(t>0?a.length<=e:a.length=0;l--){let a=t.marks[l],h=s.lastChild;if(h instanceof ye&&h.mark.eq(a.mark))h.dom!=a.dom&&h.setDOM(Lr(a.dom)),s=h;else{if(this.cache.reused.get(a)){let f=Q.get(a.dom);f&&f.setDOM(Lr(a.dom))}let c=ye.of(a.mark,a.dom);s.append(c),s=c}this.cache.reused.set(a,2)}let r=Q.get(e.text);r&&this.cache.reused.set(r,2);let o=new Et(e.text,e.text.nodeValue);o.flags|=8,this.pos=e.range.toB,s.append(o)}addInlineWidget(e,t,i){let s=this.afterWidget&&e.flags&48&&(this.afterWidget.flags&48)==(e.flags&48);s||this.flushBuffer();let r=this.ensureMarks(t,i);!s&&!(e.flags&16)&&r.append(this.getBuffer(1)),r.append(e),this.pos+=e.length,this.afterWidget=e}addMark(e,t,i){this.flushBuffer(),this.ensureMarks(t,i).append(e),this.pos+=e.length,this.afterWidget=null}addBlockWidget(e){this.getBlockPos().append(e),this.pos+=e.length,this.lastBlock=e,this.endLine()}continueWidget(e){let t=this.afterWidget||this.lastBlock;t.length+=e,this.pos+=e}addLineStart(e,t){var i;e||(e=Jh);let s=di.start(e,t||((i=this.cache.find(di))===null||i===void 0?void 0:i.dom),!!t);this.getBlockPos().append(this.lastBlock=this.curLine=s)}addLine(e){this.getBlockPos().append(e),this.pos+=e.length,this.lastBlock=e,this.endLine()}addBreak(){this.lastBlock.flags|=1,this.endLine(),this.pos++}addLineStartIfNotCovered(e){this.blockPosCovered()||this.addLineStart(e)}ensureLine(e){this.curLine||this.addLineStart(e)}ensureMarks(e,t){var i;let s=this.curLine;for(let r=e.length-1;r>=0;r--){let o=e[r],l;if(t>0&&(l=s.lastChild)&&l instanceof ye&&l.mark.eq(o))s=l,t--;else{let a=ye.of(o,(i=this.cache.find(ye,h=>h.mark.eq(o)))===null||i===void 0?void 0:i.dom);s.append(a),s=a,t=0}}return s}endLine(){if(this.curLine){this.flushBuffer();let e=this.curLine.lastChild;(!e||!Ya(this.curLine,!1)||e.dom.nodeName!="BR"&&e.isWidget()&&!(O.ios&&Ya(this.curLine,!0)))&&this.curLine.append(this.cache.findWidget(Er,0,32)||new Wt(Er.toDOM(),0,Er,32)),this.curLine=this.afterWidget=null}}updateBlockWrappers(){this.wrapperPos>this.pos+1e4&&(this.blockWrappers.goto(this.pos),this.wrappers.length=0);for(let e=this.wrappers.length-1;e>=0;e--)this.wrappers[e].to=this.pos){let t=e.rank*102+e.value.rank,i=new Jr(e.from,e.to,e.value,t),s=this.wrappers.length;for(;s>0&&(this.wrappers[s-1].rank-i.rank||this.wrappers[s-1].to-i.to)<0;)s--;this.wrappers.splice(s,0,i)}this.wrapperPos=this.pos}getBlockPos(){var e;this.updateBlockWrappers();let t=this.root;for(let i of this.wrappers){let s=t.lastChild;if(i.fromo.wrapper.eq(i.wrapper)))===null||e===void 0?void 0:e.dom);t.append(r),t=r}}return t}blockPosCovered(){let e=this.lastBlock;return e!=null&&!e.breakAfter&&(!e.isWidget()||(e.flags&160)>0)}getBuffer(e){let t=2|(e<0?16:32),i=this.cache.find(pi,void 0,1);return i&&(i.flags=t),i||new pi(t)}flushBuffer(){this.afterWidget&&!(this.afterWidget.flags&32)&&(this.afterWidget.parent.append(this.getBuffer(-1)),this.afterWidget=null)}},eo=class{constructor(e){this.skipCount=0,this.text="",this.textOff=0,this.cursor=e.iter()}skip(e){this.textOff+e<=this.text.length?this.textOff+=e:(this.skipCount+=e-(this.text.length-this.textOff),this.text="",this.textOff=0)}next(e){if(this.textOff==this.text.length){let{value:s,lineBreak:r,done:o}=this.cursor.next(this.skipCount);if(this.skipCount=0,o)throw new Error("Ran out of text content when drawing inline views");this.text=s;let l=this.textOff=Math.min(e,s.length);return r?null:s.slice(0,l)}let t=Math.min(this.text.length,this.textOff+e),i=this.text.slice(this.textOff,t);return this.textOff=t,i}},Zn=[Wt,di,Et,ye,pi,ct,ui];for(let n=0;n[]),this.index=Zn.map(()=>0),this.reused=new Map}add(e){let t=e.constructor.bucket,i=this.buckets[t];i.length<6?i.push(e):i[this.index[t]=(this.index[t]+1)%6]=e}find(e,t,i=2){let s=e.bucket,r=this.buckets[s],o=this.index[s];for(let l=r.length-1;l>=0;l--){let a=(l+o)%r.length,h=r[a];if((!t||t(h))&&!this.reused.has(h))return r.splice(a,1),a{if(this.cache.add(o),o.isComposite())return!1},enter:o=>this.cache.add(o),leave:()=>{},break:()=>{}}}run(e,t){let i=t&&this.getCompositionContext(t.text);for(let s=0,r=0,o=0;;){let l=os){let h=a-s;this.preserve(h,!o,!l),s=a,r+=h}if(!l)break;t&&l.fromA<=t.range.fromA&&l.toA>=t.range.toA?(this.forward(l.fromA,t.range.fromA,t.range.fromA{if(o.isWidget())if(this.openWidget)this.builder.continueWidget(a-l);else{let h=a>0||l{o.isLine()?this.builder.addLineStart(o.attrs,this.cache.maybeReuse(o)):(this.cache.add(o),o instanceof ye&&s.unshift(o.mark)),this.openWidget=!1},leave:o=>{o.isLine()?s.length&&(s.length=r=0):o instanceof ye&&(s.shift(),r=Math.min(r,s.length))},break:()=>{this.builder.addBreak(),this.openWidget=!1}}),this.text.skip(e)}emit(e,t){let i=null,s=this.builder,r=0,o=F.spans(this.decorations,e,t,{point:(l,a,h,c,f,u)=>{if(h instanceof Nt){if(this.disallowBlockEffectsFor[u]){if(h.block)throw new RangeError("Block decorations may not be specified via plugins");if(a>this.view.state.doc.lineAt(l).to)throw new RangeError("Decorations that replace line breaks may not be specified via plugins")}if(r=c.length,f>c.length)s.continueWidget(a-l);else{let d=h.widget||(h.block?yt.block:yt.inline),p=Zd(h),m=this.cache.findWidget(d,a-l,p)||Wt.of(d,this.view,a-l,p);h.block?(h.startSide>0&&s.addLineStartIfNotCovered(i),s.addBlockWidget(m)):(s.ensureLine(i),s.addInlineWidget(m,c,f))}i=null}else i=ep(i,h);a>l&&this.text.skip(a-l)},span:(l,a,h,c)=>{for(let f=l;fr,this.openMarks=o}forward(e,t,i=1){t-e<=10?this.old.advance(t-e,i,this.reuseWalker):(this.old.advance(5,-1,this.reuseWalker),this.old.advance(t-e-10,-1),this.old.advance(5,i,this.reuseWalker))}getCompositionContext(e){let t=[],i=null;for(let s=e.parentNode;;s=s.parentNode){let r=Q.get(s);if(s==this.view.contentDOM)break;r instanceof ye?t.push(r):r?.isLine()?i=r:r instanceof ct||(s.nodeName=="DIV"&&!i&&s!=this.view.contentDOM?i=new di(s,Jh):i||t.push(ye.of(new ji({tagName:s.nodeName.toLowerCase(),attributes:Ed(s)}),s)))}return{line:i,marks:t}}};function Ya(n,e){let t=i=>{for(let s of i.children)if((e?s.isText():s.length)||t(s))return!0;return!1};return t(n)}function Zd(n){let e=n.isReplace?(n.startSide<0?64:0)|(n.endSide>0?128:0):n.startSide>0?32:16;return n.block&&(e|=256),e}var Jh={class:"cm-line"};function ep(n,e){let t=e.spec.attributes,i=e.spec.class;return!t&&!i||(n||(n={class:"cm-line"}),t&&Fo(t,n),i&&(n.class+=" "+i)),n}function tp(n){let e=[];for(let t=n.parents.length;t>1;t--){let i=t==n.parents.length?n.tile:n.parents[t].tile;i instanceof ye&&e.push(i.mark)}return e}function Lr(n){let e=Q.get(n);return e&&e.setDOM(n.cloneNode()),n}var yt=class extends xe{constructor(e){super(),this.tag=e}eq(e){return e.tag==this.tag}toDOM(){return document.createElement(this.tag)}updateDOM(e){return e.nodeName.toLowerCase()==this.tag}get isHidden(){return!0}};yt.inline=new yt("span");yt.block=new yt("div");var Er=new class extends xe{toDOM(){return document.createElement("br")}get isHidden(){return!0}get editable(){return!0}},es=class{constructor(e){this.view=e,this.decorations=[],this.blockWrappers=[],this.dynamicDecorationMap=[!1],this.domChanged=null,this.hasComposition=null,this.editContextFormatting=P.none,this.lastCompositionAfterCursor=!1,this.minWidth=0,this.minWidthFrom=0,this.minWidthTo=0,this.impreciseAnchor=null,this.impreciseHead=null,this.forceSelection=!1,this.lastUpdate=Date.now(),this.updateDeco(),this.tile=new ui(e,e.contentDOM),this.updateInner([new $e(0,0,0,e.state.doc.length)],null)}update(e){var t;let i=e.changedRanges;this.minWidth>0&&i.length&&(i.every(({fromA:c,toA:f})=>fthis.minWidthTo)?(this.minWidthFrom=e.changes.mapPos(this.minWidthFrom,1),this.minWidthTo=e.changes.mapPos(this.minWidthTo,1)):this.minWidth=this.minWidthFrom=this.minWidthTo=0),this.updateEditContextFormatting(e);let s=-1;this.view.inputState.composing>=0&&!this.view.observer.editContext&&(!((t=this.domChanged)===null||t===void 0)&&t.newSel?s=this.domChanged.newSel.head:!hp(e.changes,this.hasComposition)&&!e.selectionSet&&(s=e.state.selection.main.head));let r=s>-1?np(this.view,e.changes,s):null;if(this.domChanged=null,this.hasComposition){let{from:c,to:f}=this.hasComposition;i=new $e(c,f,e.changes.mapPos(c,-1),e.changes.mapPos(f,1)).addToSet(i.slice())}this.hasComposition=r?{from:r.range.fromB,to:r.range.toB}:null,(O.ie||O.chrome)&&!r&&e&&e.state.doc.lines!=e.startState.doc.lines&&(this.forceSelection=!0);let o=this.decorations,l=this.blockWrappers;this.updateDeco();let a=op(o,this.decorations,e.changes);a.length&&(i=$e.extendWithRanges(i,a));let h=lp(l,this.blockWrappers,e.changes);return h.length&&(i=$e.extendWithRanges(i,h)),r&&!i.some(c=>c.fromA<=r.range.fromA&&c.toA>=r.range.toA)&&(i=r.range.addToSet(i.slice())),this.tile.flags&2&&i.length==0?!1:(this.updateInner(i,r),e.transactions.length&&(this.lastUpdate=Date.now()),!0)}updateInner(e,t){this.view.viewState.mustMeasureContent=!0;let{observer:i}=this.view;i.ignore(()=>{if(t||e.length){let o=this.tile,l=new io(this.view,o,this.blockWrappers,this.decorations,this.dynamicDecorationMap);t&&Q.get(t.text)&&l.cache.reused.set(Q.get(t.text),2),this.tile=l.run(e,t),no(o,l.cache.reused)}this.tile.dom.style.height=this.view.viewState.contentHeight/this.view.scaleY+"px",this.tile.dom.style.flexBasis=this.minWidth?this.minWidth+"px":"";let r=O.chrome||O.ios?{node:i.selectionRange.focusNode,written:!1}:void 0;this.tile.sync(r),r&&(r.written||i.selectionRange.focusNode!=r.node||!this.tile.dom.contains(r.node))&&(this.forceSelection=!0),this.tile.dom.style.height=""});let s=[];if(this.view.viewport.from||this.view.viewport.to-1)&&Ni(i,this.view.observer.selectionRange)&&!(s&&i.contains(s));if(!(r||t||o))return;let l=this.forceSelection;this.forceSelection=!1;let a=this.view.state.selection.main,h,c;if(a.empty?c=h=this.inlineDOMNearPos(a.anchor,a.assoc||1):(c=this.inlineDOMNearPos(a.head,a.head==a.from?1:-1),h=this.inlineDOMNearPos(a.anchor,a.anchor==a.from?1:-1)),O.gecko&&a.empty&&!this.hasComposition&&ip(h)){let u=document.createTextNode("");this.view.observer.ignore(()=>h.node.insertBefore(u,h.node.childNodes[h.offset]||null)),h=c=new Ze(u,0),l=!0}let f=this.view.observer.selectionRange;(l||!f.focusNode||(!Fi(h.node,h.offset,f.anchorNode,f.anchorOffset)||!Fi(c.node,c.offset,f.focusNode,f.focusOffset))&&!this.suppressWidgetCursorChange(f,a))&&(this.view.observer.ignore(()=>{O.android&&O.chrome&&i.contains(f.focusNode)&&ap(f.focusNode,i)&&(i.blur(),i.focus({preventScroll:!0}));let u=Gi(this.view.root);if(u)if(a.empty){if(O.gecko){let d=sp(h.node,h.offset);if(d&&d!=3){let p=(d==1?Bh:Rh)(h.node,h.offset);p&&(h=new Ze(p.node,p.offset))}}u.collapse(h.node,h.offset),a.bidiLevel!=null&&u.caretBidiLevel!==void 0&&(u.caretBidiLevel=a.bidiLevel)}else if(u.extend){u.collapse(h.node,h.offset);try{u.extend(c.node,c.offset)}catch{}}else{let d=document.createRange();a.anchor>a.head&&([h,c]=[c,h]),d.setEnd(c.node,c.offset),d.setStart(h.node,h.offset),u.removeAllRanges(),u.addRange(d)}o&&this.view.root.activeElement==i&&(i.blur(),s&&s.focus())}),this.view.observer.setSelectionRange(h,c)),this.impreciseAnchor=h.precise?null:new Ze(f.anchorNode,f.anchorOffset),this.impreciseHead=c.precise?null:new Ze(f.focusNode,f.focusOffset)}suppressWidgetCursorChange(e,t){return this.hasComposition&&t.empty&&Fi(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset)&&this.posFromDOM(e.focusNode,e.focusOffset)==t.head}enforceCursorAssoc(){if(this.hasComposition)return;let{view:e}=this,t=e.state.selection.main,i=Gi(e.root),{anchorNode:s,anchorOffset:r}=e.observer.selectionRange;if(!i||!t.empty||!t.assoc||!i.modify)return;let o=this.lineAt(t.head,t.assoc);if(!o)return;let l=o.posAtStart;if(t.head==l||t.head==l+o.length)return;let a=this.coordsAt(t.head,-1),h=this.coordsAt(t.head,1);if(!a||!h||a.bottom>h.top)return;let c=this.domAtPos(t.head+t.assoc,t.assoc);i.collapse(c.node,c.offset),i.modify("move",t.assoc<0?"forward":"backward","lineboundary"),e.observer.readSelectionRange();let f=e.observer.selectionRange;e.docView.posFromDOM(f.anchorNode,f.anchorOffset)!=t.from&&i.collapse(s,r)}posFromDOM(e,t){let i=this.tile.nearest(e);if(!i)return this.tile.dom.compareDocumentPosition(e)&2?0:this.view.state.doc.length;let s=i.posAtStart;if(i.isComposite()){let r;if(e==i.dom)r=i.dom.childNodes[t];else{let o=ft(e)==0?0:t==0?-1:1;for(;;){let l=e.parentNode;if(l==i.dom)break;o==0&&l.firstChild!=l.lastChild&&(e==l.firstChild?o=-1:o=1),e=l}o<0?r=e:r=e.nextSibling}if(r==i.dom.firstChild)return s;for(;r&&!Q.get(r);)r=r.nextSibling;if(!r)return s+i.length;for(let o=0,l=s;;o++){let a=i.children[o];if(a.dom==r)return l;l+=a.length+a.breakAfter}}else return i.isText()?e==i.dom?s+t:s+(t?i.length:0):s}domAtPos(e,t){let{tile:i,offset:s}=this.tile.resolveBlock(e,t);return i.isWidget()?i.domPosFor(e,t):i.domIn(s,t)}inlineDOMNearPos(e,t){let i,s=-1,r=!1,o,l=-1,a=!1;return this.tile.blockTiles((h,c)=>{if(h.isWidget()){if(h.flags&32&&c>=e)return!0;h.flags&16&&(r=!0)}else{let f=c+h.length;if(c<=e&&(i=h,s=e-c,r=f=e&&!o&&(o=h,l=e-c,a=c>e),c>e&&o)return!0}}),!i&&!o?this.domAtPos(e,t):(r&&o?i=null:a&&i&&(o=null),i&&t<0||!o?i.domIn(s,t):o.domIn(l,t))}coordsAt(e,t){let{tile:i,offset:s}=this.tile.resolveBlock(e,t);return i.isWidget()?i.widget instanceof Vi?null:i.coordsInWidget(s,t,!0):i.coordsIn(s,t)}lineAt(e,t){let{tile:i}=this.tile.resolveBlock(e,t);return i.isLine()?i:null}coordsForChar(e){let{tile:t,offset:i}=this.tile.resolveBlock(e,1);if(!t.isLine())return null;function s(r,o){if(r.isComposite())for(let l of r.children){if(l.length>=o){let a=s(l,o);if(a)return a}if(o-=l.length,o<0)break}else if(r.isText()&&oMath.max(this.view.scrollDOM.clientWidth,this.minWidth)+1,l=-1,a=this.view.textDirection==z.LTR,h=0,c=(f,u,d)=>{for(let p=0;ps);p++){let m=f.children[p],g=u+m.length,b=m.dom.getBoundingClientRect(),{height:w}=b;if(d&&!p&&(h+=b.top-d.top),m instanceof ct)g>i&&c(m,u,b);else if(u>=i&&(h>0&&t.push(-h),t.push(w+h),h=0,o)){let k=m.dom.lastChild,D=k?$n(k):[];if(D.length){let v=D[D.length-1],S=a?v.right-b.left:b.right-v.left;S>l&&(l=S,this.minWidth=r,this.minWidthFrom=u,this.minWidthTo=g)}}d&&p==f.children.length-1&&(h+=d.bottom-b.bottom),u=g+m.breakAfter}};return c(this.tile,0,null),t}textDirectionAt(e){let{tile:t}=this.tile.resolveBlock(e,1);return getComputedStyle(t.dom).direction=="rtl"?z.RTL:z.LTR}measureTextSize(){let e=this.tile.blockTiles(o=>{if(o.isLine()&&o.children.length&&o.length<=20){let l=0,a;for(let h of o.children){if(!h.isText()||/[^ -~]/.test(h.text))return;let c=$n(h.dom);if(c.length!=1)return;l+=c[0].width,a=c[0].height}if(l)return{lineHeight:o.dom.getBoundingClientRect().height,charWidth:l/o.length,textHeight:a}}});if(e)return e;let t=document.createElement("div"),i,s,r;return t.className="cm-line",t.style.width="99999px",t.style.position="absolute",t.textContent="abc def ghi jkl mno pqr stu",this.view.observer.ignore(()=>{this.tile.dom.appendChild(t);let o=$n(t.firstChild)[0];i=t.getBoundingClientRect().height,s=o&&o.width?o.width/27:7,r=o&&o.height?o.height:i,t.remove()}),{lineHeight:i,charWidth:s,textHeight:r}}computeBlockGapDeco(){let e=[],t=this.view.viewState;for(let i=0,s=0;;s++){let r=s==t.viewports.length?null:t.viewports[s],o=r?r.from-1:this.view.state.doc.length;if(o>i){let l=(t.lineBlockAt(o).bottom-t.lineBlockAt(i).top)/this.view.scaleY;e.push(P.replace({widget:new Vi(l),block:!0,inclusive:!0,isBlockGap:!0}).range(i,o))}if(!r)break;i=r.to+1}return P.set(e)}updateDeco(){let e=1,t=this.view.state.facet(ds).map(r=>(this.dynamicDecorationMap[e++]=typeof r=="function")?r(this.view):r),i=!1,s=this.view.state.facet($o).map((r,o)=>{let l=typeof r=="function";return l&&(i=!0),l?r(this.view):r});for(s.length&&(this.dynamicDecorationMap[e++]=i,t.push(F.join(s))),this.decorations=[this.editContextFormatting,...t,this.computeBlockGapDeco(),this.view.viewState.lineGapDeco];etypeof r=="function"?r(this.view):r)}scrollIntoView(e){var t;if(e.isSnapshot){let c=this.view.viewState.lineBlockAt(e.range.head);this.view.scrollDOM.scrollTop=c.top-e.yMargin,this.view.scrollDOM.scrollLeft=e.xMargin;return}for(let c of this.view.state.facet(Uh))try{if(c(this.view,e.range,e))return!0}catch(f){ne(this.view.state,f,"scroll handler")}let{range:i}=e,s=this.coordsAt(i.head,(t=i.assoc)!==null&&t!==void 0?t:i.empty?0:i.head>i.anchor?-1:1),r;if(!s)return;!i.empty&&(r=this.coordsAt(i.anchor,i.anchor>i.head?-1:1))&&(s={left:Math.min(s.left,r.left),top:Math.min(s.top,r.top),right:Math.max(s.right,r.right),bottom:Math.max(s.bottom,r.bottom)});let o=Ko(this.view),l={left:s.left-o.left,top:s.top-o.top,right:s.right+o.right,bottom:s.bottom+o.bottom},{offsetWidth:a,offsetHeight:h}=this.view.scrollDOM;if(Fd(this.view.scrollDOM,l,i.head1&&(s.top>window.pageYOffset+window.visualViewport.offsetTop+window.visualViewport.height||s.bottomi.isWidget()||i.children.some(t);return t(this.tile.resolveBlock(e,1).tile)}destroy(){no(this.tile)}};function no(n,e){let t=e?.get(n);if(t!=1){t==null&&n.destroy();for(let i of n.children)no(i,e)}}function ip(n){return n.node.nodeType==1&&n.node.firstChild&&(n.offset==0||n.node.childNodes[n.offset-1].contentEditable=="false")&&(n.offset==n.node.childNodes.length||n.node.childNodes[n.offset].contentEditable=="false")}function Zh(n,e){let t=n.observer.selectionRange;if(!t.focusNode)return null;let i=Bh(t.focusNode,t.focusOffset),s=Rh(t.focusNode,t.focusOffset),r=i||s;if(s&&i&&s.node!=i.node){let l=Q.get(s.node);if(!l||l.isText()&&l.text!=s.node.nodeValue)r=s;else if(n.docView.lastCompositionAfterCursor){let a=Q.get(i.node);!a||a.isText()&&a.text!=i.node.nodeValue||(r=s)}}if(n.docView.lastCompositionAfterCursor=r!=i,!r)return null;let o=e-r.offset;return{from:o,to:o+r.node.nodeValue.length,node:r.node}}function np(n,e,t){let i=Zh(n,t);if(!i)return null;let{node:s,from:r,to:o}=i,l=s.nodeValue;if(/[\n\r]/.test(l)||n.state.doc.sliceString(i.from,i.to)!=l)return null;let a=e.invertedDesc;return{range:new $e(a.mapPos(r),a.mapPos(o),r,o),text:s}}function sp(n,e){return n.nodeType!=1?0:(e&&n.childNodes[e-1].contentEditable=="false"?1:0)|(e{ie.from&&(t=!0)}),t}var Vi=class extends xe{constructor(e){super(),this.height=e}toDOM(){let e=document.createElement("div");return e.className="cm-gap",this.updateDOM(e),e}eq(e){return e.height==this.height}updateDOM(e){return e.style.height=this.height+"px",!0}get editable(){return!0}get estimatedHeight(){return this.height}ignoreEvent(){return!1}};function cp(n,e,t=1){let i=n.charCategorizer(e),s=n.doc.lineAt(e),r=e-s.from;if(s.length==0)return x.cursor(e);r==0?t=1:r==s.length&&(t=-1);let o=r,l=r;t<0?o=ee(s.text,r,!1):l=ee(s.text,r);let a=i(s.text.slice(o,l));for(;o>0;){let h=ee(s.text,o,!1);if(i(s.text.slice(h,o))!=a)break;o=h}for(;ln.defaultLineHeight*1.5){let l=n.viewState.heightOracle.textHeight,a=Math.floor((s-t.top-(n.defaultLineHeight-l)*.5)/l);r+=a*n.viewState.heightOracle.lineLength}let o=n.state.sliceDoc(t.from,t.to);return t.from+Rn(o,r,n.state.tabSize)}function ro(n,e,t){let i=n.lineBlockAt(e);if(Array.isArray(i.type)){let s;for(let r of i.type){if(r.from>e)break;if(!(r.toe)return r;(!s||r.type==ce.Text&&(s.type!=r.type||(t<0?r.frome)))&&(s=r)}}return s||i}return i}function up(n,e,t,i){let s=ro(n,e.head,e.assoc||-1),r=!i||s.type!=ce.Text||!(n.lineWrapping||s.widgetLineBreaks)?null:n.coordsAtPos(e.assoc<0&&e.head>s.from?e.head-1:e.head);if(r){let o=n.dom.getBoundingClientRect(),l=n.textDirectionAt(s.from),a=n.posAtCoords({x:t==(l==z.LTR)?o.right-1:o.left+1,y:(r.top+r.bottom)/2});if(a!=null)return x.cursor(a,t?-1:1)}return x.cursor(t?s.to:s.from,t?-1:1)}function Xa(n,e,t,i){let s=n.state.doc.lineAt(e.head),r=n.bidiSpans(s),o=n.textDirectionAt(s.from);for(let l=e,a=null;;){let h=Gd(s,r,o,l,t),c=Fh;if(!h){if(s.number==(t?n.state.doc.lines:1))return l;c=` +`,s=n.state.doc.line(s.number+(t?1:-1)),r=n.bidiSpans(s),h=n.visualLineSide(s,!t)}if(a){if(!a(c))return l}else{if(!i)return h;a=i(c)}l=h}}function dp(n,e,t){let i=n.state.charCategorizer(e),s=i(t);return r=>{let o=i(r);return s==K.Space&&(s=o),s==o}}function pp(n,e,t,i){let s=e.head,r=t?1:-1;if(s==(t?n.state.doc.length:0))return x.cursor(s,e.assoc);let o=e.goalColumn,l,a=n.contentDOM.getBoundingClientRect(),h=n.coordsAtPos(s,e.assoc||((e.empty?t:e.head==e.from)?1:-1)),c=n.documentTop;if(h)o==null&&(o=h.left-a.left),l=r<0?h.top:h.bottom;else{let p=n.viewState.lineBlockAt(s);o==null&&(o=Math.min(a.right-a.left,n.defaultCharacterWidth*(s-p.from))),l=(r<0?p.top:p.bottom)+c}let f=a.left+o,u=n.viewState.heightOracle.textHeight>>1,d=i??u;for(let p=0;;p+=u){let m=l+(d+p)*r,g=oo(n,{x:f,y:m},!1,r);if(t?m>a.bottom:ml:w{if(e>r&&es(n)),t.from,e.head>t.from?-1:1);return i==t.from?t:x.cursor(i,in.viewState.docHeight)return new Fe(n.state.doc.length,-1);if(h=n.elementAtHeight(a),i==null)break;if(h.type==ce.Text){if(i<0?h.ton.viewport.to)break;let u=n.docView.coordsAt(i<0?h.from:h.to,i>0?-1:1);if(u&&(i<0?u.top<=a+r:u.bottom>=a+r))break}let f=n.viewState.heightOracle.textHeight/2;a=i>0?h.bottom+f:h.top-f}if(n.viewport.from>=h.to||n.viewport.to<=h.from){if(t)return null;if(h.type==ce.Text){let f=fp(n,s,h,o,l);return new Fe(f,f==h.from?1:-1)}}if(h.type!=ce.Text)return a<(h.top+h.bottom)/2?new Fe(h.from,1):new Fe(h.to,-1);let c=n.docView.lineAt(h.from,2);return(!c||c.length!=h.length)&&(c=n.docView.lineAt(h.from,-2)),new lo(n,o,l,n.textDirectionAt(h.from)).scanTile(c,h.from)}var lo=class{constructor(e,t,i,s){this.view=e,this.x=t,this.y=i,this.baseDir=s,this.line=null,this.spans=null}bidiSpansAt(e){return(!this.line||this.line.from>e||this.line.to1||i.length&&(i[0].level!=this.baseDir||i[0].to+s.from>1;t:if(o.has(m)){let b=s+Math.floor(Math.random()*p);for(let w=0;w1)){if(w.bottomthis.y)(!h||h.top>w.top)&&(h=w),k=-1;else{let D=w.left>this.x?this.x-w.left:w.right(p+p+m)/3)return this.y=a.bottom-1,this.scan(e,t,!0);if(h&&h.top<(p+m+m)/3)return this.y=h.top+1,this.scan(e,t,!0)}let d=(l?this.dirAt(e[c],1):this.baseDir)==z.LTR;return{i:c,after:this.x>(u.left+u.right)/2==d}}scanText(e,t){let i=[];for(let r=0;r{let o=i[r]-t,l=i[r+1]-t;return _i(e.dom,o,l).getClientRects()});return s.after?new Fe(i[s.i+1],-1):new Fe(i[s.i],1)}scanTile(e,t){if(!e.length)return new Fe(t,1);if(e.children.length==1){let l=e.children[0];if(l.isText())return this.scanText(l,t);if(l.isComposite())return this.scanTile(l,t)}let i=[t];for(let l=0,a=t;l{let a=e.children[l];return a.flags&48?null:(a.dom.nodeType==1?a.dom:_i(a.dom,0,a.length)).getClientRects()}),r=e.children[s.i],o=i[s.i];return r.isText()?this.scanText(r,o):r.isComposite()?this.scanTile(r,o):s.after?new Fe(i[s.i+1],-1):new Fe(o,1)}},si="\uFFFF",ao=class{constructor(e,t){this.points=e,this.view=t,this.text="",this.lineSeparator=t.state.facet($.lineSeparator)}append(e){this.text+=e}lineBreak(){this.text+=si}readRange(e,t){if(!e)return this;let i=e.parentNode;for(let s=e;;){this.findPointBefore(i,s);let r=this.text.length;this.readNode(s);let o=Q.get(s),l=s.nextSibling;if(l==t){o?.breakAfter&&!l&&i!=this.view.contentDOM&&this.lineBreak();break}let a=Q.get(l);(o&&a?o.breakAfter:(o?o.breakAfter:Xn(s))||Xn(l)&&(s.nodeName!="BR"||o?.isWidget())&&this.text.length>r)&&!gp(l,t)&&this.lineBreak(),s=l}return this.findPointBefore(i,t),this}readTextNode(e){let t=e.nodeValue;for(let i of this.points)i.node==e&&(i.pos=this.text.length+Math.min(i.offset,t.length));for(let i=0,s=this.lineSeparator?null:/\r\n?|\n/g;;){let r=-1,o=1,l;if(this.lineSeparator?(r=t.indexOf(this.lineSeparator,i),o=this.lineSeparator.length):(l=s.exec(t))&&(r=l.index,o=l[0].length),this.append(t.slice(i,r<0?t.length:r)),r<0)break;if(this.lineBreak(),o>1)for(let a of this.points)a.node==e&&a.pos>this.text.length&&(a.pos-=o-1);i=r+o}}readNode(e){let t=Q.get(e),i=t&&t.overrideDOMText;if(i!=null){this.findPointInside(e,i.length);for(let s=i.iter();!s.next().done;)s.lineBreak?this.lineBreak():this.append(s.value)}else e.nodeType==3?this.readTextNode(e):e.nodeName=="BR"?e.nextSibling&&this.lineBreak():e.nodeType==1&&this.readRange(e.firstChild,null)}findPointBefore(e,t){for(let i of this.points)i.node==e&&e.childNodes[i.offset]==t&&(i.pos=this.text.length)}findPointInside(e,t){for(let i of this.points)(e.nodeType==3?i.node==e:e.contains(i.node))&&(i.pos=this.text.length+(mp(e,i.node,i.offset)?t:0))}};function mp(n,e,t){for(;;){if(!e||t-1;let{impreciseHead:r,impreciseAnchor:o}=e.docView,l=e.state.selection;if(e.state.readOnly&&t>-1)this.newSel=null;else if(t>-1&&(this.bounds=tc(e.docView.tile,t,i,0))){let a=r||o?[]:yp(e),h=new ao(a,e);h.readRange(this.bounds.startDOM,this.bounds.endDOM),this.text=h.text,this.newSel=xp(a,this.bounds.from)}else{let a=e.observer.selectionRange,h=r&&r.node==a.focusNode&&r.offset==a.focusOffset||!jr(e.contentDOM,a.focusNode)?l.main.head:e.docView.posFromDOM(a.focusNode,a.focusOffset),c=o&&o.node==a.anchorNode&&o.offset==a.anchorOffset||!jr(e.contentDOM,a.anchorNode)?l.main.anchor:e.docView.posFromDOM(a.anchorNode,a.anchorOffset),f=e.viewport;if((O.ios||O.chrome)&&l.main.empty&&h!=c&&(f.from>0||f.to-1&&l.ranges.length>1)this.newSel=l.replaceRange(x.range(c,h));else if(e.lineWrapping&&c==h&&!(l.main.empty&&l.main.head==h)&&e.inputState.lastTouchTime>Date.now()-100){let u=e.coordsAtPos(h,-1),d=0;u&&(d=e.inputState.lastTouchY<=u.bottom?-1:1),this.newSel=x.create([x.cursor(h,d)])}else this.newSel=x.single(c,h)}}};function tc(n,e,t,i){if(n.isComposite()){let s=-1,r=-1,o=-1,l=-1;for(let a=0,h=i,c=i;at)return tc(f,e,t,h);if(u>=e&&s==-1&&(s=a,r=h),h>t&&f.dom.parentNode==n.dom){o=a,l=c;break}c=u,h=u+f.breakAfter}return{from:r,to:l<0?i+n.length:l,startDOM:(s?n.children[s-1].dom.nextSibling:null)||n.dom.firstChild,endDOM:o=0?n.children[o].dom:null}}else return n.isText()?{from:i,to:i+n.length,startDOM:n.dom,endDOM:n.dom.nextSibling}:null}function ic(n,e){let t,{newSel:i}=e,{state:s}=n,r=s.selection.main,o=n.inputState.lastKeyTime>Date.now()-100?n.inputState.lastKeyCode:-1;if(e.bounds){let{from:l,to:a}=e.bounds,h=r.from,c=null;(o===8||O.android&&e.text.length=l&&r.to<=a&&(e.typeOver||f!=e.text)&&f.slice(0,r.from-l)==e.text.slice(0,r.from-l)&&f.slice(r.to-l)==e.text.slice(u=e.text.length-(f.length-(r.to-l)))?t={from:r.from,to:r.to,insert:N.of(e.text.slice(r.from-l,u).split(si))}:(d=nc(f,e.text,h-l,c))&&(O.chrome&&o==13&&d.toB==d.from+2&&e.text.slice(d.from,d.toB)==si+si&&d.toB--,t={from:l+d.from,to:l+d.toA,insert:N.of(e.text.slice(d.from,d.toB).split(si))})}else i&&(!n.hasFocus&&s.facet(ht)||is(i,r))&&(i=null);if(!t&&!i)return!1;if((O.mac||O.android)&&t&&t.from==t.to&&t.from==r.head-1&&/^\. ?$/.test(t.insert.toString())&&n.contentDOM.getAttribute("autocorrect")=="off"?(i&&t.insert.length==2&&(i=x.single(i.main.anchor-1,i.main.head-1)),t={from:t.from,to:t.to,insert:N.of([t.insert.toString().replace("."," ")])}):s.doc.lineAt(r.from).toDate.now()-50?t={from:r.from,to:r.to,insert:s.toText(n.inputState.insertingText)}:O.chrome&&t&&t.from==t.to&&t.from==r.head&&t.insert.toString()==` + `&&n.lineWrapping&&(i&&(i=x.single(i.main.anchor-1,i.main.head-1)),t={from:r.from,to:r.to,insert:N.of([" "])}),t)return jo(n,t,i,o);if(i&&!is(i,r)){let l=!1,a="select";return n.inputState.lastSelectionTime>Date.now()-50&&(n.inputState.lastSelectionOrigin=="select"&&(l=!0),a=n.inputState.lastSelectionOrigin,a=="select.pointer"&&(i=ec(s.facet(Yi).map(h=>h(n)),i))),n.dispatch({selection:i,scrollIntoView:l,userEvent:a}),!0}else return!1}function jo(n,e,t,i=-1){if(O.ios&&n.inputState.flushIOSKey(e))return!0;let s=n.state.selection.main;if(O.android&&(e.to==s.to&&(e.from==s.from||e.from==s.from-1&&n.state.sliceDoc(e.from,s.from)==" ")&&e.insert.length==1&&e.insert.lines==2&&ci(n.contentDOM,"Enter",13)||(e.from==s.from-1&&e.to==s.to&&e.insert.length==0||i==8&&e.insert.lengths.head)&&ci(n.contentDOM,"Backspace",8)||e.from==s.from&&e.to==s.to+1&&e.insert.length==0&&ci(n.contentDOM,"Delete",46)))return!0;let r=e.insert.toString();n.inputState.composing>=0&&n.inputState.composing++;let o,l=()=>o||(o=bp(n,e,t));return n.state.facet(qh).some(a=>a(n,e.from,e.to,r,l))||n.dispatch(l()),!0}function bp(n,e,t){let i,s=n.state,r=s.selection.main,o=-1;if(e.from==e.to&&e.fromr.to){let a=e.fromf(n)),h,a);e.from==c&&(o=c)}if(o>-1)i={changes:e,selection:x.cursor(e.from+e.insert.length,-1)};else if(e.from>=r.from&&e.to<=r.to&&e.to-e.from>=(r.to-r.from)/3&&(!t||t.main.empty&&t.main.from==e.from+e.insert.length)&&n.inputState.composing<0){let a=r.frome.to?s.sliceDoc(e.to,r.to):"";i=s.replaceSelection(n.state.toText(a+e.insert.sliceString(0,void 0,n.state.lineBreak)+h))}else{let a=s.changes(e),h=t&&t.main.to<=a.newLength?t.main:void 0;if(s.selection.ranges.length>1&&(n.inputState.composing>=0||n.inputState.compositionPendingChange)&&e.to<=r.to+10&&e.to>=r.to-10){let c=n.state.sliceDoc(e.from,e.to),f,u=t&&Zh(n,t.main.head);if(u){let p=e.insert.length-(e.to-e.from);f={from:u.from,to:u.to-p}}else f=n.state.doc.lineAt(r.head);let d=r.to-e.to;i=s.changeByRange(p=>{if(p.from==r.from&&p.to==r.to)return{changes:a,range:h||p.map(a)};let m=p.to-d,g=m-c.length;if(n.state.sliceDoc(g,m)!=c||m>=f.from&&g<=f.to)return{range:p};let b=s.changes({from:g,to:m,insert:e.insert}),w=p.to-r.to;return{changes:b,range:h?x.range(Math.max(0,h.anchor+w),Math.max(0,h.head+w)):p.map(b)}})}else i={changes:a,selection:h&&s.selection.replaceRange(h)}}let l="input.type";return(n.composing||n.inputState.compositionPendingChange&&n.inputState.compositionEndedAt>Date.now()-50)&&(n.inputState.compositionPendingChange=!1,l+=".compose",n.inputState.compositionFirstChange&&(l+=".start",n.inputState.compositionFirstChange=!1)),s.update(i,{userEvent:l,scrollIntoView:!0})}function nc(n,e,t,i){let s=Math.min(n.length,e.length),r=0;for(;r0&&l>0&&n.charCodeAt(o-1)==e.charCodeAt(l-1);)o--,l--;if(i=="end"){let a=Math.max(0,r-Math.min(o,l));t-=o+a-r}if(o=o?r-t:0;r-=a,l=r+(l-o),o=r}else if(l=l?r-t:0;r-=a,o=r+(o-l),l=r}return{from:r,toA:o,toB:l}}function yp(n){let e=[];if(n.root.activeElement!=n.contentDOM)return e;let{anchorNode:t,anchorOffset:i,focusNode:s,focusOffset:r}=n.observer.selectionRange;return t&&(e.push(new ts(t,i)),(s!=t||r!=i)&&e.push(new ts(s,r))),e}function xp(n,e){if(n.length==0)return null;let t=n[0].pos,i=n.length==2?n[1].pos:t;return t>-1&&i>-1?x.single(t+e,i+e):null}function is(n,e){return e.head==n.main.head&&e.anchor==n.main.anchor}var co=class{setSelectionOrigin(e){this.lastSelectionOrigin=e,this.lastSelectionTime=Date.now()}constructor(e){this.view=e,this.lastKeyCode=0,this.lastKeyTime=0,this.lastTouchTime=0,this.lastTouchX=0,this.lastTouchY=0,this.lastFocusTime=0,this.lastScrollTop=0,this.lastScrollLeft=0,this.lastWheelEvent=0,this.pendingIOSKey=void 0,this.tabFocusMode=-1,this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastContextMenu=0,this.scrollHandlers=[],this.handlers=Object.create(null),this.composing=-1,this.compositionFirstChange=null,this.compositionEndedAt=0,this.compositionPendingKey=!1,this.compositionPendingChange=!1,this.insertingText="",this.insertingTextAt=0,this.mouseSelection=null,this.draggedContent=null,this.handleEvent=this.handleEvent.bind(this),this.notifiedFocused=e.hasFocus,O.safari&&e.contentDOM.addEventListener("input",()=>null),O.gecko&&Lp(e.contentDOM.ownerDocument)}handleEvent(e){!Mp(this.view,e)||this.ignoreDuringComposition(e)||e.type=="keydown"&&this.keydown(e)||(this.view.updateState!=0?Promise.resolve().then(()=>this.runHandlers(e.type,e)):this.runHandlers(e.type,e))}runHandlers(e,t){let i=this.handlers[e];if(i){for(let s of i.observers)s(this.view,t);for(let s of i.handlers){if(t.defaultPrevented)break;if(s(this.view,t)){t.preventDefault();break}}}}ensureHandlers(e){let t=wp(e),i=this.handlers,s=this.view.contentDOM;for(let r in t)if(r!="scroll"){let o=!t[r].handlers.length,l=i[r];l&&o!=!l.handlers.length&&(s.removeEventListener(r,this.handleEvent),l=null),l||s.addEventListener(r,this.handleEvent,{passive:o})}for(let r in i)r!="scroll"&&!t[r]&&s.removeEventListener(r,this.handleEvent);this.handlers=t}keydown(e){if(this.lastKeyCode=e.keyCode,this.lastKeyTime=Date.now(),e.keyCode==9&&this.tabFocusMode>-1&&(!this.tabFocusMode||Date.now()<=this.tabFocusMode))return!0;if(this.tabFocusMode>0&&e.keyCode!=27&&rc.indexOf(e.keyCode)<0&&(this.tabFocusMode=-1),O.android&&O.chrome&&!e.synthetic&&(e.keyCode==13||e.keyCode==8))return this.view.observer.delayAndroidKey(e.key,e.keyCode),!0;let t;return O.ios&&!e.synthetic&&!e.altKey&&!e.metaKey&&!e.shiftKey&&((t=sc.find(i=>i.keyCode==e.keyCode))&&!e.ctrlKey||kp.indexOf(e.key)>-1&&e.ctrlKey)?(this.pendingIOSKey=t||e,setTimeout(()=>this.flushIOSKey(),250),!0):(e.keyCode!=229&&this.view.observer.forceFlush(),!1)}flushIOSKey(e){let t=this.pendingIOSKey;return!t||t.key=="Enter"&&e&&e.from0?!0:O.safari&&!O.ios&&this.compositionPendingKey&&Date.now()-this.compositionEndedAt<100?(this.compositionPendingKey=!1,!0):!1}startMouseSelection(e){this.mouseSelection&&this.mouseSelection.destroy(),this.mouseSelection=e}update(e){this.view.observer.update(e),this.mouseSelection&&this.mouseSelection.update(e),this.draggedContent&&e.docChanged&&(this.draggedContent=this.draggedContent.map(e.changes)),e.transactions.length&&(this.lastKeyCode=this.lastSelectionTime=0)}destroy(){this.mouseSelection&&this.mouseSelection.destroy()}};function Qa(n,e){return(t,i)=>{try{return e.call(n,i,t)}catch(s){ne(t.state,s)}}}function wp(n){let e=Object.create(null);function t(i){return e[i]||(e[i]={observers:[],handlers:[]})}for(let i of n){let s=i.spec,r=s&&s.plugin.domEventHandlers,o=s&&s.plugin.domEventObservers;if(r)for(let l in r){let a=r[l];a&&t(l).handlers.push(Qa(i.value,a))}if(o)for(let l in o){let a=o[l];a&&t(l).observers.push(Qa(i.value,a))}}for(let i in Ke)t(i).handlers.push(Ke[i]);for(let i in we)t(i).observers.push(we[i]);return e}var sc=[{key:"Backspace",keyCode:8,inputType:"deleteContentBackward"},{key:"Enter",keyCode:13,inputType:"insertParagraph"},{key:"Enter",keyCode:13,inputType:"insertLineBreak"},{key:"Delete",keyCode:46,inputType:"deleteContentForward"}],kp="dthko",rc=[16,17,18,20,91,92,224,225],In=6;function Nn(n){return Math.max(0,n)*.7+8}function vp(n,e){return Math.max(Math.abs(n.clientX-e.clientX),Math.abs(n.clientY-e.clientY))}var fo=class{constructor(e,t,i,s){this.view=e,this.startEvent=t,this.style=i,this.mustSelect=s,this.scrollSpeed={x:0,y:0},this.scrolling=-1,this.lastEvent=t,this.scrollParents=Oh(e.contentDOM),this.atoms=e.state.facet(Yi).map(o=>o(e));let r=e.contentDOM.ownerDocument;r.addEventListener("mousemove",this.move=this.move.bind(this)),r.addEventListener("mouseup",this.up=this.up.bind(this)),this.extend=t.shiftKey,this.multiple=e.state.facet($.allowMultipleSelections)&&Sp(e,t),this.dragging=Ap(e,t)&&ac(t)==1?null:!1}start(e){this.dragging===!1&&this.select(e)}move(e){if(e.buttons==0)return this.destroy();if(this.dragging||this.dragging==null&&vp(this.startEvent,e)<10)return;this.select(this.lastEvent=e);let t=0,i=0,s=0,r=0,o=this.view.win.innerWidth,l=this.view.win.innerHeight;this.scrollParents.x&&({left:s,right:o}=this.scrollParents.x.getBoundingClientRect()),this.scrollParents.y&&({top:r,bottom:l}=this.scrollParents.y.getBoundingClientRect());let a=Ko(this.view);e.clientX-a.left<=s+In?t=-Nn(s-e.clientX):e.clientX+a.right>=o-In&&(t=Nn(e.clientX-o)),e.clientY-a.top<=r+In?i=-Nn(r-e.clientY):e.clientY+a.bottom>=l-In&&(i=Nn(e.clientY-l)),this.setScrollSpeed(t,i)}up(e){this.dragging==null&&this.select(this.lastEvent),this.dragging||e.preventDefault(),this.destroy()}destroy(){this.setScrollSpeed(0,0);let e=this.view.contentDOM.ownerDocument;e.removeEventListener("mousemove",this.move),e.removeEventListener("mouseup",this.up),this.view.inputState.mouseSelection=this.view.inputState.draggedContent=null}setScrollSpeed(e,t){this.scrollSpeed={x:e,y:t},e||t?this.scrolling<0&&(this.scrolling=setInterval(()=>this.scroll(),50)):this.scrolling>-1&&(clearInterval(this.scrolling),this.scrolling=-1)}scroll(){let{x:e,y:t}=this.scrollSpeed;e&&this.scrollParents.x&&(this.scrollParents.x.scrollLeft+=e,e=0),t&&this.scrollParents.y&&(this.scrollParents.y.scrollTop+=t,t=0),(e||t)&&this.view.win.scrollBy(e,t),this.dragging===!1&&this.select(this.lastEvent)}select(e){let{view:t}=this,i=ec(this.atoms,this.style.get(e,this.extend,this.multiple));(this.mustSelect||!i.eq(t.state.selection,this.dragging===!1))&&this.view.dispatch({selection:i,userEvent:"select.pointer"}),this.mustSelect=!1}update(e){e.transactions.some(t=>t.isUserEvent("input.type"))?this.destroy():this.style.update(e)&&setTimeout(()=>this.select(this.lastEvent),20)}};function Sp(n,e){let t=n.state.facet(Wh);return t.length?t[0](e):O.mac?e.metaKey:e.ctrlKey}function Cp(n,e){let t=n.state.facet(Hh);return t.length?t[0](e):O.mac?!e.altKey:!e.ctrlKey}function Ap(n,e){let{main:t}=n.state.selection;if(t.empty)return!1;let i=Gi(n.root);if(!i||i.rangeCount==0)return!0;let s=i.getRangeAt(0).getClientRects();for(let r=0;r=e.clientX&&o.top<=e.clientY&&o.bottom>=e.clientY)return!0}return!1}function Mp(n,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let t=e.target,i;t!=n.contentDOM;t=t.parentNode)if(!t||t.nodeType==11||(i=Q.get(t))&&i.isWidget()&&!i.isHidden&&i.widget.ignoreEvent(e))return!1;return!0}var Ke=Object.create(null),we=Object.create(null),oc=O.ie&&O.ie_version<15||O.ios&&O.webkit_version<604;function Tp(n){let e=n.dom.parentNode;if(!e)return;let t=e.appendChild(document.createElement("textarea"));t.style.cssText="position: fixed; left: -10000px; top: 10px",t.focus(),setTimeout(()=>{n.focus(),t.remove(),lc(n,t.value)},50)}function ps(n,e,t){for(let i of n.facet(e))t=i(t,n);return t}function lc(n,e){e=ps(n.state,Vo,e);let{state:t}=n,i,s=1,r=t.toText(e),o=r.lines==t.selection.ranges.length;if(uo!=null&&t.selection.ranges.every(a=>a.empty)&&uo==r.toString()){let a=-1;i=t.changeByRange(h=>{let c=t.doc.lineAt(h.from);if(c.from==a)return{range:h};a=c.from;let f=t.toText((o?r.line(s++).text:e)+t.lineBreak);return{changes:{from:c.from,insert:f},range:x.cursor(h.from+f.length)}})}else o?i=t.changeByRange(a=>{let h=r.line(s++);return{changes:{from:a.from,to:a.to,insert:h.text},range:x.cursor(a.from+h.length)}}):i=t.replaceSelection(r);n.dispatch(i,{userEvent:"input.paste",scrollIntoView:!0})}we.scroll=n=>{n.inputState.lastScrollTop=n.scrollDOM.scrollTop,n.inputState.lastScrollLeft=n.scrollDOM.scrollLeft};we.wheel=we.mousewheel=n=>{n.inputState.lastWheelEvent=Date.now()};Ke.keydown=(n,e)=>(n.inputState.setSelectionOrigin("select"),e.keyCode==27&&n.inputState.tabFocusMode!=0&&(n.inputState.tabFocusMode=Date.now()+2e3),!1);we.touchstart=(n,e)=>{let t=n.inputState,i=e.targetTouches[0];t.lastTouchTime=Date.now(),i&&(t.lastTouchX=i.clientX,t.lastTouchY=i.clientY),t.setSelectionOrigin("select.pointer")};we.touchmove=n=>{n.inputState.setSelectionOrigin("select.pointer")};Ke.mousedown=(n,e)=>{if(n.observer.flush(),n.inputState.lastTouchTime>Date.now()-2e3)return!1;let t=null;for(let i of n.state.facet(Vh))if(t=i(n,e),t)break;if(!t&&e.button==0&&(t=Dp(n,e)),t){let i=!n.hasFocus;n.inputState.startMouseSelection(new fo(n,e,t,i)),i&&n.observer.ignore(()=>{Dh(n.contentDOM);let r=n.root.activeElement;r&&!r.contains(n.contentDOM)&&r.blur()});let s=n.inputState.mouseSelection;if(s)return s.start(e),s.dragging===!1}else n.inputState.setSelectionOrigin("select.pointer");return!1};function Ja(n,e,t,i){if(i==1)return x.cursor(e,t);if(i==2)return cp(n.state,e,t);{let s=n.docView.lineAt(e,t),r=n.state.doc.lineAt(s?s.posAtEnd:e),o=s?s.posAtStart:r.from,l=s?s.posAtEnd:r.to;return lDate.now()-400&&Math.abs(e.clientX-n.clientX)<2&&Math.abs(e.clientY-n.clientY)<2?(eh+1)%3:1}function Dp(n,e){let t=n.posAndSideAtCoords({x:e.clientX,y:e.clientY},!1),i=ac(e),s=n.state.selection;return{update(r){r.docChanged&&(t.pos=r.changes.mapPos(t.pos),s=s.map(r.changes))},get(r,o,l){let a=n.posAndSideAtCoords({x:r.clientX,y:r.clientY},!1),h,c=Ja(n,a.pos,a.assoc,i);if(t.pos!=a.pos&&!o){let f=Ja(n,t.pos,t.assoc,i),u=Math.min(f.from,c.from),d=Math.max(f.to,c.to);c=u1&&(h=Pp(s,a.pos))?h:l?s.addRange(c):x.create([c])}}}function Pp(n,e){for(let t=0;t=e)return x.create(n.ranges.slice(0,t).concat(n.ranges.slice(t+1)),n.mainIndex==t?0:n.mainIndex-(n.mainIndex>t?1:0))}return null}Ke.dragstart=(n,e)=>{let{selection:{main:t}}=n.state;if(e.target.draggable){let s=n.docView.tile.nearest(e.target);if(s&&s.isWidget()){let r=s.posAtStart,o=r+s.length;(r>=t.to||o<=t.from)&&(t=x.range(r,o))}}let{inputState:i}=n;return i.mouseSelection&&(i.mouseSelection.dragging=!0),i.draggedContent=t,e.dataTransfer&&(e.dataTransfer.setData("Text",ps(n.state,zo,n.state.sliceDoc(t.from,t.to))),e.dataTransfer.effectAllowed="copyMove"),!1};Ke.dragend=n=>(n.inputState.draggedContent=null,!1);function ih(n,e,t,i){if(t=ps(n.state,Vo,t),!t)return;let s=n.posAtCoords({x:e.clientX,y:e.clientY},!1),{draggedContent:r}=n.inputState,o=i&&r&&Cp(n,e)?{from:r.from,to:r.to}:null,l={from:s,insert:t},a=n.state.changes(o?[o,l]:l);n.focus(),n.dispatch({changes:a,selection:{anchor:a.mapPos(s,-1),head:a.mapPos(s,1)},userEvent:o?"move.drop":"input.drop"}),n.inputState.draggedContent=null}Ke.drop=(n,e)=>{if(!e.dataTransfer)return!1;if(n.state.readOnly)return!0;let t=e.dataTransfer.files;if(t&&t.length){let i=Array(t.length),s=0,r=()=>{++s==t.length&&ih(n,e,i.filter(o=>o!=null).join(n.state.lineBreak),!1)};for(let o=0;o{/[\x00-\x08\x0e-\x1f]{2}/.test(l.result)||(i[o]=l.result),r()},l.readAsText(t[o])}return!0}else{let i=e.dataTransfer.getData("Text");if(i)return ih(n,e,i,!0),!0}return!1};Ke.paste=(n,e)=>{if(n.state.readOnly)return!0;n.observer.flush();let t=oc?null:e.clipboardData;return t?(lc(n,t.getData("text/plain")||t.getData("text/uri-list")),!0):(Tp(n),!1)};function Bp(n,e){let t=n.dom.parentNode;if(!t)return;let i=t.appendChild(document.createElement("textarea"));i.style.cssText="position: fixed; left: -10000px; top: 10px",i.value=e,i.focus(),i.selectionEnd=e.length,i.selectionStart=0,setTimeout(()=>{i.remove(),n.focus()},50)}function Rp(n){let e=[],t=[],i=!1;for(let s of n.selection.ranges)s.empty||(e.push(n.sliceDoc(s.from,s.to)),t.push(s));if(!e.length){let s=-1;for(let{from:r}of n.selection.ranges){let o=n.doc.lineAt(r);o.number>s&&(e.push(o.text),t.push({from:o.from,to:Math.min(n.doc.length,o.to+1)})),s=o.number}i=!0}return{text:ps(n,zo,e.join(n.lineBreak)),ranges:t,linewise:i}}var uo=null;Ke.copy=Ke.cut=(n,e)=>{if(!Ni(n.contentDOM,n.observer.selectionRange))return!1;let{text:t,ranges:i,linewise:s}=Rp(n.state);if(!t&&!s)return!1;uo=s?t:null,e.type=="cut"&&!n.state.readOnly&&n.dispatch({changes:i,scrollIntoView:!0,userEvent:"delete.cut"});let r=oc?null:e.clipboardData;return r?(r.clearData(),r.setData("text/plain",t),!0):(Bp(n,t),!1)};var hc=be.define();function cc(n,e){let t=[];for(let i of n.facet($h)){let s=i(n,e);s&&t.push(s)}return t.length?n.update({effects:t,annotations:hc.of(!0)}):null}function fc(n){setTimeout(()=>{let e=n.hasFocus;if(e!=n.inputState.notifiedFocused){let t=cc(n.state,e);t?n.dispatch(t):n.update([])}},10)}we.focus=n=>{n.inputState.lastFocusTime=Date.now(),!n.scrollDOM.scrollTop&&(n.inputState.lastScrollTop||n.inputState.lastScrollLeft)&&(n.scrollDOM.scrollTop=n.inputState.lastScrollTop,n.scrollDOM.scrollLeft=n.inputState.lastScrollLeft),fc(n)};we.blur=n=>{n.observer.clearSelectionRange(),fc(n)};we.compositionstart=we.compositionupdate=n=>{n.observer.editContext||(n.inputState.compositionFirstChange==null&&(n.inputState.compositionFirstChange=!0),n.inputState.composing<0&&(n.inputState.composing=0))};we.compositionend=n=>{n.observer.editContext||(n.inputState.composing=-1,n.inputState.compositionEndedAt=Date.now(),n.inputState.compositionPendingKey=!0,n.inputState.compositionPendingChange=n.observer.pendingRecords().length>0,n.inputState.compositionFirstChange=null,O.chrome&&O.android?n.observer.flushSoon():n.inputState.compositionPendingChange?Promise.resolve().then(()=>n.observer.flush()):setTimeout(()=>{n.inputState.composing<0&&n.docView.hasComposition&&n.update([])},50))};we.contextmenu=n=>{n.inputState.lastContextMenu=Date.now()};Ke.beforeinput=(n,e)=>{var t,i;if((e.inputType=="insertText"||e.inputType=="insertCompositionText")&&(n.inputState.insertingText=e.data,n.inputState.insertingTextAt=Date.now()),e.inputType=="insertReplacementText"&&n.observer.editContext){let r=(t=e.dataTransfer)===null||t===void 0?void 0:t.getData("text/plain"),o=e.getTargetRanges();if(r&&o.length){let l=o[0],a=n.posAtDOM(l.startContainer,l.startOffset),h=n.posAtDOM(l.endContainer,l.endOffset);return jo(n,{from:a,to:h,insert:n.state.toText(r)},null),!0}}let s;if(O.chrome&&O.android&&(s=sc.find(r=>r.inputType==e.inputType))&&(n.observer.delayAndroidKey(s.key,s.keyCode),s.key=="Backspace"||s.key=="Delete")){let r=((i=window.visualViewport)===null||i===void 0?void 0:i.height)||0;setTimeout(()=>{var o;(((o=window.visualViewport)===null||o===void 0?void 0:o.height)||0)>r+10&&n.hasFocus&&(n.contentDOM.blur(),n.focus())},100)}return O.ios&&e.inputType=="deleteContentForward"&&n.observer.flushSoon(),O.safari&&e.inputType=="insertText"&&n.inputState.composing>=0&&setTimeout(()=>we.compositionend(n,e),20),!1};var nh=new Set;function Lp(n){nh.has(n)||(nh.add(n),n.addEventListener("copy",()=>{}),n.addEventListener("cut",()=>{}))}var sh=["pre-wrap","normal","pre-line","break-spaces"],mi=!1;function rh(){mi=!1}var po=class{constructor(e){this.lineWrapping=e,this.doc=N.empty,this.heightSamples={},this.lineHeight=14,this.charWidth=7,this.textHeight=14,this.lineLength=30}heightForGap(e,t){let i=this.doc.lineAt(t).number-this.doc.lineAt(e).number+1;return this.lineWrapping&&(i+=Math.max(0,Math.ceil((t-e-i*this.lineLength*.5)/this.lineLength))),this.lineHeight*i}heightForLine(e){return this.lineWrapping?(1+Math.max(0,Math.ceil((e-this.lineLength)/Math.max(1,this.lineLength-5))))*this.lineHeight:this.lineHeight}setDoc(e){return this.doc=e,this}mustRefreshForWrapping(e){return sh.indexOf(e)>-1!=this.lineWrapping}mustRefreshForHeights(e){let t=!1;for(let i=0;i-1,a=Math.abs(t-this.lineHeight)>.3||this.lineWrapping!=l;if(this.lineWrapping=l,this.lineHeight=t,this.charWidth=i,this.textHeight=s,this.lineLength=r,a){this.heightSamples={};for(let h=0;h0}set outdated(e){this.flags=(e?2:0)|this.flags&-3}setHeight(e){this.height!=e&&(Math.abs(this.height-e)>Kn&&(mi=!0),this.height=e)}replace(e,t,i){return n.of(i)}decomposeLeft(e,t){t.push(this)}decomposeRight(e,t){t.push(this)}applyChanges(e,t,i,s){let r=this,o=i.doc;for(let l=s.length-1;l>=0;l--){let{fromA:a,toA:h,fromB:c,toB:f}=s[l],u=r.lineAt(a,_.ByPosNoHeight,i.setDoc(t),0,0),d=u.to>=h?u:r.lineAt(h,_.ByPosNoHeight,i,0,0);for(f+=d.to-h,h=d.to;l>0&&u.from<=s[l-1].toA;)a=s[l-1].fromA,c=s[l-1].fromB,l--,ar*2){let l=e[t-1];l.break?e.splice(--t,1,l.left,null,l.right):e.splice(--t,1,l.left,l.right),i+=1+l.break,s-=l.size}else if(r>s*2){let l=e[i];l.break?e.splice(i,1,l.left,null,l.right):e.splice(i,1,l.left,l.right),i+=2+l.break,r-=l.size}else break;else if(s=r&&o(this.lineAt(0,_.ByPos,i,s,r))}setMeasuredHeight(e){let t=e.heights[e.index++];t<0?(this.spaceAbove=-t,t=e.heights[e.index++]):this.spaceAbove=0,this.setHeight(t)}updateHeight(e,t=0,i=!1,s){return s&&s.from<=t&&s.more&&this.setMeasuredHeight(s),this.outdated=!1,this}toString(){return`block(${this.length})`}},Ne=class n extends ss{constructor(e,t,i){super(e,t,null),this.collapsed=0,this.widgetHeight=0,this.breaks=0,this.spaceAbove=i}mainBlock(e,t){return new qe(t,this.length,e+this.spaceAbove,this.height-this.spaceAbove,this.breaks)}replace(e,t,i){let s=i[0];return i.length==1&&(s instanceof n||s instanceof gt&&s.flags&4)&&Math.abs(this.length-s.length)<10?(s instanceof gt?s=new n(s.length,this.height,this.spaceAbove):s.height=this.height,this.outdated||(s.outdated=!1),s):Te.of(i)}updateHeight(e,t=0,i=!1,s){return s&&s.from<=t&&s.more?this.setMeasuredHeight(s):(i||this.outdated)&&(this.spaceAbove=0,this.setHeight(Math.max(this.widgetHeight,e.heightForLine(this.length-this.collapsed))+this.breaks*e.lineHeight)),this.outdated=!1,this}toString(){return`line(${this.length}${this.collapsed?-this.collapsed:""}${this.widgetHeight?":"+this.widgetHeight:""})`}},gt=class n extends Te{constructor(e){super(e,0)}heightMetrics(e,t){let i=e.doc.lineAt(t).number,s=e.doc.lineAt(t+this.length).number,r=s-i+1,o,l=0;if(e.lineWrapping){let a=Math.min(this.height,e.lineHeight*r);o=a/r,this.length>r+1&&(l=(this.height-a)/(this.length-r-1))}else o=this.height/r;return{firstLine:i,lastLine:s,perLine:o,perChar:l}}blockAt(e,t,i,s){let{firstLine:r,lastLine:o,perLine:l,perChar:a}=this.heightMetrics(t,s);if(t.lineWrapping){let h=s+(e0){let r=i[i.length-1];r instanceof n?i[i.length-1]=new n(r.length+s):i.push(null,new n(s-1))}if(e>0){let r=i[0];r instanceof n?i[0]=new n(e+r.length):i.unshift(new n(e-1),null)}return Te.of(i)}decomposeLeft(e,t){t.push(new n(e-1),null)}decomposeRight(e,t){t.push(null,new n(this.length-e-1))}updateHeight(e,t=0,i=!1,s){let r=t+this.length;if(s&&s.from<=t+this.length&&s.more){let o=[],l=Math.max(t,s.from),a=-1;for(s.from>t&&o.push(new n(s.from-t-1).updateHeight(e,t));l<=r&&s.more;){let c=e.doc.lineAt(l).length;o.length&&o.push(null);let f=s.heights[s.index++],u=0;f<0&&(u=-f,f=s.heights[s.index++]),a==-1?a=f:Math.abs(f-a)>=Kn&&(a=-2);let d=new Ne(c,f,u);d.outdated=!1,o.push(d),l+=c+1}l<=r&&o.push(null,new n(r-l).updateHeight(e,l));let h=Te.of(o);return(a<0||Math.abs(h.height-this.height)>=Kn||Math.abs(a-this.heightMetrics(e,t).perLine)>=Kn)&&(mi=!0),ns(this,h)}else(i||this.outdated)&&(this.setHeight(e.heightForGap(t,t+this.length)),this.outdated=!1);return this}toString(){return`gap(${this.length})`}},go=class extends Te{constructor(e,t,i){super(e.length+t+i.length,e.height+i.height,t|(e.outdated||i.outdated?2:0)),this.left=e,this.right=i,this.size=e.size+i.size}get break(){return this.flags&1}blockAt(e,t,i,s){let r=i+this.left.height;return el))return h;let c=t==_.ByPosNoHeight?_.ByPosNoHeight:_.ByPos;return a?h.join(this.right.lineAt(l,c,i,o,l)):this.left.lineAt(l,c,i,s,r).join(h)}forEachLine(e,t,i,s,r,o){let l=s+this.left.height,a=r+this.left.length+this.break;if(this.break)e=a&&this.right.forEachLine(e,t,i,l,a,o);else{let h=this.lineAt(a,_.ByPos,i,s,r);e=e&&h.from<=t&&o(h),t>h.to&&this.right.forEachLine(h.to+1,t,i,l,a,o)}}replace(e,t,i){let s=this.left.length+this.break;if(tthis.left.length)return this.balanced(this.left,this.right.replace(e-s,t-s,i));let r=[];e>0&&this.decomposeLeft(e,r);let o=r.length;for(let l of i)r.push(l);if(e>0&&oh(r,o-1),t=i&&t.push(null)),e>i&&this.right.decomposeLeft(e-i,t)}decomposeRight(e,t){let i=this.left.length,s=i+this.break;if(e>=s)return this.right.decomposeRight(e-s,t);e2*t.size||t.size>2*e.size?Te.of(this.break?[e,null,t]:[e,t]):(this.left=ns(this.left,e),this.right=ns(this.right,t),this.setHeight(e.height+t.height),this.outdated=e.outdated||t.outdated,this.size=e.size+t.size,this.length=e.length+this.break+t.length,this)}updateHeight(e,t=0,i=!1,s){let{left:r,right:o}=this,l=t+r.length+this.break,a=null;return s&&s.from<=t+r.length&&s.more?a=r=r.updateHeight(e,t,i,s):r.updateHeight(e,t,i),s&&s.from<=l+o.length&&s.more?a=o=o.updateHeight(e,l,i,s):o.updateHeight(e,l,i),a?this.balanced(r,o):(this.height=this.left.height+this.right.height,this.outdated=!1,this)}toString(){return this.left+(this.break?" ":"-")+this.right}};function oh(n,e){let t,i;n[e]==null&&(t=n[e-1])instanceof gt&&(i=n[e+1])instanceof gt&&n.splice(e-1,3,new gt(t.length+1+i.length))}var Ip=5,bo=class n{constructor(e,t){this.pos=e,this.oracle=t,this.nodes=[],this.lineStart=-1,this.lineEnd=-1,this.covering=null,this.writtenTo=e}get isCovered(){return this.covering&&this.nodes[this.nodes.length-1]==this.covering}span(e,t){if(this.lineStart>-1){let i=Math.min(t,this.lineEnd),s=this.nodes[this.nodes.length-1];s instanceof Ne?s.length+=i-this.pos:(i>this.pos||!this.isCovered)&&this.nodes.push(new Ne(i-this.pos,-1,0)),this.writtenTo=i,t>i&&(this.nodes.push(null),this.writtenTo++,this.lineStart=-1)}this.pos=t}point(e,t,i){if(e=Ip)&&this.addLineDeco(s,r,o)}else t>e&&this.span(e,t);this.lineEnd>-1&&this.lineEnd-1)return;let{from:e,to:t}=this.oracle.doc.lineAt(this.pos);this.lineStart=e,this.lineEnd=t,this.writtenToe&&this.nodes.push(new Ne(this.pos-e,-1,0)),this.writtenTo=this.pos}blankContent(e,t){let i=new gt(t-e);return this.oracle.doc.lineAt(e).to==t&&(i.flags|=4),i}ensureLine(){this.enterLine();let e=this.nodes.length?this.nodes[this.nodes.length-1]:null;if(e instanceof Ne)return e;let t=new Ne(0,-1,0);return this.nodes.push(t),t}addBlock(e){this.enterLine();let t=e.deco;t&&t.startSide>0&&!this.isCovered&&this.ensureLine(),this.nodes.push(e),this.writtenTo=this.pos=this.pos+e.length,t&&t.endSide>0&&(this.covering=e)}addLineDeco(e,t,i){let s=this.ensureLine();s.length+=i,s.collapsed+=i,s.widgetHeight=Math.max(s.widgetHeight,e),s.breaks+=t,this.writtenTo=this.pos=this.pos+i}finish(e){let t=this.nodes.length==0?null:this.nodes[this.nodes.length-1];this.lineStart>-1&&!(t instanceof Ne)&&!this.isCovered?this.nodes.push(new Ne(0,-1,0)):(this.writtenToc.clientHeight||c.scrollWidth>c.clientWidth)&&f.overflow!="visible"){let u=c.getBoundingClientRect();r=Math.max(r,u.left),o=Math.min(o,u.right),l=Math.max(l,u.top),a=Math.min(h==n.parentNode?s.innerHeight:a,u.bottom)}h=f.position=="absolute"||f.position=="fixed"?c.offsetParent:c.parentNode}else if(h.nodeType==11)h=h.host;else break;return{left:r-t.left,right:Math.max(r,o)-t.left,top:l-(t.top+e),bottom:Math.max(l,a)-(t.top+e)}}function Wp(n){let e=n.getBoundingClientRect(),t=n.ownerDocument.defaultView||window;return e.left0&&e.top0}function Hp(n,e){let t=n.getBoundingClientRect();return{left:0,right:t.right-t.left,top:e,bottom:t.bottom-(t.top+e)}}var qi=class{constructor(e,t,i,s){this.from=e,this.to=t,this.size=i,this.displaySize=s}static same(e,t){if(e.length!=t.length)return!1;for(let i=0;itypeof s!="function"&&s.class=="cm-lineWrapping");this.heightOracle=new po(i),this.stateDeco=ah(t),this.heightMap=Te.empty().applyChanges(this.stateDeco,N.empty,this.heightOracle.setDoc(t.doc),[new $e(0,0,0,t.doc.length)]);for(let s=0;s<2&&(this.viewport=this.getViewport(0,null),!!this.updateForViewport());s++);this.updateViewportLines(),this.lineGaps=this.ensureLineGaps([]),this.lineGapDeco=P.set(this.lineGaps.map(s=>s.draw(this,!1))),this.scrollParent=e.scrollDOM,this.computeVisibleRanges()}updateForViewport(){let e=[this.viewport],{main:t}=this.state.selection;for(let i=0;i<=1;i++){let s=i?t.head:t.anchor;if(!e.some(({from:r,to:o})=>s>=r&&s<=o)){let{from:r,to:o}=this.lineBlockAt(s);e.push(new oi(r,o))}}return this.viewports=e.sort((i,s)=>i.from-s.from),this.updateScaler()}updateScaler(){let e=this.scaler;return this.scaler=this.heightMap.height<=7e6?lh:new wo(this.heightOracle,this.heightMap,this.viewports),e.eq(this.scaler)?0:2}updateViewportLines(){this.viewportLines=[],this.heightMap.forEachLine(this.viewport.from,this.viewport.to,this.heightOracle.setDoc(this.state.doc),0,0,e=>{this.viewportLines.push(Ei(e,this.scaler))})}update(e,t=null){this.state=e.state;let i=this.stateDeco;this.stateDeco=ah(this.state);let s=e.changedRanges,r=$e.extendWithRanges(s,Np(i,this.stateDeco,e?e.changes:me.empty(this.state.doc.length))),o=this.heightMap.height,l=this.scrolledToBottom?null:this.scrollAnchorAt(this.scrollOffset);rh(),this.heightMap=this.heightMap.applyChanges(this.stateDeco,e.startState.doc,this.heightOracle.setDoc(this.state.doc),r),(this.heightMap.height!=o||mi)&&(e.flags|=2),l?(this.scrollAnchorPos=e.changes.mapPos(l.from,-1),this.scrollAnchorHeight=l.top):(this.scrollAnchorPos=-1,this.scrollAnchorHeight=o);let a=r.length?this.mapViewport(this.viewport,e.changes):this.viewport;(t&&(t.range.heada.to)||!this.viewportIsAppropriate(a))&&(a=this.getViewport(0,t));let h=a.from!=this.viewport.from||a.to!=this.viewport.to;this.viewport=a,e.flags|=this.updateForViewport(),(h||!e.changes.empty||e.flags&2)&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps,e.changes))),e.flags|=this.computeVisibleRanges(e.changes),t&&(this.scrollTarget=t),!this.mustEnforceCursorAssoc&&(e.selectionSet||e.focusChanged)&&e.view.lineWrapping&&e.state.selection.main.empty&&e.state.selection.main.assoc&&!e.state.facet(jh)&&(this.mustEnforceCursorAssoc=!0)}measure(){let{view:e}=this,t=e.contentDOM,i=window.getComputedStyle(t),s=this.heightOracle,r=i.whiteSpace;this.defaultTextDirection=i.direction=="rtl"?z.RTL:z.LTR;let o=this.heightOracle.mustRefreshForWrapping(r)||this.mustMeasureContent==="refresh",l=t.getBoundingClientRect(),a=o||this.mustMeasureContent||this.contentDOMHeight!=l.height;this.contentDOMHeight=l.height,this.mustMeasureContent=!1;let h=0,c=0;if(l.width&&l.height){let{scaleX:v,scaleY:S}=Th(t,l);(v>.005&&Math.abs(this.scaleX-v)>.005||S>.005&&Math.abs(this.scaleY-S)>.005)&&(this.scaleX=v,this.scaleY=S,h|=16,o=a=!0)}let f=(parseInt(i.paddingTop)||0)*this.scaleY,u=(parseInt(i.paddingBottom)||0)*this.scaleY;(this.paddingTop!=f||this.paddingBottom!=u)&&(this.paddingTop=f,this.paddingBottom=u,h|=18),this.editorWidth!=e.scrollDOM.clientWidth&&(s.lineWrapping&&(a=!0),this.editorWidth=e.scrollDOM.clientWidth,h|=16);let d=Oh(this.view.contentDOM,!1).y;d!=this.scrollParent&&(this.scrollParent=d,this.scrollAnchorHeight=-1,this.scrollOffset=0);let p=this.getScrollOffset();this.scrollOffset!=p&&(this.scrollAnchorHeight=-1,this.scrollOffset=p),this.scrolledToBottom=Ph(this.scrollParent||e.win);let m=(this.printing?Hp:Fp)(t,this.paddingTop),g=m.top-this.pixelViewport.top,b=m.bottom-this.pixelViewport.bottom;this.pixelViewport=m;let w=this.pixelViewport.bottom>this.pixelViewport.top&&this.pixelViewport.right>this.pixelViewport.left;if(w!=this.inView&&(this.inView=w,w&&(a=!0)),!this.inView&&!this.scrollTarget&&!Wp(e.dom))return 0;let k=l.width;if((this.contentDOMWidth!=k||this.editorHeight!=e.scrollDOM.clientHeight)&&(this.contentDOMWidth=l.width,this.editorHeight=e.scrollDOM.clientHeight,h|=16),a){let v=e.docView.measureVisibleLineHeights(this.viewport);if(s.mustRefreshForHeights(v)&&(o=!0),o||s.lineWrapping&&Math.abs(k-this.contentDOMWidth)>s.charWidth){let{lineHeight:S,charWidth:C,textHeight:E}=e.docView.measureTextSize();o=S>0&&s.refresh(r,S,C,E,Math.max(5,k/C),v),o&&(e.docView.minWidth=0,h|=16)}g>0&&b>0?c=Math.max(g,b):g<0&&b<0&&(c=Math.min(g,b)),rh();for(let S of this.viewports){let C=S.from==this.viewport.from?v:e.docView.measureVisibleLineHeights(S);this.heightMap=(o?Te.empty().applyChanges(this.stateDeco,N.empty,this.heightOracle,[new $e(0,0,0,e.state.doc.length)]):this.heightMap).updateHeight(s,0,o,new mo(S.from,C))}mi&&(h|=2)}let D=!this.viewportIsAppropriate(this.viewport,c)||this.scrollTarget&&(this.scrollTarget.range.headthis.viewport.to);return D&&(h&2&&(h|=this.updateScaler()),this.viewport=this.getViewport(c,this.scrollTarget),h|=this.updateForViewport()),(h&2||D)&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(o?[]:this.lineGaps,e)),h|=this.computeVisibleRanges(),this.mustEnforceCursorAssoc&&(this.mustEnforceCursorAssoc=!1,e.docView.enforceCursorAssoc()),h}get visibleTop(){return this.scaler.fromDOM(this.pixelViewport.top)}get visibleBottom(){return this.scaler.fromDOM(this.pixelViewport.bottom)}getViewport(e,t){let i=.5-Math.max(-.5,Math.min(.5,e/1e3/2)),s=this.heightMap,r=this.heightOracle,{visibleTop:o,visibleBottom:l}=this,a=new oi(s.lineAt(o-i*1e3,_.ByHeight,r,0,0).from,s.lineAt(l+(1-i)*1e3,_.ByHeight,r,0,0).to);if(t){let{head:h}=t.range;if(ha.to){let c=Math.min(this.editorHeight,this.pixelViewport.bottom-this.pixelViewport.top),f=s.lineAt(h,_.ByPos,r,0,0),u;t.y=="center"?u=(f.top+f.bottom)/2-c/2:t.y=="start"||t.y=="nearest"&&h=l+Math.max(10,Math.min(i,250)))&&s>o-2*1e3&&r>1,o=s<<1;if(this.defaultTextDirection!=z.LTR&&!i)return[];let l=[],a=(c,f,u,d)=>{if(f-cc&&bb.from>=u.from&&b.to<=u.to&&Math.abs(b.from-c)b.fromw));if(!g){if(fk.from<=f&&k.to>=f)){let k=t.moveToLineBoundary(x.cursor(f),!1,!0).head;k>c&&(f=k)}let b=this.gapSize(u,c,f,d),w=i||b<2e6?b:2e6;g=new qi(c,f,b,w)}l.push(g)},h=c=>{if(c.length2e6)for(let S of e)S.from>=c.from&&S.fromc.from&&a(c.from,d,c,f),pt.draw(this,this.heightOracle.lineWrapping))))}computeVisibleRanges(e){let t=this.stateDeco;this.lineGaps.length&&(t=t.concat(this.lineGapDeco));let i=[];F.spans(t,this.viewport.from,this.viewport.to,{span(r,o){i.push({from:r,to:o})},point(){}},20);let s=0;if(i.length!=this.visibleRanges.length)s=12;else for(let r=0;r=this.viewport.from&&e<=this.viewport.to&&this.viewportLines.find(t=>t.from<=e&&t.to>=e)||Ei(this.heightMap.lineAt(e,_.ByPos,this.heightOracle,0,0),this.scaler)}lineBlockAtHeight(e){return e>=this.viewportLines[0].top&&e<=this.viewportLines[this.viewportLines.length-1].bottom&&this.viewportLines.find(t=>t.top<=e&&t.bottom>=e)||Ei(this.heightMap.lineAt(this.scaler.fromDOM(e),_.ByHeight,this.heightOracle,0,0),this.scaler)}getScrollOffset(){return(this.scrollParent==this.view.scrollDOM?this.scrollParent.scrollTop:(this.scrollParent?this.scrollParent.getBoundingClientRect().top:0)-this.view.contentDOM.getBoundingClientRect().top)*this.scaleY}scrollAnchorAt(e){let t=this.lineBlockAtHeight(e+8);return t.from>=this.viewport.from||this.viewportLines[0].top-e>200?t:this.viewportLines[0]}elementAtHeight(e){return Ei(this.heightMap.blockAt(this.scaler.fromDOM(e),this.heightOracle,0,0),this.scaler)}get docHeight(){return this.scaler.toDOM(this.heightMap.height)}get contentHeight(){return this.docHeight+this.paddingTop+this.paddingBottom}},oi=class{constructor(e,t){this.from=e,this.to=t}};function Vp(n,e,t){let i=[],s=n,r=0;return F.spans(t,n,e,{span(){},point(o,l){o>s&&(i.push({from:s,to:o}),r+=o-s),s=l}},20),s=1)return e[e.length-1].to;let i=Math.floor(n*t);for(let s=0;;s++){let{from:r,to:o}=e[s],l=o-r;if(i<=l)return r+i;i-=l}}function Wn(n,e){let t=0;for(let{from:i,to:s}of n.ranges){if(e<=s){t+=e-i;break}t+=s-i}return t/n.total}function zp(n,e){for(let t of n)if(e(t))return t}var lh={toDOM(n){return n},fromDOM(n){return n},scale:1,eq(n){return n==this}};function ah(n){let e=n.facet(ds).filter(i=>typeof i!="function"),t=n.facet($o).filter(i=>typeof i!="function");return t.length&&e.push(F.join(t)),e}var wo=class n{constructor(e,t,i){let s=0,r=0,o=0;this.viewports=i.map(({from:l,to:a})=>{let h=t.lineAt(l,_.ByPos,e,0,0).top,c=t.lineAt(a,_.ByPos,e,0,0).bottom;return s+=c-h,{from:l,to:a,top:h,bottom:c,domTop:0,domBottom:0}}),this.scale=(7e6-s)/(t.height-s);for(let l of this.viewports)l.domTop=o+(l.top-r)*this.scale,o=l.domBottom=l.domTop+(l.bottom-l.top),r=l.bottom}toDOM(e){for(let t=0,i=0,s=0;;t++){let r=tt.from==e.viewports[i].from&&t.to==e.viewports[i].to):!1}};function Ei(n,e){if(e.scale==1)return n;let t=e.toDOM(n.top),i=e.toDOM(n.bottom);return new qe(n.from,n.length,t,i-t,Array.isArray(n._content)?n._content.map(s=>Ei(s,e)):n._content)}var Hn=A.define({combine:n=>n.join(" ")}),ko=A.define({combine:n=>n.indexOf(!0)>-1}),vo=Ie.newName(),uc=Ie.newName(),dc=Ie.newName(),pc={"&light":"."+uc,"&dark":"."+dc};function So(n,e,t){return new Ie(e,{finish(i){return/&/.test(i)?i.replace(/&\w*/,s=>{if(s=="&")return n;if(!t||!t[s])throw new RangeError(`Unsupported selector: ${s}`);return t[s]}):n+" "+i}})}var qp=So("."+vo,{"&":{position:"relative !important",boxSizing:"border-box","&.cm-focused":{outline:"1px dotted #212121"},display:"flex !important",flexDirection:"column"},".cm-scroller":{display:"flex !important",alignItems:"flex-start !important",fontFamily:"monospace",lineHeight:1.4,height:"100%",overflowX:"auto",position:"relative",zIndex:0,overflowAnchor:"none"},".cm-content":{margin:0,flexGrow:2,flexShrink:0,display:"block",whiteSpace:"pre",wordWrap:"normal",boxSizing:"border-box",minHeight:"100%",padding:"4px 0",outline:"none","&[contenteditable=true]":{WebkitUserModify:"read-write-plaintext-only"}},".cm-lineWrapping":{whiteSpace_fallback:"pre-wrap",whiteSpace:"break-spaces",wordBreak:"break-word",overflowWrap:"anywhere",flexShrink:1},"&light .cm-content":{caretColor:"black"},"&dark .cm-content":{caretColor:"white"},".cm-line":{display:"block",padding:"0 2px 0 6px"},".cm-layer":{position:"absolute",left:0,top:0,contain:"size style","& > *":{position:"absolute"}},"&light .cm-selectionBackground":{background:"#d9d9d9"},"&dark .cm-selectionBackground":{background:"#222"},"&light.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"#d7d4f0"},"&dark.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"#233"},".cm-cursorLayer":{pointerEvents:"none"},"&.cm-focused > .cm-scroller > .cm-cursorLayer":{animation:"steps(1) cm-blink 1.2s infinite"},"@keyframes cm-blink":{"0%":{},"50%":{opacity:0},"100%":{}},"@keyframes cm-blink2":{"0%":{},"50%":{opacity:0},"100%":{}},".cm-cursor, .cm-dropCursor":{borderLeft:"1.2px solid black",marginLeft:"-0.6px",pointerEvents:"none"},".cm-cursor":{display:"none"},"&dark .cm-cursor":{borderLeftColor:"#ddd"},".cm-selectionHandle":{backgroundColor:"currentColor",width:"1.5px"},".cm-selectionHandle-start::before, .cm-selectionHandle-end::before":{content:'""',backgroundColor:"inherit",borderRadius:"50%",width:"8px",height:"8px",position:"absolute",left:"-3.25px"},".cm-selectionHandle-start::before":{top:"-8px"},".cm-selectionHandle-end::before":{bottom:"-8px"},".cm-dropCursor":{position:"absolute"},"&.cm-focused > .cm-scroller > .cm-cursorLayer .cm-cursor":{display:"block"},".cm-iso":{unicodeBidi:"isolate"},".cm-announced":{position:"fixed",top:"-10000px"},"@media print":{".cm-announced":{display:"none"}},"&light .cm-activeLine":{backgroundColor:"#cceeff44"},"&dark .cm-activeLine":{backgroundColor:"#99eeff33"},"&light .cm-specialChar":{color:"red"},"&dark .cm-specialChar":{color:"#f78"},".cm-gutters":{flexShrink:0,display:"flex",height:"100%",boxSizing:"border-box",zIndex:200},".cm-gutters-before":{insetInlineStart:0},".cm-gutters-after":{insetInlineEnd:0},"&light .cm-gutters":{backgroundColor:"#f5f5f5",color:"#6c6c6c",border:"0px solid #ddd","&.cm-gutters-before":{borderRightWidth:"1px"},"&.cm-gutters-after":{borderLeftWidth:"1px"}},"&dark .cm-gutters":{backgroundColor:"#333338",color:"#ccc"},".cm-gutter":{display:"flex !important",flexDirection:"column",flexShrink:0,boxSizing:"border-box",minHeight:"100%",overflow:"hidden"},".cm-gutterElement":{boxSizing:"border-box"},".cm-lineNumbers .cm-gutterElement":{padding:"0 3px 0 5px",minWidth:"20px",textAlign:"right",whiteSpace:"nowrap"},"&light .cm-activeLineGutter":{backgroundColor:"#e2f2ff"},"&dark .cm-activeLineGutter":{backgroundColor:"#222227"},".cm-panels":{boxSizing:"border-box",position:"sticky",left:0,right:0,zIndex:300},"&light .cm-panels":{backgroundColor:"#f5f5f5",color:"black"},"&light .cm-panels-top":{borderBottom:"1px solid #ddd"},"&light .cm-panels-bottom":{borderTop:"1px solid #ddd"},"&dark .cm-panels":{backgroundColor:"#333338",color:"white"},".cm-dialog":{padding:"2px 19px 4px 6px",position:"relative","& label":{fontSize:"80%"}},".cm-dialog-close":{position:"absolute",top:"3px",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",fontSize:"14px",padding:"0"},".cm-tab":{display:"inline-block",overflow:"hidden",verticalAlign:"bottom"},".cm-widgetBuffer":{verticalAlign:"text-top",height:"1em",width:0,display:"inline"},".cm-placeholder":{color:"#888",display:"inline-block",verticalAlign:"top",userSelect:"none"},".cm-highlightSpace":{backgroundImage:"radial-gradient(circle at 50% 55%, #aaa 20%, transparent 5%)",backgroundPosition:"center"},".cm-highlightTab":{backgroundImage:`url('data:image/svg+xml,')`,backgroundSize:"auto 100%",backgroundPosition:"right 90%",backgroundRepeat:"no-repeat"},".cm-trailingSpace":{backgroundColor:"#ff332255"},".cm-button":{verticalAlign:"middle",color:"inherit",fontSize:"70%",padding:".2em 1em",borderRadius:"1px"},"&light .cm-button":{backgroundImage:"linear-gradient(#eff1f5, #d9d9df)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#b4b4b4, #d0d3d6)"}},"&dark .cm-button":{backgroundImage:"linear-gradient(#393939, #111)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#111, #333)"}},".cm-textfield":{verticalAlign:"middle",color:"inherit",fontSize:"70%",border:"1px solid silver",padding:".2em .5em"},"&light .cm-textfield":{backgroundColor:"white"},"&dark .cm-textfield":{border:"1px solid #555",backgroundColor:"inherit"}},pc),$p={childList:!0,characterData:!0,subtree:!0,attributes:!0,characterDataOldValue:!0},Nr=O.ie&&O.ie_version<=11,Co=class{constructor(e){this.view=e,this.active=!1,this.editContext=null,this.selectionRange=new Ur,this.selectionChanged=!1,this.delayedFlush=-1,this.resizeTimeout=-1,this.queue=[],this.delayedAndroidKey=null,this.flushingAndroidKey=-1,this.lastChange=0,this.scrollTargets=[],this.intersection=null,this.resizeScroll=null,this.intersecting=!1,this.gapIntersection=null,this.gaps=[],this.printQuery=null,this.parentCheck=-1,this.dom=e.contentDOM,this.observer=new MutationObserver(t=>{for(let i of t)this.queue.push(i);(O.ie&&O.ie_version<=11||O.ios&&e.composing)&&t.some(i=>i.type=="childList"&&i.removedNodes.length||i.type=="characterData"&&i.oldValue.length>i.target.nodeValue.length)?this.flushSoon():this.flush()}),window.EditContext&&O.android&&e.constructor.EDIT_CONTEXT!==!1&&!(O.chrome&&O.chrome_version<126)&&(this.editContext=new Ao(e),e.state.facet(ht)&&(e.contentDOM.editContext=this.editContext.editContext)),Nr&&(this.onCharData=t=>{this.queue.push({target:t.target,type:"characterData",oldValue:t.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this),this.onResize=this.onResize.bind(this),this.onPrint=this.onPrint.bind(this),this.onScroll=this.onScroll.bind(this),window.matchMedia&&(this.printQuery=window.matchMedia("print")),typeof ResizeObserver=="function"&&(this.resizeScroll=new ResizeObserver(()=>{var t;((t=this.view.docView)===null||t===void 0?void 0:t.lastUpdate){this.parentCheck<0&&(this.parentCheck=setTimeout(this.listenForScroll.bind(this),1e3)),t.length>0&&t[t.length-1].intersectionRatio>0!=this.intersecting&&(this.intersecting=!this.intersecting,this.intersecting!=this.view.inView&&this.onScrollChanged(document.createEvent("Event")))},{threshold:[0,.001]}),this.intersection.observe(this.dom),this.gapIntersection=new IntersectionObserver(t=>{t.length>0&&t[t.length-1].intersectionRatio>0&&this.onScrollChanged(document.createEvent("Event"))},{})),this.listenForScroll(),this.readSelectionRange()}onScrollChanged(e){this.view.inputState.runHandlers("scroll",e),this.intersecting&&this.view.measure()}onScroll(e){this.intersecting&&this.flush(!1),this.editContext&&this.view.requestMeasure(this.editContext.measureReq),this.onScrollChanged(e)}onResize(){this.resizeTimeout<0&&(this.resizeTimeout=setTimeout(()=>{this.resizeTimeout=-1,this.view.requestMeasure()},50))}onPrint(e){(e.type=="change"||!e.type)&&!e.matches||(this.view.viewState.printing=!0,this.view.measure(),setTimeout(()=>{this.view.viewState.printing=!1,this.view.requestMeasure()},500))}updateGaps(e){if(this.gapIntersection&&(e.length!=this.gaps.length||this.gaps.some((t,i)=>t!=e[i]))){this.gapIntersection.disconnect();for(let t of e)this.gapIntersection.observe(t);this.gaps=e}}onSelectionChange(e){let t=this.selectionChanged;if(!this.readSelectionRange()||this.delayedAndroidKey)return;let{view:i}=this,s=this.selectionRange;if(i.state.facet(ht)?i.root.activeElement!=this.dom:!Ni(this.dom,s))return;let r=s.anchorNode&&i.docView.tile.nearest(s.anchorNode);if(r&&r.isWidget()&&r.widget.ignoreEvent(e)){t||(this.selectionChanged=!1);return}(O.ie&&O.ie_version<=11||O.android&&O.chrome)&&!i.state.selection.main.empty&&s.focusNode&&Fi(s.focusNode,s.focusOffset,s.anchorNode,s.anchorOffset)?this.flushSoon():this.flush(!1)}readSelectionRange(){let{view:e}=this,t=Gi(e.root);if(!t)return!1;let i=O.safari&&e.root.nodeType==11&&e.root.activeElement==this.dom&&Kp(this.view,t)||t;if(!i||this.selectionRange.eq(i))return!1;let s=Ni(this.dom,i);return s&&!this.selectionChanged&&e.inputState.lastFocusTime>Date.now()-200&&e.inputState.lastTouchTime{let r=this.delayedAndroidKey;r&&(this.clearDelayedAndroidKey(),this.view.inputState.lastKeyCode=r.keyCode,this.view.inputState.lastKeyTime=Date.now(),!this.flush()&&r.force&&ci(this.dom,r.key,r.keyCode))};this.flushingAndroidKey=this.view.win.requestAnimationFrame(s)}(!this.delayedAndroidKey||e=="Enter")&&(this.delayedAndroidKey={key:e,keyCode:t,force:this.lastChange{this.delayedFlush=-1,this.flush()}))}forceFlush(){this.delayedFlush>=0&&(this.view.win.cancelAnimationFrame(this.delayedFlush),this.delayedFlush=-1),this.flush()}pendingRecords(){for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}processRecords(){let e=this.pendingRecords();e.length&&(this.queue=[]);let t=-1,i=-1,s=!1;for(let r of e){let o=this.readMutation(r);o&&(o.typeOver&&(s=!0),t==-1?{from:t,to:i}=o:(t=Math.min(o.from,t),i=Math.max(o.to,i)))}return{from:t,to:i,typeOver:s}}readChange(){let{from:e,to:t,typeOver:i}=this.processRecords(),s=this.selectionChanged&&Ni(this.dom,this.selectionRange);if(e<0&&!s)return null;e>-1&&(this.lastChange=Date.now()),this.view.inputState.lastFocusTime=0,this.selectionChanged=!1;let r=new ho(this.view,e,t,i);return this.view.docView.domChanged={newSel:r.newSel?r.newSel.main:null},r}flush(e=!0){if(this.delayedFlush>=0||this.delayedAndroidKey)return!1;e&&this.readSelectionRange();let t=this.readChange();if(!t)return this.view.requestMeasure(),!1;let i=this.view.state,s=ic(this.view,t);return this.view.state==i&&(t.domChanged||t.newSel&&!is(this.view.state.selection,t.newSel.main))&&this.view.update([]),s}readMutation(e){let t=this.view.docView.tile.nearest(e.target);if(!t||t.isWidget())return null;if(t.markDirty(e.type=="attributes"),e.type=="childList"){let i=hh(t,e.previousSibling||e.target.previousSibling,-1),s=hh(t,e.nextSibling||e.target.nextSibling,1);return{from:i?t.posAfter(i):t.posAtStart,to:s?t.posBefore(s):t.posAtEnd,typeOver:!1}}else return e.type=="characterData"?{from:t.posAtStart,to:t.posAtEnd,typeOver:e.target.nodeValue==e.oldValue}:null}setWindow(e){e!=this.win&&(this.removeWindowListeners(this.win),this.win=e,this.addWindowListeners(this.win))}addWindowListeners(e){e.addEventListener("resize",this.onResize),this.printQuery?this.printQuery.addEventListener?this.printQuery.addEventListener("change",this.onPrint):this.printQuery.addListener(this.onPrint):e.addEventListener("beforeprint",this.onPrint),e.addEventListener("scroll",this.onScroll),e.document.addEventListener("selectionchange",this.onSelectionChange)}removeWindowListeners(e){e.removeEventListener("scroll",this.onScroll),e.removeEventListener("resize",this.onResize),this.printQuery?this.printQuery.removeEventListener?this.printQuery.removeEventListener("change",this.onPrint):this.printQuery.removeListener(this.onPrint):e.removeEventListener("beforeprint",this.onPrint),e.document.removeEventListener("selectionchange",this.onSelectionChange)}update(e){this.editContext&&(this.editContext.update(e),e.startState.facet(ht)!=e.state.facet(ht)&&(e.view.contentDOM.editContext=e.state.facet(ht)?this.editContext.editContext:null))}destroy(){var e,t,i;this.stop(),(e=this.intersection)===null||e===void 0||e.disconnect(),(t=this.gapIntersection)===null||t===void 0||t.disconnect(),(i=this.resizeScroll)===null||i===void 0||i.disconnect();for(let s of this.scrollTargets)s.removeEventListener("scroll",this.onScroll);this.removeWindowListeners(this.win),clearTimeout(this.parentCheck),clearTimeout(this.resizeTimeout),this.win.cancelAnimationFrame(this.delayedFlush),this.win.cancelAnimationFrame(this.flushingAndroidKey),this.editContext&&(this.view.contentDOM.editContext=null,this.editContext.destroy())}};function hh(n,e,t){for(;e;){let i=Q.get(e);if(i&&i.parent==n)return i;let s=e.parentNode;e=s!=n.dom?s:t>0?e.nextSibling:e.previousSibling}return null}function ch(n,e){let t=e.startContainer,i=e.startOffset,s=e.endContainer,r=e.endOffset,o=n.docView.domAtPos(n.state.selection.main.anchor,1);return Fi(o.node,o.offset,s,r)&&([t,i,s,r]=[s,r,t,i]),{anchorNode:t,anchorOffset:i,focusNode:s,focusOffset:r}}function Kp(n,e){if(e.getComposedRanges){let s=e.getComposedRanges(n.root)[0];if(s)return ch(n,s)}let t=null;function i(s){s.preventDefault(),s.stopImmediatePropagation(),t=s.getTargetRanges()[0]}return n.contentDOM.addEventListener("beforeinput",i,!0),n.dom.ownerDocument.execCommand("indent"),n.contentDOM.removeEventListener("beforeinput",i,!0),t?ch(n,t):null}var Ao=class{constructor(e){this.from=0,this.to=0,this.pendingContextChange=null,this.handlers=Object.create(null),this.composing=null,this.resetRange(e.state);let t=this.editContext=new window.EditContext({text:e.state.doc.sliceString(this.from,this.to),selectionStart:this.toContextPos(Math.max(this.from,Math.min(this.to,e.state.selection.main.anchor))),selectionEnd:this.toContextPos(e.state.selection.main.head)});this.handlers.textupdate=i=>{let s=e.state.selection.main,{anchor:r,head:o}=s,l=this.toEditorPos(i.updateRangeStart),a=this.toEditorPos(i.updateRangeEnd);e.inputState.composing>=0&&!this.composing&&(this.composing={contextBase:i.updateRangeStart,editorBase:l,drifted:!1});let h=a-l>i.text.length;l==this.from&&rthis.to&&(a=r);let c=nc(e.state.sliceDoc(l,a),i.text,(h?s.from:s.to)-l,h?"end":null);if(!c){let u=x.single(this.toEditorPos(i.selectionStart),this.toEditorPos(i.selectionEnd));is(u,s)||e.dispatch({selection:u,userEvent:"select"});return}let f={from:c.from+l,to:c.toA+l,insert:N.of(i.text.slice(c.from,c.toB).split(` +`))};if((O.mac||O.android)&&f.from==o-1&&/^\. ?$/.test(i.text)&&e.contentDOM.getAttribute("autocorrect")=="off"&&(f={from:l,to:a,insert:N.of([i.text.replace("."," ")])}),this.pendingContextChange=f,!e.state.readOnly){let u=this.to-this.from+(f.to-f.from+f.insert.length);jo(e,f,x.single(this.toEditorPos(i.selectionStart,u),this.toEditorPos(i.selectionEnd,u)))}this.pendingContextChange&&(this.revertPending(e.state),this.setSelection(e.state)),f.from=0&&!/[\\p{Alphabetic}\\p{Number}_]/.test(t.text.slice(Math.max(0,i.updateRangeStart-1),Math.min(t.text.length,i.updateRangeStart+1)))&&this.handlers.compositionend(i)},this.handlers.characterboundsupdate=i=>{let s=[],r=null;for(let o=this.toEditorPos(i.rangeStart),l=this.toEditorPos(i.rangeEnd);o{let s=[];for(let r of i.getTextFormats()){let o=r.underlineStyle,l=r.underlineThickness;if(!/none/i.test(o)&&!/none/i.test(l)){let a=this.toEditorPos(r.rangeStart),h=this.toEditorPos(r.rangeEnd);if(a{e.inputState.composing<0&&(e.inputState.composing=0,e.inputState.compositionFirstChange=!0)},this.handlers.compositionend=()=>{if(e.inputState.composing=-1,e.inputState.compositionFirstChange=null,this.composing){let{drifted:i}=this.composing;this.composing=null,i&&this.reset(e.state)}};for(let i in this.handlers)t.addEventListener(i,this.handlers[i]);this.measureReq={read:i=>{this.editContext.updateControlBounds(i.contentDOM.getBoundingClientRect());let s=Gi(i.root);s&&s.rangeCount&&this.editContext.updateSelectionBounds(s.getRangeAt(0).getBoundingClientRect())}}}applyEdits(e){let t=0,i=!1,s=this.pendingContextChange;return e.changes.iterChanges((r,o,l,a,h)=>{if(i)return;let c=h.length-(o-r);if(s&&o>=s.to)if(s.from==r&&s.to==o&&s.insert.eq(h)){s=this.pendingContextChange=null,t+=c,this.to+=c;return}else s=null,this.revertPending(e.state);if(r+=t,o+=t,o<=this.from)this.from+=c,this.to+=c;else if(rthis.to||this.to-this.from+h.length>3e4){i=!0;return}this.editContext.updateText(this.toContextPos(r),this.toContextPos(o),h.toString()),this.to+=c}t+=c}),s&&!i&&this.revertPending(e.state),!i}update(e){let t=this.pendingContextChange,i=e.startState.selection.main;this.composing&&(this.composing.drifted||!e.changes.touchesRange(i.from,i.to)&&e.transactions.some(s=>!s.isUserEvent("input.type")&&s.changes.touchesRange(this.from,this.to)))?(this.composing.drifted=!0,this.composing.editorBase=e.changes.mapPos(this.composing.editorBase)):!this.applyEdits(e)||!this.rangeIsValid(e.state)?(this.pendingContextChange=null,this.reset(e.state)):(e.docChanged||e.selectionSet||t)&&this.setSelection(e.state),(e.geometryChanged||e.docChanged||e.selectionSet)&&e.view.requestMeasure(this.measureReq)}resetRange(e){let{head:t}=e.selection.main;this.from=Math.max(0,t-1e4),this.to=Math.min(e.doc.length,t+1e4)}reset(e){this.resetRange(e),this.editContext.updateText(0,this.editContext.text.length,e.doc.sliceString(this.from,this.to)),this.setSelection(e)}revertPending(e){let t=this.pendingContextChange;this.pendingContextChange=null,this.editContext.updateText(this.toContextPos(t.from),this.toContextPos(t.from+t.insert.length),e.doc.sliceString(t.from,t.to))}setSelection(e){let{main:t}=e.selection,i=this.toContextPos(Math.max(this.from,Math.min(this.to,t.anchor))),s=this.toContextPos(t.head);(this.editContext.selectionStart!=i||this.editContext.selectionEnd!=s)&&this.editContext.updateSelection(i,s)}rangeIsValid(e){let{head:t}=e.selection.main;return!(this.from>0&&t-this.from<500||this.to1e4*3)}toEditorPos(e,t=this.to-this.from){e=Math.min(e,t);let i=this.composing;return i&&i.drifted?i.editorBase+(e-i.contextBase):e+this.from}toContextPos(e){let t=this.composing;return t&&t.drifted?t.contextBase+(e-t.editorBase):e-this.from}destroy(){for(let e in this.handlers)this.editContext.removeEventListener(e,this.handlers[e])}},T=class n{get state(){return this.viewState.state}get viewport(){return this.viewState.viewport}get visibleRanges(){return this.viewState.visibleRanges}get inView(){return this.viewState.inView}get composing(){return!!this.inputState&&this.inputState.composing>0}get compositionStarted(){return!!this.inputState&&this.inputState.composing>=0}get root(){return this._root}get win(){return this.dom.ownerDocument.defaultView||window}constructor(e={}){var t;this.plugins=[],this.pluginMap=new Map,this.editorAttrs={},this.contentAttrs={},this.bidiCache=[],this.destroyed=!1,this.updateState=2,this.measureScheduled=-1,this.measureRequests=[],this.contentDOM=document.createElement("div"),this.scrollDOM=document.createElement("div"),this.scrollDOM.tabIndex=-1,this.scrollDOM.className="cm-scroller",this.scrollDOM.appendChild(this.contentDOM),this.announceDOM=document.createElement("div"),this.announceDOM.className="cm-announced",this.announceDOM.setAttribute("aria-live","polite"),this.dom=document.createElement("div"),this.dom.appendChild(this.announceDOM),this.dom.appendChild(this.scrollDOM),e.parent&&e.parent.appendChild(this.dom);let{dispatch:i}=e;this.dispatchTransactions=e.dispatchTransactions||i&&(s=>s.forEach(r=>i(r,this)))||(s=>this.update(s)),this.dispatch=this.dispatch.bind(this),this._root=e.root||Wd(e.parent)||document,this.viewState=new rs(this,e.state||$.create(e)),e.scrollTo&&e.scrollTo.is(En)&&(this.viewState.scrollTarget=e.scrollTo.value.clip(this.viewState.state)),this.plugins=this.state.facet(ri).map(s=>new Hi(s));for(let s of this.plugins)s.update(this);this.observer=new Co(this),this.inputState=new co(this),this.inputState.ensureHandlers(this.plugins),this.docView=new es(this),this.mountStyles(),this.updateAttrs(),this.updateState=0,this.requestMeasure(),!((t=document.fonts)===null||t===void 0)&&t.ready&&document.fonts.ready.then(()=>{this.viewState.mustMeasureContent="refresh",this.requestMeasure()})}dispatch(...e){let t=e.length==1&&e[0]instanceof ie?e:e.length==1&&Array.isArray(e[0])?e[0]:[this.state.update(...e)];this.dispatchTransactions(t,this)}update(e){if(this.updateState!=0)throw new Error("Calls to EditorView.update are not allowed while an update is in progress");let t=!1,i=!1,s,r=this.state;for(let u of e){if(u.startState!=r)throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state.");r=u.state}if(this.destroyed){this.viewState.state=r;return}let o=this.hasFocus,l=0,a=null;e.some(u=>u.annotation(hc))?(this.inputState.notifiedFocused=o,l=1):o!=this.inputState.notifiedFocused&&(this.inputState.notifiedFocused=o,a=cc(r,o),a||(l=1));let h=this.observer.delayedAndroidKey,c=null;if(h?(this.observer.clearDelayedAndroidKey(),c=this.observer.readChange(),(c&&!this.state.doc.eq(r.doc)||!this.state.selection.eq(r.selection))&&(c=null)):this.observer.clear(),r.facet($.phrases)!=this.state.facet($.phrases))return this.setState(r);s=Jn.create(this,r,e),s.flags|=l;let f=this.viewState.scrollTarget;try{this.updateState=2;for(let u of e){if(f&&(f=f.map(u.changes)),u.scrollIntoView){let{main:d}=u.state.selection,{x:p,y:m}=this.state.facet(n.cursorScrollMargin);f=new Wi(d.empty?d:x.cursor(d.head,d.head>d.anchor?-1:1),"nearest","nearest",m,p)}for(let d of u.effects)d.is(En)&&(f=d.value.clip(this.state))}this.viewState.update(s,f),this.bidiCache=os.update(this.bidiCache,s.changes),s.empty||(this.updatePlugins(s),this.inputState.update(s)),t=this.docView.update(s),this.state.facet(Li)!=this.styleModules&&this.mountStyles(),i=this.updateAttrs(),this.showAnnouncements(e),this.docView.updateSelection(t,e.some(u=>u.isUserEvent("select.pointer")))}finally{this.updateState=0}if(s.startState.facet(Hn)!=s.state.facet(Hn)&&(this.viewState.mustMeasureContent=!0),(t||i||f||this.viewState.mustEnforceCursorAssoc||this.viewState.mustMeasureContent)&&this.requestMeasure(),t&&this.docViewUpdate(),!s.empty)for(let u of this.state.facet(Xr))try{u(s)}catch(d){ne(this.state,d,"update listener")}(a||c)&&Promise.resolve().then(()=>{a&&this.state==a.startState&&this.dispatch(a),c&&!ic(this,c)&&h.force&&ci(this.contentDOM,h.key,h.keyCode)})}setState(e){if(this.updateState!=0)throw new Error("Calls to EditorView.setState are not allowed while an update is in progress");if(this.destroyed){this.viewState.state=e;return}this.updateState=2;let t=this.hasFocus;try{for(let i of this.plugins)i.destroy(this);this.viewState=new rs(this,e),this.plugins=e.facet(ri).map(i=>new Hi(i)),this.pluginMap.clear();for(let i of this.plugins)i.update(this);this.docView.destroy(),this.docView=new es(this),this.inputState.ensureHandlers(this.plugins),this.mountStyles(),this.updateAttrs(),this.bidiCache=[]}finally{this.updateState=0}t&&this.focus(),this.requestMeasure()}updatePlugins(e){let t=e.startState.facet(ri),i=e.state.facet(ri);if(t!=i){let s=[];for(let r of i){let o=t.indexOf(r);if(o<0)s.push(new Hi(r));else{let l=this.plugins[o];l.mustUpdate=e,s.push(l)}}for(let r of this.plugins)r.mustUpdate!=e&&r.destroy(this);this.plugins=s,this.pluginMap.clear()}else for(let s of this.plugins)s.mustUpdate=e;for(let s=0;s-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.observer.delayedAndroidKey){this.measureScheduled=-1,this.requestMeasure();return}this.measureScheduled=0,e&&this.observer.forceFlush();let t=null,i=this.viewState.scrollParent,s=this.viewState.getScrollOffset(),{scrollAnchorPos:r,scrollAnchorHeight:o}=this.viewState;Math.abs(s-this.viewState.scrollOffset)>1&&(o=-1),this.viewState.scrollAnchorHeight=-1;try{for(let l=0;;l++){if(o<0)if(Ph(i||this.win))r=-1,o=this.viewState.heightMap.height;else{let d=this.viewState.scrollAnchorAt(s);r=d.from,o=d.top}this.updateState=1;let a=this.viewState.measure();if(!a&&!this.measureRequests.length&&this.viewState.scrollTarget==null)break;if(l>5){console.warn(this.measureRequests.length?"Measure loop restarted more than 5 times":"Viewport failed to stabilize");break}let h=[];a&4||([this.measureRequests,h]=[h,this.measureRequests]);let c=h.map(d=>{try{return d.read(this)}catch(p){return ne(this.state,p),fh}}),f=Jn.create(this,this.state,[]),u=!1;f.flags|=a,t?t.flags|=a:t=f,this.updateState=2,f.empty||(this.updatePlugins(f),this.inputState.update(f),this.updateAttrs(),u=this.docView.update(f),u&&this.docViewUpdate());for(let d=0;d1||p<-1)&&(i==this.scrollDOM||this.hasFocus||Math.max(this.inputState.lastWheelEvent,this.inputState.lastTouchTime)>Date.now()-100)){s=s+p,i?i.scrollTop+=p:this.win.scrollBy(0,p),o=-1;continue}}break}}}finally{this.updateState=0,this.measureScheduled=-1}if(t&&!t.empty)for(let l of this.state.facet(Xr))l(t)}get themeClasses(){return vo+" "+(this.state.facet(ko)?dc:uc)+" "+this.state.facet(Hn)}updateAttrs(){let e=uh(this,_h,{class:"cm-editor"+(this.hasFocus?" cm-focused ":" ")+this.themeClasses}),t={spellcheck:"false",autocorrect:"off",autocapitalize:"off",writingsuggestions:"false",translate:"no",contenteditable:this.state.facet(ht)?"true":"false",class:"cm-content",style:`${O.tabSize}: ${this.state.tabSize}`,role:"textbox","aria-multiline":"true"};this.state.readOnly&&(t["aria-readonly"]="true"),uh(this,qo,t);let i=this.observer.ignore(()=>{let s=Ka(this.contentDOM,this.contentAttrs,t),r=Ka(this.dom,this.editorAttrs,e);return s||r});return this.editorAttrs=e,this.contentAttrs=t,i}showAnnouncements(e){let t=!0;for(let i of e)for(let s of i.effects)if(s.is(n.announce)){t&&(this.announceDOM.textContent=""),t=!1;let r=this.announceDOM.appendChild(document.createElement("div"));r.textContent=s.value}}mountStyles(){this.styleModules=this.state.facet(Li);let e=this.state.facet(n.cspNonce);Ie.mount(this.root,this.styleModules.concat(qp).reverse(),e?{nonce:e}:void 0)}readMeasured(){if(this.updateState==2)throw new Error("Reading the editor layout isn't allowed during an update");this.updateState==0&&this.measureScheduled>-1&&this.measure(!1)}requestMeasure(e){if(this.measureScheduled<0&&(this.measureScheduled=this.win.requestAnimationFrame(()=>this.measure())),e){if(this.measureRequests.indexOf(e)>-1)return;if(e.key!=null){for(let t=0;ti.plugin==e)||null),t&&t.update(this).value}get documentTop(){return this.contentDOM.getBoundingClientRect().top+this.viewState.paddingTop}get documentPadding(){return{top:this.viewState.paddingTop,bottom:this.viewState.paddingBottom}}get scaleX(){return this.viewState.scaleX}get scaleY(){return this.viewState.scaleY}elementAtHeight(e){return this.readMeasured(),this.viewState.elementAtHeight(e)}lineBlockAtHeight(e){return this.readMeasured(),this.viewState.lineBlockAtHeight(e)}get viewportLineBlocks(){return this.viewState.viewportLines}lineBlockAt(e){return this.viewState.lineBlockAt(e)}get contentHeight(){return this.viewState.contentHeight}moveByChar(e,t,i){return Ir(this,e,Xa(this,e,t,i))}moveByGroup(e,t){return Ir(this,e,Xa(this,e,t,i=>dp(this,e.head,i)))}visualLineSide(e,t){let i=this.bidiSpans(e),s=this.textDirectionAt(e.from),r=i[t?i.length-1:0];return x.cursor(r.side(t,s)+e.from,r.forward(!t,s)?1:-1)}moveToLineBoundary(e,t,i=!0){return up(this,e,t,i)}moveVertically(e,t,i){return Ir(this,e,pp(this,e,t,i))}domAtPos(e,t=1){return this.docView.domAtPos(e,t)}posAtDOM(e,t=0){return this.docView.posFromDOM(e,t)}posAtCoords(e,t=!0){this.readMeasured();let i=oo(this,e,t);return i&&i.pos}posAndSideAtCoords(e,t=!0){return this.readMeasured(),oo(this,e,t)}coordsAtPos(e,t=1){this.readMeasured();let i=this.docView.coordsAt(e,t);if(!i||i.left==i.right)return i;let s=this.state.doc.lineAt(e),r=this.bidiSpans(s),o=r[We.find(r,e-s.from,-1,t)];return Qn(i,o.dir==z.LTR==t>0)}coordsForChar(e){return this.readMeasured(),this.docView.coordsForChar(e)}get defaultCharacterWidth(){return this.viewState.heightOracle.charWidth}get defaultLineHeight(){return this.viewState.heightOracle.lineHeight}get textDirection(){return this.viewState.defaultTextDirection}textDirectionAt(e){return!this.state.facet(Kh)||ethis.viewport.to?this.textDirection:(this.readMeasured(),this.docView.textDirectionAt(e))}get lineWrapping(){return this.viewState.heightOracle.lineWrapping}bidiSpans(e){if(e.length>jp)return Nh(e.length);let t=this.textDirectionAt(e.from),i;for(let r of this.bidiCache)if(r.from==e.from&&r.dir==t&&(r.fresh||Ih(r.isolates,i=Ga(this,e))))return r.order;i||(i=Ga(this,e));let s=Ud(e.text,t,i);return this.bidiCache.push(new os(e.from,e.to,t,i,!0,s)),s}get hasFocus(){var e;return(this.dom.ownerDocument.hasFocus()||O.safari&&((e=this.inputState)===null||e===void 0?void 0:e.lastContextMenu)>Date.now()-3e4)&&this.root.activeElement==this.contentDOM}focus(){this.observer.ignore(()=>{Dh(this.contentDOM),this.docView.updateSelection()})}setRoot(e){this._root!=e&&(this._root=e,this.observer.setWindow((e.nodeType==9?e:e.ownerDocument).defaultView||window),this.mountStyles())}destroy(){this.root.activeElement==this.contentDOM&&this.contentDOM.blur();for(let e of this.plugins)e.destroy(this);this.plugins=[],this.inputState.destroy(),this.docView.destroy(),this.dom.remove(),this.observer.destroy(),this.measureScheduled>-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.destroyed=!0}static scrollIntoView(e,t={}){var i,s,r,o;return En.of(new Wi(typeof e=="number"?x.cursor(e):e,(i=t.y)!==null&&i!==void 0?i:"nearest",(s=t.x)!==null&&s!==void 0?s:"nearest",(r=t.yMargin)!==null&&r!==void 0?r:5,(o=t.xMargin)!==null&&o!==void 0?o:5))}scrollSnapshot(){let{scrollTop:e,scrollLeft:t}=this.scrollDOM,i=this.viewState.scrollAnchorAt(e);return En.of(new Wi(x.cursor(i.from),"start","start",i.top-e,t,!0))}setTabFocusMode(e){e==null?this.inputState.tabFocusMode=this.inputState.tabFocusMode<0?0:-1:typeof e=="boolean"?this.inputState.tabFocusMode=e?0:-1:this.inputState.tabFocusMode!=0&&(this.inputState.tabFocusMode=Date.now()+e)}static domEventHandlers(e){return Y.define(()=>({}),{eventHandlers:e})}static domEventObservers(e){return Y.define(()=>({}),{eventObservers:e})}static theme(e,t){let i=Ie.newName(),s=[Hn.of(i),Li.of(So(`.${i}`,e))];return t&&t.dark&&s.push(ko.of(!0)),s}static baseTheme(e){return ze.lowest(Li.of(So("."+vo,e,pc)))}static findFromDOM(e){var t;let i=e.querySelector(".cm-content"),s=i&&Q.get(i)||Q.get(e);return((t=s?.root)===null||t===void 0?void 0:t.view)||null}};T.styleModule=Li;T.inputHandler=qh;T.clipboardInputFilter=Vo;T.clipboardOutputFilter=zo;T.scrollHandler=Uh;T.focusChangeEffect=$h;T.perLineTextDirection=Kh;T.exceptionSink=zh;T.updateListener=Xr;T.editable=ht;T.mouseSelectionStyle=Vh;T.dragMovesSelection=Hh;T.clickAddsSelectionRange=Wh;T.decorations=ds;T.blockWrappers=Yh;T.outerDecorations=$o;T.atomicRanges=Yi;T.bidiIsolatedRanges=Xh;T.cursorScrollMargin=A.define({combine:n=>{let e=5,t=5;for(let i of n)typeof i=="number"?e=t=i:{x:e,y:t}=i;return{x:e,y:t}}});T.scrollMargins=Qh;T.darkTheme=ko;T.cspNonce=A.define({combine:n=>n.length?n[0]:""});T.contentAttributes=qo;T.editorAttributes=_h;T.lineWrapping=T.contentAttributes.of({class:"cm-lineWrapping"});T.announce=R.define();var jp=4096,fh={},os=class n{constructor(e,t,i,s,r,o){this.from=e,this.to=t,this.dir=i,this.isolates=s,this.fresh=r,this.order=o}static update(e,t){if(t.empty&&!e.some(r=>r.fresh))return e;let i=[],s=e.length?e[e.length-1].dir:z.LTR;for(let r=Math.max(0,e.length-10);r=0;s--){let r=i[s],o=typeof r=="function"?r(n):r;o&&Fo(o,t)}return t}var Up=O.mac?"mac":O.windows?"win":O.linux?"linux":"key";function Gp(n,e){let t=n.split(/-(?!$)/),i=t[t.length-1];i=="Space"&&(i=" ");let s,r,o,l;for(let a=0;ai.concat(s),[]))),t}function gc(n,e,t){return bc(mc(n.state),e,n,t)}var mt=null,Yp=4e3;function Xp(n,e=Up){let t=Object.create(null),i=Object.create(null),s=(o,l)=>{let a=i[o];if(a==null)i[o]=l;else if(a!=l)throw new Error("Key binding "+o+" is used both as a regular binding and as a multi-stroke prefix")},r=(o,l,a,h,c)=>{var f,u;let d=t[o]||(t[o]=Object.create(null)),p=l.split(/ (?!$)/).map(b=>Gp(b,e));for(let b=1;b{let D=mt={view:k,prefix:w,scope:o};return setTimeout(()=>{mt==D&&(mt=null)},Yp),!0}]})}let m=p.join(" ");s(m,!1);let g=d[m]||(d[m]={preventDefault:!1,stopPropagation:!1,run:((u=(f=d._any)===null||f===void 0?void 0:f.run)===null||u===void 0?void 0:u.slice())||[]});a&&g.run.push(a),h&&(g.preventDefault=!0),c&&(g.stopPropagation=!0)};for(let o of n){let l=o.scope?o.scope.split(" "):["editor"];if(o.any)for(let h of l){let c=t[h]||(t[h]=Object.create(null));c._any||(c._any={preventDefault:!1,stopPropagation:!1,run:[]});let{any:f}=o;for(let u in c)c[u].run.push(d=>f(d,Mo))}let a=o[e]||o.key;if(a)for(let h of l)r(h,a,o.run,o.preventDefault,o.stopPropagation),o.shift&&r(h,"Shift-"+a,o.shift,o.preventDefault,o.stopPropagation)}return t}var Mo=null;function bc(n,e,t,i){Mo=e;let s=Ha(e),r=ae(s,0),o=Me(r)==s.length&&s!=" ",l="",a=!1,h=!1,c=!1;mt&&mt.view==t&&mt.scope==i&&(l=mt.prefix+" ",rc.indexOf(e.keyCode)<0&&(h=!0,mt=null));let f=new Set,u=g=>{if(g){for(let b of g.run)if(!f.has(b)&&(f.add(b),b(t)))return g.stopPropagation&&(c=!0),!0;g.preventDefault&&(g.stopPropagation&&(c=!0),h=!0)}return!1},d=n[i],p,m;return d&&(u(d[l+Vn(s,e,!o)])?a=!0:o&&(e.altKey||e.metaKey||e.ctrlKey)&&!(O.windows&&e.ctrlKey&&e.altKey)&&!(O.mac&&e.altKey&&!(e.ctrlKey||e.metaKey))&&(p=at[e.keyCode])&&p!=s?(u(d[l+Vn(p,e,!0)])||e.shiftKey&&(m=ni[e.keyCode])!=s&&m!=p&&u(d[l+Vn(m,e,!1)]))&&(a=!0):o&&e.shiftKey&&u(d[l+Vn(s,e,!0)])&&(a=!0),!a&&u(d._any)&&(a=!0)),h&&(a=!0),a&&c&&e.stopPropagation(),Mo=null,a}var It=class n{constructor(e,t,i,s,r){this.className=e,this.left=t,this.top=i,this.width=s,this.height=r}draw(){let e=document.createElement("div");return e.className=this.className,this.adjust(e),e}update(e,t){return t.className!=this.className?!1:(this.adjust(e),!0)}adjust(e){e.style.left=this.left+"px",e.style.top=this.top+"px",this.width!=null&&(e.style.width=this.width+"px"),e.style.height=this.height+"px"}eq(e){return this.left==e.left&&this.top==e.top&&this.width==e.width&&this.height==e.height&&this.className==e.className}static forRange(e,t,i){if(i.empty){let s=e.coordsAtPos(i.head,i.assoc||1);if(!s)return[];let r=yc(e);return[new n(t,s.left-r.left,s.top-r.top,null,s.bottom-s.top)]}else return Qp(e,t,i)}};function yc(n){let e=n.scrollDOM.getBoundingClientRect();return{left:(n.textDirection==z.LTR?e.left:e.right-n.scrollDOM.clientWidth*n.scaleX)-n.scrollDOM.scrollLeft*n.scaleX,top:e.top-n.scrollDOM.scrollTop*n.scaleY}}function ph(n,e,t,i){let s=n.coordsAtPos(e,t*2);if(!s)return i;let r=n.dom.getBoundingClientRect(),o=(s.top+s.bottom)/2,l=n.posAtCoords({x:r.left+1,y:o}),a=n.posAtCoords({x:r.right-1,y:o});return l==null||a==null?i:{from:Math.max(i.from,Math.min(l,a)),to:Math.min(i.to,Math.max(l,a))}}function Qp(n,e,t){if(t.to<=n.viewport.from||t.from>=n.viewport.to)return[];let i=Math.max(t.from,n.viewport.from),s=Math.min(t.to,n.viewport.to),r=n.textDirection==z.LTR,o=n.contentDOM,l=o.getBoundingClientRect(),a=yc(n),h=o.querySelector(".cm-line"),c=h&&window.getComputedStyle(h),f=l.left+(c?parseInt(c.paddingLeft)+Math.min(0,parseInt(c.textIndent)):0),u=l.right-(c?parseInt(c.paddingRight):0),d=ro(n,i,1),p=ro(n,s,-1),m=d.type==ce.Text?d:null,g=p.type==ce.Text?p:null;if(m&&(n.lineWrapping||d.widgetLineBreaks)&&(m=ph(n,i,1,m)),g&&(n.lineWrapping||p.widgetLineBreaks)&&(g=ph(n,s,-1,g)),m&&g&&m.from==g.from&&m.to==g.to)return w(k(t.from,t.to,m));{let v=m?k(t.from,null,m):D(d,!1),S=g?k(null,t.to,g):D(p,!0),C=[];return(m||d).to<(g||p).from-(m&&g?1:0)||d.widgetLineBreaks>1&&v.bottom+n.defaultLineHeight/2B&&V.from=pe)break;Re>G&&I(Math.max(oe,G),v==null&&oe<=B,Math.min(Re,pe),S==null&&Re>=q,Xe.dir)}if(G=Se.to+1,G>=pe)break}return j.length==0&&I(B,v==null,q,S==null,n.textDirection),{top:E,bottom:W,horizontal:j}}function D(v,S){let C=l.top+(S?v.top:v.bottom);return{top:C,bottom:C,horizontal:[]}}}function Jp(n,e){return n.constructor==e.constructor&&n.eq(e)}var To=class{constructor(e,t){this.view=e,this.layer=t,this.drawn=[],this.scaleX=1,this.scaleY=1,this.measureReq={read:this.measure.bind(this),write:this.draw.bind(this)},this.dom=e.scrollDOM.appendChild(document.createElement("div")),this.dom.classList.add("cm-layer"),t.above&&this.dom.classList.add("cm-layer-above"),t.class&&this.dom.classList.add(t.class),this.scale(),this.dom.setAttribute("aria-hidden","true"),this.setOrder(e.state),e.requestMeasure(this.measureReq),t.mount&&t.mount(this.dom,e)}update(e){e.startState.facet(jn)!=e.state.facet(jn)&&this.setOrder(e.state),(this.layer.update(e,this.dom)||e.geometryChanged)&&(this.scale(),e.view.requestMeasure(this.measureReq))}docViewUpdate(e){this.layer.updateOnDocViewUpdate!==!1&&e.requestMeasure(this.measureReq)}setOrder(e){let t=0,i=e.facet(jn);for(;t!Jp(t,this.drawn[i]))){let t=this.dom.firstChild,i=0;for(let s of e)s.update&&t&&s.constructor&&this.drawn[i].constructor&&s.update(t,this.drawn[i])?(t=t.nextSibling,i++):this.dom.insertBefore(s.draw(),t);for(;t;){let s=t.nextSibling;t.remove(),t=s}this.drawn=e,O.webkit&&(this.dom.style.display=this.dom.firstChild?"":"none")}}destroy(){this.layer.destroy&&this.layer.destroy(this.dom,this.view),this.dom.remove()}},jn=A.define();function xc(n){return[Y.define(e=>new To(e,n)),jn.of(n)]}var gi=A.define({combine(n){return he(n,{cursorBlinkRate:1200,drawRangeCursor:!0,iosSelectionHandles:!0},{cursorBlinkRate:(e,t)=>Math.min(e,t),drawRangeCursor:(e,t)=>e||t})}});function wc(n={}){return[gi.of(n),Zp,em,tm,jh.of(!0)]}function kc(n){return n.startState.facet(gi)!=n.state.facet(gi)}var Zp=xc({above:!0,markers(n){let{state:e}=n,t=e.facet(gi),i=[];for(let s of e.selection.ranges){let r=s==e.selection.main;if(s.empty||t.drawRangeCursor&&!(r&&O.ios&&t.iosSelectionHandles)){let o=r?"cm-cursor cm-cursor-primary":"cm-cursor cm-cursor-secondary",l=s.empty?s:x.cursor(s.head,s.assoc);for(let a of It.forRange(n,o,l))i.push(a)}}return i},update(n,e){n.transactions.some(i=>i.selection)&&(e.style.animationName=e.style.animationName=="cm-blink"?"cm-blink2":"cm-blink");let t=kc(n);return t&&mh(n.state,e),n.docChanged||n.selectionSet||t},mount(n,e){mh(e.state,n)},class:"cm-cursorLayer"});function mh(n,e){e.style.animationDuration=n.facet(gi).cursorBlinkRate+"ms"}var em=xc({above:!1,markers(n){let e=[],{main:t,ranges:i}=n.state.selection;for(let s of i)if(!s.empty)for(let r of It.forRange(n,"cm-selectionBackground",s))e.push(r);if(O.ios&&!t.empty&&n.state.facet(gi).iosSelectionHandles){for(let s of It.forRange(n,"cm-selectionHandle cm-selectionHandle-start",x.cursor(t.from,1)))e.push(s);for(let s of It.forRange(n,"cm-selectionHandle cm-selectionHandle-end",x.cursor(t.to,1)))e.push(s)}return e},update(n,e){return n.docChanged||n.selectionSet||n.viewportChanged||kc(n)},class:"cm-selectionLayer"}),tm=ze.highest(T.theme({".cm-line":{"& ::selection, &::selection":{backgroundColor:"transparent !important"},caretColor:"transparent !important"},".cm-content":{caretColor:"transparent !important","& :focus":{caretColor:"initial !important","&::selection, & ::selection":{backgroundColor:"Highlight !important"}}}})),vc=R.define({map(n,e){return n==null?null:e.mapPos(n)}}),Ii=X.define({create(){return null},update(n,e){return n!=null&&(n=e.changes.mapPos(n)),e.effects.reduce((t,i)=>i.is(vc)?i.value:t,n)}}),im=Y.fromClass(class{constructor(n){this.view=n,this.cursor=null,this.measureReq={read:this.readPos.bind(this),write:this.drawCursor.bind(this)}}update(n){var e;let t=n.state.field(Ii);t==null?this.cursor!=null&&((e=this.cursor)===null||e===void 0||e.remove(),this.cursor=null):(this.cursor||(this.cursor=this.view.scrollDOM.appendChild(document.createElement("div")),this.cursor.className="cm-dropCursor"),(n.startState.field(Ii)!=t||n.docChanged||n.geometryChanged)&&this.view.requestMeasure(this.measureReq))}readPos(){let{view:n}=this,e=n.state.field(Ii),t=e!=null&&n.coordsAtPos(e);if(!t)return null;let i=n.scrollDOM.getBoundingClientRect();return{left:t.left-i.left+n.scrollDOM.scrollLeft*n.scaleX,top:t.top-i.top+n.scrollDOM.scrollTop*n.scaleY,height:t.bottom-t.top}}drawCursor(n){if(this.cursor){let{scaleX:e,scaleY:t}=this.view;n?(this.cursor.style.left=n.left/e+"px",this.cursor.style.top=n.top/t+"px",this.cursor.style.height=n.height/t+"px"):this.cursor.style.left="-100000px"}}destroy(){this.cursor&&this.cursor.remove()}setDropPos(n){this.view.state.field(Ii)!=n&&this.view.dispatch({effects:vc.of(n)})}},{eventObservers:{dragover(n){this.setDropPos(this.view.posAtCoords({x:n.clientX,y:n.clientY}))},dragleave(n){(n.target==this.view.contentDOM||!this.view.contentDOM.contains(n.relatedTarget))&&this.setDropPos(null)},dragend(){this.setDropPos(null)},drop(){this.setDropPos(null)}}});function Sc(){return[Ii,im]}function gh(n,e,t,i,s){e.lastIndex=0;for(let r=n.iterRange(t,i),o=t,l;!r.next().done;o+=r.value.length)if(!r.lineBreak)for(;l=e.exec(r.value);)s(o+l.index,l)}function nm(n,e){let t=n.visibleRanges;if(t.length==1&&t[0].from==n.viewport.from&&t[0].to==n.viewport.to)return t;let i=[];for(let{from:s,to:r}of t)s=Math.max(n.state.doc.lineAt(s).from,s-e),r=Math.min(n.state.doc.lineAt(r).to,r+e),i.length&&i[i.length-1].to>=s?i[i.length-1].to=r:i.push({from:s,to:r});return i}var Oo=class{constructor(e){let{regexp:t,decoration:i,decorate:s,boundary:r,maxLength:o=1e3}=e;if(!t.global)throw new RangeError("The regular expression given to MatchDecorator should have its 'g' flag set");if(this.regexp=t,s)this.addMatch=(l,a,h,c)=>s(c,h,h+l[0].length,l,a);else if(typeof i=="function")this.addMatch=(l,a,h,c)=>{let f=i(l,a,h);f&&c(h,h+l[0].length,f)};else if(i)this.addMatch=(l,a,h,c)=>c(h,h+l[0].length,i);else throw new RangeError("Either 'decorate' or 'decoration' should be provided to MatchDecorator");this.boundary=r,this.maxLength=o}createDeco(e){let t=new Ae,i=t.add.bind(t);for(let{from:s,to:r}of nm(e,this.maxLength))gh(e.state.doc,this.regexp,s,r,(o,l)=>this.addMatch(l,e,o,i));return t.finish()}updateDeco(e,t){let i=1e9,s=-1;return e.docChanged&&e.changes.iterChanges((r,o,l,a)=>{a>=e.view.viewport.from&&l<=e.view.viewport.to&&(i=Math.min(l,i),s=Math.max(a,s))}),e.viewportMoved||s-i>1e3?this.createDeco(e.view):s>-1?this.updateRange(e.view,t.map(e.changes),i,s):t}updateRange(e,t,i,s){for(let r of e.visibleRanges){let o=Math.max(r.from,i),l=Math.min(r.to,s);if(l>=o){let a=e.state.doc.lineAt(o),h=a.toa.from;o--)if(this.boundary.test(a.text[o-1-a.from])){c=o;break}for(;lu.push(b.range(m,g));if(a==h)for(this.regexp.lastIndex=c-a.from;(d=this.regexp.exec(a.text))&&d.indexthis.addMatch(g,e,m,p));t=t.update({filterFrom:c,filterTo:f,filter:(m,g)=>mf,add:u})}}return t}},Do=/x/.unicode!=null?"gu":"g",sm=new RegExp(`[\0-\b +-\x7F-\x9F\xAD\u061C\u200B\u200E\u200F\u2028\u2029\u202D\u202E\u2066\u2067\u2069\uFEFF\uFFF9-\uFFFC]`,Do),rm={0:"null",7:"bell",8:"backspace",10:"newline",11:"vertical tab",13:"carriage return",27:"escape",8203:"zero width space",8204:"zero width non-joiner",8205:"zero width joiner",8206:"left-to-right mark",8207:"right-to-left mark",8232:"line separator",8237:"left-to-right override",8238:"right-to-left override",8294:"left-to-right isolate",8295:"right-to-left isolate",8297:"pop directional isolate",8233:"paragraph separator",65279:"zero width no-break space",65532:"object replacement"},Fr=null;function om(){var n;if(Fr==null&&typeof document<"u"&&document.body){let e=document.body.style;Fr=((n=e.tabSize)!==null&&n!==void 0?n:e.MozTabSize)!=null}return Fr||!1}var Un=A.define({combine(n){let e=he(n,{render:null,specialChars:sm,addSpecialChars:null});return(e.replaceTabs=!om())&&(e.specialChars=new RegExp(" |"+e.specialChars.source,Do)),e.addSpecialChars&&(e.specialChars=new RegExp(e.specialChars.source+"|"+e.addSpecialChars.source,Do)),e}});function Cc(n={}){return[Un.of(n),lm()]}var bh=null;function lm(){return bh||(bh=Y.fromClass(class{constructor(n){this.view=n,this.decorations=P.none,this.decorationCache=Object.create(null),this.decorator=this.makeDecorator(n.state.facet(Un)),this.decorations=this.decorator.createDeco(n)}makeDecorator(n){return new Oo({regexp:n.specialChars,decoration:(e,t,i)=>{let{doc:s}=t.state,r=ae(e[0],0);if(r==9){let o=s.lineAt(i),l=t.state.tabSize,a=lt(o.text,l,i-o.from);return P.replace({widget:new Bo((l-a%l)*this.view.defaultCharacterWidth/this.view.scaleX)})}return this.decorationCache[r]||(this.decorationCache[r]=P.replace({widget:new Po(n,r)}))},boundary:n.replaceTabs?void 0:/[^]/})}update(n){let e=n.state.facet(Un);n.startState.facet(Un)!=e?(this.decorator=this.makeDecorator(e),this.decorations=this.decorator.createDeco(n.view)):this.decorations=this.decorator.updateDeco(n,this.decorations)}},{decorations:n=>n.decorations}))}var am="\u2022";function hm(n){return n>=32?am:n==10?"\u2424":String.fromCharCode(9216+n)}var Po=class extends xe{constructor(e,t){super(),this.options=e,this.code=t}eq(e){return e.code==this.code}toDOM(e){let t=hm(this.code),i=e.state.phrase("Control character")+" "+(rm[this.code]||"0x"+this.code.toString(16)),s=this.options.render&&this.options.render(this.code,i,t);if(s)return s;let r=document.createElement("span");return r.textContent=t,r.title=i,r.setAttribute("aria-label",i),r.className="cm-specialChar",r}ignoreEvent(){return!1}},Bo=class extends xe{constructor(e){super(),this.width=e}eq(e){return e.width==this.width}toDOM(){let e=document.createElement("span");return e.textContent=" ",e.className="cm-tab",e.style.width=this.width+"px",e}ignoreEvent(){return!1}};function Ac(){return fm}var cm=P.line({class:"cm-activeLine"}),fm=Y.fromClass(class{constructor(n){this.decorations=this.getDeco(n)}update(n){(n.docChanged||n.selectionSet)&&(this.decorations=this.getDeco(n.view))}getDeco(n){let e=-1,t=[];for(let i of n.state.selection.ranges){let s=n.lineBlockAt(i.head);s.from>e&&(t.push(cm.range(s.from)),e=s.from)}return P.set(t)}},{decorations:n=>n.decorations});var Ro=2e3;function um(n,e,t){let i=Math.min(e.line,t.line),s=Math.max(e.line,t.line),r=[];if(e.off>Ro||t.off>Ro||e.col<0||t.col<0){let o=Math.min(e.off,t.off),l=Math.max(e.off,t.off);for(let a=i;a<=s;a++){let h=n.doc.line(a);h.length<=l&&r.push(x.range(h.from+o,h.to+l))}}else{let o=Math.min(e.col,t.col),l=Math.max(e.col,t.col);for(let a=i;a<=s;a++){let h=n.doc.line(a),c=Rn(h.text,o,n.tabSize,!0);if(c<0)r.push(x.cursor(h.to));else{let f=Rn(h.text,l,n.tabSize);r.push(x.range(h.from+c,h.from+f))}}}return r}function dm(n,e){let t=n.coordsAtPos(n.viewport.from);return t?Math.round(Math.abs((t.left-e)/n.defaultCharacterWidth)):-1}function yh(n,e){let t=n.posAtCoords({x:e.clientX,y:e.clientY},!1),i=n.state.doc.lineAt(t),s=t-i.from,r=s>Ro?-1:s==i.length?dm(n,e.clientX):lt(i.text,n.state.tabSize,t-i.from);return{line:i.number,col:r,off:s}}function pm(n,e){let t=yh(n,e),i=n.state.selection;return t?{update(s){if(s.docChanged){let r=s.changes.mapPos(s.startState.doc.line(t.line).from),o=s.state.doc.lineAt(r);t={line:o.number,col:t.col,off:Math.min(t.off,o.length)},i=i.map(s.changes)}},get(s,r,o){let l=yh(n,s);if(!l)return i;let a=um(n.state,t,l);return a.length?o?x.create(a.concat(i.ranges)):x.create(a):i}}:null}function Mc(n){let e=n?.eventFilter||(t=>t.altKey&&t.button==0);return T.mouseSelectionStyle.of((t,i)=>e(i)?pm(t,i):null)}var mm={Alt:[18,n=>!!n.altKey],Control:[17,n=>!!n.ctrlKey],Shift:[16,n=>!!n.shiftKey],Meta:[91,n=>!!n.metaKey]},gm={style:"cursor: crosshair"};function Tc(n={}){let[e,t]=mm[n.key||"Alt"],i=Y.fromClass(class{constructor(s){this.view=s,this.isDown=!1}set(s){this.isDown!=s&&(this.isDown=s,this.view.update([]))}},{eventObservers:{keydown(s){this.set(s.keyCode==e||t(s))},keyup(s){(s.keyCode==e||!t(s))&&this.set(!1)},mousemove(s){this.set(t(s))}}});return[i,T.contentAttributes.of(s=>{var r;return!((r=s.plugin(i))===null||r===void 0)&&r.isDown?gm:null})]}var zn="-10000px",ls=class{constructor(e,t,i,s){this.facet=t,this.createTooltipView=i,this.removeTooltipView=s,this.input=e.state.facet(t),this.tooltips=this.input.filter(o=>o);let r=null;this.tooltipViews=this.tooltips.map(o=>r=i(o,r))}update(e,t){var i;let s=e.state.facet(this.facet),r=s.filter(a=>a);if(s===this.input){for(let a of this.tooltipViews)a.update&&a.update(e);return!1}let o=[],l=t?[]:null;for(let a=0;at[h]=a),t.length=l.length),this.input=s,this.tooltips=r,this.tooltipViews=o,!0}};function bm(n){let e=n.dom.ownerDocument.documentElement;return{top:0,left:0,bottom:e.clientHeight,right:e.clientWidth}}var Wr=A.define({combine:n=>{var e,t,i;return{position:O.ios?"absolute":((e=n.find(s=>s.position))===null||e===void 0?void 0:e.position)||"fixed",parent:((t=n.find(s=>s.parent))===null||t===void 0?void 0:t.parent)||null,tooltipSpace:((i=n.find(s=>s.tooltipSpace))===null||i===void 0?void 0:i.tooltipSpace)||bm}}}),xh=new WeakMap,Uo=Y.fromClass(class{constructor(n){this.view=n,this.above=[],this.inView=!0,this.madeAbsolute=!1,this.lastTransaction=0,this.measureTimeout=-1;let e=n.state.facet(Wr);this.position=e.position,this.parent=e.parent,this.classes=n.themeClasses,this.createContainer(),this.measureReq={read:this.readMeasure.bind(this),write:this.writeMeasure.bind(this),key:this},this.resizeObserver=typeof ResizeObserver=="function"?new ResizeObserver(()=>this.measureSoon()):null,this.manager=new ls(n,bi,(t,i)=>this.createTooltip(t,i),t=>{this.resizeObserver&&this.resizeObserver.unobserve(t.dom),t.dom.remove()}),this.above=this.manager.tooltips.map(t=>!!t.above),this.intersectionObserver=typeof IntersectionObserver=="function"?new IntersectionObserver(t=>{Date.now()>this.lastTransaction-50&&t.length>0&&t[t.length-1].intersectionRatio<1&&this.measureSoon()},{threshold:[1]}):null,this.observeIntersection(),n.win.addEventListener("resize",this.measureSoon=this.measureSoon.bind(this)),this.maybeMeasure()}createContainer(){this.parent?(this.container=document.createElement("div"),this.container.style.position="relative",this.container.className=this.view.themeClasses,this.parent.appendChild(this.container)):this.container=this.view.dom}observeIntersection(){if(this.intersectionObserver){this.intersectionObserver.disconnect();for(let n of this.manager.tooltipViews)this.intersectionObserver.observe(n.dom)}}measureSoon(){this.measureTimeout<0&&(this.measureTimeout=setTimeout(()=>{this.measureTimeout=-1,this.maybeMeasure()},50))}update(n){n.transactions.length&&(this.lastTransaction=Date.now());let e=this.manager.update(n,this.above);e&&this.observeIntersection();let t=e||n.geometryChanged,i=n.state.facet(Wr);if(i.position!=this.position&&!this.madeAbsolute){this.position=i.position;for(let s of this.manager.tooltipViews)s.dom.style.position=this.position;t=!0}if(i.parent!=this.parent){this.parent&&this.container.remove(),this.parent=i.parent,this.createContainer();for(let s of this.manager.tooltipViews)this.container.appendChild(s.dom);t=!0}else this.parent&&this.view.themeClasses!=this.classes&&(this.classes=this.container.className=this.view.themeClasses);t&&this.maybeMeasure()}createTooltip(n,e){let t=n.create(this.view),i=e?e.dom:null;if(t.dom.classList.add("cm-tooltip"),n.arrow&&!t.dom.querySelector(".cm-tooltip > .cm-tooltip-arrow")){let s=document.createElement("div");s.className="cm-tooltip-arrow",t.dom.appendChild(s)}return t.dom.style.position=this.position,t.dom.style.top=zn,t.dom.style.left="0px",this.container.insertBefore(t.dom,i),t.mount&&t.mount(this.view),this.resizeObserver&&this.resizeObserver.observe(t.dom),t}destroy(){var n,e,t;this.view.win.removeEventListener("resize",this.measureSoon);for(let i of this.manager.tooltipViews)i.dom.remove(),(n=i.destroy)===null||n===void 0||n.call(i);this.parent&&this.container.remove(),(e=this.resizeObserver)===null||e===void 0||e.disconnect(),(t=this.intersectionObserver)===null||t===void 0||t.disconnect(),clearTimeout(this.measureTimeout)}readMeasure(){let n=1,e=1,t=!1;if(this.position=="fixed"&&this.manager.tooltipViews.length){let{dom:r}=this.manager.tooltipViews[0];if(O.safari){let o=r.getBoundingClientRect();t=Math.abs(o.top+1e4)>1||Math.abs(o.left)>1}else t=!!r.offsetParent&&r.offsetParent!=this.container.ownerDocument.body}if(t||this.position=="absolute")if(this.parent){let r=this.parent.getBoundingClientRect();r.width&&r.height&&(n=r.width/this.parent.offsetWidth,e=r.height/this.parent.offsetHeight)}else({scaleX:n,scaleY:e}=this.view.viewState);let i=this.view.scrollDOM.getBoundingClientRect(),s=Ko(this.view);return{visible:{left:i.left+s.left,top:i.top+s.top,right:i.right-s.right,bottom:i.bottom-s.bottom},parent:this.parent?this.container.getBoundingClientRect():this.view.dom.getBoundingClientRect(),pos:this.manager.tooltips.map((r,o)=>{let l=this.manager.tooltipViews[o];return l.getCoords?l.getCoords(r.pos):this.view.coordsAtPos(r.pos)}),size:this.manager.tooltipViews.map(({dom:r})=>r.getBoundingClientRect()),space:this.view.state.facet(Wr).tooltipSpace(this.view),scaleX:n,scaleY:e,makeAbsolute:t}}writeMeasure(n){var e;if(n.makeAbsolute){this.madeAbsolute=!0,this.position="absolute";for(let l of this.manager.tooltipViews)l.dom.style.position="absolute"}let{visible:t,space:i,scaleX:s,scaleY:r}=n,o=[];for(let l=0;l=Math.min(t.bottom,i.bottom)||f.rightMath.min(t.right,i.right)+.1)){c.style.top=zn;continue}let d=a.arrow?h.dom.querySelector(".cm-tooltip-arrow"):null,p=d?7:0,m=u.right-u.left,g=(e=xh.get(h))!==null&&e!==void 0?e:u.bottom-u.top,b=h.offset||xm,w=this.view.textDirection==z.LTR,k=u.width>i.right-i.left?w?i.left:i.right-u.width:w?Math.max(i.left,Math.min(f.left-(d?14:0)+b.x,i.right-m)):Math.min(Math.max(i.left,f.left-m+(d?14:0)-b.x),i.right-m),D=this.above[l];!a.strictSide&&(D?f.top-g-p-b.yi.bottom)&&D==i.bottom-f.bottom>f.top-i.top&&(D=this.above[l]=!D);let v=(D?f.top-i.top:i.bottom-f.bottom)-p;if(vk&&E.topS&&(S=D?E.top-g-2-p:E.bottom+p+2);if(this.position=="absolute"?(c.style.top=(S-n.parent.top)/r+"px",wh(c,(k-n.parent.left)/s)):(c.style.top=S/r+"px",wh(c,k/s)),d){let E=f.left+(w?b.x:-b.x)-(k+14-7);d.style.left=E/s+"px"}h.overlap!==!0&&o.push({left:k,top:S,right:C,bottom:S+g}),c.classList.toggle("cm-tooltip-above",D),c.classList.toggle("cm-tooltip-below",!D),h.positioned&&h.positioned(n.space)}}maybeMeasure(){if(this.manager.tooltips.length&&(this.view.inView&&this.view.requestMeasure(this.measureReq),this.inView!=this.view.inView&&(this.inView=this.view.inView,!this.inView)))for(let n of this.manager.tooltipViews)n.dom.style.top=zn}},{eventObservers:{scroll(){this.maybeMeasure()}}});function wh(n,e){let t=parseInt(n.style.left,10);(isNaN(t)||Math.abs(e-t)>1)&&(n.style.left=e+"px")}var ym=T.baseTheme({".cm-tooltip":{zIndex:500,boxSizing:"border-box"},"&light .cm-tooltip":{border:"1px solid #bbb",backgroundColor:"#f5f5f5"},"&light .cm-tooltip-section:not(:first-child)":{borderTop:"1px solid #bbb"},"&dark .cm-tooltip":{backgroundColor:"#333338",color:"white"},".cm-tooltip-arrow":{height:"7px",width:"14px",position:"absolute",zIndex:-1,overflow:"hidden","&:before, &:after":{content:"''",position:"absolute",width:0,height:0,borderLeft:"7px solid transparent",borderRight:"7px solid transparent"},".cm-tooltip-above &":{bottom:"-7px","&:before":{borderTop:"7px solid #bbb"},"&:after":{borderTop:"7px solid #f5f5f5",bottom:"1px"}},".cm-tooltip-below &":{top:"-7px","&:before":{borderBottom:"7px solid #bbb"},"&:after":{borderBottom:"7px solid #f5f5f5",top:"1px"}}},"&dark .cm-tooltip .cm-tooltip-arrow":{"&:before":{borderTopColor:"#333338",borderBottomColor:"#333338"},"&:after":{borderTopColor:"transparent",borderBottomColor:"transparent"}}}),xm={x:0,y:0},bi=A.define({enables:[Uo,ym]}),as=A.define({combine:n=>n.reduce((e,t)=>e.concat(t),[])}),hs=class n{static create(e){return new n(e)}constructor(e){this.view=e,this.mounted=!1,this.dom=document.createElement("div"),this.dom.classList.add("cm-tooltip-hover"),this.manager=new ls(e,as,(t,i)=>this.createHostedView(t,i),t=>t.dom.remove())}createHostedView(e,t){let i=e.create(this.view);return i.dom.classList.add("cm-tooltip-section"),this.dom.insertBefore(i.dom,t?t.dom.nextSibling:this.dom.firstChild),this.mounted&&i.mount&&i.mount(this.view),i}mount(e){for(let t of this.manager.tooltipViews)t.mount&&t.mount(e);this.mounted=!0}positioned(e){for(let t of this.manager.tooltipViews)t.positioned&&t.positioned(e)}update(e){this.manager.update(e)}destroy(){var e;for(let t of this.manager.tooltipViews)(e=t.destroy)===null||e===void 0||e.call(t)}passProp(e){let t;for(let i of this.manager.tooltipViews){let s=i[e];if(s!==void 0){if(t===void 0)t=s;else if(t!==s)return}}return t}get offset(){return this.passProp("offset")}get getCoords(){return this.passProp("getCoords")}get overlap(){return this.passProp("overlap")}get resize(){return this.passProp("resize")}},wm=bi.compute([as],n=>{let e=n.facet(as);return e.length===0?null:{pos:Math.min(...e.map(t=>t.pos)),end:Math.max(...e.map(t=>{var i;return(i=t.end)!==null&&i!==void 0?i:t.pos})),create:hs.create,above:e[0].above,arrow:e.some(t=>t.arrow)}}),Oc=A.define(),Lo=class{constructor(e,t,i,s,r,o){this.view=e,this.source=t,this.field=i,this.locked=s,this.setHover=r,this.hoverTime=o,this.hoverTimeout=-1,this.restartTimeout=-1,this.pending=null,this.lastMove={x:0,y:0,target:e.dom,time:0},this.checkHover=this.checkHover.bind(this),e.dom.addEventListener("mouseleave",this.mouseleave=this.mouseleave.bind(this)),e.dom.addEventListener("mousemove",this.mousemove=this.mousemove.bind(this))}update(e){this.pending&&(this.pending=null,clearTimeout(this.restartTimeout),this.restartTimeout=setTimeout(()=>this.startHover(),20))}get active(){return this.view.state.field(this.field)}checkHover(){if(this.hoverTimeout=-1,this.active.length)return;let e=Date.now()-this.lastMove.time;eo.bottom||t.xo.right+e.defaultCharacterWidth)return;let l=e.bidiSpans(e.state.doc.lineAt(s)).find(h=>h.from<=s&&h.to>=s),a=l&&l.dir==z.RTL?-1:1;r=t.x{if(l&&!(Array.isArray(l)&&!l.length)){let a=Array.isArray(l)?l:[l];s&&this.locked.set(a,s),e.dispatch({effects:this.setHover.of(a)})}};if(r&&"then"in r){let l=this.pending={pos:t};r.then(a=>{this.pending==l&&(this.pending=null,o(a))},a=>ne(e.state,a,"hover tooltip"))}else o(r)}get tooltip(){let e=this.view.plugin(Uo),t=e?e.manager.tooltips.findIndex(i=>i.create==hs.create):-1;return t>-1?e.manager.tooltipViews[t]:null}mousemove(e){var t,i;this.lastMove={x:e.clientX,y:e.clientY,target:e.target,time:Date.now()},this.hoverTimeout<0&&(this.hoverTimeout=setTimeout(this.checkHover,this.hoverTime));let{active:s,tooltip:r}=this;if(s.length&&!this.locked.has(s)&&r&&!km(r.dom,e)||this.pending){let{pos:o}=s[0]||this.pending,l=(i=(t=s[0])===null||t===void 0?void 0:t.end)!==null&&i!==void 0?i:o;(o==l?this.view.posAtCoords(this.lastMove)!=o:!vm(this.view,o,l,e.clientX,e.clientY))&&(this.view.dispatch({effects:this.setHover.of([])}),this.pending=null)}}mouseleave(e){clearTimeout(this.hoverTimeout),this.hoverTimeout=-1;let{active:t}=this;if(t.length&&!this.locked.has(t)){let{tooltip:i}=this;i&&i.dom.contains(e.relatedTarget)?this.watchTooltipLeave(i.dom):this.view.dispatch({effects:this.setHover.of([])})}}watchTooltipLeave(e){let t=i=>{e.removeEventListener("mouseleave",t);let{active:s}=this;s.length&&!this.locked.has(s)&&!this.view.dom.contains(i.relatedTarget)&&this.view.dispatch({effects:this.setHover.of([])})};e.addEventListener("mouseleave",t)}destroy(){clearTimeout(this.hoverTimeout),clearTimeout(this.restartTimeout),this.view.dom.removeEventListener("mouseleave",this.mouseleave),this.view.dom.removeEventListener("mousemove",this.mousemove)}},qn=4;function km(n,e){let{left:t,right:i,top:s,bottom:r}=n.getBoundingClientRect(),o;if(o=n.querySelector(".cm-tooltip-arrow")){let l=o.getBoundingClientRect();s=Math.min(l.top,s),r=Math.max(l.bottom,r)}return e.clientX>=t-qn&&e.clientX<=i+qn&&e.clientY>=s-qn&&e.clientY<=r+qn}function vm(n,e,t,i,s,r){let o=n.scrollDOM.getBoundingClientRect(),l=n.documentTop+n.documentPadding.top+n.contentHeight;if(o.left>i||o.rights||Math.min(o.bottom,l)=e&&a<=t}function Dc(n,e={}){let t=R.define(),i=new WeakMap,s=X.define({create(){return[]},update(o,l){let a=i.get(o);if(o.length&&(e.hideOnChange&&(l.docChanged||l.selection)?o=[]:a&&a(l)?o=[]:e.hideOn&&(o=o.filter(h=>!e.hideOn(l,h)))),l.docChanged&&o.length){let h=[];for(let c of o){let f=l.changes.mapPos(c.pos,-1,le.TrackDel);if(f!=null){let u=Object.assign(Object.create(null),c);u.pos=f,u.end!=null&&(u.end=l.changes.mapPos(u.end)),h.push(u)}}o=h}for(let h of l.effects)h.is(t)&&(o=h.value,a=void 0),(h.is(Sm)&&!h.value||h.value==s)&&(o=[]);return o.length&&a&&i.set(o,a),o},provide:o=>as.from(o)}),r=Y.define(o=>new Lo(o,n,s,i,t,e.hoverTime||300));return{active:s,extension:[s,r,Oc.of(r),wm]}}function Pc(n,e,t,i={}){var s;let r=n.state.facet(Oc).map(o=>n.plugin(o)).filter(o=>!!o);if(i.tooltip&&i.tooltip.active){let o=r.find(l=>l.field==i.tooltip.active);o&&(r=[o])}for(let o of r)o.activateHover(n,e,t,(s=i.until)!==null&&s!==void 0?s:(()=>!1))}function Go(n,e){let t=n.plugin(Uo);if(!t)return null;let i=t.manager.tooltips.indexOf(e);return i<0?null:t.manager.tooltipViews[i]}var Sm=R.define();var kh=A.define({combine(n){let e,t;for(let i of n)e=e||i.topContainer,t=t||i.bottomContainer;return{topContainer:e,bottomContainer:t}}});function Qi(n,e){let t=n.plugin(Bc),i=t?t.specs.indexOf(e):-1;return i>-1?t.panels[i]:null}var Bc=Y.fromClass(class{constructor(n){this.input=n.state.facet(Ht),this.specs=this.input.filter(t=>t),this.panels=this.specs.map(t=>t(n));let e=n.state.facet(kh);this.top=new li(n,!0,e.topContainer),this.bottom=new li(n,!1,e.bottomContainer),this.top.sync(this.panels.filter(t=>t.top)),this.bottom.sync(this.panels.filter(t=>!t.top));for(let t of this.panels)t.dom.classList.add("cm-panel"),t.mount&&t.mount()}update(n){let e=n.state.facet(kh);this.top.container!=e.topContainer&&(this.top.sync([]),this.top=new li(n.view,!0,e.topContainer)),this.bottom.container!=e.bottomContainer&&(this.bottom.sync([]),this.bottom=new li(n.view,!1,e.bottomContainer)),this.top.syncClasses(),this.bottom.syncClasses();let t=n.state.facet(Ht);if(t!=this.input){let i=t.filter(a=>a),s=[],r=[],o=[],l=[];for(let a of i){let h=this.specs.indexOf(a),c;h<0?(c=a(n.view),l.push(c)):(c=this.panels[h],c.update&&c.update(n)),s.push(c),(c.top?r:o).push(c)}this.specs=i,this.panels=s,this.top.sync(r),this.bottom.sync(o);for(let a of l)a.dom.classList.add("cm-panel"),a.mount&&a.mount()}else for(let i of this.panels)i.update&&i.update(n)}destroy(){this.top.sync([]),this.bottom.sync([])}},{provide:n=>T.scrollMargins.of(e=>{let t=e.plugin(n);return t&&{top:t.top.scrollMargin(),bottom:t.bottom.scrollMargin()}})}),li=class{constructor(e,t,i){this.view=e,this.top=t,this.container=i,this.dom=void 0,this.classes="",this.panels=[],this.syncClasses()}sync(e){for(let t of this.panels)t.destroy&&e.indexOf(t)<0&&t.destroy();this.panels=e,this.syncDOM()}syncDOM(){if(this.panels.length==0){this.dom&&(this.dom.remove(),this.dom=void 0);return}if(!this.dom){this.dom=document.createElement("div"),this.dom.className=this.top?"cm-panels cm-panels-top":"cm-panels cm-panels-bottom",this.dom.style[this.top?"top":"bottom"]="0";let t=this.container||this.view.dom;t.insertBefore(this.dom,this.top?t.firstChild:null)}let e=this.dom.firstChild;for(let t of this.panels)if(t.dom.parentNode==this.dom){for(;e!=t.dom;)e=vh(e);e=e.nextSibling}else this.dom.insertBefore(t.dom,e);for(;e;)e=vh(e)}scrollMargin(){return!this.dom||this.container?0:Math.max(0,this.top?this.dom.getBoundingClientRect().bottom-Math.max(0,this.view.scrollDOM.getBoundingClientRect().top):Math.min(innerHeight,this.view.scrollDOM.getBoundingClientRect().bottom)-this.dom.getBoundingClientRect().top)}syncClasses(){if(!(!this.container||this.classes==this.view.themeClasses)){for(let e of this.classes.split(" "))e&&this.container.classList.remove(e);for(let e of(this.classes=this.view.themeClasses).split(" "))e&&this.container.classList.add(e)}}};function vh(n){let e=n.nextSibling;return n.remove(),e}var Ht=A.define({enables:Bc});function Rc(n,e){let t,i=new Promise(o=>t=o),s=o=>Cm(o,e,t);n.state.field(Hr,!1)?n.dispatch({effects:Lc.of(s)}):n.dispatch({effects:R.appendConfig.of(Hr.init(()=>[s]))});let r=Ec.of(s);return{close:r,result:i.then(o=>((n.win.queueMicrotask||(a=>n.win.setTimeout(a,10)))(()=>{n.state.field(Hr).indexOf(s)>-1&&n.dispatch({effects:r})}),o))}}var Hr=X.define({create(){return[]},update(n,e){for(let t of e.effects)t.is(Lc)?n=[t.value].concat(n):t.is(Ec)&&(n=n.filter(i=>i!=t.value));return n},provide:n=>Ht.computeN([n],e=>e.field(n))}),Lc=R.define(),Ec=R.define();function Cm(n,e,t){let i=e.content?e.content(n,()=>o(null)):null;if(!i){if(i=H("form"),e.input){let l=H("input",e.input);/^(text|password|number|email|tel|url)$/.test(l.type)&&l.classList.add("cm-textfield"),l.name||(l.name="input"),i.appendChild(H("label",(e.label||"")+": ",l))}else i.appendChild(document.createTextNode(e.label||""));i.appendChild(document.createTextNode(" ")),i.appendChild(H("button",{class:"cm-button",type:"submit"},e.submitLabel||"OK"))}let s=i.nodeName=="FORM"?[i]:i.querySelectorAll("form");for(let l=0;l{h.keyCode==27?(h.preventDefault(),o(null)):h.keyCode==13&&(h.preventDefault(),o(a))}),a.addEventListener("submit",h=>{h.preventDefault(),o(a)})}let r=H("div",i,H("button",{onclick:()=>o(null),"aria-label":n.state.phrase("close"),class:"cm-dialog-close",type:"button"},["\xD7"]));e.class&&(r.className=e.class),r.classList.add("cm-dialog");function o(l){r.contains(r.ownerDocument.activeElement)&&n.focus(),t(l)}return{dom:r,top:e.top,mount:()=>{if(e.focus){let l;typeof e.focus=="string"?l=i.querySelector(e.focus):l=i.querySelector("input")||i.querySelector("button"),l&&"select"in l?l.select():l&&"focus"in l&&l.focus()}}}}var ke=class extends Ee{compare(e){return this==e||this.constructor==e.constructor&&this.eq(e)}eq(e){return!1}destroy(e){}};ke.prototype.elementClass="";ke.prototype.toDOM=void 0;ke.prototype.mapMode=le.TrackBefore;ke.prototype.startSide=ke.prototype.endSide=-1;ke.prototype.point=!0;var Gn=A.define(),Am=A.define(),Mm={class:"",renderEmptyElements:!1,elementStyle:"",markers:()=>F.empty,lineMarker:()=>null,widgetMarker:()=>null,lineMarkerChange:null,initialSpacer:null,updateSpacer:null,domEventHandlers:{},side:"before"},$i=A.define();function ms(n){return[Ic(),$i.of({...Mm,...n})]}var Eo=A.define({combine:n=>n.some(e=>e)});function Ic(n){let e=[Tm];return n&&n.fixed===!1&&e.push(Eo.of(!0)),e}var Tm=Y.fromClass(class{constructor(n){this.view=n,this.domAfter=null,this.prevViewport=n.viewport,this.dom=document.createElement("div"),this.dom.className="cm-gutters cm-gutters-before",this.dom.setAttribute("aria-hidden","true"),this.dom.style.minHeight=this.view.contentHeight/this.view.scaleY+"px",this.gutters=n.state.facet($i).map(e=>new cs(n,e)),this.fixed=!n.state.facet(Eo);for(let e of this.gutters)e.config.side=="after"?this.getDOMAfter().appendChild(e.dom):this.dom.appendChild(e.dom);this.fixed&&(this.dom.style.position="sticky"),this.syncGutters(!1),n.scrollDOM.insertBefore(this.dom,n.contentDOM)}getDOMAfter(){return this.domAfter||(this.domAfter=document.createElement("div"),this.domAfter.className="cm-gutters cm-gutters-after",this.domAfter.setAttribute("aria-hidden","true"),this.domAfter.style.minHeight=this.view.contentHeight/this.view.scaleY+"px",this.domAfter.style.position=this.fixed?"sticky":"",this.view.scrollDOM.appendChild(this.domAfter)),this.domAfter}update(n){if(this.updateGutters(n)){let e=this.prevViewport,t=n.view.viewport,i=Math.min(e.to,t.to)-Math.max(e.from,t.from);this.syncGutters(i<(t.to-t.from)*.8)}if(n.geometryChanged){let e=this.view.contentHeight/this.view.scaleY+"px";this.dom.style.minHeight=e,this.domAfter&&(this.domAfter.style.minHeight=e)}this.view.state.facet(Eo)!=!this.fixed&&(this.fixed=!this.fixed,this.dom.style.position=this.fixed?"sticky":"",this.domAfter&&(this.domAfter.style.position=this.fixed?"sticky":"")),this.prevViewport=n.view.viewport}syncGutters(n){let e=this.dom.nextSibling;n&&(this.dom.remove(),this.domAfter&&this.domAfter.remove());let t=F.iter(this.view.state.facet(Gn),this.view.viewport.from),i=[],s=this.gutters.map(r=>new No(r,this.view.viewport,-this.view.documentPadding.top));for(let r of this.view.viewportLineBlocks)if(i.length&&(i=[]),Array.isArray(r.type)){let o=!0;for(let l of r.type)if(l.type==ce.Text&&o){Io(t,i,l.from);for(let a of s)a.line(this.view,l,i);o=!1}else if(l.widget)for(let a of s)a.widget(this.view,l)}else if(r.type==ce.Text){Io(t,i,r.from);for(let o of s)o.line(this.view,r,i)}else if(r.widget)for(let o of s)o.widget(this.view,r);for(let r of s)r.finish();n&&(this.view.scrollDOM.insertBefore(this.dom,e),this.domAfter&&this.view.scrollDOM.appendChild(this.domAfter))}updateGutters(n){let e=n.startState.facet($i),t=n.state.facet($i),i=n.docChanged||n.heightChanged||n.viewportChanged||!F.eq(n.startState.facet(Gn),n.state.facet(Gn),n.view.viewport.from,n.view.viewport.to);if(e==t)for(let s of this.gutters)s.update(n)&&(i=!0);else{i=!0;let s=[];for(let r of t){let o=e.indexOf(r);o<0?s.push(new cs(this.view,r)):(this.gutters[o].update(n),s.push(this.gutters[o]))}for(let r of this.gutters)r.dom.remove(),s.indexOf(r)<0&&r.destroy();for(let r of s)r.config.side=="after"?this.getDOMAfter().appendChild(r.dom):this.dom.appendChild(r.dom);this.gutters=s}return i}destroy(){for(let n of this.gutters)n.destroy();this.dom.remove(),this.domAfter&&this.domAfter.remove()}},{provide:n=>T.scrollMargins.of(e=>{let t=e.plugin(n);if(!t||t.gutters.length==0||!t.fixed)return null;let i=t.dom.offsetWidth*e.scaleX,s=t.domAfter?t.domAfter.offsetWidth*e.scaleX:0;return e.textDirection==z.LTR?{left:i,right:s}:{right:i,left:s}})});function Sh(n){return Array.isArray(n)?n:[n]}function Io(n,e,t){for(;n.value&&n.from<=t;)n.from==t&&e.push(n.value),n.next()}var No=class{constructor(e,t,i){this.gutter=e,this.height=i,this.i=0,this.cursor=F.iter(e.markers,t.from)}addElement(e,t,i){let{gutter:s}=this,r=(t.top-this.height)/e.scaleY,o=t.height/e.scaleY;if(this.i==s.elements.length){let l=new fs(e,o,r,i);s.elements.push(l),s.dom.appendChild(l.dom)}else s.elements[this.i].update(e,o,r,i);this.height=t.bottom,this.i++}line(e,t,i){let s=[];Io(this.cursor,s,t.from),i.length&&(s=s.concat(i));let r=this.gutter.config.lineMarker(e,t,s);r&&s.unshift(r);let o=this.gutter;s.length==0&&!o.config.renderEmptyElements||this.addElement(e,t,s)}widget(e,t){let i=this.gutter.config.widgetMarker(e,t.widget,t),s=i?[i]:null;for(let r of e.state.facet(Am)){let o=r(e,t.widget,t);o&&(s||(s=[])).push(o)}s&&this.addElement(e,t,s)}finish(){let e=this.gutter;for(;e.elements.length>this.i;){let t=e.elements.pop();e.dom.removeChild(t.dom),t.destroy()}}},cs=class{constructor(e,t){this.view=e,this.config=t,this.elements=[],this.spacer=null,this.dom=document.createElement("div"),this.dom.className="cm-gutter"+(this.config.class?" "+this.config.class:"");for(let i in t.domEventHandlers)this.dom.addEventListener(i,s=>{let r=s.target,o;if(r!=this.dom&&this.dom.contains(r)){for(;r.parentNode!=this.dom;)r=r.parentNode;let a=r.getBoundingClientRect();o=(a.top+a.bottom)/2}else o=s.clientY;let l=e.lineBlockAtHeight(o-e.documentTop);t.domEventHandlers[i](e,l,s)&&s.preventDefault()});this.markers=Sh(t.markers(e)),t.initialSpacer&&(this.spacer=new fs(e,0,0,[t.initialSpacer(e)]),this.dom.appendChild(this.spacer.dom),this.spacer.dom.style.cssText+="visibility: hidden; pointer-events: none")}update(e){let t=this.markers;if(this.markers=Sh(this.config.markers(e.view)),this.spacer&&this.config.updateSpacer){let s=this.config.updateSpacer(this.spacer.markers[0],e);s!=this.spacer.markers[0]&&this.spacer.update(e.view,0,0,[s])}let i=e.view.viewport;return!F.eq(this.markers,t,i.from,i.to)||(this.config.lineMarkerChange?this.config.lineMarkerChange(e):!1)}destroy(){for(let e of this.elements)e.destroy()}},fs=class{constructor(e,t,i,s){this.height=-1,this.above=0,this.markers=[],this.dom=document.createElement("div"),this.dom.className="cm-gutterElement",this.update(e,t,i,s)}update(e,t,i,s){this.height!=t&&(this.height=t,this.dom.style.height=t+"px"),this.above!=i&&(this.dom.style.marginTop=(this.above=i)?i+"px":""),Om(this.markers,s)||this.setMarkers(e,s)}setMarkers(e,t){let i="cm-gutterElement",s=this.dom.firstChild;for(let r=0,o=0;;){let l=o,a=rr(l,a,h)||o(l,a,h):o}return i}})}}),Ki=class extends ke{constructor(e){super(),this.number=e}eq(e){return this.number==e.number}toDOM(){return document.createTextNode(this.number)}};function Vr(n,e){return n.state.facet(ai).formatNumber(e,n.state)}var Bm=$i.compute([ai],n=>({class:"cm-lineNumbers",renderEmptyElements:!1,markers(e){return e.state.facet(Dm)},lineMarker(e,t,i){return i.some(s=>s.toDOM)?null:new Ki(Vr(e,e.state.doc.lineAt(t.from).number))},widgetMarker:(e,t,i)=>{for(let s of e.state.facet(Pm)){let r=s(e,t,i);if(r)return r}return null},lineMarkerChange:e=>e.startState.facet(ai)!=e.state.facet(ai),initialSpacer(e){return new Ki(Vr(e,Ch(e.state.doc.lines)))},updateSpacer(e,t){let i=Vr(t.view,Ch(t.view.state.doc.lines));return i==e.number?e:new Ki(i)},domEventHandlers:n.facet(ai).domEventHandlers,side:"before"}));function Nc(n={}){return[ai.of(n),Ic(),Bm]}function Ch(n){let e=9;for(;e{let e=[],t=-1;for(let i of n.selection.ranges){let s=n.doc.lineAt(i.head).from;s>t&&(t=s,e.push(Rm.range(s)))}return F.of(e)});function Fc(){return Lm}var Em=0,Ji=class{constructor(e,t){this.from=e,this.to=t}},L=class{constructor(e={}){this.id=Em++,this.perNode=!!e.perNode,this.deserialize=e.deserialize||(()=>{throw new Error("This node type doesn't define a deserialize function")}),this.combine=e.combine||null}add(e){if(this.perNode)throw new RangeError("Can't add per-node props to node types");return typeof e!="function"&&(e=ue.match(e)),t=>{let i=e(t);return i===void 0?null:[this,i]}}};L.closedBy=new L({deserialize:n=>n.split(" ")});L.openedBy=new L({deserialize:n=>n.split(" ")});L.group=new L({deserialize:n=>n.split(" ")});L.isolate=new L({deserialize:n=>{if(n&&n!="rtl"&&n!="ltr"&&n!="auto")throw new RangeError("Invalid value for isolate: "+n);return n||"auto"}});L.contextHash=new L({perNode:!0});L.lookAhead=new L({perNode:!0});L.mounted=new L({perNode:!0});var Vt=class{constructor(e,t,i,s=!1){this.tree=e,this.overlay=t,this.parser=i,this.bracketed=s}static get(e){return e&&e.props&&e.props[L.mounted.id]}},Im=Object.create(null),ue=class n{constructor(e,t,i,s=0){this.name=e,this.props=t,this.id=i,this.flags=s}static define(e){let t=e.props&&e.props.length?Object.create(null):Im,i=(e.top?1:0)|(e.skipped?2:0)|(e.error?4:0)|(e.name==null?8:0),s=new n(e.name||"",t,e.id,i);if(e.props){for(let r of e.props)if(Array.isArray(r)||(r=r(s)),r){if(r[0].perNode)throw new RangeError("Can't store a per-node prop on a node type");t[r[0].id]=r[1]}}return s}prop(e){return this.props[e.id]}get isTop(){return(this.flags&1)>0}get isSkipped(){return(this.flags&2)>0}get isError(){return(this.flags&4)>0}get isAnonymous(){return(this.flags&8)>0}is(e){if(typeof e=="string"){if(this.name==e)return!0;let t=this.prop(L.group);return t?t.indexOf(e)>-1:!1}return this.id==e}static match(e){let t=Object.create(null);for(let i in e)for(let s of i.split(" "))t[s]=e[i];return i=>{for(let s=i.prop(L.group),r=-1;r<(s?s.length:0);r++){let o=t[r<0?i.name:s[r]];if(o)return o}}}};ue.none=new ue("",Object.create(null),0,8);var Zi=class n{constructor(e){this.types=e;for(let t=0;t0;for(let a=this.cursor(o|J.IncludeAnonymous);;){let h=!1;if(a.from<=r&&a.to>=s&&(!l&&a.type.isAnonymous||t(a)!==!1)){if(a.firstChild())continue;h=!0}for(;h&&i&&(l||!a.type.isAnonymous)&&i(a),!a.nextSibling();){if(!a.parent())return;h=!0}}}prop(e){return e.perNode?this.props?this.props[e.id]:void 0:this.type.prop(e)}get propValues(){let e=[];if(this.props)for(let t in this.props)e.push([+t,this.props[t]]);return e}balance(e={}){return this.children.length<=8?this:el(ue.none,this.children,this.positions,0,this.children.length,0,this.length,(t,i,s)=>new n(this.type,t,i,s,this.propValues),e.makeTree||((t,i,s)=>new n(ue.none,t,i,s)))}static build(e){return Fm(e)}};Z.empty=new Z(ue.none,[],[],0);var _o=class n{constructor(e,t){this.buffer=e,this.index=t}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}get pos(){return this.index}next(){this.index-=4}fork(){return new n(this.buffer,this.index)}},xt=class n{constructor(e,t,i){this.buffer=e,this.length=t,this.set=i}get type(){return ue.none}toString(){let e=[];for(let t=0;t0));a=o[a+3]);return l}slice(e,t,i){let s=this.buffer,r=new Uint16Array(t-e),o=0;for(let l=e,a=0;l=e&&te;case 1:return t<=e&&i>e;case 2:return i>e;case 4:return!0}}function en(n,e,t,i){for(var s;n.from==n.to||(t<1?n.from>=e:n.from>e)||(t>-1?n.to<=e:n.to0?l.length:-1;e!=h;e+=t){let c=l[e],f=a[e]+o.from,u;if(!(!(r&J.EnterBracketed&&c instanceof Z&&(u=Vt.get(c))&&!u.overlay&&u.bracketed&&i>=f&&i<=f+c.length)&&!zc(s,i,f,f+c.length))){if(c instanceof xt){if(r&J.ExcludeBuffers)continue;let d=c.findChild(0,c.buffer.length,t,i-f,s);if(d>-1)return new tn(new Xo(o,c,e,f),null,d)}else if(r&J.IncludeAnonymous||!c.type.isAnonymous||Zo(c)){let d;if(!(r&J.IgnoreMounts)&&(d=Vt.get(c))&&!d.overlay)return new n(d.tree,f,e,o);let p=new n(c,f,e,o);return r&J.IncludeAnonymous||!p.type.isAnonymous?p:p.nextChild(t<0?c.children.length-1:0,t,i,s,r)}}}if(r&J.IncludeAnonymous||!o.type.isAnonymous||(o.index>=0?e=o.index+t:e=t<0?-1:o._parent._tree.children.length,o=o._parent,!o))return null}}get firstChild(){return this.nextChild(0,1,0,4)}get lastChild(){return this.nextChild(this._tree.children.length-1,-1,0,4)}childAfter(e){return this.nextChild(0,1,e,2)}childBefore(e){return this.nextChild(this._tree.children.length-1,-1,e,-2)}prop(e){return this._tree.prop(e)}enter(e,t,i=0){let s;if(!(i&J.IgnoreOverlays)&&(s=Vt.get(this._tree))&&s.overlay){let r=e-this.from,o=i&J.EnterBracketed&&s.bracketed;for(let{from:l,to:a}of s.overlay)if((t>0||o?l<=r:l=r:a>r))return new n(s.tree,s.overlay[0].from+this.from,-1,this)}return this.nextChild(0,1,e,t,i)}nextSignificantParent(){let e=this;for(;e.type.isAnonymous&&e._parent;)e=e._parent;return e}get parent(){return this._parent?this._parent.nextSignificantParent():null}get nextSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index+1,1,0,4):null}get prevSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index-1,-1,0,4):null}get tree(){return this._tree}toTree(){return this._tree}toString(){return this._tree.toString()}};function Hc(n,e,t,i){let s=n.cursor(),r=[];if(!s.firstChild())return r;if(t!=null){for(let o=!1;!o;)if(o=s.type.is(t),!s.nextSibling())return r}for(;;){if(i!=null&&s.type.is(i))return r;if(s.type.is(e)&&r.push(s.node),!s.nextSibling())return i==null?r:[]}}function Yo(n,e,t=e.length-1){for(let i=n;t>=0;i=i.parent){if(!i)return!1;if(!i.type.isAnonymous){if(e[t]&&e[t]!=i.name)return!1;t--}}return!0}var Xo=class{constructor(e,t,i,s){this.parent=e,this.buffer=t,this.index=i,this.start=s}},tn=class n extends ys{get name(){return this.type.name}get from(){return this.context.start+this.context.buffer.buffer[this.index+1]}get to(){return this.context.start+this.context.buffer.buffer[this.index+2]}constructor(e,t,i){super(),this.context=e,this._parent=t,this.index=i,this.type=e.buffer.set.types[e.buffer.buffer[i]]}child(e,t,i){let{buffer:s}=this.context,r=s.findChild(this.index+4,s.buffer[this.index+3],e,t-this.context.start,i);return r<0?null:new n(this.context,this,r)}get firstChild(){return this.child(1,0,4)}get lastChild(){return this.child(-1,0,4)}childAfter(e){return this.child(1,e,2)}childBefore(e){return this.child(-1,e,-2)}prop(e){return this.type.prop(e)}enter(e,t,i=0){if(i&J.ExcludeBuffers)return null;let{buffer:s}=this.context,r=s.findChild(this.index+4,s.buffer[this.index+3],t>0?1:-1,e-this.context.start,t);return r<0?null:new n(this.context,this,r)}get parent(){return this._parent||this.context.parent.nextSignificantParent()}externalSibling(e){return this._parent?null:this.context.parent.nextChild(this.context.index+e,e,0,4)}get nextSibling(){let{buffer:e}=this.context,t=e.buffer[this.index+3];return t<(this._parent?e.buffer[this._parent.index+3]:e.buffer.length)?new n(this.context,this._parent,t):this.externalSibling(1)}get prevSibling(){let{buffer:e}=this.context,t=this._parent?this._parent.index+4:0;return this.index==t?this.externalSibling(-1):new n(this.context,this._parent,e.findChild(t,this.index,-1,0,4))}get tree(){return null}toTree(){let e=[],t=[],{buffer:i}=this.context,s=this.index+4,r=i.buffer[this.index+3];if(r>s){let o=i.buffer[this.index+1];e.push(i.slice(s,r,o)),t.push(0)}return new Z(this.type,e,t,this.to-this.from)}toString(){return this.context.buffer.childString(this.index)}};function qc(n){if(!n.length)return null;let e=0,t=n[0];for(let r=1;rt.from||o.to=e){let l=new et(o.tree,o.overlay[0].from+r.from,-1,r);(s||(s=[i])).push(en(l,e,t,!1))}}return s?qc(s):i}var nn=class{get name(){return this.type.name}constructor(e,t=0){if(this.buffer=null,this.stack=[],this.index=0,this.bufferNode=null,this.mode=t&~J.EnterBracketed,e instanceof et)this.yieldNode(e);else{this._tree=e.context.parent,this.buffer=e.context;for(let i=e._parent;i;i=i._parent)this.stack.unshift(i.index);this.bufferNode=e,this.yieldBuf(e.index)}}yieldNode(e){return e?(this._tree=e,this.type=e.type,this.from=e.from,this.to=e.to,!0):!1}yieldBuf(e,t){this.index=e;let{start:i,buffer:s}=this.buffer;return this.type=t||s.set.types[s.buffer[e]],this.from=i+s.buffer[e+1],this.to=i+s.buffer[e+2],!0}yield(e){return e?e instanceof et?(this.buffer=null,this.yieldNode(e)):(this.buffer=e.context,this.yieldBuf(e.index,e.type)):!1}toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString()}enterChild(e,t,i){if(!this.buffer)return this.yield(this._tree.nextChild(e<0?this._tree._tree.children.length-1:0,e,t,i,this.mode));let{buffer:s}=this.buffer,r=s.findChild(this.index+4,s.buffer[this.index+3],e,t-this.buffer.start,i);return r<0?!1:(this.stack.push(this.index),this.yieldBuf(r))}firstChild(){return this.enterChild(1,0,4)}lastChild(){return this.enterChild(-1,0,4)}childAfter(e){return this.enterChild(1,e,2)}childBefore(e){return this.enterChild(-1,e,-2)}enter(e,t,i=this.mode){return this.buffer?i&J.ExcludeBuffers?!1:this.enterChild(1,e,t):this.yield(this._tree.enter(e,t,i))}parent(){if(!this.buffer)return this.yieldNode(this.mode&J.IncludeAnonymous?this._tree._parent:this._tree.parent);if(this.stack.length)return this.yieldBuf(this.stack.pop());let e=this.mode&J.IncludeAnonymous?this.buffer.parent:this.buffer.parent.nextSignificantParent();return this.buffer=null,this.yieldNode(e)}sibling(e){if(!this.buffer)return this._tree._parent?this.yield(this._tree.index<0?null:this._tree._parent.nextChild(this._tree.index+e,e,0,4,this.mode)):!1;let{buffer:t}=this.buffer,i=this.stack.length-1;if(e<0){let s=i<0?0:this.stack[i]+4;if(this.index!=s)return this.yieldBuf(t.findChild(s,this.index,-1,0,4))}else{let s=t.buffer[this.index+3];if(s<(i<0?t.buffer.length:t.buffer[this.stack[i]+3]))return this.yieldBuf(s)}return i<0?this.yield(this.buffer.parent.nextChild(this.buffer.index+e,e,0,4,this.mode)):!1}nextSibling(){return this.sibling(1)}prevSibling(){return this.sibling(-1)}atLastNode(e){let t,i,{buffer:s}=this;if(s){if(e>0){if(this.index-1)for(let r=t+e,o=e<0?-1:i._tree.children.length;r!=o;r+=e){let l=i._tree.children[r];if(this.mode&J.IncludeAnonymous||l instanceof xt||!l.type.isAnonymous||Zo(l))return!1}return!0}move(e,t){if(t&&this.enterChild(e,0,4))return!0;for(;;){if(this.sibling(e))return!0;if(this.atLastNode(e)||!this.parent())return!1}}next(e=!0){return this.move(1,e)}prev(e=!0){return this.move(-1,e)}moveTo(e,t=0){for(;(this.from==this.to||(t<1?this.from>=e:this.from>e)||(t>-1?this.to<=e:this.to=0;){for(let o=e;o;o=o._parent)if(o.index==s){if(s==this.index)return o;t=o,i=r+1;break e}s=this.stack[--r]}for(let s=i;s=0;r--){if(r<0)return Yo(this._tree,e,s);let o=i[t.buffer[this.stack[r]]];if(!o.isAnonymous){if(e[s]&&e[s]!=o.name)return!1;s--}}return!0}};function Zo(n){return n.children.some(e=>e instanceof xt||!e.type.isAnonymous||Zo(e))}function Fm(n){var e;let{buffer:t,nodeSet:i,maxBufferLength:s=1024,reused:r=[],minRepeatType:o=i.types.length}=n,l=Array.isArray(t)?new _o(t,t.length):t,a=i.types,h=0,c=0;function f(v,S,C,E,W,j){let{id:I,start:B,end:q,size:V}=l,G=c,pe=h;if(V<0)if(l.next(),V==-1){let rt=r[I];C.push(rt),E.push(B-v);return}else if(V==-3){h=I;return}else if(V==-4){c=I;return}else throw new RangeError(`Unrecognized record size: ${V}`);let Se=a[I],Xe,oe,Re=B-v;if(q-B<=s&&(oe=g(l.pos-S,W))){let rt=new Uint16Array(oe.size-oe.skip),Le=l.pos-oe.size,Qe=rt.length;for(;l.pos>Le;)Qe=b(oe.start,rt,Qe);Xe=new xt(rt,q-oe.start,i),Re=oe.start-v}else{let rt=l.pos-V;l.next();let Le=[],Qe=[],Ot=I>=o?I:-1,Xt=0,kn=q;for(;l.pos>rt;)Ot>=0&&l.id==Ot&&l.size>=0?(l.end<=kn-s&&(p(Le,Qe,B,Xt,l.end,kn,Ot,G,pe),Xt=Le.length,kn=l.end),l.next()):j>2500?u(B,rt,Le,Qe):f(B,rt,Le,Qe,Ot,j+1);if(Ot>=0&&Xt>0&&Xt-1&&Xt>0){let ua=d(Se,pe);Xe=el(Se,Le,Qe,0,Le.length,0,q-B,ua,ua)}else Xe=m(Se,Le,Qe,q-B,G-q,pe)}C.push(Xe),E.push(Re)}function u(v,S,C,E){let W=[],j=0,I=-1;for(;l.pos>S;){let{id:B,start:q,end:V,size:G}=l;if(G>4)l.next();else{if(I>-1&&q=0;V-=3)B[G++]=W[V],B[G++]=W[V+1]-q,B[G++]=W[V+2]-q,B[G++]=G;C.push(new xt(B,W[2]-q,i)),E.push(q-v)}}function d(v,S){return(C,E,W)=>{let j=0,I=C.length-1,B,q;if(I>=0&&(B=C[I])instanceof Z){if(!I&&B.type==v&&B.length==W)return B;(q=B.prop(L.lookAhead))&&(j=E[I]+B.length+q)}return m(v,C,E,W,j,S)}}function p(v,S,C,E,W,j,I,B,q){let V=[],G=[];for(;v.length>E;)V.push(v.pop()),G.push(S.pop()+C-W);v.push(m(i.types[I],V,G,j-W,B-j,q)),S.push(W-C)}function m(v,S,C,E,W,j,I){if(j){let B=[L.contextHash,j];I=I?[B].concat(I):[B]}if(W>25){let B=[L.lookAhead,W];I=I?[B].concat(I):[B]}return new Z(v,S,C,E,I)}function g(v,S){let C=l.fork(),E=0,W=0,j=0,I=C.end-s,B={size:0,start:0,skip:0};e:for(let q=C.pos-v;C.pos>q;){let V=C.size;if(C.id==S&&V>=0){B.size=E,B.start=W,B.skip=j,j+=4,E+=4,C.next();continue}let G=C.pos-V;if(V<0||G=o?4:0,Se=C.start;for(C.next();C.pos>G;){if(C.size<0)if(C.size==-3||C.size==-4)pe+=4;else break e;else C.id>=o&&(pe+=4);C.next()}W=Se,E+=V,j+=pe}return(S<0||E==v)&&(B.size=E,B.start=W,B.skip=j),B.size>4?B:void 0}function b(v,S,C){let{id:E,start:W,end:j,size:I}=l;if(l.next(),I>=0&&E4){let q=l.pos-(I-4);for(;l.pos>q;)C=b(v,S,C)}S[--C]=B,S[--C]=j-v,S[--C]=W-v,S[--C]=E}else I==-3?h=E:I==-4&&(c=E);return C}let w=[],k=[];for(;l.pos>0;)f(n.start||0,n.bufferStart||0,w,k,-1,0);let D=(e=n.length)!==null&&e!==void 0?e:w.length?k[0]+w[0].length:0;return new Z(a[n.topID],w.reverse(),k.reverse(),D)}var Vc=new WeakMap;function bs(n,e){if(!n.isAnonymous||e instanceof xt||e.type!=n)return 1;let t=Vc.get(e);if(t==null){t=1;for(let i of e.children){if(i.type!=n||!(i instanceof Z)){t=1;break}t+=bs(n,i)}Vc.set(e,t)}return t}function el(n,e,t,i,s,r,o,l,a){let h=0;for(let p=i;p=c)break;S+=C}if(k==D+1){if(S>c){let C=p[D];d(C.children,C.positions,0,C.children.length,m[D]+w);continue}f.push(p[D])}else{let C=m[k-1]+p[k-1].length-v;f.push(el(n,p,m,D,k,v,C,null,a))}u.push(v+w-r)}}return d(e,t,i,s,0),(l||a)(f,u,o)}var zt=class n{constructor(e,t,i,s,r=!1,o=!1){this.from=e,this.to=t,this.tree=i,this.offset=s,this.open=(r?1:0)|(o?2:0)}get openStart(){return(this.open&1)>0}get openEnd(){return(this.open&2)>0}static addTree(e,t=[],i=!1){let s=[new n(0,e.length,e,0,!1,i)];for(let r of t)r.to>e.length&&s.push(r);return s}static applyChanges(e,t,i=128){if(!t.length)return e;let s=[],r=1,o=e.length?e[0]:null;for(let l=0,a=0,h=0;;l++){let c=l=i)for(;o&&o.from=u.from||f<=u.to||h){let d=Math.max(u.from,a)-h,p=Math.min(u.to,f)-h;u=d>=p?null:new n(d,p,u.tree,u.offset+h,l>0,!!c)}if(u&&s.push(u),o.to>f)break;o=rnew Ji(s.from,s.to)):[new Ji(0,0)]:[new Ji(0,e.length)],this.createParse(e,t||[],i)}parse(e,t,i){let s=this.startParse(e,t,i);for(;;){let r=s.advance();if(r)return r}}},Jo=class{constructor(e){this.string=e}get length(){return this.string.length}chunk(e){return this.string.slice(e)}get lineChunks(){return!1}read(e,t){return this.string.slice(e,t)}};var Iy=new L({perNode:!0});var Wm=0,je=class n{constructor(e,t,i,s){this.name=e,this.set=t,this.base=i,this.modified=s,this.id=Wm++}toString(){let{name:e}=this;for(let t of this.modified)t.name&&(e=`${t.name}(${e})`);return e}static define(e,t){let i=typeof e=="string"?e:"?";if(e instanceof n&&(t=e),t?.base)throw new Error("Can not derive from a modified tag");let s=new n(i,[],null,[]);if(s.set.push(s),t)for(let r of t.set)s.set.push(r);return s}static defineModifier(e){let t=new vs(e);return i=>i.modified.indexOf(t)>-1?i:vs.get(i.base||i,i.modified.concat(t).sort((s,r)=>s.id-r.id))}},Hm=0,vs=class n{constructor(e){this.name=e,this.instances=[],this.id=Hm++}static get(e,t){if(!t.length)return e;let i=t[0].instances.find(l=>l.base==e&&Vm(t,l.modified));if(i)return i;let s=[],r=new je(e.name,s,e,t);for(let l of t)l.instances.push(r);let o=zm(t);for(let l of e.set)if(!l.modified.length)for(let a of o)s.push(n.get(l,a));return r}};function Vm(n,e){return n.length==e.length&&n.every((t,i)=>t==e[i])}function zm(n){let e=[[]];for(let t=0;ti.length-t.length)}function Ss(n){let e=Object.create(null);for(let t in n){let i=n[t];Array.isArray(i)||(i=[i]);for(let s of t.split(" "))if(s){let r=[],o=2,l=s;for(let f=0;;){if(l=="..."&&f>0&&f+3==s.length){o=1;break}let u=/^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(l);if(!u)throw new RangeError("Invalid path: "+s);if(r.push(u[0]=="*"?"":u[0][0]=='"'?JSON.parse(u[0]):u[0]),f+=u[0].length,f==s.length)break;let d=s[f++];if(f==s.length&&d=="!"){o=0;break}if(d!="/")throw new RangeError("Invalid path: "+s);l=s.slice(f)}let a=r.length-1,h=r[a];if(!h)throw new RangeError("Invalid path: "+s);let c=new $t(i,o,a>0?r.slice(0,a):null);e[h]=c.sort(e[h])}}return jc.add(e)}var jc=new L({combine(n,e){let t,i,s;for(;n||e;){if(!n||e&&n.depth>=e.depth?(s=e,e=e.next):(s=n,n=n.next),t&&t.mode==s.mode&&!s.context&&!t.context)continue;let r=new $t(s.tags,s.mode,s.context);t?t.next=r:i=r,t=r}return i}}),$t=class{constructor(e,t,i,s){this.tags=e,this.mode=t,this.context=i,this.next=s}get opaque(){return this.mode==0}get inherit(){return this.mode==1}sort(e){return!e||e.depth{let o=s;for(let l of r)for(let a of l.set){let h=t[a.id];if(h){o=o?o+" "+h:h;break}}return o},scope:i}}function qm(n,e){let t=null;for(let i of n){let s=i.style(e);s&&(t=t?t+" "+s:s)}return t}function Uc(n,e,t,i=0,s=n.length){let r=new il(i,Array.isArray(e)?e:[e],t);r.highlightRange(n.cursor(),i,s,"",r.highlighters),r.flush(s)}var il=class{constructor(e,t,i){this.at=e,this.highlighters=t,this.span=i,this.class=""}startSpan(e,t){t!=this.class&&(this.flush(e),e>this.at&&(this.at=e),this.class=t)}flush(e){e>this.at&&this.class&&this.span(this.at,e,this.class)}highlightRange(e,t,i,s,r){let{type:o,from:l,to:a}=e;if(l>=i||a<=t)return;o.isTop&&(r=this.highlighters.filter(d=>!d.scope||d.scope(o)));let h=s,c=$m(e)||$t.empty,f=qm(r,c.tags);if(f&&(h&&(h+=" "),h+=f,c.mode==1&&(s+=(s?" ":"")+f)),this.startSpan(Math.max(t,l),h),c.opaque)return;let u=e.tree&&e.tree.prop(L.mounted);if(u&&u.overlay){let d=e.node.enter(u.overlay[0].from+l,1),p=this.highlighters.filter(g=>!g.scope||g.scope(u.tree.type)),m=e.firstChild();for(let g=0,b=l;;g++){let w=g=k||!e.nextSibling())););if(!w||k>i)break;b=w.to+l,b>t&&(this.highlightRange(d.cursor(),Math.max(t,w.from+l),Math.min(i,b),"",p),this.startSpan(Math.min(i,b),h))}m&&e.parent()}else if(e.firstChild()){u&&(s="");do if(!(e.to<=t)){if(e.from>=i)break;this.highlightRange(e,t,i,s,r),this.startSpan(Math.min(i,e.to),h)}while(e.nextSibling());e.parent()}}};function $m(n){let e=n.type.prop(jc);for(;e&&e.context&&!n.matchContext(e.context);)e=e.next;return e||null}var M=je.define,xs=M(),wt=M(),$c=M(wt),Kc=M(wt),kt=M(),ws=M(kt),tl=M(kt),nt=M(),qt=M(nt),tt=M(),it=M(),nl=M(),sn=M(nl),ks=M(),y={comment:xs,lineComment:M(xs),blockComment:M(xs),docComment:M(xs),name:wt,variableName:M(wt),typeName:$c,tagName:M($c),propertyName:Kc,attributeName:M(Kc),className:M(wt),labelName:M(wt),namespace:M(wt),macroName:M(wt),literal:kt,string:ws,docString:M(ws),character:M(ws),attributeValue:M(ws),number:tl,integer:M(tl),float:M(tl),bool:M(kt),regexp:M(kt),escape:M(kt),color:M(kt),url:M(kt),keyword:tt,self:M(tt),null:M(tt),atom:M(tt),unit:M(tt),modifier:M(tt),operatorKeyword:M(tt),controlKeyword:M(tt),definitionKeyword:M(tt),moduleKeyword:M(tt),operator:it,derefOperator:M(it),arithmeticOperator:M(it),logicOperator:M(it),bitwiseOperator:M(it),compareOperator:M(it),updateOperator:M(it),definitionOperator:M(it),typeOperator:M(it),controlOperator:M(it),punctuation:nl,separator:M(nl),bracket:sn,angleBracket:M(sn),squareBracket:M(sn),paren:M(sn),brace:M(sn),content:nt,heading:qt,heading1:M(qt),heading2:M(qt),heading3:M(qt),heading4:M(qt),heading5:M(qt),heading6:M(qt),contentSeparator:M(nt),list:M(nt),quote:M(nt),emphasis:M(nt),strong:M(nt),link:M(nt),monospace:M(nt),strikethrough:M(nt),inserted:M(),deleted:M(),changed:M(),invalid:M(),meta:ks,documentMeta:M(ks),annotation:M(ks),processingInstruction:M(ks),definition:je.defineModifier("definition"),constant:je.defineModifier("constant"),function:je.defineModifier("function"),standard:je.defineModifier("standard"),local:je.defineModifier("local"),special:je.defineModifier("special")};for(let n in y){let e=y[n];e instanceof je&&(e.name=n)}var Wy=sl([{tag:y.link,class:"tok-link"},{tag:y.heading,class:"tok-heading"},{tag:y.emphasis,class:"tok-emphasis"},{tag:y.strong,class:"tok-strong"},{tag:y.keyword,class:"tok-keyword"},{tag:y.atom,class:"tok-atom"},{tag:y.bool,class:"tok-bool"},{tag:y.url,class:"tok-url"},{tag:y.labelName,class:"tok-labelName"},{tag:y.inserted,class:"tok-inserted"},{tag:y.deleted,class:"tok-deleted"},{tag:y.literal,class:"tok-literal"},{tag:y.string,class:"tok-string"},{tag:y.number,class:"tok-number"},{tag:[y.regexp,y.escape,y.special(y.string)],class:"tok-string2"},{tag:y.variableName,class:"tok-variableName"},{tag:y.local(y.variableName),class:"tok-variableName tok-local"},{tag:y.definition(y.variableName),class:"tok-variableName tok-definition"},{tag:y.special(y.variableName),class:"tok-variableName2"},{tag:y.definition(y.propertyName),class:"tok-propertyName tok-definition"},{tag:y.typeName,class:"tok-typeName"},{tag:y.namespace,class:"tok-namespace"},{tag:y.className,class:"tok-className"},{tag:y.macroName,class:"tok-macroName"},{tag:y.propertyName,class:"tok-propertyName"},{tag:y.operator,class:"tok-operator"},{tag:y.comment,class:"tok-comment"},{tag:y.meta,class:"tok-meta"},{tag:y.invalid,class:"tok-invalid"},{tag:y.punctuation,class:"tok-punctuation"}]);var rl,xi=new L;function Km(n){return A.define({combine:n?e=>e.concat(n):void 0})}var jm=new L,Oe=class{constructor(e,t,i=[],s=""){this.data=e,this.name=s,$.prototype.hasOwnProperty("tree")||Object.defineProperty($.prototype,"tree",{get(){return se(this)}}),this.parser=t,this.extension=[vt.of(this),$.languageData.of((r,o,l)=>{let a=Gc(r,o,l),h=a.type.prop(xi);if(!h)return[];let c=r.facet(h),f=a.type.prop(jm);if(f){let u=a.resolve(o-a.from,l);for(let d of f)if(d.test(u,r)){let p=r.facet(d.facet);return d.type=="replace"?p:p.concat(c)}}return c})].concat(i)}isActiveAt(e,t,i=-1){return Gc(e,t,i).type.prop(xi)==this.data}findRegions(e){let t=e.facet(vt);if(t?.data==this.data)return[{from:0,to:e.doc.length}];if(!t||!t.allowsNesting)return[];let i=[],s=(r,o)=>{if(r.prop(xi)==this.data){i.push({from:o,to:o+r.length});return}let l=r.prop(L.mounted);if(l){if(l.tree.prop(xi)==this.data){if(l.overlay)for(let a of l.overlay)i.push({from:a.from+o,to:a.to+o});else i.push({from:o,to:o+r.length});return}else if(l.overlay){let a=i.length;if(s(l.tree,l.overlay[0].from+o),i.length>a)return}}for(let a=0;ai.isTop?t:void 0)]}),e.name)}configure(e,t){return new n(this.data,this.parser.configure(e),t||this.name)}get allowsNesting(){return this.parser.hasWrappers()}};function se(n){let e=n.field(Oe.state,!1);return e?e.tree:Z.empty}var hl=class{constructor(e){this.doc=e,this.cursorPos=0,this.string="",this.cursor=e.iter()}get length(){return this.doc.length}syncTo(e){return this.string=this.cursor.next(e-this.cursorPos).value,this.cursorPos=e+this.string.length,this.cursorPos-this.string.length}chunk(e){return this.syncTo(e),this.string}get lineChunks(){return!0}read(e,t){let i=this.cursorPos-this.string.length;return e=this.cursorPos?this.doc.sliceString(e,t):this.string.slice(e-i,t-i)}},rn=null,cl=class n{constructor(e,t,i=[],s,r,o,l,a){this.parser=e,this.state=t,this.fragments=i,this.tree=s,this.treeLen=r,this.viewport=o,this.skipped=l,this.scheduleOn=a,this.parse=null,this.tempSkipped=[]}static create(e,t,i){return new n(e,t,[],Z.empty,0,i,[],null)}startParse(){return this.parser.startParse(new hl(this.state.doc),this.fragments)}work(e,t){return t!=null&&t>=this.state.doc.length&&(t=void 0),this.tree!=Z.empty&&this.isDone(t??this.state.doc.length)?(this.takeTree(),!0):this.withContext(()=>{var i;if(typeof e=="number"){let s=Date.now()+e;e=()=>Date.now()>s}for(this.parse||(this.parse=this.startParse()),t!=null&&(this.parse.stoppedAt==null||this.parse.stoppedAt>t)&&t=this.treeLen&&((this.parse.stoppedAt==null||this.parse.stoppedAt>e)&&this.parse.stopAt(e),this.withContext(()=>{for(;!(t=this.parse.advance()););}),this.treeLen=e,this.tree=t,this.fragments=this.withoutTempSkipped(zt.addTree(this.tree,this.fragments,!0)),this.parse=null)}withContext(e){let t=rn;rn=this;try{return e()}finally{rn=t}}withoutTempSkipped(e){for(let t;t=this.tempSkipped.pop();)e=_c(e,t.from,t.to);return e}changes(e,t){let{fragments:i,tree:s,treeLen:r,viewport:o,skipped:l}=this;if(this.takeTree(),!e.empty){let a=[];if(e.iterChangedRanges((h,c,f,u)=>a.push({fromA:h,toA:c,fromB:f,toB:u})),i=zt.applyChanges(i,a),s=Z.empty,r=0,o={from:e.mapPos(o.from,-1),to:e.mapPos(o.to,1)},this.skipped.length){l=[];for(let h of this.skipped){let c=e.mapPos(h.from,1),f=e.mapPos(h.to,-1);ce.from&&(this.fragments=_c(this.fragments,s,r),this.skipped.splice(i--,1))}return this.skipped.length>=t?!1:(this.reset(),!0)}reset(){this.parse&&(this.takeTree(),this.parse=null)}skipUntilInView(e,t){this.skipped.push({from:e,to:t})}static getSkippingParser(e){return new class extends yi{createParse(t,i,s){let r=s[0].from,o=s[s.length-1].to;return{parsedPos:r,advance(){let a=rn;if(a){for(let h of s)a.tempSkipped.push(h);e&&(a.scheduleOn=a.scheduleOn?Promise.all([a.scheduleOn,e]):e)}return this.parsedPos=o,new Z(ue.none,[],[],o-r)},stoppedAt:null,stopAt(){}}}}}isDone(e){e=Math.min(e,this.state.doc.length);let t=this.fragments;return this.treeLen>=e&&t.length&&t[0].from==0&&t[0].to>=e}static get(){return rn}};function _c(n,e,t){return zt.applyChanges(n,[{fromA:e,toA:t,fromB:e,toB:t}])}var ln=class n{constructor(e){this.context=e,this.tree=e.tree}apply(e){if(!e.docChanged&&this.tree==this.context.tree)return this;let t=this.context.changes(e.changes,e.state),i=this.context.treeLen==e.startState.doc.length?void 0:Math.max(e.changes.mapPos(this.context.treeLen),t.viewport.to);return t.work(20,i)||t.takeTree(),new n(t)}static init(e){let t=Math.min(3e3,e.doc.length),i=cl.create(e.facet(vt).parser,e,{from:0,to:t});return i.work(20,t)||i.takeTree(),new n(i)}};Oe.state=X.define({create:ln.init,update(n,e){for(let t of e.effects)if(t.is(Oe.setState))return t.value;return e.startState.facet(vt)!=e.state.facet(vt)?ln.init(e.state):n.apply(e)}});var tf=n=>{let e=setTimeout(()=>n(),500);return()=>clearTimeout(e)};typeof requestIdleCallback<"u"&&(tf=n=>{let e=-1,t=setTimeout(()=>{e=requestIdleCallback(n,{timeout:400})},100);return()=>e<0?clearTimeout(t):cancelIdleCallback(e)});var ol=typeof navigator<"u"&&(!((rl=navigator.scheduling)===null||rl===void 0)&&rl.isInputPending)?()=>navigator.scheduling.isInputPending():null,Um=Y.fromClass(class{constructor(e){this.view=e,this.working=null,this.workScheduled=0,this.chunkEnd=-1,this.chunkBudget=-1,this.work=this.work.bind(this),this.scheduleWork()}update(e){let t=this.view.state.field(Oe.state).context;(t.updateViewport(e.view.viewport)||this.view.viewport.to>t.treeLen)&&this.scheduleWork(),(e.docChanged||e.selectionSet)&&(this.view.hasFocus&&(this.chunkBudget+=50),this.scheduleWork()),this.checkAsyncSchedule(t)}scheduleWork(){if(this.working)return;let{state:e}=this.view,t=e.field(Oe.state);(t.tree!=t.context.tree||!t.context.isDone(e.doc.length))&&(this.working=tf(this.work))}work(e){this.working=null;let t=Date.now();if(this.chunkEnds+1e3,a=r.context.work(()=>ol&&ol()||Date.now()>o,s+(l?0:1e5));this.chunkBudget-=Date.now()-t,(a||this.chunkBudget<=0)&&(r.context.takeTree(),this.view.dispatch({effects:Oe.setState.of(new ln(r.context))})),this.chunkBudget>0&&!(a&&!l)&&this.scheduleWork(),this.checkAsyncSchedule(r.context)}checkAsyncSchedule(e){e.scheduleOn&&(this.workScheduled++,e.scheduleOn.then(()=>this.scheduleWork()).catch(t=>ne(this.view.state,t)).then(()=>this.workScheduled--),e.scheduleOn=null)}destroy(){this.working&&this.working()}isWorking(){return!!(this.working||this.workScheduled>0)}},{eventHandlers:{focus(){this.scheduleWork()}}}),vt=A.define({combine(n){return n.length?n[0]:null},enables:n=>[Oe.state,Um,T.contentAttributes.compute([n],e=>{let t=e.facet(n);return t&&t.name?{"data-language":t.name}:{}})]}),As=class{constructor(e,t=[]){this.language=e,this.support=t,this.extension=[e,t]}};var Gm=A.define(),an=A.define({combine:n=>{if(!n.length)return" ";let e=n[0];if(!e||/\S/.test(e)||Array.from(e).some(t=>t!=e[0]))throw new Error("Invalid indent unit: "+JSON.stringify(n[0]));return e}});function hn(n){let e=n.facet(an);return e.charCodeAt(0)==9?n.tabSize*e.length:e.length}function ki(n,e){let t="",i=n.tabSize,s=n.facet(an)[0];if(s==" "){for(;e>=i;)t+=" ",e-=i;s=" "}for(let r=0;r=e?_m(n,t,e):null}var Kt=class{constructor(e,t={}){this.state=e,this.options=t,this.unit=hn(e)}lineAt(e,t=1){let i=this.state.doc.lineAt(e),{simulateBreak:s,simulateDoubleBreak:r}=this.options;return s!=null&&s>=i.from&&s<=i.to?r&&s==e?{text:"",from:e}:(t<0?s-1&&(r+=o-this.countColumn(i,i.search(/\S|$/))),r}countColumn(e,t=e.length){return lt(e,this.state.tabSize,t)}lineIndent(e,t=1){let{text:i,from:s}=this.lineAt(e,t),r=this.options.overrideIndentation;if(r){let o=r(s);if(o>-1)return o}return this.countColumn(i,i.search(/\S|$/))}get simulatedBreak(){return this.options.simulateBreak||null}},bl=new L;function _m(n,e,t){let i=e.resolveStack(t),s=e.resolveInner(t,-1).resolve(t,0).enterUnfinishedNodesBefore(t);if(s!=i.node){let r=[];for(let o=s;o&&!(o.fromi.node.to||o.from==i.node.from&&o.type==i.node.type);o=o.parent)r.push(o);for(let o=r.length-1;o>=0;o--)i={node:r[o],next:i}}return nf(i,n,t)}function nf(n,e,t){for(let i=n;i;i=i.next){let s=Xm(i.node);if(s)return s(fl.create(e,t,i))}return 0}function Ym(n){return n.pos==n.options.simulateBreak&&n.options.simulateDoubleBreak}function Xm(n){let e=n.type.prop(bl);if(e)return e;let t=n.firstChild,i;if(t&&(i=t.type.prop(L.closedBy))){let s=n.lastChild,r=s&&i.indexOf(s.name)>-1;return o=>eg(o,!0,1,void 0,r&&!Ym(o)?s.from:void 0)}return n.parent==null?Qm:null}function Qm(){return 0}var fl=class n extends Kt{constructor(e,t,i){super(e.state,e.options),this.base=e,this.pos=t,this.context=i}get node(){return this.context.node}static create(e,t,i){return new n(e,t,i)}get textAfter(){return this.textAfterPos(this.pos)}get baseIndent(){return this.baseIndentFor(this.node)}baseIndentFor(e){let t=this.state.doc.lineAt(e.from);for(;;){let i=e.resolve(t.from);for(;i.parent&&i.parent.from==i.from;)i=i.parent;if(Jm(i,e))break;t=this.state.doc.lineAt(i.from)}return this.lineIndent(t.from)}continue(){return nf(this.context.next,this.base,this.pos)}};function Jm(n,e){for(let t=e;t;t=t.parent)if(n==t)return!0;return!1}function Zm(n){let e=n.node,t=e.childAfter(e.from),i=e.lastChild;if(!t)return null;let s=n.options.simulateBreak,r=n.state.doc.lineAt(t.from),o=s==null||s<=r.from?r.to:Math.min(r.to,s);for(let l=t.to;;){let a=e.childAfter(l);if(!a||a==i)return null;if(!a.type.isSkipped){if(a.from>=o)return null;let h=/^ */.exec(r.text.slice(t.to-r.from))[0].length;return{from:t.from,to:t.to+h}}l=a.to}}function eg(n,e,t,i,s){let r=n.textAfter,o=r.match(/^\s*/)[0].length,l=i&&r.slice(o,o+i.length)==i||s==n.pos+o,a=e?Zm(n):null;return a?l?n.column(a.from):n.column(a.to):n.baseIndent+(l?0:n.unit*t)}function yl({except:n,units:e=1}={}){return t=>{let i=n&&n.test(t.textAfter);return t.baseIndent+(i?0:e*t.unit)}}var tg=200;function sf(){return $.transactionFilter.of(n=>{if(!n.docChanged||!n.isUserEvent("input.type")&&!n.isUserEvent("input.complete"))return n;let e=n.startState.languageDataAt("indentOnInput",n.startState.selection.main.head);if(!e.length)return n;let t=n.newDoc,{head:i}=n.newSelection.main,s=t.lineAt(i);if(i>s.from+tg)return n;let r=t.sliceString(s.from,i);if(!e.some(h=>h.test(r)))return n;let{state:o}=n,l=-1,a=[];for(let{head:h}of o.selection.ranges){let c=o.doc.lineAt(h);if(c.from==l)continue;l=c.from;let f=Os(o,c.from);if(f==null)continue;let u=/^\s*/.exec(c.text)[0],d=ki(o,f);u!=d&&a.push({from:c.from,to:c.from+u.length,insert:d})}return a.length?[n,{changes:a,sequential:!0}]:n})}var ig=A.define(),xl=new L;function rf(n){let e=n.firstChild,t=n.lastChild;return e&&e.tot)continue;if(r&&l.from=e&&h.to>t&&(r=h)}}return r}function sg(n){let e=n.lastChild;return e&&e.to==n.to&&e.type.isError}function Ms(n,e,t){for(let i of n.facet(ig)){let s=i(n,e,t);if(s)return s}return ng(n,e,t)}function of(n,e){let t=e.mapPos(n.from,1),i=e.mapPos(n.to,-1);return t>=i?void 0:{from:t,to:i}}var Ds=R.define({map:of}),cn=R.define({map:of});function lf(n){let e=[];for(let{head:t}of n.state.selection.ranges)e.some(i=>i.from<=t&&i.to>=t)||e.push(n.lineBlockAt(t));return e}var jt=X.define({create(){return P.none},update(n,e){e.isUserEvent("delete")&&e.changes.iterChangedRanges((t,i)=>n=Yc(n,t,i)),n=n.map(e.changes);for(let t of e.effects)if(t.is(Ds)&&!rg(n,t.value.from,t.value.to)){let{preparePlaceholder:i}=e.state.facet(wl),s=i?P.replace({widget:new ul(i(e.state,t.value))}):Xc;n=n.update({add:[s.range(t.value.from,t.value.to)]})}else t.is(cn)&&(n=n.update({filter:(i,s)=>t.value.from!=i||t.value.to!=s,filterFrom:t.value.from,filterTo:t.value.to}));return e.selection&&(n=Yc(n,e.selection.main.head)),n},provide:n=>T.decorations.from(n),toJSON(n,e){let t=[];return n.between(0,e.doc.length,(i,s)=>{t.push(i,s)}),t},fromJSON(n){if(!Array.isArray(n)||n.length%2)throw new RangeError("Invalid JSON for fold state");let e=[];for(let t=0;t{se&&(i=!0)}),i?n.update({filterFrom:e,filterTo:t,filter:(s,r)=>s>=t||r<=e}):n}function Ts(n,e,t){var i;let s=null;return(i=n.field(jt,!1))===null||i===void 0||i.between(e,t,(r,o)=>{(!s||s.from>r)&&(s={from:r,to:o})}),s}function rg(n,e,t){let i=!1;return n.between(e,e,(s,r)=>{s==e&&r==t&&(i=!0)}),i}function af(n,e){return n.field(jt,!1)?e:e.concat(R.appendConfig.of(ff()))}var og=n=>{for(let e of lf(n)){let t=Ms(n.state,e.from,e.to);if(t)return n.dispatch({effects:af(n.state,[Ds.of(t),hf(n,t)])}),!0}return!1},lg=n=>{if(!n.state.field(jt,!1))return!1;let e=[];for(let t of lf(n)){let i=Ts(n.state,t.from,t.to);i&&e.push(cn.of(i),hf(n,i,!1))}return e.length&&n.dispatch({effects:e}),e.length>0};function hf(n,e,t=!0){let i=n.state.doc.lineAt(e.from).number,s=n.state.doc.lineAt(e.to).number;return T.announce.of(`${n.state.phrase(t?"Folded lines":"Unfolded lines")} ${i} ${n.state.phrase("to")} ${s}.`)}var ag=n=>{let{state:e}=n,t=[];for(let i=0;i{let e=n.state.field(jt,!1);if(!e||!e.size)return!1;let t=[];return e.between(0,n.state.doc.length,(i,s)=>{t.push(cn.of({from:i,to:s}))}),n.dispatch({effects:t}),!0};var cf=[{key:"Ctrl-Shift-[",mac:"Cmd-Alt-[",run:og},{key:"Ctrl-Shift-]",mac:"Cmd-Alt-]",run:lg},{key:"Ctrl-Alt-[",run:ag},{key:"Ctrl-Alt-]",run:hg}],cg={placeholderDOM:null,preparePlaceholder:null,placeholderText:"\u2026"},wl=A.define({combine(n){return he(n,cg)}});function ff(n){let e=[jt,ug];return n&&e.push(wl.of(n)),e}function uf(n,e){let{state:t}=n,i=t.facet(wl),s=o=>{let l=n.lineBlockAt(n.posAtDOM(o.target)),a=Ts(n.state,l.from,l.to);a&&n.dispatch({effects:cn.of(a)}),o.preventDefault()};if(i.placeholderDOM)return i.placeholderDOM(n,s,e);let r=document.createElement("span");return r.textContent=i.placeholderText,r.setAttribute("aria-label",t.phrase("folded code")),r.title=t.phrase("unfold"),r.className="cm-foldPlaceholder",r.onclick=s,r}var Xc=P.replace({widget:new class extends xe{toDOM(n){return uf(n,null)}}}),ul=class extends xe{constructor(e){super(),this.value=e}eq(e){return this.value==e.value}toDOM(e){return uf(e,this.value)}},fg={openText:"\u2304",closedText:"\u203A",markerDOM:null,domEventHandlers:{},foldingChanged:()=>!1},on=class extends ke{constructor(e,t){super(),this.config=e,this.open=t}eq(e){return this.config==e.config&&this.open==e.open}toDOM(e){if(this.config.markerDOM)return this.config.markerDOM(this.open);let t=document.createElement("span");return t.textContent=this.open?this.config.openText:this.config.closedText,t.title=e.state.phrase(this.open?"Fold line":"Unfold line"),t}};function df(n={}){let e={...fg,...n},t=new on(e,!0),i=new on(e,!1),s=Y.fromClass(class{constructor(o){this.from=o.viewport.from,this.markers=this.buildMarkers(o)}update(o){(o.docChanged||o.viewportChanged||o.startState.facet(vt)!=o.state.facet(vt)||o.startState.field(jt,!1)!=o.state.field(jt,!1)||se(o.startState)!=se(o.state)||e.foldingChanged(o))&&(this.markers=this.buildMarkers(o.view))}buildMarkers(o){let l=new Ae;for(let a of o.viewportLineBlocks){let h=Ts(o.state,a.from,a.to)?i:Ms(o.state,a.from,a.to)?t:null;h&&l.add(a.from,a.from,h)}return l.finish()}}),{domEventHandlers:r}=e;return[s,ms({class:"cm-foldGutter",markers(o){var l;return((l=o.plugin(s))===null||l===void 0?void 0:l.markers)||F.empty},initialSpacer(){return new on(e,!1)},domEventHandlers:{...r,click:(o,l,a)=>{if(r.click&&r.click(o,l,a))return!0;let h=Ts(o.state,l.from,l.to);if(h)return o.dispatch({effects:cn.of(h)}),!0;let c=Ms(o.state,l.from,l.to);return c?(o.dispatch({effects:Ds.of(c)}),!0):!1}}}),ff()]}var ug=T.baseTheme({".cm-foldPlaceholder":{backgroundColor:"#eee",border:"1px solid #ddd",color:"#888",borderRadius:".2em",margin:"0 1px",padding:"0 1px",cursor:"pointer"},".cm-foldGutter span":{padding:"0 1px",cursor:"pointer"}}),wi=class n{constructor(e,t){this.specs=e;let i;function s(l){let a=Ie.newName();return(i||(i=Object.create(null)))["."+a]=l,a}let r=typeof t.all=="string"?t.all:t.all?s(t.all):void 0,o=t.scope;this.scope=o instanceof Oe?l=>l.prop(xi)==o.data:o?l=>l==o:void 0,this.style=sl(e.map(l=>({tag:l.tag,class:l.class||s(Object.assign({},l,{tag:null}))})),{all:r}).style,this.module=i?new Ie(i):null,this.themeType=t.themeType}static define(e,t){return new n(e,t||{})}},dl=A.define(),pf=A.define({combine(n){return n.length?[n[0]]:null}});function ll(n){let e=n.facet(dl);return e.length?e:n.facet(pf)}function fn(n,e){let t=[dg],i;return n instanceof wi&&(n.module&&t.push(T.styleModule.of(n.module)),i=n.themeType),e?.fallback?t.push(pf.of(n)):i?t.push(dl.computeN([T.darkTheme],s=>s.facet(T.darkTheme)==(i=="dark")?[n]:[])):t.push(dl.of(n)),t}var pl=class{constructor(e){this.markCache=Object.create(null),this.tree=se(e.state),this.decorations=this.buildDeco(e,ll(e.state)),this.decoratedTo=e.viewport.to}update(e){let t=se(e.state),i=ll(e.state),s=i!=ll(e.startState),{viewport:r}=e.view,o=e.changes.mapPos(this.decoratedTo,1);t.length=r.to?(this.decorations=this.decorations.map(e.changes),this.decoratedTo=o):(t!=this.tree||e.viewportChanged||s)&&(this.tree=t,this.decorations=this.buildDeco(e.view,i),this.decoratedTo=r.to)}buildDeco(e,t){if(!t||!this.tree.length)return P.none;let i=new Ae;for(let{from:s,to:r}of e.visibleRanges)Uc(this.tree,t,(o,l,a)=>{i.add(o,l,this.markCache[a]||(this.markCache[a]=P.mark({class:a})))},s,r);return i.finish()}},dg=ze.high(Y.fromClass(pl,{decorations:n=>n.decorations})),Ps=wi.define([{tag:y.meta,color:"#404740"},{tag:y.link,textDecoration:"underline"},{tag:y.heading,textDecoration:"underline",fontWeight:"bold"},{tag:y.emphasis,fontStyle:"italic"},{tag:y.strong,fontWeight:"bold"},{tag:y.strikethrough,textDecoration:"line-through"},{tag:y.keyword,color:"#708"},{tag:[y.atom,y.bool,y.url,y.contentSeparator,y.labelName],color:"#219"},{tag:[y.literal,y.inserted],color:"#164"},{tag:[y.string,y.deleted],color:"#a11"},{tag:[y.regexp,y.escape,y.special(y.string)],color:"#e40"},{tag:y.definition(y.variableName),color:"#00f"},{tag:y.local(y.variableName),color:"#30a"},{tag:[y.typeName,y.namespace],color:"#085"},{tag:y.className,color:"#167"},{tag:[y.special(y.variableName),y.macroName],color:"#256"},{tag:y.definition(y.propertyName),color:"#00c"},{tag:y.comment,color:"#940"},{tag:y.invalid,color:"#f00"}]),pg=T.baseTheme({"&.cm-focused .cm-matchingBracket":{backgroundColor:"#328c8252"},"&.cm-focused .cm-nonmatchingBracket":{backgroundColor:"#bb555544"}}),mf=1e4,gf="()[]{}",bf=A.define({combine(n){return he(n,{afterCursor:!0,brackets:gf,maxScanDistance:mf,renderMatch:bg})}}),mg=P.mark({class:"cm-matchingBracket"}),gg=P.mark({class:"cm-nonmatchingBracket"});function bg(n){let e=[],t=n.matched?mg:gg;return e.push(t.range(n.start.from,n.start.to)),n.end&&e.push(t.range(n.end.from,n.end.to)),e}function Qc(n){let e=[],t=n.facet(bf);for(let i of n.selection.ranges){if(!i.empty)continue;let s=Ue(n,i.head,-1,t)||i.head>0&&Ue(n,i.head-1,1,t)||t.afterCursor&&(Ue(n,i.head,1,t)||i.headn.decorations}),xg=[yg,pg];function yf(n={}){return[bf.of(n),xg]}var wg=new L;function ml(n,e,t){let i=n.prop(e<0?L.openedBy:L.closedBy);if(i)return i;if(n.name.length==1){let s=t.indexOf(n.name);if(s>-1&&s%2==(e<0?1:0))return[t[s+e]]}return null}function gl(n){let e=n.type.prop(wg);return e?e(n.node):n}function Ue(n,e,t,i={}){let s=i.maxScanDistance||mf,r=i.brackets||gf,o=se(n),l=o.resolveInner(e,t);for(let a=l;a;a=a.parent){let h=ml(a.type,t,r);if(h&&a.from0?e>=c.from&&ec.from&&e<=c.to))return kg(n,e,t,a,c,h,r)}}return vg(n,e,t,o,l.type,s,r)}function kg(n,e,t,i,s,r,o){let l=i.parent,a={from:s.from,to:s.to},h=0,c=l?.cursor();if(c&&(t<0?c.childBefore(i.from):c.childAfter(i.to)))do if(t<0?c.to<=i.from:c.from>=i.to){if(h==0&&r.indexOf(c.type.name)>-1&&c.from0)return null;let h={from:t<0?e-1:e,to:t>0?e+1:e},c=n.doc.iterRange(e,t>0?n.doc.length:0),f=0;for(let u=0;!c.next().done&&u<=r;){let d=c.value;t<0&&(u+=d.length);let p=e+u*t;for(let m=t>0?0:d.length-1,g=t>0?d.length:-1;m!=g;m+=t){let b=o.indexOf(d[m]);if(!(b<0||i.resolveInner(p+m,1).type!=s))if(b%2==0==t>0)f++;else{if(f==1)return{start:h,end:{from:p+m,to:p+m+1},matched:b>>1==a>>1};f--}}t>0&&(u+=d.length)}return c.done?{start:h,matched:!1}:null}var Sg=Object.create(null),Jc=[ue.none];var Zc=[],ef=Object.create(null),Cg=Object.create(null);for(let[n,e]of[["variable","variableName"],["variable-2","variableName.special"],["string-2","string.special"],["def","variableName.definition"],["tag","tagName"],["attribute","attributeName"],["type","typeName"],["builtin","variableName.standard"],["qualifier","modifier"],["error","invalid"],["header","heading"],["property","propertyName"]])Cg[n]=Ag(Sg,e);function al(n,e){Zc.indexOf(n)>-1||(Zc.push(n),console.warn(e))}function Ag(n,e){let t=[];for(let l of e.split(" ")){let a=[];for(let h of l.split(".")){let c=n[h]||y[h];c?typeof c=="function"?a.length?a=a.map(c):al(h,`Modifier ${h} used at start of tag`):a.length?al(h,`Tag ${h} used as modifier`):a=Array.isArray(c)?c:[c]:al(h,`Unknown highlighting tag ${h}`)}for(let h of a)t.push(h)}if(!t.length)return 0;let i=e.replace(/ /g,"_"),s=i+" "+t.map(l=>l.id),r=ef[s];if(r)return r.id;let o=ef[s]=ue.define({id:Jc.length,name:i,props:[Ss({[i]:t})]});return Jc.push(o),o.id}var Uy={rtl:P.mark({class:"cm-iso",inclusive:!0,attributes:{dir:"rtl"},bidiIsolate:z.RTL}),ltr:P.mark({class:"cm-iso",inclusive:!0,attributes:{dir:"ltr"},bidiIsolate:z.LTR}),auto:P.mark({class:"cm-iso",inclusive:!0,attributes:{dir:"auto"},bidiIsolate:null})};var Mg=n=>{let{state:e}=n,t=e.doc.lineAt(e.selection.main.from),i=Tl(n.state,t.from);return i.line?Tg(n):i.block?Dg(n):!1};function Ml(n,e){return({state:t,dispatch:i})=>{if(t.readOnly)return!1;let s=n(e,t);return s?(i(t.update(s)),!0):!1}}var Tg=Ml(Rg,0);var Og=Ml(Tf,0);var Dg=Ml((n,e)=>Tf(n,e,Bg(e)),0);function Tl(n,e){let t=n.languageDataAt("commentTokens",e,1);return t.length?t[0]:{}}var un=50;function Pg(n,{open:e,close:t},i,s){let r=n.sliceDoc(i-un,i),o=n.sliceDoc(s,s+un),l=/\s*$/.exec(r)[0].length,a=/^\s*/.exec(o)[0].length,h=r.length-l;if(r.slice(h-e.length,h)==e&&o.slice(a,a+t.length)==t)return{open:{pos:i-l,margin:l&&1},close:{pos:s+a,margin:a&&1}};let c,f;s-i<=2*un?c=f=n.sliceDoc(i,s):(c=n.sliceDoc(i,i+un),f=n.sliceDoc(s-un,s));let u=/^\s*/.exec(c)[0].length,d=/\s*$/.exec(f)[0].length,p=f.length-d-t.length;return c.slice(u,u+e.length)==e&&f.slice(p,p+t.length)==t?{open:{pos:i+u+e.length,margin:/\s/.test(c.charAt(u+e.length))?1:0},close:{pos:s-d-t.length,margin:/\s/.test(f.charAt(p-1))?1:0}}:null}function Bg(n){let e=[];for(let t of n.selection.ranges){let i=n.doc.lineAt(t.from),s=t.to<=i.to?i:n.doc.lineAt(t.to);s.from>i.from&&s.from==t.to&&(s=t.to==i.to+1?i:n.doc.lineAt(t.to-1));let r=e.length-1;r>=0&&e[r].to>i.from?e[r].to=s.to:e.push({from:i.from+/^\s*/.exec(i.text)[0].length,to:s.to})}return e}function Tf(n,e,t=e.selection.ranges){let i=t.map(r=>Tl(e,r.from).block);if(!i.every(r=>r))return null;let s=t.map((r,o)=>Pg(e,i[o],r.from,r.to));if(n!=2&&!s.every(r=>r))return{changes:e.changes(t.map((r,o)=>s[o]?[]:[{from:r.from,insert:i[o].open+" "},{from:r.to,insert:" "+i[o].close}]))};if(n!=1&&s.some(r=>r)){let r=[];for(let o=0,l;os&&(r==o||o>f.from)){s=f.from;let u=/^\s*/.exec(f.text)[0].length,d=u==f.length,p=f.text.slice(u,u+h.length)==h?u:-1;ur.comment<0&&(!r.empty||r.single))){let r=[];for(let{line:l,token:a,indent:h,empty:c,single:f}of i)(f||!c)&&r.push({from:l.from+h,insert:a+" "});let o=e.changes(r);return{changes:o,selection:e.selection.map(o,1)}}else if(n!=1&&i.some(r=>r.comment>=0)){let r=[];for(let{line:o,comment:l,token:a}of i)if(l>=0){let h=o.from+l,c=h+a.length;o.text[c-o.from]==" "&&c++,r.push({from:h,to:c})}return{changes:r}}return null}var vl=be.define(),Lg=be.define(),Eg=A.define(),Of=A.define({combine(n){return he(n,{minDepth:100,newGroupDelay:500,joinToEvent:(e,t)=>t},{minDepth:Math.max,newGroupDelay:Math.min,joinToEvent:(e,t)=>(i,s)=>e(i,s)||t(i,s)})}}),Df=X.define({create(){return Ut.empty},update(n,e){let t=e.state.facet(Of),i=e.annotation(vl);if(i){let a=Ge.fromTransaction(e,i.selection),h=i.side,c=h==0?n.undone:n.done;return a?c=Rs(c,c.length,t.minDepth,a):c=Lf(c,e.startState.selection),new Ut(h==0?i.rest:c,h==0?c:i.rest)}let s=e.annotation(Lg);if((s=="full"||s=="before")&&(n=n.isolate()),e.annotation(ie.addToHistory)===!1)return e.changes.empty?n:n.addMapping(e.changes.desc);let r=Ge.fromTransaction(e),o=e.annotation(ie.time),l=e.annotation(ie.userEvent);return r?n=n.addChanges(r,o,l,t,e):e.selection&&(n=n.addSelection(e.startState.selection,o,l,t.newGroupDelay)),(s=="full"||s=="after")&&(n=n.isolate()),n},toJSON(n){return{done:n.done.map(e=>e.toJSON()),undone:n.undone.map(e=>e.toJSON())}},fromJSON(n){return new Ut(n.done.map(Ge.fromJSON),n.undone.map(Ge.fromJSON))}});function Pf(n={}){return[Df,Of.of(n),T.domEventHandlers({beforeinput(e,t){let i=e.inputType=="historyUndo"?Bf:e.inputType=="historyRedo"?Sl:null;return i?(e.preventDefault(),i(t)):!1}})]}function Ls(n,e){return function({state:t,dispatch:i}){if(!e&&t.readOnly)return!1;let s=t.field(Df,!1);if(!s)return!1;let r=s.pop(n,t,e);return r?(i(r),!0):!1}}var Bf=Ls(0,!1),Sl=Ls(1,!1),Ig=Ls(0,!0),Ng=Ls(1,!0);var Ge=class n{constructor(e,t,i,s,r){this.changes=e,this.effects=t,this.mapped=i,this.startSelection=s,this.selectionsAfter=r}setSelAfter(e){return new n(this.changes,this.effects,this.mapped,this.startSelection,e)}toJSON(){var e,t,i;return{changes:(e=this.changes)===null||e===void 0?void 0:e.toJSON(),mapped:(t=this.mapped)===null||t===void 0?void 0:t.toJSON(),startSelection:(i=this.startSelection)===null||i===void 0?void 0:i.toJSON(),selectionsAfter:this.selectionsAfter.map(s=>s.toJSON())}}static fromJSON(e){return new n(e.changes&&me.fromJSON(e.changes),[],e.mapped&&ot.fromJSON(e.mapped),e.startSelection&&x.fromJSON(e.startSelection),e.selectionsAfter.map(x.fromJSON))}static fromTransaction(e,t){let i=He;for(let s of e.startState.facet(Eg)){let r=s(e);r.length&&(i=i.concat(r))}return!i.length&&e.changes.empty?null:new n(e.changes.invert(e.startState.doc),i,void 0,t||e.startState.selection,He)}static selection(e){return new n(void 0,He,void 0,void 0,e)}};function Rs(n,e,t,i){let s=e+1>t+20?e-t-1:0,r=n.slice(s,e);return r.push(i),r}function Fg(n,e){let t=[],i=!1;return n.iterChangedRanges((s,r)=>t.push(s,r)),e.iterChangedRanges((s,r,o,l)=>{for(let a=0;a=h&&o<=c&&(i=!0)}}),i}function Wg(n,e){return n.ranges.length==e.ranges.length&&n.ranges.filter((t,i)=>t.empty!=e.ranges[i].empty).length===0}function Rf(n,e){return n.length?e.length?n.concat(e):n:e}var He=[],Hg=200;function Lf(n,e){if(n.length){let t=n[n.length-1],i=t.selectionsAfter.slice(Math.max(0,t.selectionsAfter.length-Hg));return i.length&&i[i.length-1].eq(e)?n:(i.push(e),Rs(n,n.length-1,1e9,t.setSelAfter(i)))}else return[Ge.selection([e])]}function Vg(n){let e=n[n.length-1],t=n.slice();return t[n.length-1]=e.setSelAfter(e.selectionsAfter.slice(0,e.selectionsAfter.length-1)),t}function kl(n,e){if(!n.length)return n;let t=n.length,i=He;for(;t;){let s=zg(n[t-1],e,i);if(s.changes&&!s.changes.empty||s.effects.length){let r=n.slice(0,t);return r[t-1]=s,r}else e=s.mapped,t--,i=s.selectionsAfter}return i.length?[Ge.selection(i)]:He}function zg(n,e,t){let i=Rf(n.selectionsAfter.length?n.selectionsAfter.map(l=>l.map(e)):He,t);if(!n.changes)return Ge.selection(i);let s=n.changes.map(e),r=e.mapDesc(n.changes,!0),o=n.mapped?n.mapped.composeDesc(r):r;return new Ge(s,R.mapEffects(n.effects,e),o,n.startSelection.map(r),i)}var qg=/^(input\.type|delete)($|\.)/,Ut=class n{constructor(e,t,i=0,s=void 0){this.done=e,this.undone=t,this.prevTime=i,this.prevUserEvent=s}isolate(){return this.prevTime?new n(this.done,this.undone):this}addChanges(e,t,i,s,r){let o=this.done,l=o[o.length-1];return l&&l.changes&&!l.changes.empty&&e.changes&&(!i||qg.test(i))&&(!l.selectionsAfter.length&&t-this.prevTime0&&t-this.prevTimet.empty?n.moveByChar(t,e):Es(t,e))}function de(n){return n.textDirectionAt(n.state.selection.main.head)==z.LTR}var Nf=n=>If(n,!de(n)),Ff=n=>If(n,de(n));function Wf(n,e){return Ye(n,t=>t.empty?n.moveByGroup(t,e):Es(t,e))}var $g=n=>Wf(n,!de(n)),Kg=n=>Wf(n,de(n));var i1=typeof Intl<"u"&&Intl.Segmenter?new Intl.Segmenter(void 0,{granularity:"word"}):null;function jg(n,e,t){if(e.type.prop(t))return!0;let i=e.to-e.from;return i&&(i>2||/[^\s,.;:]/.test(n.sliceDoc(e.from,e.to)))||e.firstChild}function Is(n,e,t){let i=se(n).resolveInner(e.head),s=t?L.closedBy:L.openedBy;for(let a=e.head;;){let h=t?i.childAfter(a):i.childBefore(a);if(!h)break;jg(n,h,s)?i=h:a=t?h.to:h.from}let r=i.type.prop(s),o,l;return r&&(o=t?Ue(n,i.from,1):Ue(n,i.to,-1))&&o.matched?l=t?o.end.to:o.end.from:l=t?i.to:i.from,x.cursor(l,t?-1:1)}var Ug=n=>Ye(n,e=>Is(n.state,e,!de(n))),Gg=n=>Ye(n,e=>Is(n.state,e,de(n)));function Hf(n,e){return Ye(n,t=>{if(!t.empty)return Es(t,e);let i=n.moveVertically(t,e);return i.head!=t.head?i:n.moveToLineBoundary(t,e)})}var Vf=n=>Hf(n,!1),zf=n=>Hf(n,!0);function qf(n){let e=n.scrollDOM.clientHeighto.empty?n.moveVertically(o,e,t.height):Es(o,e));if(s.eq(i.selection))return!1;let r;if(t.selfScroll){let o=n.coordsAtPos(i.selection.main.head),l=n.scrollDOM.getBoundingClientRect(),a=l.top+t.marginTop,h=l.bottom-t.marginBottom;o&&o.top>a&&o.bottom$f(n,!1),Cl=n=>$f(n,!0);function St(n,e,t){let i=n.lineBlockAt(e.head),s=n.moveToLineBoundary(e,t);if(s.head==e.head&&s.head!=(t?i.to:i.from)&&(s=n.moveToLineBoundary(e,t,!1)),!t&&s.head==i.from&&i.length){let r=/^\s*/.exec(n.state.sliceDoc(i.from,Math.min(i.from+100,i.to)))[0].length;r&&e.head!=i.from+r&&(s=x.cursor(i.from+r))}return s}var _g=n=>Ye(n,e=>St(n,e,!0)),Yg=n=>Ye(n,e=>St(n,e,!1)),Xg=n=>Ye(n,e=>St(n,e,!de(n))),Qg=n=>Ye(n,e=>St(n,e,de(n))),Jg=n=>Ye(n,e=>x.cursor(n.lineBlockAt(e.head).from,1)),Zg=n=>Ye(n,e=>x.cursor(n.lineBlockAt(e.head).to,-1));function e0(n,e,t){let i=!1,s=vi(n.selection,r=>{let o=Ue(n,r.head,-1)||Ue(n,r.head,1)||r.head>0&&Ue(n,r.head-1,1)||r.heade0(n,e,!1);function Ve(n,e){let t=vi(n.state.selection,i=>{let s=e(i);return x.range(i.anchor,s.head,s.goalColumn,s.bidiLevel||void 0,s.assoc)});return t.eq(n.state.selection)?!1:(n.dispatch(_e(n.state,t)),!0)}function Kf(n,e){return Ve(n,t=>n.moveByChar(t,e))}var jf=n=>Kf(n,!de(n)),Uf=n=>Kf(n,de(n));function Gf(n,e){return Ve(n,t=>n.moveByGroup(t,e))}var i0=n=>Gf(n,!de(n)),n0=n=>Gf(n,de(n));var s0=n=>Ve(n,e=>Is(n.state,e,!de(n))),r0=n=>Ve(n,e=>Is(n.state,e,de(n)));function _f(n,e){return Ve(n,t=>n.moveVertically(t,e))}var Yf=n=>_f(n,!1),Xf=n=>_f(n,!0);function Qf(n,e){return Ve(n,t=>n.moveVertically(t,e,qf(n).height))}var wf=n=>Qf(n,!1),kf=n=>Qf(n,!0),o0=n=>Ve(n,e=>St(n,e,!0)),l0=n=>Ve(n,e=>St(n,e,!1)),a0=n=>Ve(n,e=>St(n,e,!de(n))),h0=n=>Ve(n,e=>St(n,e,de(n))),c0=n=>Ve(n,e=>x.cursor(n.lineBlockAt(e.head).from)),f0=n=>Ve(n,e=>x.cursor(n.lineBlockAt(e.head).to)),vf=({state:n,dispatch:e})=>(e(_e(n,{anchor:0})),!0),Sf=({state:n,dispatch:e})=>(e(_e(n,{anchor:n.doc.length})),!0),Cf=({state:n,dispatch:e})=>(e(_e(n,{anchor:n.selection.main.anchor,head:0})),!0),Af=({state:n,dispatch:e})=>(e(_e(n,{anchor:n.selection.main.anchor,head:n.doc.length})),!0),u0=({state:n,dispatch:e})=>(e(n.update({selection:{anchor:0,head:n.doc.length},userEvent:"select"})),!0),d0=({state:n,dispatch:e})=>{let t=Ns(n).map(({from:i,to:s})=>x.range(i,Math.min(s+1,n.doc.length)));return e(n.update({selection:x.create(t),userEvent:"select"})),!0},p0=({state:n,dispatch:e})=>{let t=vi(n.selection,i=>{let s=se(n),r=s.resolveStack(i.from,1);if(i.empty){let o=s.resolveStack(i.from,-1);o.node.from>=r.node.from&&o.node.to<=r.node.to&&(r=o)}for(let o=r;o;o=o.next){let{node:l}=o;if((l.from=i.to||l.to>i.to&&l.from<=i.from)&&o.next)return x.range(l.to,l.from)}return i});return t.eq(n.selection)?!1:(e(_e(n,t)),!0)};function Jf(n,e){let{state:t}=n,i=t.selection,s=t.selection.ranges.slice();for(let r of t.selection.ranges){let o=t.doc.lineAt(r.head);if(e?o.to0)for(let l=r;;){let a=n.moveVertically(l,e);if(a.heado.to){s.some(h=>h.head==a.head)||s.push(a);break}else{if(a.head==l.head)break;l=a}}}return s.length==i.ranges.length?!1:(n.dispatch(_e(t,x.create(s,s.length-1))),!0)}var m0=n=>Jf(n,!1),g0=n=>Jf(n,!0),b0=({state:n,dispatch:e})=>{let t=n.selection,i=null;return t.ranges.length>1?i=x.create([t.main]):t.main.empty||(i=x.create([x.cursor(t.main.head)])),i?(e(_e(n,i)),!0):!1};function dn(n,e){if(n.state.readOnly)return!1;let t="delete.selection",{state:i}=n,s=i.changeByRange(r=>{let{from:o,to:l}=r;if(o==l){let a=e(r);ao&&(t="delete.forward",a=Bs(n,a,!0)),o=Math.min(o,a),l=Math.max(l,a)}else o=Bs(n,o,!1),l=Bs(n,l,!0);return o==l?{range:r}:{changes:{from:o,to:l},range:x.cursor(o,os(n)))i.between(e,e,(s,r)=>{se&&(e=t?r:s)});return e}var Zf=(n,e,t)=>dn(n,i=>{let s=i.from,{state:r}=n,o=r.doc.lineAt(s),l,a;if(t&&!e&&s>o.from&&sZf(n,!1,!0);var eu=n=>Zf(n,!0,!1),tu=(n,e)=>dn(n,t=>{let i=t.head,{state:s}=n,r=s.doc.lineAt(i),o=s.charCategorizer(i);for(let l=null;;){if(i==(e?r.to:r.from)){i==t.head&&r.number!=(e?s.doc.lines:1)&&(i+=e?1:-1);break}let a=ee(r.text,i-r.from,e)+r.from,h=r.text.slice(Math.min(i,a)-r.from,Math.max(i,a)-r.from),c=o(h);if(l!=null&&c!=l)break;(h!=" "||i!=t.head)&&(l=c),i=a}return i}),iu=n=>tu(n,!1),y0=n=>tu(n,!0);var x0=n=>dn(n,e=>{let t=n.lineBlockAt(e.head).to;return e.headdn(n,e=>{let t=n.moveToLineBoundary(e,!1).head;return e.head>t?t:Math.max(0,e.head-1)}),k0=n=>dn(n,e=>{let t=n.moveToLineBoundary(e,!0).head;return e.head{if(n.readOnly)return!1;let t=n.changeByRange(i=>({changes:{from:i.from,to:i.to,insert:N.of(["",""])},range:x.cursor(i.from)}));return e(n.update(t,{scrollIntoView:!0,userEvent:"input"})),!0},S0=({state:n,dispatch:e})=>{if(n.readOnly)return!1;let t=n.changeByRange(i=>{if(!i.empty||i.from==0||i.from==n.doc.length)return{range:i};let s=i.from,r=n.doc.lineAt(s),o=s==r.from?s-1:ee(r.text,s-r.from,!1)+r.from,l=s==r.to?s+1:ee(r.text,s-r.from,!0)+r.from;return{changes:{from:o,to:l,insert:n.doc.slice(s,l).append(n.doc.slice(o,s))},range:x.cursor(l)}});return t.changes.empty?!1:(e(n.update(t,{scrollIntoView:!0,userEvent:"move.character"})),!0)};function Ns(n){let e=[],t=-1;for(let i of n.selection.ranges){let s=n.doc.lineAt(i.from),r=n.doc.lineAt(i.to);if(!i.empty&&i.to==r.from&&(r=n.doc.lineAt(i.to-1)),t>=s.number){let o=e[e.length-1];o.to=r.to,o.ranges.push(i)}else e.push({from:s.from,to:r.to,ranges:[i]});t=r.number+1}return e}function nu(n,e,t){if(n.readOnly)return!1;let i=[],s=[];for(let r of Ns(n)){if(t?r.to==n.doc.length:r.from==0)continue;let o=n.doc.lineAt(t?r.to+1:r.from-1),l=o.length+1;if(t){i.push({from:r.to,to:o.to},{from:r.from,insert:o.text+n.lineBreak});for(let a of r.ranges)s.push(x.range(Math.min(n.doc.length,a.anchor+l),Math.min(n.doc.length,a.head+l)))}else{i.push({from:o.from,to:r.from},{from:r.to,insert:n.lineBreak+o.text});for(let a of r.ranges)s.push(x.range(a.anchor-l,a.head-l))}}return i.length?(e(n.update({changes:i,scrollIntoView:!0,selection:x.create(s,n.selection.mainIndex),userEvent:"move.line"})),!0):!1}var C0=({state:n,dispatch:e})=>nu(n,e,!1),A0=({state:n,dispatch:e})=>nu(n,e,!0);function su(n,e,t){if(n.readOnly)return!1;let i=[];for(let r of Ns(n))t?i.push({from:r.from,insert:n.doc.slice(r.from,r.to)+n.lineBreak}):i.push({from:r.to,insert:n.lineBreak+n.doc.slice(r.from,r.to)});let s=n.changes(i);return e(n.update({changes:s,selection:n.selection.map(s,t?1:-1),scrollIntoView:!0,userEvent:"input.copyline"})),!0}var M0=({state:n,dispatch:e})=>su(n,e,!1),T0=({state:n,dispatch:e})=>su(n,e,!0),O0=n=>{if(n.state.readOnly)return!1;let{state:e}=n,t=e.changes(Ns(e).map(({from:s,to:r})=>(s>0?s--:r{let r;if(n.lineWrapping){let o=n.lineBlockAt(s.head),l=n.coordsAtPos(s.head,s.assoc||1);l&&(r=o.bottom+n.documentTop-l.bottom+n.defaultLineHeight/2)}return n.moveVertically(s,!0,r)}).map(t);return n.dispatch({changes:t,selection:i,scrollIntoView:!0,userEvent:"delete.line"}),!0};function D0(n,e){if(/\(\)|\[\]|\{\}/.test(n.sliceDoc(e-1,e+1)))return{from:e,to:e};let t=se(n).resolveInner(e),i=t.childBefore(e),s=t.childAfter(e),r;return i&&s&&i.to<=e&&s.from>=e&&(r=i.type.prop(L.closedBy))&&r.indexOf(s.name)>-1&&n.doc.lineAt(i.to).from==n.doc.lineAt(s.from).from&&!/\S/.test(n.sliceDoc(i.to,s.from))?{from:i.to,to:s.from}:null}var Mf=ru(!1),P0=ru(!0);function ru(n){return({state:e,dispatch:t})=>{if(e.readOnly)return!1;let i=e.changeByRange(s=>{let{from:r,to:o}=s,l=e.doc.lineAt(r),a=!n&&r==o&&D0(e,r);n&&(r=o=(o<=l.to?l:e.doc.lineAt(o)).to);let h=new Kt(e,{simulateBreak:r,simulateDoubleBreak:!!a}),c=Os(h,r);for(c==null&&(c=lt(/^\s*/.exec(e.doc.lineAt(r).text)[0],e.tabSize));ol.from&&r{let s=[];for(let o=i.from;o<=i.to;){let l=n.doc.lineAt(o);l.number>t&&(i.empty||i.to>l.from)&&(e(l,s,i),t=l.number),o=l.to+1}let r=n.changes(s);return{changes:s,range:x.range(r.mapPos(i.anchor,1),r.mapPos(i.head,1))}})}var B0=({state:n,dispatch:e})=>{if(n.readOnly)return!1;let t=Object.create(null),i=new Kt(n,{overrideIndentation:r=>{let o=t[r];return o??-1}}),s=Ol(n,(r,o,l)=>{let a=Os(i,r.from);if(a==null)return;/\S/.test(r.text)||(a=0);let h=/^\s*/.exec(r.text)[0],c=ki(n,a);(h!=c||l.fromn.readOnly?!1:(e(n.update(Ol(n,(t,i)=>{i.push({from:t.from,insert:n.facet(an)})}),{userEvent:"input.indent"})),!0),L0=({state:n,dispatch:e})=>n.readOnly?!1:(e(n.update(Ol(n,(t,i)=>{let s=/^\s*/.exec(t.text)[0];if(!s)return;let r=lt(s,n.tabSize),o=0,l=ki(n,Math.max(0,r-hn(n)));for(;o(n.setTabFocusMode(),!0);var I0=[{key:"Ctrl-b",run:Nf,shift:jf,preventDefault:!0},{key:"Ctrl-f",run:Ff,shift:Uf},{key:"Ctrl-p",run:Vf,shift:Yf},{key:"Ctrl-n",run:zf,shift:Xf},{key:"Ctrl-a",run:Jg,shift:c0},{key:"Ctrl-e",run:Zg,shift:f0},{key:"Ctrl-d",run:eu},{key:"Ctrl-h",run:Al},{key:"Ctrl-k",run:x0},{key:"Ctrl-Alt-h",run:iu},{key:"Ctrl-o",run:v0},{key:"Ctrl-t",run:S0},{key:"Ctrl-v",run:Cl}],N0=[{key:"ArrowLeft",run:Nf,shift:jf,preventDefault:!0},{key:"Mod-ArrowLeft",mac:"Alt-ArrowLeft",run:$g,shift:i0,preventDefault:!0},{mac:"Cmd-ArrowLeft",run:Xg,shift:a0,preventDefault:!0},{key:"ArrowRight",run:Ff,shift:Uf,preventDefault:!0},{key:"Mod-ArrowRight",mac:"Alt-ArrowRight",run:Kg,shift:n0,preventDefault:!0},{mac:"Cmd-ArrowRight",run:Qg,shift:h0,preventDefault:!0},{key:"ArrowUp",run:Vf,shift:Yf,preventDefault:!0},{mac:"Cmd-ArrowUp",run:vf,shift:Cf},{mac:"Ctrl-ArrowUp",run:xf,shift:wf},{key:"ArrowDown",run:zf,shift:Xf,preventDefault:!0},{mac:"Cmd-ArrowDown",run:Sf,shift:Af},{mac:"Ctrl-ArrowDown",run:Cl,shift:kf},{key:"PageUp",run:xf,shift:wf},{key:"PageDown",run:Cl,shift:kf},{key:"Home",run:Yg,shift:l0,preventDefault:!0},{key:"Mod-Home",run:vf,shift:Cf},{key:"End",run:_g,shift:o0,preventDefault:!0},{key:"Mod-End",run:Sf,shift:Af},{key:"Enter",run:Mf,shift:Mf},{key:"Mod-a",run:u0},{key:"Backspace",run:Al,shift:Al,preventDefault:!0},{key:"Delete",run:eu,preventDefault:!0},{key:"Mod-Backspace",mac:"Alt-Backspace",run:iu,preventDefault:!0},{key:"Mod-Delete",mac:"Alt-Delete",run:y0,preventDefault:!0},{mac:"Mod-Backspace",run:w0,preventDefault:!0},{mac:"Mod-Delete",run:k0,preventDefault:!0}].concat(I0.map(n=>({mac:n.key,run:n.run,shift:n.shift}))),ou=[{key:"Alt-ArrowLeft",mac:"Ctrl-ArrowLeft",run:Ug,shift:s0},{key:"Alt-ArrowRight",mac:"Ctrl-ArrowRight",run:Gg,shift:r0},{key:"Alt-ArrowUp",run:C0},{key:"Shift-Alt-ArrowUp",run:M0},{key:"Alt-ArrowDown",run:A0},{key:"Shift-Alt-ArrowDown",run:T0},{key:"Mod-Alt-ArrowUp",run:m0},{key:"Mod-Alt-ArrowDown",run:g0},{key:"Escape",run:b0},{key:"Mod-Enter",run:P0},{key:"Alt-l",mac:"Ctrl-l",run:d0},{key:"Mod-i",run:p0,preventDefault:!0},{key:"Mod-[",run:L0},{key:"Mod-]",run:R0},{key:"Mod-Alt-\\",run:B0},{key:"Shift-Mod-k",run:O0},{key:"Shift-Mod-\\",run:t0},{key:"Mod-/",run:Mg},{key:"Alt-A",run:Og},{key:"Ctrl-m",mac:"Shift-Alt-m",run:E0}].concat(N0);var lu=typeof String.prototype.normalize=="function"?n=>n.normalize("NFKD"):n=>n,At=class{constructor(e,t,i=0,s=e.length,r,o){this.test=o,this.value={from:0,to:0,precise:!1},this.done=!1,this.matches=[],this.buffer="",this.bufferPos=0,this.iter=e.iterRange(i,s),this.bufferStart=i,this.normalize=r?l=>r(lu(l)):lu,this.query=this.normalize(t)}peek(){if(this.bufferPos==this.buffer.length){if(this.bufferStart+=this.buffer.length,this.iter.next(),this.iter.done)return-1;this.bufferPos=0,this.buffer=this.iter.value}return ae(this.buffer,this.bufferPos)}next(){for(;this.matches.length;)this.matches.pop();return this.nextOverlapping()}nextOverlapping(){for(;;){let e=this.peek();if(e<0)return this.done=!0,this;let t=Ri(e),i=this.bufferStart+this.bufferPos;this.bufferPos+=Me(e);let s=this.normalize(t);if(s.length)for(let r=0,o=i,l=!0;;r++){let a=s.charCodeAt(r),h=this.match(a,o,l,this.bufferPos+this.bufferStart,r==s.length-1);if(h)return this.value=h,this;if(r==s.length-1)break;l&&rthis.to&&(this.curLine=this.curLine.slice(0,this.to-this.curLineStart)),this.iter.next())}nextLine(){this.curLineStart=this.curLineStart+this.curLine.length+1,this.curLineStart>this.to?this.curLine="":this.getLine(0)}next(){for(let e=this.matchPos-this.curLineStart;;){this.re.lastIndex=e;let t=this.matchPos<=this.to&&this.re.exec(this.curLine);if(t){let i=this.curLineStart+t.index,s=i+t[0].length;if(this.matchPos=qs(this.text,s+(i==s?1:0)),i==this.curLineStart+this.curLine.length&&this.nextLine(),(ithis.value.to)&&(!this.test||this.test(i,s,t)))return this.value={from:i,to:s,precise:!0,match:t},this;e=this.matchPos-this.curLineStart}else if(this.curLineStart+this.curLine.length=i||s.to<=t){let l=new n(t,e.sliceString(t,i));return Dl.set(e,l),l}if(s.from==t&&s.to==i)return s;let{text:r,from:o}=s;return o>t&&(r=e.sliceString(t,o)+r,o=t),s.to=this.to?this.to:this.text.lineAt(e).to}next(){for(;;){let e=this.re.lastIndex=this.matchPos-this.flat.from,t=this.re.exec(this.flat.text);if(t&&!t[0]&&t.index==e&&(this.re.lastIndex=e+1,t=this.re.exec(this.flat.text)),t){let i=this.flat.from+t.index,s=i+t[0].length;if((this.flat.to>=this.to||t.index+t[0].length<=this.flat.text.length-10)&&(!this.test||this.test(i,s,t)))return this.value={from:i,to:s,precise:!0,match:t},this.matchPos=qs(this.text,s+(i==s?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=Vs.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}};typeof Symbol<"u"&&(Hs.prototype[Symbol.iterator]=zs.prototype[Symbol.iterator]=function(){return this});function F0(n){try{return new RegExp(n,El),!0}catch{return!1}}function qs(n,e){if(e>=n.length)return e;let t=n.lineAt(e),i;for(;e=56320&&i<57344;)e++;return e}var W0=n=>{let{state:e}=n,t=String(e.doc.lineAt(n.state.selection.main.head).number),{close:i,result:s}=Rc(n,{label:e.phrase("Go to line"),input:{type:"text",name:"line",value:t},focus:!0,submitLabel:e.phrase("go")});return s.then(r=>{let o=r&&/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(r.elements.line.value);if(!o){n.dispatch({effects:i});return}let l=e.doc.lineAt(e.selection.main.head),[,a,h,c,f]=o,u=c?+c.slice(1):0,d=h?+h:l.number;if(h&&f){let g=d/100;a&&(g=g*(a=="-"?-1:1)+l.number/e.doc.lines),d=Math.round(e.doc.lines*g)}else h&&a&&(d=d*(a=="-"?-1:1)+l.number);let p=e.doc.line(Math.max(1,Math.min(e.doc.lines,d))),m=x.cursor(p.from+Math.max(0,Math.min(u,p.length)));n.dispatch({effects:[i,T.scrollIntoView(m.from,{y:"center"})],selection:m})}),!0},H0={highlightWordAroundCursor:!1,minSelectionLength:1,maxMatches:100,wholeWords:!1},fu=A.define({combine(n){return he(n,H0,{highlightWordAroundCursor:(e,t)=>e||t,minSelectionLength:Math.min,maxMatches:Math.min})}});function uu(n){let e=[K0,$0];return n&&e.push(fu.of(n)),e}var V0=P.mark({class:"cm-selectionMatch"}),z0=P.mark({class:"cm-selectionMatch cm-selectionMatch-main"});function au(n,e,t,i){return(t==0||n(e.sliceDoc(t-1,t))!=K.Word)&&(i==e.doc.length||n(e.sliceDoc(i,i+1))!=K.Word)}function q0(n,e,t,i){return n(e.sliceDoc(t,t+1))==K.Word&&n(e.sliceDoc(i-1,i))==K.Word}var $0=Y.fromClass(class{constructor(n){this.decorations=this.getDeco(n)}update(n){(n.selectionSet||n.docChanged||n.viewportChanged)&&(this.decorations=this.getDeco(n.view))}getDeco(n){let e=n.state.facet(fu),{state:t}=n,i=t.selection;if(i.ranges.length>1)return P.none;let s=i.main,r,o=null;if(s.empty){if(!e.highlightWordAroundCursor)return P.none;let a=t.wordAt(s.head);if(!a)return P.none;o=t.charCategorizer(s.head),r=t.sliceDoc(a.from,a.to)}else{let a=s.to-s.from;if(a200)return P.none;if(e.wholeWords){if(r=t.sliceDoc(s.from,s.to),o=t.charCategorizer(s.head),!(au(o,t,s.from,s.to)&&q0(o,t,s.from,s.to)))return P.none}else if(r=t.sliceDoc(s.from,s.to),!r)return P.none}let l=[];for(let a of n.visibleRanges){let h=new At(t.doc,r,a.from,a.to);for(;!h.next().done;){let{from:c,to:f}=h.value;if((!o||au(o,t,c,f))&&(s.empty&&c<=s.from&&f>=s.to?l.push(z0.range(c,f)):(c>=s.to||f<=s.from)&&l.push(V0.range(c,f)),l.length>e.maxMatches))return P.none}}return P.set(l)}},{decorations:n=>n.decorations}),K0=T.baseTheme({".cm-selectionMatch":{backgroundColor:"#99ff7780"},".cm-searchMatch .cm-selectionMatch":{backgroundColor:"transparent"}}),j0=({state:n,dispatch:e})=>{let{selection:t}=n,i=x.create(t.ranges.map(s=>n.wordAt(s.head)||x.cursor(s.head)),t.mainIndex);return i.eq(t)?!1:(e(n.update({selection:i})),!0)};function U0(n,e){let{main:t,ranges:i}=n.selection,s=n.wordAt(t.head),r=s&&s.from==t.from&&s.to==t.to;for(let o=!1,l=new At(n.doc,e,i[i.length-1].to);;)if(l.next(),l.done){if(o)return null;l=new At(n.doc,e,0,Math.max(0,i[i.length-1].from-1)),o=!0}else{if(o&&i.some(a=>a.from==l.value.from))continue;if(r){let a=n.wordAt(l.value.from);if(!a||a.from!=l.value.from||a.to!=l.value.to)continue}return l.value}}var G0=({state:n,dispatch:e})=>{let{ranges:t}=n.selection;if(t.some(r=>r.from===r.to))return j0({state:n,dispatch:e});let i=n.sliceDoc(t[0].from,t[0].to);if(n.selection.ranges.some(r=>n.sliceDoc(r.from,r.to)!=i))return!1;let s=U0(n,i);return s?(e(n.update({selection:n.selection.addRange(x.range(s.from,s.to),!1),effects:T.scrollIntoView(s.to)})),!0):!1},Ai=A.define({combine(n){return he(n,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:e=>new Ll(e),scrollToMatch:e=>T.scrollIntoView(e)})}});var $s=class{constructor(e){this.search=e.search,this.caseSensitive=!!e.caseSensitive,this.literal=!!e.literal,this.regexp=!!e.regexp,this.replace=e.replace||"",this.valid=!!this.search&&(!this.regexp||F0(this.search)),this.unquoted=this.unquote(this.search),this.wholeWord=!!e.wholeWord,this.test=e.test}unquote(e){return this.literal?e:e.replace(/\\([nrt\\])/g,(t,i)=>i=="n"?` +`:i=="r"?"\r":i=="t"?" ":"\\")}eq(e){return this.search==e.search&&this.replace==e.replace&&this.caseSensitive==e.caseSensitive&&this.regexp==e.regexp&&this.wholeWord==e.wholeWord&&this.test==e.test}create(){return this.regexp?new Bl(this):new Pl(this)}getCursor(e,t=0,i){let s=e.doc?e:$.create({doc:e});return i==null&&(i=s.doc.length),this.regexp?Ci(this,s,t,i):Si(this,s,t,i)}},Ks=class{constructor(e){this.spec=e}};function _0(n,e,t){return(i,s,r,o)=>{if(t&&!t(i,s,r,o))return!1;let l=i>=o&&s<=o+r.length?r.slice(i-o,s-o):e.doc.sliceString(i,s);return n(l,e,i,s)}}function Si(n,e,t,i){let s;return n.wholeWord&&(s=Y0(e.doc,e.charCategorizer(e.selection.main.head))),n.test&&(s=_0(n.test,e,s)),new At(e.doc,n.unquoted,t,i,n.caseSensitive?void 0:r=>r.toLowerCase(),s)}function Y0(n,e){return(t,i,s,r)=>((r>t||r+s.length=t)return null;s.push(i.value)}return s}highlight(e,t,i,s){let r=Si(this.spec,e,Math.max(0,t-this.spec.unquoted.length),Math.min(i+this.spec.unquoted.length,e.doc.length));for(;!r.next().done;)s(r.value.from,r.value.to)}};function X0(n,e,t){return(i,s,r)=>(!t||t(i,s,r))&&n(r[0],e,i,s)}function Ci(n,e,t,i){let s;return n.wholeWord&&(s=Q0(e.charCategorizer(e.selection.main.head))),n.test&&(s=X0(n.test,e,s)),new Hs(e.doc,n.search,{ignoreCase:!n.caseSensitive,test:s},t,i)}function js(n,e){return n.slice(ee(n,e,!1),e)}function Us(n,e){return n.slice(e,ee(n,e))}function Q0(n){return(e,t,i)=>!i[0].length||(n(js(i.input,i.index))!=K.Word||n(Us(i.input,i.index))!=K.Word)&&(n(Us(i.input,i.index+i[0].length))!=K.Word||n(js(i.input,i.index+i[0].length))!=K.Word)}var Bl=class extends Ks{nextMatch(e,t,i){let s=Ci(this.spec,e,i,e.doc.length).next();return s.done&&(s=Ci(this.spec,e,0,t).next()),s.done?null:s.value}prevMatchInRange(e,t,i){for(let s=1;;s++){let r=Math.max(t,i-s*1e4),o=Ci(this.spec,e,r,i),l=null;for(;!o.next().done;)l=o.value;if(l&&(r==t||l.from>r+10))return l;if(r==t)return null}}prevMatch(e,t,i){return this.prevMatchInRange(e,0,t)||this.prevMatchInRange(e,i,e.doc.length)}getReplacement(e){return this.spec.unquote(this.spec.replace).replace(/\$([$&]|\d+)/g,(t,i)=>{if(i=="&")return e.match[0];if(i=="$")return"$";for(let s=i.length;s>0;s--){let r=+i.slice(0,s);if(r>0&&r=t)return null;s.push(i.value)}return s}highlight(e,t,i,s){let r=Ci(this.spec,e,Math.max(0,t-250),Math.min(i+250,e.doc.length));for(;!r.next().done;)s(r.value.from,r.value.to)}},mn=R.define(),Il=R.define(),Ct=X.define({create(n){return new pn(Rl(n).create(),null)},update(n,e){for(let t of e.effects)t.is(mn)?n=new pn(t.value.create(),n.panel):t.is(Il)&&(n=new pn(n.query,t.value?Nl:null));return n},provide:n=>Ht.from(n,e=>e.panel)});var pn=class{constructor(e,t){this.query=e,this.panel=t}},J0=P.mark({class:"cm-searchMatch"}),Z0=P.mark({class:"cm-searchMatch cm-searchMatch-selected"}),eb=Y.fromClass(class{constructor(n){this.view=n,this.decorations=this.highlight(n.state.field(Ct))}update(n){let e=n.state.field(Ct);(e!=n.startState.field(Ct)||n.docChanged||n.selectionSet||n.viewportChanged)&&(this.decorations=this.highlight(e))}highlight({query:n,panel:e}){if(!e||!n.spec.valid)return P.none;let{view:t}=this,i=new Ae;for(let s=0,r=t.visibleRanges,o=r.length;sr[s+1].from-500;)a=r[++s].to;n.highlight(t.state,l,a,(h,c)=>{let f=t.state.selection.ranges.some(u=>u.from==h&&u.to==c);i.add(h,c,f?Z0:J0)})}return i.finish()}},{decorations:n=>n.decorations});function gn(n){return e=>{let t=e.state.field(Ct,!1);return t&&t.query.spec.valid?n(e,t):mu(e)}}var Gs=gn((n,{query:e})=>{let{to:t}=n.state.selection.main,i=e.nextMatch(n.state,t,t);if(!i)return!1;let s=x.single(i.from,i.to),r=n.state.facet(Ai);return n.dispatch({selection:s,effects:[Fl(n,i),r.scrollToMatch(s.main,n)],userEvent:"select.search"}),pu(n),!0}),_s=gn((n,{query:e})=>{let{state:t}=n,{from:i}=t.selection.main,s=e.prevMatch(t,i,i);if(!s)return!1;let r=x.single(s.from,s.to),o=n.state.facet(Ai);return n.dispatch({selection:r,effects:[Fl(n,s),o.scrollToMatch(r.main,n)],userEvent:"select.search"}),pu(n),!0}),tb=gn((n,{query:e})=>{let t=e.matchAll(n.state,1e3);return!t||!t.length?!1:(n.dispatch({selection:x.create(t.map(i=>x.range(i.from,i.to))),userEvent:"select.search.matches"}),!0)}),ib=({state:n,dispatch:e})=>{let t=n.selection;if(t.ranges.length>1||t.main.empty)return!1;let{from:i,to:s}=t.main,r=[],o=0;for(let l=new At(n.doc,n.sliceDoc(i,s));!l.next().done;){if(r.length>1e3)return!1;l.value.from==i&&(o=r.length),r.push(x.range(l.value.from,l.value.to))}return e(n.update({selection:x.create(r,o),userEvent:"select.search.matches"})),!0},hu=gn((n,{query:e})=>{let{state:t}=n,{from:i,to:s}=t.selection.main;if(t.readOnly)return!1;let r=e.nextMatch(t,i,i);if(!r)return!1;let o=r,l=[],a,h,c=[];o.precise?o.from==i&&o.to==s&&(h=t.toText(e.getReplacement(o)),l.push({from:o.from,to:o.to,insert:h}),c.push(T.announce.of(t.phrase("replaced match on line $",t.doc.lineAt(i).number)+"."))):o=e.nextMatch(t,o.from,o.to);let f=n.state.changes(l);return o&&(a=x.single(o.from,o.to).map(f),c.push(Fl(n,o)),c.push(t.facet(Ai).scrollToMatch(a.main,n))),n.dispatch({changes:f,selection:a,effects:c,userEvent:"input.replace"}),!0}),nb=gn((n,{query:e})=>{if(n.state.readOnly)return!1;let t=[];for(let s of e.matchAll(n.state,1e9)){let{from:r,to:o,precise:l}=s;l&&t.push({from:r,to:o,insert:e.getReplacement(s)})}if(!t.length)return!1;let i=n.state.phrase("replaced $ matches",t.length)+".";return n.dispatch({changes:t,effects:T.announce.of(i),userEvent:"input.replace.all"}),!0});function Nl(n){return n.state.facet(Ai).createPanel(n)}function Rl(n,e){var t,i,s,r,o;let l=n.selection.main,a=l.empty||l.to>l.from+100?"":n.sliceDoc(l.from,l.to);if(e&&!a)return e;let h=n.facet(Ai);return new $s({search:((t=e?.literal)!==null&&t!==void 0?t:h.literal)?a:a.replace(/\n/g,"\\n"),caseSensitive:(i=e?.caseSensitive)!==null&&i!==void 0?i:h.caseSensitive,literal:(s=e?.literal)!==null&&s!==void 0?s:h.literal,regexp:(r=e?.regexp)!==null&&r!==void 0?r:h.regexp,wholeWord:(o=e?.wholeWord)!==null&&o!==void 0?o:h.wholeWord})}function du(n){let e=Qi(n,Nl);return e&&e.dom.querySelector("[main-field]")}function pu(n){let e=du(n);e&&e==n.root.activeElement&&e.select()}var mu=n=>{let e=n.state.field(Ct,!1);if(e&&e.panel){let t=du(n);if(t&&t!=n.root.activeElement){let i=Rl(n.state,e.query.spec);i.valid&&n.dispatch({effects:mn.of(i)}),t.focus(),t.select()}}else n.dispatch({effects:[Il.of(!0),e?mn.of(Rl(n.state,e.query.spec)):R.appendConfig.of(rb)]});return!0},gu=n=>{let e=n.state.field(Ct,!1);if(!e||!e.panel)return!1;let t=Qi(n,Nl);return t&&t.dom.contains(n.root.activeElement)&&n.focus(),n.dispatch({effects:Il.of(!1)}),!0},bu=[{key:"Mod-f",run:mu,scope:"editor search-panel"},{key:"F3",run:Gs,shift:_s,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:Gs,shift:_s,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:gu,scope:"editor search-panel"},{key:"Mod-Shift-l",run:ib},{key:"Mod-Alt-g",run:W0},{key:"Mod-d",run:G0,preventDefault:!0}],Ll=class{constructor(e){this.view=e;let t=this.query=e.state.field(Ct).query.spec;this.commit=this.commit.bind(this),this.searchField=H("input",{value:t.search,placeholder:De(e,"Find"),"aria-label":De(e,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=H("input",{value:t.replace,placeholder:De(e,"Replace"),"aria-label":De(e,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=H("input",{type:"checkbox",name:"case",form:"",checked:t.caseSensitive,onchange:this.commit}),this.reField=H("input",{type:"checkbox",name:"re",form:"",checked:t.regexp,onchange:this.commit}),this.wordField=H("input",{type:"checkbox",name:"word",form:"",checked:t.wholeWord,onchange:this.commit});function i(s,r,o){return H("button",{class:"cm-button",name:s,onclick:r,type:"button"},o)}this.dom=H("div",{onkeydown:s=>this.keydown(s),class:"cm-search"},[this.searchField,i("next",()=>Gs(e),[De(e,"next")]),i("prev",()=>_s(e),[De(e,"previous")]),i("select",()=>tb(e),[De(e,"all")]),H("label",null,[this.caseField,De(e,"match case")]),H("label",null,[this.reField,De(e,"regexp")]),H("label",null,[this.wordField,De(e,"by word")]),...e.state.readOnly?[]:[H("br"),this.replaceField,i("replace",()=>hu(e),[De(e,"replace")]),i("replaceAll",()=>nb(e),[De(e,"replace all")])],H("button",{name:"close",onclick:()=>gu(e),"aria-label":De(e,"close"),type:"button"},["\xD7"])])}commit(){let e=new $s({search:this.searchField.value,caseSensitive:this.caseField.checked,regexp:this.reField.checked,wholeWord:this.wordField.checked,replace:this.replaceField.value});e.eq(this.query)||(this.query=e,this.view.dispatch({effects:mn.of(e)}))}keydown(e){gc(this.view,e,"search-panel")?e.preventDefault():e.keyCode==13&&e.target==this.searchField?(e.preventDefault(),(e.shiftKey?_s:Gs)(this.view)):e.keyCode==13&&e.target==this.replaceField&&(e.preventDefault(),hu(this.view))}update(e){for(let t of e.transactions)for(let i of t.effects)i.is(mn)&&!i.value.eq(this.query)&&this.setQuery(i.value)}setQuery(e){this.query=e,this.searchField.value=e.search,this.replaceField.value=e.replace,this.caseField.checked=e.caseSensitive,this.reField.checked=e.regexp,this.wordField.checked=e.wholeWord}mount(){this.searchField.select()}get pos(){return 80}get top(){return this.view.state.facet(Ai).top}};function De(n,e){return n.state.phrase(e)}var Fs=30,Ws=/[\s\.,:;?!]/;function Fl(n,{from:e,to:t}){let i=n.state.doc.lineAt(e),s=n.state.doc.lineAt(t).to,r=Math.max(i.from,e-Fs),o=Math.min(s,t+Fs),l=n.state.sliceDoc(r,o);if(r!=i.from){for(let a=0;al.length-Fs;a--)if(!Ws.test(l[a-1])&&Ws.test(l[a])){l=l.slice(0,a);break}}return T.announce.of(`${n.state.phrase("current match")}. ${l} ${n.state.phrase("on line")} ${i.number}.`)}var sb=T.baseTheme({".cm-panel.cm-search":{padding:"2px 6px 4px",position:"relative","& [name=close]":{position:"absolute",top:"0",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",padding:0,margin:0},"& input, & button, & label":{margin:".2em .6em .2em 0"},"& input[type=checkbox]":{marginRight:".2em"},"& label":{fontSize:"80%",whiteSpace:"pre"}},"&light .cm-searchMatch":{backgroundColor:"#ffff0054"},"&dark .cm-searchMatch":{backgroundColor:"#00ffff8a"},"&light .cm-searchMatch-selected":{backgroundColor:"#ff6a0054"},"&dark .cm-searchMatch-selected":{backgroundColor:"#ff00ff8a"}}),rb=[Ct,ze.low(eb),sb];var Xs=class{constructor(e,t,i,s){this.state=e,this.pos=t,this.explicit=i,this.view=s,this.abortListeners=[],this.abortOnDocChange=!1}tokenBefore(e){let t=se(this.state).resolveInner(this.pos,-1);for(;t&&e.indexOf(t.name)<0;)t=t.parent;return t?{from:t.from,to:this.pos,text:this.state.sliceDoc(t.from,this.pos),type:t.type}:null}matchBefore(e){let t=this.state.doc.lineAt(this.pos),i=Math.max(t.from,this.pos-250),s=t.text.slice(i-t.from,this.pos-t.from),r=s.search(Au(e,!1));return r<0?null:{from:i+r,to:this.pos,text:s.slice(r)}}get aborted(){return this.abortListeners==null}addEventListener(e,t,i){e=="abort"&&this.abortListeners&&(this.abortListeners.push(t),i&&i.onDocChange&&(this.abortOnDocChange=!0))}};function yu(n){let e=Object.keys(n).join(""),t=/\w/.test(e);return t&&(e=e.replace(/\w/g,"")),`[${t?"\\w":""}${e.replace(/[^\w\s]/g,"\\$&")}]`}function ob(n){let e=Object.create(null),t=Object.create(null);for(let{label:s}of n){e[s[0]]=!0;for(let r=1;rtypeof s=="string"?{label:s}:s),[t,i]=e.every(s=>/^\w+$/.test(s.label))?[/\w*$/,/\w+$/]:ob(e);return s=>{let r=s.matchBefore(i);return r||s.explicit?{from:r?r.from:s.pos,options:e,validFor:t}:null}}var Qs=class{constructor(e,t,i,s){this.completion=e,this.source=t,this.match=i,this.score=s}};function _t(n){return n.selection.main.from}function Au(n,e){var t;let{source:i}=n,s=e&&i[0]!="^",r=i[i.length-1]!="$";return!s&&!r?n:new RegExp(`${s?"^":""}(?:${i})${r?"$":""}`,(t=n.flags)!==null&&t!==void 0?t:n.ignoreCase?"i":"")}var Mu=be.define();function ab(n,e,t,i){let{main:s}=n.selection,r=t-s.from,o=i-s.from;return{...n.changeByRange(l=>{if(l!=s&&t!=i&&n.sliceDoc(l.from+r,l.from+o)!=n.sliceDoc(t,i))return{range:l};let a=n.toText(e);return{changes:{from:l.from+r,to:i==s.from?l.to:l.from+o,insert:a},range:x.cursor(l.from+r+a.length)}}),scrollIntoView:!0,userEvent:"input.complete"}}var xu=new WeakMap;function hb(n){if(!Array.isArray(n))return n;let e=xu.get(n);return e||xu.set(n,e=lb(n)),e}var Js=R.define(),bn=R.define(),zl=class{constructor(e){this.pattern=e,this.chars=[],this.folded=[],this.any=[],this.precise=[],this.byWord=[],this.score=0,this.matched=[];for(let t=0;t=48&&v<=57||v>=97&&v<=122?2:v>=65&&v<=90?1:0:(S=Ri(v))!=S.toLowerCase()?1:S!=S.toUpperCase()?2:0;(!w||C==1&&g||D==0&&C!=0)&&(t[f]==v||i[f]==v&&(u=!0)?o[f++]=w:o.length&&(b=!1)),D=C,w+=Me(v)}return f==a&&o[0]==0&&b?this.result(-100+(u?-200:0),o,e):d==a&&p==0?this.ret(-200-e.length+(m==e.length?0:-100),[0,m]):l>-1?this.ret(-700-e.length,[l,l+this.pattern.length]):d==a?this.ret(-900-e.length,[p,m]):f==a?this.result(-100+(u?-200:0)+-700+(b?0:-1100),o,e):t.length==2?null:this.result((s[0]?-700:0)+-200+-1100,s,e)}result(e,t,i){let s=[],r=0;for(let o of t){let l=o+(this.astral?Me(ae(i,o)):1);r&&s[r-1]==o?s[r-1]=l:(s[r++]=o,s[r++]=l)}return this.ret(e-i.length,s)}},ql=class{constructor(e){this.pattern=e,this.matched=[],this.score=0,this.folded=e.toLowerCase()}match(e){if(e.length!1,activateOnTypingDelay:100,selectOnOpen:!0,override:null,closeOnBlur:!0,maxRenderedOptions:100,defaultKeymap:!0,tooltipClass:()=>"",optionClass:()=>"",aboveCursor:!1,icons:!0,addToOptions:[],positionInfo:cb,filterStrict:!1,compareCompletions:(e,t)=>(e.sortText||e.label).localeCompare(t.sortText||t.label),interactionDelay:75,updateSyncTime:100},{defaultKeymap:(e,t)=>e&&t,closeOnBlur:(e,t)=>e&&t,icons:(e,t)=>e&&t,tooltipClass:(e,t)=>i=>wu(e(i),t(i)),optionClass:(e,t)=>i=>wu(e(i),t(i)),addToOptions:(e,t)=>e.concat(t),filterStrict:(e,t)=>e||t})}});function wu(n,e){return n?e?n+" "+e:n:e}function cb(n,e,t,i,s,r){let o=n.textDirection==z.RTL,l=o,a=!1,h="top",c,f,u=e.left-s.left,d=s.right-e.right,p=i.right-i.left,m=i.bottom-i.top;if(l&&u=m||w>e.top?c=t.bottom-e.top:(h="bottom",c=e.bottom-t.top)}let g=(e.bottom-e.top)/r.offsetHeight,b=(e.right-e.left)/r.offsetWidth;return{style:`${h}: ${c/g}px; max-width: ${f/b}px`,class:"cm-completionInfo-"+(a?o?"left-narrow":"right-narrow":l?"left":"right")}}var Gl=R.define();function fb(n){let e=n.addToOptions.slice();return n.icons&&e.push({render(t){let i=document.createElement("div");return i.classList.add("cm-completionIcon"),t.type&&i.classList.add(...t.type.split(/\s+/g).map(s=>"cm-completionIcon-"+s)),i.setAttribute("aria-hidden","true"),i},position:20}),e.push({render(t,i,s,r){let o=document.createElement("span");o.className="cm-completionLabel";let l=t.displayLabel||t.label,a=0;for(let h=0;ha&&o.appendChild(document.createTextNode(l.slice(a,c)));let u=o.appendChild(document.createElement("span"));u.appendChild(document.createTextNode(l.slice(c,f))),u.className="cm-completionMatchedText",a=f}return at.position-i.position).map(t=>t.render)}function Wl(n,e,t){if(n<=t)return{from:0,to:n};if(e<0&&(e=0),e<=n>>1){let s=Math.floor(e/t);return{from:s*t,to:(s+1)*t}}let i=Math.ceil((n-e)/t);return{from:n-i*t,to:n-(i-1)*t}}var $l=class{constructor(e,t,i){this.view=e,this.stateField=t,this.applyCompletion=i,this.info=null,this.infoDestroy=null,this.placeInfoReq={read:()=>this.measureInfo(),write:a=>this.placeInfo(a),key:this},this.space=null,this.currentClass="";let s=e.state.field(t),{options:r,selected:o}=s.open,l=e.state.facet(re);this.optionContent=fb(l),this.optionClass=l.optionClass,this.tooltipClass=l.tooltipClass,this.range=Wl(r.length,o,l.maxRenderedOptions),this.dom=document.createElement("div"),this.dom.className="cm-tooltip-autocomplete",this.updateTooltipClass(e.state),this.dom.addEventListener("mousedown",a=>{let{options:h}=e.state.field(t).open;for(let c=a.target,f;c&&c!=this.dom;c=c.parentNode)if(c.nodeName=="LI"&&(f=/-(\d+)$/.exec(c.id))&&+f[1]this.list.lastChild.getBoundingClientRect().bottom?this.range.to:null;c!=null&&(e.dispatch({effects:Gl.of(c)}),a.preventDefault())}}),this.dom.addEventListener("focusout",a=>{let h=e.state.field(this.stateField,!1);h&&h.tooltip&&e.state.facet(re).closeOnBlur&&a.relatedTarget!=e.contentDOM&&e.dispatch({effects:bn.of(null)})}),this.showOptions(r,s.id)}mount(){this.updateSel()}showOptions(e,t){this.list&&this.list.remove(),this.list=this.dom.appendChild(this.createListBox(e,t,this.range)),this.list.addEventListener("scroll",()=>{this.info&&this.view.requestMeasure(this.placeInfoReq)})}update(e){var t;let i=e.state.field(this.stateField),s=e.startState.field(this.stateField);if(this.updateTooltipClass(e.state),i!=s){let{options:r,selected:o,disabled:l}=i.open;(!s.open||s.open.options!=r)&&(this.range=Wl(r.length,o,e.state.facet(re).maxRenderedOptions),this.showOptions(r,i.id)),this.updateSel(),l!=((t=s.open)===null||t===void 0?void 0:t.disabled)&&this.dom.classList.toggle("cm-tooltip-autocomplete-disabled",!!l)}}updateTooltipClass(e){let t=this.tooltipClass(e);if(t!=this.currentClass){for(let i of this.currentClass.split(" "))i&&this.dom.classList.remove(i);for(let i of t.split(" "))i&&this.dom.classList.add(i);this.currentClass=t}}positioned(e){this.space=e,this.info&&this.view.requestMeasure(this.placeInfoReq)}updateSel(){let e=this.view.state.field(this.stateField),t=e.open;(t.selected>-1&&t.selected=this.range.to)&&(this.range=Wl(t.options.length,t.selected,this.view.state.facet(re).maxRenderedOptions),this.showOptions(t.options,e.id));let i=this.updateSelectedOption(t.selected);if(i){this.destroyInfo();let{completion:s}=t.options[t.selected],{info:r}=s;if(!r)return;let o=typeof r=="string"?document.createTextNode(r):r(s);if(!o)return;"then"in o?o.then(l=>{l&&this.view.state.field(this.stateField,!1)==e&&this.addInfoPane(l,s)}).catch(l=>ne(this.view.state,l,"completion info")):(this.addInfoPane(o,s),i.setAttribute("aria-describedby",this.info.id))}}addInfoPane(e,t){this.destroyInfo();let i=this.info=document.createElement("div");if(i.className="cm-tooltip cm-completionInfo",i.id="cm-completionInfo-"+Math.floor(Math.random()*65535).toString(16),e.nodeType!=null)i.appendChild(e),this.infoDestroy=null;else{let{dom:s,destroy:r}=e;i.appendChild(s),this.infoDestroy=r||null}this.dom.appendChild(i),this.view.requestMeasure(this.placeInfoReq)}updateSelectedOption(e){let t=null;for(let i=this.list.firstChild,s=this.range.from;i;i=i.nextSibling,s++)i.nodeName!="LI"||!i.id?s--:s==e?i.hasAttribute("aria-selected")||(i.setAttribute("aria-selected","true"),t=i):i.hasAttribute("aria-selected")&&(i.removeAttribute("aria-selected"),i.removeAttribute("aria-describedby"));return t&&db(this.list,t),t}measureInfo(){let e=this.dom.querySelector("[aria-selected]");if(!e||!this.info)return null;let t=this.dom.getBoundingClientRect(),i=this.info.getBoundingClientRect(),s=e.getBoundingClientRect(),r=this.space;if(!r){let o=this.dom.ownerDocument.documentElement;r={left:0,top:0,right:o.clientWidth,bottom:o.clientHeight}}return s.top>Math.min(r.bottom,t.bottom)-10||s.bottom{o.target==s&&o.preventDefault()});let r=null;for(let o=i.from;oi.from||i.from==0))if(r=u,typeof h!="string"&&h.header)s.appendChild(h.header(h));else{let d=s.appendChild(document.createElement("completion-section"));d.textContent=u}}let c=s.appendChild(document.createElement("li"));c.id=t+"-"+o,c.setAttribute("role","option");let f=this.optionClass(l);f&&(c.className=f);for(let u of this.optionContent){let d=u(l,this.view.state,this.view,a);d&&c.appendChild(d)}}return i.from&&s.classList.add("cm-completionListIncompleteTop"),i.tonew $l(t,n,e)}function db(n,e){let t=n.getBoundingClientRect(),i=e.getBoundingClientRect(),s=t.height/n.offsetHeight;i.topt.bottom&&(n.scrollTop+=(i.bottom-t.bottom)/s)}function ku(n){return(n.boost||0)*100+(n.apply?10:0)+(n.info?5:0)+(n.type?1:0)}function pb(n,e){let t=[],i=null,s=null,r=c=>{t.push(c);let{section:f}=c.completion;if(f){i||(i=[]);let u=typeof f=="string"?f:f.name;i.some(d=>d.name==u)||i.push(typeof f=="string"?{name:u}:f)}},o=e.facet(re);for(let c of n)if(c.hasResult()){let f=c.result.getMatch;if(c.result.filter===!1)for(let u of c.result.options)r(new Qs(u,c.source,f?f(u):[],1e9-t.length));else{let u=e.sliceDoc(c.from,c.to),d,p=o.filterStrict?new ql(u):new zl(u);for(let m of c.result.options)if(d=p.match(m.label)){let g=m.displayLabel?f?f(m,d.matched):[]:d.matched,b=d.score+(m.boost||0);if(r(new Qs(m,c.source,g,b)),typeof m.section=="object"&&m.section.rank==="dynamic"){let{name:w}=m.section;s||(s=Object.create(null)),s[w]=Math.max(b,s[w]||-1e9)}}}}if(i){let c=Object.create(null),f=0,u=(d,p)=>(d.rank==="dynamic"&&p.rank==="dynamic"?s[p.name]-s[d.name]:0)||(typeof d.rank=="number"?d.rank:1e9)-(typeof p.rank=="number"?p.rank:1e9)||(d.nameu.score-f.score||h(f.completion,u.completion))){let f=c.completion;!a||a.label!=f.label||a.detail!=f.detail||a.type!=null&&f.type!=null&&a.type!=f.type||a.apply!=f.apply||a.boost!=f.boost?l.push(c):ku(c.completion)>ku(a)&&(l[l.length-1]=c),a=c.completion}return l}var Kl=class n{constructor(e,t,i,s,r,o){this.options=e,this.attrs=t,this.tooltip=i,this.timestamp=s,this.selected=r,this.disabled=o}setSelected(e,t){return e==this.selected||e>=this.options.length?this:new n(this.options,vu(t,e),this.tooltip,this.timestamp,e,this.disabled)}static build(e,t,i,s,r,o){if(s&&!o&&e.some(h=>h.isPending))return s.setDisabled();let l=pb(e,t);if(!l.length)return s&&e.some(h=>h.isPending)?s.setDisabled():null;let a=t.facet(re).selectOnOpen?0:-1;if(s&&s.selected!=a&&s.selected!=-1){let h=s.options[s.selected].completion;for(let c=0;cc.hasResult()?Math.min(h,c.from):h,1e8),create:wb,above:r.aboveCursor},s?s.timestamp:Date.now(),a,!1)}map(e){return new n(this.options,this.attrs,{...this.tooltip,pos:e.mapPos(this.tooltip.pos)},this.timestamp,this.selected,this.disabled)}setDisabled(){return new n(this.options,this.attrs,this.tooltip,this.timestamp,this.selected,!0)}},jl=class n{constructor(e,t,i){this.active=e,this.id=t,this.open=i}static start(){return new n(yb,"cm-ac-"+Math.floor(Math.random()*2e6).toString(36),null)}update(e){let{state:t}=e,i=t.facet(re),r=(i.override||t.languageDataAt("autocomplete",_t(t)).map(hb)).map(a=>(this.active.find(c=>c.source==a)||new ut(a,this.active.some(c=>c.state!=0)?1:0)).update(e,i));r.length==this.active.length&&r.every((a,h)=>a==this.active[h])&&(r=this.active);let o=this.open,l=e.effects.some(a=>a.is(_l));o&&e.docChanged&&(o=o.map(e.changes)),e.selection||r.some(a=>a.hasResult()&&e.changes.touchesRange(a.from,a.to))||!mb(r,this.active)||l?o=Kl.build(r,t,this.id,o,i,l):o&&o.disabled&&!r.some(a=>a.isPending)&&(o=null),!o&&r.every(a=>!a.isPending)&&r.some(a=>a.hasResult())&&(r=r.map(a=>a.hasResult()?new ut(a.source,0):a));for(let a of e.effects)a.is(Gl)&&(o=o&&o.setSelected(a.value,this.id));return r==this.active&&o==this.open?this:new n(r,this.id,o)}get tooltip(){return this.open?this.open.tooltip:null}get attrs(){return this.open?this.open.attrs:this.active.length?gb:bb}};function mb(n,e){if(n==e)return!0;for(let t=0,i=0;;){for(;t-1&&(t["aria-activedescendant"]=n+"-"+e),t}var yb=[];function Tu(n,e){if(n.isUserEvent("input.complete")){let i=n.annotation(Mu);if(i&&e.activateOnCompletion(i))return 12}let t=n.isUserEvent("input.type");return t&&e.activateOnTyping?5:t?1:n.isUserEvent("delete.backward")?2:n.selection?8:n.docChanged?16:0}var ut=class n{constructor(e,t,i=!1){this.source=e,this.state=t,this.explicit=i}hasResult(){return!1}get isPending(){return this.state==1}update(e,t){let i=Tu(e,t),s=this;(i&8||i&16&&this.touches(e))&&(s=new n(s.source,0)),i&4&&s.state==0&&(s=new n(this.source,1)),s=s.updateFor(e,i);for(let r of e.effects)if(r.is(Js))s=new n(s.source,1,r.value);else if(r.is(bn))s=new n(s.source,0);else if(r.is(_l))for(let o of r.value)o.source==s.source&&(s=o);return s}updateFor(e,t){return this.map(e.changes)}map(e){return this}touches(e){return e.changes.touchesRange(_t(e.state))}},Zs=class n extends ut{constructor(e,t,i,s,r,o){super(e,3,t),this.limit=i,this.result=s,this.from=r,this.to=o}hasResult(){return!0}updateFor(e,t){var i;if(!(t&3))return this.map(e.changes);let s=this.result;s.map&&!e.changes.empty&&(s=s.map(s,e.changes));let r=e.changes.mapPos(this.from),o=e.changes.mapPos(this.to,1),l=_t(e.state);if(l>o||!s||t&2&&(_t(e.startState)==this.from||lt.map(e))}}),ve=X.define({create(){return jl.start()},update(n,e){return n.update(e)},provide:n=>[bi.from(n,e=>e.tooltip),T.contentAttributes.from(n,e=>e.attrs)]});function Yl(n,e){let t=e.completion.apply||e.completion.label,i=n.state.field(ve).active.find(s=>s.source==e.source);return i instanceof Zs?(typeof t=="string"?n.dispatch({...ab(n.state,t,i.from,i.to),annotations:Mu.of(e.completion)}):t(n,e.completion,i.from,i.to),!0):!1}var wb=ub(ve,Yl);function Ys(n,e="option"){return t=>{let i=t.state.field(ve,!1);if(!i||!i.open||i.open.disabled||Date.now()-i.open.timestamp-1?i.open.selected+s*(n?1:-1):n?0:o-1;return l<0?l=e=="page"?0:o-1:l>=o&&(l=e=="page"?o-1:0),t.dispatch({effects:Gl.of(l)}),!0}}var kb=n=>{let e=n.state.field(ve,!1);return n.state.readOnly||!e||!e.open||e.open.selected<0||e.open.disabled||Date.now()-e.open.timestampn.state.field(ve,!1)?(n.dispatch({effects:Js.of(!0)}),!0):!1,vb=n=>{let e=n.state.field(ve,!1);return!e||!e.active.some(t=>t.state!=0)?!1:(n.dispatch({effects:bn.of(null)}),!0)},Ul=class{constructor(e,t){this.active=e,this.context=t,this.time=Date.now(),this.updates=[],this.done=void 0}},Sb=50,Cb=1e3,Ab=Y.fromClass(class{constructor(n){this.view=n,this.debounceUpdate=-1,this.running=[],this.debounceAccept=-1,this.pendingStart=!1,this.composing=0;for(let e of n.state.field(ve).active)e.isPending&&this.startQuery(e)}update(n){let e=n.state.field(ve),t=n.state.facet(re);if(!n.selectionSet&&!n.docChanged&&n.startState.field(ve)==e)return;let i=n.transactions.some(r=>{let o=Tu(r,t);return o&8||(r.selection||r.docChanged)&&!(o&3)});for(let r=0;rSb&&Date.now()-o.time>Cb){for(let l of o.context.abortListeners)try{l()}catch(a){ne(this.view.state,a)}o.context.abortListeners=null,this.running.splice(r--,1)}else o.updates.push(...n.transactions)}this.debounceUpdate>-1&&clearTimeout(this.debounceUpdate),n.transactions.some(r=>r.effects.some(o=>o.is(Js)))&&(this.pendingStart=!0);let s=this.pendingStart?50:t.activateOnTypingDelay;if(this.debounceUpdate=e.active.some(r=>r.isPending&&!this.running.some(o=>o.active.source==r.source))?setTimeout(()=>this.startUpdate(),s):-1,this.composing!=0)for(let r of n.transactions)r.isUserEvent("input.type")?this.composing=2:this.composing==2&&r.selection&&(this.composing=3)}startUpdate(){this.debounceUpdate=-1,this.pendingStart=!1;let{state:n}=this.view,e=n.field(ve);for(let t of e.active)t.isPending&&!this.running.some(i=>i.active.source==t.source)&&this.startQuery(t);this.running.length&&e.open&&e.open.disabled&&(this.debounceAccept=setTimeout(()=>this.accept(),this.view.state.facet(re).updateSyncTime))}startQuery(n){let{state:e}=this.view,t=_t(e),i=new Xs(e,t,n.explicit,this.view),s=new Ul(n,i);this.running.push(s),Promise.resolve(n.source(i)).then(r=>{s.context.aborted||(s.done=r||null,this.scheduleAccept())},r=>{this.view.dispatch({effects:bn.of(null)}),ne(this.view.state,r)})}scheduleAccept(){this.running.every(n=>n.done!==void 0)?this.accept():this.debounceAccept<0&&(this.debounceAccept=setTimeout(()=>this.accept(),this.view.state.facet(re).updateSyncTime))}accept(){var n;this.debounceAccept>-1&&clearTimeout(this.debounceAccept),this.debounceAccept=-1;let e=[],t=this.view.state.facet(re),i=this.view.state.field(ve);for(let s=0;sl.source==r.active.source);if(o&&o.isPending)if(r.done==null){let l=new ut(r.active.source,0);for(let a of r.updates)l=l.update(a,t);l.isPending||e.push(l)}else this.startQuery(o)}(e.length||i.open&&i.open.disabled)&&this.view.dispatch({effects:_l.of(e)})}},{eventHandlers:{blur(n){let e=this.view.state.field(ve,!1);if(e&&e.tooltip&&this.view.state.facet(re).closeOnBlur){let t=e.open&&Go(this.view,e.open.tooltip);(!t||!t.dom.contains(n.relatedTarget))&&setTimeout(()=>this.view.dispatch({effects:bn.of(null)}),10)}},compositionstart(){this.composing=1},compositionend(){this.composing==3&&setTimeout(()=>this.view.dispatch({effects:Js.of(!1)}),20),this.composing=0}}}),Mb=typeof navigator=="object"&&/Win/.test(navigator.platform),Tb=ze.highest(T.domEventHandlers({keydown(n,e){let t=e.state.field(ve,!1);if(!t||!t.open||t.open.disabled||t.open.selected<0||n.key.length>1||n.ctrlKey&&!(Mb&&n.altKey)||n.metaKey)return!1;let i=t.open.options[t.open.selected],s=t.active.find(o=>o.source==i.source),r=i.completion.commitCharacters||s.result.commitCharacters;return r&&r.indexOf(n.key)>-1&&Yl(e,i),!1}})),Ob=T.baseTheme({".cm-tooltip.cm-tooltip-autocomplete":{"& > ul":{fontFamily:"monospace",whiteSpace:"nowrap",overflow:"hidden auto",maxWidth_fallback:"700px",maxWidth:"min(700px, 95vw)",minWidth:"250px",maxHeight:"10em",height:"100%",listStyle:"none",margin:0,padding:0,"& > li, & > completion-section":{padding:"1px 3px",lineHeight:1.2},"& > li":{overflowX:"hidden",textOverflow:"ellipsis",cursor:"pointer"},"& > completion-section":{display:"list-item",borderBottom:"1px solid silver",paddingLeft:"0.5em",opacity:.7}}},"&light .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#17c",color:"white"},"&light .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:"#777"},"&dark .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#347",color:"white"},"&dark .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:"#444"},".cm-completionListIncompleteTop:before, .cm-completionListIncompleteBottom:after":{content:'"\xB7\xB7\xB7"',opacity:.5,display:"block",textAlign:"center",cursor:"pointer"},".cm-tooltip.cm-completionInfo":{position:"absolute",padding:"3px 9px",width:"max-content",maxWidth:"400px",boxSizing:"border-box",whiteSpace:"pre-line"},".cm-completionInfo.cm-completionInfo-left":{right:"100%"},".cm-completionInfo.cm-completionInfo-right":{left:"100%"},".cm-completionInfo.cm-completionInfo-left-narrow":{right:"30px"},".cm-completionInfo.cm-completionInfo-right-narrow":{left:"30px"},"&light .cm-snippetField":{backgroundColor:"#00000022"},"&dark .cm-snippetField":{backgroundColor:"#ffffff22"},".cm-snippetFieldPosition":{verticalAlign:"text-top",width:0,height:"1.15em",display:"inline-block",margin:"0 -0.7px -.7em",borderLeft:"1.4px dotted #888"},".cm-completionMatchedText":{textDecoration:"underline"},".cm-completionDetail":{marginLeft:"0.5em",fontStyle:"italic"},".cm-completionIcon":{fontSize:"90%",width:".8em",display:"inline-block",textAlign:"center",paddingRight:".6em",opacity:"0.6",boxSizing:"content-box"},".cm-completionIcon-function, .cm-completionIcon-method":{"&:after":{content:"'\u0192'"}},".cm-completionIcon-class":{"&:after":{content:"'\u25CB'"}},".cm-completionIcon-interface":{"&:after":{content:"'\u25CC'"}},".cm-completionIcon-variable":{"&:after":{content:"'\u{1D465}'"}},".cm-completionIcon-constant":{"&:after":{content:"'\u{1D436}'"}},".cm-completionIcon-type":{"&:after":{content:"'\u{1D461}'"}},".cm-completionIcon-enum":{"&:after":{content:"'\u222A'"}},".cm-completionIcon-property":{"&:after":{content:"'\u25A1'"}},".cm-completionIcon-keyword":{"&:after":{content:"'\u{1F511}\uFE0E'"}},".cm-completionIcon-namespace":{"&:after":{content:"'\u25A2'"}},".cm-completionIcon-text":{"&:after":{content:"'abc'",fontSize:"50%",verticalAlign:"middle"}}});var yn={brackets:["(","[","{","'",'"'],before:")]}:;>",stringPrefixes:[]},Gt=R.define({map(n,e){let t=e.mapPos(n,-1,le.TrackAfter);return t??void 0}}),Xl=new class extends Ee{};Xl.startSide=1;Xl.endSide=-1;var Ou=X.define({create(){return F.empty},update(n,e){if(n=n.map(e.changes),e.selection){let t=e.state.doc.lineAt(e.selection.main.head);n=n.update({filter:i=>i>=t.from&&i<=t.to})}for(let t of e.effects)t.is(Gt)&&(n=n.update({add:[Xl.range(t.value,t.value+1)]}));return n}});function Du(){return[Pb,Ou]}var Vl="()[]{}<>\xAB\xBB\xBB\xAB\uFF3B\uFF3D\uFF5B\uFF5D";function Pu(n){for(let e=0;e{if((Db?n.composing:n.compositionStarted)||n.state.readOnly)return!1;let s=n.state.selection.main;if(i.length>2||i.length==2&&Me(ae(i,0))==1||e!=s.from||t!=s.to)return!1;let r=Rb(n.state,i);return r?(n.dispatch(r),!0):!1}),Bb=({state:n,dispatch:e})=>{if(n.readOnly)return!1;let i=Bu(n,n.selection.main.head).brackets||yn.brackets,s=null,r=n.changeByRange(o=>{if(o.empty){let l=Lb(n.doc,o.head);for(let a of i)if(a==l&&er(n.doc,o.head)==Pu(ae(a,0)))return{changes:{from:o.head-a.length,to:o.head+a.length},range:x.cursor(o.head-a.length)}}return{range:s=o}});return s||e(n.update(r,{scrollIntoView:!0,userEvent:"delete.backward"})),!s},Ru=[{key:"Backspace",run:Bb}];function Rb(n,e){let t=Bu(n,n.selection.main.head),i=t.brackets||yn.brackets;for(let s of i){let r=Pu(ae(s,0));if(e==s)return r==s?Nb(n,s,i.indexOf(s+s+s)>-1,t):Eb(n,s,r,t.before||yn.before);if(e==r&&Lu(n,n.selection.main.from))return Ib(n,s,r)}return null}function Lu(n,e){let t=!1;return n.field(Ou).between(0,n.doc.length,i=>{i==e&&(t=!0)}),t}function er(n,e){let t=n.sliceString(e,e+2);return t.slice(0,Me(ae(t,0)))}function Lb(n,e){let t=n.sliceString(e-2,e);return Me(ae(t,0))==t.length?t:t.slice(1)}function Eb(n,e,t,i){let s=null,r=n.changeByRange(o=>{if(!o.empty)return{changes:[{insert:e,from:o.from},{insert:t,from:o.to}],effects:Gt.of(o.to+e.length),range:x.range(o.anchor+e.length,o.head+e.length)};let l=er(n.doc,o.head);return!l||/\s/.test(l)||i.indexOf(l)>-1?{changes:{insert:e+t,from:o.head},effects:Gt.of(o.head+e.length),range:x.cursor(o.head+e.length)}:{range:s=o}});return s?null:n.update(r,{scrollIntoView:!0,userEvent:"input.type"})}function Ib(n,e,t){let i=null,s=n.changeByRange(r=>r.empty&&er(n.doc,r.head)==t?{changes:{from:r.head,to:r.head+t.length,insert:t},range:x.cursor(r.head+t.length)}:i={range:r});return i?null:n.update(s,{scrollIntoView:!0,userEvent:"input.type"})}function Nb(n,e,t,i){let s=i.stringPrefixes||yn.stringPrefixes,r=null,o=n.changeByRange(l=>{if(!l.empty)return{changes:[{insert:e,from:l.from},{insert:e,from:l.to}],effects:Gt.of(l.to+e.length),range:x.range(l.anchor+e.length,l.head+e.length)};let a=l.head,h=er(n.doc,a),c;if(h==e){if(Su(n,a))return{changes:{insert:e+e,from:a},effects:Gt.of(a+e.length),range:x.cursor(a+e.length)};if(Lu(n,a)){let u=t&&n.sliceDoc(a,a+e.length*3)==e+e+e?e+e+e:e;return{changes:{from:a,to:a+u.length,insert:u},range:x.cursor(a+u.length)}}}else{if(t&&n.sliceDoc(a-2*e.length,a)==e+e&&(c=Cu(n,a-2*e.length,s))>-1&&Su(n,c))return{changes:{insert:e+e+e+e,from:a},effects:Gt.of(a+e.length),range:x.cursor(a+e.length)};if(n.charCategorizer(a)(h)!=K.Word&&Cu(n,a,s)>-1&&!Fb(n,a,e,s))return{changes:{insert:e+e,from:a},effects:Gt.of(a+e.length),range:x.cursor(a+e.length)}}return{range:r=l}});return r?null:n.update(o,{scrollIntoView:!0,userEvent:"input.type"})}function Su(n,e){let t=se(n).resolveInner(e+1);return t.parent&&t.from==e}function Fb(n,e,t,i){let s=se(n).resolveInner(e,-1),r=i.reduce((o,l)=>Math.max(o,l.length),0);for(let o=0;o<5;o++){let l=n.sliceDoc(s.from,Math.min(s.to,s.from+t.length+r)),a=l.indexOf(t);if(!a||a>-1&&i.indexOf(l.slice(0,a))>-1){let c=s.firstChild;for(;c&&c.from==s.from&&c.to-c.from>t.length+a;){if(n.sliceDoc(c.to-t.length,c.to)==t)return!1;c=c.firstChild}return!0}let h=s.to==e&&s.parent;if(!h)break;s=h}return!1}function Cu(n,e,t){let i=n.charCategorizer(e);if(i(n.sliceDoc(e-1,e))!=K.Word)return e;for(let s of t){let r=e-s.length;if(n.sliceDoc(r,e)==s&&i(n.sliceDoc(r-1,r))!=K.Word)return r}return-1}function Eu(n={}){return[Tb,ve,re.of(n),Ab,Wb,Ob]}var Ql=[{key:"Ctrl-Space",run:Hl},{mac:"Alt-`",run:Hl},{mac:"Alt-i",run:Hl},{key:"Escape",run:vb},{key:"ArrowDown",run:Ys(!0)},{key:"ArrowUp",run:Ys(!1)},{key:"PageDown",run:Ys(!0,"page")},{key:"PageUp",run:Ys(!1,"page")},{key:"Enter",run:kb}],Wb=ze.highest(Xi.computeN([re],n=>n.facet(re).defaultKeymap?[Ql]:[]));var nr=class{constructor(e,t,i){this.from=e,this.to=t,this.diagnostic=i}},Yt=class n{constructor(e,t,i){this.diagnostics=e,this.panel=t,this.selected=i}static init(e,t,i){let s=i.facet(st).markerFilter;s&&(e=s(e,i));let r=e.slice().sort((d,p)=>d.from-p.from||d.to-p.to),o=new Ae,l=[],a=0,h=i.doc.iter(),c=0,f=i.doc.length;for(let d=0;;){let p=d==r.length?null:r[d];if(!p&&!l.length)break;let m,g;if(l.length)m=a,g=l.reduce((k,D)=>Math.min(k,D.to),p&&p.from>m?p.from:1e8);else{if(m=p.from,m>f)break;g=p.to,l.push(p),d++}for(;dk.from||k.to==m))l.push(k),d++,g=Math.min(k.to,g);else{g=Math.min(k.from,g);break}}g=Math.min(g,f);let b=!1;if(l.some(k=>k.from==m&&(k.to==g||g==f))&&(b=m==g,!b&&g-m<10)){let k=m-(c+h.value.length);k>0&&(h.next(k),c=m);for(let D=m;;){if(D>=g){b=!0;break}if(!h.lineBreak&&c+h.value.length>D)break;D=c+h.value.length,c+=h.value.length,h.next()}}let w=ju(l);if(b)o.add(m,m,P.widget({widget:new Jl(w),diagnostics:l.slice()}));else{let k=l.reduce((D,v)=>v.markClass?D+" "+v.markClass:D,"");o.add(m,g,P.mark({class:"cm-lintRange cm-lintRange-"+w+k,diagnostics:l.slice(),inclusiveEnd:l.some(D=>D.to>g)}))}if(a=g,a==f)break;for(let k=0;k{if(!(e&&o.diagnostics.indexOf(e)<0))if(!i)i=new nr(s,r,e||o.diagnostics[0]);else{if(o.diagnostics.indexOf(i.diagnostic)<0)return!1;i=new nr(i.from,r,i.diagnostic)}}),i}function Fu(n,e){let t=e.pos,i=e.end||t,s=n.state.facet(st).hideOn(n,t,i);if(s!=null)return s;let r=n.startState.doc.lineAt(e.pos);return!!(n.effects.some(o=>o.is(or))||n.changes.touchesRange(r.from,Math.max(r.to,i)))}function Wu(n,e){return n.field(Pe,!1)?e:e.concat(R.appendConfig.of(_u))}function Hb(n,e){return{effects:Wu(n,[or.of(e)])}}var or=R.define(),ea=R.define(),Hu=R.define(),Pe=X.define({create(){return new Yt(P.none,null,null)},update(n,e){if(e.docChanged&&n.diagnostics.size){let t=n.diagnostics.map(e.changes),i=null,s=n.panel;if(n.selected){let r=e.changes.mapPos(n.selected.from,1);i=Mt(t,n.selected.diagnostic,r)||Mt(t,null,r)}!t.size&&s&&e.state.facet(st).autoPanel&&(s=null),n=new Yt(t,s,i)}for(let t of e.effects)if(t.is(or)){let i=e.state.facet(st).autoPanel?t.value.length?xn.open:null:n.panel;n=Yt.init(t.value,i,e.state)}else t.is(ea)?n=new Yt(n.diagnostics,t.value?xn.open:null,n.selected):t.is(Hu)&&(n=new Yt(n.diagnostics,n.panel,t.value));return n},provide:n=>[Ht.from(n,e=>e.panel),T.decorations.from(n,e=>e.diagnostics)]});var Vb=P.mark({class:"cm-lintRange cm-lintRange-active"});function zb(n,e,t){let{diagnostics:i}=n.state.field(Pe),s,r=-1,o=-1;i.between(e-(t<0?1:0),e+(t>0?1:0),(a,h,{spec:c})=>{if(e>=a&&e<=h&&(a==h||(e>a||t>0)&&(eKu(n,t,!1)))}var qb=n=>{let e=n.state.field(Pe,!1);(!e||!e.panel)&&n.dispatch({effects:Wu(n.state,[ea.of(!0)])});let t=Qi(n,xn.open);return t&&t.dom.querySelector(".cm-panel-lint ul").focus(),!0},Iu=n=>{let e=n.state.field(Pe,!1);return!e||!e.panel?!1:(n.dispatch({effects:ea.of(!1)}),!0)},$b=n=>{let e=n.state.field(Pe,!1);if(!e)return!1;let t=n.state.selection.main,i=Mt(e.diagnostics,null,t.to+1);return!i&&(i=Mt(e.diagnostics,null,0),!i||i.from==t.from&&i.to==t.to)?!1:(n.dispatch({selection:{anchor:i.from,head:i.to},scrollIntoView:!0}),Pc(n,i.from,1,{tooltip:Gu,until:s=>s.docChanged||s.newSelection.main.headi.to}),!0)};var zu=[{key:"Mod-Shift-m",run:qb,preventDefault:!0},{key:"F8",run:$b}],Kb=Y.fromClass(class{constructor(n){this.view=n,this.timeout=-1,this.set=!0;let{delay:e}=n.state.facet(st);this.lintTime=Date.now()+e,this.run=this.run.bind(this),this.timeout=setTimeout(this.run,e)}run(){clearTimeout(this.timeout);let n=Date.now();if(nPromise.resolve(i(this.view))),i=>{this.view.state.doc==e.doc&&this.view.dispatch(Hb(this.view.state,i.reduce((s,r)=>s.concat(r))))},i=>{ne(this.view.state,i)})}}update(n){let e=n.state.facet(st);(n.docChanged||e!=n.startState.facet(st)||e.needsRefresh&&e.needsRefresh(n))&&(this.lintTime=Date.now()+e.delay,this.set||(this.set=!0,this.timeout=setTimeout(this.run,e.delay)))}force(){this.set&&(this.lintTime=Date.now(),this.run())}destroy(){clearTimeout(this.timeout)}});function jb(n,e,t){let i=[],s=-1;for(let r of n)r.then(o=>{i.push(o),clearTimeout(s),i.length==n.length?e(i):s=setTimeout(()=>e(i),200)},t)}var st=A.define({combine(n){return{sources:n.map(e=>e.source).filter(e=>e!=null),...he(n.map(e=>e.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null,hideOn:()=>null},{delay:Math.max,markerFilter:Nu,tooltipFilter:Nu,needsRefresh:(e,t)=>e?t?i=>e(i)||t(i):e:t,hideOn:(e,t)=>e?t?(i,s,r)=>e(i,s,r)||t(i,s,r):e:t,autoPanel:(e,t)=>e||t})}}});function Nu(n,e){return n?e?(t,i)=>e(n(t,i),i):n:e}function qu(n,e={}){return[st.of({source:n,config:e}),Kb,_u]}function $u(n){let e=[];if(n)e:for(let{name:t}of n){for(let i=0;ir.toLowerCase()==s.toLowerCase())){e.push(s);continue e}}e.push("")}return e}function Ku(n,e,t){var i;let s=t?$u(e.actions):[];return H("li",{class:"cm-diagnostic cm-diagnostic-"+e.severity},H("span",{class:"cm-diagnosticText"},e.renderMessage?e.renderMessage(n):e.message),(i=e.actions)===null||i===void 0?void 0:i.map((r,o)=>{let l=!1,a=d=>{if(d.preventDefault(),l)return;l=!0;let p=Mt(n.state.field(Pe).diagnostics,e);p&&r.apply(n,p.from,p.to)},{name:h}=r,c=s[o]?h.indexOf(s[o]):-1,f=c<0?h:[h.slice(0,c),H("u",h.slice(c,c+1)),h.slice(c+1)],u=r.markClass?" "+r.markClass:"";return H("button",{type:"button",class:"cm-diagnosticAction"+u,onclick:a,onmousedown:a,"aria-label":` Action: ${h}${c<0?"":` (access key "${s[o]})"`}.`},f)}),e.source&&H("div",{class:"cm-diagnosticSource"},e.source))}var Jl=class extends xe{constructor(e){super(),this.sev=e}eq(e){return e.sev==this.sev}toDOM(){return H("span",{class:"cm-lintPoint cm-lintPoint-"+this.sev})}},sr=class{constructor(e,t){this.diagnostic=t,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=Ku(e,t,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}},xn=class n{constructor(e){this.view=e,this.items=[];let t=s=>{if(!(s.ctrlKey||s.altKey||s.metaKey)){if(s.keyCode==27)Iu(this.view),this.view.focus();else if(s.keyCode==38||s.keyCode==33)this.moveSelection((this.selectedIndex-1+this.items.length)%this.items.length);else if(s.keyCode==40||s.keyCode==34)this.moveSelection((this.selectedIndex+1)%this.items.length);else if(s.keyCode==36)this.moveSelection(0);else if(s.keyCode==35)this.moveSelection(this.items.length-1);else if(s.keyCode==13)this.view.focus();else if(s.keyCode>=65&&s.keyCode<=90&&this.selectedIndex>=0){let{diagnostic:r}=this.items[this.selectedIndex],o=$u(r.actions);for(let l=0;l{for(let r=0;rIu(this.view)},"\xD7")),this.update()}get selectedIndex(){let e=this.view.state.field(Pe).selected;if(!e)return-1;for(let t=0;t{for(let c of h.diagnostics){if(o.has(c))continue;o.add(c);let f=-1,u;for(let d=i;di&&(this.items.splice(i,f-i),s=!0)),t&&u.diagnostic==t.diagnostic?u.dom.hasAttribute("aria-selected")||(u.dom.setAttribute("aria-selected","true"),r=u):u.dom.hasAttribute("aria-selected")&&u.dom.removeAttribute("aria-selected"),i++}});i({sel:r.dom.getBoundingClientRect(),panel:this.list.getBoundingClientRect()}),write:({sel:l,panel:a})=>{let h=a.height/this.list.offsetHeight;l.topa.bottom&&(this.list.scrollTop+=(l.bottom-a.bottom)/h)}})):this.selectedIndex<0&&this.list.removeAttribute("aria-activedescendant"),s&&this.sync()}sync(){let e=this.list.firstChild;function t(){let i=e;e=i.nextSibling,i.remove()}for(let i of this.items)if(i.dom.parentNode==this.list){for(;e!=i.dom;)t();e=i.dom.nextSibling}else this.list.insertBefore(i.dom,e);for(;e;)t()}moveSelection(e){if(this.selectedIndex<0)return;let t=this.view.state.field(Pe),i=Mt(t.diagnostics,this.items[e].diagnostic);i&&this.view.dispatch({selection:{anchor:i.from,head:i.to},scrollIntoView:!0,effects:Hu.of(i)})}static open(e){return new n(e)}};function ir(n,e='viewBox="0 0 40 40"'){return`url('data:image/svg+xml,${encodeURIComponent(n)}')`}function tr(n){return ir(``,'width="6" height="3"')}var Ub=T.baseTheme({".cm-diagnostic":{padding:"3px 6px 3px 8px",marginLeft:"-1px",display:"block",whiteSpace:"pre-wrap"},".cm-diagnostic-error":{borderLeft:"5px solid #d11"},".cm-diagnostic-warning":{borderLeft:"5px solid orange"},".cm-diagnostic-info":{borderLeft:"5px solid #999"},".cm-diagnostic-hint":{borderLeft:"5px solid #66d"},".cm-diagnosticAction":{font:"inherit",border:"none",padding:"2px 4px",backgroundColor:"#444",color:"white",borderRadius:"3px",marginLeft:"8px",cursor:"pointer"},".cm-diagnosticSource":{fontSize:"70%",opacity:.7},".cm-lintRange":{backgroundPosition:"left bottom",backgroundRepeat:"repeat-x",paddingBottom:"0.7px"},".cm-lintRange-error":{backgroundImage:tr("#f11")},".cm-lintRange-warning":{backgroundImage:tr("orange")},".cm-lintRange-info":{backgroundImage:tr("#999")},".cm-lintRange-hint":{backgroundImage:tr("#66d")},".cm-lintRange-active":{backgroundColor:"#ffdd9980"},".cm-tooltip-lint":{padding:0,margin:0},".cm-lintPoint":{position:"relative","&:after":{content:'""',position:"absolute",bottom:0,left:"-2px",borderLeft:"3px solid transparent",borderRight:"3px solid transparent",borderBottom:"4px solid #d11"}},".cm-lintPoint-warning":{"&:after":{borderBottomColor:"orange"}},".cm-lintPoint-info":{"&:after":{borderBottomColor:"#999"}},".cm-lintPoint-hint":{"&:after":{borderBottomColor:"#66d"}},".cm-panel.cm-panel-lint":{position:"relative","& ul":{maxHeight:"100px",overflowY:"auto","& [aria-selected]":{backgroundColor:"#ddd","& u":{textDecoration:"underline"}},"&:focus [aria-selected]":{background_fallback:"#bdf",backgroundColor:"Highlight",color_fallback:"white",color:"HighlightText"},"& u":{textDecoration:"none"},padding:0,margin:0},"& [name=close]":{position:"absolute",top:"0",right:"2px",background:"inherit",border:"none",font:"inherit",padding:0,margin:0}},"&dark .cm-lintRange-active":{backgroundColor:"#86714a80"},"&dark .cm-panel.cm-panel-lint ul":{"& [aria-selected]":{backgroundColor:"#2e343e"}}});function Gb(n){return n=="error"?4:n=="warning"?3:n=="info"?2:1}function ju(n){let e="hint",t=1;for(let i of n){let s=Gb(i.severity);s>t&&(t=s,e=i.severity)}return e}var rr=class extends ke{constructor(e){super(),this.diagnostics=e,this.severity=ju(e)}toDOM(e){let t=document.createElement("div");t.className="cm-lint-marker cm-lint-marker-"+this.severity;let i=this.diagnostics,s=e.state.facet(lr).tooltipFilter;return s&&(i=s(i,e.state)),i.length&&(t.onmouseover=()=>Yb(e,t,i)),t}};function _b(n,e){let t=i=>{let s=e.getBoundingClientRect();if(!(i.clientX>s.left-10&&i.clientXs.top-10&&i.clientYe.getBoundingClientRect()}}})}),e.onmouseout=e.onmousemove=null,_b(n,e)}let{hoverTime:s}=n.state.facet(lr),r=setTimeout(i,s);e.onmouseout=()=>{clearTimeout(r),e.onmouseout=e.onmousemove=null},e.onmousemove=()=>{clearTimeout(r),r=setTimeout(i,s)}}function Xb(n,e){let t=Object.create(null);for(let s of e){let r=n.lineAt(s.from);(t[r.from]||(t[r.from]=[])).push(s)}let i=[];for(let s in t)i.push(new rr(t[s]).range(+s));return F.of(i,!0)}var Qb=ms({class:"cm-gutter-lint",markers:n=>n.state.field(Zl),widgetMarker:(n,e,t)=>{let i=[];return n.state.field(Zl).between(t.from,t.to,(s,r,o)=>{s>t.from&&si.is(ta)?i.value:t,n)},provide:n=>bi.from(n)}),Jb=T.baseTheme({".cm-gutter-lint":{width:"1.4em","& .cm-gutterElement":{padding:".2em"}},".cm-lint-marker":{width:"1em",height:"1em"},".cm-lint-marker-info":{content:ir('')},".cm-lint-marker-warning":{content:ir('')},".cm-lint-marker-error":{content:ir('')}}),Gu=Dc(zb,{hideOn:Fu}),_u=[Pe,T.decorations.compute([Pe],n=>{let{selected:e,panel:t}=n.field(Pe);return!e||!t||e.from==e.to?P.none:P.set([Vb.range(e.from,e.to)])}),Gu,Ub],lr=A.define({combine(n){return he(n,{hoverTime:300,markerFilter:null,tooltipFilter:null})}});function Yu(n={}){return[lr.of(n),Zl,Qb,Jb,Uu]}var Xu=[Nc(),Fc(),Cc(),Pf(),df(),wc(),Sc(),$.allowMultipleSelections.of(!0),sf(),fn(Ps,{fallback:!0}),yf(),Du(),Eu(),Mc(),Tc(),Ac(),uu(),Xi.of([...Ru,...ou,...bu,...Ef,...cf,...Ql,...zu])];var na=class n{constructor(e,t,i,s,r,o,l,a,h,c=0,f){this.p=e,this.stack=t,this.state=i,this.reducePos=s,this.pos=r,this.score=o,this.buffer=l,this.bufferBase=a,this.curContext=h,this.lookAhead=c,this.parent=f}toString(){return`[${this.stack.filter((e,t)=>t%3==0).concat(this.state)}]@${this.pos}${this.score?"!"+this.score:""}`}static start(e,t,i=0){let s=e.parser.context;return new n(e,[],t,i,i,0,[],0,s?new ar(s,s.start):null,0,null)}get context(){return this.curContext?this.curContext.context:null}pushState(e,t){this.stack.push(this.state,t,this.bufferBase+this.buffer.length),this.state=e}reduce(e){var t;let i=e>>19,s=e&65535,{parser:r}=this.p,o=this.reducePos=2e3&&!(!((t=this.p.parser.nodeSet.types[s])===null||t===void 0)&&t.isAnonymous)&&(h==this.p.lastBigReductionStart?(this.p.bigReductionCount++,this.p.lastBigReductionSize=c):this.p.lastBigReductionSizea;)this.stack.pop();this.reduceContext(s,h)}storeNode(e,t,i,s=4,r=!1){if(e==0&&(!this.stack.length||this.stack[this.stack.length-1]0&&this.buffer[o-4]==0&&this.buffer[o-1]>-1){if(t==i)return;if(this.buffer[o-2]>=t){this.buffer[o-2]=i;return}}}if(!r||this.pos==i)this.buffer.push(e,t,i,s);else{let o=this.buffer.length;if(o>0&&(this.buffer[o-4]!=0||this.buffer[o-1]<0)){let l=!1;for(let a=o;a>0&&this.buffer[a-2]>i;a-=4)if(this.buffer[a-1]>=0){l=!0;break}if(l)for(;o>0&&this.buffer[o-2]>i;)this.buffer[o]=this.buffer[o-4],this.buffer[o+1]=this.buffer[o-3],this.buffer[o+2]=this.buffer[o-2],this.buffer[o+3]=this.buffer[o-1],o-=4,s>4&&(s-=4)}this.buffer[o]=e,this.buffer[o+1]=t,this.buffer[o+2]=i,this.buffer[o+3]=s}}shift(e,t,i,s){if(e&131072)this.pushState(e&65535,this.pos);else if((e&262144)==0){let r=e,{parser:o}=this.p;this.pos=s;let l=o.stateFlag(r,1);!l&&(s>i||t<=o.maxNode)&&(this.reducePos=s),this.pushState(r,l?i:Math.min(i,this.reducePos)),this.shiftContext(t,i),t<=o.maxNode&&this.buffer.push(t,i,s,4)}else this.pos=s,this.shiftContext(t,i),t<=this.p.parser.maxNode&&this.buffer.push(t,i,s,4)}apply(e,t,i,s){e&65536?this.reduce(e):this.shift(e,t,i,s)}useNode(e,t){let i=this.p.reused.length-1;(i<0||this.p.reused[i]!=e)&&(this.p.reused.push(e),i++);let s=this.pos;this.reducePos=this.pos=s+e.length,this.pushState(t,s),this.buffer.push(i,s,this.reducePos,-1),this.curContext&&this.updateContext(this.curContext.tracker.reuse(this.curContext.context,e,this,this.p.stream.reset(this.pos-e.length)))}split(){let e=this,t=e.buffer.length;for(t&&e.buffer[t-4]==0&&(t-=4);t>0&&e.buffer[t-2]>e.reducePos;)t-=4;let i=e.buffer.slice(t),s=e.bufferBase+t;for(;e&&s==e.bufferBase;)e=e.parent;return new n(this.p,this.stack.slice(),this.state,this.reducePos,this.pos,this.score,i,s,this.curContext,this.lookAhead,e)}recoverByDelete(e,t){let i=e<=this.p.parser.maxNode;i&&this.storeNode(e,this.pos,t,4),this.storeNode(0,this.pos,t,i?8:4),this.pos=this.reducePos=t,this.score-=190}canShift(e){for(let t=new sa(this);;){let i=this.p.parser.stateSlot(t.state,4)||this.p.parser.hasAction(t.state,e);if(i==0)return!1;if((i&65536)==0)return!0;t.reduce(i)}}recoverByInsert(e){if(this.stack.length>=300)return[];let t=this.p.parser.nextStates(this.state);if(t.length>8||this.stack.length>=120){let s=[];for(let r=0,o;ra&1&&l==o)||s.push(t[r],o)}t=s}let i=[];for(let s=0;s>19,s=t&65535,r=this.stack.length-i*3;if(r<0||e.getGoto(this.stack[r],s,!1)<0){let o=this.findForcedReduction();if(o==null)return!1;t=o}this.storeNode(0,this.pos,this.pos,4,!0),this.score-=100}return this.reducePos=this.pos,this.reduce(t),!0}findForcedReduction(){let{parser:e}=this.p,t=[],i=(s,r)=>{if(!t.includes(s))return t.push(s),e.allActions(s,o=>{if(!(o&393216))if(o&65536){let l=(o>>19)-r;if(l>1){let a=o&65535,h=this.stack.length-l*3;if(h>=0&&e.getGoto(this.stack[h],a,!1)>=0)return l<<19|65536|a}}else{let l=i(o,r+1);if(l!=null)return l}})};return i(this.state,0)}forceAll(){for(;!this.p.parser.stateFlag(this.state,2);)if(!this.forceReduce()){this.storeNode(0,this.pos,this.pos,4,!0);break}return this}get deadEnd(){if(this.stack.length!=3)return!1;let{parser:e}=this.p;return e.data[e.stateSlot(this.state,1)]==65535&&!e.stateSlot(this.state,4)}restart(){this.storeNode(0,this.pos,this.pos,4,!0),this.state=this.stack[0],this.stack.length=0}sameState(e){if(this.state!=e.state||this.stack.length!=e.stack.length)return!1;for(let t=0;t0&&this.emitLookAhead()}},ar=class{constructor(e,t){this.tracker=e,this.context=t,this.hash=e.strict?e.hash(t):0}},sa=class{constructor(e){this.start=e,this.state=e.state,this.stack=e.stack,this.base=this.stack.length}reduce(e){let t=e&65535,i=e>>19;i==0?(this.stack==this.start.stack&&(this.stack=this.stack.slice()),this.stack.push(this.state,0,0),this.base+=3):this.base-=(i-1)*3;let s=this.start.p.parser.getGoto(this.stack[this.base-3],t,!0);this.state=s}},ra=class n{constructor(e,t,i){this.stack=e,this.pos=t,this.index=i,this.buffer=e.buffer,this.index==0&&this.maybeNext()}static create(e,t=e.bufferBase+e.buffer.length){return new n(e,t,t-e.bufferBase)}maybeNext(){let e=this.stack.parent;e!=null&&(this.index=this.stack.bufferBase-e.bufferBase,this.stack=e,this.buffer=e.buffer)}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}next(){this.index-=4,this.pos-=4,this.index==0&&this.maybeNext()}fork(){return new n(this.stack,this.pos,this.index)}};function wn(n,e=Uint16Array){if(typeof n!="string")return n;let t=null;for(let i=0,s=0;i=92&&o--,o>=34&&o--;let a=o-32;if(a>=46&&(a-=46,l=!0),r+=a,l)break;r*=46}t?t[s++]=r:t=new e(r)}return t}var Mi=class{constructor(){this.start=-1,this.value=-1,this.end=-1,this.extended=-1,this.lookAhead=0,this.mask=0,this.context=0}},Qu=new Mi,oa=class{constructor(e,t){this.input=e,this.ranges=t,this.chunk="",this.chunkOff=0,this.chunk2="",this.chunk2Pos=0,this.next=-1,this.token=Qu,this.rangeIndex=0,this.pos=this.chunkPos=t[0].from,this.range=t[0],this.end=t[t.length-1].to,this.readNext()}resolveOffset(e,t){let i=this.range,s=this.rangeIndex,r=this.pos+e;for(;ri.to:r>=i.to;){if(s==this.ranges.length-1)return null;let o=this.ranges[++s];r+=o.from-i.to,i=o}return r}clipPos(e){if(e>=this.range.from&&ee)return Math.max(e,t.from);return this.end}peek(e){let t=this.chunkOff+e,i,s;if(t>=0&&t=this.chunk2Pos&&il.to&&(this.chunk2=this.chunk2.slice(0,l.to-i)),s=this.chunk2.charCodeAt(0)}}return i>=this.token.lookAhead&&(this.token.lookAhead=i+1),s}acceptToken(e,t=0){let i=t?this.resolveOffset(t,-1):this.pos;if(i==null||i=this.chunk2Pos&&this.posthis.range.to?e.slice(0,this.range.to-this.pos):e,this.chunkPos=this.pos,this.chunkOff=0}}readNext(){return this.chunkOff>=this.chunk.length&&(this.getChunk(),this.chunkOff==this.chunk.length)?this.next=-1:this.next=this.chunk.charCodeAt(this.chunkOff)}advance(e=1){for(this.chunkOff+=e;this.pos+e>=this.range.to;){if(this.rangeIndex==this.ranges.length-1)return this.setDone();e-=this.range.to-this.pos,this.range=this.ranges[++this.rangeIndex],this.pos=this.range.from}return this.pos+=e,this.pos>=this.token.lookAhead&&(this.token.lookAhead=this.pos+1),this.readNext()}setDone(){return this.pos=this.chunkPos=this.end,this.range=this.ranges[this.rangeIndex=this.ranges.length-1],this.chunk="",this.next=-1}reset(e,t){if(t?(this.token=t,t.start=e,t.lookAhead=e+1,t.value=t.extended=-1):this.token=Qu,this.pos!=e){if(this.pos=e,e==this.end)return this.setDone(),this;for(;e=this.range.to;)this.range=this.ranges[++this.rangeIndex];e>=this.chunkPos&&e=this.chunkPos&&t<=this.chunkPos+this.chunk.length)return this.chunk.slice(e-this.chunkPos,t-this.chunkPos);if(e>=this.chunk2Pos&&t<=this.chunk2Pos+this.chunk2.length)return this.chunk2.slice(e-this.chunk2Pos,t-this.chunk2Pos);if(e>=this.range.from&&t<=this.range.to)return this.input.read(e,t);let i="";for(let s of this.ranges){if(s.from>=t)break;s.to>e&&(i+=this.input.read(Math.max(s.from,e),Math.min(s.to,t)))}return i}},Tt=class{constructor(e,t){this.data=e,this.id=t}token(e,t){let{parser:i}=t.p;id(this.data,e,t,this.id,i.data,i.tokenPrecTable)}};Tt.prototype.contextual=Tt.prototype.fallback=Tt.prototype.extend=!1;var la=class{constructor(e,t,i){this.precTable=t,this.elseToken=i,this.data=typeof e=="string"?wn(e):e}token(e,t){let i=e.pos,s=0;for(;;){let r=e.next<0,o=e.resolveOffset(1,1);if(id(this.data,e,t,0,this.data,this.precTable),e.token.value>-1)break;if(this.elseToken==null)return;if(r||s++,o==null)break;e.reset(o,e.token)}s&&(e.reset(i,e.token),e.acceptToken(this.elseToken,s))}};la.prototype.contextual=Tt.prototype.fallback=Tt.prototype.extend=!1;function id(n,e,t,i,s,r){let o=0,l=1<0){let p=n[d];if(a.allows(p)&&(e.token.value==-1||e.token.value==p||ey(p,e.token.value,s,r))){e.acceptToken(p);break}}let c=e.next,f=0,u=n[o+2];if(e.next<0&&u>f&&n[h+u*3-3]==65535){o=n[h+u*3-1];continue e}for(;f>1,p=h+d+(d<<1),m=n[p],g=n[p+1]||65536;if(c=g)f=d+1;else{o=n[p+2],e.advance();continue e}}break}}function Ju(n,e,t){for(let i=e,s;(s=n[i])!=65535;i++)if(s==t)return i-e;return-1}function ey(n,e,t,i){let s=Ju(t,i,e);return s<0||Ju(t,i,n)e)&&!i.type.isError)return t<0?Math.max(0,Math.min(i.to-1,e-25)):Math.min(n.length,Math.max(i.from+1,e+25));if(t<0?i.prevSibling():i.nextSibling())break;if(!i.parent())return t<0?0:n.length}}var aa=class{constructor(e,t){this.fragments=e,this.nodeSet=t,this.i=0,this.fragment=null,this.safeFrom=-1,this.safeTo=-1,this.trees=[],this.start=[],this.index=[],this.nextFragment()}nextFragment(){let e=this.fragment=this.i==this.fragments.length?null:this.fragments[this.i++];if(e){for(this.safeFrom=e.openStart?Zu(e.tree,e.from+e.offset,1)-e.offset:e.from,this.safeTo=e.openEnd?Zu(e.tree,e.to+e.offset,-1)-e.offset:e.to;this.trees.length;)this.trees.pop(),this.start.pop(),this.index.pop();this.trees.push(e.tree),this.start.push(-e.offset),this.index.push(0),this.nextStart=this.safeFrom}else this.nextStart=1e9}nodeAt(e){if(ee)return this.nextStart=o,null;if(r instanceof Z){if(o==e){if(o=Math.max(this.safeFrom,e)&&(this.trees.push(r),this.start.push(o),this.index.push(0))}else this.index[t]++,this.nextStart=o+r.length}}},ha=class{constructor(e,t){this.stream=t,this.tokens=[],this.mainToken=null,this.actions=[],this.tokens=e.tokenizers.map(i=>new Mi)}getActions(e){let t=0,i=null,{parser:s}=e.p,{tokenizers:r}=s,o=s.stateSlot(e.state,3),l=e.curContext?e.curContext.hash:0,a=0;for(let h=0;hf.end+25&&(a=Math.max(f.lookAhead,a)),f.value!=0)){let u=t;if(f.extended>-1&&(t=this.addActions(e,f.extended,f.end,t)),t=this.addActions(e,f.value,f.end,t),!c.extend&&(i=f,t>u))break}}for(;this.actions.length>t;)this.actions.pop();return a&&e.setLookAhead(a),!i&&e.pos==this.stream.end&&(i=new Mi,i.value=e.p.parser.eofTerm,i.start=i.end=e.pos,t=this.addActions(e,i.value,i.end,t)),this.mainToken=i,this.actions}getMainToken(e){if(this.mainToken)return this.mainToken;let t=new Mi,{pos:i,p:s}=e;return t.start=i,t.end=Math.min(i+1,s.stream.end),t.value=i==s.stream.end?s.parser.eofTerm:0,t}updateCachedToken(e,t,i){let s=this.stream.clipPos(i.pos);if(t.token(this.stream.reset(s,e),i),e.value>-1){let{parser:r}=i.p;for(let o=0;o=0&&i.p.parser.dialect.allows(l>>1)){(l&1)==0?e.value=l>>1:e.extended=l>>1;break}}}else e.value=0,e.end=this.stream.clipPos(s+1)}putAction(e,t,i,s){for(let r=0;re.bufferLength*4?new aa(i,e.nodeSet):null}get parsedPos(){return this.minStackPos}advance(){let e=this.stacks,t=this.minStackPos,i=this.stacks=[],s,r;if(this.bigReductionCount>300&&e.length==1){let[o]=e;for(;o.forceReduce()&&o.stack.length&&o.stack[o.stack.length-2]>=this.lastBigReductionStart;);this.bigReductionCount=this.lastBigReductionSize=0}for(let o=0;ot)i.push(l);else{if(this.advanceStack(l,i,e))continue;{s||(s=[],r=[]),s.push(l);let a=this.tokens.getMainToken(l);r.push(a.value,a.end)}}break}}if(!i.length){let o=s&&ty(s);if(o)return Be&&console.log("Finish with "+this.stackID(o)),this.stackToTree(o);if(this.parser.strict)throw Be&&s&&console.log("Stuck with token "+(this.tokens.mainToken?this.parser.getName(this.tokens.mainToken.value):"none")),new SyntaxError("No parse at "+t);this.recovering||(this.recovering=5)}if(this.recovering&&s){let o=this.stoppedAt!=null&&s[0].pos>this.stoppedAt?s[0]:this.runRecovery(s,r,i);if(o)return Be&&console.log("Force-finish "+this.stackID(o)),this.stackToTree(o.forceAll())}if(this.recovering){let o=this.recovering==1?1:this.recovering*3;if(i.length>o)for(i.sort((l,a)=>a.score-l.score);i.length>o;)i.pop();i.some(l=>l.reducePos>t)&&this.recovering--}else if(i.length>1){e:for(let o=0;o500&&h.buffer.length>500)if((l.score-h.score||l.buffer.length-h.buffer.length)>0)i.splice(a--,1);else{i.splice(o--,1);continue e}}}i.length>12&&(i.sort((o,l)=>l.score-o.score),i.splice(12,i.length-12))}this.minStackPos=i[0].pos;for(let o=1;o ":"";if(this.stoppedAt!=null&&s>this.stoppedAt)return e.forceReduce()?e:null;if(this.fragments){let h=e.curContext&&e.curContext.tracker.strict,c=h?e.curContext.hash:0;for(let f=this.fragments.nodeAt(s);f;){let u=this.parser.nodeSet.types[f.type.id]==f.type?r.getGoto(e.state,f.type.id):-1;if(u>-1&&f.length&&(!h||(f.prop(L.contextHash)||0)==c))return e.useNode(f,u),Be&&console.log(o+this.stackID(e)+` (via reuse of ${r.getName(f.type.id)})`),!0;if(!(f instanceof Z)||f.children.length==0||f.positions[0]>0)break;let d=f.children[0];if(d instanceof Z&&f.positions[0]==0)f=d;else break}}let l=r.stateSlot(e.state,4);if(l>0)return e.reduce(l),Be&&console.log(o+this.stackID(e)+` (via always-reduce ${r.getName(l&65535)})`),!0;if(e.stack.length>=8400)for(;e.stack.length>6e3&&e.forceReduce(););let a=this.tokens.getActions(e);for(let h=0;hs?t.push(p):i.push(p)}return!1}advanceFully(e,t){let i=e.pos;for(;;){if(!this.advanceStack(e,null,null))return!1;if(e.pos>i)return ed(e,t),!0}}runRecovery(e,t,i){let s=null,r=!1;for(let o=0;o ":"";if(l.deadEnd&&(r||(r=!0,l.restart(),Be&&console.log(c+this.stackID(l)+" (restarted)"),this.advanceFully(l,i))))continue;let f=l.split(),u=c;for(let d=0;d<10&&f.forceReduce()&&(Be&&console.log(u+this.stackID(f)+" (via force-reduce)"),!this.advanceFully(f,i));d++)Be&&(u=this.stackID(f)+" -> ");for(let d of l.recoverByInsert(a))Be&&console.log(c+this.stackID(d)+" (via recover-insert)"),this.advanceFully(d,i);this.stream.end>l.pos?(h==l.pos&&(h++,a=0),l.recoverByDelete(a,h),Be&&console.log(c+this.stackID(l)+` (via recover-delete ${this.parser.getName(a)})`),ed(l,i)):(!s||s.scoree.topRules[l][1]),s=[];for(let l=0;l=0)r(c,a,l[h++]);else{let f=l[h+-c];for(let u=-c;u>0;u--)r(l[h++],a,f);h++}}}this.nodeSet=new Zi(t.map((l,a)=>ue.define({name:a>=this.minRepeatTerm?void 0:l,id:a,props:s[a],top:i.indexOf(a)>-1,error:a==0,skipped:e.skippedNodes&&e.skippedNodes.indexOf(a)>-1}))),e.propSources&&(this.nodeSet=this.nodeSet.extend(...e.propSources)),this.strict=!1,this.bufferLength=1024;let o=wn(e.tokenData);this.context=e.context,this.specializerSpecs=e.specialized||[],this.specialized=new Uint16Array(this.specializerSpecs.length);for(let l=0;ltypeof l=="number"?new Tt(o,l):l),this.topRules=e.topRules,this.dialects=e.dialects||{},this.dynamicPrecedences=e.dynamicPrecedences||null,this.tokenPrecTable=e.tokenPrec,this.termNames=e.termNames||null,this.maxNode=this.nodeSet.types.length-1,this.dialect=this.parseDialect(),this.top=this.topRules[Object.keys(this.topRules)[0]]}createParse(e,t,i){let s=new ca(this,e,t,i);for(let r of this.wrappers)s=r(s,e,t,i);return s}getGoto(e,t,i=!1){let s=this.goto;if(t>=s[0])return-1;for(let r=s[t+1];;){let o=s[r++],l=o&1,a=s[r++];if(l&&i)return a;for(let h=r+(o>>1);r0}validAction(e,t){return!!this.allActions(e,i=>i==t?!0:null)}allActions(e,t){let i=this.stateSlot(e,4),s=i?t(i):void 0;for(let r=this.stateSlot(e,1);s==null;r+=3){if(this.data[r]==65535)if(this.data[r+1]==1)r=dt(this.data,r+2);else break;s=t(dt(this.data,r+1))}return s}nextStates(e){let t=[];for(let i=this.stateSlot(e,1);;i+=3){if(this.data[i]==65535)if(this.data[i+1]==1)i=dt(this.data,i+2);else break;if((this.data[i+2]&1)==0){let s=this.data[i+1];t.some((r,o)=>o&1&&r==s)||t.push(this.data[i],s)}}return t}configure(e){let t=Object.assign(Object.create(n.prototype),this);if(e.props&&(t.nodeSet=this.nodeSet.extend(...e.props)),e.top){let i=this.topRules[e.top];if(!i)throw new RangeError(`Invalid top rule name ${e.top}`);t.top=i}return e.tokenizers&&(t.tokenizers=this.tokenizers.map(i=>{let s=e.tokenizers.find(r=>r.from==i);return s?s.to:i})),e.specializers&&(t.specializers=this.specializers.slice(),t.specializerSpecs=this.specializerSpecs.map((i,s)=>{let r=e.specializers.find(l=>l.from==i.external);if(!r)return i;let o=Object.assign(Object.assign({},i),{external:r.to});return t.specializers[s]=td(o),o})),e.contextTracker&&(t.context=e.contextTracker),e.dialect&&(t.dialect=this.parseDialect(e.dialect)),e.strict!=null&&(t.strict=e.strict),e.wrap&&(t.wrappers=t.wrappers.concat(e.wrap)),e.bufferLength!=null&&(t.bufferLength=e.bufferLength),t}hasWrappers(){return this.wrappers.length>0}getName(e){return this.termNames?this.termNames[e]:String(e<=this.maxNode&&this.nodeSet.types[e].name||e)}get eofTerm(){return this.maxNode+1}get topNode(){return this.nodeSet.types[this.top[1]]}dynamicPrecedence(e){let t=this.dynamicPrecedences;return t==null?0:t[e]||0}parseDialect(e){let t=Object.keys(this.dialects),i=t.map(()=>!1);if(e)for(let r of e.split(" ")){let o=t.indexOf(r);o>=0&&(i[o]=!0)}let s=null;for(let r=0;ri)&&t.p.parser.stateFlag(t.state,2)&&(!e||e.scoren.external(t,i)<<1|e}return n.get}var iy=Ss({String:y.string,Number:y.number,"True False":y.bool,PropertyName:y.propertyName,Null:y.null,", :":y.separator,"[ ]":y.squareBracket,"{ }":y.brace}),nd=hr.deserialize({version:14,states:"$bOVQPOOOOQO'#Cb'#CbOnQPO'#CeOvQPO'#ClOOQO'#Cr'#CrQOQPOOOOQO'#Cg'#CgO}QPO'#CfO!SQPO'#CtOOQO,59P,59PO![QPO,59PO!aQPO'#CuOOQO,59W,59WO!iQPO,59WOVQPO,59QOqQPO'#CmO!nQPO,59`OOQO1G.k1G.kOVQPO'#CnO!vQPO,59aOOQO1G.r1G.rOOQO1G.l1G.lOOQO,59X,59XOOQO-E6k-E6kOOQO,59Y,59YOOQO-E6l-E6l",stateData:"#O~OeOS~OQSORSOSSOTSOWQO_ROgPO~OVXOgUO~O^[O~PVO[^O~O]_OVhX~OVaO~O]bO^iX~O^dO~O]_OVha~O]bO^ia~O",goto:"!kjPPPPPPkPPkqwPPPPk{!RPPP!XP!e!hXSOR^bQWQRf_TVQ_Q`WRg`QcZRicQTOQZRQe^RhbRYQR]R",nodeNames:"\u26A0 JsonText True False Null Number String } { Object Property PropertyName : , ] [ Array",maxTerm:25,nodeProps:[["isolate",-2,6,11,""],["openedBy",7,"{",14,"["],["closedBy",8,"}",15,"]"]],propSources:[iy],skippedNodes:[0],repeatNodeCount:2,tokenData:"(|~RaXY!WYZ!W]^!Wpq!Wrs!]|}$u}!O$z!Q!R%T!R![&c![!]&t!}#O&y#P#Q'O#Y#Z'T#b#c'r#h#i(Z#o#p(r#q#r(w~!]Oe~~!`Wpq!]qr!]rs!xs#O!]#O#P!}#P;'S!];'S;=`$o<%lO!]~!}Og~~#QXrs!]!P!Q!]#O#P!]#U#V!]#Y#Z!]#b#c!]#f#g!]#h#i!]#i#j#m~#pR!Q![#y!c!i#y#T#Z#y~#|R!Q![$V!c!i$V#T#Z$V~$YR!Q![$c!c!i$c#T#Z$c~$fR!Q![!]!c!i!]#T#Z!]~$rP;=`<%l!]~$zO]~~$}Q!Q!R%T!R![&c~%YRT~!O!P%c!g!h%w#X#Y%w~%fP!Q![%i~%nRT~!Q![%i!g!h%w#X#Y%w~%zR{|&T}!O&T!Q![&Z~&WP!Q![&Z~&`PT~!Q![&Z~&hST~!O!P%c!Q![&c!g!h%w#X#Y%w~&yO[~~'OO_~~'TO^~~'WP#T#U'Z~'^P#`#a'a~'dP#g#h'g~'jP#X#Y'm~'rOR~~'uP#i#j'x~'{P#`#a(O~(RP#`#a(U~(ZOS~~(^P#f#g(a~(dP#i#j(g~(jP#X#Y(m~(rOQ~~(wOW~~(|OV~",tokenizers:[0],topRules:{JsonText:[0,1]},tokenPrec:0});var sd=()=>n=>{try{JSON.parse(n.state.doc.toString())}catch(e){if(!(e instanceof SyntaxError))throw e;let t=ny(e,n.state.doc);return[{from:t,message:e.message,severity:"error",to:t}]}return[]};function ny(n,e){let t;return(t=n.message.match(/at position (\d+)/))?Math.min(+t[1],e.length):(t=n.message.match(/at line (\d+) column (\d+)/))?Math.min(e.line(+t[1]).from+ +t[2]-1,e.length):0}var sy=Cs.define({name:"json",parser:nd.configure({props:[bl.add({Object:yl({except:/^\s*\}/}),Array:yl({except:/^\s*\]/})}),xl.add({"Object Array":rf})]}),languageData:{closeBrackets:{brackets:["[","{",'"']},indentOnInput:/^\s*[\}\]]$/}});function rd(){return new As(sy)}var ry="#e5c07b",od="#e06c75",oy="#56b6c2",ly="#ffffff",ay="#abb2bf",ld="#7d8799",hy="#61afef",cy="#98c379",ad="#d19a66",fy="#c678dd";var hd=wi.define([{tag:y.keyword,color:fy},{tag:[y.name,y.deleted,y.character,y.propertyName,y.macroName],color:od},{tag:[y.function(y.variableName),y.labelName],color:hy},{tag:[y.color,y.constant(y.name),y.standard(y.name)],color:ad},{tag:[y.definition(y.name),y.separator],color:ay},{tag:[y.typeName,y.className,y.number,y.changed,y.annotation,y.modifier,y.self,y.namespace],color:ry},{tag:[y.operator,y.operatorKeyword,y.url,y.escape,y.regexp,y.link,y.special(y.string)],color:oy},{tag:[y.meta,y.comment],color:ld},{tag:y.strong,fontWeight:"bold"},{tag:y.emphasis,fontStyle:"italic"},{tag:y.strikethrough,textDecoration:"line-through"},{tag:y.link,color:ld,textDecoration:"underline"},{tag:y.heading,fontWeight:"bold",color:od},{tag:[y.atom,y.bool,y.special(y.variableName)],color:ad},{tag:[y.processingInstruction,y.string,y.inserted],color:cy},{tag:y.invalid,color:ly}]);return md(uy);})(); diff --git a/src/mujoco_mojo/utils/layers/dojo/templates/static/vendored/litegraph.min.css b/src/mujoco_mojo/utils/layers/dojo/templates/static/vendored/litegraph.min.css new file mode 100644 index 00000000..e4a0dcf7 --- /dev/null +++ b/src/mujoco_mojo/utils/layers/dojo/templates/static/vendored/litegraph.min.css @@ -0,0 +1,8 @@ +/** + * Minified by jsDelivr using clean-css v5.3.3. + * Original file: /npm/litegraph.js@0.7.18/css/litegraph.css + * + * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files + */ +.lgraphcanvas{user-select:none;-moz-user-select:none;-webkit-user-select:none;outline:0;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 #000!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 #000;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:.5;cursor:default}.litegraph .litemenu-entry.separator{display:block;border-top:1px solid #333;border-bottom:1px solid #666;width:100%;height:0;margin:3px 0 2px 0;background-color:transparent;padding:0!important;cursor:default!important}.litegraph .litemenu-entry.has_submenu{border-right:2px solid #0ff}.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 .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,.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,.5);padding-top:4px}.litegraph.litesearchbox input,.litegraph.litesearchbox select{margin-top:3px;min-width:60px;min-height:1.5em;background-color:#000;border:0;color:#fff;padding-left:10px;margin-right:5px}.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,.5);color:#fff;padding-top:2px}.litegraph.lite-search-item.not_in_filter{color:#b99;font-style:italic}.litegraph.lite-search-item.generic_type{color:#999;font-style:italic}.litegraph.lite-search-item.selected,.litegraph.lite-search-item:hover{cursor:pointer;background-color:#fff;color:#000}.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:#fff}.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-alt-content,.litegraph .dialog .dialog-content{height:calc(100% - 90px);width:100%;min-height:100px;display:inline-block;color:#aaa;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:#000;display:flex}.litegraph .dialog .node_type{font-size:1.2em;display:block;margin:10px}.litegraph .dialog .node_desc{opacity:.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:#fff}.litegraph .dialog .property_value{display:inline-block;text-align:right;color:#aaa;background-color:#1a1a1a;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:#fff}.litegraph .dialog .property.boolean .property_value{padding-right:30px;color:#a88}.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:0;background-color:#060606;color:#8e8e8e}.litegraph .dialog .btn:hover{background-color:#111;color:#fff}.litegraph .dialog .btn.delete:hover{background-color:#f33;color:#000}.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:.5;margin-right:20px;padding-left:4px}.litegraph .subgraph_property span.label{display:inline-block;width:60px;padding:0 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 .1s ease 0s;-moz-transition:background-color .1s ease 0s}.litegraph .bullet_icon:hover{background-color:#698;cursor:pointer}.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 .3s}.graphmenu-entry.event,.litemenu-entry.event{border-left:8px solid orange;padding-left:12px}.graphmenu-entry.disabled{opacity:.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,.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 #000!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 select,.graphdialog textarea{margin:3px;min-width:60px;min-height:1.5em;background-color:#000;border:0;color:#fff;padding-left:10px;outline:0}.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.selected,.graphdialog .help-item:hover{cursor:pointer;background-color:#fff;color:#000}.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} +/*# sourceMappingURL=/sm/d0bf782f349fcc0193a2bfe11aa3dab77155a28e977ec97b561e504a3c8ccc8e.map */ \ No newline at end of file diff --git a/src/mujoco_mojo/utils/layers/dojo/templates/static/vendored/litegraph.min.js b/src/mujoco_mojo/utils/layers/dojo/templates/static/vendored/litegraph.min.js new file mode 100644 index 00000000..3cdfbb34 --- /dev/null +++ b/src/mujoco_mojo/utils/layers/dojo/templates/static/vendored/litegraph.min.js @@ -0,0 +1,915 @@ +var $jscomp=$jscomp||{};$jscomp.scope={};$jscomp.ASSUME_ES5=!1;$jscomp.ASSUME_NO_NATIVE_MAP=!1;$jscomp.ASSUME_NO_NATIVE_SET=!1;$jscomp.defineProperty=$jscomp.ASSUME_ES5||"function"==typeof Object.defineProperties?Object.defineProperty:function(y,c,k){y!=Array.prototype&&y!=Object.prototype&&(y[c]=k.value)};$jscomp.getGlobal=function(y){return"undefined"!=typeof window&&window===y?y:"undefined"!=typeof global&&null!=global?global:y};$jscomp.global=$jscomp.getGlobal(this);$jscomp.SYMBOL_PREFIX="jscomp_symbol_"; +$jscomp.initSymbol=function(){$jscomp.initSymbol=function(){};$jscomp.global.Symbol||($jscomp.global.Symbol=$jscomp.Symbol)};$jscomp.Symbol=function(){var y=0;return function(c){return $jscomp.SYMBOL_PREFIX+(c||"")+y++}}(); +$jscomp.initSymbolIterator=function(){$jscomp.initSymbol();var y=$jscomp.global.Symbol.iterator;y||(y=$jscomp.global.Symbol.iterator=$jscomp.global.Symbol("iterator"));"function"!=typeof Array.prototype[y]&&$jscomp.defineProperty(Array.prototype,y,{configurable:!0,writable:!0,value:function(){return $jscomp.arrayIterator(this)}});$jscomp.initSymbolIterator=function(){}};$jscomp.arrayIterator=function(y){var c=0;return $jscomp.iteratorPrototype(function(){return ck&&(k=Math.max(0,r+k));if(null==n||n>r)n=r;n=Number(n);0>n&&(n=Math.max(0,r+n));for(k=Number(k||0);k=u}},"es6","es3");$jscomp.findInternal=function(y,c,k){y instanceof String&&(y=String(y));for(var n=y.length,r=0;rc?-k:k}},"es6","es3"); +(function(y){function c(a){e.debug&&console.log("Graph created");this.list_of_graphcanvas=null;this.clear();a&&this.configure(a)}function k(a,b,d,f,g,e){this.id=a;this.type=b;this.origin_id=d;this.origin_slot=f;this.target_id=g;this.target_slot=e;this._data=null;this._pos=new Float32Array(2)}function n(a){this._ctor(a)}function r(a){this._ctor(a)}function u(a,b){this.offset=new Float32Array([0,0]);this.scale=1;this.max_scale=10;this.min_scale=.1;this.onredraw=null;this.enabled=!0;this.last_mouse= +[0,0];this.element=null;this.visible_area=new Float32Array(4);a&&(this.element=a,b||this.bindEvents(a))}function h(a,b,d){this.options=d=d||{};this.background_image=h.DEFAULT_BACKGROUND_IMAGE;a&&a.constructor===String&&(a=document.querySelector(a));this.ds=new u;this.zoom_modify_alpha=!0;this.title_text_font=""+e.NODE_TEXT_SIZE+"px Arial";this.inner_text_font="normal "+e.NODE_SUBTEXT_SIZE+"px Arial";this.node_title_color=e.NODE_TITLE_COLOR;this.default_link_color=e.LINK_COLOR;this.default_connection_color= +{input_off:"#778",input_on:"#7F7",output_off:"#778",output_on:"#7F7"};this.default_connection_color_byType={};this.default_connection_color_byTypeOff={};this.highquality_render=!0;this.use_gradients=!1;this.editor_alpha=1;this.pause_rendering=!1;this.clear_background=!0;this.clear_background_color="#222";this.read_only=!1;this.render_only_selected=!0;this.live_mode=!1;this.allow_interaction=this.allow_dragnodes=this.allow_dragcanvas=this.show_info=!0;this.multi_select=!1;this.allow_reconnect_links= +this.allow_searchbox=!0;this.drag_mode=this.align_to_grid=!1;this.filter=this.dragging_rectangle=null;this.set_canvas_dirty_on_mouse_event=!0;this.always_render_background=!1;this.render_canvas_border=this.render_shadows=!0;this.render_connections_shadows=!1;this.render_connections_border=!0;this.render_connection_arrows=this.render_curved_connections=!1;this.render_collapsed_slots=!0;this.render_execution_order=!1;this.render_link_tooltip=this.render_title_colored=!0;this.links_render_mode=e.SPLINE_LINK; +this.mouse=[0,0];this.canvas_mouse=this.graph_mouse=[0,0];this.onAfterChange=this.onBeforeChange=this.onConnectingChange=this.onSelectionChange=this.onNodeMoved=this.onDrawLinkTooltip=this.onDrawOverlay=this.onDrawForeground=this.onDrawBackground=this.onMouse=this.onSearchBoxSelection=this.onSearchBox=null;this.connections_width=3;this.round_radius=8;this.over_link_center=this.node_widget=this.current_node=null;this.last_mouse_position=[0,0];this.visible_area=this.ds.visible_area;this.visible_links= +[];this.viewport=d.viewport||null;b&&b.attachCanvas(this);this.setCanvas(a,d.skip_events);this.clear();d.skip_render||this.startRendering();this.autoresize=d.autoresize}function E(a,b){return Math.sqrt((b[0]-a[0])*(b[0]-a[0])+(b[1]-a[1])*(b[1]-a[1]))}function D(a,b,d,f,g,e){return da&&fb?!0:!1}function J(a,b){var d=a[0]+a[2],f=a[1]+a[3],g=b[1]+b[3];return a[0]>b[0]+b[2]||a[1]>g||dz.width-c.width-10&&(g=z.width-c.width-10),z.height&&a>z.height-c.height-10&&(a=z.height-c.height-10));q.style.left=g+"px";q.style.top=a+"px";b.scale&&(q.style.transform="scale("+b.scale+")")}function H(a){this.points=a;this.nearest=this.selected=-1;this.size=null;this.must_update=!0;this.margin=5}function F(a,b,d){return b>a?b:d>a/4).toString(16)})},isValidConnection:function(a, +b){if(""==a||"*"===a)a=0;if(""==b||"*"===b)b=0;if(!a||!b||a==b||a==e.EVENT&&b==e.ACTION)return!0;a=String(a);b=String(b);a=a.toLowerCase();b=b.toLowerCase();if(-1==a.indexOf(",")&&-1==b.indexOf(","))return a==b;a=a.split(",");b=b.split(",");for(var d=0;dz&&(z=t.size[v]);c+=t.size[b==e.VERTICAL_LAYOUT?0:1]+a+e.NODE_TITLE_HEIGHT}d+=z+a}this.setDirtyCanvas(!0,!0)};c.prototype.getTime=function(){return this.globaltime};c.prototype.getFixedTime=function(){return this.fixedtime};c.prototype.getElapsedTime=function(){return this.elapsed_time};c.prototype.sendEventToAllNodes=function(a, +b,d){d=d||e.ALWAYS;var f=this._nodes_in_order?this._nodes_in_order:this._nodes;if(f)for(var g=0,q=f.length;g=e.MAX_NUMBER_OF_NODES)throw"LiteGraph: max number of nodes in a graph reached";if(e.use_uuids){if(null==a.id||-1==a.id)a.id=e.uuidv4()}else null==a.id||-1==a.id? +a.id=++this.last_node_id:this.last_node_ida.length||(this._pos[0]=a[0],this._pos[1]=a[1])},get:function(){return this._pos},enumerable:!0});this.id=e.use_uuids?e.uuidv4():-1;this.type=null;this.inputs=[];this.outputs=[];this.connections=[];this.properties={};this.properties_info=[];this.flags={}};n.prototype.configure=function(a){this.graph&& +this.graph._version++;for(var b in a)if("properties"==b)for(var d in a.properties){if(this.properties[d]=a.properties[d],this.onPropertyChanged)this.onPropertyChanged(d,a.properties[d])}else null!=a[b]&&("object"==typeof a[b]?this[b]&&this[b].configure?this[b].configure(a[b]):this[b]=e.cloneObject(a[b],this[b]):this[b]=a[b]);a.title||(this.title=this.constructor.title);if(this.inputs)for(d=0;d=this.outputs.length)){var d=this.outputs[a];if(d&&(d._data=b,this.outputs[a].links))for(d=0;d=this.outputs.length)){var d=this.outputs[a];if(d&&(d.type=b,this.outputs[a].links))for(d=0;d=this.inputs.length||null==this.inputs[a].link)){a=this.graph.links[this.inputs[a].link];if(!a)return null;if(!b)return a.data;b=this.graph.getNodeById(a.origin_id);if(!b)return a.data;if(b.updateOutputData)b.updateOutputData(a.origin_slot);else if(b.onExecute)b.onExecute();return a.data}};n.prototype.getInputDataType=function(a){if(!this.inputs||a>=this.inputs.length||null==this.inputs[a].link)return null;a=this.graph.links[this.inputs[a].link];if(!a)return null; +var b=this.graph.getNodeById(a.origin_id);return b?(a=b.outputs[a.origin_slot])?a.type:null:a.type};n.prototype.getInputDataByName=function(a,b){a=this.findInputSlot(a);return-1==a?null:this.getInputData(a,b)};n.prototype.isInputConnected=function(a){return this.inputs?a=this.inputs.length)return null;a=this.inputs[a];return a&&null!==a.link?(a=this.graph.links[a.link])?this.graph.getNodeById(a.origin_id):null:null};n.prototype.getInputOrProperty=function(a){if(!this.inputs||!this.inputs.length)return this.properties?this.properties[a]:null;for(var b=0,d=this.inputs.length;b=this.outputs.length?null:this.outputs[a]._data};n.prototype.getOutputInfo=function(a){return this.outputs?a=this.outputs.length)return null;a=this.outputs[a];if(!a.links||0==a.links.length)return null;for(var b=[],d=0;da&&this.pos[1]-g-db)return!0;return!1};n.prototype.getSlotInPosition=function(a,b){var d=new Float32Array(2);if(this.inputs)for(var f=0,g=this.inputs.length;f=this.outputs.length)return e.debug&&console.log("Connect: Error, slot number not found"),null;b&&b.constructor=== +Number&&(b=this.graph.getNodeById(b));if(!b)throw"target node is null";if(b==this)return null;if(d.constructor===String){if(d=b.findInputSlot(d),-1==d)return e.debug&&console.log("Connect: Error, no slot of name "+d),null}else if(d===e.EVENT)if(e.do_add_triggers_slots)b.changeMode(e.ON_TRIGGER),d=b.findInputSlot("onTrigger");else return null;else if(!b.inputs||d>=b.inputs.length)return e.debug&&console.log("Connect: Error, slot number not found"),null;var f=b.inputs[d],g=this.outputs[a];if(!this.outputs[a])return null; +b.onBeforeConnectInput&&(d=b.onBeforeConnectInput(d));if(!1===d||null===d||!e.isValidConnection(g.type,f.type))return this.setDirtyCanvas(!1,!0),null;if(b.onConnectInput&&!1===b.onConnectInput(d,g.type,g,this,a)||this.onConnectOutput&&!1===this.onConnectOutput(a,f.type,f,b,d))return null;b.inputs[d]&&null!=b.inputs[d].link&&(this.graph.beforeChange(),b.disconnectInput(d,{doProcessChange:!1}));if(null!==g.links&&g.links.length)switch(g.type){case e.EVENT:e.allow_multi_output_for_events||(this.graph.beforeChange(), +this.disconnectOutput(a,!1,{doProcessChange:!1}))}var q=e.use_uuids?e.uuidv4():++this.graph.last_link_id;q=new k(q,f.type||g.type,this.id,a,b.id,d);this.graph.links[q.id]=q;null==g.links&&(g.links=[]);g.links.push(q.id);b.inputs[d].link=q.id;this.graph&&this.graph._version++;if(this.onConnectionsChange)this.onConnectionsChange(e.OUTPUT,a,!0,q,g);if(b.onConnectionsChange)b.onConnectionsChange(e.INPUT,d,!0,q,f);this.graph&&this.graph.onNodeConnectionChange&&(this.graph.onNodeConnectionChange(e.INPUT, +b,d,this,a),this.graph.onNodeConnectionChange(e.OUTPUT,this,a,b,d));this.setDirtyCanvas(!1,!0);this.graph.afterChange();this.graph.connectionChange(this,q);return q};n.prototype.disconnectOutput=function(a,b){if(a.constructor===String){if(a=this.findOutputSlot(a),-1==a)return e.debug&&console.log("Connect: Error, no slot of name "+a),!1}else if(!this.outputs||a>=this.outputs.length)return e.debug&&console.log("Connect: Error, slot number not found"),!1;var d=this.outputs[a];if(!d||!d.links||0==d.links.length)return!1; +if(b){b.constructor===Number&&(b=this.graph.getNodeById(b));if(!b)throw"Target Node not found";for(var f=0,g=d.links.length;f=this.inputs.length)return e.debug&&console.log("Connect: Error, slot number not found"),!1;var b=this.inputs[a];if(!b)return!1;var d=this.inputs[a].link;if(null!=d){this.inputs[a].link=null;var f=this.graph.links[d];if(f){var g=this.graph.getNodeById(f.origin_id);if(!g)return!1;var q=g.outputs[f.origin_slot];if(!q||!q.links||0==q.links.length)return!1;for(var c=0,l=q.links.length;cb&&this.inputs[b].pos)return d[0]=this.pos[0]+this.inputs[b].pos[0],d[1]=this.pos[1]+ +this.inputs[b].pos[1],d;if(!a&&f>b&&this.outputs[b].pos)return d[0]=this.pos[0]+this.outputs[b].pos[0],d[1]=this.pos[1]+this.outputs[b].pos[1],d;if(this.horizontal)return d[0]=this.pos[0]+this.size[0]/f*(b+.5),d[1]=a?this.pos[1]-e.NODE_TITLE_HEIGHT:this.pos[1]+this.size[1],d;d[0]=a?this.pos[0]+g:this.pos[0]+this.size[0]+1-g;d[1]=this.pos[1]+(b+.7)*e.NODE_SLOT_HEIGHT+(this.constructor.slot_start_y||0);return d};n.prototype.alignToGrid=function(){this.pos[0]=e.CANVAS_GRID_SIZE*Math.round(this.pos[0]/ +e.CANVAS_GRID_SIZE);this.pos[1]=e.CANVAS_GRID_SIZE*Math.round(this.pos[1]/e.CANVAS_GRID_SIZE)};n.prototype.trace=function(a){this.console||(this.console=[]);this.console.push(a);this.console.length>n.MAX_CONSOLE&&this.console.shift();if(this.graph.onNodeTrace)this.graph.onNodeTrace(this,a)};n.prototype.setDirtyCanvas=function(a,b){this.graph&&this.graph.sendActionToCanvas("setDirty",[a,b])};n.prototype.loadImage=function(a){var b=new Image;b.src=e.node_images_path+a;b.ready=!1;var d=this;b.onload= +function(){this.ready=!0;d.setDirtyCanvas(!0)};return b};n.prototype.captureInput=function(a){if(this.graph&&this.graph.list_of_graphcanvas)for(var b=this.graph.list_of_graphcanvas,d=0;da.length||(this._pos[0]=a[0],this._pos[1]=a[1])},get:function(){return this._pos},enumerable:!0});Object.defineProperty(this,"size",{set:function(a){!a||2>a.length||(this._size[0]=Math.max(140,a[0]),this._size[1]=Math.max(80,a[1]))},get:function(){return this._size},enumerable:!0})};r.prototype.configure=function(a){this.title=a.title;this._bounding.set(a.bounding);this.color=a.color;this.font_size=a.font_size};r.prototype.serialize=function(){var a= +this._bounding;return{title:this.title,bounding:[Math.round(a[0]),Math.round(a[1]),Math.round(a[2]),Math.round(a[3])],color:this.color,font_size:this.font_size}};r.prototype.move=function(a,b,d){this._pos[0]+=a;this._pos[1]+=b;if(!d)for(d=0;d=this.viewport[0]&&f=this.viewport[1]&&dthis.max_scale&&(a=this.max_scale);if(a!=this.scale&&this.element){var d=this.element.getBoundingClientRect();if(d&&(b= +b||[.5*d.width,.5*d.height],d=this.convertCanvasToOffset(b),this.scale=a,.01>Math.abs(this.scale-1)&&(this.scale=1),a=this.convertCanvasToOffset(b),a=[a[0]-d[0],a[1]-d[1]],this.offset[0]+=a[0],this.offset[1]+=a[1],this.onredraw))this.onredraw(this)}};u.prototype.changeDeltaScale=function(a,b){this.changeScale(this.scale*a,b)};u.prototype.reset=function(){this.scale=1;this.offset[0]=0;this.offset[1]=0};y.LGraphCanvas=e.LGraphCanvas=h;h.DEFAULT_BACKGROUND_IMAGE="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAQBJREFUeNrs1rEKwjAUhlETUkj3vP9rdmr1Ysammk2w5wdxuLgcMHyptfawuZX4pJSWZTnfnu/lnIe/jNNxHHGNn//HNbbv+4dr6V+11uF527arU7+u63qfa/bnmh8sWLBgwYJlqRf8MEptXPBXJXa37BSl3ixYsGDBMliwFLyCV/DeLIMFCxYsWLBMwSt4Be/NggXLYMGCBUvBK3iNruC9WbBgwYJlsGApeAWv4L1ZBgsWLFiwYJmCV/AK3psFC5bBggULloJX8BpdwXuzYMGCBctgwVLwCl7Be7MMFixYsGDBsu8FH1FaSmExVfAxBa/gvVmwYMGCZbBg/W4vAQYA5tRF9QYlv/QAAAAASUVORK5CYII="; +h.link_type_colors={"-1":e.EVENT_LINK_COLOR,number:"#AAA",node:"#DCA"};h.gradients={};h.prototype.clear=function(){this.fps=this.render_time=this.last_draw_time=this.frame=0;this.dragging_rectangle=null;this.selected_nodes={};this.selected_group=null;this.visible_nodes=[];this.connecting_node=this.node_capturing_input=this.node_over=this.node_dragged=null;this.highlighted_links={};this.dragging_canvas=!1;this.dirty_bgcanvas=this.dirty_canvas=!0;this.node_widget=this.node_in_panel=this.dirty_area= +null;this.last_mouse=[0,0];this.last_mouseclick=0;this.pointer_is_double=this.pointer_is_down=!1;this.visible_area.set([0,0,0,0]);if(this.onClear)this.onClear()};h.prototype.setGraph=function(a,b){this.graph!=a&&(b||this.clear(),!a&&this.graph?this.graph.detachCanvas(this):(a.attachCanvas(this),this._graph_stack&&(this._graph_stack=null),this.setDirty(!0,!0)))};h.prototype.getTopGraph=function(){return this._graph_stack.length?this._graph_stack[0]:this.graph};h.prototype.openSubgraph=function(a){if(!a)throw"graph cannot be null"; +if(this.graph==a)throw"graph cannot be the same";this.clear();this.graph&&(this._graph_stack||(this._graph_stack=[]),this._graph_stack.push(this.graph));a.attachCanvas(this);this.checkPanels();this.setDirty(!0,!0)};h.prototype.closeSubgraph=function(){if(this._graph_stack&&0!=this._graph_stack.length){var a=this.graph._subgraph_node,b=this._graph_stack.pop();this.selected_nodes={};this.highlighted_links={};b.attachCanvas(this);this.setDirty(!0,!0);a&&(this.centerOnNode(a),this.selectNodes([a]));this.ds.offset= +[0,0];this.ds.scale=1}};h.prototype.getCurrentGraph=function(){return this.graph};h.prototype.setCanvas=function(a,b){if(a&&a.constructor===String&&(a=document.getElementById(a),!a))throw"Error creating LiteGraph canvas: Canvas not found";if(a!==this.canvas&&(!a&&this.canvas&&(b||this.unbindEvents()),this.canvas=a,this.ds.element=a)){a.className+=" lgraphcanvas";a.data=this;a.tabindex="1";this.bgcanvas=null;this.bgcanvas||(this.bgcanvas=document.createElement("canvas"),this.bgcanvas.width=this.canvas.width, +this.bgcanvas.height=this.canvas.height);if(null==a.getContext){if("canvas"!=a.localName)throw"Element supplied for LGraphCanvas must be a element, you passed a "+a.localName;throw"This browser doesn't support Canvas";}null==(this.ctx=a.getContext("2d"))&&(a.webgl_enabled||console.warn("This canvas seems to be WebGL, enabling WebGL renderer"),this.enableWebGL());b||this.bindEvents()}};h.prototype._doNothing=function(a){a.preventDefault();return!1};h.prototype._doReturnTrue=function(a){a.preventDefault(); +return!0};h.prototype.bindEvents=function(){if(this._events_binded)console.warn("LGraphCanvas: events already binded");else{var a=this.canvas,b=this.getCanvasWindow().document;this._mousedown_callback=this.processMouseDown.bind(this);this._mousewheel_callback=this.processMouseWheel.bind(this);this._mousemove_callback=this.processMouseMove.bind(this);this._mouseup_callback=this.processMouseUp.bind(this);e.pointerListenerAdd(a,"down",this._mousedown_callback,!0);a.addEventListener("mousewheel",this._mousewheel_callback, +!1);e.pointerListenerAdd(a,"up",this._mouseup_callback,!0);e.pointerListenerAdd(a,"move",this._mousemove_callback);a.addEventListener("contextmenu",this._doNothing);a.addEventListener("DOMMouseScroll",this._mousewheel_callback,!1);this._key_callback=this.processKey.bind(this);a.addEventListener("keydown",this._key_callback,!0);b.addEventListener("keyup",this._key_callback,!0);this._ondrop_callback=this.processDrop.bind(this);a.addEventListener("dragover",this._doNothing,!1);a.addEventListener("dragend", +this._doNothing,!1);a.addEventListener("drop",this._ondrop_callback,!1);a.addEventListener("dragenter",this._doReturnTrue,!1);this._events_binded=!0}};h.prototype.unbindEvents=function(){if(this._events_binded){var a=this.getCanvasWindow().document;e.pointerListenerRemove(this.canvas,"move",this._mousedown_callback);e.pointerListenerRemove(this.canvas,"up",this._mousedown_callback);e.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);a.removeEventListener("keyup",this._key_callback);this.canvas.removeEventListener("contextmenu",this._doNothing);this.canvas.removeEventListener("drop",this._ondrop_callback);this.canvas.removeEventListener("dragenter",this._doReturnTrue);this._ondrop_callback=this._key_callback=this._mousewheel_callback=this._mousedown_callback=null;this._events_binded=!1}else console.warn("LGraphCanvas: no events binded")}; +h.getFileExtension=function(a){var b=a.indexOf("?");-1!=b&&(a=a.substr(0,b));b=a.lastIndexOf(".");return-1==b?"":a.substr(b+1).toLowerCase()};h.prototype.enableWebGL=function(){if("undefined"===typeof GL)throw"litegl.js must be included to use a WebGL canvas";if("undefined"===typeof enableWebGLCanvas)throw"webglCanvas.js must be included to use this feature";this.gl=this.ctx=enableWebGLCanvas(this.canvas);this.ctx.webgl=!0;this.bgcanvas=this.canvas;this.bgctx=this.gl;this.canvas.webgl_enabled=!0}; +h.prototype.setDirty=function(a,b){a&&(this.dirty_canvas=!0);b&&(this.dirty_bgcanvas=!0)};h.prototype.getCanvasWindow=function(){if(!this.canvas)return window;var a=this.canvas.ownerDocument;return a.defaultView||a.parentWindow};h.prototype.startRendering=function(){function a(){this.pause_rendering||this.draw();var b=this.getCanvasWindow();this.is_rendering&&b.requestAnimationFrame(a.bind(this))}this.is_rendering||(this.is_rendering=!0,a.call(this))};h.prototype.stopRendering=function(){this.is_rendering= +!1};h.prototype.blockClick=function(){this.block_click=!0;this.last_mouseclick=0};h.prototype.processMouseDown=function(a){this.set_canvas_dirty_on_mouse_event&&(this.dirty_canvas=!0);if(this.graph){this.adjustMouseEvent(a);var b=this.getCanvasWindow();h.active_canvas=this;var d=this,f=a.clientX,g=a.clientY;this.ds.viewport=this.viewport;f=!this.viewport||this.viewport&&f>=this.viewport[0]&&f=this.viewport[1]&&gg-this.last_mouseclick&&c;this.mouse[0]=a.clientX;this.mouse[1]=a.clientY;this.graph_mouse[0]=a.canvasX;this.graph_mouse[1]=a.canvasY;this.last_click_position= +[this.mouse[0],this.mouse[1]];this.pointer_is_double=this.pointer_is_down&&c?!0:!1;this.pointer_is_down=!0;this.canvas.focus();e.closeAllContextMenus(b);if(!this.onMouse||1!=this.onMouse(a)){if(1!=a.which||this.pointer_is_double)if(2==a.which)if(e.middle_click_slot_add_default_node){if(q&&this.allow_interaction&&!f&&!this.read_only&&!this.connecting_node&&!q.flags.collapsed&&!this.live_mode){g=f=c=!1;if(q.outputs)for(v=0,l=q.outputs.length;vq.size[0]-e.NODE_TITLE_HEIGHT&& +0>l[1]&&(d=this,setTimeout(function(){d.openSubgraph(q.subgraph)},10)),this.live_mode&&(v=c=!0));v?q.is_selected||this.processNodeSelected(q,a):(this.allow_dragnodes&&(this.graph.beforeChange(),this.node_dragged=q),this.processNodeSelected(q,a));this.dirty_canvas=!0}}else if(!f){if(!this.read_only)for(v=0;vl[0]+4||a.canvasYl[1]+4)){this.showLinkMenu(c,a);this.over_link_center=null; +break}this.selected_group=this.graph.getGroupOnPos(a.canvasX,a.canvasY);this.selected_group_resizing=!1;this.selected_group&&!this.read_only&&(a.ctrlKey&&(this.dragging_rectangle=null),10>E([a.canvasX,a.canvasY],[this.selected_group.pos[0]+this.selected_group.size[0],this.selected_group.pos[1]+this.selected_group.size[1]])*this.ds.scale?this.selected_group_resizing=!0:this.selected_group.recomputeInsideNodes());g&&!this.read_only&&this.allow_searchbox&&(this.showSearchBox(a),a.preventDefault(),a.stopPropagation()); +c=!0}!f&&c&&this.allow_dragcanvas&&(this.dragging_canvas=!0)}this.last_mouse[0]=a.clientX;this.last_mouse[1]=a.clientY;this.last_mouseclick=e.getTime();this.last_mouse_dragging=!0;this.graph.change();(!b.document.activeElement||"input"!=b.document.activeElement.nodeName.toLowerCase()&&"textarea"!=b.document.activeElement.nodeName.toLowerCase())&&a.preventDefault();a.stopPropagation();if(this.onMouseDown)this.onMouseDown(a);return!1}}}};h.prototype.processMouseMove=function(a){this.autoresize&&this.resize(); +this.set_canvas_dirty_on_mouse_event&&(this.dirty_canvas=!0);if(this.graph){h.active_canvas=this;this.adjustMouseEvent(a);var b=[a.clientX,a.clientY];this.mouse[0]=b[0];this.mouse[1]=b[1];var d=[b[0]-this.last_mouse[0],b[1]-this.last_mouse[1]];this.last_mouse=b;this.graph_mouse[0]=a.canvasX;this.graph_mouse[1]=a.canvasY;if(this.block_click)return a.preventDefault(),!1;a.dragging=this.last_mouse_dragging;this.node_widget&&(this.processNodeWidgets(this.node_widget[0],this.graph_mouse,a,this.node_widget[1]), +this.dirty_canvas=!0);var f=this.graph.getNodeOnPos(a.canvasX,a.canvasY,this.visible_nodes);if(this.dragging_rectangle)this.dragging_rectangle[2]=a.canvasX-this.dragging_rectangle[0],this.dragging_rectangle[3]=a.canvasY-this.dragging_rectangle[1],this.dirty_canvas=!0;else if(this.selected_group&&!this.read_only)this.selected_group_resizing?this.selected_group.size=[a.canvasX-this.selected_group.pos[0],a.canvasY-this.selected_group.pos[1]]:(this.selected_group.move(d[0]/this.ds.scale,d[1]/this.ds.scale, +a.ctrlKey),this.selected_group._nodes.length&&(this.dirty_canvas=!0)),this.dirty_bgcanvas=!0;else if(this.dragging_canvas)this.ds.offset[0]+=d[0]/this.ds.scale,this.ds.offset[1]+=d[1]/this.ds.scale,this.dirty_bgcanvas=this.dirty_canvas=!0;else if((this.allow_interaction||f&&f.flags.allow_interaction)&&!this.read_only){this.connecting_node&&(this.dirty_canvas=!0);b=0;for(var g=this.graph._nodes.length;bc[0]+4||a.canvasYc[1]+4)){g=q;break}g!=this.over_link_center&&(this.over_link_center=g,this.dirty_canvas=!0);this.canvas&&(this.canvas.style.cursor="")}if(this.node_capturing_input&& +this.node_capturing_input!=f&&this.node_capturing_input.onMouseMove)this.node_capturing_input.onMouseMove(a,[a.canvasX-this.node_capturing_input.pos[0],a.canvasY-this.node_capturing_input.pos[1]],this);if(this.node_dragged&&!this.live_mode){for(b in this.selected_nodes)f=this.selected_nodes[b],f.pos[0]+=d[0]/this.ds.scale,f.pos[1]+=d[1]/this.ds.scale,f.is_selected||this.processNodeSelected(f,a);this.dirty_bgcanvas=this.dirty_canvas=!0}this.resizing_node&&!this.live_mode&&(d=[a.canvasX-this.resizing_node.pos[0], +a.canvasY-this.resizing_node.pos[1]],b=this.resizing_node.computeSize(),d[0]=Math.max(b[0],d[0]),d[1]=Math.max(b[1],d[1]),this.resizing_node.setSize(d),this.canvas.style.cursor="se-resize",this.dirty_bgcanvas=this.dirty_canvas=!0)}a.preventDefault();return!1}};h.prototype.processMouseUp=function(a){var b=void 0===a.isPrimary||a.isPrimary;if(!b)return!1;this.set_canvas_dirty_on_mouse_event&&(this.dirty_canvas=!0);if(this.graph){var d=this.getCanvasWindow().document;h.active_canvas=this;this.options.skip_events|| +(e.pointerListenerRemove(d,"move",this._mousemove_callback,!0),e.pointerListenerAdd(this.canvas,"move",this._mousemove_callback,!0),e.pointerListenerRemove(d,"up",this._mouseup_callback,!0));this.adjustMouseEvent(a);d=e.getTime();a.click_time=d-this.last_mouseclick;this.last_mouse_dragging=!1;this.last_click_position=null;this.block_click&&(this.block_click=!1);if(1==a.which){this.node_widget&&this.processNodeWidgets(this.node_widget[0],this.graph_mouse,a);this.node_widget=null;this.selected_group&& +(this.selected_group.move(this.selected_group.pos[0]-Math.round(this.selected_group.pos[0]),this.selected_group.pos[1]-Math.round(this.selected_group.pos[1]),a.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]),this.selected_group._nodes.length&&(this.dirty_canvas=!0),this.selected_group=null);this.selected_group_resizing=!1;var f=this.graph.getNodeOnPos(a.canvasX,a.canvasY,this.visible_nodes);if(this.dragging_rectangle){if(this.graph){d= +this.graph._nodes;var g=new Float32Array(4),q=Math.abs(this.dragging_rectangle[2]),c=Math.abs(this.dragging_rectangle[3]),l=0>this.dragging_rectangle[3]?this.dragging_rectangle[1]-c:this.dragging_rectangle[1];this.dragging_rectangle[0]=0>this.dragging_rectangle[2]?this.dragging_rectangle[0]-q:this.dragging_rectangle[0];this.dragging_rectangle[1]=l;this.dragging_rectangle[2]=q;this.dragging_rectangle[3]=c;if(!f||10a.click_time&&D(a.canvasX,a.canvasY,f.pos[0],f.pos[1]-e.NODE_TITLE_HEIGHT,e.NODE_TITLE_HEIGHT,e.NODE_TITLE_HEIGHT)&&f.collapse();this.dirty_bgcanvas=this.dirty_canvas=!0;this.node_dragged.pos[0]=Math.round(this.node_dragged.pos[0]);this.node_dragged.pos[1]=Math.round(this.node_dragged.pos[1]);(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}else{f=this.graph.getNodeOnPos(a.canvasX,a.canvasY,this.visible_nodes);!f&&300>a.click_time&&this.deselectAllNodes();this.dirty_canvas=!0;this.dragging_canvas=!1;if(this.node_over&&this.node_over.onMouseUp)this.node_over.onMouseUp(a,[a.canvasX-this.node_over.pos[0],a.canvasY-this.node_over.pos[1]],this);if(this.node_capturing_input&&this.node_capturing_input.onMouseUp)this.node_capturing_input.onMouseUp(a,[a.canvasX-this.node_capturing_input.pos[0],a.canvasY-this.node_capturing_input.pos[1]])}}else 2== +a.which?(this.dirty_canvas=!0,this.dragging_canvas=!1):3==a.which&&(this.dirty_canvas=!0,this.dragging_canvas=!1);b&&(this.pointer_is_double=this.pointer_is_down=!1);this.graph.change();a.stopPropagation();a.preventDefault();return!1}};h.prototype.processMouseWheel=function(a){if(this.graph&&this.allow_dragcanvas){var b=null!=a.wheelDeltaY?a.wheelDeltaY:-60*a.detail;this.adjustMouseEvent(a);var d=a.clientX,f=a.clientY;if(!this.viewport||this.viewport&&d>=this.viewport[0]&&d=this.viewport[1]&&fb&&(d*=1/1.1),this.ds.changeScale(d,[a.clientX,a.clientY]),this.graph.change(),a.preventDefault(),!1}};h.prototype.isOverNodeBox=function(a,b,d){var f=e.NODE_TITLE_HEIGHT;return D(b,d,a.pos[0]+2,a.pos[1]+2-f,f-4,f-4)?!0:!1};h.prototype.isOverNodeInput=function(a,b,d,f){if(a.inputs)for(var g=0,e=a.inputs.length;gb.nodes[g].pos[0]&&(d[0]=b.nodes[g].pos[0],f[0]=g),d[1]>b.nodes[g].pos[1]&&(d[1]=b.nodes[g].pos[1],f[1]=g)):(d=[b.nodes[g].pos[0],b.nodes[g].pos[1]],f=[g,g]);f=[];for(g=0;g=this.viewport[0]&&b=this.viewport[1]&&dd-this.graph._last_trigger_time)&&this.drawBackCanvas();(this.dirty_canvas||a)&&this.drawFrontCanvas();this.fps=this.render_time?1/this.render_time:0;this.frame+=1}};h.prototype.drawFrontCanvas= +function(){this.dirty_canvas=!1;this.ctx||(this.ctx=this.bgcanvas.getContext("2d"));var a=this.ctx;if(a){var b=this.canvas;a.start2D&&!this.viewport&&(a.start2D(),a.restore(),a.setTransform(1,0,0,1,0,0));var d=this.viewport||this.dirty_area;d&&(a.save(),a.beginPath(),a.rect(d[0],d[1],d[2],d[3]),a.clip());this.clear_background&&(d?a.clearRect(d[0],d[1],d[2],d[3]):a.clearRect(0,0,b.width,b.height));this.bgcanvas==this.canvas?this.drawBackCanvas():a.drawImage(this.bgcanvas,0,0);if(this.onRender)this.onRender(b, +a);this.show_info&&this.renderInfo(a,d?d[0]:0,d?d[1]:0);if(this.graph){a.save();this.ds.toCanvasContext(a);b=this.computeVisibleNodes(null,this.visible_nodes);for(var f=0;f> ";b.fillText(f+d.getTitle(),.5*a.width,40);b.restore()}d=!1;this.onRenderBackground&&(d=this.onRenderBackground(a,b));this.viewport||(b.restore(),b.setTransform(1,0,0,1,0,0));this.visible_links.length=0;if(this.graph){b.save();this.ds.toCanvasContext(b);1.5>this.ds.scale&&!d&&this.clear_background_color&& +(b.fillStyle=this.clear_background_color,b.fillRect(this.visible_area[0],this.visible_area[1],this.visible_area[2],this.visible_area[3]));if(this.background_image&&.5this.ds.scale;if(this.live_mode){if(!a.flags.collapsed&&(b.shadowColor="transparent",a.onDrawForeground))a.onDrawForeground(b,this,this.canvas)}else{var c=this.editor_alpha;b.globalAlpha=c;this.render_shadows&&!g?(b.shadowColor=e.DEFAULT_SHADOW_COLOR,b.shadowOffsetX=2*this.ds.scale, +b.shadowOffsetY=2*this.ds.scale,b.shadowBlur=3*this.ds.scale):b.shadowColor="transparent";if(!a.flags.collapsed||!a.onDrawCollapsed||1!=a.onDrawCollapsed(b,this)){var l=a._shape||e.BOX_SHAPE;B.set(a.size);var m=a.horizontal;if(a.flags.collapsed){b.font=this.inner_text_font;var h=a.getTitle?a.getTitle():a.title;null!=h&&(a._collapsed_width=Math.min(a.size[0],b.measureText(h).width+2*e.NODE_TITLE_HEIGHT),B[0]=a._collapsed_width,B[1]=0)}a.clip_area&&(b.save(),b.beginPath(),l==e.BOX_SHAPE?b.rect(0,0, +B[0],B[1]):l==e.ROUND_SHAPE?b.roundRect(0,0,B[0],B[1],[10]):l==e.CIRCLE_SHAPE&&b.arc(.5*B[0],.5*B[1],.5*B[0],0,2*Math.PI),b.clip());a.has_errors&&(f="red");this.drawNodeShape(a,b,B,d,f,a.is_selected,a.mouseOver);b.shadowColor="transparent";if(a.onDrawForeground)a.onDrawForeground(b,this,this.canvas);b.textAlign=m?"center":"left";b.font=this.inner_text_font;f=!g;var t=this.connecting_output;l=this.connecting_input;b.lineWidth=1;h=0;var v=new Float32Array(2);if(!a.flags.collapsed){if(a.inputs)for(d= +0;dthis.ds.scale,z=a._shape||a.constructor.shape||e.ROUND_SHAPE,t=a.constructor.title_mode,v=!0;t==e.TRANSPARENT_TITLE||t==e.NO_TITLE?v=!1:t==e.AUTOHIDE_TITLE&&l&&(v=!0);M[0]=0;M[1]=v?-g:0;M[2]=d[0]+1;M[3]=v?d[1]+g:d[1];l=b.globalAlpha;b.beginPath();z==e.BOX_SHAPE||q?b.fillRect(M[0],M[1],M[2],M[3]):z==e.ROUND_SHAPE||z==e.CARD_SHAPE?b.roundRect(M[0],M[1],M[2],M[3],z==e.CARD_SHAPE?[this.round_radius, +this.round_radius,0,0]:[this.round_radius]):z==e.CIRCLE_SHAPE&&b.arc(.5*d[0],.5*d[1],.5*d[0],0,2*Math.PI);b.fill();!a.flags.collapsed&&v&&(b.shadowColor="transparent",b.fillStyle="rgba(0,0,0,0.2)",b.fillRect(0,-1,M[2],2));b.shadowColor="transparent";if(a.onDrawBackground)a.onDrawBackground(b,this,this.canvas,this.graph_mouse);if(v||t==e.TRANSPARENT_TITLE){if(a.onDrawTitleBar)a.onDrawTitleBar(b,g,d,this.ds.scale,f);else if(t!=e.TRANSPARENT_TITLE&&(a.constructor.title_color||this.render_title_colored)){v= +a.constructor.title_color||f;a.flags.collapsed&&(b.shadowColor=e.DEFAULT_SHADOW_COLOR);if(this.use_gradients){var C=h.gradients[v];C||(C=h.gradients[v]=b.createLinearGradient(0,0,400,0),C.addColorStop(0,v),C.addColorStop(1,"#000"));b.fillStyle=C}else b.fillStyle=v;b.beginPath();z==e.BOX_SHAPE||q?b.rect(0,-g,d[0]+1,g):(z==e.ROUND_SHAPE||z==e.CARD_SHAPE)&&b.roundRect(0,-g,d[0]+1,g,a.flags.collapsed?[this.round_radius]:[this.round_radius,this.round_radius,0,0]);b.fill();b.shadowColor="transparent"}v= +!1;e.node_box_coloured_by_mode&&e.NODE_MODES_COLORS[a.mode]&&(v=e.NODE_MODES_COLORS[a.mode]);e.node_box_coloured_when_on&&(v=a.action_triggered?"#FFF":a.execute_triggered?"#AAA":v);if(a.onDrawTitleBox)a.onDrawTitleBox(b,g,d,this.ds.scale);else z==e.ROUND_SHAPE||z==e.CIRCLE_SHAPE||z==e.CARD_SHAPE?(q&&(b.fillStyle="black",b.beginPath(),b.arc(.5*g,-.5*g,6,0,2*Math.PI),b.fill()),b.fillStyle=a.boxcolor||v||e.NODE_DEFAULT_BOXCOLOR,q?b.fillRect(.5*g-5,-.5*g-5,10,10):(b.beginPath(),b.arc(.5*g,-.5*g,5,0,2* +Math.PI),b.fill())):(q&&(b.fillStyle="black",b.fillRect(.5*(g-10)-1,-.5*(g+10)-1,12,12)),b.fillStyle=a.boxcolor||v||e.NODE_DEFAULT_BOXCOLOR,b.fillRect(.5*(g-10),-.5*(g+10),10,10));b.globalAlpha=l;if(a.onDrawTitleText)a.onDrawTitleText(b,g,d,this.ds.scale,this.title_text_font,c);!q&&(b.font=this.title_text_font,l=String(a.getTitle()))&&(b.fillStyle=c?e.NODE_SELECTED_TITLE_COLOR:a.constructor.title_text_color||this.node_title_color,a.flags.collapsed?(b.textAlign="left",b.measureText(l),b.fillText(l.substr(0, +20),g,e.NODE_TITLE_TEXT_Y-g),b.textAlign="left"):(b.textAlign="left",b.fillText(l,g,e.NODE_TITLE_TEXT_Y-g)));a.flags.collapsed||!a.subgraph||a.skip_subgraph_button||(l=e.NODE_TITLE_HEIGHT,v=a.size[0]-l,C=e.isInsideRectangle(this.graph_mouse[0]-a.pos[0],this.graph_mouse[1]-a.pos[1],v+2,-l+2,l-4,l-4),b.fillStyle=C?"#888":"#555",z==e.BOX_SHAPE||q?b.fillRect(v+2,-l+2,l-4,l-4):(b.beginPath(),b.roundRect(v+2,-l+2,l-4,l-4,[4]),b.fill()),b.fillStyle="#333",b.beginPath(),b.moveTo(v+.2*l,.6*-l),b.lineTo(v+ +.8*l,.6*-l),b.lineTo(v+.5*l,.3*-l),b.fill());if(a.onDrawTitle)a.onDrawTitle(b)}if(c){if(a.onBounding)a.onBounding(M);t==e.TRANSPARENT_TITLE&&(M[1]-=g,M[3]+=g);b.lineWidth=1;b.globalAlpha=.8;b.beginPath();z==e.BOX_SHAPE?b.rect(-6+M[0],-6+M[1],12+M[2],12+M[3]):z==e.ROUND_SHAPE||z==e.CARD_SHAPE&&a.flags.collapsed?b.roundRect(-6+M[0],-6+M[1],12+M[2],12+M[3],[2*this.round_radius]):z==e.CARD_SHAPE?b.roundRect(-6+M[0],-6+M[1],12+M[2],12+M[3],[2*this.round_radius,2,2*this.round_radius,2]):z==e.CIRCLE_SHAPE&& +b.arc(.5*d[0],.5*d[1],.5*d[0]+6,0,2*Math.PI);b.strokeStyle=e.NODE_BOX_OUTLINE_COLOR;b.stroke();b.strokeStyle=f;b.globalAlpha=1}0m[2]&&(m[0]+=m[2],m[2]=Math.abs(m[2]));0>m[3]&& +(m[1]+=m[3],m[3]=Math.abs(m[3]));if(J(m,l)){var x=k.outputs[t];t=c.inputs[z];if(x&&t&&(k=x.dir||(k.horizontal?e.DOWN:e.RIGHT),t=t.dir||(c.horizontal?e.UP:e.LEFT),this.renderLink(a,v,C,h,!1,0,null,k,t),h&&h._last_time&&1E3>b-h._last_time)){x=2-.002*(b-h._last_time);var G=a.globalAlpha;a.globalAlpha=G*x;this.renderLink(a,v,C,h,!0,x,"white",k,t);a.globalAlpha=G}}}}}}a.globalAlpha=1};h.prototype.renderLink=function(a,b,d,f,g,c,l,m,w,t){f&&this.visible_links.push(f);!l&&f&&(l=f.color||h.link_type_colors[f.type]); +l||(l=this.default_link_color);null!=f&&this.highlighted_links[f.id]&&(l="#FFF");m=m||e.RIGHT;w=w||e.LEFT;var q=E(b,d);this.render_connections_border&&.6b[1]?0:Math.PI,a.save(),a.translate(C[0],C[1]),a.rotate(q),a.beginPath(),a.moveTo(-5,-3),a.lineTo(0,7),a.lineTo(5, +-3),a.fill(),a.restore(),a.save(),a.translate(f[0],f[1]),a.rotate(t),a.beginPath(),a.moveTo(-5,-3),a.lineTo(0,7),a.lineTo(5,-3),a.fill(),a.restore()),a.beginPath(),a.arc(g[0],g[1],5,0,2*Math.PI),a.fill());if(c)for(a.fillStyle=l,C=0;5>C;++C)c=(.001*e.getTime()+.2*C)%1,g=this.computeConnectionPoint(b,d,c,m,w),a.beginPath(),a.arc(g[0],g[1],5,0,2*Math.PI),a.fill()};h.prototype.computeConnectionPoint=function(a,b,d,f,g){f=f||e.RIGHT;g=g||e.LEFT;var c=E(a,b),l=[a[0],a[1]],m=[b[0],b[1]];switch(f){case e.LEFT:l[0]+= +-.25*c;break;case e.RIGHT:l[0]+=.25*c;break;case e.UP:l[1]+=-.25*c;break;case e.DOWN:l[1]+=.25*c}switch(g){case e.LEFT:m[0]+=-.25*c;break;case e.RIGHT:m[0]+=.25*c;break;case e.UP:m[1]+=-.25*c;break;case e.DOWN:m[1]+=.25*c}f=(1-d)*(1-d)*(1-d);g=3*(1-d)*(1-d)*d;c=3*(1-d)*d*d;d*=d*d;return[f*a[0]+g*l[0]+c*m[0]+d*b[0],f*a[1]+g*l[1]+c*m[1]+d*b[1]]};h.prototype.drawExecutionOrder=function(a){a.shadowColor="transparent";a.globalAlpha=.25;a.textAlign="center";a.strokeStyle="white";a.globalAlpha=.75;for(var b= +this.visible_nodes,d=0;dn&&(n=0);1k&&(k=0),1c||c>A-12||lx.last_y+G||void 0===x.last_y)){f=x.value;switch(x.type){case "button":d.type===e.pointerevents_method+"down"&&(x.callback&&setTimeout(function(){x.callback(x,t,a,b,d)},20),this.dirty_canvas=x.clicked=!0);break;case "slider":f=x.value;v=F((c-15)/(A-30),0,1);if(x.options.read_only)break;x.value=x.options.min+(x.options.max-x.options.min)*v;f!=x.value&&setTimeout(function(){g(x,x.value)},20);this.dirty_canvas= +!0;break;case "number":case "combo":f=x.value;if(d.type==e.pointerevents_method+"move"&&"number"==x.type)h&&(x.value+=.1*h*(x.options.step||1)),null!=x.options.min&&x.valuex.options.max&&(x.value=x.options.max);else if(d.type==e.pointerevents_method+"down"){var w=x.options.values;w&&w.constructor===Function&&(w=x.options.values(x,a));var k=null;"number"!=x.type&&(k=w.constructor===Array?w:Object.keys(w));c=40>c?-1:c>A-40?1:0;if("number"== +x.type)x.value+=.1*c*(x.options.step||1),null!=x.options.min&&x.valuex.options.max&&(x.value=x.options.max);else if(c)v=-1,this.last_mouseclick=0,v=w.constructor===Object?k.indexOf(String(x.value))+c:k.indexOf(x.value)+c,v>=k.length&&(v=k.length-1),0>v&&(v=0),x.value=w.constructor===Array?w[v]:v;else{var n=w!=k?Object.values(w):w;new e.ContextMenu(n,{scale:Math.max(1,this.ds.scale),event:d,className:"dark",callback:function(a,b, +d){w!=k&&(a=n.indexOf(a));this.value=a;g(this,a);t.dirty_canvas=!0;return!1}.bind(x)},v)}}else d.type==e.pointerevents_method+"up"&&"number"==x.type&&(c=40>c?-1:c>A-40?1:0,200>d.click_time&&0==c&&this.prompt("Value",x.value,function(a){if(/^[0-9+\-*/()\s]+|\d+\.\d+$/.test(a))try{a=eval(a)}catch(V){}this.value=Number(a);g(this,this.value)}.bind(x),d));f!=x.value&&setTimeout(function(){g(this,this.value)}.bind(x),20);this.dirty_canvas=!0;break;case "toggle":d.type==e.pointerevents_method+"down"&&(x.value= +!x.value,setTimeout(function(){g(x,x.value)},20));break;case "string":case "text":d.type==e.pointerevents_method+"down"&&this.prompt("Value",x.value,function(a){g(this,a)}.bind(x),d,x.options?x.options.multiline:!1);break;default:x.mouse&&(this.dirty_canvas=x.mouse(d,[c,l],a))}if(f!=x.value){if(a.onWidgetChanged)a.onWidgetChanged(x.name,x.value,f,x);a.graph._version++}return x}}}return null};h.prototype.drawGroups=function(a,b){if(this.graph){a=this.graph._groups;b.save();b.globalAlpha=.5*this.editor_alpha; +for(var d=0;dd&&.01>b.editor_alpha&&(clearInterval(f),1>d&&(b.live_mode=!0));1d.pos[0]+d.size[0])d=c;if(null===f||l+t>f.pos[1]+f.size[1])f=c;if(null===g||m"+(w.label?w.label:m)+""+a+"",value:m})}if(l.length)return new e.ContextMenu(l,{event:d,callback:function(a,b,d,f){g&&(b=this.getBoundingClientRect(),c.showEditPropertyValue(g,a.value,{position:[b.left,b.top]}))},parentMenu:f,allow_html:!0, +node:g},b),!1}};h.decodeHTML=function(a){var b=document.createElement("div");b.innerText=a;return b.innerHTML};h.onMenuResizeNode=function(a,b,d,f,g){if(g){a=function(a){a.size=a.computeSize();if(a.onResize)a.onResize(a.size)};b=h.active_canvas;if(!b.selected_nodes||1>=Object.keys(b.selected_nodes).length)a(g);else for(var e in b.selected_nodes)a(b.selected_nodes[e]);g.setDirtyCanvas(!0,!0)}};h.prototype.showLinkMenu=function(a,b){var d=this,f=d.graph.getNodeById(a.origin_id),g=d.graph.getNodeById(a.target_id), +c=!1;f&&f.outputs&&f.outputs[a.origin_slot]&&(c=f.outputs[a.origin_slot].type);var l=!1;g&&g.outputs&&g.outputs[a.target_slot]&&(l=g.inputs[a.target_slot].type);var m=new e.ContextMenu(["Add Node",null,"Delete",null],{event:b,title:null!=a.data?a.data.constructor.name:null,callback:function(b,e,q){switch(b){case "Add Node":h.onMenuAdd(null,null,q,m,function(b){b.inputs&&b.inputs.length&&b.outputs&&b.outputs.length&&f.connectByType(a.origin_slot,b,c)&&(b.connectByType(a.target_slot,g,l),b.pos[0]-= +.5*b.size[0])});break;case "Delete":d.graph.removeLink(a.id)}}});return!1};h.prototype.createDefaultNodeForSlot=function(a){a=a||{};a=Object.assign({nodeFrom:null,slotFrom:null,nodeTo:null,slotTo:null,position:[],nodeType:null,posAdd:[0,0],posSizeFix:[0,0]},a);var b=a.nodeFrom&&null!==a.slotFrom,d=!b&&a.nodeTo&&null!==a.slotTo;if(!b&&!d)return console.warn("No data passed to createDefaultNodeForSlot "+a.nodeFrom+" "+a.slotFrom+" "+a.nodeTo+" "+a.slotTo),!1;if(!a.nodeType)return console.warn("No type to createDefaultNodeForSlot"), +!1;var f=b?a.nodeFrom:a.nodeTo,g=b?a.slotFrom:a.slotTo;switch(typeof g){case "string":d=b?f.findOutputSlot(g,!1):f.findInputSlot(g,!1);g=b?f.outputs[g]:f.inputs[g];break;case "object":d=b?f.findOutputSlot(g.name):f.findInputSlot(g.name);break;case "number":d=g;g=b?f.outputs[g]:f.inputs[g];break;default:return console.warn("Cant get slot information "+g),!1}!1!==g&&!1!==d||console.warn("createDefaultNodeForSlot bad slotX "+g+" "+d);f=g.type==e.EVENT?"_event_":g.type;if((g=b?e.slot_types_default_out: +e.slot_types_default_in)&&g[f]){nodeNewType=!1;if("object"==typeof g[f]||"array"==typeof g[f])for(var c in g[f]){if(a.nodeType==g[f][c]||"AUTO"==a.nodeType){nodeNewType=g[f][c];break}}else if(a.nodeType==g[f]||"AUTO"==a.nodeType)nodeNewType=g[f];if(nodeNewType){c=!1;"object"==typeof nodeNewType&&nodeNewType.node&&(c=nodeNewType,nodeNewType=nodeNewType.node);if(g=e.createNode(nodeNewType)){if(c){if(c.properties)for(var l in c.properties)g.addProperty(l,c.properties[l]);if(c.inputs)for(l in g.inputs= +[],c.inputs)g.addOutput(c.inputs[l][0],c.inputs[l][1]);if(c.outputs)for(l in g.outputs=[],c.outputs)g.addOutput(c.outputs[l][0],c.outputs[l][1]);c.title&&(g.title=c.title);c.json&&g.configure(c.json)}this.graph.add(g);g.pos=[a.position[0]+a.posAdd[0]+(a.posSizeFix[0]?a.posSizeFix[0]*g.size[0]:0),a.position[1]+a.posAdd[1]+(a.posSizeFix[1]?a.posSizeFix[1]*g.size[1]:0)];b?a.nodeFrom.connectByType(d,g,f):a.nodeTo.connectByTypeOutput(d,g,f);return!0}console.log("failed creating "+nodeNewType)}}return!1}; +h.prototype.showConnectionMenu=function(a){a=a||{};var b=Object.assign({nodeFrom:null,slotFrom:null,nodeTo:null,slotTo:null,e:null},a),d=this,f=b.nodeFrom&&b.slotFrom;a=!f&&b.nodeTo&&b.slotTo;if(!f&&!a)return console.warn("No data passed to showConnectionMenu"),!1;a=f?b.nodeFrom:b.nodeTo;var g=f?b.slotFrom:b.slotTo,c=!1;switch(typeof g){case "string":c=f?a.findOutputSlot(g,!1):a.findInputSlot(g,!1);g=f?a.outputs[g]:a.inputs[g];break;case "object":c=f?a.findOutputSlot(g.name):a.findInputSlot(g.name); +break;case "number":c=g;g=f?a.outputs[g]:a.inputs[g];break;default:return console.warn("Cant get slot information "+g),!1}a=["Add Node",null];d.allow_searchbox&&(a.push("Search"),a.push(null));var l=g.type==e.EVENT?"_event_":g.type,m=f?e.slot_types_default_out:e.slot_types_default_in;if(m&&m[l])if("object"==typeof m[l]||"array"==typeof m[l])for(var w in m[l])a.push(m[l][w]);else a.push(m[l]);var t=new e.ContextMenu(a,{event:b.e,title:(g&&""!=g.name?g.name+(l?" | ":""):"")+(g&&l?l:""),callback:function(a, +e,x){switch(a){case "Add Node":h.onMenuAdd(null,null,x,t,function(a){f?b.nodeFrom.connectByType(c,a,l):b.nodeTo.connectByTypeOutput(c,a,l)});break;case "Search":f?d.showSearchBox(x,{node_from:b.nodeFrom,slot_from:g,type_filter_in:l}):d.showSearchBox(x,{node_to:b.nodeTo,slot_from:g,type_filter_out:l});break;default:d.createDefaultNodeForSlot(Object.assign(b,{position:[b.e.canvasX,b.e.canvasY],nodeType:a}))}}});return!1};h.onShowPropertyEditor=function(a,b,d,f,g){function c(){if(w){var b=w.value;"Number"== +a.type?b=Number(b):"Boolean"==a.type&&(b=!!b);g[l]=b;m.parentNode&&m.parentNode.removeChild(m);g.setDirtyCanvas(!0,!0)}}var l=a.property||"title";b=g[l];var m=document.createElement("div");m.is_modified=!1;m.className="graphdialog";m.innerHTML="";m.close=function(){m.parentNode&&m.parentNode.removeChild(m)};m.querySelector(".name").innerText=l;var w=m.querySelector(".value");w&&(w.value=b,w.addEventListener("blur", +function(a){this.focus()}),w.addEventListener("keydown",function(a){m.is_modified=!0;if(27==a.keyCode)m.close();else if(13==a.keyCode)c();else if(13!=a.keyCode&&"textarea"!=a.target.localName)return;a.preventDefault();a.stopPropagation()}));b=h.active_canvas.canvas;d=b.getBoundingClientRect();var t=f=-20;d&&(f-=d.left,t-=d.top);event?(m.style.left=event.clientX+f+"px",m.style.top=event.clientY+t+"px"):(m.style.left=.5*b.width+f+"px",m.style.top=.5*b.height+t+"px");m.querySelector("button").addEventListener("click", +c);b.parentNode.appendChild(m);w&&w.focus();var v=null;m.addEventListener("mouseleave",function(a){e.dialog_close_on_mouse_leave&&!m.is_modified&&e.dialog_close_on_mouse_leave&&(v=setTimeout(m.close,e.dialog_close_on_mouse_leave_delay))});m.addEventListener("mouseenter",function(a){e.dialog_close_on_mouse_leave&&v&&clearTimeout(v)})};h.prototype.prompt=function(a,b,d,f,g){var c=this;a=a||"";var l=document.createElement("div");l.is_modified=!1;l.className="graphdialog rounded";l.innerHTML=g?" ": +" ";l.close=function(){c.prompt_box=null;l.parentNode&&l.parentNode.removeChild(l)};g=h.active_canvas.canvas;g.parentNode.appendChild(l);1h.search_limit))break}}q=null;if(Array.prototype.filter)q=Object.keys(e.registered_node_types).filter(g);else for(x in q=[],e.registered_node_types)g(x)&&q.push(x);for(x=0;xh.search_limit);x++);if(b.show_general_after_typefiltered&&(G.value|| +Q.value)){filtered_extra=[];for(x in e.registered_node_types)g(x,{inTypeOverride:G&&G.value?"*":!1,outTypeOverride:Q&&Q.value?"*":!1})&&filtered_extra.push(x);for(x=0;xh.search_limit);x++);}if((G.value||Q.value)&&0==A.childNodes.length&&b.show_general_if_none_on_typefilter){filtered_extra=[];for(x in e.registered_node_types)g(x,{skipFilter:!0})&&filtered_extra.push(x);for(x=0;xh.search_limit);x++);}}}b=Object.assign({slot_from:null,node_from:null,node_to:null,do_type_filter:e.search_filter_enabled,type_filter_in:!1,type_filter_out:!1,show_general_if_none_on_typefilter:!0,show_general_after_typefiltered:!0,hide_on_mouse_leave:e.search_hide_on_mouse_leave,show_all_if_empty:!0,show_all_on_open:e.search_show_all_on_open},b||{});var c=this,l=h.active_canvas,m=l.canvas,w=m.ownerDocument||document,t=document.createElement("div");t.className= +"litegraph litesearchbox graphdialog rounded";t.innerHTML="Search ";b.do_type_filter&&(t.innerHTML+="",t.innerHTML+="");t.innerHTML+="
";w.fullscreenElement?w.fullscreenElement.appendChild(t):(w.body.appendChild(t),w.body.style.overflow="hidden");if(b.do_type_filter)var v= +t.querySelector(".slot_in_type_filter"),C=t.querySelector(".slot_out_type_filter");t.close=function(){c.search_box=null;this.blur();m.focus();w.body.style.overflow="";setTimeout(function(){c.canvas.focus()},20);t.parentNode&&t.parentNode.removeChild(t)};1v.height-200&&(A.style.maxHeight=v.height-a.layerY-20+"px");K.focus();b.show_all_on_open&&g();return t};h.prototype.showEditPropertyValue=function(a,b,d){function f(){g(C.value)}function g(f){e&&e.values&&e.values.constructor===Object&&void 0!=e.values[f]&&(f=e.values[f]);"number"==typeof a.properties[b]&& +(f=Number(f));if("array"==c||"object"==c)f=JSON.parse(f);a.properties[b]=f;a.graph&&a.graph._version++;if(a.onPropertyChanged)a.onPropertyChanged(b,f);if(d.onclose)d.onclose();v.close();a.setDirtyCanvas(!0,!0)}if(a&&void 0!==a.properties[b]){d=d||{};var e=a.getPropertyInfo(b),c=e.type,l="";if("string"==c||"number"==c||"array"==c||"object"==c)l="";else if("enum"!=c&&"combo"!=c||!e.values)if("boolean"==c||"toggle"==c)l="";else{console.warn("unknown type: "+c);return}else{l=""}var v=this.createDialog(""+(e.label?e.label:b)+""+l+"",d),C=!1;if("enum"!=c&&"combo"!=c||!e.values)if("boolean"==c||"toggle"==c)(C=v.querySelector("input"))&& +C.addEventListener("click",function(a){v.modified();g(!!C.checked)});else{if(C=v.querySelector("input"))C.addEventListener("blur",function(a){this.focus()}),t=void 0!==a.properties[b]?a.properties[b]:"","string"!==c&&(t=JSON.stringify(t)),C.value=t,C.addEventListener("keydown",function(a){if(27==a.keyCode)v.close();else if(13==a.keyCode)f();else if(13!=a.keyCode){v.modified();return}a.preventDefault();a.stopPropagation()})}else C=v.querySelector("select"),C.addEventListener("change",function(a){v.modified(); +g(a.target.value)});C&&C.focus();v.querySelector("button").addEventListener("click",f);return v}};h.prototype.createDialog=function(a,b){b=Object.assign({checkForInput:!1,closeOnLeave:!0,closeOnLeave_checkModified:!0},b||{});var d=document.createElement("div");d.className="graphdialog";d.innerHTML=a;d.is_modified=!1;a=this.canvas.getBoundingClientRect();var f=-20,g=-20;a&&(f-=a.left,g-=a.top);b.position?(f+=b.position[0],g+=b.position[1]):b.event?(f+=b.event.clientX,g+=b.event.clientY):(f+=.5*this.canvas.width, +g+=.5*this.canvas.height);d.style.left=f+"px";d.style.top=g+"px";this.canvas.parentNode.appendChild(d);b.checkForInput&&(a=[],(a=d.querySelectorAll("input"))&&a.forEach(function(a){a.addEventListener("keydown",function(a){d.modified();if(27==a.keyCode)d.close();else if(13!=a.keyCode)return;a.preventDefault();a.stopPropagation()});a.focus()}));d.modified=function(){d.is_modified=!0};d.close=function(){d.parentNode&&d.parentNode.removeChild(d)};var c=null,l=!1;d.addEventListener("mouseleave",function(a){l|| +(b.closeOnLeave||e.dialog_close_on_mouse_leave)&&!d.is_modified&&e.dialog_close_on_mouse_leave&&(c=setTimeout(d.close,e.dialog_close_on_mouse_leave_delay))});d.addEventListener("mouseenter",function(a){(b.closeOnLeave||e.dialog_close_on_mouse_leave)&&c&&clearTimeout(c)});(a=d.querySelectorAll("select"))&&a.forEach(function(a){a.addEventListener("click",function(a){l++});a.addEventListener("blur",function(a){l=0});a.addEventListener("change",function(a){l=-1})});return d};h.prototype.createPanel=function(a, +b){b=b||{};var d=b.window||window,f=document.createElement("div");f.className="litegraph dialog";f.innerHTML="
";f.header=f.querySelector(".dialog-header");b.width&&(f.style.width=b.width+(b.width.constructor===Number?"px":""));b.height&&(f.style.height=b.height+(b.height.constructor===Number?"px":""));b.closable&& +(b=document.createElement("span"),b.innerHTML="✕",b.classList.add("close"),b.addEventListener("click",function(){f.close()}),f.header.appendChild(b));f.title_element=f.querySelector(".dialog-title");f.title_element.innerText=a;f.content=f.querySelector(".dialog-content");f.alt_content=f.querySelector(".dialog-alt-content");f.footer=f.querySelector(".dialog-footer");f.close=function(){if(f.onClose&&"function"==typeof f.onClose)f.onClose();f.parentNode&&f.parentNode.removeChild(f);this.parentNode&& +this.parentNode.removeChild(this)};f.toggleAltContent=function(a){if("undefined"!=typeof a){var b=a?"block":"none";a=a?"none":"block"}else b="block"!=f.alt_content.style.display?"block":"none",a="block"!=f.alt_content.style.display?"none":"block";f.alt_content.style.display=b;f.content.style.display=a};f.toggleFooterVisibility=function(a){f.footer.style.display="undefined"!=typeof a?a?"block":"none":"block"!=f.footer.style.display?"block":"none"};f.clear=function(){this.content.innerHTML=""};f.addHTML= +function(a,b,d){var g=document.createElement("div");b&&(g.className=b);g.innerHTML=a;d?f.footer.appendChild(g):f.content.appendChild(g);return g};f.addButton=function(a,b,d){var g=document.createElement("button");g.innerText=a;g.options=d;g.classList.add("btn");g.addEventListener("click",b);f.footer.appendChild(g);return g};f.addSeparator=function(){var a=document.createElement("div");a.className="separator";f.content.appendChild(a)};f.addWidget=function(a,b,c,l,m){function g(a,b){l.callback&&l.callback(a, +b,l);m&&m(a,b,l)}l=l||{};var q=String(c);a=a.toLowerCase();"number"==a&&(q=c.toFixed(3));var C=document.createElement("div");C.className="property";C.innerHTML="";C.querySelector(".property_name").innerText=l.label||b;var x=C.querySelector(".property_value");x.innerText=q;C.dataset.property=b;C.dataset.type=l.type||a;C.options=l;C.value=c;if("code"==a)C.addEventListener("click",function(a){f.inner_showCodePad(this.dataset.property)}); +else if("boolean"==a)C.classList.add("boolean"),c&&C.classList.add("bool-on"),C.addEventListener("click",function(){var a=this.dataset.property;this.value=!this.value;this.classList.toggle("bool-on");this.querySelector(".property_value").innerText=this.value?"true":"false";g(a,this.value)});else if("string"==a||"number"==a)x.setAttribute("contenteditable",!0),x.addEventListener("keydown",function(b){"Enter"!=b.code||"string"==a&&b.shiftKey||(b.preventDefault(),this.blur())}),x.addEventListener("blur", +function(){var a=this.innerText,b=this.parentNode.dataset.property;"number"==this.parentNode.dataset.type&&(a=Number(a));g(b,a)});else if("enum"==a||"combo"==a)q=h.getPropertyPrintableValue(c,l.values),x.innerText=q,x.addEventListener("click",function(a){var b=this.parentNode.dataset.property,f=this;new e.ContextMenu(l.values||[],{event:a,className:"dark",callback:function(a,d,c){f.innerText=a;g(b,a);return!1}},d)});f.content.appendChild(C);return C};if(f.onOpen&&"function"==typeof f.onOpen)f.onOpen(); +return f};h.getPropertyPrintableValue=function(a,b){if(!b||b.constructor===Array)return String(a);if(b.constructor===Object){var d="",f;for(f in b)if(b[f]==a){d=f;break}return String(a)+" ("+d+")"}};h.prototype.closePanels=function(){var a=document.querySelector("#node-panel");a&&a.close();(a=document.querySelector("#option-panel"))&&a.close()};h.prototype.showShowGraphOptionsPanel=function(a,b,d,f){if(this.constructor&&"HTMLDivElement"==this.constructor.name){if(!(b&&b.event&&b.event.target&&b.event.target.lgraphcanvas)){console.warn("Canvas not found"); +return}var g=b.event.target.lgraphcanvas}else g=this;g.closePanels();a=g.getCanvasWindow();panel=g.createPanel("Options",{closable:!0,window:a,onOpen:function(){g.OPTIONPANEL_IS_OPEN=!0},onClose:function(){g.OPTIONPANEL_IS_OPEN=!1;g.options_panel=null}});g.options_panel=panel;panel.id="option-panel";panel.classList.add("settings");(function(){panel.content.innerHTML="";var a=function(a,b,d){d&&d.key&&(a=d.key);d.values&&(b=Object.values(d.values).indexOf(b));g[a]=b},b=e.availableCanvasOptions;b.sort(); +for(var d in b){var f=b[d];panel.addWidget("boolean",f,g[f],{key:f,on:"True",off:"False"},a)}panel.addWidget("combo","Render mode",e.LINK_RENDER_MODES[g.links_render_mode],{key:"links_render_mode",values:e.LINK_RENDER_MODES},a);panel.addSeparator();panel.footer.innerHTML=""})();g.canvas.parentNode.appendChild(panel)};h.prototype.showShowNodePanel=function(a){function b(){g.content.innerHTML="";g.addHTML(""+a.type+""+(a.constructor.desc||"")+""); +g.addHTML("

Properties

");var b=function(b,d){f.graph.beforeChange(a);switch(b){case "Title":a.title=d;break;case "Mode":b=Object.values(e.NODE_MODES).indexOf(d);0<=b&&e.NODE_MODES[b]?a.changeMode(b):console.warn("unexpected mode: "+d);break;case "Color":h.node_colors[d]?(a.color=h.node_colors[d].color,a.bgcolor=h.node_colors[d].bgcolor):console.warn("unexpected color: "+d);break;default:a.setProperty(b,d)}f.graph.afterChange();f.dirty_canvas=!0};g.addWidget("string","Title",a.title,{},b); +g.addWidget("combo","Mode",e.NODE_MODES[a.mode],{values:e.NODE_MODES},b);var d="";void 0!==a.color&&(d=Object.keys(h.node_colors).filter(function(b){return h.node_colors[b].color==a.color}));g.addWidget("combo","Color",d,{values:Object.keys(h.node_colors)},b);for(var c in a.properties){d=a.properties[c];var l=a.getPropertyInfo(c);a.onAddPropertyToPanel&&a.onAddPropertyToPanel(c,g)||g.addWidget(l.widget||l.type,c,d,l,b)}g.addSeparator();if(a.onShowCustomPanelInfo)a.onShowCustomPanelInfo(g);g.footer.innerHTML= +"";g.addButton("Delete",function(){a.block_delete||(a.graph.remove(a),g.close())}).classList.add("delete")}this.SELECTED_NODE=a;this.closePanels();var d=this.getCanvasWindow(),f=this,g=this.createPanel(a.title||"",{closable:!0,window:d,onOpen:function(){f.NODEPANEL_IS_OPEN=!0},onClose:function(){f.NODEPANEL_IS_OPEN=!1;f.node_panel=null}});f.node_panel=g;g.id="node-panel";g.node=a;g.classList.add("settings");g.inner_showCodePad=function(d){g.classList.remove("settings");g.classList.add("centered"); +g.alt_content.innerHTML="";var f=g.alt_content.querySelector("textarea"),c=function(){g.toggleAltContent(!1);g.toggleFooterVisibility(!0);f.parentNode.removeChild(f);g.classList.add("settings");g.classList.remove("centered");b()};f.value=a.properties[d];f.addEventListener("keydown",function(b){"Enter"==b.code&&b.ctrlKey&&(a.setProperty(d,f.value),c())});g.toggleAltContent(!0);g.toggleFooterVisibility(!1);f.style.height="calc(100% - 40px)";var e=g.addButton("Assign", +function(){a.setProperty(d,f.value);c()});g.alt_content.appendChild(e);e=g.addButton("Close",c);e.style.float="right";g.alt_content.appendChild(e)};b();this.canvas.parentNode.appendChild(g)};h.prototype.showSubgraphPropertiesDialog=function(a){function b(){f.clear();if(a.inputs)for(var d=0;d","subgraph_property"); +e.dataset.name=c.name;e.dataset.slot=d;e.querySelector(".name").innerText=c.name;e.querySelector(".type").innerText=c.type;e.querySelector("button").addEventListener("click",function(d){a.removeInput(Number(this.parentNode.dataset.slot));b()})}}}console.log("showing subgraph properties dialog");var d=this.canvas.parentNode.querySelector(".subgraph_dialog");d&&d.close();var f=this.createPanel("Subgraph Inputs",{closable:!0,width:500});f.node=a;f.classList.add("subgraph_dialog");f.addHTML(" + NameType", +"subgraph_property extra",!0).querySelector("button").addEventListener("click",function(d){d=this.parentNode;var f=d.querySelector(".name").value,g=d.querySelector(".type").value;f&&-1==a.findInputSlot(f)&&(a.addInput(f,g),d.querySelector(".name").value="",d.querySelector(".type").value="",b())});b();this.canvas.parentNode.appendChild(f);return f};h.prototype.showSubgraphPropertiesDialogRight=function(a){function b(){g.clear();if(a.outputs)for(var d=0;d","subgraph_property");c.dataset.name=f.name;c.dataset.slot=d;c.querySelector(".name").innerText=f.name;c.querySelector(".type").innerText=f.type;c.querySelector("button").addEventListener("click",function(d){a.removeOutput(Number(this.parentNode.dataset.slot));b()})}}}function d(){var d=this.parentNode,f=d.querySelector(".name").value,g=d.querySelector(".type").value;f&&-1==a.findOutputSlot(f)&& +(a.addOutput(f,g),d.querySelector(".name").value="",d.querySelector(".type").value="",b())}var f=this.canvas.parentNode.querySelector(".subgraph_dialog");f&&f.close();var g=this.createPanel("Subgraph Outputs",{closable:!0,width:500});g.node=a;g.classList.add("subgraph_dialog");f=g.addHTML(" + NameType","subgraph_property extra",!0);f.querySelector(".name").addEventListener("keydown", +function(a){13==a.keyCode&&d.apply(this)});f.querySelector("button").addEventListener("click",function(a){d.apply(this)});b();this.canvas.parentNode.appendChild(g);return g};h.prototype.checkPanels=function(){if(this.canvas)for(var a=this.canvas.parentNode.querySelectorAll(".litegraph.dialog"),b=0;b=Object.keys(a.selected_nodes).length)g.collapse(); +else for(var c in a.selected_nodes)a.selected_nodes[c].collapse();g.graph.afterChange()};h.onMenuNodePin=function(a,b,d,f,g){g.pin()};h.onMenuNodeMode=function(a,b,d,f,g){new e.ContextMenu(e.NODE_MODES,{event:d,callback:function(a){if(g){var b=Object.values(e.NODE_MODES).indexOf(a),d=function(d){0<=b&&e.NODE_MODES[b]?d.changeMode(b):(console.warn("unexpected mode: "+a),d.changeMode(e.ALWAYS))},f=h.active_canvas;if(!f.selected_nodes||1>=Object.keys(f.selected_nodes).length)d(g);else for(var c in f.selected_nodes)d(f.selected_nodes[c])}}, +parentMenu:f,node:g});return!1};h.onMenuNodeColors=function(a,b,d,f,g){if(!g)throw"no node for color";b=[];b.push({value:null,content:"No color"});for(var c in h.node_colors)a=h.node_colors[c],a={value:c,content:""+c+""},b.push(a);new e.ContextMenu(b,{event:d,callback:function(a){if(g){var b=a.value?h.node_colors[a.value]: +null;a=function(a){b?a.constructor===e.LGraphGroup?a.color=b.groupcolor:(a.color=b.color,a.bgcolor=b.bgcolor):(delete a.color,delete a.bgcolor)};var d=h.active_canvas;if(!d.selected_nodes||1>=Object.keys(d.selected_nodes).length)a(g);else for(var f in d.selected_nodes)a(d.selected_nodes[f]);g.setDirtyCanvas(!0,!0)}},parentMenu:f,node:g});return!1};h.onMenuNodeShapes=function(a,b,d,f,g){if(!g)throw"no node passed";new e.ContextMenu(e.VALID_SHAPES,{event:d,callback:function(a){if(g){g.graph.beforeChange(); +var b=h.active_canvas;if(!b.selected_nodes||1>=Object.keys(b.selected_nodes).length)g.shape=a;else for(var d in b.selected_nodes)b.selected_nodes[d].shape=a;g.graph.afterChange();g.setDirtyCanvas(!0)}},parentMenu:f,node:g});return!1};h.onMenuNodeRemove=function(a,b,d,f,g){if(!g)throw"no node passed";a=g.graph;a.beforeChange();b=h.active_canvas;if(!b.selected_nodes||1>=Object.keys(b.selected_nodes).length)!1!==g.removable&&a.remove(g);else for(var c in b.selected_nodes)d=b.selected_nodes[c],!1!==d.removable&& +a.remove(d);a.afterChange();g.setDirtyCanvas(!0,!0)};h.onMenuNodeToSubgraph=function(a,b,d,f,g){a=g.graph;if(b=h.active_canvas)d=Object.values(b.selected_nodes||{}),d.length||(d=[g]),f=e.createNode("graph/subgraph"),f.pos=g.pos.concat(),a.add(f),f.buildFromNodes(d),b.deselectAllNodes(),g.setDirtyCanvas(!0,!0)};h.onMenuNodeClone=function(a,b,d,f,g){g.graph.beforeChange();var c={};a=function(a){if(!1!==a.clonable){var b=a.clone();b&&(b.pos=[a.pos[0]+5,a.pos[1]+5],a.graph.add(b),c[b.id]=b)}};b=h.active_canvas; +if(!b.selected_nodes||1>=Object.keys(b.selected_nodes).length)a(g);else for(var e in b.selected_nodes)a(b.selected_nodes[e]);Object.keys(c).length&&b.selectNodes(c);g.graph.afterChange();g.setDirtyCanvas(!0,!0)};h.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"}};h.prototype.getCanvasMenuOptions=function(){if(this.getMenuOptions)var a=this.getMenuOptions();else a=[{content:"Add Node",has_submenu:!0,callback:h.onMenuAdd},{content:"Add Group",callback:h.onGroupAdd}],1Name", +f),l=e.querySelector("input");l&&c&&(l.value=c.label||"");var t=function(){a.graph.beforeChange();l.value&&(c&&(c.label=l.value),d.setDirty(!0));e.close();a.graph.afterChange()};e.querySelector("button").addEventListener("click",t);l.addEventListener("keydown",function(a){e.is_modified=!0;if(27==a.keyCode)e.close();else if(13==a.keyCode)t();else if(13!=a.keyCode&&"textarea"!=a.target.localName)return;a.preventDefault();a.stopPropagation()});l.focus()}},extra:a};a&&(c.title=a.type);var l=null;a&&(l= +a.getSlotInPosition(b.canvasX,b.canvasY),h.active_node=a);l?(g=[],a.getSlotMenuOptions?g=a.getSlotMenuOptions(l):(l&&l.output&&l.output.links&&l.output.links.length&&g.push({content:"Disconnect Links",slot:l}),b=l.input||l.output,b.removable&&g.push(b.locked?"Cannot remove":{content:"Remove Slot",slot:l}),b.nameLocked||g.push({content:"Rename Slot",slot:l})),c.title=(l.input?l.input.type:l.output.type)||"*",l.input&&l.input.type==e.ACTION&&(c.title="Action"),l.output&&l.output.type==e.EVENT&&(c.title= +"Event")):a?g=this.getNodeMenuOptions(a):(g=this.getCanvasMenuOptions(),(l=this.graph.getGroupOnPos(b.canvasX,b.canvasY))&&g.push(null,{content:"Edit Group",has_submenu:!0,submenu:{title:"Group",extra:l,options:this.getGroupMenuOptions(l)}}));g&&new e.ContextMenu(g,c,f)};e.compareObjects=function(a,b){for(var d in a)if(a[d]!=b[d])return!1;return!0};e.distance=E;e.colorToString=function(a){return"rgba("+Math.round(255*a[0]).toFixed()+","+Math.round(255*a[1]).toFixed()+","+Math.round(255*a[2]).toFixed()+ +","+(4==a.length?a[3].toFixed(2):"1.0")+")"};e.isInsideRectangle=D;e.growBounding=function(a,b,d){ba[2]&&(a[2]=b);da[3]&&(a[3]=d)};e.isInsideBounding=function(a,b){return a[0]b[1][0]||a[1]>b[1][1]?!1:!0};e.overlapBounding=J;e.hex2num=function(a){"#"==a.charAt(0)&&(a=a.slice(1));a=a.toUpperCase();for(var b=Array(3),d=0,f,g,c=0;6>c;c+=2)f="0123456789ABCDEF".indexOf(a.charAt(c)),g="0123456789ABCDEF".indexOf(a.charAt(c+1)),b[d]=16*f+g,d++;return b}; +e.num2hex=function(a){for(var b="#",d,f,g=0;3>g;g++)d=a[g]/16,f=a[g]%16,b+="0123456789ABCDEF".charAt(d)+"0123456789ABCDEF".charAt(f);return b};L.prototype.addItem=function(a,b,d){function f(a){var b=this.value;b&&b.has_submenu&&g.call(this,a)}function g(a){var b=this.value,f=!0;c.current_submenu&&c.current_submenu.close(a);if(d.callback){var g=d.callback.call(this,b,d,a,c,d.node);!0===g&&(f=!1)}if(b&&(b.callback&&!d.ignore_item_callbacks&&!0!==b.disabled&&(g=b.callback.call(this,b,d,a,c,d.extra), +!0===g&&(f=!1)),b.submenu)){if(!b.submenu.options)throw"ContextMenu submenu needs options";new c.constructor(b.submenu.options,{callback:b.submenu.callback,event:a,parentMenu:c,ignore_item_callbacks:b.submenu.ignore_item_callbacks,title:b.submenu.title,extra:b.submenu.extra,autoopen:d.autoopen});f=!1}f&&!c.lock&&c.close()}var c=this;d=d||{};var l=document.createElement("div");l.className="litemenu-entry submenu";var m=!1;if(null===b)l.classList.add("separator");else{l.innerHTML=b&&b.title?b.title: +a;if(l.value=b)b.disabled&&(m=!0,l.classList.add("disabled")),(b.submenu||b.has_submenu)&&l.classList.add("has_submenu");"function"==typeof b?(l.dataset.value=a,l.onclick_callback=b):l.dataset.value=b;b.className&&(l.className+=" "+b.className)}this.root.appendChild(l);m||l.addEventListener("click",g);!m&&d.autoopen&&e.pointerListenerAdd(l,"enter",f);return l};L.prototype.close=function(a,b){this.root.parentNode&&this.root.parentNode.removeChild(this.root);this.parentMenu&&!b&&(this.parentMenu.lock= +!1,this.parentMenu.current_submenu=null,void 0===a?this.parentMenu.close():a&&!L.isCursorOverElement(a,this.parentMenu.root)&&L.trigger(this.parentMenu.root,e.pointerevents_method+"leave",a));this.current_submenu&&this.current_submenu.close(a,!0);this.root.closing_timer&&clearTimeout(this.root.closing_timer)};L.trigger=function(a,b,d,f){var g=document.createEvent("CustomEvent");g.initCustomEvent(b,!0,!0,d);g.srcElement=f;a.dispatchEvent?a.dispatchEvent(g):a.__events&&a.__events.dispatchEvent(g);return g}; +L.prototype.getTopMenu=function(){return this.options.parentMenu?this.options.parentMenu.getTopMenu():this};L.prototype.getFirstEvent=function(){return this.options.parentMenu?this.options.parentMenu.getFirstEvent():this.options.event};L.isCursorOverElement=function(a,b){var d=a.clientX;a=a.clientY;return(b=b.getBoundingClientRect())?a>b.top&&ab.left&&dMath.abs(b))return f[1];a=(a-f[0])/b;return f[1]*(1-a)+g[1]*a}}return 0}};H.prototype.draw=function(a,b,d,f,g,c){if(d=this.points){this.size=b;var e=b[0]-2*this.margin;b=b[1]-2*this.margin;g=g||"#666";a.save();a.translate(this.margin,this.margin);f&&(a.fillStyle="#111",a.fillRect(0,0,e,b),a.fillStyle="#222",a.fillRect(.5*e,0,1,b),a.strokeStyle="#333", +a.strokeRect(0,0,e,b));a.strokeStyle=g;c&&(a.globalAlpha=.5);a.beginPath();for(f=0;fa[1])){var f=this.size[0]-2*this.margin,g=this.size[1]-2*this.margin,c=a[0]-this.margin;a=a[1]-this.margin; +this.selected=this.getCloserPoint([c,a],30/b.ds.scale);-1==this.selected&&(b=[c/f,1-a/g],d.push(b),d.sort(function(a,b){return a[0]-b[0]}),this.selected=d.indexOf(b),this.must_update=!0);if(-1!=this.selected)return!0}};H.prototype.onMouseMove=function(a,b){var d=this.points;if(d){var f=this.selected;if(!(0>f)){var g=(a[0]-this.margin)/(this.size[0]-2*this.margin),c=(a[1]-this.margin)/(this.size[1]-2*this.margin);this._nearest=this.getCloserPoint([a[0]-this.margin,a[1]-this.margin],30/b.ds.scale); +if(b=d[f]){var e=0==f||f==d.length-1;!e&&(-10>a[0]||a[0]>this.size[0]+10||-10>a[1]||a[1]>this.size[1]+10)?(d.splice(f,1),this.selected=-1):(b[0]=e?0==f?0:1:F(g,0,1),b[1]=1-F(c,0,1),d.sort(function(a,b){return a[0]-b[0]}),this.selected=d.indexOf(b),this.must_update=!0)}}}};H.prototype.onMouseUp=function(a,b){this.selected=-1;return!1};H.prototype.getCloserPoint=function(a,b){var d=this.points;if(!d)return-1;b=b||30;for(var f=this.size[0]-2*this.margin,g=this.size[1]-2*this.margin,c=d.length,e=[0,0], +l=1E6,m=-1,t=0;tl||w>b||(m=t,l=w)}return m};e.CurveEditor=H;e.getParameterNames=function(a){return(a+"").replace(/[/][/].*$/gm,"").replace(/\s+/g,"").replace(/[/][*][^/*]*[*][/]/g,"").split("){",1)[0].replace(/^[^(]*[(]/,"").replace(/=[^,]+/g,"").split(",").filter(Boolean)};e.pointerListenerAdd=function(a,b,d,f){f=void 0===f?!1:f;if(a&&a.addEventListener&&b&&"function"===typeof d){var g=e.pointerevents_method;if("pointer"==g&&!window.PointerEvent)switch(console.warn("sMethod=='pointer' && !window.PointerEvent"), +console.log("Converting pointer["+b+"] : down move up cancel enter TO touchstart touchmove touchend, etc .."),b){case "down":g="touch";b="start";break;case "move":g="touch";break;case "up":g="touch";b="end";break;case "cancel":g="touch";break;case "enter":console.log("debug: Should I send a move event?");break;default:console.warn("PointerEvent not available in this browser ? The event "+b+" would not be called")}switch(b){case "down":case "up":case "move":case "over":case "out":case "enter":a.addEventListener(g+ +b,d,f);case "leave":case "cancel":case "gotpointercapture":case "lostpointercapture":if("mouse"!=g)return a.addEventListener(g+b,d,f);default:return a.addEventListener(b,d,f)}}};e.pointerListenerRemove=function(a,b,d,f){f=void 0===f?!1:f;if(a&&a.removeEventListener&&b&&"function"===typeof d)switch(b){case "down":case "up":case "move":case "over":case "out":case "enter":"pointer"!=e.pointerevents_method&&"mouse"!=e.pointerevents_method||a.removeEventListener(e.pointerevents_method+b,d,f);case "leave":case "cancel":case "gotpointercapture":case "lostpointercapture":if("pointer"== +e.pointerevents_method)return a.removeEventListener(e.pointerevents_method+b,d,f);default:return a.removeEventListener(b,d,f)}};y.clamp=F;"undefined"==typeof window||window.requestAnimationFrame||(window.requestAnimationFrame=window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||function(a){window.setTimeout(a,1E3/60)})})(this); +"undefined"!=typeof exports&&(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); +(function(y){function c(){this.addOutput("in ms","number");this.addOutput("in sec","number")}function k(){this.size=[140,80];this.properties={enabled:!0};this.enabled=!0;this.subgraph=new I.LGraph;this.subgraph._subgraph_node=this;this.subgraph._is_subgraph=!0;this.subgraph.onTrigger=this.onSubgraphTrigger.bind(this);this.subgraph.onInputAdded=this.onSubgraphNewInput.bind(this);this.subgraph.onInputRenamed=this.onSubgraphRenamedInput.bind(this);this.subgraph.onInputTypeChanged=this.onSubgraphTypeChangeInput.bind(this); +this.subgraph.onInputRemoved=this.onSubgraphRemovedInput.bind(this);this.subgraph.onOutputAdded=this.onSubgraphNewOutput.bind(this);this.subgraph.onOutputRenamed=this.onSubgraphRenamedOutput.bind(this);this.subgraph.onOutputTypeChanged=this.onSubgraphTypeChangeOutput.bind(this);this.subgraph.onOutputRemoved=this.onSubgraphRemovedOutput.bind(this)}function n(){this.addOutput("","number");this.name_in_graph="";this.properties={name:"",type:"number",value:0};var a=this;this.name_widget=this.addWidget("text", +"Name",this.properties.name,function(b){b&&a.setProperty("name",b)});this.type_widget=this.addWidget("text","Type",this.properties.type,function(b){a.setProperty("type",b)});this.value_widget=this.addWidget("number","Value",this.properties.value,function(b){a.setProperty("value",b)});this.widgets_up=!0;this.size=[180,90]}function r(){this.addInput("","");this.name_in_graph="";this.properties={name:"",type:""};this.name_widget=this.addWidget("text","Name",this.properties.name,"name");this.type_widget= +this.addWidget("text","Type",this.properties.type,"type");this.widgets_up=!0;this.size=[180,60]}function u(){this.addOutput("value","number");this.addProperty("value",1);this.widget=this.addWidget("number","value",1,"value");this.widgets_up=!0;this.size=[180,30]}function h(){this.addOutput("bool","boolean");this.addProperty("value",!0);this.widget=this.addWidget("toggle","value",!0,"value");this.widgets_up=this.serialize_widgets=!0;this.size=[140,30]}function E(){this.addOutput("string","string"); +this.addProperty("value","");this.widget=this.addWidget("text","value","","value");this.widgets_up=!0;this.size=[180,30]}function D(){this.addOutput("obj","object");this.size=[120,30];this._object={}}function J(){this.addInput("url","string");this.addOutput("file","string");this.addProperty("url","");this.addProperty("type","text");this.widget=this.addWidget("text","url","","url");this._data=null}function L(){this.addInput("parse",I.ACTION);this.addInput("json","string");this.addOutput("done",I.EVENT); +this.addOutput("object","object");this.widget=this.addWidget("button","parse","",this.parse.bind(this));this._obj=this._str=null}function H(){this.addOutput("data","object");this.addProperty("value","");this.widget=this.addWidget("text","json","","value");this.widgets_up=!0;this.size=[140,30];this._value=null}function F(){this._value=[];this.addInput("json","");this.addOutput("arrayOut","array");this.addOutput("length","number");this.addProperty("value","[]");this.widget=this.addWidget("text","array", +this.properties.value,"value");this.widgets_up=!0;this.size=[140,50]}function e(){this.addInput("arr","array");this.addInput("value","");this.addOutput("arr","array");this.properties={index:0};this.widget=this.addWidget("number","i",this.properties.index,"index",{precision:0,step:10,min:0})}function K(){this.addInput("array","array,table,string");this.addInput("index","number");this.addOutput("value","");this.addProperty("index",0)}function B(){this.addInput("table","table");this.addInput("row","number"); +this.addInput("col","number");this.addOutput("value","");this.addProperty("row",0);this.addProperty("column",0)}function M(){this.addInput("obj","object");this.addOutput("property",0);this.addProperty("value",0);this.widget=this.addWidget("text","prop.","",this.setValue.bind(this));this.widgets_up=!0;this.size=[140,30];this._value=null}function l(){this.addInput("obj","");this.addOutput("keys","array");this.size=[140,30]}function m(){this.addInput("obj","");this.addInput("value","");this.addOutput("obj", +"");this.properties={property:""};this.name_widget=this.addWidget("text","prop.",this.properties.property,"property")}function w(){this.addInput("A","object");this.addInput("B","object");this.addOutput("out","object");this._result={};var a=this;this.addWidget("button","clear","",function(){a._result={}});this.size=this.computeSize()}function N(){this.size=[60,30];this.addInput("in");this.addOutput("out");this.properties={varname:"myname",container:N.LITEGRAPH};this.value=null}function a(a){return a&& +null!=a.length?Number(a.length):0}function a(a){return a&&null!=a.length?Number(a.length):0}function b(){this.size=[60,30];this.addInput("data",0);this.addInput("download",I.ACTION);this.properties={filename:"data.json"};this.value=null;var a=this;this.addWidget("button","Download","",function(b){a.value&&a.downloadAsFile()})}function d(){this.size=[60,30];this.addInput("value",0,{label:""});this.value=0}function f(){this.addInput("in",0);this.addOutput("out",0);this.size=[40,30]}function g(){this.mode= +I.ON_EVENT;this.size=[80,30];this.addProperty("msg","");this.addInput("log",I.EVENT);this.addInput("msg",0)}function q(){this.mode=I.ON_EVENT;this.addProperty("msg","");this.addInput("",I.EVENT);this.widget=this.addWidget("text","Text","","msg");this.widgets_up=!0;this.size=[200,30]}function z(){this.size=[60,30];this.addProperty("onExecute","return A;");this.addInput("A",0);this.addInput("B",0);this.addOutput("out",0);this._func=null;this.data={}}function P(){this.addInput("A",0);this.addInput("B", +0);this.addOutput("true","boolean");this.addOutput("false","boolean");this.addProperty("A",1);this.addProperty("B",1);this.addProperty("OP","==","enum",{values:P.values});this.addWidget("combo","Op.",this.properties.OP,{property:"OP",values:P.values});this.size=[80,60]}var I=y.LiteGraph;c.title="Time";c.desc="Time";c.prototype.onExecute=function(){this.setOutputData(0,1E3*this.graph.globaltime);this.setOutputData(1,this.graph.globaltime)};I.registerNodeType("basic/time",c);k.title="Subgraph";k.desc= +"Graph inside a node";k.title_color="#334";k.prototype.onGetInputs=function(){return[["enabled","boolean"]]};k.prototype.onDblClick=function(a,b,d){var f=this;setTimeout(function(){d.openSubgraph(f.subgraph)},10)};k.prototype.onAction=function(a,b){this.subgraph.onAction(a,b)};k.prototype.onExecute=function(){if(this.enabled=this.getInputOrProperty("enabled")){if(this.inputs)for(var a=0;aa&&(b[0]=c?this.trigger(null,e,h):this._pending.push([c,e])};D.prototype.onExecute= +function(c,e){c=1E3*this.graph.elapsed_time;this.isInputConnected(1)&&(this.properties.time_in_ms=this.getInputData(1));for(var h=0;he[1]))return this.old_y=c.canvasY,this.captureInput(!0),this.mouse_captured=!0};n.prototype.onMouseMove=function(c){if(this.mouse_captured){var e=this.old_y-c.canvasY;c.shiftKey&&(e*=10);if(c.metaKey||c.altKey)e*=.1;this.old_y=c.canvasY;c=this._remainder+e/n.pixels_threshold;this._remainder=c%1;c=clamp(this.properties.value+ +(c|0)*this.properties.step,this.properties.min,this.properties.max);this.properties.value=c;this.graph._version++;this.setDirtyCanvas(!0)}};n.prototype.onMouseUp=function(c,e){200>c.click_time&&(this.properties.value=clamp(this.properties.value+(e[1]>.5*this.size[1]?-1:1)*this.properties.step,this.properties.min,this.properties.max),this.graph._version++,this.setDirtyCanvas(!0));this.mouse_captured&&(this.mouse_captured=!1,this.captureInput(!1))};H.registerNodeType("widget/number",n);r.title="Combo"; +r.desc="Widget to select from a list";r.prototype.onExecute=function(){this.setOutputData(0,this.properties.value)};r.prototype.onPropertyChanged=function(c,e){"values"==c?(this._values=e.split(";"),this.widget.options.values=this._values):"value"==c&&(this.widget.value=e)};H.registerNodeType("widget/combo",r);u.title="Knob";u.desc="Circular controller";u.size=[80,100];u.prototype.onDrawForeground=function(c){if(!this.flags.collapsed){-1==this.value&&(this.value=(this.properties.value-this.properties.min)/ +(this.properties.max-this.properties.min));var e=.5*this.size[0],h=.5*this.size[1],k=.5*Math.min(this.size[0],this.size[1])-5;c.globalAlpha=1;c.save();c.translate(e,h);c.rotate(.75*Math.PI);c.fillStyle="rgba(0,0,0,0.5)";c.beginPath();c.moveTo(0,0);c.arc(0,0,k,0,1.5*Math.PI);c.fill();c.strokeStyle="black";c.fillStyle=this.properties.color;c.lineWidth=2;c.beginPath();c.moveTo(0,0);c.arc(0,0,k-4,0,1.5*Math.PI*Math.max(.01,this.value));c.closePath();c.fill();c.lineWidth=1;c.globalAlpha=1;c.restore(); +c.fillStyle="black";c.beginPath();c.arc(e,h,.75*k,0,2*Math.PI,!0);c.fill();c.fillStyle=this.mouseOver?"white":this.properties.color;c.beginPath();var n=this.value*Math.PI*1.5+.75*Math.PI;c.arc(e+Math.cos(n)*k*.65,h+Math.sin(n)*k*.65,.05*k,0,2*Math.PI,!0);c.fill();c.fillStyle=this.mouseOver?"white":"#AAA";c.font=Math.floor(.5*k)+"px Arial";c.textAlign="center";c.fillText(this.properties.value.toFixed(this.properties.precision),e,h+.15*k)}};u.prototype.onExecute=function(){this.setOutputData(0,this.properties.value); +this.boxcolor=H.colorToString([this.value,this.value,this.value])};u.prototype.onMouseDown=function(c){this.center=[.5*this.size[0],.5*this.size[1]+20];this.radius=.5*this.size[0];if(20>c.canvasY-this.pos[1]||H.distance([c.canvasX,c.canvasY],[this.pos[0]+this.center[0],this.pos[1]+this.center[1]])>this.radius)return!1;this.oldmouse=[c.canvasX-this.pos[0],c.canvasY-this.pos[1]];this.captureInput(!0);return!0};u.prototype.onMouseMove=function(c){if(this.oldmouse){c=[c.canvasX-this.pos[0],c.canvasY- +this.pos[1]];var e=this.value;e-=.01*(c[1]-this.oldmouse[1]);1e&&(e=0);this.value=e;this.properties.value=this.properties.min+(this.properties.max-this.properties.min)*this.value;this.oldmouse=c;this.setDirtyCanvas(!0)}};u.prototype.onMouseUp=function(c){this.oldmouse&&(this.oldmouse=null,this.captureInput(!1))};u.prototype.onPropertyChanged=function(c,e){if("min"==c||"max"==c||"value"==c)return this.properties[c]=parseFloat(e),!0};H.registerNodeType("widget/knob",u);h.title="Inner Slider"; +h.prototype.onPropertyChanged=function(c,e){"value"==c&&(this.slider.value=e)};h.prototype.onExecute=function(){this.setOutputData(0,this.properties.value)};H.registerNodeType("widget/internal_slider",h);E.title="H.Slider";E.desc="Linear slider controller";E.prototype.onDrawForeground=function(c){-1==this.value&&(this.value=(this.properties.value-this.properties.min)/(this.properties.max-this.properties.min));c.globalAlpha=1;c.lineWidth=1;c.fillStyle="#000";c.fillRect(2,2,this.size[0]-4,this.size[1]- +4);c.fillStyle=this.properties.color;c.beginPath();c.rect(4,4,(this.size[0]-8)*this.value,this.size[1]-8);c.fill()};E.prototype.onExecute=function(){this.properties.value=this.properties.min+(this.properties.max-this.properties.min)*this.value;this.setOutputData(0,this.properties.value);this.boxcolor=H.colorToString([this.value,this.value,this.value])};E.prototype.onMouseDown=function(c){if(0>c.canvasY-this.pos[1])return!1;this.oldmouse=[c.canvasX-this.pos[0],c.canvasY-this.pos[1]];this.captureInput(!0); +return!0};E.prototype.onMouseMove=function(c){if(this.oldmouse){c=[c.canvasX-this.pos[0],c.canvasY-this.pos[1]];var e=this.value;e+=(c[0]-this.oldmouse[0])/this.size[0];1e&&(e=0);this.value=e;this.oldmouse=c;this.setDirtyCanvas(!0)}};E.prototype.onMouseUp=function(c){this.oldmouse=null;this.captureInput(!1)};E.prototype.onMouseLeave=function(c){};H.registerNodeType("widget/hslider",E);D.title="Progress";D.desc="Shows data in linear progress";D.prototype.onExecute=function(){var c=this.getInputData(0); +void 0!=c&&(this.properties.value=c)};D.prototype.onDrawForeground=function(c){c.lineWidth=1;c.fillStyle=this.properties.color;var e=(this.properties.value-this.properties.min)/(this.properties.max-this.properties.min);e=Math.min(1,e);e=Math.max(0,e);c.fillRect(2,2,(this.size[0]-4)*e,this.size[1]-4)};H.registerNodeType("widget/progress",D);J.title="Text";J.desc="Shows the input value";J.widgets=[{name:"resize",text:"Resize box",type:"button"},{name:"led_text",text:"LED",type:"minibutton"},{name:"normal_text", +text:"Normal",type:"minibutton"}];J.prototype.onDrawForeground=function(c){c.fillStyle=this.properties.color;var e=this.properties.value;this.properties.glowSize?(c.shadowColor=this.properties.color,c.shadowOffsetX=0,c.shadowOffsetY=0,c.shadowBlur=this.properties.glowSize):c.shadowColor="transparent";var h=this.properties.fontsize;c.textAlign=this.properties.align;c.font=h.toString()+"px "+this.properties.font;this.str="number"==typeof e?e.toFixed(this.properties.decimals):e;if("string"==typeof this.str){e= +this.str.replace(/[\r\n]/g,"\\n").split("\\n");for(var k=0;kr?k.xbox.axes.lx:0,this._left_axis[1]=Math.abs(k.xbox.axes.ly)>r?k.xbox.axes.ly:0,this._right_axis[0]=Math.abs(k.xbox.axes.rx)>r?k.xbox.axes.rx:0,this._right_axis[1]=Math.abs(k.xbox.axes.ry)>r?k.xbox.axes.ry:0,this._triggers[0]=Math.abs(k.xbox.axes.ltrigger)>r?k.xbox.axes.ltrigger: +0,this._triggers[1]=Math.abs(k.xbox.axes.rtrigger)>r?k.xbox.axes.rtrigger:0);if(this.outputs)for(r=0;rr;r++)if(k[r]){k=k[r];r=this.xbox_mapping;r||(r=this.xbox_mapping={axes:[], +buttons:{},hat:"",hatmap:c.CENTER});r.axes.lx=k.axes[0];r.axes.ly=k.axes[1];r.axes.rx=k.axes[2];r.axes.ry=k.axes[3];r.axes.ltrigger=k.buttons[6].value;r.axes.rtrigger=k.buttons[7].value;r.hat="";r.hatmap=c.CENTER;for(var u=0;uu)r.buttons[c.mapping_array[u]]=k.buttons[u].pressed,k.buttons[u].was_pressed&&this.trigger(c.mapping_array[u]+"_button_event");else switch(u){case 12:k.buttons[u].pressed&&(r.hat+="up",r.hatmap|=c.UP); +break;case 13:k.buttons[u].pressed&&(r.hat+="down",r.hatmap|=c.DOWN);break;case 14:k.buttons[u].pressed&&(r.hat+="left",r.hatmap|=c.LEFT);break;case 15:k.buttons[u].pressed&&(r.hat+="right",r.hatmap|=c.RIGHT);break;case 16:r.buttons.home=k.buttons[u].pressed}k.xbox=r;return k}};c.prototype.onDrawBackground=function(c){if(!this.flags.collapsed){var k=this._left_axis,n=this._right_axis;c.strokeStyle="#88A";c.strokeRect(.5*(k[0]+1)*this.size[0]-4,.5*(k[1]+1)*this.size[1]-4,8,8);c.strokeStyle="#8A8"; +c.strokeRect(.5*(n[0]+1)*this.size[0]-4,.5*(n[1]+1)*this.size[1]-4,8,8);k=this.size[1]/this._current_buttons.length;c.fillStyle="#AEB";for(n=0;n","enum",{values:N.values});this.addWidget("combo", +"Cond.",this.properties.OP,{property:"OP",values:N.values});this.size=[80,60]}function a(){this.addInput("in",0);this.addInput("cond","boolean");this.addOutput("true",0);this.addOutput("false",0);this.size=[80,60]}function b(){this.addInput("inc","number");this.addOutput("total","number");this.addProperty("increment",1);this.addProperty("value",0)}function d(){this.addInput("v","number");this.addOutput("sin","number");this.addProperty("amplitude",1);this.addProperty("offset",0);this.bgImageUrl="nodes/imgs/icon-sin.png"} +function f(){this.addInput("x","number");this.addInput("y","number");this.addOutput("","number");this.properties={x:1,y:1,formula:"x+y"};this.code_widget=this.addWidget("text","F(x,y)",this.properties.formula,function(a,b,d){d.properties.formula=a});this.addWidget("toggle","allow",v.allow_scripts,function(a){v.allow_scripts=a});this._func=null}function g(){this.addInput("vec2","vec2");this.addOutput("x","number");this.addOutput("y","number")}function q(){this.addInputs([["x","number"],["y","number"]]); +this.addOutput("vec2","vec2");this.properties={x:0,y:0};this._data=new Float32Array(2)}function z(){this.addInput("vec3","vec3");this.addOutput("x","number");this.addOutput("y","number");this.addOutput("z","number")}function P(){this.addInputs([["x","number"],["y","number"],["z","number"]]);this.addOutput("vec3","vec3");this.properties={x:0,y:0,z:0};this._data=new Float32Array(3)}function I(){this.addInput("vec4","vec4");this.addOutput("x","number");this.addOutput("y","number");this.addOutput("z", +"number");this.addOutput("w","number")}function t(){this.addInputs([["x","number"],["y","number"],["z","number"],["w","number"]]);this.addOutput("vec4","vec4");this.properties={x:0,y:0,z:0,w:0};this._data=new Float32Array(4)}var v=y.LiteGraph;c.title="Converter";c.desc="type A to type B";c.prototype.onExecute=function(){var a=this.getInputData(0);if(null!=a&&this.outputs)for(var b=0;ba&&(a+=1024);var c=Math.floor(a);a-=c;d=h.data[c];c=h.data[1023==c?0:c+1];b&&(a=a*a*a*(a*(6*a-15)+10));return d*(1-a)+c*a};h.prototype.onExecute=function(){var a=this.getInputData(0)|| +0,b=this.properties.octaves||1,d=0,c=1;a+=this.properties.seed||0;for(var f=this.properties.speed||1,g=0,e=0;ec);++e);a=this.properties.min;this._last_v=d/g*(this.properties.max-a)+a;this.setOutputData(0,this._last_v)};h.prototype.onDrawBackground=function(a){this.outputs[0].label=(this._last_v||0).toFixed(3)};v.registerNodeType("math/noise",h);E.title="Spikes";E.desc="spike every random time";E.prototype.onExecute= +function(){var a=this.graph.elapsed_time;this._remaining_time-=a;this._blink_time-=a;a=0;0this._remaining_time?(this._remaining_time=Math.random()*(this.properties.max_time-this.properties.min_time)+this.properties.min_time,this._blink_time=this.properties.duration,this.boxcolor="#FFF"):this.boxcolor="#000";this.setOutputData(0,a)};v.registerNodeType("math/spikes",E);D.title="Clamp";D.desc="Clamp number between min and max"; +D.prototype.onExecute=function(){var a=this.getInputData(0);null!=a&&(a=Math.max(this.properties.min,a),a=Math.min(this.properties.max,a),this.setOutputData(0,a))};D.prototype.getCode=function(a){a="";this.isInputConnected(0)&&(a+="clamp({{0}},"+this.properties.min+","+this.properties.max+")");return a};v.registerNodeType("math/clamp",D);J.title="Lerp";J.desc="Linear Interpolation";J.prototype.onExecute=function(){var a=this.getInputData(0);null==a&&(a=0);var b=this.getInputData(1);null==b&&(b=0); +var d=this.properties.f,c=this.getInputData(2);void 0!==c&&(d=c);this.setOutputData(0,a*(1-d)+b*d)};J.prototype.onGetInputs=function(){return[["f","number"]]};v.registerNodeType("math/lerp",J);L.title="Abs";L.desc="Absolute";L.prototype.onExecute=function(){var a=this.getInputData(0);null!=a&&this.setOutputData(0,Math.abs(a))};v.registerNodeType("math/abs",L);H.title="Floor";H.desc="Floor number to remove fractional part";H.prototype.onExecute=function(){var a=this.getInputData(0);null!=a&&this.setOutputData(0, +Math.floor(a))};v.registerNodeType("math/floor",H);F.title="Frac";F.desc="Returns fractional part";F.prototype.onExecute=function(){var a=this.getInputData(0);null!=a&&this.setOutputData(0,a%1)};v.registerNodeType("math/frac",F);e.title="Smoothstep";e.desc="Smoothstep";e.prototype.onExecute=function(){var a=this.getInputData(0);if(void 0!==a){var b=this.properties.A;a=clamp((a-b)/(this.properties.B-b),0,1);this.setOutputData(0,a*a*(3-2*a))}};v.registerNodeType("math/smoothstep",e);K.title="Scale"; +K.desc="v * factor";K.prototype.onExecute=function(){var a=this.getInputData(0);null!=a&&this.setOutputData(0,a*this.properties.factor)};v.registerNodeType("math/scale",K);B.title="Gate";B.desc="if v is true, then outputs A, otherwise B";B.prototype.onExecute=function(){var a=this.getInputData(0);this.setOutputData(0,this.getInputData(a?1:2))};v.registerNodeType("math/gate",B);M.title="Average";M.desc="Average Filter";M.prototype.onExecute=function(){var a=this.getInputData(0);null==a&&(a=0);var b= +this._values.length;this._values[this._current%b]=a;this._current+=1;this._current>b&&(this._current=0);for(var d=a=0;db&&(b=1);this.properties.samples=Math.round(b);a=this._values;this._values=new Float32Array(this.properties.samples);a.length<=this._values.length?this._values.set(a):this._values.set(a.subarray(0,this._values.length))};v.registerNodeType("math/average",M);l.title="TendTo";l.desc="moves the output value always closer to the input"; +l.prototype.onExecute=function(){var a=this.getInputData(0);null==a&&(a=0);var b=this.properties.factor;this._value=null==this._value?a:this._value*(1-b)+a*b;this.setOutputData(0,this._value)};v.registerNodeType("math/tendTo",l);m.values="+ - * / % ^ max min".split(" ");m.funcs={"+":function(a,b){return a+b},"-":function(a,b){return a-b},x:function(a,b){return a*b},X:function(a,b){return a*b},"*":function(a,b){return a*b},"/":function(a,b){return a/b},"%":function(a,b){return a%b},"^":function(a, +b){return Math.pow(a,b)},max:function(a,b){return Math.max(a,b)},min:function(a,b){return Math.min(a,b)}};m.title="Operation";m.desc="Easy math operators";m["@OP"]={type:"enum",title:"operation",values:m.values};m.size=[100,60];m.prototype.getTitle=function(){return"max"==this.properties.OP||"min"==this.properties.OP?this.properties.OP+"(A,B)":"A "+this.properties.OP+" B"};m.prototype.setValue=function(a){"string"==typeof a&&(a=parseFloat(a));this.properties.value=a};m.prototype.onPropertyChanged= +function(a,b){"OP"==a&&(this._func=m.funcs[this.properties.OP],this._func||(console.warn("Unknown operation: "+this.properties.OP),this._func=function(a){return a}))};m.prototype.onExecute=function(){var a=this.getInputData(0),b=this.getInputData(1);null!=a?a.constructor===Number&&(this.properties.A=a):a=this.properties.A;null!=b?this.properties.B=b:b=this.properties.B;var d=m.funcs[this.properties.OP];if(a.constructor===Number)var c=d(a,b);else if(a.constructor===Array){c=this._result;c.length=a.length; +for(var f=0;fB":g=a>b;break;case "A=B":g=a>=b}this.setOutputData(d,g)}}};w.prototype.onGetOutputs=function(){return[["A==B","boolean"],["A!=B","boolean"],["A>B","boolean"],["A=B","boolean"],["A<=B","boolean"]]};v.registerNodeType("math/compare",w);v.registerSearchboxExtra("math/compare","==",{outputs:[["A==B","boolean"]],title:"A==B"});v.registerSearchboxExtra("math/compare","!=",{outputs:[["A!=B","boolean"]],title:"A!=B"});v.registerSearchboxExtra("math/compare",">",{outputs:[["A>B","boolean"]], +title:"A>B"});v.registerSearchboxExtra("math/compare","<",{outputs:[["A=",{outputs:[["A>=B","boolean"]],title:"A>=B"});v.registerSearchboxExtra("math/compare","<=",{outputs:[["A<=B","boolean"]],title:"A<=B"});N.values="> < == != <= >= || &&".split(" ");N["@OP"]={type:"enum",title:"operation",values:N.values};N.title="Condition";N.desc="evaluates condition between A and B";N.prototype.getTitle=function(){return"A "+this.properties.OP+ +" B"};N.prototype.onExecute=function(){var a=this.getInputData(0);void 0===a?a=this.properties.A:this.properties.A=a;var b=this.getInputData(1);void 0===b?b=this.properties.B:this.properties.B=b;var d=!0;switch(this.properties.OP){case ">":d=a>b;break;case "<":d=a=":d=a>=b;break;case "||":d=a||b;break;case "&&":d=a&&b}this.setOutputData(0,d);this.setOutputData(1,!d)};v.registerNodeType("math/condition",N);a.title= +"Branch";a.desc="If condition is true, outputs IN in true, otherwise in false";a.prototype.onExecute=function(){var a=this.getInputData(0);this.getInputData(1)?(this.setOutputData(0,a),this.setOutputData(1,null)):(this.setOutputData(0,null),this.setOutputData(1,a))};v.registerNodeType("math/branch",a);b.title="Accumulate";b.desc="Increments a value every time";b.prototype.onExecute=function(){null===this.properties.value&&(this.properties.value=0);var a=this.getInputData(0);this.properties.value= +null!==a?this.properties.value+a:this.properties.value+this.properties.increment;this.setOutputData(0,this.properties.value)};v.registerNodeType("math/accumulate",b);d.title="Trigonometry";d.desc="Sin Cos Tan";d.prototype.onExecute=function(){var a=this.getInputData(0);null==a&&(a=0);var b=this.properties.amplitude,d=this.findInputSlot("amplitude");-1!=d&&(b=this.getInputData(d));var c=this.properties.offset;d=this.findInputSlot("offset");-1!=d&&(c=this.getInputData(d));d=0;for(var f=this.outputs.length;d< +f;++d){switch(this.outputs[d].name){case "sin":var g=Math.sin(a);break;case "cos":g=Math.cos(a);break;case "tan":g=Math.tan(a);break;case "asin":g=Math.asin(a);break;case "acos":g=Math.acos(a);break;case "atan":g=Math.atan(a)}this.setOutputData(d,b*g+c)}};d.prototype.onGetInputs=function(){return[["v","number"],["amplitude","number"],["offset","number"]]};d.prototype.onGetOutputs=function(){return[["sin","number"],["cos","number"],["tan","number"],["asin","number"],["acos","number"],["atan","number"]]}; +v.registerNodeType("math/trigonometry",d);v.registerSearchboxExtra("math/trigonometry","SIN()",{outputs:[["sin","number"]],title:"SIN()"});v.registerSearchboxExtra("math/trigonometry","COS()",{outputs:[["cos","number"]],title:"COS()"});v.registerSearchboxExtra("math/trigonometry","TAN()",{outputs:[["tan","number"]],title:"TAN()"});f.title="Formula";f.desc="Compute formula";f.size=[160,100];M.prototype.onPropertyChanged=function(a,b){"formula"==a&&(this.code_widget.value=b)};f.prototype.onExecute= +function(){if(v.allow_scripts){var a=this.getInputData(0),b=this.getInputData(1);null!=a?this.properties.x=a:a=this.properties.x;null!=b?this.properties.y=b:b=this.properties.y;try{this._func&&this._func_code==this.properties.formula||(this._func=new Function("x","y","TIME","return "+this.properties.formula),this._func_code=this.properties.formula);var d=this._func(a,b,this.graph.globaltime);this.boxcolor=null}catch(A){this.boxcolor="red"}this.setOutputData(0,d)}};f.prototype.getTitle=function(){return this._func_code|| +"Formula"};f.prototype.onDrawBackground=function(){var a=this.properties.formula;this.outputs&&this.outputs.length&&(this.outputs[0].label=a)};v.registerNodeType("math/formula",f);g.title="Vec2->XY";g.desc="vector 2 to components";g.prototype.onExecute=function(){var a=this.getInputData(0);null!=a&&(this.setOutputData(0,a[0]),this.setOutputData(1,a[1]))};v.registerNodeType("math3d/vec2-to-xy",g);q.title="XY->Vec2";q.desc="components to vector2";q.prototype.onExecute=function(){var a=this.getInputData(0); +null==a&&(a=this.properties.x);var b=this.getInputData(1);null==b&&(b=this.properties.y);var d=this._data;d[0]=a;d[1]=b;this.setOutputData(0,d)};v.registerNodeType("math3d/xy-to-vec2",q);z.title="Vec3->XYZ";z.desc="vector 3 to components";z.prototype.onExecute=function(){var a=this.getInputData(0);null!=a&&(this.setOutputData(0,a[0]),this.setOutputData(1,a[1]),this.setOutputData(2,a[2]))};v.registerNodeType("math3d/vec3-to-xyz",z);P.title="XYZ->Vec3";P.desc="components to vector3";P.prototype.onExecute= +function(){var a=this.getInputData(0);null==a&&(a=this.properties.x);var b=this.getInputData(1);null==b&&(b=this.properties.y);var d=this.getInputData(2);null==d&&(d=this.properties.z);var c=this._data;c[0]=a;c[1]=b;c[2]=d;this.setOutputData(0,c)};v.registerNodeType("math3d/xyz-to-vec3",P);I.title="Vec4->XYZW";I.desc="vector 4 to components";I.prototype.onExecute=function(){var a=this.getInputData(0);null!=a&&(this.setOutputData(0,a[0]),this.setOutputData(1,a[1]),this.setOutputData(2,a[2]),this.setOutputData(3, +a[3]))};v.registerNodeType("math3d/vec4-to-xyzw",I);t.title="XYZW->Vec4";t.desc="components to vector4";t.prototype.onExecute=function(){var a=this.getInputData(0);null==a&&(a=this.properties.x);var b=this.getInputData(1);null==b&&(b=this.properties.y);var d=this.getInputData(2);null==d&&(d=this.properties.z);var c=this.getInputData(3);null==c&&(c=this.properties.w);var f=this._data;f[0]=a;f[1]=b;f[2]=d;f[3]=c;this.setOutputData(0,f)};v.registerNodeType("math3d/xyzw-to-vec4",t)})(this); +(function(y){function c(){this.addInput("T","vec3");this.addInput("R","vec3");this.addInput("S","vec3");this.addOutput("mat4","mat4");this.properties={T:[0,0,0],R:[0,0,0],S:[1,1,1],R_in_degrees:!0};this._result=mat4.create();this._must_update=!0}function k(){this.addInput("A","number,vec3");this.addInput("B","number,vec3");this.addOutput("=","number,vec3");this.addProperty("OP","+","enum",{values:k.values});this._result=vec3.create()}function n(){this.addInput("in","vec3");this.addInput("f","number"); +this.addOutput("out","vec3");this.properties={f:1};this._data=new Float32Array(3)}function r(){this.addInput("in","vec3");this.addOutput("out","number")}function u(){this.addInput("in","vec3");this.addOutput("out","vec3");this._data=new Float32Array(3)}function h(){this.addInput("A","vec3");this.addInput("B","vec3");this.addInput("f","vec3");this.addOutput("out","vec3");this.properties={f:.5};this._data=new Float32Array(3)}function E(){this.addInput("A","vec3");this.addInput("B","vec3");this.addOutput("out", +"number")}var D=y.LiteGraph;c.title="mat4";c.temp_quat=new Float32Array([0,0,0,1]);c.temp_mat4=new Float32Array(16);c.temp_vec3=new Float32Array(3);c.prototype.onPropertyChanged=function(c,e){this._must_update=!0};c.prototype.onExecute=function(){var e=this._result,l=c.temp_quat,m=c.temp_mat4,h=c.temp_vec3,k=this.getInputData(0),a=this.getInputData(1),b=this.getInputData(2);if(this._must_update||k||a||b)k=k||this.properties.T,a=a||this.properties.R,b=b||this.properties.S,mat4.identity(e),mat4.translate(e, +e,k),this.properties.R_in_degrees?(h.set(a),vec3.scale(h,h,DEG2RAD),quat.fromEuler(l,h)):quat.fromEuler(l,a),mat4.fromQuat(m,l),mat4.multiply(e,e,m),mat4.scale(e,e,b);this.setOutputData(0,e)};D.registerNodeType("math3d/mat4",c);k.values="+ - * / % ^ max min dot cross".split(" ");D.registerSearchboxExtra("math3d/operation","CROSS()",{properties:{OP:"cross"},title:"CROSS()"});D.registerSearchboxExtra("math3d/operation","DOT()",{properties:{OP:"dot"},title:"DOT()"});k.title="Operation";k.desc="Easy math 3D operators"; +k["@OP"]={type:"enum",title:"operation",values:k.values};k.size=[100,60];k.prototype.getTitle=function(){return"max"==this.properties.OP||"min"==this.properties.OP?this.properties.OP+"(A,B)":"A "+this.properties.OP+" B"};k.prototype.onExecute=function(){var c=this.getInputData(0),e=this.getInputData(1);if(null!=c&&null!=e){c.constructor===Number&&(c=[c,c,c]);e.constructor===Number&&(e=[e,e,e]);var m=this._result;switch(this.properties.OP){case "+":m=vec3.add(m,c,e);break;case "-":m=vec3.sub(m,c,e); +break;case "x":case "X":case "*":m=vec3.mul(m,c,e);break;case "/":m=vec3.div(m,c,e);break;case "%":m[0]=c[0]%e[0];m[1]=c[1]%e[1];m[2]=c[2]%e[2];break;case "^":m[0]=Math.pow(c[0],e[0]);m[1]=Math.pow(c[1],e[1]);m[2]=Math.pow(c[2],e[2]);break;case "max":m[0]=Math.max(c[0],e[0]);m[1]=Math.max(c[1],e[1]);m[2]=Math.max(c[2],e[2]);break;case "min":m[0]=Math.min(c[0],e[0]),m[1]=Math.min(c[1],e[1]),m[2]=Math.min(c[2],e[2]);case "dot":m=vec3.dot(c,e);break;case "cross":vec3.cross(m,c,e);break;default:console.warn("Unknown operation: "+ +this.properties.OP)}this.setOutputData(0,m)}};k.prototype.onDrawBackground=function(c){this.flags.collapsed||(c.font="40px Arial",c.fillStyle="#666",c.textAlign="center",c.fillText(this.properties.OP,.5*this.size[0],.5*(this.size[1]+D.NODE_TITLE_HEIGHT)),c.textAlign="left")};D.registerNodeType("math3d/operation",k);n.title="vec3_scale";n.desc="scales the components of a vec3";n.prototype.onExecute=function(){var c=this.getInputData(0);if(null!=c){var e=this.getInputData(1);null==e&&(e=this.properties.f); +var m=this._data;m[0]=c[0]*e;m[1]=c[1]*e;m[2]=c[2]*e;this.setOutputData(0,m)}};D.registerNodeType("math3d/vec3-scale",n);r.title="vec3_length";r.desc="returns the module of a vector";r.prototype.onExecute=function(){var c=this.getInputData(0);null!=c&&this.setOutputData(0,Math.sqrt(c[0]*c[0]+c[1]*c[1]+c[2]*c[2]))};D.registerNodeType("math3d/vec3-length",r);u.title="vec3_normalize";u.desc="returns the vector normalized";u.prototype.onExecute=function(){var c=this.getInputData(0);if(null!=c){var e= +Math.sqrt(c[0]*c[0]+c[1]*c[1]+c[2]*c[2]),m=this._data;m[0]=c[0]/e;m[1]=c[1]/e;m[2]=c[2]/e;this.setOutputData(0,m)}};D.registerNodeType("math3d/vec3-normalize",u);h.title="vec3_lerp";h.desc="returns the interpolated vector";h.prototype.onExecute=function(){var c=this.getInputData(0);if(null!=c){var e=this.getInputData(1);if(null!=e){var m=this.getInputOrProperty("f"),h=this._data;h[0]=c[0]*(1-m)+e[0]*m;h[1]=c[1]*(1-m)+e[1]*m;h[2]=c[2]*(1-m)+e[2]*m;this.setOutputData(0,h)}}};D.registerNodeType("math3d/vec3-lerp", +h);E.title="vec3_dot";E.desc="returns the dot product";E.prototype.onExecute=function(){var c=this.getInputData(0);if(null!=c){var e=this.getInputData(1);null!=e&&this.setOutputData(0,c[0]*e[0]+c[1]*e[1]+c[2]*e[2])}};D.registerNodeType("math3d/vec3-dot",E);if(y.glMatrix){y=function(){this.addInput("vec3","vec3");this.addOutput("remap","vec3");this.addOutput("clamped","vec3");this.properties={clamp:!0,range_min:[-1,-1,0],range_max:[1,1,0],target_min:[-1,-1,0],target_max:[1,1,0]};this._value=vec3.create(); +this._clamped=vec3.create()};var J=function(){this.addInputs([["A","quat"],["B","quat"],["factor","number"]]);this.addOutput("slerp","quat");this.addProperty("factor",.5);this._value=quat.create()},L=function(){this.addInputs([["A","quat"],["B","quat"]]);this.addOutput("A*B","quat");this._value=quat.create()},H=function(){this.addInputs([["vec3","vec3"],["quat","quat"]]);this.addOutput("result","vec3");this.properties={vec:[0,0,1]}},F=function(){this.addInput(["quat","quat"]);this.addOutput("euler", +"vec3");this._value=vec3.create()},e=function(){this.addInput("euler","vec3");this.addOutput("quat","quat");this.properties={euler:[0,0,0],use_yaw_pitch_roll:!1};this._degs=vec3.create();this._value=quat.create()},K=function(){this.addInputs([["degrees","number"],["axis","vec3"]]);this.addOutput("quat","quat");this.properties={angle:90,axis:vec3.fromValues(0,1,0)};this._value=quat.create()},B=function(){this.addOutput("quat","quat");this.properties={x:0,y:0,z:0,w:1,normalize:!1};this._value=quat.create()}; +B.title="Quaternion";B.desc="quaternion";B.prototype.onExecute=function(){this._value[0]=this.getInputOrProperty("x");this._value[1]=this.getInputOrProperty("y");this._value[2]=this.getInputOrProperty("z");this._value[3]=this.getInputOrProperty("w");this.properties.normalize&&quat.normalize(this._value,this._value);this.setOutputData(0,this._value)};B.prototype.onGetInputs=function(){return[["x","number"],["y","number"],["z","number"],["w","number"]]};D.registerNodeType("math3d/quaternion",B);K.title= +"Rotation";K.desc="quaternion rotation";K.prototype.onExecute=function(){var c=this.getInputData(0);null==c&&(c=this.properties.angle);var e=this.getInputData(1);null==e&&(e=this.properties.axis);c=quat.setAxisAngle(this._value,e,.0174532925*c);this.setOutputData(0,c)};D.registerNodeType("math3d/rotation",K);e.title="Euler->Quat";e.desc="Converts euler angles (in degrees) to quaternion";e.prototype.onExecute=function(){var c=this.getInputData(0);null==c&&(c=this.properties.euler);vec3.scale(this._degs, +c,DEG2RAD);this.properties.use_yaw_pitch_roll&&(this._degs=[this._degs[2],this._degs[0],this._degs[1]]);c=quat.fromEuler(this._value,this._degs);this.setOutputData(0,c)};D.registerNodeType("math3d/euler_to_quat",e);F.title="Euler->Quat";F.desc="Converts rotX,rotY,rotZ in degrees to quat";F.prototype.onExecute=function(){var c=this.getInputData(0);c&&(quat.toEuler(this._value,c),vec3.scale(this._value,this._value,DEG2RAD),this.setOutputData(0,this._value))};D.registerNodeType("math3d/quat_to_euler", +F);H.title="Rot. Vec3";H.desc="rotate a point";H.prototype.onExecute=function(){var c=this.getInputData(0);null==c&&(c=this.properties.vec);var e=this.getInputData(1);null==e?this.setOutputData(c):this.setOutputData(0,vec3.transformQuat(vec3.create(),c,e))};D.registerNodeType("math3d/rotate_vec3",H);L.title="Mult. Quat";L.desc="rotate quaternion";L.prototype.onExecute=function(){var c=this.getInputData(0);if(null!=c){var e=this.getInputData(1);null!=e&&(c=quat.multiply(this._value,c,e),this.setOutputData(0, +c))}};D.registerNodeType("math3d/mult-quat",L);J.title="Quat Slerp";J.desc="quaternion spherical interpolation";J.prototype.onExecute=function(){var c=this.getInputData(0);if(null!=c){var e=this.getInputData(1);if(null!=e){var m=this.properties.factor;null!=this.getInputData(2)&&(m=this.getInputData(2));c=quat.slerp(this._value,c,e,m);this.setOutputData(0,c)}}};D.registerNodeType("math3d/quat-slerp",J);y.title="Remap Range";y.desc="remap a 3D range";y.prototype.onExecute=function(){var c=this.getInputData(0); +c&&this._value.set(c);c=this.properties.range_min;for(var e=this.properties.range_max,m=this.properties.target_min,h=this.properties.target_max,k=0;3>k;++k){var a=e[k]-c[k];this._clamped[k]=clamp(this._value[k],c[k],e[k]);0==a?this._value[k]=.5*(m[k]+h[k]):(a=(this._value[k]-c[k])/a,this.properties.clamp&&(a=clamp(a,0,1)),this._value[k]=m[k]+a*(h[k]-m[k]))}this.setOutputData(0,this._value);this.setOutputData(1,this._clamped)};D.registerNodeType("math3d/remap_range",y)}else D.debug&&console.warn("No glmatrix found, some Math3D nodes may not work")})(this); +(function(y){function c(){this.addInput("","string");this.addOutput("table","table");this.addOutput("rows","number");this.addProperty("value","");this.addProperty("separator",",");this._table=null}y=y.LiteGraph;y.wrapFunctionAsNode("string/toString",function(c){if(c&&c.constructor===Object)try{return JSON.stringify(c)}catch(n){}return String(c)},[""],"string");y.wrapFunctionAsNode("string/compare",function(c,n){return c==n},["string","string"],"boolean");y.wrapFunctionAsNode("string/concatenate", +function(c,n){return void 0===c?n:void 0===n?c:c+n},["string","string"],"string");y.wrapFunctionAsNode("string/contains",function(c,n){return void 0===c||void 0===n?!1:-1!=c.indexOf(n)},["string","string"],"boolean");y.wrapFunctionAsNode("string/toUpperCase",function(c){return null!=c&&c.constructor===String?c.toUpperCase():c},["string"],"string");y.wrapFunctionAsNode("string/split",function(c,n){null==n&&(n=this.properties.separator);if(null==c)return[];if(c.constructor===String)return c.split(n|| +" ");if(c.constructor===Array){for(var k=[],u=0;ue;++e){var h=this.getInputData(e);if(null!=h){var k=this.values[e];k.push(h);k.length>c[0]&&k.shift()}}}};c.prototype.onDrawBackground=function(e){if(!this.flags.collapsed){var h= +this.size,k=.5*h[1]/this.properties.scale,n=c.colors,l=.5*h[1];e.fillStyle="#000";e.fillRect(0,0,h[0],h[1]);e.strokeStyle="#555";e.beginPath();e.moveTo(0,l);e.lineTo(h[0],l);e.stroke();if(this.inputs)for(var m=0;4>m;++m){var w=this.values[m];if(this.inputs[m]&&this.inputs[m].link){e.strokeStyle=n[m];e.beginPath();var r=w[0]*k*-1+l;e.moveTo(0,clamp(r,0,h[1]));for(var a=1;ah&&(h=0);if(0!=c.length){var k=[0,0,0];if(0==h)k=c[0];else if(1==h)k=c[c.length-1];else{var n= +(c.length-1)*h;h=c[Math.floor(n)];c=c[Math.floor(n)+1];n-=Math.floor(n);k[0]=h[0]*(1-n)+c[0]*n;k[1]=h[1]*(1-n)+c[1]*n;k[2]=h[2]*(1-n)+c[2]*n}for(h=0;h=c&&(this._video.currentTime=c*this._video.duration,this._video.pause()); +this._video.dirty=!0;this.setOutputData(0,this._video);this.setOutputData(1,this._video.currentTime);this.setOutputData(2,this._video.duration);this.setDirtyCanvas(!0)}};L.prototype.onStart=function(){this.play()};L.prototype.onStop=function(){this.stop()};L.prototype.loadVideo=function(c){this._video_url=c;var e=c.substr(0,10).indexOf(":"),h="";-1!=e&&(h=c.substr(0,e));e="";h&&(e=c.substr(0,c.indexOf("/",h.length+3)),e=e.substr(h.length+3));this.properties.use_proxy&&h&&F.proxy&&e!=location.host&& +(c=F.proxy+c.substr(c.indexOf(":")+3));this._video=document.createElement("video");this._video.src=c;this._video.type="type=video/mp4";this._video.muted=!0;this._video.autoplay=!0;var k=this;this._video.addEventListener("loadedmetadata",function(c){console.log("Duration: "+this.duration+" seconds");console.log("Size: "+this.videoWidth+","+this.videoHeight);k.setDirtyCanvas(!0);this.width=this.videoWidth;this.height=this.videoHeight});this._video.addEventListener("progress",function(c){console.log("video loading...")}); +this._video.addEventListener("error",function(c){console.error("Error loading video: "+this.src);if(this.error)switch(this.error.code){case this.error.MEDIA_ERR_ABORTED:console.error("You stopped the video.");break;case this.error.MEDIA_ERR_NETWORK:console.error("Network error - please try again later.");break;case this.error.MEDIA_ERR_DECODE:console.error("Video is broken..");break;case this.error.MEDIA_ERR_SRC_NOT_SUPPORTED:console.error("Sorry, your browser can't play this video.")}});this._video.addEventListener("ended", +function(c){console.log("Video Ended.");this.play()})};L.prototype.onPropertyChanged=function(c,h){this.properties[c]=h;"url"==c&&""!=h&&this.loadVideo(h);return!0};L.prototype.play=function(){this._video&&this._video.videoWidth&&this._video.play()};L.prototype.playPause=function(){this._video&&(this._video.paused?this.play():this.pause())};L.prototype.stop=function(){this._video&&(this._video.pause(),this._video.currentTime=0)};L.prototype.pause=function(){this._video&&(console.log("Video paused"), +this._video.pause())};L.prototype.onWidget=function(c,h){};F.registerNodeType("graphics/video",L);H.title="Webcam";H.desc="Webcam image";H.is_webcam_open=!1;H.prototype.openStream=function(){if(navigator.mediaDevices.getUserMedia){this._waiting_confirmation=!0;navigator.mediaDevices.getUserMedia({audio:!1,video:this.properties.filterFacingMode?{facingMode:this.properties.facingMode}:!0}).then(this.streamReady.bind(this)).catch(function(e){console.log("Webcam rejected",e);c._webcam_stream=!1;H.is_webcam_open= +!1;c.boxcolor="red";c.trigger("stream_error")});var c=this}else console.log("getUserMedia() is not supported in your browser, use chrome and enable WebRTC from about://flags")};H.prototype.closeStream=function(){if(this._webcam_stream){var c=this._webcam_stream.getTracks();if(c.length)for(var h=0;h=this.size[1]||!this.properties.show||!this._video||(c.save(),c.drawImage(this._video,0,0,this.size[0],this.size[1]),c.restore())};H.prototype.onGetOutputs=function(){return[["width","number"],["height","number"],["stream_ready",F.EVENT],["stream_closed",F.EVENT],["stream_error",F.EVENT]]};F.registerNodeType("graphics/webcam",H)})(this); +(function(y){function c(){this.addOutput("tex","Texture");this.addOutput("name","string");this.properties={name:"",filter:!0};this.size=[c.image_preview_size,c.image_preview_size]}function k(){this.addInput("Texture","Texture");this.properties={flipY:!1};this.size=[c.image_preview_size,c.image_preview_size]}function n(){this.addInput("Texture","Texture");this.addOutput("tex","Texture");this.addOutput("name","string");this.properties={name:"",generate_mipmaps:!1}}function r(){this.addInput("Texture", +"Texture");this.addInput("TextureB","Texture");this.addInput("value","number");this.addOutput("Texture","Texture");this.help="

pixelcode must be vec3, uvcode must be vec2, is optional

\t\t

uv: tex. coords

color: texture colorB: textureB

time: scene time value: input value

For multiline you must type: result = ...

";this.properties={value:1,pixelcode:"color + colorB * value",uvcode:"",precision:c.DEFAULT}; +this.has_error=!1}function u(){this.addOutput("out","Texture");this.properties={code:"",u_value:1,u_color:[1,1,1,1],width:512,height:512,precision:c.DEFAULT};this.properties.code=u.pixel_shader;this._uniforms={u_value:1,u_color:vec4.create(),in_texture:0,texSize:vec4.create(),time:0}}function h(){this.addInput("in","Texture");this.addInput("scale","vec2");this.addInput("offset","vec2");this.addOutput("out","Texture");this.properties={offset:vec2.fromValues(0,0),scale:vec2.fromValues(1,1),precision:c.DEFAULT}} +function E(){this.addInput("in","Texture");this.addInput("warp","Texture");this.addInput("factor","number");this.addOutput("out","Texture");this.properties={factor:.01,scale:[1,1],offset:[0,0],precision:c.DEFAULT};this._uniforms={u_texture:0,u_textureB:1,u_factor:1,u_scale:vec2.create(),u_offset:vec2.create()}}function D(){this.addInput("Texture","Texture");this.properties={additive:!1,antialiasing:!1,filter:!0,disable_alpha:!1,gamma:1,viewport:[0,0,1,1]};this.size[0]=130}function J(){this.addInput("Texture", +"Texture");this.addOutput("","Texture");this.properties={size:0,generate_mipmaps:!1,precision:c.DEFAULT}}function L(){this.addInput("Texture","Texture");this.addOutput("","Texture");this.properties={iterations:1,generate_mipmaps:!1,precision:c.DEFAULT}}function H(){this.addInput("Texture","Texture");this.addOutput("","Texture");this.properties={size:[512,512],generate_mipmaps:!1,precision:c.DEFAULT}}function F(){this.addInput("Texture","Texture");this.addOutput("tex","Texture");this.addOutput("avg", +"vec4");this.addOutput("lum","number");this.properties={use_previous_frame:!0,high_quality:!1};this._uniforms={u_texture:0,u_mipmap_offset:0};this._luminance=new Float32Array(4)}function e(){this.addInput("in","Texture");this.addInput("factor","Number");this.addOutput("out","Texture");this.properties={factor:.5};this._uniforms={u_texture:0,u_textureB:1,u_factor:this.properties.factor}}function K(){this.addInput("in","Texture");this.addOutput("avg","Texture");this.addOutput("array","Texture");this.properties= +{samples:64,frames_interval:1};this._uniforms={u_texture:0,u_textureB:1,u_samples:this.properties.samples,u_isamples:1/this.properties.samples};this.frame=0}function B(){this.addInput("Image","image");this.addOutput("","Texture");this.properties={}}function M(){this.addInput("Texture","Texture");this.addInput("LUT","Texture");this.addInput("Intensity","number");this.addOutput("","Texture");this.properties={enabled:!0,intensity:1,precision:c.DEFAULT,texture:null};M._shader||(M._shader=new GL.Shader(Shader.SCREEN_VERTEX_SHADER, +M.pixel_shader))}function l(){this.addInput("Texture","Texture");this.addInput("Atlas","Texture");this.addOutput("","Texture");this.properties={enabled:!0,num_row_symbols:4,symbol_size:16,brightness:1,colorize:!1,filter:!1,invert:!1,precision:c.DEFAULT,generate_mipmaps:!1,texture:null};l._shader||(l._shader=new GL.Shader(Shader.SCREEN_VERTEX_SHADER,l.pixel_shader));this._uniforms={u_texture:0,u_textureB:1,u_row_simbols:4,u_simbol_size:16,u_res:vec2.create()}}function m(){this.addInput("Texture","Texture"); +this.addOutput("R","Texture");this.addOutput("G","Texture");this.addOutput("B","Texture");this.addOutput("A","Texture");m._shader||(m._shader=new GL.Shader(Shader.SCREEN_VERTEX_SHADER,m.pixel_shader))}function w(){this.addInput("R","Texture");this.addInput("G","Texture");this.addInput("B","Texture");this.addInput("A","Texture");this.addOutput("Texture","Texture");this.properties={precision:c.DEFAULT,R:1,G:1,B:1,A:1};this._color=vec4.create();this._uniforms={u_textureR:0,u_textureG:1,u_textureB:2, +u_textureA:3,u_color:this._color}}function N(){this.addOutput("Texture","Texture");this._tex_color=vec4.create();this.properties={color:vec4.create(),precision:c.DEFAULT}}function a(){this.addInput("A","color");this.addInput("B","color");this.addOutput("Texture","Texture");this.properties={angle:0,scale:1,A:[0,0,0],B:[1,1,1],texture_size:32};a._shader||(a._shader=new GL.Shader(Shader.SCREEN_VERTEX_SHADER,a.pixel_shader));this._uniforms={u_angle:0,u_colorA:vec3.create(),u_colorB:vec3.create()}}function b(){this.addInput("A", +"Texture");this.addInput("B","Texture");this.addInput("Mixer","Texture");this.addOutput("Texture","Texture");this.properties={factor:.5,size_from_biggest:!0,invert:!1,precision:c.DEFAULT};this._uniforms={u_textureA:0,u_textureB:1,u_textureMix:2,u_mix:vec4.create()}}function d(){this.addInput("Tex.","Texture");this.addOutput("Edges","Texture");this.properties={invert:!0,threshold:!1,factor:1,precision:c.DEFAULT};d._shader||(d._shader=new GL.Shader(Shader.SCREEN_VERTEX_SHADER,d.pixel_shader))}function f(){this.addInput("Texture", +"Texture");this.addInput("Distance","number");this.addInput("Range","number");this.addOutput("Texture","Texture");this.properties={distance:100,range:50,only_depth:!1,high_precision:!1};this._uniforms={u_texture:0,u_distance:100,u_range:50,u_camera_planes:null}}function g(){this.addInput("Texture","Texture");this.addOutput("Texture","Texture");this.properties={precision:c.DEFAULT,invert:!1};this._uniforms={u_texture:0,u_camera_planes:null,u_ires:vec2.create()}}function q(){this.addInput("Texture", +"Texture");this.addInput("Iterations","number");this.addInput("Intensity","number");this.addOutput("Blurred","Texture");this.properties={intensity:1,iterations:1,preserve_aspect:!1,scale:[1,1],precision:c.DEFAULT}}function z(){this.intensity=.5;this.persistence=.6;this.iterations=8;this.threshold=.8;this.scale=1;this.dirt_texture=null;this.dirt_factor=.5;this._textures=[];this._uniforms={u_intensity:1,u_texture:0,u_glow_texture:1,u_threshold:0,u_texel_size:vec2.create()}}function P(){this.addInput("in", +"Texture");this.addInput("dirt","Texture");this.addOutput("out","Texture");this.addOutput("glow","Texture");this.properties={enabled:!0,intensity:1,persistence:.99,iterations:16,threshold:0,scale:1,dirt_factor:.5,precision:c.DEFAULT};this.fx=new z}function I(){this.addInput("Texture","Texture");this.addOutput("Filtered","Texture");this.properties={intensity:1,radius:5}}function t(){this.addInput("Texture","Texture");this.addOutput("Filtered","Texture");this.properties={sigma:1.4,k:1.6,p:21.7,epsilon:79, +phi:.017}}function v(){this.addOutput("Webcam","Texture");this.properties={texture_name:"",facingMode:"user"};this.boxcolor="black";this.version=0}function C(){this.addInput("in","Texture");this.addInput("f","number");this.addOutput("out","Texture");this.properties={enabled:!0,factor:1,precision:c.LOW};this._uniforms={u_texture:0,u_factor:1}}function x(){this.addInput("in","");this.properties={precision:c.LOW,width:0,height:0,channels:1};this.addOutput("out","Texture")}function G(){this.addInput("in", +"Texture");this.addOutput("out","Texture");this.properties={precision:c.LOW,split_channels:!1};this._values=new Uint8Array(1024);this._values.fill(255);this._curve_texture=null;this._uniforms={u_texture:0,u_curve:1,u_range:1};this._must_update=!0;this._points={RGB:[[0,0],[1,1]],R:[[0,0],[1,1]],G:[[0,0],[1,1]],B:[[0,0],[1,1]]};this.curve_editor=null;this.addWidget("toggle","Split Channels",!1,"split_channels");this.addWidget("combo","Channel","RGB",{values:["RGB","R","G","B"]});this.curve_offset=68; +this.size=[240,160]}function A(){this.addInput("in","Texture");this.addInput("exp","number");this.addOutput("out","Texture");this.properties={exposition:1,precision:c.LOW};this._uniforms={u_texture:0,u_exposition:1}}function R(){this.addInput("in","Texture");this.addInput("avg","number,Texture");this.addOutput("out","Texture");this.properties={enabled:!0,scale:1,gamma:1,average_lum:1,lum_white:1,precision:c.LOW};this._uniforms={u_texture:0,u_lumwhite2:1,u_igamma:1,u_scale:1,u_average_lum:1}}function T(){this.addOutput("out", +"Texture");this.properties={width:512,height:512,seed:0,persistence:.1,octaves:8,scale:1,offset:[0,0],amplitude:1,precision:c.DEFAULT};this._key=0;this._texture=null;this._uniforms={u_persistence:.1,u_seed:0,u_offset:vec2.create(),u_scale:1,u_viewport:vec2.create()}}function S(){this.addInput("v");this.addOutput("out","Texture");this.properties={code:S.default_code,width:512,height:512,clear:!0,precision:c.DEFAULT,use_html_canvas:!1};this._temp_texture=this._func=null;this.compileCode()}function U(){this.addInput("in", +"Texture");this.addOutput("out","Texture");this.properties={key_color:vec3.fromValues(0,1,0),threshold:.8,slope:.2,precision:c.DEFAULT}}function V(){this.addInput("in","texture");this.addInput("yaw","number");this.addOutput("out","texture");this.properties={yaw:0}}var O=y.LiteGraph,aa=y.LGraphCanvas;y.LGraphTexture=null;"undefined"!=typeof GL&&(aa.link_type_colors.Texture="#987",y.LGraphTexture=c,c.title="Texture",c.desc="Texture",c.widgets_info={name:{widget:"texture"},filter:{widget:"checkbox"}}, +c.loadTextureCallback=null,c.image_preview_size=256,c.UNDEFINED=0,c.PASS_THROUGH=1,c.COPY=2,c.LOW=3,c.HIGH=4,c.REUSE=5,c.DEFAULT=2,c.MODE_VALUES={undefined:c.UNDEFINED,"pass through":c.PASS_THROUGH,copy:c.COPY,low:c.LOW,high:c.HIGH,reuse:c.REUSE,default:c.DEFAULT},c.getTexturesContainer=function(){return gl.textures},c.loadTexture=function(a,b){b=b||{};var d=a;"http://"==d.substr(0,7)&&O.proxy&&(d=O.proxy+d.substr(7));return c.getTexturesContainer()[a]=GL.Texture.fromURL(d,b)},c.getTexture=function(a){var b= +this.getTexturesContainer();if(!b)throw"Cannot load texture, container of textures not found";b=b[a];return!b&&a&&":"!=a[0]?this.loadTexture(a):b},c.getTargetTexture=function(a,b,d){if(!a)throw"LGraphTexture.getTargetTexture expects a reference texture";switch(d){case c.LOW:d=gl.UNSIGNED_BYTE;break;case c.HIGH:d=gl.HIGH_PRECISION_FORMAT;break;case c.REUSE:return a;default:d=a?a.type:gl.UNSIGNED_BYTE}b&&b.width==a.width&&b.height==a.height&&b.type==d&&b.format==a.format||(b=new GL.Texture(a.width, +a.height,{type:d,format:a.format,filter:gl.LINEAR}));return b},c.getTextureType=function(a,b){b=b?b.type:gl.UNSIGNED_BYTE;switch(a){case c.HIGH:b=gl.HIGH_PRECISION_FORMAT;break;case c.LOW:b=gl.UNSIGNED_BYTE}return b},c.getWhiteTexture=function(){return this._white_texture?this._white_texture:this._white_texture=GL.Texture.fromMemory(1,1,[255,255,255,255],{format:gl.RGBA,wrap:gl.REPEAT,filter:gl.NEAREST})},c.getNoiseTexture=function(){if(this._noise_texture)return this._noise_texture;for(var a=new Uint8Array(1048576), +b=0;1048576>b;++b)a[b]=255*Math.random();return this._noise_texture=a=GL.Texture.fromMemory(512,512,a,{format:gl.RGBA,wrap:gl.REPEAT,filter:gl.NEAREST})},c.prototype.onDropFile=function(a,b,c){a?("string"==typeof a?a=GL.Texture.fromURL(a):-1!=b.toLowerCase().indexOf(".dds")?a=GL.Texture.fromDDSInMemory(a):(a=new Blob([c]),a=URL.createObjectURL(a),a=GL.Texture.fromURL(a)),this._drop_texture=a,this.properties.name=b):(this._drop_texture=null,this.properties.name="")},c.prototype.getExtraMenuOptions= +function(a){var b=this;if(this._drop_texture)return[{content:"Clear",callback:function(){b._drop_texture=null;b.properties.name=""}}]},c.prototype.onExecute=function(){var a=null;this.isOutputConnected(1)&&(a=this.getInputData(0));!a&&this._drop_texture&&(a=this._drop_texture);!a&&this.properties.name&&(a=c.getTexture(this.properties.name));if(a){this._last_tex=a;!1===this.properties.filter?a.setParameter(gl.TEXTURE_MAG_FILTER,gl.NEAREST):a.setParameter(gl.TEXTURE_MAG_FILTER,gl.LINEAR);this.setOutputData(0, +a);this.setOutputData(1,a.fullpath||a.filename);for(var b=2;b=this.size[1]))if(this._drop_texture&& +a.webgl)a.drawImage(this._drop_texture,0,0,this.size[0],this.size[1]);else{if(this._last_preview_tex!=this._last_tex)if(a.webgl)this._canvas=this._last_tex;else{var b=c.generateLowResTexturePreview(this._last_tex);if(!b)return;this._last_preview_tex=this._last_tex;this._canvas=cloneCanvas(b)}this._canvas&&(a.save(),a.webgl||(a.translate(0,this.size[1]),a.scale(1,-1)),a.drawImage(this._canvas,0,0,this.size[0],this.size[1]),a.restore())}},c.generateLowResTexturePreview=function(a){if(!a)return null; +var b=c.image_preview_size,d=a;if(a.format==gl.DEPTH_COMPONENT)return null;if(a.width>b||a.height>b)d=this._preview_temp_tex,this._preview_temp_tex||(this._preview_temp_tex=d=new GL.Texture(b,b,{minFilter:gl.NEAREST})),a.copyTo(d);a=this._preview_canvas;a||(this._preview_canvas=a=createCanvas(b,b));d&&d.toCanvas(a);return a},c.prototype.getResources=function(a){this.properties.name&&(a[this.properties.name]=GL.Texture);return a},c.prototype.onGetInputs=function(){return[["in","Texture"]]},c.prototype.onGetOutputs= +function(){return[["width","number"],["height","number"],["aspect","number"]]},c.replaceCode=function(a,b){return a.replace(/\{\{[a-zA-Z0-9_]*\}\}/g,function(a){a=a.replace(/[\{\}]/g,"");return b[a]||""})},O.registerNodeType("texture/texture",c),k.title="Preview",k.desc="Show a texture in the graph canvas",k.allow_preview=!1,k.prototype.onDrawBackground=function(a){if(!this.flags.collapsed&&(a.webgl||k.allow_preview)){var b=this.getInputData(0);b&&(b=!b.handle&&a.webgl?b:c.generateLowResTexturePreview(b), +a.save(),this.properties.flipY&&(a.translate(0,this.size[1]),a.scale(1,-1)),a.drawImage(b,0,0,this.size[0],this.size[1]),a.restore())}},O.registerNodeType("texture/preview",k),n.title="Save",n.desc="Save a texture in the repository",n.prototype.getPreviewTexture=function(){return this._texture},n.prototype.onExecute=function(){var a=this.getInputData(0);a&&(this.properties.generate_mipmaps&&(a.bind(0),a.setParameter(gl.TEXTURE_MIN_FILTER,gl.LINEAR_MIPMAP_LINEAR),gl.generateMipmap(a.texture_type), +a.unbind(0)),this.properties.name&&(c.storeTexture?c.storeTexture(this.properties.name,a):c.getTexturesContainer()[this.properties.name]=a),this._texture=a,this.setOutputData(0,a),this.setOutputData(1,this.properties.name))},O.registerNodeType("texture/save",n),r.widgets_info={uvcode:{widget:"code"},pixelcode:{widget:"code"},precision:{widget:"combo",values:c.MODE_VALUES}},r.title="Operation",r.desc="Texture shader operation",r.presets={},r.prototype.getExtraMenuOptions=function(a){var b=this;return[{content:b.properties.show? +"Hide Texture":"Show Texture",callback:function(){b.properties.show=!b.properties.show}}]},r.prototype.onPropertyChanged=function(){this.has_error=!1},r.prototype.onDrawBackground=function(a){this.flags.collapsed||20>=this.size[1]||!this.properties.show||!this._tex||this._tex.gl!=a||(a.save(),a.drawImage(this._tex,0,0,this.size[0],this.size[1]),a.restore())},r.prototype.onExecute=function(){var a=this.getInputData(0);if(this.isOutputConnected(0))if(this.properties.precision===c.PASS_THROUGH)this.setOutputData(0, +a);else{var b=this.getInputData(1);if(this.properties.uvcode||this.properties.pixelcode){var d=512,f=512;a?(d=a.width,f=a.height):b&&(d=b.width,f=b.height);b||(b=GL.Texture.getWhiteTexture());var g=c.getTextureType(this.properties.precision,a);this._tex=a||this._tex?c.getTargetTexture(a||this._tex,this._tex,this.properties.precision):new GL.Texture(d,f,{type:g,format:gl.RGBA,filter:gl.LINEAR});g="";this.properties.uvcode&&(g="uv = "+this.properties.uvcode,-1!=this.properties.uvcode.indexOf(";")&& +(g=this.properties.uvcode));var e="";this.properties.pixelcode&&(e="result = "+this.properties.pixelcode,-1!=this.properties.pixelcode.indexOf(";")&&(e=this.properties.pixelcode));var l=this._shader;if(!(this.has_error||l&&this._shader_code==g+"|"+e)){var h=c.replaceCode(r.pixel_shader,{UV_CODE:g,PIXEL_CODE:e});try{l=new GL.Shader(Shader.SCREEN_VERTEX_SHADER,h),this.boxcolor="#00FF00"}catch(Z){GL.Shader.dumpErrorToConsole(Z,Shader.SCREEN_VERTEX_SHADER,h);this.boxcolor="#FF0000";this.has_error=!0; +return}this._shader=l;this._shader_code=g+"|"+e}if(this._shader){var m=this.getInputData(2);null!=m?this.properties.value=m:m=parseFloat(this.properties.value);var k=this.graph.getTime();this._tex.drawTo(function(){gl.disable(gl.DEPTH_TEST);gl.disable(gl.CULL_FACE);gl.disable(gl.BLEND);a&&a.bind(0);b&&b.bind(1);var c=Mesh.getScreenQuad();l.uniforms({u_texture:0,u_textureB:1,value:m,texSize:[d,f,1/d,1/f],time:k}).draw(c)});this.setOutputData(0,this._tex)}}}},r.pixel_shader="precision highp float;\n\t\t\n\t\tuniform sampler2D u_texture;\n\t\tuniform sampler2D u_textureB;\n\t\tvarying vec2 v_coord;\n\t\tuniform vec4 texSize;\n\t\tuniform float time;\n\t\tuniform float value;\n\t\t\n\t\tvoid main() {\n\t\t\tvec2 uv = v_coord;\n\t\t\t{{UV_CODE}};\n\t\t\tvec4 color4 = texture2D(u_texture, uv);\n\t\t\tvec3 color = color4.rgb;\n\t\t\tvec4 color4B = texture2D(u_textureB, uv);\n\t\t\tvec3 colorB = color4B.rgb;\n\t\t\tvec3 result = color;\n\t\t\tfloat alpha = 1.0;\n\t\t\t{{PIXEL_CODE}};\n\t\t\tgl_FragColor = vec4(result, alpha);\n\t\t}\n\t\t", +r.registerPreset=function(a,b){r.presets[a]=b},r.registerPreset("",""),r.registerPreset("bypass","color"),r.registerPreset("add","color + colorB * value"),r.registerPreset("substract","(color - colorB) * value"),r.registerPreset("mate","mix( color, colorB, color4B.a * value)"),r.registerPreset("invert","vec3(1.0) - color"),r.registerPreset("multiply","color * colorB * value"),r.registerPreset("divide","(color / colorB) / value"),r.registerPreset("difference","abs(color - colorB) * value"),r.registerPreset("max", +"max(color, colorB) * value"),r.registerPreset("min","min(color, colorB) * value"),r.registerPreset("displace","texture2D(u_texture, uv + (colorB.xy - vec2(0.5)) * value).xyz"),r.registerPreset("grayscale","vec3(color.x + color.y + color.z) * value / 3.0"),r.registerPreset("saturation","mix( vec3(color.x + color.y + color.z) / 3.0, color, value )"),r.registerPreset("normalmap","\n\t\tfloat z0 = texture2D(u_texture, uv + vec2(-texSize.z, -texSize.w) ).x;\n\t\tfloat z1 = texture2D(u_texture, uv + vec2(0.0, -texSize.w) ).x;\n\t\tfloat z2 = texture2D(u_texture, uv + vec2(texSize.z, -texSize.w) ).x;\n\t\tfloat z3 = texture2D(u_texture, uv + vec2(-texSize.z, 0.0) ).x;\n\t\tfloat z4 = color.x;\n\t\tfloat z5 = texture2D(u_texture, uv + vec2(texSize.z, 0.0) ).x;\n\t\tfloat z6 = texture2D(u_texture, uv + vec2(-texSize.z, texSize.w) ).x;\n\t\tfloat z7 = texture2D(u_texture, uv + vec2(0.0, texSize.w) ).x;\n\t\tfloat z8 = texture2D(u_texture, uv + vec2(texSize.z, texSize.w) ).x;\n\t\tvec3 normal = vec3( z2 + 2.0*z4 + z7 - z0 - 2.0*z3 - z5, z5 + 2.0*z6 + z7 -z0 - 2.0*z1 - z2, 1.0 );\n\t\tnormal.xy *= value;\n\t\tresult.xyz = normalize(normal) * 0.5 + vec3(0.5);\n\t"), +r.registerPreset("threshold","vec3(color.x > colorB.x * value ? 1.0 : 0.0,color.y > colorB.y * value ? 1.0 : 0.0,color.z > colorB.z * value ? 1.0 : 0.0)"),r.prototype.onInspect=function(a){var b=this;a.addCombo("Presets","",{values:Object.keys(r.presets),callback:function(d){var c=r.presets[d];c&&(b.setProperty("pixelcode",c),b.title=d,a.refresh())}})},O.registerNodeType("texture/operation",r),u.title="Shader",u.desc="Texture shader",u.widgets_info={code:{type:"code",lang:"glsl"},precision:{widget:"combo", +values:c.MODE_VALUES}},u.prototype.onPropertyChanged=function(a,b){if("code"==a&&(a=this.getShader())){b=a.uniformInfo;if(this.inputs)for(var d={},c=0;c=this.size[1])){var b=this.getInputData(0);b&&a.drawImage(a==gl?b:gl.canvas,10,30,this.size[0]-20,this.size[1]-40)}},D.prototype.onExecute=function(){var a=this.getInputData(0);if(a){this.properties.disable_alpha?gl.disable(gl.BLEND):(gl.enable(gl.BLEND),this.properties.additive?gl.blendFunc(gl.SRC_ALPHA, +gl.ONE):gl.blendFunc(gl.SRC_ALPHA,gl.ONE_MINUS_SRC_ALPHA));gl.disable(gl.DEPTH_TEST);var b=this.properties.gamma||1;this.isInputConnected(1)&&(b=this.getInputData(1));a.setParameter(gl.TEXTURE_MAG_FILTER,this.properties.filter?gl.LINEAR:gl.NEAREST);var d=D._prev_viewport;d.set(gl.viewport_data);var c=this.properties.viewport;gl.viewport(d[0]+d[2]*c[0],d[1]+d[3]*c[1],d[2]*c[2],d[3]*c[3]);gl.getViewport();this.properties.antialiasing?(D._shader||(D._shader=new GL.Shader(GL.Shader.SCREEN_VERTEX_SHADER, +D.aa_pixel_shader)),c=Mesh.getScreenQuad(),a.bind(0),D._shader.uniforms({u_texture:0,uViewportSize:[a.width,a.height],u_igamma:1/b,inverseVP:[1/a.width,1/a.height]}).draw(c)):1!=b?(D._gamma_shader||(D._gamma_shader=new GL.Shader(Shader.SCREEN_VERTEX_SHADER,D.gamma_pixel_shader)),a.toViewport(D._gamma_shader,{u_texture:0,u_igamma:1/b})):a.toViewport();gl.viewport(d[0],d[1],d[2],d[3])}},D.prototype.onGetInputs=function(){return[["gamma","number"]]},D.aa_pixel_shader="precision highp float;\n\t\tprecision highp float;\n\t\tvarying vec2 v_coord;\n\t\tuniform sampler2D u_texture;\n\t\tuniform vec2 uViewportSize;\n\t\tuniform vec2 inverseVP;\n\t\tuniform float u_igamma;\n\t\t#define FXAA_REDUCE_MIN (1.0/ 128.0)\n\t\t#define FXAA_REDUCE_MUL (1.0 / 8.0)\n\t\t#define FXAA_SPAN_MAX 8.0\n\t\t\n\t\t/* from mitsuhiko/webgl-meincraft based on the code on geeks3d.com */\n\t\tvec4 applyFXAA(sampler2D tex, vec2 fragCoord)\n\t\t{\n\t\t\tvec4 color = vec4(0.0);\n\t\t\t/*vec2 inverseVP = vec2(1.0 / uViewportSize.x, 1.0 / uViewportSize.y);*/\n\t\t\tvec3 rgbNW = texture2D(tex, (fragCoord + vec2(-1.0, -1.0)) * inverseVP).xyz;\n\t\t\tvec3 rgbNE = texture2D(tex, (fragCoord + vec2(1.0, -1.0)) * inverseVP).xyz;\n\t\t\tvec3 rgbSW = texture2D(tex, (fragCoord + vec2(-1.0, 1.0)) * inverseVP).xyz;\n\t\t\tvec3 rgbSE = texture2D(tex, (fragCoord + vec2(1.0, 1.0)) * inverseVP).xyz;\n\t\t\tvec3 rgbM = texture2D(tex, fragCoord * inverseVP).xyz;\n\t\t\tvec3 luma = vec3(0.299, 0.587, 0.114);\n\t\t\tfloat lumaNW = dot(rgbNW, luma);\n\t\t\tfloat lumaNE = dot(rgbNE, luma);\n\t\t\tfloat lumaSW = dot(rgbSW, luma);\n\t\t\tfloat lumaSE = dot(rgbSE, luma);\n\t\t\tfloat lumaM = dot(rgbM, luma);\n\t\t\tfloat lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n\t\t\tfloat lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n\t\t\t\n\t\t\tvec2 dir;\n\t\t\tdir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));\n\t\t\tdir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));\n\t\t\t\n\t\t\tfloat dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL), FXAA_REDUCE_MIN);\n\t\t\t\n\t\t\tfloat rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n\t\t\tdir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX), max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX), dir * rcpDirMin)) * inverseVP;\n\t\t\t\n\t\t\tvec3 rgbA = 0.5 * (texture2D(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz + \n\t\t\t\ttexture2D(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);\n\t\t\tvec3 rgbB = rgbA * 0.5 + 0.25 * (texture2D(tex, fragCoord * inverseVP + dir * -0.5).xyz + \n\t\t\t\ttexture2D(tex, fragCoord * inverseVP + dir * 0.5).xyz);\n\t\t\t\n\t\t\t//return vec4(rgbA,1.0);\n\t\t\tfloat lumaB = dot(rgbB, luma);\n\t\t\tif ((lumaB < lumaMin) || (lumaB > lumaMax))\n\t\t\t\tcolor = vec4(rgbA, 1.0);\n\t\t\telse\n\t\t\t\tcolor = vec4(rgbB, 1.0);\n\t\t\tif(u_igamma != 1.0)\n\t\t\t\tcolor.xyz = pow( color.xyz, vec3(u_igamma) );\n\t\t\treturn color;\n\t\t}\n\t\t\n\t\tvoid main() {\n\t\t gl_FragColor = applyFXAA( u_texture, v_coord * uViewportSize) ;\n\t\t}\n\t\t", +D.gamma_pixel_shader="precision highp float;\n\t\tprecision highp float;\n\t\tvarying vec2 v_coord;\n\t\tuniform sampler2D u_texture;\n\t\tuniform float u_igamma;\n\t\tvoid main() {\n\t\t\tvec4 color = texture2D( u_texture, v_coord);\n\t\t\tcolor.xyz = pow(color.xyz, vec3(u_igamma) );\n\t\t gl_FragColor = color;\n\t\t}\n\t\t",O.registerNodeType("texture/toviewport",D),J.title="Copy",J.desc="Copy Texture",J.widgets_info={size:{widget:"combo",values:[0,32,64,128,256,512,1024,2048]},precision:{widget:"combo", +values:c.MODE_VALUES}},J.prototype.onExecute=function(){var a=this.getInputData(0);if((a||this._temp_texture)&&this.isOutputConnected(0)){if(a){var b=a.width,d=a.height;0!=this.properties.size&&(d=b=this.properties.size);var f=this._temp_texture,g=a.type;this.properties.precision===c.LOW?g=gl.UNSIGNED_BYTE:this.properties.precision===c.HIGH&&(g=gl.HIGH_PRECISION_FORMAT);f&&f.width==b&&f.height==d&&f.type==g||(f=gl.LINEAR,this.properties.generate_mipmaps&&isPowerOfTwo(b)&&isPowerOfTwo(d)&&(f=gl.LINEAR_MIPMAP_LINEAR), +this._temp_texture=new GL.Texture(b,d,{type:g,format:gl.RGBA,minFilter:f,magFilter:gl.LINEAR}));a.copyTo(this._temp_texture);this.properties.generate_mipmaps&&(this._temp_texture.bind(0),gl.generateMipmap(this._temp_texture.texture_type),this._temp_texture.unbind(0))}this.setOutputData(0,this._temp_texture)}},O.registerNodeType("texture/copy",J),L.title="Downsample",L.desc="Downsample Texture",L.widgets_info={iterations:{type:"number",step:1,precision:0,min:0},precision:{widget:"combo",values:c.MODE_VALUES}}, +L.prototype.onExecute=function(){var a=this.getInputData(0);if((a||this._temp_texture)&&this.isOutputConnected(0)&&a&&a.texture_type===GL.TEXTURE_2D)if(1>this.properties.iterations)this.setOutputData(0,a);else{var b=L._shader;b||(L._shader=b=new GL.Shader(GL.Shader.SCREEN_VERTEX_SHADER,L.pixel_shader));var d=a.width|0,f=a.height|0,g=a.type;this.properties.precision===c.LOW?g=gl.UNSIGNED_BYTE:this.properties.precision===c.HIGH&&(g=gl.HIGH_PRECISION_FORMAT);var e=this.properties.iterations||1,l=a,h= +[];g={type:g,format:a.format};var m=vec2.create(),k={u_offset:m};this._texture&&GL.Texture.releaseTemporary(this._texture);for(var w=0;w>1||0;f=f>>1||0;a=GL.Texture.getTemporary(d,f,g);h.push(a);l.setParameter(GL.TEXTURE_MAG_FILTER,GL.NEAREST);l.copyTo(a,b,k);if(1==d&&1==f)break;l=a}this._texture=h.pop();for(w=0;wc;c++)this.isOutputConnected(c)?(this._channels[c]&&this._channels[c].width==a.width&&this._channels[c].height==a.height&&this._channels[c].type==a.type&&this._channels[c].format==b||(this._channels[c]=new GL.Texture(a.width,a.height,{type:a.type,format:b,filter:gl.LINEAR})), +d++):this._channels[c]=null;if(d){gl.disable(gl.BLEND);gl.disable(gl.DEPTH_TEST);var f=Mesh.getScreenQuad(),g=m._shader,e=[[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]];for(c=0;4>c;c++)this._channels[c]&&(this._channels[c].drawTo(function(){a.bind(0);g.uniforms({u_texture:0,u_mask:e[c]}).draw(f)}),this.setOutputData(c,this._channels[c]))}}},m.pixel_shader="precision highp float;\n\t\tprecision highp float;\n\t\tvarying vec2 v_coord;\n\t\tuniform sampler2D u_texture;\n\t\tuniform vec4 u_mask;\n\t\t\n\t\tvoid main() {\n\t\t gl_FragColor = vec4( vec3( length( texture2D(u_texture, v_coord) * u_mask )), 1.0 );\n\t\t}\n\t\t", +O.registerNodeType("texture/textureChannels",m),w.title="Channels to Texture",w.desc="Split texture channels",w.widgets_info={precision:{widget:"combo",values:c.MODE_VALUES}},w.prototype.onExecute=function(){var a=c.getWhiteTexture(),b=this.getInputData(0)||a,d=this.getInputData(1)||a,f=this.getInputData(2)||a,g=this.getInputData(3)||a;gl.disable(gl.BLEND);gl.disable(gl.DEPTH_TEST);var e=Mesh.getScreenQuad();w._shader||(w._shader=new GL.Shader(Shader.SCREEN_VERTEX_SHADER,w.pixel_shader));var l=w._shader; +a=Math.max(b.width,d.width,f.width,g.width);var h=Math.max(b.height,d.height,f.height,g.height),m=this.properties.precision==c.HIGH?c.HIGH_PRECISION_FORMAT:gl.UNSIGNED_BYTE;this._texture&&this._texture.width==a&&this._texture.height==h&&this._texture.type==m||(this._texture=new GL.Texture(a,h,{type:m,format:gl.RGBA,filter:gl.LINEAR}));a=this._color;a[0]=this.properties.R;a[1]=this.properties.G;a[2]=this.properties.B;a[3]=this.properties.A;var k=this._uniforms;this._texture.drawTo(function(){b.bind(0); +d.bind(1);f.bind(2);g.bind(3);l.uniforms(k).draw(e)});this.setOutputData(0,this._texture)},w.pixel_shader="precision highp float;\n\t\tprecision highp float;\n\t\tvarying vec2 v_coord;\n\t\tuniform sampler2D u_textureR;\n\t\tuniform sampler2D u_textureG;\n\t\tuniform sampler2D u_textureB;\n\t\tuniform sampler2D u_textureA;\n\t\tuniform vec4 u_color;\n\t\t\n\t\tvoid main() {\n\t\t gl_FragColor = u_color * vec4( \t\t\t\t\ttexture2D(u_textureR, v_coord).r,\t\t\t\t\ttexture2D(u_textureG, v_coord).r,\t\t\t\t\ttexture2D(u_textureB, v_coord).r,\t\t\t\t\ttexture2D(u_textureA, v_coord).r);\n\t\t}\n\t\t", +O.registerNodeType("texture/channelsTexture",w),N.title="Color",N.desc="Generates a 1x1 texture with a constant color",N.widgets_info={precision:{widget:"combo",values:c.MODE_VALUES}},N.prototype.onDrawBackground=function(a){var b=this.properties.color;a.fillStyle="rgb("+Math.floor(255*clamp(b[0],0,1))+","+Math.floor(255*clamp(b[1],0,1))+","+Math.floor(255*clamp(b[2],0,1))+")";this.flags.collapsed?this.boxcolor=a.fillStyle:a.fillRect(0,0,this.size[0],this.size[1])},N.prototype.onExecute=function(){var a= +this.properties.precision==c.HIGH?c.HIGH_PRECISION_FORMAT:gl.UNSIGNED_BYTE;this._tex&&this._tex.type==a||(this._tex=new GL.Texture(1,1,{format:gl.RGBA,type:a,minFilter:gl.NEAREST}));a=this.properties.color;if(this.inputs)for(var b=0;ba.width?d: +a,this._tex,this.properties.precision);gl.disable(gl.BLEND);gl.disable(gl.DEPTH_TEST);var e=Mesh.getScreenQuad(),l=null,h=this._uniforms;f?(l=b._shader_tex,l||(l=b._shader_tex=new GL.Shader(Shader.SCREEN_VERTEX_SHADER,b.pixel_shader,{MIX_TEX:""}))):(l=b._shader_factor,l||(l=b._shader_factor=new GL.Shader(Shader.SCREEN_VERTEX_SHADER,b.pixel_shader)),g=null==g?this.properties.factor:g,h.u_mix.set([g,g,g,g]));var m=this.properties.invert;this._tex.drawTo(function(){a.bind(m?1:0);d.bind(m?0:1);f&&f.bind(2); +l.uniforms(h).draw(e)});this.setOutputData(0,this._tex)}}},b.prototype.onGetInputs=function(){return[["factor","number"]]},b.pixel_shader="precision highp float;\n\t\tprecision highp float;\n\t\tvarying vec2 v_coord;\n\t\tuniform sampler2D u_textureA;\n\t\tuniform sampler2D u_textureB;\n\t\t#ifdef MIX_TEX\n\t\t\tuniform sampler2D u_textureMix;\n\t\t#else\n\t\t\tuniform vec4 u_mix;\n\t\t#endif\n\t\t\n\t\tvoid main() {\n\t\t\t#ifdef MIX_TEX\n\t\t\t vec4 f = texture2D(u_textureMix, v_coord);\n\t\t\t#else\n\t\t\t vec4 f = u_mix;\n\t\t\t#endif\n\t\t gl_FragColor = mix( texture2D(u_textureA, v_coord), texture2D(u_textureB, v_coord), f );\n\t\t}\n\t\t", +O.registerNodeType("texture/mix",b),d.title="Edges",d.desc="Detects edges",d.widgets_info={precision:{widget:"combo",values:c.MODE_VALUES}},d.prototype.onExecute=function(){if(this.isOutputConnected(0)){var a=this.getInputData(0);if(this.properties.precision===c.PASS_THROUGH)this.setOutputData(0,a);else if(a){this._tex=c.getTargetTexture(a,this._tex,this.properties.precision);gl.disable(gl.BLEND);gl.disable(gl.DEPTH_TEST);var b=Mesh.getScreenQuad(),f=d._shader,g=this.properties.invert,e=this.properties.factor, +l=this.properties.threshold?1:0;this._tex.drawTo(function(){a.bind(0);f.uniforms({u_texture:0,u_isize:[1/a.width,1/a.height],u_factor:e,u_threshold:l,u_invert:g?1:0}).draw(b)});this.setOutputData(0,this._tex)}}},d.pixel_shader="precision highp float;\n\t\tprecision highp float;\n\t\tvarying vec2 v_coord;\n\t\tuniform sampler2D u_texture;\n\t\tuniform vec2 u_isize;\n\t\tuniform int u_invert;\n\t\tuniform float u_factor;\n\t\tuniform float u_threshold;\n\t\t\n\t\tvoid main() {\n\t\t\tvec4 center = texture2D(u_texture, v_coord);\n\t\t\tvec4 up = texture2D(u_texture, v_coord + u_isize * vec2(0.0,1.0) );\n\t\t\tvec4 down = texture2D(u_texture, v_coord + u_isize * vec2(0.0,-1.0) );\n\t\t\tvec4 left = texture2D(u_texture, v_coord + u_isize * vec2(1.0,0.0) );\n\t\t\tvec4 right = texture2D(u_texture, v_coord + u_isize * vec2(-1.0,0.0) );\n\t\t\tvec4 diff = abs(center - up) + abs(center - down) + abs(center - left) + abs(center - right);\n\t\t\tdiff *= u_factor;\n\t\t\tif(u_invert == 1)\n\t\t\t\tdiff.xyz = vec3(1.0) - diff.xyz;\n\t\t\tif( u_threshold == 0.0 )\n\t\t\t\tgl_FragColor = vec4( diff.xyz, center.a );\n\t\t\telse\n\t\t\t\tgl_FragColor = vec4( diff.x > 0.5 ? 1.0 : 0.0, diff.y > 0.5 ? 1.0 : 0.0, diff.z > 0.5 ? 1.0 : 0.0, center.a );\n\t\t}\n\t\t", +O.registerNodeType("texture/edges",d),f.title="Depth Range",f.desc="Generates a texture with a depth range",f.prototype.onExecute=function(){if(this.isOutputConnected(0)){var a=this.getInputData(0);if(a){var b=gl.UNSIGNED_BYTE;this.properties.high_precision&&(b=gl.half_float_ext?gl.HALF_FLOAT_OES:gl.FLOAT);this._temp_texture&&this._temp_texture.type==b&&this._temp_texture.width==a.width&&this._temp_texture.height==a.height||(this._temp_texture=new GL.Texture(a.width,a.height,{type:b,format:gl.RGBA, +filter:gl.LINEAR}));var d=this._uniforms;b=this.properties.distance;this.isInputConnected(1)&&(b=this.getInputData(1),this.properties.distance=b);var c=this.properties.range;this.isInputConnected(2)&&(c=this.getInputData(2),this.properties.range=c);d.u_distance=b;d.u_range=c;gl.disable(gl.BLEND);gl.disable(gl.DEPTH_TEST);var g=Mesh.getScreenQuad();f._shader||(f._shader=new GL.Shader(Shader.SCREEN_VERTEX_SHADER,f.pixel_shader),f._shader_onlydepth=new GL.Shader(Shader.SCREEN_VERTEX_SHADER,f.pixel_shader, +{ONLY_DEPTH:""}));var e=this.properties.only_depth?f._shader_onlydepth:f._shader;b=null;b=a.near_far_planes?a.near_far_planes:window.LS&&LS.Renderer._main_camera?LS.Renderer._main_camera._uniforms.u_camera_planes:[.1,1E3];d.u_camera_planes=b;this._temp_texture.drawTo(function(){a.bind(0);e.uniforms(d).draw(g)});this._temp_texture.near_far_planes=b;this.setOutputData(0,this._temp_texture)}}},f.pixel_shader="precision highp float;\n\t\tprecision highp float;\n\t\tvarying vec2 v_coord;\n\t\tuniform sampler2D u_texture;\n\t\tuniform vec2 u_camera_planes;\n\t\tuniform float u_distance;\n\t\tuniform float u_range;\n\t\t\n\t\tfloat LinearDepth()\n\t\t{\n\t\t\tfloat zNear = u_camera_planes.x;\n\t\t\tfloat zFar = u_camera_planes.y;\n\t\t\tfloat depth = texture2D(u_texture, v_coord).x;\n\t\t\tdepth = depth * 2.0 - 1.0;\n\t\t\treturn zNear * (depth + 1.0) / (zFar + zNear - depth * (zFar - zNear));\n\t\t}\n\t\t\n\t\tvoid main() {\n\t\t\tfloat depth = LinearDepth();\n\t\t\t#ifdef ONLY_DEPTH\n\t\t\t gl_FragColor = vec4(depth);\n\t\t\t#else\n\t\t\t\tfloat diff = abs(depth * u_camera_planes.y - u_distance);\n\t\t\t\tfloat dof = 1.0;\n\t\t\t\tif(diff <= u_range)\n\t\t\t\t\tdof = diff / u_range;\n\t\t\t gl_FragColor = vec4(dof);\n\t\t\t#endif\n\t\t}\n\t\t", +O.registerNodeType("texture/depth_range",f),g.widgets_info={precision:{widget:"combo",values:c.MODE_VALUES}},g.title="Linear Depth",g.desc="Creates a color texture with linear depth",g.prototype.onExecute=function(){if(this.isOutputConnected(0)){var a=this.getInputData(0);if(a&&(a.format==gl.DEPTH_COMPONENT||a.format==gl.DEPTH_STENCIL)){var b=this.properties.precision==c.HIGH?gl.HIGH_PRECISION_FORMAT:gl.UNSIGNED_BYTE;this._temp_texture&&this._temp_texture.type==b&&this._temp_texture.width==a.width&& +this._temp_texture.height==a.height||(this._temp_texture=new GL.Texture(a.width,a.height,{type:b,format:gl.RGB,filter:gl.LINEAR}));var d=this._uniforms;d.u_invert=this.properties.invert?1:0;gl.disable(gl.BLEND);gl.disable(gl.DEPTH_TEST);var f=Mesh.getScreenQuad();g._shader||(g._shader=new GL.Shader(GL.Shader.SCREEN_VERTEX_SHADER,g.pixel_shader));var e=g._shader;b=null;b=a.near_far_planes?a.near_far_planes:window.LS&&LS.Renderer._main_camera?LS.Renderer._main_camera._uniforms.u_camera_planes:[.1,1E3]; +d.u_camera_planes=b;d.u_ires.set([0,0]);this._temp_texture.drawTo(function(){a.bind(0);e.uniforms(d).draw(f)});this._temp_texture.near_far_planes=b;this.setOutputData(0,this._temp_texture)}}},g.pixel_shader="precision highp float;\n\t\tprecision highp float;\n\t\tvarying vec2 v_coord;\n\t\tuniform sampler2D u_texture;\n\t\tuniform vec2 u_camera_planes;\n\t\tuniform int u_invert;\n\t\tuniform vec2 u_ires;\n\t\t\n\t\tvoid main() {\n\t\t\tfloat zNear = u_camera_planes.x;\n\t\t\tfloat zFar = u_camera_planes.y;\n\t\t\tfloat depth = texture2D(u_texture, v_coord + u_ires*0.5).x * 2.0 - 1.0;\n\t\t\tfloat f = zNear * (depth + 1.0) / (zFar + zNear - depth * (zFar - zNear));\n\t\t\tif( u_invert == 1 )\n\t\t\t\tf = 1.0 - f;\n\t\t\tgl_FragColor = vec4(vec3(f),1.0);\n\t\t}\n\t\t", +O.registerNodeType("texture/linear_depth",g),q.title="Blur",q.desc="Blur a texture",q.widgets_info={precision:{widget:"combo",values:c.MODE_VALUES}},q.max_iterations=20,q.prototype.onExecute=function(){var a=this.getInputData(0);if(a&&this.isOutputConnected(0)){var b=this._final_texture;b&&b.width==a.width&&b.height==a.height&&b.type==a.type||(b=this._final_texture=new GL.Texture(a.width,a.height,{type:a.type,format:gl.RGBA,filter:gl.LINEAR}));var d=this.properties.iterations;this.isInputConnected(1)&& +(d=this.getInputData(1),this.properties.iterations=d);d=Math.min(Math.floor(d),q.max_iterations);if(0==d)this.setOutputData(0,a);else{var c=this.properties.intensity;this.isInputConnected(2)&&(c=this.getInputData(2),this.properties.intensity=c);var f=O.camera_aspect;f||void 0===window.gl||(f=gl.canvas.height/gl.canvas.width);f||(f=1);f=this.properties.preserve_aspect?f:1;var g=this.properties.scale||[1,1];a.applyBlur(f*g[0],g[1],c,b);for(a=1;a>=1;1<(g|0)&&(g>>=1);if(2>f)break;k=h[A]=GL.Texture.getTemporary(f,g,e);q[0]=1/w.width;q[1]=1/w.height;w.blit(k,m.uniforms(l));w=k}c&&(q[0]=1/w.width,q[1]=1/w.height,l.u_intensity=G,l.u_delta=1,w.blit(c,m.uniforms(l)));gl.enable(gl.BLEND);gl.blendFunc(gl.ONE,gl.ONE);l.u_intensity=this.persistence; +l.u_delta=.5;for(A-=2;0<=A;A--)k=h[A],h[A]=null,q[0]=1/w.width,q[1]=1/w.height,w.blit(k,m.uniforms(l)),GL.Texture.releaseTemporary(w),w=k;gl.disable(gl.BLEND);d&&w.blit(d);if(b){var n=this.dirt_texture,t=this.dirt_factor;l.u_intensity=G;m=n?z._dirt_final_shader:z._final_shader;m||(m=n?z._dirt_final_shader=new GL.Shader(GL.Shader.SCREEN_VERTEX_SHADER,z.final_pixel_shader,{USE_DIRT:""}):z._final_shader=new GL.Shader(GL.Shader.SCREEN_VERTEX_SHADER,z.final_pixel_shader));b.drawTo(function(){a.bind(0); +w.bind(1);n&&(m.setUniform("u_dirt_factor",t),m.setUniform("u_dirt_texture",n.bind(2)));m.toViewport(l)})}GL.Texture.releaseTemporary(w)},z.cut_pixel_shader="precision highp float;\n\tvarying vec2 v_coord;\n\tuniform sampler2D u_texture;\n\tuniform float u_threshold;\n\tvoid main() {\n\t\tgl_FragColor = max( texture2D( u_texture, v_coord ) - vec4( u_threshold ), vec4(0.0) );\n\t}",z.scale_pixel_shader="precision highp float;\n\tvarying vec2 v_coord;\n\tuniform sampler2D u_texture;\n\tuniform vec2 u_texel_size;\n\tuniform float u_delta;\n\tuniform float u_intensity;\n\t\n\tvec4 sampleBox(vec2 uv) {\n\t\tvec4 o = u_texel_size.xyxy * vec2(-u_delta, u_delta).xxyy;\n\t\tvec4 s = texture2D( u_texture, uv + o.xy ) + texture2D( u_texture, uv + o.zy) + texture2D( u_texture, uv + o.xw) + texture2D( u_texture, uv + o.zw);\n\t\treturn s * 0.25;\n\t}\n\tvoid main() {\n\t\tgl_FragColor = u_intensity * sampleBox( v_coord );\n\t}", +z.final_pixel_shader="precision highp float;\n\tvarying vec2 v_coord;\n\tuniform sampler2D u_texture;\n\tuniform sampler2D u_glow_texture;\n\t#ifdef USE_DIRT\n\t\tuniform sampler2D u_dirt_texture;\n\t#endif\n\tuniform vec2 u_texel_size;\n\tuniform float u_delta;\n\tuniform float u_intensity;\n\tuniform float u_dirt_factor;\n\t\n\tvec4 sampleBox(vec2 uv) {\n\t\tvec4 o = u_texel_size.xyxy * vec2(-u_delta, u_delta).xxyy;\n\t\tvec4 s = texture2D( u_glow_texture, uv + o.xy ) + texture2D( u_glow_texture, uv + o.zy) + texture2D( u_glow_texture, uv + o.xw) + texture2D( u_glow_texture, uv + o.zw);\n\t\treturn s * 0.25;\n\t}\n\tvoid main() {\n\t\tvec4 glow = sampleBox( v_coord );\n\t\t#ifdef USE_DIRT\n\t\t\tglow = mix( glow, glow * texture2D( u_dirt_texture, v_coord ), u_dirt_factor );\n\t\t#endif\n\t\tgl_FragColor = texture2D( u_texture, v_coord ) + u_intensity * glow;\n\t}", +P.title="Glow",P.desc="Filters a texture giving it a glow effect",P.widgets_info={iterations:{type:"number",min:0,max:16,step:1,precision:0},threshold:{type:"number",min:0,max:10,step:.01,precision:2},precision:{widget:"combo",values:c.MODE_VALUES}},P.prototype.onGetInputs=function(){return[["enabled","boolean"],["threshold","number"],["intensity","number"],["persistence","number"],["iterations","number"],["dirt_factor","number"]]},P.prototype.onGetOutputs=function(){return[["average","Texture"]]}, +P.prototype.onExecute=function(){var a=this.getInputData(0);if(a&&this.isAnyOutputConnected())if(this.properties.precision===c.PASS_THROUGH||!1===this.getInputOrProperty("enabled"))this.setOutputData(0,a);else{var b=this.fx;b.threshold=this.getInputOrProperty("threshold");b.iterations=this.getInputOrProperty("iterations");b.intensity=this.getInputOrProperty("intensity");b.persistence=this.getInputOrProperty("persistence");b.dirt_texture=this.getInputData(1);b.dirt_factor=this.getInputOrProperty("dirt_factor"); +b.scale=this.properties.scale;var d=c.getTextureType(this.properties.precision,a),f=null;this.isOutputConnected(2)&&(f=this._average_texture,f&&f.type==a.type&&f.format==a.format||(f=this._average_texture=new GL.Texture(1,1,{type:a.type,format:a.format,filter:gl.LINEAR})));var g=null;this.isOutputConnected(1)&&(g=this._glow_texture,g&&g.width==a.width&&g.height==a.height&&g.type==d&&g.format==a.format||(g=this._glow_texture=new GL.Texture(a.width,a.height,{type:d,format:a.format,filter:gl.LINEAR}))); +var e=null;this.isOutputConnected(0)&&(e=this._final_texture,e&&e.width==a.width&&e.height==a.height&&e.type==d&&e.format==a.format||(e=this._final_texture=new GL.Texture(a.width,a.height,{type:d,format:a.format,filter:gl.LINEAR})));b.applyFX(a,e,g,f);this.isOutputConnected(0)&&this.setOutputData(0,e);this.isOutputConnected(1)&&this.setOutputData(1,f);this.isOutputConnected(2)&&this.setOutputData(2,g)}},O.registerNodeType("texture/glow",P),I.title="Kuwahara Filter",I.desc="Filters a texture giving an artistic oil canvas painting", +I.max_radius=10,I._shaders=[],I.prototype.onExecute=function(){var a=this.getInputData(0);if(a&&this.isOutputConnected(0)){var b=this._temp_texture;b&&b.width==a.width&&b.height==a.height&&b.type==a.type||(this._temp_texture=new GL.Texture(a.width,a.height,{type:a.type,format:gl.RGBA,filter:gl.LINEAR}));b=this.properties.radius;b=Math.min(Math.floor(b),I.max_radius);if(0==b)this.setOutputData(0,a);else{var d=this.properties.intensity,c=O.camera_aspect;c||void 0===window.gl||(c=gl.canvas.height/gl.canvas.width); +c||(c=1);c=this.properties.preserve_aspect?c:1;I._shaders[b]||(I._shaders[b]=new GL.Shader(Shader.SCREEN_VERTEX_SHADER,I.pixel_shader,{RADIUS:b.toFixed(0)}));var f=I._shaders[b],g=GL.Mesh.getScreenQuad();a.bind(0);this._temp_texture.drawTo(function(){f.uniforms({u_texture:0,u_intensity:d,u_resolution:[a.width,a.height],u_iResolution:[1/a.width,1/a.height]}).draw(g)});this.setOutputData(0,this._temp_texture)}}},I.pixel_shader="\nprecision highp float;\nvarying vec2 v_coord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nuniform vec2 u_resolution;\nuniform vec2 u_iResolution;\n#ifndef RADIUS\n\t#define RADIUS 7\n#endif\nvoid main() {\n\n\tconst int radius = RADIUS;\n\tvec2 fragCoord = v_coord;\n\tvec2 src_size = u_iResolution;\n\tvec2 uv = v_coord;\n\tfloat n = float((radius + 1) * (radius + 1));\n\tint i;\n\tint j;\n\tvec3 m0 = vec3(0.0); vec3 m1 = vec3(0.0); vec3 m2 = vec3(0.0); vec3 m3 = vec3(0.0);\n\tvec3 s0 = vec3(0.0); vec3 s1 = vec3(0.0); vec3 s2 = vec3(0.0); vec3 s3 = vec3(0.0);\n\tvec3 c;\n\t\n\tfor (int j = -radius; j <= 0; ++j) {\n\t\tfor (int i = -radius; i <= 0; ++i) {\n\t\t\tc = texture2D(u_texture, uv + vec2(i,j) * src_size).rgb;\n\t\t\tm0 += c;\n\t\t\ts0 += c * c;\n\t\t}\n\t}\n\t\n\tfor (int j = -radius; j <= 0; ++j) {\n\t\tfor (int i = 0; i <= radius; ++i) {\n\t\t\tc = texture2D(u_texture, uv + vec2(i,j) * src_size).rgb;\n\t\t\tm1 += c;\n\t\t\ts1 += c * c;\n\t\t}\n\t}\n\t\n\tfor (int j = 0; j <= radius; ++j) {\n\t\tfor (int i = 0; i <= radius; ++i) {\n\t\t\tc = texture2D(u_texture, uv + vec2(i,j) * src_size).rgb;\n\t\t\tm2 += c;\n\t\t\ts2 += c * c;\n\t\t}\n\t}\n\t\n\tfor (int j = 0; j <= radius; ++j) {\n\t\tfor (int i = -radius; i <= 0; ++i) {\n\t\t\tc = texture2D(u_texture, uv + vec2(i,j) * src_size).rgb;\n\t\t\tm3 += c;\n\t\t\ts3 += c * c;\n\t\t}\n\t}\n\t\n\tfloat min_sigma2 = 1e+2;\n\tm0 /= n;\n\ts0 = abs(s0 / n - m0 * m0);\n\t\n\tfloat sigma2 = s0.r + s0.g + s0.b;\n\tif (sigma2 < min_sigma2) {\n\t\tmin_sigma2 = sigma2;\n\t\tgl_FragColor = vec4(m0, 1.0);\n\t}\n\t\n\tm1 /= n;\n\ts1 = abs(s1 / n - m1 * m1);\n\t\n\tsigma2 = s1.r + s1.g + s1.b;\n\tif (sigma2 < min_sigma2) {\n\t\tmin_sigma2 = sigma2;\n\t\tgl_FragColor = vec4(m1, 1.0);\n\t}\n\t\n\tm2 /= n;\n\ts2 = abs(s2 / n - m2 * m2);\n\t\n\tsigma2 = s2.r + s2.g + s2.b;\n\tif (sigma2 < min_sigma2) {\n\t\tmin_sigma2 = sigma2;\n\t\tgl_FragColor = vec4(m2, 1.0);\n\t}\n\t\n\tm3 /= n;\n\ts3 = abs(s3 / n - m3 * m3);\n\t\n\tsigma2 = s3.r + s3.g + s3.b;\n\tif (sigma2 < min_sigma2) {\n\t\tmin_sigma2 = sigma2;\n\t\tgl_FragColor = vec4(m3, 1.0);\n\t}\n}\n", +O.registerNodeType("texture/kuwahara",I),t.title="XDoG Filter",t.desc="Filters a texture giving an artistic ink style",t.max_radius=10,t._shaders=[],t.prototype.onExecute=function(){var a=this.getInputData(0);if(a&&this.isOutputConnected(0)){var b=this._temp_texture;b&&b.width==a.width&&b.height==a.height&&b.type==a.type||(this._temp_texture=new GL.Texture(a.width,a.height,{type:a.type,format:gl.RGBA,filter:gl.LINEAR}));t._xdog_shader||(t._xdog_shader=new GL.Shader(Shader.SCREEN_VERTEX_SHADER,t.xdog_pixel_shader)); +var d=t._xdog_shader,c=GL.Mesh.getScreenQuad(),f=this.properties.sigma,g=this.properties.k,e=this.properties.p,l=this.properties.epsilon,h=this.properties.phi;a.bind(0);this._temp_texture.drawTo(function(){d.uniforms({src:0,sigma:f,k:g,p:e,epsilon:l,phi:h,cvsWidth:a.width,cvsHeight:a.height}).draw(c)});this.setOutputData(0,this._temp_texture)}},t.xdog_pixel_shader="\nprecision highp float;\nuniform sampler2D src;\n\nuniform float cvsHeight;\nuniform float cvsWidth;\n\nuniform float sigma;\nuniform float k;\nuniform float p;\nuniform float epsilon;\nuniform float phi;\nvarying vec2 v_coord;\n\nfloat cosh(float val)\n{\n\tfloat tmp = exp(val);\n\tfloat cosH = (tmp + 1.0 / tmp) / 2.0;\n\treturn cosH;\n}\n\nfloat tanh(float val)\n{\n\tfloat tmp = exp(val);\n\tfloat tanH = (tmp - 1.0 / tmp) / (tmp + 1.0 / tmp);\n\treturn tanH;\n}\n\nfloat sinh(float val)\n{\n\tfloat tmp = exp(val);\n\tfloat sinH = (tmp - 1.0 / tmp) / 2.0;\n\treturn sinH;\n}\n\nvoid main(void){\n\tvec3 destColor = vec3(0.0);\n\tfloat tFrag = 1.0 / cvsHeight;\n\tfloat sFrag = 1.0 / cvsWidth;\n\tvec2 Frag = vec2(sFrag,tFrag);\n\tvec2 uv = gl_FragCoord.st;\n\tfloat twoSigmaESquared = 2.0 * sigma * sigma;\n\tfloat twoSigmaRSquared = twoSigmaESquared * k * k;\n\tint halfWidth = int(ceil( 1.0 * sigma * k ));\n\n\tconst int MAX_NUM_ITERATION = 99999;\n\tvec2 sum = vec2(0.0);\n\tvec2 norm = vec2(0.0);\n\n\tfor(int cnt=0;cnt (2*halfWidth+1)*(2*halfWidth+1)){break;}\n\t\tint i = int(cnt / (2*halfWidth+1)) - halfWidth;\n\t\tint j = cnt - halfWidth - int(cnt / (2*halfWidth+1)) * (2*halfWidth+1);\n\n\t\tfloat d = length(vec2(i,j));\n\t\tvec2 kernel = vec2( exp( -d * d / twoSigmaESquared ), \n\t\t\t\t\t\t\texp( -d * d / twoSigmaRSquared ));\n\n\t\tvec2 L = texture2D(src, (uv + vec2(i,j)) * Frag).xx;\n\n\t\tnorm += kernel;\n\t\tsum += kernel * L;\n\t}\n\n\tsum /= norm;\n\n\tfloat H = 100.0 * ((1.0 + p) * sum.x - p * sum.y);\n\tfloat edge = ( H > epsilon )? 1.0 : 1.0 + tanh( phi * (H - epsilon));\n\tdestColor = vec3(edge);\n\tgl_FragColor = vec4(destColor, 1.0);\n}", +O.registerNodeType("texture/xDoG",t),v.title="Webcam",v.desc="Webcam texture",v.is_webcam_open=!1,v.prototype.openStream=function(){if(navigator.getUserMedia){this._waiting_confirmation=!0;navigator.mediaDevices.getUserMedia({audio:!1,video:{facingMode:this.properties.facingMode}}).then(this.streamReady.bind(this)).catch(function(b){v.is_webcam_open=!1;console.log("Webcam rejected",b);a._webcam_stream=!1;a.boxcolor="red";a.trigger("stream_error")});var a=this}},v.prototype.closeStream=function(){if(this._webcam_stream){var a= +this._webcam_stream.getTracks();if(a.length)for(var b=0;b=this.size[1]||!this._video||(a.save(),a.webgl?this._video_texture&&a.drawImage(this._video_texture,0,0,this.size[0],this.size[1]):a.drawImage(this._video, +0,0,this.size[0],this.size[1]),a.restore())},v.prototype.onExecute=function(){null!=this._webcam_stream||this._waiting_confirmation||this.openStream();if(this._video&&this._video.videoWidth){var a=this._video.videoWidth,b=this._video.videoHeight,d=this._video_texture;d&&d.width==a&&d.height==b||(this._video_texture=new GL.Texture(a,b,{format:gl.RGB,filter:gl.LINEAR}));this._video_texture.uploadImage(this._video);this._video_texture.version=++this.version;this.properties.texture_name&&(c.getTexturesContainer()[this.properties.texture_name]= +this._video_texture);this.setOutputData(0,this._video_texture);for(a=1;aMath.abs(b))return c[1];a=(a-c[0])/b;return c[1]*(1-a)+f[1]*a}}return 0}},G.prototype.updateCurve=function(){for(var a=this._values,b=a.length/4,d=this.properties.split_channels,c=0;cd+f.NODE_TITLE_HEIGHT&&a.drawImage(b,10,g,this.size[0]-20,this.size[1]-d-f.NODE_TITLE_HEIGHT);var g=this.size[1]-f.NODE_TITLE_HEIGHT+.5;c=f.isInsideRectangle(c[0],c[1],this.pos[0],this.pos[1]+g,this.size[0],f.NODE_TITLE_HEIGHT);a.fillStyle=c?"#555":"#222";a.beginPath();this._shape==f.BOX_SHAPE?a.rect(0,g,this.size[0]+1,f.NODE_TITLE_HEIGHT):a.roundRect(0,g,this.size[0]+1,f.NODE_TITLE_HEIGHT,0,8);a.fill();a.textAlign="center";a.font="24px Arial";a.fillStyle= +c?"#DDD":"#999";a.fillText("+",.5*this.size[0],g+24)}};E.prototype.onMouseDown=function(a,b,d){b[1]>this.size[1]-f.NODE_TITLE_HEIGHT+.5&&d.showSubgraphPropertiesDialog(this)};E.prototype.onDrawSubgraphBackground=function(a){};E.prototype.getExtraMenuOptions=function(a){var b=this;return[{content:"Print Code",callback:function(){var a=b._context.computeShaderCode();console.log(a.vs_code,a.fs_code)}}]};f.registerNodeType("texture/shaderGraph",E);D.title="Uniform";D.desc="Input data for the shader"; +D.prototype.getTitle=function(){return this.properties.name&&this.flags.collapsed?this.properties.type+" "+this.properties.name:"Uniform"};D.prototype.onPropertyChanged=function(a,b){this.outputs[0].name=this.properties.type+" "+this.properties.name};D.prototype.onGetCode=function(a){if(this.shader_destination){var b=this.properties.type;if(!b){if(!a.onGetPropertyInfo)return;b=a.onGetPropertyInfo(this.property.name);if(!b)return;b=b.type}"number"==b?b="float":"texture"==b&&(b="sampler2D");-1!=g.GLSL_types.indexOf(b)&& +(a.addUniform("u_"+this.properties.name,b),this.setOutputData(0,b))}};D.prototype.getOutputVarName=function(a){return"u_"+this.properties.name};k("input/uniform",D);J.title="Attribute";J.desc="Input data from mesh attribute";J.prototype.getTitle=function(){return"att. "+this.properties.name};J.prototype.onGetCode=function(a){if(this.shader_destination){var b=this.properties.type;b&&-1!=g.GLSL_types.indexOf(b)&&("number"==b&&(b="float"),"coord"!=this.properties.name&&a.addCode("varying"," varying "+ +b+" v_"+this.properties.name+";"),this.setOutputData(0,b))}};J.prototype.getOutputVarName=function(a){return"v_"+this.properties.name};k("input/attribute",J);L.title="Sampler2D";L.desc="Reads a pixel from a texture";L.prototype.onGetCode=function(a){if(this.shader_destination){var b=r(this,0),d=n(this),c="vec4 "+d+" = vec4(0.0);\n";if(b){var f=r(this,1)||a.buffer_names.uvs;c+=d+" = texture2D("+b+","+f+");\n"}u(this,0)&&(c+="vec4 "+u(this,0)+" = "+d+";\n");u(this,1)&&(c+="vec3 "+u(this,1)+" = "+d+ +".xyz;\n");a.addCode("code",c,this.shader_destination);this.setOutputData(0,"vec4");this.setOutputData(1,"vec3")}};k("texture/sampler2D",L);H.title="const";H.prototype.getTitle=function(){return this.flags.collapsed?t(this.properties.value,this.properties.type,2):"Const"};H.prototype.onPropertyChanged=function(a,b){"type"==a&&(this.outputs[0].type!=b&&(this.disconnectOutput(0),this.outputs[0].type=b),this.widgets.length=1,this.updateWidgets());"value"==a&&(b.length?(this.widgets[1].value=b[1],2d;++d)b.push({name:r(this,d),type:this.getInputData(d)||"float"});var c=u(this,0);if(c){var f=b[0].type,g=this.properties.operation, +e=[];for(d=0;2>d;++d){var l=b[d].name;null==l&&(l=null!=p.value?p.value:"(1.0)",b[d].type="float");b[d].type!=f&&("float"!=b[d].type||"*"!=g&&"/"!=g)&&(l=C(l,b[d].type,f));e.push(l)}a.addCode("code",f+" "+c+" = "+e[0]+g+e[1]+";",this.shader_destination);this.setOutputData(0,f)}}};k("math/operation",M);l.title="Func";l.prototype.onPropertyChanged=function(a,b){this.graph&&this.graph._version++;if("func"==a&&(a=P[b])){for(b=a.params.length;bd;++d)b.push({name:r(this,d),type:this.getInputData(d)||"float"});var c=u(this,0);if(c){var f=P[this.properties.func];if(f){var g=b[0].type,e=f.return_type;"T"==e&&(e=g);var l=[];for(d= +0;d=c;){g=.5*(e+c)|0;d=a[g];if(d==b)break;if(c==e-1)return c;da&&(a=1);this.points&&this.points.length==3*a||(this.points=new Float32Array(3*a));this.properties.generate_normals?this.normals&&this.normals.length==this.points.length||(this.normals=new Float32Array(this.points.length)):this.normals=null;var b=this._last_radius||this.properties.radius,d=this.properties.mode,c=this.getInputData(0);this._old_obj_version=c?c._version:null;this.points=k.generatePoints(b,a,d,this.points,this.normals, +this.properties.regular,c);this.version++};k.generatePoints=function(a,b,d,c,g,e,l){var f=3*b;c&&c.length==f||(c=new Float32Array(f));var h=new Float32Array(3),m=new Float32Array([0,1,0]);if(e)if(d==k.RECTANGLE){f=Math.floor(Math.sqrt(b));for(b=0;bg||ue&&el))break}this.geometry.indices=this.indices=new Uint32Array(h)}this.indices&&this.indices.length?(this.geometry.indices=this.indices,this.setOutputData(0,this.geometry)):this.setOutputData(0,null)}};B.registerNodeType("geometry/connectPoints",J);"undefined"!=typeof GL&&(L.title="to geometry",L.desc="converts a mesh to geometry",L.prototype.onExecute=function(){var a=this.getInputData(0);if(a){if(a!=this.last_mesh){this.last_mesh=a;for(i in a.vertexBuffers)this.geometry[i]= +a.vertexBuffers[i].data;a.indexBuffers.triangles&&(this.geometry.indices=a.indexBuffers.triangles.data);this.geometry._id=c();this.geometry._version=0}this.setOutputData(0,this.geometry);this.geometry&&this.setOutputData(1,this.geometry.vertices)}},B.registerNodeType("geometry/toGeometry",L),H.title="Geo to Mesh",H.prototype.updateMesh=function(a){this.mesh||(this.mesh=new GL.Mesh);for(var b in a)if("_"!=b[0]){var d=a[b],c=GL.Mesh.common_buffers[b];if(c||"indices"==b){c=c?c.spacing:3;var g=this.mesh.vertexBuffers[b]; +g&&g.data.length==d.length?(g.data.set(d),g.upload(GL.DYNAMIC_DRAW)):g=new GL.Buffer("indices"==b?GL.ELEMENT_ARRAY_BUFFER:GL.ARRAY_BUFFER,d,c,GL.DYNAMIC_DRAW);this.mesh.addBuffer(b,g)}}if(this.mesh.vertexBuffers.normals&&this.mesh.vertexBuffers.normals.data.length!=this.mesh.vertexBuffers.vertices.data.length){d=new Float32Array([0,1,0]);c=new Float32Array(this.mesh.vertexBuffers.vertices.data.length);for(b=0;b=c.NOTEON||l<=c.NOTEOFF)this.channel=e&15};Object.defineProperty(c.prototype,"velocity",{get:function(){return this.cmd==c.NOTEON?this.data[2]:-1},set:function(c){this.data[2]=c},enumerable:!0});c.notes="A A# B C C# D D# E F F# G G#".split(" ");c.note_to_index={A:0,"A#":1,B:2,C:3,"C#":4,D:5,"D#":6,E:7,F:8,"F#":9,G:10,"G#":11};Object.defineProperty(c.prototype,"note",{get:function(){return this.cmd!= +c.NOTEON?-1:c.toNoteString(this.data[1],!0)},set:function(c){throw"notes cannot be assigned this way, must modify the data[1]";},enumerable:!0});Object.defineProperty(c.prototype,"octave",{get:function(){return this.cmd!=c.NOTEON?-1:Math.floor((this.data[1]-24)/12+1)},set:function(c){throw"octave cannot be assigned this way, must modify the data[1]";},enumerable:!0});c.prototype.getPitch=function(){return 440*Math.pow(2,(this.data[1]-69)/12)};c.computePitch=function(c){return 440*Math.pow(2,(c-69)/ +12)};c.prototype.getCC=function(){return this.data[1]};c.prototype.getCCValue=function(){return this.data[2]};c.prototype.getPitchBend=function(){return this.data[1]+(this.data[2]<<7)-8192};c.computePitchBend=function(c,e){return c+(e<<7)-8192};c.prototype.setCommandFromString=function(e){this.cmd=c.computeCommandFromString(e)};c.computeCommandFromString=function(e){if(!e)return 0;if(e&&e.constructor===Number)return e;e=e.toUpperCase();switch(e){case "NOTE ON":case "NOTEON":return c.NOTEON;case "NOTE OFF":case "NOTEOFF":return c.NOTEON; +case "KEY PRESSURE":case "KEYPRESSURE":return c.KEYPRESSURE;case "CONTROLLER CHANGE":case "CONTROLLERCHANGE":case "CC":return c.CONTROLLERCHANGE;case "PROGRAM CHANGE":case "PROGRAMCHANGE":case "PC":return c.PROGRAMCHANGE;case "CHANNEL PRESSURE":case "CHANNELPRESSURE":return c.CHANNELPRESSURE;case "PITCH BEND":case "PITCHBEND":return c.PITCHBEND;case "TIME TICK":case "TIMETICK":return c.TIMETICK;default:return Number(e)}};c.toNoteString=function(e,h){e=Math.round(e);var l=Math.floor((e-24)/12+1);e= +(e-21)%12;0>e&&(e=12+e);return c.notes[e]+(h?"":l)};c.NoteStringToPitch=function(e){e=e.toUpperCase();var l=e[0],h=4;"#"==e[1]?(l+="#",2this.properties.max_value)return;this.trigger("on_midi",h)}};B.registerNodeType("midi/filter",h);E.title="MIDIEvent";E.desc="Create a MIDI Event";E.color="#243";E.prototype.onAction=function(e,h){"assign"==e?(this.properties.channel=h.channel,this.properties.cmd=h.cmd,this.properties.value1=h.data[1],this.properties.value2=h.data[2],h.cmd== +c.NOTEON?this.gate=!0:h.cmd==c.NOTEOFF&&(this.gate=!1)):(h=this.midi_event,h.channel=this.properties.channel,this.properties.cmd&&this.properties.cmd.constructor===String?h.setCommandFromString(this.properties.cmd):h.cmd=this.properties.cmd,h.data[0]=h.cmd|h.channel,h.data[1]=Number(this.properties.value1),h.data[2]=Number(this.properties.value2),this.trigger("on_midi",h))};E.prototype.onExecute=function(){var e=this.properties;if(this.inputs)for(var h=0;hc;++c)this.valid_notes[c]=-1!=this.notes_pitches.indexOf(c);for(c=0;12>c;++c)if(this.valid_notes[c])this.offset_notes[c]=0;else for(var e=1;12>e;++e){if(this.valid_notes[(c-e)%12]){this.offset_notes[c]=-e;break}if(this.valid_notes[(c+e)%12]){this.offset_notes[c]=e;break}}};H.prototype.onAction=function(e,h){h&&h.constructor===c&&(h.data[0]==c.NOTEON||h.data[0]==c.NOTEOFF?(this.midi_event=new c,this.midi_event.setup(h.data),this.midi_event.data[1]+=this.offset_notes[c.note_to_index[h.note]], +this.trigger("out",this.midi_event)):this.trigger("out",h))};H.prototype.onExecute=function(){var c=this.getInputData(1);null!=c&&c!=this._current_scale&&this.processScale(c)};B.registerNodeType("midi/quantize",H);F.title="MIDI fromFile";F.desc="Plays a MIDI file";F.color="#243";F.prototype.onAction=function(c){"play"==c?this.play():"pause"==c&&(this._playing=!this._playing)};F.prototype.onPropertyChanged=function(c,e){"url"==c&&this.loadMIDIFile(e)};F.prototype.onExecute=function(){if(this._midi&& +this._playing){this._current_time+=this.graph.elapsed_time;for(var e=100*this._current_time,h=0;ha;a++)for(var b=0;bd+f||c[1]>b))return a}}return-1};K.prototype.onAction=function(e,h){if("reset"==e)for(h=0;hh[1]))return e=this.getKeyIndex(h),this.keys[e]=!0,this._last_key=e,e=12*(this.properties.start_octave-1)+29+e,h=new c,h.setup([c.NOTEON,e,100]),this.trigger("note",h),!0};K.prototype.onMouseMove=function(e,h){if(!(0>h[1]||-1==this._last_key)){this.setDirtyCanvas(!0); +e=this.getKeyIndex(h);if(this._last_key==e)return!0;this.keys[this._last_key]=!1;h=12*(this.properties.start_octave-1)+29+this._last_key;var k=new c;k.setup([c.NOTEOFF,h,100]);this.trigger("note",k);this.keys[e]=!0;h=12*(this.properties.start_octave-1)+29+e;k=new c;k.setup([c.NOTEON,h,100]);this.trigger("note",k);this._last_key=e;return!0}};K.prototype.onMouseUp=function(e,h){if(!(0>h[1]))return e=this.getKeyIndex(h),this.keys[e]=!1,this._last_key=-1,e=12*(this.properties.start_octave-1)+29+e,h=new c, +h.setup([c.NOTEOFF,e,100]),this.trigger("note",h),!0};B.registerNodeType("midi/keys",K)})(this); +(function(y){function c(){this.properties={src:"",gain:.5,loop:!0,autoplay:!0,playbackRate:1};this._loading_audio=!1;this._audiobuffer=null;this._audionodes=[];this._last_sourcenode=null;this.addOutput("out","audio");this.addInput("gain","number");this.audionode=m.getAudioContext().createGain();this.audionode.graphnode=this;this.audionode.gain.value=this.properties.gain;this.properties.src&&this.loadSound(this.properties.src)}function k(){this.properties={gain:.5};this._audionodes=[];this._media_stream= +null;this.addOutput("out","audio");this.addInput("gain","number");this.audionode=m.getAudioContext().createGain();this.audionode.graphnode=this;this.audionode.gain.value=this.properties.gain}function n(){this.properties={fftSize:2048,minDecibels:-100,maxDecibels:-10,smoothingTimeConstant:.5};this.audionode=m.getAudioContext().createAnalyser();this.audionode.graphnode=this;this.audionode.fftSize=this.properties.fftSize;this.audionode.minDecibels=this.properties.minDecibels;this.audionode.maxDecibels= +this.properties.maxDecibels;this.audionode.smoothingTimeConstant=this.properties.smoothingTimeConstant;this.addInput("in","audio");this.addOutput("freqs","array");this.addOutput("samples","array");this._time_bin=this._freq_bin=null}function r(){this.properties={gain:1};this.audionode=m.getAudioContext().createGain();this.addInput("in","audio");this.addInput("gain","number");this.addOutput("out","audio")}function u(){this.properties={impulse_src:"",normalize:!0};this.audionode=m.getAudioContext().createConvolver(); +this.addInput("in","audio");this.addOutput("out","audio")}function h(){this.properties={threshold:-50,knee:40,ratio:12,reduction:-20,attack:0,release:.25};this.audionode=m.getAudioContext().createDynamicsCompressor();this.addInput("in","audio");this.addOutput("out","audio")}function E(){this.properties={};this.audionode=m.getAudioContext().createWaveShaper();this.addInput("in","audio");this.addInput("shape","waveshape");this.addOutput("out","audio")}function D(){this.properties={gain1:.5,gain2:.5}; +this.audionode=m.getAudioContext().createGain();this.audionode1=m.getAudioContext().createGain();this.audionode1.gain.value=this.properties.gain1;this.audionode2=m.getAudioContext().createGain();this.audionode2.gain.value=this.properties.gain2;this.audionode1.connect(this.audionode);this.audionode2.connect(this.audionode);this.addInput("in1","audio");this.addInput("in1 gain","number");this.addInput("in2","audio");this.addInput("in2 gain","number");this.addOutput("out","audio")}function J(){this.properties= +{A:.1,D:.1,S:.1,R:.1};this.audionode=m.getAudioContext().createGain();this.audionode.gain.value=0;this.addInput("in","audio");this.addInput("gate","boolean");this.addOutput("out","audio");this.gate=!1}function L(){this.properties={delayTime:.5};this.audionode=m.getAudioContext().createDelay(10);this.audionode.delayTime.value=this.properties.delayTime;this.addInput("in","audio");this.addInput("time","number");this.addOutput("out","audio")}function H(){this.properties={frequency:350,detune:0,Q:1};this.addProperty("type", +"lowpass","enum",{values:"lowpass highpass bandpass lowshelf highshelf peaking notch allpass".split(" ")});this.audionode=m.getAudioContext().createBiquadFilter();this.addInput("in","audio");this.addOutput("out","audio")}function F(){this.properties={frequency:440,detune:0,type:"sine"};this.addProperty("type","sine","enum",{values:["sine","square","sawtooth","triangle","custom"]});this.audionode=m.getAudioContext().createOscillator();this.addOutput("out","audio")}function e(){this.properties={continuous:!0, +mark:-1};this.addInput("data","array");this.addInput("mark","number");this.size=[300,200];this._last_buffer=null}function K(){this.properties={band:440,amplitude:1};this.addInput("freqs","array");this.addOutput("signal","number")}function B(){if(!B.default_code){var c=B.default_function.toString(),e=c.indexOf("{")+1,a=c.lastIndexOf("}");B.default_code=c.substr(e,a-e)}this.properties={code:B.default_code};c=m.getAudioContext();c.createScriptProcessor?this.audionode=c.createScriptProcessor(4096,1,1): +(console.warn("ScriptProcessorNode deprecated"),this.audionode=c.createGain());this.processCode();B._bypass_function||(B._bypass_function=this.audionode.onaudioprocess);this.addInput("in","audio");this.addOutput("out","audio")}function M(){this.audionode=m.getAudioContext().destination;this.addInput("in","audio")}var l=y.LiteGraph,m={};y.LGAudio=m;m.getAudioContext=function(){if(!this._audio_context){window.AudioContext=window.AudioContext||window.webkitAudioContext;if(!window.AudioContext)return console.error("AudioContext not supported by browser"), +null;this._audio_context=new AudioContext;this._audio_context.onmessage=function(c){console.log("msg",c)};this._audio_context.onended=function(c){console.log("ended",c)};this._audio_context.oncomplete=function(c){console.log("complete",c)}}return this._audio_context};m.connect=function(c,e){try{c.connect(e)}catch(a){console.warn("LGraphAudio:",a)}};m.disconnect=function(c,e){try{c.disconnect(e)}catch(a){console.warn("LGraphAudio:",a)}};m.changeAllAudiosConnections=function(c,e){if(c.inputs)for(var a= +0;a=this.size[0]&&(d=this.size[0]-1),c.strokeStyle= +"red",c.beginPath(),c.moveTo(d,b),c.lineTo(d,0),c.stroke())}};e.title="Visualization";e.desc="Audio Visualization";l.registerNodeType("audio/visualization",e);K.prototype.onExecute=function(){if(this._freqs=this.getInputData(0)){var c=this.properties.band,e=this.getInputData(1);void 0!==e&&(c=e);e=m.getAudioContext().sampleRate/this._freqs.length;e=c/e*2;e>=this._freqs.length?e=this._freqs[this._freqs.length-1]:(c=e|0,e-=c,e=this._freqs[c]*(1-e)+this._freqs[c+1]*e);this.setOutputData(0,e/255*this.properties.amplitude)}}; +K.prototype.onGetInputs=function(){return[["band","number"]]};K.title="Signal";K.desc="extract the signal of some frequency";l.registerNodeType("audio/signal",K);B.prototype.onAdded=function(c){c.status==LGraph.STATUS_RUNNING&&(this.audionode.onaudioprocess=this._callback)};B["@code"]={widget:"code",type:"code"};B.prototype.onStart=function(){this.audionode.onaudioprocess=this._callback};B.prototype.onStop=function(){this.audionode.onaudioprocess=B._bypass_function};B.prototype.onPause=function(){this.audionode.onaudioprocess= +B._bypass_function};B.prototype.onUnpause=function(){this.audionode.onaudioprocess=this._callback};B.prototype.onExecute=function(){};B.prototype.onRemoved=function(){this.audionode.onaudioprocess=B._bypass_function};B.prototype.processCode=function(){try{this._script=new (new Function("properties",this.properties.code))(this.properties),this._old_code=this.properties.code,this._callback=this._script.onaudioprocess}catch(w){console.error("Error in onaudioprocess code",w),this._callback=B._bypass_function, +this.audionode.onaudioprocess=this._callback}};B.prototype.onPropertyChanged=function(c,e){"code"==c&&(this.properties.code=e,this.processCode(),this.graph&&this.graph.status==LGraph.STATUS_RUNNING&&(this.audionode.onaudioprocess=this._callback))};B.default_function=function(){this.onaudioprocess=function(c){var e=c.inputBuffer;c=c.outputBuffer;for(var a=0;a + + + {% endblock %} @@ -43,13 +52,14 @@ @dragleave.prevent="dragCounter--" @dragover.prevent @drop.prevent="dragCounter = 0; handleDrop($event)" - class="space-y-4 relative pb-10"> + class="space-y-4 relative"> {% include 'partials/trial_viewer/_overlays.html' %} {% include 'partials/trial_viewer/_header.html' %} {% include 'partials/trial_viewer/_series_panel.html' %} {% include 'partials/trial_viewer/_chart.html' %} {% include 'partials/trial_viewer/_json_editor.html' %} + {% include 'partials/trial_viewer/_signal_lab.html' %} {% endblock %}