UNPKG

iobroker.vis-2

Version:

Next generation graphical user interface for ioBroker.

4,848 lines 184 kB
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./visOrderMenu-B4G4EPYH.js","./jsx-runtime-DgDbgMDY.js","./iobroker_vis__loadShare__react__loadShare__.js_commonjs-proxy-RR2_-oCU.js","./iobroker_vis__loadShare__react__loadShare__.js-Bo2lxMHB.js","./visWidgetsCatalog-D4OT0wlf.js","./iobroker_vis__loadShare___mf_0_iobroker_mf_1_adapter_mf_2_react_mf_2_v5__loadShare__.js-CyaIGDzt.js","./index-Cs8MllMO.js","./iobroker_vis__loadShare___mf_0_mui_mf_1_material__loadShare__.js-y8HJH6Vp.js","./iobroker_vis__loadShare___mf_0_mui_mf_1_icons_mf_2_material__loadShare__.js-L78p1KXL.js","./InsertDriveFile-B8DoT0SQ.js","./createSvgIcon-DDwAmV8Q.js","./iobroker_vis__loadShare__prop_mf_2_types__loadShare__.js-OoAqYupB.js","./clsx-XqGtd7JN.js","./iobroker_vis__loadShare___mf_0_mui_mf_1_system__loadShare__.js-Dt1au33l.js","./createStyled-BvULSPVR.js","./Dialog-DElqR5zv.js","./useMediaQuery-D88JRmB1.js","./assertThisInitialized-DFQXnDE3.js","./iobroker_vis__loadShare__react_mf_2_dom__loadShare__.js-1rEIXFyN.js","./hoist-non-react-statics.cjs-1ABLww7O.js","./preload-helper-D5QYaGzd.js"])))=>i.map(i=>d[i]);
import { j as jsxRuntimeExports, __tla as __tla_0 } from "./jsx-runtime-DgDbgMDY.js";
import { S as __mf_19, T as __mf_22, __tla as __tla_1 } from "./iobroker_vis__loadShare___mf_0_mui_mf_1_material__loadShare__.js-y8HJH6Vp.js";
import { _ as __mf_2, g as __mf_70, b as __mf_15, __tla as __tla_2 } from "./iobroker_vis__loadShare___mf_0_iobroker_mf_1_adapter_mf_2_react_mf_2_v5__loadShare__.js-CyaIGDzt.js";
import { _ as __vitePreload } from "./preload-helper-D5QYaGzd.js";
import { a as React, __tla as __tla_3 } from "./iobroker_vis__loadShare__react__loadShare__.js-Bo2lxMHB.js";
import { al as __mf_410, am as __mf_3181, an as __mf_4885, o as __mf_576, q as __mf_526, __tla as __tla_4 } from "./iobroker_vis__loadShare___mf_0_mui_mf_1_icons_mf_2_material__loadShare__.js-L78p1KXL.js";
import { __tla as __tla_5 } from "./iobroker_vis__loadShare__react__loadShare__.js_commonjs-proxy-RR2_-oCU.js";
let isVarFinite, replaceGroupAttr, selectView, DEFAULT_PERMISSIONS, parseDimension, hasWidgetAccess, visRxWidget, NOTHING_SELECTED, VisRxWidget, recalculateFields, selectWidget, getNewWidgetId, deepClone, extractBinding, findWidgetUsages, getNewWidgetIdNumber, hasViewAccess, isGroup, getNewGroupId, applyTitleAndIcon, isLocalStateId, getUrlParameter, updateProject, updateActiveUser, pasteGroup, hasProjectAccess, readFile, store, pasteSingleWidget, updateWidget, unsyncMultipleWidgets, VisBaseWidget, getUsedObjectIDsInWidget, addClass, calculateOverflow;
let __tla = Promise.all([
  (() => {
    try {
      return __tla_0;
    } catch {
    }
  })(),
  (() => {
    try {
      return __tla_1;
    } catch {
    }
  })(),
  (() => {
    try {
      return __tla_2;
    } catch {
    }
  })(),
  (() => {
    try {
      return __tla_3;
    } catch {
    }
  })(),
  (() => {
    try {
      return __tla_4;
    } catch {
    }
  })(),
  (() => {
    try {
      return __tla_5;
    } catch {
    }
  })()
]).then(async () => {
  function formatProdErrorMessage$1(code) {
    return `Minified Redux error #${code}; visit https://redux.js.org/Errors?code=${code} for the full message or use the non-minified dev environment for full errors. `;
  }
  var $$observable = (() => typeof Symbol === "function" && Symbol.observable || "@@observable")();
  var symbol_observable_default = $$observable;
  var randomString = () => Math.random().toString(36).substring(7).split("").join(".");
  var ActionTypes = {
    INIT: `@@redux/INIT${randomString()}`,
    REPLACE: `@@redux/REPLACE${randomString()}`,
    PROBE_UNKNOWN_ACTION: () => `@@redux/PROBE_UNKNOWN_ACTION${randomString()}`
  };
  var actionTypes_default = ActionTypes;
  function isPlainObject$1(obj) {
    if (typeof obj !== "object" || obj === null) return false;
    let proto = obj;
    while (Object.getPrototypeOf(proto) !== null) {
      proto = Object.getPrototypeOf(proto);
    }
    return Object.getPrototypeOf(obj) === proto || Object.getPrototypeOf(obj) === null;
  }
  function createStore(reducer2, preloadedState, enhancer) {
    if (typeof reducer2 !== "function") {
      throw new Error(formatProdErrorMessage$1(2));
    }
    if (typeof preloadedState === "function" && typeof enhancer === "function" || typeof enhancer === "function" && typeof arguments[3] === "function") {
      throw new Error(formatProdErrorMessage$1(0));
    }
    if (typeof preloadedState === "function" && typeof enhancer === "undefined") {
      enhancer = preloadedState;
      preloadedState = void 0;
    }
    if (typeof enhancer !== "undefined") {
      if (typeof enhancer !== "function") {
        throw new Error(formatProdErrorMessage$1(1));
      }
      return enhancer(createStore)(reducer2, preloadedState);
    }
    let currentReducer = reducer2;
    let currentState = preloadedState;
    let currentListeners = /* @__PURE__ */ new Map();
    let nextListeners = currentListeners;
    let listenerIdCounter = 0;
    let isDispatching = false;
    function ensureCanMutateNextListeners() {
      if (nextListeners === currentListeners) {
        nextListeners = /* @__PURE__ */ new Map();
        currentListeners.forEach((listener, key) => {
          nextListeners.set(key, listener);
        });
      }
    }
    function getState() {
      if (isDispatching) {
        throw new Error(formatProdErrorMessage$1(3));
      }
      return currentState;
    }
    function subscribe(listener) {
      if (typeof listener !== "function") {
        throw new Error(formatProdErrorMessage$1(4));
      }
      if (isDispatching) {
        throw new Error(formatProdErrorMessage$1(5));
      }
      let isSubscribed = true;
      ensureCanMutateNextListeners();
      const listenerId = listenerIdCounter++;
      nextListeners.set(listenerId, listener);
      return function unsubscribe() {
        if (!isSubscribed) {
          return;
        }
        if (isDispatching) {
          throw new Error(formatProdErrorMessage$1(6));
        }
        isSubscribed = false;
        ensureCanMutateNextListeners();
        nextListeners.delete(listenerId);
        currentListeners = null;
      };
    }
    function dispatch(action) {
      if (!isPlainObject$1(action)) {
        throw new Error(formatProdErrorMessage$1(7));
      }
      if (typeof action.type === "undefined") {
        throw new Error(formatProdErrorMessage$1(8));
      }
      if (typeof action.type !== "string") {
        throw new Error(formatProdErrorMessage$1(17));
      }
      if (isDispatching) {
        throw new Error(formatProdErrorMessage$1(9));
      }
      try {
        isDispatching = true;
        currentState = currentReducer(currentState, action);
      } finally {
        isDispatching = false;
      }
      const listeners = currentListeners = nextListeners;
      listeners.forEach((listener) => {
        listener();
      });
      return action;
    }
    function replaceReducer(nextReducer) {
      if (typeof nextReducer !== "function") {
        throw new Error(formatProdErrorMessage$1(10));
      }
      currentReducer = nextReducer;
      dispatch({
        type: actionTypes_default.REPLACE
      });
    }
    function observable() {
      const outerSubscribe = subscribe;
      return {
        subscribe(observer) {
          if (typeof observer !== "object" || observer === null) {
            throw new Error(formatProdErrorMessage$1(11));
          }
          function observeState() {
            const observerAsObserver = observer;
            if (observerAsObserver.next) {
              observerAsObserver.next(getState());
            }
          }
          observeState();
          const unsubscribe = outerSubscribe(observeState);
          return {
            unsubscribe
          };
        },
        [symbol_observable_default]() {
          return this;
        }
      };
    }
    dispatch({
      type: actionTypes_default.INIT
    });
    const store2 = {
      dispatch,
      subscribe,
      getState,
      replaceReducer,
      [symbol_observable_default]: observable
    };
    return store2;
  }
  function assertReducerShape(reducers) {
    Object.keys(reducers).forEach((key) => {
      const reducer2 = reducers[key];
      const initialState2 = reducer2(void 0, {
        type: actionTypes_default.INIT
      });
      if (typeof initialState2 === "undefined") {
        throw new Error(formatProdErrorMessage$1(12));
      }
      if (typeof reducer2(void 0, {
        type: actionTypes_default.PROBE_UNKNOWN_ACTION()
      }) === "undefined") {
        throw new Error(formatProdErrorMessage$1(13));
      }
    });
  }
  function combineReducers(reducers) {
    const reducerKeys = Object.keys(reducers);
    const finalReducers = {};
    for (let i = 0; i < reducerKeys.length; i++) {
      const key = reducerKeys[i];
      if (typeof reducers[key] === "function") {
        finalReducers[key] = reducers[key];
      }
    }
    const finalReducerKeys = Object.keys(finalReducers);
    let shapeAssertionError;
    try {
      assertReducerShape(finalReducers);
    } catch (e) {
      shapeAssertionError = e;
    }
    return function combination(state = {}, action) {
      if (shapeAssertionError) {
        throw shapeAssertionError;
      }
      let hasChanged = false;
      const nextState = {};
      for (let i = 0; i < finalReducerKeys.length; i++) {
        const key = finalReducerKeys[i];
        const reducer2 = finalReducers[key];
        const previousStateForKey = state[key];
        const nextStateForKey = reducer2(previousStateForKey, action);
        if (typeof nextStateForKey === "undefined") {
          action && action.type;
          throw new Error(formatProdErrorMessage$1(14));
        }
        nextState[key] = nextStateForKey;
        hasChanged = hasChanged || nextStateForKey !== previousStateForKey;
      }
      hasChanged = hasChanged || finalReducerKeys.length !== Object.keys(state).length;
      return hasChanged ? nextState : state;
    };
  }
  function compose(...funcs) {
    if (funcs.length === 0) {
      return (arg) => arg;
    }
    if (funcs.length === 1) {
      return funcs[0];
    }
    return funcs.reduce((a, b) => (...args) => a(b(...args)));
  }
  function applyMiddleware(...middlewares) {
    return (createStore2) => (reducer2, preloadedState) => {
      const store2 = createStore2(reducer2, preloadedState);
      let dispatch = () => {
        throw new Error(formatProdErrorMessage$1(15));
      };
      const middlewareAPI = {
        getState: store2.getState,
        dispatch: (action, ...args) => dispatch(action, ...args)
      };
      const chain = middlewares.map((middleware) => middleware(middlewareAPI));
      dispatch = compose(...chain)(store2.dispatch);
      return {
        ...store2,
        dispatch
      };
    };
  }
  function isAction(action) {
    return isPlainObject$1(action) && "type" in action && typeof action.type === "string";
  }
  var NOTHING = /* @__PURE__ */ Symbol.for("immer-nothing");
  var DRAFTABLE = /* @__PURE__ */ Symbol.for("immer-draftable");
  var DRAFT_STATE = /* @__PURE__ */ Symbol.for("immer-state");
  function die(error, ...args) {
    throw new Error(`[Immer] minified error nr: ${error}. Full error at: https://bit.ly/3cXEKWf`);
  }
  var O = Object;
  var getPrototypeOf = O.getPrototypeOf;
  var CONSTRUCTOR = "constructor";
  var PROTOTYPE = "prototype";
  var CONFIGURABLE = "configurable";
  var ENUMERABLE = "enumerable";
  var WRITABLE = "writable";
  var VALUE = "value";
  var isDraft = (value) => !!value && !!value[DRAFT_STATE];
  function isDraftable(value) {
    var _a;
    if (!value) return false;
    return isPlainObject(value) || isArray(value) || !!value[DRAFTABLE] || !!((_a = value[CONSTRUCTOR]) == null ? void 0 : _a[DRAFTABLE]) || isMap(value) || isSet(value);
  }
  var objectCtorString = O[PROTOTYPE][CONSTRUCTOR].toString();
  var cachedCtorStrings = /* @__PURE__ */ new WeakMap();
  function isPlainObject(value) {
    if (!value || !isObjectish(value)) return false;
    const proto = getPrototypeOf(value);
    if (proto === null || proto === O[PROTOTYPE]) return true;
    const Ctor = O.hasOwnProperty.call(proto, CONSTRUCTOR) && proto[CONSTRUCTOR];
    if (Ctor === Object) return true;
    if (!isFunction(Ctor)) return false;
    let ctorString = cachedCtorStrings.get(Ctor);
    if (ctorString === void 0) {
      ctorString = Function.toString.call(Ctor);
      cachedCtorStrings.set(Ctor, ctorString);
    }
    return ctorString === objectCtorString;
  }
  function each(obj, iter, strict = true) {
    if (getArchtype(obj) === 0) {
      const keys = strict ? Reflect.ownKeys(obj) : O.keys(obj);
      keys.forEach((key) => {
        iter(key, obj[key], obj);
      });
    } else {
      obj.forEach((entry, index) => iter(index, entry, obj));
    }
  }
  function getArchtype(thing) {
    const state = thing[DRAFT_STATE];
    return state ? state.type_ : isArray(thing) ? 1 : isMap(thing) ? 2 : isSet(thing) ? 3 : 0;
  }
  var has = (thing, prop, type = getArchtype(thing)) => type === 2 ? thing.has(prop) : O[PROTOTYPE].hasOwnProperty.call(thing, prop);
  var get = (thing, prop, type = getArchtype(thing)) => type === 2 ? thing.get(prop) : thing[prop];
  var set = (thing, propOrOldValue, value, type = getArchtype(thing)) => {
    if (type === 2) thing.set(propOrOldValue, value);
    else if (type === 3) {
      thing.add(value);
    } else thing[propOrOldValue] = value;
  };
  function is(x, y) {
    if (x === y) {
      return x !== 0 || 1 / x === 1 / y;
    } else {
      return x !== x && y !== y;
    }
  }
  var isArray = Array.isArray;
  var isMap = (target) => target instanceof Map;
  var isSet = (target) => target instanceof Set;
  var isObjectish = (target) => typeof target === "object";
  var isFunction = (target) => typeof target === "function";
  var isBoolean$1 = (target) => typeof target === "boolean";
  function isArrayIndex(value) {
    const n = +value;
    return Number.isInteger(n) && String(n) === value;
  }
  var latest = (state) => state.copy_ || state.base_;
  var getFinalValue = (state) => state.modified_ ? state.copy_ : state.base_;
  function shallowCopy(base, strict) {
    if (isMap(base)) {
      return new Map(base);
    }
    if (isSet(base)) {
      return new Set(base);
    }
    if (isArray(base)) return Array[PROTOTYPE].slice.call(base);
    const isPlain = isPlainObject(base);
    if (strict === true || strict === "class_only" && !isPlain) {
      const descriptors = O.getOwnPropertyDescriptors(base);
      delete descriptors[DRAFT_STATE];
      let keys = Reflect.ownKeys(descriptors);
      for (let i = 0; i < keys.length; i++) {
        const key = keys[i];
        const desc = descriptors[key];
        if (desc[WRITABLE] === false) {
          desc[WRITABLE] = true;
          desc[CONFIGURABLE] = true;
        }
        if (desc.get || desc.set) descriptors[key] = {
          [CONFIGURABLE]: true,
          [WRITABLE]: true,
          [ENUMERABLE]: desc[ENUMERABLE],
          [VALUE]: base[key]
        };
      }
      return O.create(getPrototypeOf(base), descriptors);
    } else {
      const proto = getPrototypeOf(base);
      if (proto !== null && isPlain) {
        return {
          ...base
        };
      }
      const obj = O.create(proto);
      return O.assign(obj, base);
    }
  }
  function freeze(obj, deep = false) {
    if (isFrozen(obj) || isDraft(obj) || !isDraftable(obj)) return obj;
    if (getArchtype(obj) > 1) {
      O.defineProperties(obj, {
        set: dontMutateMethodOverride,
        add: dontMutateMethodOverride,
        clear: dontMutateMethodOverride,
        delete: dontMutateMethodOverride
      });
    }
    O.freeze(obj);
    if (deep) each(obj, (_key, value) => {
      freeze(value, true);
    }, false);
    return obj;
  }
  function dontMutateFrozenCollections() {
    die(2);
  }
  var dontMutateMethodOverride = {
    [VALUE]: dontMutateFrozenCollections
  };
  function isFrozen(obj) {
    if (obj === null || !isObjectish(obj)) return true;
    return O.isFrozen(obj);
  }
  var PluginMapSet = "MapSet";
  var PluginPatches = "Patches";
  var PluginArrayMethods = "ArrayMethods";
  var plugins = {};
  function getPlugin(pluginKey) {
    const plugin = plugins[pluginKey];
    if (!plugin) {
      die(0, pluginKey);
    }
    return plugin;
  }
  var isPluginLoaded = (pluginKey) => !!plugins[pluginKey];
  var currentScope;
  var getCurrentScope = () => currentScope;
  var createScope = (parent_, immer_) => ({
    drafts_: [],
    parent_,
    immer_,
    canAutoFreeze_: true,
    unfinalizedDrafts_: 0,
    handledSet_: /* @__PURE__ */ new Set(),
    processedForPatches_: /* @__PURE__ */ new Set(),
    mapSetPlugin_: isPluginLoaded(PluginMapSet) ? getPlugin(PluginMapSet) : void 0,
    arrayMethodsPlugin_: isPluginLoaded(PluginArrayMethods) ? getPlugin(PluginArrayMethods) : void 0
  });
  function usePatchesInScope(scope, patchListener) {
    if (patchListener) {
      scope.patchPlugin_ = getPlugin(PluginPatches);
      scope.patches_ = [];
      scope.inversePatches_ = [];
      scope.patchListener_ = patchListener;
    }
  }
  function revokeScope(scope) {
    leaveScope(scope);
    scope.drafts_.forEach(revokeDraft);
    scope.drafts_ = null;
  }
  function leaveScope(scope) {
    if (scope === currentScope) {
      currentScope = scope.parent_;
    }
  }
  var enterScope = (immer2) => currentScope = createScope(currentScope, immer2);
  function revokeDraft(draft) {
    const state = draft[DRAFT_STATE];
    if (state.type_ === 0 || state.type_ === 1) state.revoke_();
    else state.revoked_ = true;
  }
  function processResult(result, scope) {
    scope.unfinalizedDrafts_ = scope.drafts_.length;
    const baseDraft = scope.drafts_[0];
    const isReplaced = result !== void 0 && result !== baseDraft;
    if (isReplaced) {
      if (baseDraft[DRAFT_STATE].modified_) {
        revokeScope(scope);
        die(4);
      }
      if (isDraftable(result)) {
        result = finalize(scope, result);
      }
      const { patchPlugin_ } = scope;
      if (patchPlugin_) {
        patchPlugin_.generateReplacementPatches_(baseDraft[DRAFT_STATE].base_, result, scope);
      }
    } else {
      result = finalize(scope, baseDraft);
    }
    maybeFreeze(scope, result, true);
    revokeScope(scope);
    if (scope.patches_) {
      scope.patchListener_(scope.patches_, scope.inversePatches_);
    }
    return result !== NOTHING ? result : void 0;
  }
  function finalize(rootScope, value) {
    if (isFrozen(value)) return value;
    const state = value[DRAFT_STATE];
    if (!state) {
      const finalValue = handleValue(value, rootScope.handledSet_, rootScope);
      return finalValue;
    }
    if (!isSameScope(state, rootScope)) {
      return value;
    }
    if (!state.modified_) {
      return state.base_;
    }
    if (!state.finalized_) {
      const { callbacks_ } = state;
      if (callbacks_) {
        while (callbacks_.length > 0) {
          const callback = callbacks_.pop();
          callback(rootScope);
        }
      }
      generatePatchesAndFinalize(state, rootScope);
    }
    return state.copy_;
  }
  function maybeFreeze(scope, value, deep = false) {
    if (!scope.parent_ && scope.immer_.autoFreeze_ && scope.canAutoFreeze_) {
      freeze(value, deep);
    }
  }
  function markStateFinalized(state) {
    state.finalized_ = true;
    state.scope_.unfinalizedDrafts_--;
  }
  var isSameScope = (state, rootScope) => state.scope_ === rootScope;
  var EMPTY_LOCATIONS_RESULT = [];
  function updateDraftInParent(parent, draftValue, finalizedValue, originalKey) {
    const parentCopy = latest(parent);
    const parentType = parent.type_;
    if (originalKey !== void 0) {
      const currentValue = get(parentCopy, originalKey, parentType);
      if (currentValue === draftValue) {
        set(parentCopy, originalKey, finalizedValue, parentType);
        return;
      }
    }
    if (!parent.draftLocations_) {
      const draftLocations = parent.draftLocations_ = /* @__PURE__ */ new Map();
      each(parentCopy, (key, value) => {
        if (isDraft(value)) {
          const keys = draftLocations.get(value) || [];
          keys.push(key);
          draftLocations.set(value, keys);
        }
      });
    }
    const locations = parent.draftLocations_.get(draftValue) ?? EMPTY_LOCATIONS_RESULT;
    for (const location of locations) {
      set(parentCopy, location, finalizedValue, parentType);
    }
  }
  function registerChildFinalizationCallback(parent, child, key) {
    parent.callbacks_.push(function childCleanup(rootScope) {
      var _a;
      const state = child;
      if (!state || !isSameScope(state, rootScope)) {
        return;
      }
      (_a = rootScope.mapSetPlugin_) == null ? void 0 : _a.fixSetContents(state);
      const finalizedValue = getFinalValue(state);
      updateDraftInParent(parent, state.draft_ ?? state, finalizedValue, key);
      generatePatchesAndFinalize(state, rootScope);
    });
  }
  function generatePatchesAndFinalize(state, rootScope) {
    var _a;
    const shouldFinalize = state.modified_ && !state.finalized_ && (state.type_ === 3 || state.type_ === 1 && state.allIndicesReassigned_ || (((_a = state.assigned_) == null ? void 0 : _a.size) ?? 0) > 0);
    if (shouldFinalize) {
      const { patchPlugin_ } = rootScope;
      if (patchPlugin_) {
        const basePath = patchPlugin_.getPath(state);
        if (basePath) {
          patchPlugin_.generatePatches_(state, basePath, rootScope);
        }
      }
      markStateFinalized(state);
    }
  }
  function handleCrossReference(target, key, value) {
    const { scope_ } = target;
    if (isDraft(value)) {
      const state = value[DRAFT_STATE];
      if (isSameScope(state, scope_)) {
        state.callbacks_.push(function crossReferenceCleanup() {
          prepareCopy(target);
          const finalizedValue = getFinalValue(state);
          updateDraftInParent(target, value, finalizedValue, key);
        });
      }
    } else if (isDraftable(value)) {
      target.callbacks_.push(function nestedDraftCleanup() {
        const targetCopy = latest(target);
        if (target.type_ === 3) {
          if (targetCopy.has(value)) {
            handleValue(value, scope_.handledSet_, scope_);
          }
        } else {
          if (get(targetCopy, key, target.type_) === value) {
            if (scope_.drafts_.length > 1 && (target.assigned_.get(key) ?? false) === true && target.copy_) {
              handleValue(get(target.copy_, key, target.type_), scope_.handledSet_, scope_);
            }
          }
        }
      });
    }
  }
  function handleValue(target, handledSet, rootScope) {
    if (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {
      return target;
    }
    if (isDraft(target) || handledSet.has(target) || !isDraftable(target) || isFrozen(target)) {
      return target;
    }
    handledSet.add(target);
    each(target, (key, value) => {
      if (isDraft(value)) {
        const state = value[DRAFT_STATE];
        if (isSameScope(state, rootScope)) {
          const updatedValue = getFinalValue(state);
          set(target, key, updatedValue, target.type_);
          markStateFinalized(state);
        }
      } else if (isDraftable(value)) {
        handleValue(value, handledSet, rootScope);
      }
    });
    return target;
  }
  function createProxyProxy(base, parent) {
    const baseIsArray = isArray(base);
    const state = {
      type_: baseIsArray ? 1 : 0,
      scope_: parent ? parent.scope_ : getCurrentScope(),
      modified_: false,
      finalized_: false,
      assigned_: void 0,
      parent_: parent,
      base_: base,
      draft_: null,
      copy_: null,
      revoke_: null,
      isManual_: false,
      callbacks_: void 0
    };
    let target = state;
    let traps = objectTraps;
    if (baseIsArray) {
      target = [
        state
      ];
      traps = arrayTraps;
    }
    const { revoke, proxy } = Proxy.revocable(target, traps);
    state.draft_ = proxy;
    state.revoke_ = revoke;
    return [
      proxy,
      state
    ];
  }
  var objectTraps = {
    get(state, prop) {
      if (prop === DRAFT_STATE) return state;
      let arrayPlugin = state.scope_.arrayMethodsPlugin_;
      const isArrayWithStringProp = state.type_ === 1 && typeof prop === "string";
      if (isArrayWithStringProp) {
        if (arrayPlugin == null ? void 0 : arrayPlugin.isArrayOperationMethod(prop)) {
          return arrayPlugin.createMethodInterceptor(state, prop);
        }
      }
      const source = latest(state);
      if (!has(source, prop, state.type_)) {
        return readPropFromProto(state, source, prop);
      }
      const value = source[prop];
      if (state.finalized_ || !isDraftable(value)) {
        return value;
      }
      if (isArrayWithStringProp && state.operationMethod && (arrayPlugin == null ? void 0 : arrayPlugin.isMutatingArrayMethod(state.operationMethod)) && isArrayIndex(prop)) {
        return value;
      }
      if (value === peek(state.base_, prop)) {
        prepareCopy(state);
        const childKey = state.type_ === 1 ? +prop : prop;
        const childDraft = createProxy(state.scope_, value, state, childKey);
        return state.copy_[childKey] = childDraft;
      }
      return value;
    },
    has(state, prop) {
      return prop in latest(state);
    },
    ownKeys(state) {
      return Reflect.ownKeys(latest(state));
    },
    set(state, prop, value) {
      const desc = getDescriptorFromProto(latest(state), prop);
      if (desc == null ? void 0 : desc.set) {
        desc.set.call(state.draft_, value);
        return true;
      }
      if (!state.modified_) {
        const current2 = peek(latest(state), prop);
        const currentState = current2 == null ? void 0 : current2[DRAFT_STATE];
        if (currentState && currentState.base_ === value) {
          state.copy_[prop] = value;
          state.assigned_.set(prop, false);
          return true;
        }
        if (is(value, current2) && (value !== void 0 || has(state.base_, prop, state.type_))) return true;
        prepareCopy(state);
        markChanged(state);
      }
      if (state.copy_[prop] === value && (value !== void 0 || prop in state.copy_) || Number.isNaN(value) && Number.isNaN(state.copy_[prop])) return true;
      state.copy_[prop] = value;
      state.assigned_.set(prop, true);
      handleCrossReference(state, prop, value);
      return true;
    },
    deleteProperty(state, prop) {
      prepareCopy(state);
      if (peek(state.base_, prop) !== void 0 || prop in state.base_) {
        state.assigned_.set(prop, false);
        markChanged(state);
      } else {
        state.assigned_.delete(prop);
      }
      if (state.copy_) {
        delete state.copy_[prop];
      }
      return true;
    },
    getOwnPropertyDescriptor(state, prop) {
      const owner = latest(state);
      const desc = Reflect.getOwnPropertyDescriptor(owner, prop);
      if (!desc) return desc;
      return {
        [WRITABLE]: true,
        [CONFIGURABLE]: state.type_ !== 1 || prop !== "length",
        [ENUMERABLE]: desc[ENUMERABLE],
        [VALUE]: owner[prop]
      };
    },
    defineProperty() {
      die(11);
    },
    getPrototypeOf(state) {
      return getPrototypeOf(state.base_);
    },
    setPrototypeOf() {
      die(12);
    }
  };
  var arrayTraps = {};
  for (let key in objectTraps) {
    let fn = objectTraps[key];
    arrayTraps[key] = function() {
      const args = arguments;
      args[0] = args[0][0];
      return fn.apply(this, args);
    };
  }
  arrayTraps.deleteProperty = function(state, prop) {
    return arrayTraps.set.call(this, state, prop, void 0);
  };
  arrayTraps.set = function(state, prop, value) {
    return objectTraps.set.call(this, state[0], prop, value, state[0]);
  };
  function peek(draft, prop) {
    const state = draft[DRAFT_STATE];
    const source = state ? latest(state) : draft;
    return source[prop];
  }
  function readPropFromProto(state, source, prop) {
    var _a;
    const desc = getDescriptorFromProto(source, prop);
    return desc ? VALUE in desc ? desc[VALUE] : (_a = desc.get) == null ? void 0 : _a.call(state.draft_) : void 0;
  }
  function getDescriptorFromProto(source, prop) {
    if (!(prop in source)) return void 0;
    let proto = getPrototypeOf(source);
    while (proto) {
      const desc = Object.getOwnPropertyDescriptor(proto, prop);
      if (desc) return desc;
      proto = getPrototypeOf(proto);
    }
    return void 0;
  }
  function markChanged(state) {
    if (!state.modified_) {
      state.modified_ = true;
      if (state.parent_) {
        markChanged(state.parent_);
      }
    }
  }
  function prepareCopy(state) {
    if (!state.copy_) {
      state.assigned_ = /* @__PURE__ */ new Map();
      state.copy_ = shallowCopy(state.base_, state.scope_.immer_.useStrictShallowCopy_);
    }
  }
  var Immer2 = class {
    constructor(config) {
      this.autoFreeze_ = true;
      this.useStrictShallowCopy_ = false;
      this.useStrictIteration_ = false;
      this.produce = (base, recipe, patchListener) => {
        if (isFunction(base) && !isFunction(recipe)) {
          const defaultBase = recipe;
          recipe = base;
          const self = this;
          return function curriedProduce(base2 = defaultBase, ...args) {
            return self.produce(base2, (draft) => recipe.call(this, draft, ...args));
          };
        }
        if (!isFunction(recipe)) die(6);
        if (patchListener !== void 0 && !isFunction(patchListener)) die(7);
        let result;
        if (isDraftable(base)) {
          const scope = enterScope(this);
          const proxy = createProxy(scope, base, void 0);
          let hasError = true;
          try {
            result = recipe(proxy);
            hasError = false;
          } finally {
            if (hasError) revokeScope(scope);
            else leaveScope(scope);
          }
          usePatchesInScope(scope, patchListener);
          return processResult(result, scope);
        } else if (!base || !isObjectish(base)) {
          result = recipe(base);
          if (result === void 0) result = base;
          if (result === NOTHING) result = void 0;
          if (this.autoFreeze_) freeze(result, true);
          if (patchListener) {
            const p = [];
            const ip = [];
            getPlugin(PluginPatches).generateReplacementPatches_(base, result, {
              patches_: p,
              inversePatches_: ip
            });
            patchListener(p, ip);
          }
          return result;
        } else die(1, base);
      };
      this.produceWithPatches = (base, recipe) => {
        if (isFunction(base)) {
          return (state, ...args) => this.produceWithPatches(state, (draft) => base(draft, ...args));
        }
        let patches, inversePatches;
        const result = this.produce(base, recipe, (p, ip) => {
          patches = p;
          inversePatches = ip;
        });
        return [
          result,
          patches,
          inversePatches
        ];
      };
      if (isBoolean$1(config == null ? void 0 : config.autoFreeze)) this.setAutoFreeze(config.autoFreeze);
      if (isBoolean$1(config == null ? void 0 : config.useStrictShallowCopy)) this.setUseStrictShallowCopy(config.useStrictShallowCopy);
      if (isBoolean$1(config == null ? void 0 : config.useStrictIteration)) this.setUseStrictIteration(config.useStrictIteration);
    }
    createDraft(base) {
      if (!isDraftable(base)) die(8);
      if (isDraft(base)) base = current(base);
      const scope = enterScope(this);
      const proxy = createProxy(scope, base, void 0);
      proxy[DRAFT_STATE].isManual_ = true;
      leaveScope(scope);
      return proxy;
    }
    finishDraft(draft, patchListener) {
      const state = draft && draft[DRAFT_STATE];
      if (!state || !state.isManual_) die(9);
      const { scope_: scope } = state;
      usePatchesInScope(scope, patchListener);
      return processResult(void 0, scope);
    }
    setAutoFreeze(value) {
      this.autoFreeze_ = value;
    }
    setUseStrictShallowCopy(value) {
      this.useStrictShallowCopy_ = value;
    }
    setUseStrictIteration(value) {
      this.useStrictIteration_ = value;
    }
    shouldUseStrictIteration() {
      return this.useStrictIteration_;
    }
    applyPatches(base, patches) {
      let i;
      for (i = patches.length - 1; i >= 0; i--) {
        const patch = patches[i];
        if (patch.path.length === 0 && patch.op === "replace") {
          base = patch.value;
          break;
        }
      }
      if (i > -1) {
        patches = patches.slice(i + 1);
      }
      const applyPatchesImpl = getPlugin(PluginPatches).applyPatches_;
      if (isDraft(base)) {
        return applyPatchesImpl(base, patches);
      }
      return this.produce(base, (draft) => applyPatchesImpl(draft, patches));
    }
  };
  function createProxy(rootScope, value, parent, key) {
    const [draft, state] = isMap(value) ? getPlugin(PluginMapSet).proxyMap_(value, parent) : isSet(value) ? getPlugin(PluginMapSet).proxySet_(value, parent) : createProxyProxy(value, parent);
    const scope = (parent == null ? void 0 : parent.scope_) ?? getCurrentScope();
    scope.drafts_.push(draft);
    state.callbacks_ = (parent == null ? void 0 : parent.callbacks_) ?? [];
    state.key_ = key;
    if (parent && key !== void 0) {
      registerChildFinalizationCallback(parent, state, key);
    } else {
      state.callbacks_.push(function rootDraftCleanup(rootScope2) {
        var _a;
        (_a = rootScope2.mapSetPlugin_) == null ? void 0 : _a.fixSetContents(state);
        const { patchPlugin_ } = rootScope2;
        if (state.modified_ && patchPlugin_) {
          patchPlugin_.generatePatches_(state, [], rootScope2);
        }
      });
    }
    return draft;
  }
  function current(value) {
    if (!isDraft(value)) die(10, value);
    return currentImpl(value);
  }
  function currentImpl(value) {
    if (!isDraftable(value) || isFrozen(value)) return value;
    const state = value[DRAFT_STATE];
    let copy;
    let strict = true;
    if (state) {
      if (!state.modified_) return state.base_;
      state.finalized_ = true;
      copy = shallowCopy(value, state.scope_.immer_.useStrictShallowCopy_);
      strict = state.scope_.immer_.shouldUseStrictIteration();
    } else {
      copy = shallowCopy(value, true);
    }
    each(copy, (key, childValue) => {
      set(copy, key, currentImpl(childValue));
    }, strict);
    if (state) {
      state.finalized_ = false;
    }
    return copy;
  }
  var immer = new Immer2();
  var produce = immer.produce;
  function assertIsFunction(func, errorMessage = `expected a function, instead received ${typeof func}`) {
    if (typeof func !== "function") {
      throw new TypeError(errorMessage);
    }
  }
  function assertIsObject(object, errorMessage = `expected an object, instead received ${typeof object}`) {
    if (typeof object !== "object") {
      throw new TypeError(errorMessage);
    }
  }
  function assertIsArrayOfFunctions(array, errorMessage = `expected all items to be functions, instead received the following types: `) {
    if (!array.every((item) => typeof item === "function")) {
      const itemTypes = array.map((item) => typeof item === "function" ? `function ${item.name || "unnamed"}()` : typeof item).join(", ");
      throw new TypeError(`${errorMessage}[${itemTypes}]`);
    }
  }
  var ensureIsArray = (item) => {
    return Array.isArray(item) ? item : [
      item
    ];
  };
  function getDependencies(createSelectorArgs) {
    const dependencies = Array.isArray(createSelectorArgs[0]) ? createSelectorArgs[0] : createSelectorArgs;
    assertIsArrayOfFunctions(dependencies, `createSelector expects all input-selectors to be functions, but received the following types: `);
    return dependencies;
  }
  function collectInputSelectorResults(dependencies, inputSelectorArgs) {
    const inputSelectorResults = [];
    const { length } = dependencies;
    for (let i = 0; i < length; i++) {
      inputSelectorResults.push(dependencies[i].apply(null, inputSelectorArgs));
    }
    return inputSelectorResults;
  }
  var StrongRef = class {
    constructor(value) {
      this.value = value;
    }
    deref() {
      return this.value;
    }
  };
  var Ref = typeof WeakRef !== "undefined" ? WeakRef : StrongRef;
  var UNTERMINATED = 0;
  var TERMINATED = 1;
  function createCacheNode() {
    return {
      s: UNTERMINATED,
      v: void 0,
      o: null,
      p: null
    };
  }
  function weakMapMemoize(func, options = {}) {
    let fnNode = createCacheNode();
    const { resultEqualityCheck } = options;
    let lastResult;
    let resultsCount = 0;
    function memoized() {
      var _a;
      let cacheNode = fnNode;
      const { length } = arguments;
      for (let i = 0, l = length; i < l; i++) {
        const arg = arguments[i];
        if (typeof arg === "function" || typeof arg === "object" && arg !== null) {
          let objectCache = cacheNode.o;
          if (objectCache === null) {
            cacheNode.o = objectCache = /* @__PURE__ */ new WeakMap();
          }
          const objectNode = objectCache.get(arg);
          if (objectNode === void 0) {
            cacheNode = createCacheNode();
            objectCache.set(arg, cacheNode);
          } else {
            cacheNode = objectNode;
          }
        } else {
          let primitiveCache = cacheNode.p;
          if (primitiveCache === null) {
            cacheNode.p = primitiveCache = /* @__PURE__ */ new Map();
          }
          const primitiveNode = primitiveCache.get(arg);
          if (primitiveNode === void 0) {
            cacheNode = createCacheNode();
            primitiveCache.set(arg, cacheNode);
          } else {
            cacheNode = primitiveNode;
          }
        }
      }
      const terminatedNode = cacheNode;
      let result;
      if (cacheNode.s === TERMINATED) {
        result = cacheNode.v;
      } else {
        result = func.apply(null, arguments);
        resultsCount++;
        if (resultEqualityCheck) {
          const lastResultValue = ((_a = lastResult == null ? void 0 : lastResult.deref) == null ? void 0 : _a.call(lastResult)) ?? lastResult;
          if (lastResultValue != null && resultEqualityCheck(lastResultValue, result)) {
            result = lastResultValue;
            resultsCount !== 0 && resultsCount--;
          }
          const needsWeakRef = typeof result === "object" && result !== null || typeof result === "function";
          lastResult = needsWeakRef ? new Ref(result) : result;
        }
      }
      terminatedNode.s = TERMINATED;
      terminatedNode.v = result;
      return result;
    }
    memoized.clearCache = () => {
      fnNode = createCacheNode();
      memoized.resetResultsCount();
    };
    memoized.resultsCount = () => resultsCount;
    memoized.resetResultsCount = () => {
      resultsCount = 0;
    };
    return memoized;
  }
  function createSelectorCreator(memoizeOrOptions, ...memoizeOptionsFromArgs) {
    const createSelectorCreatorOptions = typeof memoizeOrOptions === "function" ? {
      memoize: memoizeOrOptions,
      memoizeOptions: memoizeOptionsFromArgs
    } : memoizeOrOptions;
    const createSelector2 = (...createSelectorArgs) => {
      let recomputations = 0;
      let dependencyRecomputations = 0;
      let lastResult;
      let directlyPassedOptions = {};
      let resultFunc = createSelectorArgs.pop();
      if (typeof resultFunc === "object") {
        directlyPassedOptions = resultFunc;
        resultFunc = createSelectorArgs.pop();
      }
      assertIsFunction(resultFunc, `createSelector expects an output function after the inputs, but received: [${typeof resultFunc}]`);
      const combinedOptions = {
        ...createSelectorCreatorOptions,
        ...directlyPassedOptions
      };
      const { memoize, memoizeOptions = [], argsMemoize = weakMapMemoize, argsMemoizeOptions = [] } = combinedOptions;
      const finalMemoizeOptions = ensureIsArray(memoizeOptions);
      const finalArgsMemoizeOptions = ensureIsArray(argsMemoizeOptions);
      const dependencies = getDependencies(createSelectorArgs);
      const memoizedResultFunc = memoize(function recomputationWrapper() {
        recomputations++;
        return resultFunc.apply(null, arguments);
      }, ...finalMemoizeOptions);
      const selector = argsMemoize(function dependenciesChecker() {
        dependencyRecomputations++;
        const inputSelectorResults = collectInputSelectorResults(dependencies, arguments);
        lastResult = memoizedResultFunc.apply(null, inputSelectorResults);
        return lastResult;
      }, ...finalArgsMemoizeOptions);
      return Object.assign(selector, {
        resultFunc,
        memoizedResultFunc,
        dependencies,
        dependencyRecomputations: () => dependencyRecomputations,
        resetDependencyRecomputations: () => {
          dependencyRecomputations = 0;
        },
        lastResult: () => lastResult,
        recomputations: () => recomputations,
        resetRecomputations: () => {
          recomputations = 0;
        },
        memoize,
        argsMemoize
      });
    };
    Object.assign(createSelector2, {
      withTypes: () => createSelector2
    });
    return createSelector2;
  }
  var createSelector = createSelectorCreator(weakMapMemoize);
  var createStructuredSelector = Object.assign((inputSelectorsObject, selectorCreator = createSelector) => {
    assertIsObject(inputSelectorsObject, `createStructuredSelector expects first argument to be an object where each property is a selector, instead received a ${typeof inputSelectorsObject}`);
    const inputSelectorKeys = Object.keys(inputSelectorsObject);
    const dependencies = inputSelectorKeys.map((key) => inputSelectorsObject[key]);
    const structuredSelector = selectorCreator(dependencies, (...inputSelectorResults) => {
      return inputSelectorResults.reduce((composition, value, index) => {
        composition[inputSelectorKeys[index]] = value;
        return composition;
      }, {});
    });
    return structuredSelector;
  }, {
    withTypes: () => createStructuredSelector
  });
  function createThunkMiddleware(extraArgument) {
    const middleware = ({ dispatch, getState }) => (next) => (action) => {
      if (typeof action === "function") {
        return action(dispatch, getState, extraArgument);
      }
      return next(action);
    };
    return middleware;
  }
  var thunk = createThunkMiddleware();
  var withExtraArgument = createThunkMiddleware;
  var composeWithDevTools = typeof window !== "undefined" && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : function() {
    if (arguments.length === 0) return void 0;
    if (typeof arguments[0] === "object") return compose;
    return compose.apply(null, arguments);
  };
  function createAction(type, prepareAction) {
    function actionCreator(...args) {
      return {
        type,
        payload: args[0]
      };
    }
    actionCreator.toString = () => `${type}`;
    actionCreator.type = type;
    actionCreator.match = (action) => isAction(action) && action.type === type;
    return actionCreator;
  }
  var Tuple = class _Tuple extends Array {
    constructor(...items) {
      super(...items);
      Object.setPrototypeOf(this, _Tuple.prototype);
    }
    static get [Symbol.species]() {
      return _Tuple;
    }
    concat(...arr) {
      return super.concat.apply(this, arr);
    }
    prepend(...arr) {
      if (arr.length === 1 && Array.isArray(arr[0])) {
        return new _Tuple(...arr[0].concat(this));
      }
      return new _Tuple(...arr.concat(this));
    }
  };
  function freezeDraftable(val) {
    return isDraftable(val) ? produce(val, () => {
    }) : val;
  }
  function isBoolean(x) {
    return typeof x === "boolean";
  }
  var buildGetDefaultMiddleware = () => function getDefaultMiddleware(options) {
    const { thunk: thunk$1 = true, immutableCheck = true, serializableCheck = true, actionCreatorCheck = true } = options ?? {};
    let middlewareArray = new Tuple();
    if (thunk$1) {
      if (isBoolean(thunk$1)) {
        middlewareArray.push(thunk);
      } else {
        middlewareArray.push(withExtraArgument(thunk$1.extraArgument));
      }
    }
    return middlewareArray;
  };
  var SHOULD_AUTOBATCH = "RTK_autoBatch";
  var createQueueWithTimer = (timeout) => {
    return (notify) => {
      setTimeout(notify, timeout);
    };
  };
  var autoBatchEnhancer = (options = {
    type: "raf"
  }) => (next) => (...args) => {
    const store2 = next(...args);
    let notifying = true;
    let shouldNotifyAtEndOfTick = false;
    let notificationQueued = false;
    const listeners = /* @__PURE__ */ new Set();
    const queueCallback = options.type === "tick" ? queueMicrotask : options.type === "raf" ? typeof window !== "undefined" && window.requestAnimationFrame ? window.requestAnimationFrame : createQueueWithTimer(10) : options.type === "callback" ? options.queueNotification : createQueueWithTimer(options.timeout);
    const notifyListeners = () => {
      notificationQueued = false;
      if (shouldNotifyAtEndOfTick) {
        shouldNotifyAtEndOfTick = false;
        listeners.forEach((l) => l());
      }
    };
    return Object.assign({}, store2, {
      subscribe(listener2) {
        const wrappedListener = () => notifying && listener2();
        const unsubscribe = store2.subscribe(wrappedListener);
        listeners.add(listener2);
        return () => {
          unsubscribe();
          listeners.delete(listener2);
        };
      },
      dispatch(action) {
        var _a;
        try {
          notifying = !((_a = action == null ? void 0 : action.meta) == null ? void 0 : _a[SHOULD_AUTOBATCH]);
          shouldNotifyAtEndOfTick = !notifying;
          if (shouldNotifyAtEndOfTick) {
            if (!notificationQueued) {
              notificationQueued = true;
              queueCallback(notifyListeners);
            }
          }
          return store2.dispatch(action);
        } finally {
          notifying = true;
        }
      }
    });
  };
  var buildGetDefaultEnhancers = (middlewareEnhancer) => function getDefaultEnhancers(options) {
    const { autoBatch = true } = options ?? {};
    let enhancerArray = new Tuple(middlewareEnhancer);
    if (autoBatch) {
      enhancerArray.push(autoBatchEnhancer(typeof autoBatch === "object" ? autoBatch : void 0));
    }
    return enhancerArray;
  };
  function configureStore(options) {
    const getDefaultMiddleware = buildGetDefaultMiddleware();
    const { reducer: reducer2 = void 0, middleware, devTools = true, preloadedState = void 0, enhancers = void 0 } = options || {};
    let rootReducer;
    if (typeof reducer2 === "function") {
      rootReducer = reducer2;
    } else if (isPlainObject$1(reducer2)) {
      rootReducer = combineReducers(reducer2);
    } else {
      throw new Error(formatProdErrorMessage(1));
    }
    let finalMiddleware;
    if (typeof middleware === "function") {
      finalMiddleware = middleware(getDefaultMiddleware);
    } else {
      finalMiddleware = getDefaultMiddleware();
    }
    let finalCompose = compose;
    if (devTools) {
      finalCompose = composeWithDevTools({
        trace: false,
        ...typeof devTools === "object" && devTools
      });
    }
    const middlewareEnhancer = applyMiddleware(...finalMiddleware);
    const getDefaultEnhancers = buildGetDefaultEnhancers(middlewareEnhancer);
    let storeEnhancers = typeof enhancers === "function" ? enhancers(getDefaultEnhancers) : getDefaultEnhancers();
    const composedEnhancer = finalCompose(...storeEnhancers);
    return createStore(rootReducer, preloadedState, composedEnhancer);
  }
  function executeReducerBuilderCallback(builderCallback) {
    const actionsMap = {};
    const actionMatchers = [];
    let defaultCaseReducer;
    const builder = {
      addCase(typeOrActionCreator, reducer2) {
        const type = typeof typeOrActionCreator === "string" ? typeOrActionCreator : typeOrActionCreator.type;
        if (!type) {
          throw new Error(formatProdErrorMessage(28));
        }
        if (type in actionsMap) {
          throw new Error(formatProdErrorMessage(29));
        }
        actionsMap[type] = reducer2;
        return builder;
      },
      addAsyncThunk(asyncThunk, reducers) {
        if (reducers.pending) actionsMap[asyncThunk.pending.type] = reducers.pending;
        if (reducers.rejected) actionsMap[asyncThunk.rejected.type] = reducers.rejected;
        if (reducers.fulfilled) actionsMap[asyncThunk.fulfilled.type] = reducers.fulfilled;
        if (reducers.settled) actionMatchers.push({
          matcher: asyncThunk.settled,
          reducer: reducers.settled
        });
        return builder;
      },
      addMatcher(matcher, reducer2) {
        actionMatchers.push({
          matcher,
          reducer: reducer2
        });
        return builder;
      },
      addDefaultCase(reducer2) {
        defaultCaseReducer = reducer2;
        return builder;
      }
    };
    builderCallback(builder);
    return [
      actionsMap,
      actionMatchers,
      defaultCaseReducer
    ];
  }
  function isStateFunction(x) {
    return typeof x === "function";
  }
  function createReducer(initialState2, mapOrBuilderCallback) {
    let [actionsMap, finalActionMatchers, finalDefaultCaseReducer] = executeReducerBuilderCallback(mapOrBuilderCallback);
    let getInitialState;
    if (isStateFunction(initialState2)) {
      getInitialState = () => freezeDraftable(initialState2());
    } else {
      const frozenInitialState = freezeDraftable(initialState2);
      getInitialState = () => frozenInitialState;
    }
    function reducer2(state = getInitialState(), action) {
      let caseReducers = [
        actionsMap[action.type],
        ...finalActionMatchers.filter(({ matcher }) => matcher(action)).map(({ reducer: reducer22 }) => reducer22)
      ];
      if (caseReducers.filter((cr) => !!cr).length === 0) {
        caseReducers = [
          finalDefaultCaseReducer
        ];
      }
      return caseReducers.reduce((previousState, caseReducer) => {
        if (caseReducer) {
          if (isDraft(previousState)) {
            const draft = previousState;
            const result = caseReducer(draft, action);
            if (result === void 0) {
              return previousState;
            }
            return result;
          } else if (!isDraftable(previousState)) {
            const result = caseReducer(previousState, action);
            if (result === void 0) {
              if (previousState === null) {
                return previousState;
              }
              throw Error("A case reducer on a non-draftable value must not return undefined");
            }
            return result;
          } else {
            return produce(previousState, (draft) => {
              return caseReducer(draft, action);
            });
          }
        }
        return previousState;
      }, state);
    }
    reducer2.getInitialState = getInitialState;
    return reducer2;
  }
  function formatProdErrorMessage(code) {
    return `Minified Redux Toolkit error #${code}; visit https://redux-toolkit.js.org/Errors?code=${code} for the full message or use the non-minified dev environment for full errors. `;
  }
  const FAKE_ID = "fakeId";
  updateProject = createAction("project/update");
  const updateView = createAction("view/update");
  updateWidget = createAction("widget/update");
  const updateGroupWidget = createAction("group/update");
  updateActiveUser = createAction("activeUser/update");
  recalculateFields = createAction("attributes/recalculate");
  const initialState = {
    visProject: {},
    recalculateFields: false,
    activeUser: ""
  };
  const reducer = createReducer(initialState, (builder) => {
    builder.addCase(updateProject, (state, action) => {
      state.visProject = action.payload;
    }).addCase(updateView, (state, action) => {
      const { viewId, data } = action.payload;
      state.visProject[viewId] = data;
    }).addCase(updateWidget, (state, action) => {
      const { viewId, widgetId, data } = action.payload;
      if (widgetId === FAKE_ID) {
        return;
      }
      if (!(viewId in state.visProject)) {
        console.error(`Cannot update widget "${widgetId}". The view "${viewId}" does not exist in the project.`);
        return;
      }
      state.visProject[viewId].widgets[widgetId] = data;
    }).addCase(updateGroupWidget, (state, action) => {
      const { viewId, widgetId, data } = action.payload;
      if (widgetId === FAKE_ID) {
        return;
      }
      if (!(viewId in state.visProject)) {
        console.error(`Cannot update group widget "${widgetId}". The view "${viewId}" does not exist in the project.`);
        return;
      }
      state.visProject[viewId].widgets[widgetId] = data;
    }).addCase(updateActiveUser, (state, action) => {
      state.activeUser = action.payload;
    }).addCase(recalculateFields, (state, action) => {
      state.recalculateFields = action.payload;
    });
  });
  const selectProject = (state) => state.visProject;
  selectView = createSelector([
    selectProject,
    (_state, viewName) => viewName
  ], (project, view) => project[view]);
  selectWidget = createSelector([
    selectView,
    (_state, _viewName, wid) => wid
  ], (view, wid) => view.widgets[wid]);
  store = configureStore({
    reducer
  });
  NOTHING_SELECTED = "nothing_selected";
  calculateOverflow = function(style) {
    if (!style.overflowX && !style.overflowY) {
      style.overflow = "visible";
    } else if (style.overflow) {
      delete style.overflow;
    }
  };
  isVarFinite = function(numberOrString) {
    return window.isFinite(numberOrString);
  };
  isGroup = function(widget) {
    return widget.tpl === "_tplGroup";
  };
  deepClone = function(object) {
    return JSON.parse(JSON.stringify(object));
  };
  getNewWidgetIdNumber = function(isWidgetGroup, project, offset = 0) {
    const widgets = [];
    project = project || store.getState().visProject;
    Object.keys(project).forEach((view) => project[view].widgets && Object.keys(project[view].widgets).forEach((widget) => widgets.push(widget)));
    let newKey = 1;
    widgets.forEach((name) => {
      const matches = isWidgetGroup ? name.match(/^g([0-9]+)$/) : name.match(/^w([0-9]+)$/);
      if (matches) {
        const num = parseInt(matches[1], 10);
        if (num >= newKey) {
          newKey = num + 1;
        }
      }
    });
    return newKey + offset;
  };
  getNewWidgetId = function(project, offset = 0) {
    const newKey = getNewWidgetIdNumber(false, project, offset);
    return `w${newKey.toString().padStart(6, "0")}`;
  };
  getNewGroupId = function(project, offset = 0) {
    const newKey = getNewWidgetIdNumber(true, project, offset);
    return `g${newKey.toString().padStart(6, "0")}`;
  };
  pasteSingleWidget = function(options) {
    const { widgets, offset, project, widget, selectedGroup } = options;
    const newKey = getNewWidgetId(project, offset);
    if (selectedGroup && isGroup(widgets[selectedGroup])) {
      widget.grouped = true;
      widget.groupid = selectedGroup;
      widgets[selectedGroup].data.members.push(newKey);
    }
    widgets[newKey] = widget;
    return newKey;
  };
  pasteGroup = function(options) {
    const { widgets, group, groupMembers, offset, project } = options;
    const newGroupId = getNewGroupId(project, offset ?? 0);
    for (let i = 0; i < group.data.members.length; i++) {
      const wid = group.data.members[i];
      const newMember = deepClone(groupMembers[wid]);
      const newMemberId = getNewWidgetId(project, i);
      newMember.groupid = newGroupId;
      group.data.members[i] = newMemberId;
      widgets[newMemberId] = newMember;
    }
    widgets[newGroupId] = group;
    return newGroupId;
  };
  unsyncMultipleWidgets = function(project) {
    project = deepClone(project || store.getState().visProject);
    for (const [viewName, view] of Object.entries(project)) {
      if (viewName === "___settings") {
        continue;
      }
      for (const widgetId of Object.keys(view.widgets)) {
        if (widgetId.includes("_")) {
          delete view.widgets[widgetId];
        }
      }
    }
    return project;
  };
  DEFAULT_PERMISSIONS = {
    read: true,
    write: true
  };
  hasProjectAccess = function(options) {
    var _a, _b;
    const { project, user, editMode } = options;
    const permissions = ((_b = (_a = project == null ? void 0 : project.___settings) == null ? void 0 : _a.permissions) == null ? void 0 : _b[user]) ?? DEFAULT_PERMISSIONS;
    if (editMode && (permissions == null ? void 0 : permissions.write)) {
      return true;
    }
    return !editMode && permissions.read;
  };
  hasViewAccess = function(options) {
    var _a, _b, _c;
    const { project, user, editMode, view } = options;
    const permissions = ((_c = (_b = (_a = project[view]) == null ? void 0 : _a.settings) == null ? void 0 : _b.permissions) == null ? void 0 : _c[user]) ?? DEFAULT_PERMISSIONS;
    if (editMode && permissions.write) {
      return true;
    }
    return !editMode && permissions.read;
  };
  hasWidgetAccess = function(options) {
    var _a, _b, _c;
    const { project, user, editMode, view, wid } = options;
    const permissions = ((_c = (_b = (_a = project[view]) == null ? void 0 : _a.widgets[wid]) == null ? void 0 : _b.permissions) == null ? void 0 : _c[user]) ?? DEFAULT_PERMISSIONS;
    if (editMode && permissions.write) {
      return true;
    }
    return !editMode && permissions.read;
  };
  replaceGroupAttr = function(inputStr, groupAttrList) {
    let newString = inputStr;
    let match = false;
    let ms = inputStr.match(/(groupAttr\d+)+?/g);
    if (ms) {
      match = true;
      ms.forEach((m) => {
        const val = groupAttrList[m];
        if (val === null || val === void 0) {
          newString = newString.replace(/groupAttr(\d+)/, "");
        } else {
          newString = newString.replace(/groupAttr(\d+)/, groupAttrList[m]);
        }
      });
    }
    ms = inputStr.match(/%([-_a-zA-Z\d]+)+?%/g);
    if (ms) {
      match = true;
      ms.forEach((m) => {
        const attr = m.substring(1, m.length - 1);
        const val = groupAttrList[attr];
        if (val === null || val === void 0) {
          newString = newString.replace(m, "");
        } else {
          newString = newString.replace(m, val);
        }
      });
    }
    return {
      doesMatch: match,
      newString
    };
  };
  function getWidgetGroup(views, view, widget) {
    var _a;
    const widgets = views[view].widgets;
    const groupId = (_a = widgets[widget]) == null ? void 0 : _a.groupid;
    if (groupId && widgets[groupId]) {
      return views[view].widgets[widget].groupid;
    }
    const widgetKeys = Object.keys(widgets);
    return widgetKeys.find((w) => {
      var _a2, _b;
      return (_b = (_a2 = widgets[w].data) == null ? void 0 : _a2.members) == null ? void 0 : _b.includes(widget);
    });
  }
  const LOCAL_STATE_PREFIX = "local_";
  isLocalStateId = function(id) {
    return id.startsWith(LOCAL_STATE_PREFIX);
  };
  function isIdBinding(assignment) {
    return !!assignment.match(/^[\w_]+:\s?[-._/ :!#$%&()+=@^{}|~\p{Ll}\p{Lu}\p{Nd}]+$/u);
  }
  extractBinding = function(format) {
    var _a;
    const oid = format.match(/{(.+?)}/g);
    let result = null;
    if (oid) {
      if (oid.length > 50) {
        console.warn(`Too many bindings in one widget: ${oid.length}[max = 50]`);
      }
      for (let p = 0; p < oid.length && p < 50; p++) {
        const _oid = oid[p].substring(1, oid[p].length - 1);
        if (_oid[0] === "{") {
          continue;
        }
        if (_oid && _oid[0] === '"') {
          continue;
        }
        const parts = _oid.split(";");
        result = result || [];
        let systemOid = parts[0].trim();
        let visOid = systemOid;
        let test1 = visOid.substring(visOid.length - 4).trim();
        let test2 = visOid.substring(visOid.length - 3).trim();
        if (visOid && test1 !== ".val" && test2 !== ".ts" && test2 !== ".lc" && test1 !== ".ack") {
          visOid += ".val";
        }
        const isSeconds = test2 === ".ts" || test2 === ".lc";
        test1 = systemOid.substring(systemOid.length - 4);
        test2 = systemOid.substring(systemOid.length - 3);
        if (test1 === ".val" || test1 === ".ack") {
          systemOid = systemOid.substring(0, systemOid.length - 4);
        } else if (test2 === ".lc" || test2 === ".ts") {
          systemOid = systemOid.substring(0, systemOid.length - 3);
        }
        let operations = null;
        const isEval = visOid.match(/^[\w_]+:\s?[-._/ :!#$%&()+=@^{}|~\p{Ll}\p{Lu}\p{Nd}]+$/u) || !visOid.length && parts.length > 0;
        if (isEval) {
          const xx = visOid.split(":", 2);
          const yy = systemOid.split(":", 2);
          visOid = xx[1].trim();
          systemOid = yy[1].trim();
          operations = [];
          operations.push({
            op: "eval",
            arg: [
              {
                name: xx[0],
                visOid,
                systemOid
              }
            ]
          });
          for (let u = 1; u < parts.length; u++) {
            const trimmed = parts[u].trim();
            if (isIdBinding(trimmed)) {
              const argParts = trimmed.split(":", 2);
              let _visOid = argParts[1].trim();
              let _systemOid = _visOid;
              test1 = _visOid.substring(_visOid.length - 4);
              test2 = _visOid.substring(_visOid.length - 3);
              if (test1 !== ".val" && test2 !== ".ts" && test2 !== ".lc" && test1 !== ".ack") {
                _visOid += ".val";
              }
              test1 = _systemOid.substring(_systemOid.length - 4);
              if (test1 === ".val" || test1 === ".ack") {
                _systemOid = _systemOid.substring(0, _systemOid.length - 4);
              } else {
                test2 = _systemOid.substring(_systemOid.length - 3);
                if (test2 === ".lc" || test2 === ".ts") {
                  _systemOid = _systemOid.substring(0, _systemOid.length - 3);
                }
              }
              (_a = operations[0].arg) == null ? void 0 : _a.push({
                name: argParts[0].trim(),
                visOid: _visOid,
                systemOid: _systemOid
              });
            } else {
              parts[u] = parts[u].replace(/::/g, ":");
              if (operations[0].formula) {
                const n = deepClone(operations[0]);
                n.formula = parts[u];
                operations.push(n);
              } else {
                operations[0].formula = parts[u];
              }
            }
          }
        } else {
          for (let u = 1; u < parts.length; u++) {
            const parse = parts[u].match(/([\w\s/+*-]+)(\(.+\))?/);
            if (parse && parse[1]) {
              const op = parse[1].trim();
              if (op === "*" || op === "+" || op === "-" || op === "/" || op === "%" || op === "min" || op === "max") {
                if (parse[2] === void 0) {
                  console.log(`Invalid format of format string: ${format}`);
                } else {
                  let argStr = (parse[2] || "").trim().replace(",", ".");
                  argStr = argStr.substring(1, argStr.length - 1).trim();
                  const arg = parseFloat(argStr);
                  if (arg.toString() === "NaN") {
                    console.log(`Invalid format of format string: ${format}`);
                  } else {
                    operations = operations || [];
                    operations.push({
                      op,
                      arg
                    });
                  }
                }
              } else if (op === "date" || op === "momentDate") {
                operations = operations || [];
                let arg = (parse[2] || "").trim();
                arg = arg.substring(1, arg.length - 1);
                operations.push({
                  op,
                  arg
                });
              } else if (op === "array") {
                operations = operations || [];
                let param = (parse[2] || "").trim();
                param = param.substring(1, param.length - 1);
                operations.push({
                  op,
                  arg: param.split(",")
                });
              } else if (op === "value") {
                operations = operations || [];
                let arg = parse[2] === void 0 ? "(2)" : parse[2] || "";
                arg = arg.trim();
                arg = arg.substring(1, arg.length - 1);
                operations.push({
                  op,
                  arg
                });
              } else if (op === "pow" || op === "round" || op === "random") {
                if (parse[2] === void 0) {
                  operations = operations || [];
                  operations.push({
                    op
                  });
                } else {
                  let argStr = (parse[2] || "").trim().replace(",", ".");
                  argStr = argStr.substring(1, argStr.length - 1);
                  const arg = parseFloat(argStr.trim());
                  if (arg.toString() === "NaN") {
                    console.log(`Invalid format of format string: ${format}`);
                  } else {
                    operations = operations || [];
                    operations.push({
                      op,
                      arg
                    });
                  }
                }
              } else if (op === "json") {
                operations = operations || [];
                let arg = (parse[2] || "").trim();
                arg = arg.substring(1, arg.length - 1);
                operations.push({
                  op,
                  arg
                });
              } else {
                operations = operations || [];
                operations.push({
                  op
                });
              }
            } else {
              console.log(`Invalid format ${format}`);
            }
          }
        }
        result.push({
          visOid,
          systemOid,
          token: oid[p],
          operations: operations || void 0,
          format,
          isSeconds
        });
      }
    }
    return result;
  };
  getUsedObjectIDsInWidget = function(views, view, wid, linkContext) {
    var _a;
    const widget = deepClone(views[view].widgets[wid]);
    if (widget.groupped) {
      widget.grouped = true;
      delete widget.groupped;
    }
    if (widget.widgetSet === "hqWidgets") {
      widget.widgetSet = "hqwidgets";
    }
    if (widget.widgetSet === "RGraph") {
      widget.widgetSet = "rgraph";
    }
    if (widget.widgetSet === "timeAndWeather") {
      widget.widgetSet = "timeandweather";
    }
    if (widget.tpl === "tplShowValue") {
      widget.tpl = "tplHtml";
      widget.data["visibility-oid"] = widget.data.oid;
      widget.data["visibility-val"] = widget.data.value;
      delete widget.data.oid;
      delete widget.data.value;
    }
    if (widget.tpl === "tplHideTrue") {
      widget.tpl = "tplHtml";
      widget.data["visibility-cond"] = "!=";
      widget.data["visibility-oid"] = widget.data.oid;
      widget.data["visibility-val"] = true;
      delete widget.data.oid;
    }
    if (widget.tpl === "tplHide") {
      widget.tpl = "tplHtml";
      widget.data["visibility-cond"] = "!=";
      widget.data["visibility-oid"] = widget.data.oid;
      widget.data["visibility-val"] = false;
      delete widget.data.oid;
    }
    if (widget.tpl === "tplHmWindow") {
      widget.tpl = "tplValueBool";
      widget.data.html_false = widget.data.html_closed;
      widget.data.html_true = widget.data.html_open;
      delete widget.data.html_closed;
      delete widget.data.html_open;
    }
    if (widget.tpl === "tplHmWindowRotary") {
      widget.tpl = "tplValueListHtml8";
      widget.data.count = 2;
      widget.data.value0 = widget.data.html_closed;
      widget.data.value1 = widget.data.html_open;
      widget.data.value2 = widget.data.html_tilt;
      delete widget.data.html_closed;
      delete widget.data.html_open;
      delete widget.data.html_tilt;
    }
    if (widget.tpl === "tplBulbOnOff") {
      widget.tpl = "tplBulbOnOffCtrl";
      widget.data.readOnly = true;
    }
    if (widget.tpl === "tplValueFloatBarVertical") {
      widget.tpl = "tplValueFloatBar";
      widget.data.orientation = "vertical";
    }
    let { data } = widget;
    const { style } = widget;
    if (widget.grouped) {
      if (!widget.groupid) {
        store.dispatch(updateWidget({
          viewId: view,
          widgetId: wid,
          data: {
            ...widget,
            groupid: getWidgetGroup(views, view, wid)
          }
        }));
      }
      if (widget.groupid && !store.getState().visProject[view].widgets[widget.groupid]) {
        store.dispatch(updateWidget({
          viewId: view,
          widgetId: wid,
          data: {
            ...widget,
            groupid: getWidgetGroup(views, view, wid)
          }
        }));
        if (!widget.groupid) {
          let groupNum = 1;
          let gId = `g${groupNum.toString().padStart(5, "0")}`;
          while (views[view].widgets[gId]) {
            groupNum++;
            gId = `g${groupNum.toString().padStart(5, "0")}`;
          }
          const currView = deepClone(views[view]);
          currView.widgets[gId] = {
            tpl: "_tplGroup",
            data: {
              members: [
                wid
              ]
            },
            style: {
              top: "100px",
              left: "100px",
              width: "200px",
              height: "200px"
            },
            widgetSet: null
          };
          store.dispatch(updateView({
            viewId: view,
            data: currView
          }));
        }
      }
      if (widget.groupid) {
        const parentWidgetData = (_a = views[view].widgets[widget.groupid]) == null ? void 0 : _a.data;
        if (parentWidgetData) {
          let newGroupData;
          Object.keys(data).forEach((attr) => {
            if (typeof data[attr] === "string") {
              const result = replaceGroupAttr(data[attr], parentWidgetData);
              if (result.doesMatch) {
                newGroupData = newGroupData || deepClone(data);
                newGroupData[attr] = result.newString || "";
              }
            }
          });
          if (newGroupData) {
            data = newGroupData;
          }
        } else {
          console.error(`Invalid group id "${widget.groupid}" in widget "${wid}"`);
        }
      }
    }
    Object.keys(data || {}).forEach((attr) => {
      var _a2;
      if (!attr) {
        return;
      }
      if (typeof data[attr] === "string") {
        let m;
        const OIDs = extractBinding(data[attr]);
        if (OIDs) {
          OIDs.forEach((item) => {
            const systemOid = item.systemOid;
            if (systemOid) {
              !linkContext.IDs.includes(systemOid) && linkContext.IDs.push(systemOid);
              if (linkContext.byViews && !linkContext.byViews[view].includes(systemOid)) {
                linkContext.byViews[view].push(systemOid);
              }
              linkContext.bindings[systemOid] = linkContext.bindings[systemOid] || [];
              item.type = "data";
              item.attr = attr;
              item.view = view;
              item.widget = wid;
              linkContext.bindings[systemOid].push(item);
            }
            const operation0 = item.operations && item.operations[0];
            if (operation0 && Array.isArray(operation0.arg)) {
              for (let ww = 0; ww < operation0.arg.length; ww++) {
                const arg = operation0.arg[ww];
                const _systemOid = arg.systemOid;
                if (!_systemOid) {
                  continue;
                }
                !linkContext.IDs.includes(_systemOid) && linkContext.IDs.push(_systemOid);
                if (linkContext.byViews && !linkContext.byViews[view].includes(_systemOid)) {
                  linkContext.byViews[view].push(_systemOid);
                }
                linkContext.bindings[_systemOid] = linkContext.bindings[_systemOid] || [];
                if (!linkContext.bindings[_systemOid].includes(item)) {
                  linkContext.bindings[_systemOid].push(item);
                }
              }
            }
          });
        } else if (attr !== "oidTrueValue" && attr !== "oidFalseValue" && data[attr] && data[attr] !== "nothing_selected") {
          let isID = !!attr.match(/oid\d{0,2}$/);
          if (attr.startsWith("oid")) {
            isID = true;
          } else if (attr.startsWith("signals-oid-")) {
            isID = true;
          } else if (linkContext.widgetAttrInfo) {
            const _attr = attr.replace(/\d{0,2}$/, "");
            if (((_a2 = linkContext.widgetAttrInfo[_attr]) == null ? void 0 : _a2.type) === "id" && linkContext.widgetAttrInfo[_attr].noSubscribe !== true) {
              isID = true;
            }
          }
          if (isID) {
            if (!data[attr].startsWith('"')) {
              if (!linkContext.IDs.includes(data[attr])) {
                linkContext.IDs.push(data[attr]);
              }
              if (linkContext.byViews && !linkContext.byViews[view].includes(data[attr])) {
                linkContext.byViews[view].push(data[attr]);
              }
            }
            if (attr === "visibility-oid") {
              let vid = data["visibility-oid"];
              if (widget.grouped) {
                const vGroup = getWidgetGroup(views, view, wid);
                if (vGroup) {
                  if (views[view].widgets[vGroup]) {
                    const result1 = replaceGroupAttr(vid, views[view].widgets[vGroup].data);
                    if (result1.doesMatch) {
                      vid = result1.newString;
                    }
                  } else {
                    console.warn(`Invalid group: ${vGroup} in ${view} / ${wid}`);
                  }
                }
              }
              linkContext.visibility[vid] = linkContext.visibility[vid] || [];
              linkContext.visibility[vid].push({
                view,
                widget: wid
              });
            } else if (attr.startsWith("signals-oid-")) {
              let sid = data[attr];
              if (widget.grouped) {
                const group = getWidgetGroup(views, view, wid);
                if (group) {
                  const result2 = replaceGroupAttr(sid, views[view].widgets[group].data);
                  if (result2.doesMatch) {
                    sid = result2.newString;
                  }
                }
              }
              linkContext.signals[sid] = linkContext.signals[sid] || [];
              linkContext.signals[sid].push({
                view,
                widget: wid,
                index: parseInt(attr.substring(12), 10)
              });
            } else if (attr === "lc-oid") {
              let lcSid = data[attr];
              if (widget.grouped) {
                const gGroup = getWidgetGroup(views, view, wid);
                if (gGroup) {
                  const result3 = replaceGroupAttr(lcSid, views[view].widgets[gGroup].data);
                  if (result3.doesMatch) {
                    lcSid = result3.newString;
                  }
                }
              }
              linkContext.lastChanges[lcSid] = linkContext.lastChanges[lcSid] || [];
              linkContext.lastChanges[lcSid].push({
                view,
                widget: wid
              });
            }
          } else if (data[attr] === "id") {
            m = attr.match(/^attrType(\d+)$/);
            if (m) {
              const _id = `groupAttr${m[1]}`;
              if (data[_id]) {
                if (!linkContext.IDs.includes(data[_id])) {
                  linkContext.IDs.push(data[_id]);
                }
                if (linkContext.byViews && !linkContext.byViews[view].includes(data[_id])) {
                  linkContext.byViews[view].push(data[_id]);
                }
              }
            }
          }
        }
      }
    });
    if (style) {
      Object.keys(style).forEach((cssAttr) => {
        const styleValue = style[cssAttr];
        if (cssAttr && styleValue && typeof styleValue === "string") {
          const OIDs = extractBinding(styleValue);
          if (OIDs) {
            OIDs.forEach((item) => {
              const systemOid = item.systemOid;
              if (systemOid) {
                !linkContext.IDs.includes(systemOid) && linkContext.IDs.push(systemOid);
                if (linkContext.byViews && linkContext.byViews[view].includes(systemOid)) {
                  linkContext.byViews[view].push(systemOid);
                }
                linkContext.bindings[systemOid] = linkContext.bindings[systemOid] || [];
                item.type = "style";
                item.attr = cssAttr;
                item.view = view;
                item.widget = wid;
                linkContext.bindings[systemOid].push(item);
              }
              const operation0 = item.operations && item.operations[0];
              if (operation0 && Array.isArray(operation0.arg)) {
                for (let w = 0; w < operation0.arg.length; w++) {
                  const arg = operation0.arg[w];
                  const _systemOid = arg.systemOid;
                  if (!_systemOid) {
                    continue;
                  }
                  !linkContext.IDs.includes(_systemOid) && linkContext.IDs.push(_systemOid);
                  if (linkContext.byViews && !linkContext.byViews[view].includes(_systemOid)) {
                    linkContext.byViews[view].push(_systemOid);
                  }
                  linkContext.bindings[_systemOid] = linkContext.bindings[_systemOid] || [];
                  if (!linkContext.bindings[_systemOid].includes) {
                    linkContext.bindings[_systemOid].push(item);
                  }
                }
              }
            });
          }
        }
      });
    }
    store.dispatch(updateWidget({
      viewId: view,
      widgetId: wid,
      data: widget
    }));
  };
  getUrlParameter = function(attr) {
    const sURLVariables = new URLSearchParams(window.location.search);
    if (!sURLVariables.has(attr)) {
      return "";
    }
    const sParameterName = sURLVariables.get(attr);
    return typeof sParameterName === "undefined" ? true : decodeURIComponent(sParameterName);
  };
  readFile = async function(socket, id, fileName, withType) {
    const file = await socket.readFile(id, fileName);
    let mimeType = "";
    let data;
    if (typeof file === "object") {
      if (withType) {
        mimeType = file.mimeType ? file.mimeType : file.type ? file.type : "";
      }
      data = file.file || file.data;
    } else {
      data = file;
    }
    if (withType) {
      return {
        file: data,
        mimeType
      };
    }
    return data;
  };
  addClass = function(actualClass, toAdd) {
    if (actualClass) {
      const parts = actualClass.split(" ").map((cl) => cl.trim()).filter((cl) => cl);
      if (toAdd && !parts.includes(toAdd)) {
        parts.push(toAdd);
      }
      return parts.join(" ");
    }
    return toAdd || "";
  };
  function removeClass(actualClass, toRemove) {
    if (actualClass) {
      const parts = actualClass.split(" ").map((cl) => cl.trim()).filter((cl) => cl);
      const pos = parts.indexOf(toRemove);
      if (pos !== -1) {
        parts.splice(pos, 1);
      }
      return parts.join(" ");
    }
    return "";
  }
  parseDimension = function(field) {
    const result = {
      value: 0,
      dimension: "px"
    };
    if (!field) {
      return result;
    }
    const match = field.toString().match(/^([0-9-.]+)([a-z%]*)$/);
    if (!match) {
      return result;
    }
    result.value = parseInt(match[1]);
    result.dimension = match[2] || "px";
    return result;
  };
  findWidgetUsages = function(views, view, widgetId, _result) {
    if (view) {
      _result = _result || [];
      Object.keys(views[view].widgets).forEach((wid) => {
        if (wid === widgetId) {
          return;
        }
        const oWidget = views[view].widgets[wid];
        const attrs = Object.keys(oWidget.data);
        attrs.forEach((attr) => {
          if (attr.startsWith("widget") && oWidget.data[attr] === widgetId) {
            _result.push({
              view,
              wid,
              attr
            });
          }
        });
      });
      return _result;
    }
    const result = [];
    Object.keys(views).forEach((_view) => _view !== "___settings" && findWidgetUsages(views, _view, widgetId, _result));
    return result;
  };
  applyTitleAndIcon = function(title, icon, options) {
    title || (title = window.location.pathname.includes("edit.html") ? "Editor.vis" : "ioBroker.vis");
    icon || (icon = window.location.pathname.includes("edit.html") ? "./faviconEdit.ico" : "./favicon.ico");
    window.document.title = title;
    if (icon.startsWith("../")) {
      icon = icon.substring(3);
    } else if (icon.startsWith("_PRJ_NAME/")) {
      icon = icon.replace("_PRJ_NAME/", `../${options.adapterName}.${options.instance}/${options.projectName}/`);
    }
    const link = window.document.querySelector('link[rel="icon"]');
    if (link) {
      link.setAttribute("href", icon);
    } else {
      const newLink = window.document.createElement("link");
      newLink.setAttribute("rel", "icon");
      newLink.setAttribute("href", icon);
      window.document.head.appendChild(newLink);
    }
    const manifestJSON = {
      short_name: title,
      name: title,
      icons: [
        {
          src: icon,
          sizes: "64x64 32x32 24x24 16x16",
          type: "image/x-icon"
        }
      ],
      start_url: ".",
      display: "standalone",
      theme_color: options.themeType === "dark" ? "rgb(51, 51, 51)" : "rgb(230, 230, 230)",
      background_color: options.themeType === "dark" ? "#000" : "#FFF"
    };
    const stringManifest = JSON.stringify(manifestJSON);
    const blob = new Blob([
      stringManifest
    ], {
      type: "application/json"
    });
    const manifestURL = URL.createObjectURL(blob);
    document.querySelector("#vis-manifest").setAttribute("href", manifestURL);
  };
  const VisOrderMenu = React.lazy(() => __vitePreload(() => import("./visOrderMenu-B4G4EPYH.js").then(async (m) => {
    await m.__tla;
    return m;
  }), true ? __vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]) : void 0, import.meta.url));
  VisBaseWidget = class extends React.Component {
    static FORBIDDEN_CHARS = /[^._\-/ :!#$%&()+=@^{}|~]+/g;
    relativeMoveMenu;
    resize = false;
    uuid = `${Date.now()}.${Math.round(Math.random() * 1e6)}`;
    refService = React.createRef();
    widDiv = null;
    onCommandBound;
    onResize;
    updateInterval;
    pressTimeout;
    shadowDiv;
    stealCursor;
    beforeIncludeColor;
    lastClick;
    movement;
    resizeLocked;
    visDynamicResizable;
    isCanWidget;
    constructor(props) {
      var _a, _b, _c;
      super(props);
      const widget = props.context.views[props.view].widgets[props.id];
      const multiViewWidget = props.id.includes("_");
      const selected = !multiViewWidget && props.editMode && ((_a = props.selectedWidgets) == null ? void 0 : _a.includes(props.id));
      const data = deepClone(widget.data || {});
      const style = deepClone(widget.style || {});
      VisBaseWidget.replacePRJ_NAME(data, style, props);
      this.state = {
        data,
        style,
        applyBindings: false,
        editMode: !multiViewWidget && this.props.editMode,
        multiViewWidget,
        selected,
        selectedOne: selected && this.props.selectedWidgets.length === 1,
        resizable: true,
        resizeHandles: [
          "n",
          "e",
          "s",
          "w",
          "nw",
          "ne",
          "sw",
          "se"
        ],
        widgetHint: props.context.widgetHint,
        isHidden: VisBaseWidget.isWidgetFilteredOutStatic(props.viewsActiveFilter, widget.data, props.view, props.editMode),
        usedInWidget: widget.usedInWidget,
        hideHelper: false,
        gap: style.position === "relative" ? isVarFinite((_b = props.context.views[props.view].settings) == null ? void 0 : _b.rowGap) ? parseFloat((_c = props.context.views[props.view].settings) == null ? void 0 : _c.rowGap) : 0 : 0
      };
      this.onCommandBound = this.onCommand.bind(this);
    }
    static replacePRJ_NAME(data, style, props) {
      const context = props.context;
      if (data) {
        delete data._originalData;
        Object.keys(data).forEach((attr) => {
          if (attr && data[attr] && typeof data[attr] === "string" && (attr.startsWith("src") || attr.endsWith("src") || attr.includes("icon")) && data[attr].startsWith("_PRJ_NAME")) {
            if (!data._originalData) {
              data._originalData = JSON.stringify(data);
            }
            data[attr] = `../${context.adapterName}.${context.instance}/${context.projectName}${data[attr].substring(9)}`;
          }
        });
      }
      if (style) {
        delete style._originalData;
        if (style["background-image"] && style["background-image"].startsWith("_PRJ_NAME")) {
          if (!style._originalData) {
            style._originalData = JSON.stringify(style);
          }
          style["background-image"] = `../${context.adapterName}.${context.instance}/${context.projectName}${style["background-image"].substring(9)}`;
        }
      }
    }
    componentDidMount() {
      this.props.askView && this.props.askView("register", {
        id: this.props.id,
        uuid: this.uuid,
        widDiv: this.widDiv,
        refService: this.refService,
        onMove: this.onMove,
        onResize: this.onResize,
        onTempSelect: this.onTempSelect,
        onCommand: this.onCommandBound
      });
    }
    componentWillUnmount() {
      this.updateInterval && clearInterval(this.updateInterval);
      this.updateInterval = void 0;
      this.pressTimeout && clearTimeout(this.pressTimeout);
      this.pressTimeout = void 0;
      this.props.askView && this.props.askView("unregister", {
        id: this.props.id,
        uuid: this.uuid
      });
      if (this.shadowDiv) {
        this.shadowDiv.remove();
        this.shadowDiv = null;
      }
    }
    onCommand(command, _option) {
      var _a, _b, _c, _d, _e, _f, _g, _h;
      if (command === "includePossible") {
        const overlay = (_a = this.refService.current) == null ? void 0 : _a.querySelector(".vis-editmode-overlay");
        if (overlay && this.beforeIncludeColor === void 0) {
          this.beforeIncludeColor = overlay.style.backgroundColor;
          overlay.style.backgroundColor = "rgba(0, 255, 0, 0.3)";
        }
        return true;
      }
      if (command === "includePossibleNOT") {
        if (this.beforeIncludeColor !== void 0) {
          const overlay = (_b = this.refService.current) == null ? void 0 : _b.querySelector(".vis-editmode-overlay");
          overlay && (overlay.style.backgroundColor = this.beforeIncludeColor);
          this.beforeIncludeColor = void 0;
        }
        return true;
      }
      if (command === "startStealMode") {
        this.stealCursor = ((_c = this.refService.current) == null ? void 0 : _c.style.cursor) || "nocursor";
        if (this.refService.current) {
          this.refService.current.style.cursor = "crosshair";
          this.refService.current.className = addClass(this.refService.current.className, "vis-editmode-steal-style");
        }
        const resizers = (_d = this.refService.current) == null ? void 0 : _d.querySelectorAll(".vis-editmode-resizer");
        resizers == null ? void 0 : resizers.forEach((item) => item.style.display = "none");
        return true;
      }
      if (command === "cancelStealMode") {
        if (this.stealCursor !== "nocursor" && this.refService.current && this.stealCursor) {
          this.refService.current.style.cursor = this.stealCursor;
        }
        this.stealCursor = void 0;
        if (this.refService.current) {
          this.refService.current.className = removeClass(this.refService.current.className, "vis-editmode-steal-style");
        }
        const resizers = (_e = this.refService.current) == null ? void 0 : _e.querySelectorAll(".vis-editmode-resizer");
        resizers == null ? void 0 : resizers.forEach((item) => item.style.display = "");
        return true;
      }
      if (command === "startMove" || command === "startResize") {
        const overlay = (_f = this.refService.current) == null ? void 0 : _f.querySelector(".vis-editmode-overlay");
        if (overlay) {
          if (this.state.selected) {
            overlay.className = removeClass(overlay.className, "vis-editmode-selected");
          } else {
            overlay.className = removeClass(overlay.className, "vis-editmode-overlay-not-selected");
          }
        }
        if (command === "startResize") {
          this.resize = true;
        }
        return true;
      }
      if (command === "stopMove" || command === "stopResize") {
        const overlay = (_g = this.refService.current) == null ? void 0 : _g.querySelector(".vis-editmode-overlay");
        if (overlay) {
          if (this.beforeIncludeColor !== void 0) {
            overlay.style.backgroundColor = this.beforeIncludeColor;
            this.beforeIncludeColor = void 0;
          }
          if (this.state.selected) {
            overlay.className = addClass(overlay.className, "vis-editmode-selected");
          } else {
            overlay.className = addClass(overlay.className, "vis-editmode-overlay-not-selected");
          }
        }
        const resizers = (_h = this.refService.current) == null ? void 0 : _h.querySelectorAll(".vis-editmode-resizer");
        resizers == null ? void 0 : resizers.forEach((item) => item.style.display = "block");
        if (command === "stopResize") {
          this.resize = false;
        }
        return true;
      }
      return false;
    }
    static getDerivedStateFromProps(props, state) {
      var _a, _b, _c, _d;
      const context = props.context;
      let newState = null;
      let widget = context.views[props.view].widgets[props.id];
      const gap = widget.style.position === "relative" ? isVarFinite((_a = context.views[props.view].settings) == null ? void 0 : _a.rowGap) ? parseFloat((_b = context.views[props.view].settings) == null ? void 0 : _b.rowGap) : 0 : 0;
      let copied = false;
      if (widget.groupid) {
        const parentWidgetData = context.views[props.view].widgets[widget.groupid].data;
        const names = Object.keys(parentWidgetData).map((attr) => attr.startsWith("attrType_") ? attr.substring(9) : null).filter((attr) => attr);
        if (names.length && widget.data) {
          for (const [attr, val] of Object.entries(widget.data)) {
            if (typeof val === "string" && names.find((a) => val.includes(a))) {
              const result = replaceGroupAttr(widget.data[attr], parentWidgetData);
              if (result.doesMatch) {
                if (!copied) {
                  copied = true;
                  widget = deepClone(widget);
                }
                widget.data[attr] = result.newString || "";
              }
            }
          }
        }
      }
      const styleStr = ((_c = state.style) == null ? void 0 : _c._originalData) ? state.style._originalData : JSON.stringify(state.style);
      const dataStr = ((_d = state.data) == null ? void 0 : _d._originalData) ? state.data._originalData : JSON.stringify(state.data);
      const isHidden = VisBaseWidget.isWidgetFilteredOutStatic(props.viewsActiveFilter, widget.data, props.view, props.editMode);
      if (JSON.stringify(widget.style || {}) !== styleStr || JSON.stringify(widget.data || {}) !== dataStr || gap !== state.gap || isHidden !== state.isHidden) {
        if (!props.runtime) {
          const styleObj = JSON.parse(styleStr);
          Object.keys(styleObj).forEach((attr) => {
            const oldStyle = widget.style[attr];
            const newStyle = styleObj[attr];
            if (newStyle !== oldStyle) {
              console.log(`[${Date.now()} / ${props.id}] Rerender because of style.${attr}: ${newStyle} !== ${oldStyle}`);
            }
          });
          Object.keys(widget.style).forEach((attr) => {
            const oldStyle = widget.style[attr];
            const newStyle = styleObj[attr];
            if (newStyle !== oldStyle) {
              console.log(`[${Date.now()} / ${props.id}] Rerender because of style.${attr}: ${newStyle} !== ${oldStyle}`);
            }
          });
          const dataObj = JSON.parse(dataStr);
          Object.keys(dataObj).forEach((attr) => {
            if (JSON.stringify(dataObj[attr]) !== JSON.stringify(widget.data[attr])) {
              console.log(`[${Date.now()} / ${props.id}] Rerender because of data.${attr}: ${dataObj[attr]} !== ${widget.data[attr]}`);
            }
          });
        }
        let data;
        let style;
        if (copied) {
          data = widget.data || {
            bindings: []
          };
          style = widget.style || {
            bindings: []
          };
        } else {
          data = widget.data ? deepClone(widget.data) : {
            bindings: []
          };
          style = widget.style ? deepClone(widget.style) : {
            bindings: []
          };
        }
        VisBaseWidget.replacePRJ_NAME(data, style, props);
        newState = {};
        newState.isHidden = isHidden;
        newState.style = style;
        newState.data = data;
        newState.gap = gap;
        newState.applyBindings = {
          top: widget.style.top,
          left: widget.style.left
        };
      }
      if (props.editMode !== state.editMode) {
        newState = newState || {};
        newState.editMode = props.editMode;
        newState.applyBindings = true;
      }
      if (props.context.widgetHint !== state.widgetHint) {
        newState = newState || {};
        newState.widgetHint = props.context.widgetHint;
      }
      const selected = !state.multiViewWidget && props.editMode && props.selectedWidgets && props.selectedWidgets.includes(props.id);
      const selectedOne = selected && props.selectedWidgets.length === 1;
      if (selected !== state.selected || selectedOne !== state.selectedOne) {
        newState = newState || {};
        newState.selected = selected;
        newState.selectedOne = selectedOne;
      }
      if (!!widget.usedInWidget !== !!state.usedInWidget) {
        newState = newState || {};
        newState.usedInWidget = !!widget.usedInWidget;
      }
      return newState;
    }
    static removeFromArray(items, IDs, view, widget) {
      items && Object.keys(items).forEach((id) => {
        if (!IDs || IDs.includes(id)) {
          for (let i = items[id].length - 1; i >= 0; i--) {
            const item = items[id][i];
            if (item.view === view && item.widget === widget) {
              items[id].splice(i, 1);
            }
          }
        }
      });
    }
    static parseStyle(style, isRxStyle) {
      const result = {};
      (style || "").split(";").forEach((part) => {
        part = part.trim();
        if (part) {
          let [attr, value] = part.split(":");
          attr = attr.trim();
          if (attr && value) {
            value = value.trim();
            if (!isRxStyle && (attr === "top" || attr === "left" || attr === "width" || attr === "height")) {
              if (!isRxStyle) {
                if (value !== "0" && value.match(/^[-+]?\d+$/)) {
                  value = `${value}px`;
                }
              } else {
                const f = parseFloat(value);
                if (value === f.toString()) {
                  value = f;
                }
              }
            }
            if (value) {
              if (isRxStyle) {
                attr = attr.replace(/(-\w)/, (text) => text[1].toUpperCase());
              }
              result[attr] = value;
            }
          }
        }
      });
      return result;
    }
    onMouseDown(e) {
      e.stopPropagation();
      if (this.stealCursor && !this.state.multiViewWidget) {
        e.stopPropagation();
        this.props.mouseDownOnView(e, this.props.id, this.props.isRelative);
        return;
      }
      if (this.props.context.views[this.props.view].widgets[this.props.id].data.locked) {
        return;
      }
      if (this.lastClick !== void 0 && Date.now() - this.lastClick < 250) {
        console.log("AAA");
      }
      if (this.lastClick) {
        if (this.state.multiViewWidget) {
          if (Date.now() - this.lastClick < 250) {
            const lastUnderscore = this.props.id.lastIndexOf("_");
            const multiView = this.props.id.substring(1, lastUnderscore);
            const multiId = this.props.id.substring(lastUnderscore + 1);
            this.props.context.setSelectedWidgets([
              multiId
            ], multiView);
          }
          this.lastClick = Date.now();
          return;
        }
      }
      if (e.shiftKey || e.ctrlKey) {
        const pos = this.props.selectedWidgets.indexOf(this.props.id);
        if (pos === -1) {
          const selectedWidgets = [
            ...this.props.selectedWidgets,
            this.props.id
          ];
          this.props.context.setSelectedWidgets(selectedWidgets);
        } else {
          const selectedWidgets = [
            ...this.props.selectedWidgets
          ];
          selectedWidgets.splice(pos, 1);
          this.props.context.setSelectedWidgets(selectedWidgets);
        }
        return;
      }
      if (!this.props.selectedWidgets.includes(this.props.id)) {
        this.props.context.setSelectedWidgets([
          this.props.id
        ]);
      } else if (this.props.moveAllowed && this.state.draggable !== false) {
        if (!this.props.isRelative) {
          this.props.mouseDownOnView(e, this.props.id, this.props.isRelative, false, this.lastClick !== void 0 && Date.now() - this.lastClick < 300);
        } else if (this.lastClick && Date.now() - this.lastClick < 250) {
          if (this.props.selectedWidgets.length === 1 && this.props.context.views[this.props.view].widgets[this.props.selectedWidgets[0]].tpl === "_tplGroup") {
            this.props.context.setSelectedGroup(this.props.selectedWidgets[0]);
          }
        }
      }
      this.lastClick = Date.now();
    }
    createWidgetMovementShadow() {
      if (this.shadowDiv) {
        this.shadowDiv.remove();
        this.shadowDiv = null;
      }
      if (!this.movement) {
        console.error("Unknown issue, movement is falsy");
        return;
      }
      this.shadowDiv = window.document.createElement("div");
      this.shadowDiv.setAttribute("id", `${this.props.id}_shadow`);
      this.shadowDiv.className = "vis-editmode-widget-shadow";
      if (this.refService.current) {
        this.shadowDiv.style.width = `${this.refService.current.clientWidth}px`;
        this.shadowDiv.style.height = `${this.refService.current.clientHeight}px`;
        if (this.refService.current.style.borderRadius) {
          this.shadowDiv.style.borderRadius = this.refService.current.style.borderRadius;
        }
      }
      let parentDiv;
      if (Object.prototype.hasOwnProperty.call(this.props.refParent, "current")) {
        parentDiv = this.props.refParent.current;
      } else {
        parentDiv = this.props.refParent;
      }
      if (this.widDiv) {
        parentDiv.insertBefore(this.shadowDiv, this.widDiv);
        this.widDiv.style.position = "absolute";
        this.widDiv.style.left = `${this.movement.left}px`;
        this.widDiv.style.top = `${this.movement.top}px`;
      } else {
        parentDiv.insertBefore(this.shadowDiv, this.refService.current);
        if (this.refService.current) {
          this.refService.current.style.position = "absolute";
        }
      }
      if (this.refService.current) {
        this.refService.current.style.left = `${this.movement.left}px`;
        this.refService.current.style.top = `${this.movement.top}px`;
      }
    }
    isResizable() {
      if (this.visDynamicResizable) {
        return typeof this.state.data.visResizable === "boolean" ? this.state.data.visResizable : this.visDynamicResizable.default;
      }
      return this.state.resizable;
    }
    onMove = (x, y, save, calculateRelativeWidgetPosition) => {
      var _a, _b;
      if (this.state.multiViewWidget || !this.state.editMode) {
        return;
      }
      const movement = this.movement;
      if (!this.refService.current) {
        return;
      }
      if (this.resize) {
        if (this.isResizable() === false) {
          return;
        }
        if (x === void 0) {
          const rect = (_a = this.widDiv || this.refService.current) == null ? void 0 : _a.getBoundingClientRect();
          if (rect) {
            this.movement = {
              top: this.refService.current.offsetTop,
              left: this.refService.current.offsetLeft,
              width: rect.width,
              height: rect.height
            };
          }
          const resizers = this.refService.current.querySelectorAll(".vis-editmode-resizer");
          resizers.forEach((item) => {
            item._storedOpacity = item.style.opacity;
            item.style.opacity = "0.3";
          });
        } else if (movement && y !== void 0) {
          if (this.resize === "top") {
            this.refService.current.style.top = `${movement.top + y}px`;
            this.refService.current.style.height = `${movement.height - y}px`;
            if (this.resizeLocked) {
              this.refService.current.style.width = this.refService.current.style.height;
            }
            if (this.widDiv) {
              this.widDiv.style.top = `${movement.top + y}px`;
              this.widDiv.style.height = `${movement.height - y}px`;
              if (this.resizeLocked) {
                this.widDiv.style.width = this.widDiv.style.height;
              }
            }
          } else if (this.resize === "bottom") {
            this.widDiv && (this.widDiv.style.height = `${movement.height + y}px`);
            this.refService.current.style.height = `${movement.height + y}px`;
            if (this.resizeLocked) {
              this.refService.current.style.width = this.refService.current.style.height;
            }
            if (this.widDiv && this.resizeLocked) {
              this.widDiv.style.width = this.widDiv.style.height;
            }
          } else if (this.resize === "left") {
            this.refService.current.style.left = `${movement.left + x}px`;
            this.refService.current.style.width = `${movement.width - x}px`;
            if (this.resizeLocked) {
              this.refService.current.style.height = this.refService.current.style.width;
            }
            if (this.widDiv) {
              this.widDiv.style.left = `${movement.left + x}px`;
              this.widDiv.style.width = `${movement.width - x}px`;
              if (this.resizeLocked) {
                this.widDiv.style.height = this.widDiv.style.width;
              }
            }
          } else if (this.resize === "right") {
            this.widDiv && (this.widDiv.style.width = `${movement.width + x}px`);
            this.refService.current.style.width = `${movement.width + x}px`;
            if (this.resizeLocked) {
              this.refService.current.style.height = this.refService.current.style.width;
            }
            if (this.widDiv && this.resizeLocked) {
              this.widDiv.style.height = this.widDiv.style.width;
            }
          } else if (this.resize === "top-left") {
            this.refService.current.style.top = `${movement.top + y}px`;
            this.refService.current.style.left = `${movement.left + x}px`;
            this.refService.current.style.height = `${movement.height - y}px`;
            this.refService.current.style.width = `${movement.width - x}px`;
            if (this.resizeLocked) {
              this.refService.current.style.height = this.refService.current.style.width;
            }
            if (this.widDiv) {
              this.widDiv.style.top = `${movement.top + y}px`;
              this.widDiv.style.left = `${movement.left + x}px`;
              this.widDiv.style.height = `${movement.height - y}px`;
              this.widDiv.style.width = `${movement.width - x}px`;
              if (this.resizeLocked) {
                this.widDiv.style.height = this.widDiv.style.width;
              }
            }
          } else if (this.resize === "top-right") {
            this.refService.current.style.top = `${movement.top + y}px`;
            this.refService.current.style.height = `${movement.height - y}px`;
            this.refService.current.style.width = `${movement.width + x}px`;
            if (this.resizeLocked) {
              this.refService.current.style.height = this.refService.current.style.width;
            }
            if (this.widDiv) {
              this.widDiv.style.top = `${movement.top + y}px`;
              this.widDiv.style.height = `${movement.height - y}px`;
              this.widDiv.style.width = `${movement.width + x}px`;
              if (this.resizeLocked) {
                this.widDiv.style.height = this.widDiv.style.width;
              }
            }
          } else if (this.resize === "bottom-left") {
            this.refService.current.style.left = `${movement.left + x}px`;
            this.refService.current.style.height = `${movement.height + y}px`;
            this.refService.current.style.width = `${movement.width - x}px`;
            if (this.resizeLocked) {
              this.refService.current.style.height = this.refService.current.style.width;
            }
            if (this.widDiv) {
              this.widDiv.style.left = `${movement.left + x}px`;
              this.widDiv.style.height = `${movement.height + y}px`;
              this.widDiv.style.width = `${movement.width - x}px`;
              if (this.resizeLocked) {
                this.widDiv.style.height = this.widDiv.style.width;
              }
            }
          } else {
            this.refService.current.style.height = `${movement.height + y}px`;
            this.refService.current.style.width = `${movement.width + x}px`;
            if (this.resizeLocked) {
              this.refService.current.style.height = this.refService.current.style.width;
            }
            if (this.widDiv) {
              this.widDiv.style.height = `${movement.height + y}px`;
              this.widDiv.style.width = `${movement.width + x}px`;
              if (this.resizeLocked) {
                this.widDiv.style.height = this.widDiv.style.width;
              }
            }
          }
        }
        if (save) {
          const resizers = (_b = this.refService.current) == null ? void 0 : _b.querySelectorAll(".vis-editmode-resizer");
          resizers == null ? void 0 : resizers.forEach((item) => {
            if (item._storedOpacity !== void 0) {
              item.style.opacity = item._storedOpacity;
              delete item._storedOpacity;
            }
          });
          this.resize = false;
          this.props.context.onWidgetsChanged([
            {
              wid: this.props.id,
              view: this.props.view,
              style: {
                top: this.refService.current.style.top,
                left: this.refService.current.style.left,
                width: this.refService.current.style.width,
                height: this.refService.current.style.height
              }
            }
          ]);
          this.movement = void 0;
        }
      } else if (x === void 0) {
        if (this.state.draggable === false) {
          return;
        }
        this.movement = {
          top: this.refService.current.offsetTop,
          left: this.refService.current.offsetLeft,
          order: [
            ...this.props.relativeWidgetOrder
          ],
          width: 0,
          height: 0
        };
        const resizers = this.refService.current.querySelectorAll(".vis-editmode-resizer");
        resizers.forEach((item) => item.style.display = "none");
        if (this.props.isRelative) {
          this.createWidgetMovementShadow();
        }
      } else if (this.movement && y !== void 0 && x !== void 0) {
        const left = `${this.movement.left + x}px`;
        const top = `${this.movement.top + y}px`;
        if (this.refService.current) {
          this.refService.current.style.left = left;
          this.refService.current.style.top = top;
        }
        if (this.widDiv) {
          this.widDiv.style.left = left;
          this.widDiv.style.top = top;
          if (this.widDiv._customHandlers && this.widDiv._customHandlers.onMove) {
            this.widDiv._customHandlers.onMove(this.widDiv, this.props.id);
          }
        }
        if (this.props.isRelative && calculateRelativeWidgetPosition) {
          calculateRelativeWidgetPosition(this.props.id, left, top, this.shadowDiv, this.movement.order);
        }
        if (save) {
          const resizers = this.refService.current.querySelectorAll(".vis-editmode-resizer");
          resizers.forEach((item) => item.style.display = "block");
          if (this.props.isRelative) {
            let parentDiv;
            if (Object.prototype.hasOwnProperty.call(this.props.refParent, "current")) {
              parentDiv = this.props.refParent.current;
            } else {
              parentDiv = this.props.refParent;
            }
            if (this.widDiv) {
              this.widDiv.style.position = "relative";
              this.widDiv.style.top = "0";
              this.widDiv.style.left = "0";
              parentDiv.insertBefore(this.widDiv, this.shadowDiv);
              this.refService.current.style.top = `${this.widDiv.offsetTop}px`;
              this.refService.current.style.left = `${this.widDiv.offsetLeft}px`;
            } else {
              parentDiv.insertBefore(this.refService.current, this.shadowDiv);
              this.refService.current.style.position = "relative";
              this.refService.current.style.top = "0";
              this.refService.current.style.left = "0";
            }
            this.shadowDiv.remove();
            this.shadowDiv = null;
            this.props.context.onWidgetsChanged([
              {
                wid: this.props.id,
                view: this.props.view,
                style: {
                  left: null,
                  top: null
                }
              }
            ], this.props.view, {
              order: this.movement.order
            });
          } else {
            this.props.context.onWidgetsChanged([
              {
                wid: this.props.id,
                view: this.props.view,
                style: {
                  left: this.movement.left + x,
                  top: this.movement.top + y
                }
              }
            ]);
          }
          this.movement = void 0;
        }
      }
    };
    onTempSelect = (selected) => {
      var _a;
      const ref = (_a = this.refService.current) == null ? void 0 : _a.querySelector(".vis-editmode-overlay");
      if (!ref) {
        return;
      }
      if (selected === null || selected === void 0) {
        if (this.props.selectedWidgets.includes(this.props.id)) {
          if (!ref.className.includes("vis-editmode-selected")) {
            ref.className = addClass("vis-editmode-selected", ref.className);
          }
        } else {
          ref.style.backgroundColor = "";
          ref.className = removeClass(ref.className, "vis-editmode-selected");
        }
      } else if (selected) {
        if (!ref.className.includes("vis-editmode-selected")) {
          ref.className = addClass("vis-editmode-selected", ref.className);
        }
      } else {
        ref.className = removeClass(ref.className, "vis-editmode-selected");
      }
    };
    onResizeStart(e, type) {
      e.stopPropagation();
      this.resize = type;
      this.props.mouseDownOnView(e, this.props.id, this.props.isRelative, true);
    }
    getResizeHandlers(selected, widget, borderWidth) {
      var _a;
      if (!this.state.editMode || !selected || ((_a = this.props.selectedWidgets) == null ? void 0 : _a.length) !== 1) {
        return null;
      }
      const thickness = 0.4;
      const shift = 0.3;
      const square = 0.4;
      const squareShift = `calc(${shift - square}em - ${borderWidth})`;
      const squareWidthHeight = `${square}em`;
      const shiftEm = `${shift}em`;
      const thicknessEm = `${thickness}em`;
      const offsetEm = `calc(${shift - thickness}em - ${borderWidth})`;
      const widgetWidth100 = widget.style.width === "100%";
      const widgetHeight100 = widget.style.height === "100%";
      const color = "#014488";
      const border = `0.1em dashed ${color}`;
      const borderDisabled = "0.1em dashed #888";
      const resizable = this.isResizable();
      let resizeHandlers = resizable && this.state.resizeHandles ? this.state.resizeHandles : [];
      if (resizable && this.props.selectedGroup && this.props.selectedGroup === this.props.id) {
        resizeHandlers = [
          "s",
          "e",
          "se"
        ];
      }
      const RESIZERS_OPACITY = 0.9;
      const RESIZERS_OPACITY_DISABLED = 0.5;
      const isRelative = widget.usedInWidget || this.props.isRelative;
      const controllable = {
        top: !isRelative && resizeHandlers.includes("n"),
        bottom: !widget.usedInWidget && !widgetHeight100 && resizeHandlers.includes("s"),
        left: !isRelative && resizeHandlers.includes("w"),
        right: !widget.usedInWidget && !widgetWidth100 && resizeHandlers.includes("e"),
        "top-left": !widgetHeight100 && !widgetWidth100 && !isRelative && resizeHandlers.includes("nw"),
        "top-right": !widgetHeight100 && !widgetWidth100 && !isRelative && resizeHandlers.includes("ne"),
        "bottom-left": !widgetHeight100 && !widgetWidth100 && !isRelative && resizeHandlers.includes("sw"),
        "bottom-right": !widgetHeight100 && !widgetWidth100 && !widget.usedInWidget && resizeHandlers.includes("se")
      };
      const handlers = {
        top: {
          top: offsetEm,
          height: thicknessEm,
          left: controllable["top-left"] ? shiftEm : 0,
          right: controllable["top-right"] ? shiftEm : 0,
          cursor: "ns-resize",
          background: "transparent",
          opacity: controllable.top ? RESIZERS_OPACITY : RESIZERS_OPACITY_DISABLED,
          borderTop: controllable.top ? border : borderDisabled
        },
        bottom: {
          bottom: offsetEm,
          height: thicknessEm,
          left: controllable["bottom-left"] ? shiftEm : 0,
          right: controllable["bottom-right"] ? shiftEm : 0,
          cursor: "ns-resize",
          background: "transparent",
          opacity: controllable.bottom ? RESIZERS_OPACITY : RESIZERS_OPACITY_DISABLED,
          borderBottom: controllable.bottom ? border : borderDisabled
        },
        left: {
          top: controllable["top-left"] ? shiftEm : 0,
          bottom: controllable["bottom-left"] ? shiftEm : 0,
          left: offsetEm,
          width: thicknessEm,
          cursor: "ew-resize",
          background: "transparent",
          opacity: controllable.left ? RESIZERS_OPACITY : RESIZERS_OPACITY_DISABLED,
          borderLeft: controllable.left ? border : borderDisabled
        },
        right: {
          top: controllable["top-right"] ? shiftEm : 0,
          bottom: controllable["bottom-right"] ? shiftEm : 0,
          right: offsetEm,
          width: thicknessEm,
          cursor: "ew-resize",
          background: "transparent",
          opacity: controllable.right ? RESIZERS_OPACITY : RESIZERS_OPACITY_DISABLED,
          borderRight: controllable.right ? border : borderDisabled
        },
        "top-left": {
          top: squareShift,
          height: squareWidthHeight,
          left: squareShift,
          width: squareWidthHeight,
          cursor: "nwse-resize",
          background: color,
          opacity: RESIZERS_OPACITY
        },
        "top-right": {
          top: squareShift,
          height: squareWidthHeight,
          right: squareShift,
          width: squareWidthHeight,
          cursor: "nesw-resize",
          background: color,
          opacity: RESIZERS_OPACITY
        },
        "bottom-left": {
          bottom: squareShift,
          height: squareWidthHeight,
          left: squareShift,
          width: squareWidthHeight,
          cursor: "nesw-resize",
          background: color,
          opacity: RESIZERS_OPACITY
        },
        "bottom-right": {
          bottom: squareShift,
          height: squareWidthHeight,
          right: squareShift,
          width: squareWidthHeight,
          cursor: "nwse-resize",
          background: color,
          opacity: RESIZERS_OPACITY
        }
      };
      const style = {
        position: "absolute",
        zIndex: 1001
      };
      return Object.keys(handlers).map((key) => {
        const handler = handlers[key];
        if (!controllable[key]) {
          if (key.includes("-")) {
            return null;
          }
          handler.cursor = "default";
        }
        return jsxRuntimeExports.jsx("div", {
          className: "vis-editmode-resizer",
          style: Object.assign(handler, style),
          onMouseDown: handler.opacity === RESIZERS_OPACITY ? (e) => this.onResizeStart(e, key) : void 0
        }, key);
      });
    }
    isUserMemberOfGroup(user, userGroups) {
      if (!userGroups) {
        return true;
      }
      if (!Array.isArray(userGroups)) {
        userGroups = [
          userGroups
        ];
      }
      return !!userGroups.find((groupId) => {
        var _a, _b;
        const group = this.props.context.userGroups[`system.group.${groupId}`];
        return ((_b = (_a = group == null ? void 0 : group.common) == null ? void 0 : _a.members) == null ? void 0 : _b.length) && group.common.members.includes(`system.user.${user}`);
      });
    }
    static isWidgetFilteredOutStatic(viewsActiveFilter, widgetData, view, editMode) {
      if (!viewsActiveFilter) {
        console.warn(`viewsActiveFilter is not defined in ${view}, data: ${JSON.stringify(widgetData)}`);
        return false;
      }
      const vf = viewsActiveFilter[view];
      if (!editMode && (widgetData == null ? void 0 : widgetData.filterkey) && (vf == null ? void 0 : vf.length)) {
        if (vf[0] === "$") {
          return true;
        }
        let filterKeys;
        if (typeof widgetData.filterkey === "string") {
          filterKeys = widgetData.filterkey.split(",").map((f) => f.trim()).filter((f) => f);
        } else {
          filterKeys = widgetData.filterkey;
        }
        for (let f = 0; f < filterKeys.length; f++) {
          if (vf.includes(filterKeys[f])) {
            return false;
          }
        }
        return true;
      }
      return false;
    }
    isWidgetFilteredOut(widgetData) {
      return VisBaseWidget.isWidgetFilteredOutStatic(this.props.viewsActiveFilter, widgetData, this.props.view, this.state.editMode);
    }
    static isWidgetHidden(widgetData, states, id) {
      const oid = widgetData["visibility-oid"];
      const condition = widgetData["visibility-cond"];
      if (oid) {
        if (!Object.keys(states).includes(`${oid}.val`)) {
          return true;
        }
        let val = states[`${oid}.val`];
        if (val === void 0 || val === null) {
          return condition === "not exist";
        }
        let value = widgetData["visibility-val"];
        if (!condition || value === void 0 || value === null) {
          return condition === "not exist";
        }
        if (val === "null" && condition !== "exist" && condition !== "not exist") {
          return false;
        }
        const t = typeof val;
        if (t === "boolean" || val === "false" || val === "true") {
          value = value === "true" || value === true || value === 1 || value === "1";
        } else if (t === "number") {
          value = parseFloat(value);
        } else if (t === "object") {
          val = JSON.stringify(val);
        }
        switch (condition) {
          case "==":
            value = value.toString();
            val = val.toString();
            if (val === "1") {
              val = "true";
            }
            if (value === "1") {
              value = "true";
            }
            if (val === "0") {
              val = "false";
            }
            if (value === "0") {
              value = "false";
            }
            return value !== val;
          case "!=":
            value = value.toString();
            val = val.toString();
            if (val === "1") {
              val = "true";
            }
            if (value === "1") {
              value = "true";
            }
            if (val === "0") {
              val = "false";
            }
            if (value === "0") {
              value = "false";
            }
            return value === val;
          case ">=":
            return val < value;
          case "<=":
            return val > value;
          case ">":
            return val <= value;
          case "<":
            return val >= value;
          case "consist":
            value = value.toString();
            val = val.toString();
            return !val.toString().includes(value);
          case "not consist":
            value = value.toString();
            val = val.toString();
            return val.toString().includes(value);
          case "exist":
            return val === "null";
          case "not exist":
            return val !== "null";
          default:
            console.log(`[${id}] Unknown visibility condition: ${condition}`);
            return false;
        }
      } else {
        return condition && condition === "not exist";
      }
    }
    renderWidgetBody(_props) {
      var _a;
      if (((_a = this.props.context.views.___settings) == null ? void 0 : _a.ignoreNotLoaded) && !this.state.editMode) {
        return null;
      }
      return jsxRuntimeExports.jsxs("div", {
        style: {
          width: "100%",
          height: "100%",
          overflow: "hidden",
          background: "repeating-linear-gradient(45deg, #333, #333 10px, #666 10px, #666 20px)",
          color: "#FFF"
        },
        children: [
          jsxRuntimeExports.jsx("div", {
            style: {
              color: "#FF0000",
              paddingLeft: 10
            },
            children: __mf_2.t('Unknown widget type "%s"', this.props.tpl)
          }),
          jsxRuntimeExports.jsx("pre", {
            children: JSON.stringify(this.state.data, null, 2)
          })
        ]
      });
    }
    changeOrder(e, dir) {
      e.stopPropagation();
      e.preventDefault();
      if (this.state.multiViewWidget || !this.state.editMode) {
        return;
      }
      const order = [
        ...this.props.relativeWidgetOrder
      ];
      const pos = order.indexOf(this.props.id);
      if (dir > 0) {
        if (pos === order.length - 1) {
          return;
        }
        const nextId = order[pos + 1];
        order[pos + 1] = this.props.id;
        order[pos] = nextId;
      } else if (!pos) {
        return;
      } else {
        const nextId = order[pos - 1];
        order[pos - 1] = this.props.id;
        order[pos] = nextId;
      }
      this.props.context.onWidgetsChanged(null, this.props.view, {
        order
      });
    }
    static formatValue(value, decimals, _format) {
      if (typeof decimals !== "number") {
        decimals = 2;
        _format = decimals;
      }
      const format = _format === void 0 ? ".," : _format;
      if (typeof value !== "number") {
        value = parseFloat(value);
      }
      return Number.isNaN(value) ? "" : value.toFixed(decimals || 0).replace(format[0], format[1]).replace(/\B(?=(\d{3})+(?!\d))/g, format[0]);
    }
    formatIntervalHelper(value, type) {
      let singular;
      let plural;
      let special24;
      if (this.props.context.lang === "de") {
        if (type === "seconds") {
          singular = "Sekunde";
          plural = "Sekunden";
        } else if (type === "minutes") {
          singular = "Minute";
          plural = "Minuten";
        } else if (type === "hours") {
          singular = "Stunde";
          plural = "Stunden";
        } else if (type === "days") {
          singular = "Tag";
          plural = "Tagen";
        }
      } else if (this.props.context.lang === "ru") {
        if (type === "seconds") {
          singular = "\u0441\u0435\u043A\u0443\u043D\u0434\u0443";
          plural = "\u0441\u0435\u043A\u0443\u043D\u0434";
          special24 = "\u0441\u0435\u043A\u0443\u043D\u0434\u044B";
        } else if (type === "minutes") {
          singular = "\u043C\u0438\u043D\u0443\u0442\u0443";
          plural = "\u043C\u0438\u043D\u0443\u0442";
          special24 = "\u043C\u0438\u043D\u0443\u0442\u044B";
        } else if (type === "hours") {
          singular = "\u0447\u0430\u0441";
          plural = "\u0447\u0430\u0441\u043E\u0432";
          special24 = "\u0447\u0430\u0441\u0430";
        } else if (type === "days") {
          singular = "\u0434\u0435\u043D\u044C";
          plural = "\u0434\u043D\u0435\u0439";
          special24 = "\u0434\u043D\u044F";
        }
      } else if (type === "seconds") {
        singular = "second";
        plural = "seconds";
      } else if (type === "minutes") {
        singular = "minute";
        plural = "minutes";
      } else if (type === "hours") {
        singular = "hour";
        plural = "hours";
      } else if (type === "days") {
        singular = "day";
        plural = "days";
      }
      if (value === 1) {
        if (this.props.context.lang === "de") {
          if (type === "days") {
            return `einem ${singular}`;
          }
          return `einer ${singular}`;
        }
        if (this.props.context.lang === "ru") {
          if (type === "days" || type === "hours") {
            return `\u043E\u0434\u0438\u043D ${singular}`;
          }
          return `\u043E\u0434\u043D\u0443 ${singular}`;
        }
        return `one ${singular}`;
      }
      if (this.props.context.lang === "de") {
        return `${value} ${plural}`;
      }
      if (this.props.context.lang === "ru") {
        const d = value % 10;
        if (d === 1 && value !== 11) {
          return `${value} ${singular}`;
        }
        if (d >= 2 && d <= 4 && (value > 20 || value < 10)) {
          return `${value} ${special24}`;
        }
        return `${value} ${plural}`;
      }
      return `${value} ${plural}`;
    }
    formatInterval(timestamp, isMomentJs) {
      if (isMomentJs) {
        return this.props.context.moment(new Date(timestamp)).fromNow();
      }
      let diff = Date.now() - timestamp;
      diff = Math.round(diff / 1e3);
      let text;
      if (diff <= 60) {
        if (this.props.context.lang === "de") {
          text = `vor ${this.formatIntervalHelper(diff, "seconds")}`;
        } else if (this.props.context.lang === "ru") {
          text = `${this.formatIntervalHelper(diff, "seconds")} \u043D\u0430\u0437\u0430\u0434`;
        } else {
          text = `${this.formatIntervalHelper(diff, "seconds")} ago`;
        }
      } else if (diff < 3600) {
        const m = Math.floor(diff / 60);
        const s = diff - m * 60;
        text = "";
        if (this.props.context.lang === "de") {
          text = `vor ${this.formatIntervalHelper(m, "minutes")}`;
        } else if (this.props.context.lang === "ru") {
          text = this.formatIntervalHelper(m, "minutes");
        } else {
          text = this.formatIntervalHelper(m, "minutes");
        }
        if (m < 5) {
          if (this.props.context.lang === "de") {
            text += ` und ${this.formatIntervalHelper(s, "seconds")}`;
          } else if (this.props.context.lang === "ru") {
            text += ` \u0438 ${this.formatIntervalHelper(s, "seconds")}`;
          } else {
            text += ` and ${this.formatIntervalHelper(s, "seconds")}`;
          }
        }
        if (this.props.context.lang === "de") ;
        else if (this.props.context.lang === "ru") {
          text += " \u043D\u0430\u0437\u0430\u0434";
        } else {
          text += " ago";
        }
      } else if (diff < 3600 * 24) {
        const h = Math.floor(diff / 3600);
        const m = Math.floor((diff - h * 3600) / 60);
        text = "";
        if (this.props.context.lang === "de") {
          text = `vor ${this.formatIntervalHelper(h, "hours")}`;
        } else if (this.props.context.lang === "ru") {
          text = this.formatIntervalHelper(h, "hours");
        } else {
          text = this.formatIntervalHelper(h, "hours");
        }
        if (h < 10) {
          if (this.props.context.lang === "de") {
            text += ` und ${this.formatIntervalHelper(m, "minutes")}`;
          } else if (this.props.context.lang === "ru") {
            text += ` \u0438 ${this.formatIntervalHelper(m, "minutes")}`;
          } else {
            text += ` and ${this.formatIntervalHelper(m, "minutes")}`;
          }
        }
        if (this.props.context.lang === "de") ;
        else if (this.props.context.lang === "ru") {
          text += " \u043D\u0430\u0437\u0430\u0434";
        } else {
          text += " ago";
        }
      } else {
        const d = Math.floor(diff / (3600 * 24));
        const h = Math.floor((diff - d * (3600 * 24)) / 3600);
        text = "";
        if (this.props.context.lang === "de") {
          text = `vor ${this.formatIntervalHelper(d, "days")}`;
        } else if (this.props.context.lang === "ru") {
          text = this.formatIntervalHelper(d, "days");
        } else {
          text = this.formatIntervalHelper(d, "days");
        }
        if (d < 3) {
          if (this.props.context.lang === "de") {
            text += ` und ${this.formatIntervalHelper(h, "hours")}`;
          } else if (this.props.context.lang === "ru") {
            text += ` \u0438 ${this.formatIntervalHelper(h, "hours")}`;
          } else {
            text += ` and ${this.formatIntervalHelper(h, "hours")}`;
          }
        }
        if (this.props.context.lang === "de") ;
        else if (this.props.context.lang === "ru") {
          text += " \u043D\u0430\u0437\u0430\u0434";
        } else {
          text += " ago";
        }
      }
      return text;
    }
    startUpdateInterval() {
      this.updateInterval = this.updateInterval || setInterval(() => {
        var _a;
        const timeIntervalEl = (_a = this.widDiv || this.refService.current) == null ? void 0 : _a.querySelector(".time-interval");
        if (timeIntervalEl) {
          const time = parseInt(timeIntervalEl.dataset.time, 10);
          timeIntervalEl.innerHTML = this.formatInterval(time, timeIntervalEl.dataset.moment === "true");
        }
      }, 1e4);
    }
    formatDate(value, format, interval, isMomentJs, forRx) {
      if (typeof format === "boolean") {
        interval = format;
        format = "auto";
      }
      if (format === "auto") {
        format = `${this.props.context.dateFormat || "DD.MM.YYYY"} hh:mm:ss`;
      }
      format = format || this.props.context.dateFormat || "DD.MM.YYYY";
      if (!value) {
        return "";
      }
      let dateObj;
      const text = typeof value;
      if (text === "string") {
        dateObj = new Date(value);
      }
      if (text !== "object") {
        if (isVarFinite(value)) {
          const i = parseInt(value, 10);
          if (i > 9466812e5) {
            dateObj = new Date(value);
          } else {
            dateObj = new Date(value * 1e3);
          }
        } else {
          dateObj = new Date(value);
        }
      }
      if (interval) {
        this.startUpdateInterval();
        if (forRx) {
          return jsxRuntimeExports.jsx("span", {
            className: "time-interval",
            "data-time": dateObj.getTime(),
            "data-moment": isMomentJs || false,
            title: dateObj.toLocaleString(),
            children: this.formatInterval(dateObj.getTime(), isMomentJs)
          });
        }
        return `<span class="time-interval" data-time="${dateObj.getTime()}" data-moment="${isMomentJs || false}">${this.formatInterval(dateObj.getTime(), isMomentJs)}</span>`;
      }
      if (format.includes("YYYY") || format.includes("JJJJ") || format.includes("\u0413\u0413\u0413\u0413")) {
        const yearStr = dateObj.getFullYear().toString();
        format = format.replace("YYYY", yearStr);
        format = format.replace("JJJJ", yearStr);
        format = format.replace("\u0413\u0413\u0413\u0413", yearStr);
      } else if (format.includes("YY") || format.includes("JJ") || format.includes("\u0413\u0413")) {
        const yearStr = (dateObj.getFullYear() % 100).toString();
        format = format.replace("YY", yearStr);
        format = format.replace("JJ", yearStr);
        format = format.replace("\u0413\u0413", yearStr);
      }
      if (format.includes("MM") || format.includes("\u041C\u041C")) {
        const monthStr = (dateObj.getMonth() + 1).toString().padStart(2, "0");
        format = format.replace("MM", monthStr);
        format = format.replace("\u041C\u041C", monthStr);
      } else if (format.includes("M") || format.includes("\u041C")) {
        const monthStr = (dateObj.getMonth() + 1).toString();
        format = format.replace("M", monthStr);
        format = format.replace("\u041C", monthStr);
      }
      if (format.includes("DD") || format.includes("TT") || format.includes("\u0414\u0414")) {
        const dateStr = dateObj.getDate().toString().padStart(2, "0");
        format = format.replace("DD", dateStr);
        format = format.replace("TT", dateStr);
        format = format.replace("\u0414\u0414", dateStr);
      } else if (format.includes("D") || format.includes("TT") || format.includes("\u0414")) {
        const dateStr = dateObj.getDate().toString();
        format = format.replace("D", dateStr);
        format = format.replace("T", dateStr);
        format = format.replace("\u0414", dateStr);
      }
      if (format.includes("hh") || format.includes("SS") || format.includes("\u0447\u0447")) {
        const hoursStr = dateObj.getHours().toString().padStart(2, "0");
        format = format.replace("hh", hoursStr);
        format = format.replace("SS", hoursStr);
        format = format.replace("\u0447\u0447", hoursStr);
      } else if (format.includes("h") || format.includes("S") || format.includes("\u0447")) {
        const hoursStr = dateObj.getHours().toString();
        format = format.replace("h", hoursStr);
        format = format.replace("S", hoursStr);
        format = format.replace("\u0447", hoursStr);
      }
      if (format.includes("mm") || format.includes("\u043C\u043C")) {
        const minutesStr = dateObj.getMinutes().toString().padStart(2, "0");
        format = format.replace("mm", minutesStr);
        format = format.replace("\u043C\u043C", minutesStr);
      } else if (format.includes("m") || format.includes("\u043C")) {
        const minutesStr = dateObj.getMinutes().toString();
        format = format.replace("m", minutesStr);
        format = format.replace("v", minutesStr);
      }
      if (format.includes("sss") || format.includes("\u0441\u0441\u0441")) {
        const msStr = dateObj.getMilliseconds().toString().padStart(3, "0");
        format = format.replace("sss", msStr);
        format = format.replace("\u0441\u0441\u0441", msStr);
      }
      if (format.includes("ss") || format.includes("\u0441\u0441")) {
        const secondsStr = dateObj.getSeconds().toString().padStart(2, "0");
        format = format.replace("ss", secondsStr);
        format = format.replace("cc", secondsStr);
      } else if (format.includes("s") || format.includes("\u0441")) {
        const secondsStr = dateObj.getSeconds().toString();
        format = format.replace("s", secondsStr);
        format = format.replace("\u0441", secondsStr);
      }
      return format;
    }
    onToggleRelative(e) {
      e.stopPropagation();
      e.preventDefault();
      const widget = this.props.context.views[this.props.view].widgets[this.props.id];
      const width = this.props.isRelative ? widget.style.absoluteWidth || "100px" : "100%";
      this.props.context.onWidgetsChanged([
        {
          wid: this.props.id,
          view: this.props.view,
          style: {
            position: this.props.isRelative ? "absolute" : "relative",
            width,
            absoluteWidth: !this.props.isRelative ? widget.style.width : null,
            noPxToPercent: true
          }
        }
      ]);
    }
    onToggleWidth(e) {
      e.stopPropagation();
      e.preventDefault();
      const widget = this.props.context.views[this.props.view].widgets[this.props.id];
      this.props.context.onWidgetsChanged([
        {
          wid: this.props.id,
          view: this.props.view,
          style: {
            width: widget.style.width === "100%" ? widget.style.absoluteWidth || "100px" : "100%",
            absoluteWidth: widget.style.width !== "100%" ? widget.style.width : null,
            noPxToPercent: true
          }
        }
      ]);
    }
    onToggleLineBreak(e) {
      e.stopPropagation();
      e.preventDefault();
      const widget = this.props.context.views[this.props.view].widgets[this.props.id];
      this.props.context.onWidgetsChanged([
        {
          wid: this.props.id,
          view: this.props.view,
          style: {
            newLine: !widget.style.newLine
          }
        }
      ]);
    }
    static correctStylePxValue(value) {
      if (typeof value === "string") {
        if (isVarFinite(value)) {
          return parseFloat(value) || 0;
        }
      }
      return value;
    }
    renderRelativeMoveMenu() {
      if (this.props.context.runtime || !this.state.editMode) {
        return null;
      }
      return jsxRuntimeExports.jsx(React.Suspense, {
        fallback: null,
        children: jsxRuntimeExports.jsx(VisOrderMenu, {
          anchorEl: this.state.showRelativeMoveMenu ? this.relativeMoveMenu : void 0,
          order: this.props.relativeWidgetOrder,
          wid: this.props.id,
          view: this.props.view,
          views: this.props.context.views,
          themeType: this.props.context.themeType,
          onClose: (order) => {
            this.props.onIgnoreMouseEvents(false);
            this.setState({
              showRelativeMoveMenu: false
            });
            order && this.props.context.onWidgetsChanged(null, this.props.view, {
              order
            });
          }
        })
      });
    }
    render() {
      var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
      const widget = this.props.context.views[this.props.view].widgets[this.props.id];
      if (!widget || typeof widget !== "object") {
        console.error(`EMPTY Widget: ${this.props.id}`);
        return null;
      }
      const style = {
        boxSizing: "border-box"
      };
      const selected = !this.state.multiViewWidget && this.state.editMode && ((_a = this.props.selectedWidgets) == null ? void 0 : _a.includes(this.props.id));
      const classNames = selected ? [
        "vis-editmode-selected"
      ] : [
        "vis-editmode-overlay-not-selected"
      ];
      if (selected && this.state.widgetHint === "hide") {
        classNames.push("vis-editmode-selected-background");
      }
      if (this.state.editMode && !(widget.groupid && !this.props.selectedGroup)) {
        if (!this.props.isRelative && Object.prototype.hasOwnProperty.call(this.state.style, "top")) {
          style.top = VisBaseWidget.correctStylePxValue(this.state.style.top);
        }
        if (!this.props.isRelative && Object.prototype.hasOwnProperty.call(this.state.style, "left")) {
          style.left = VisBaseWidget.correctStylePxValue(this.state.style.left);
        }
        if (Object.prototype.hasOwnProperty.call(this.state.style, "width")) {
          style.width = VisBaseWidget.correctStylePxValue(this.state.style.width);
        }
        if (Object.prototype.hasOwnProperty.call(this.state.style, "height")) {
          style.height = VisBaseWidget.correctStylePxValue(this.state.style.height);
        }
        if (!this.props.isRelative && Object.prototype.hasOwnProperty.call(this.state.style, "right")) {
          style.right = VisBaseWidget.correctStylePxValue(this.state.style.right);
        }
        if (!this.props.isRelative && Object.prototype.hasOwnProperty.call(this.state.style, "bottom")) {
          style.bottom = VisBaseWidget.correctStylePxValue(this.state.style.bottom);
        }
        style.position = this.props.isRelative ? "relative" : "absolute";
        style.userSelect = "none";
        if (selected) {
          if (this.props.moveAllowed && this.state.draggable !== false && !this.props.isRelative && (!this.props.selectedGroup || this.props.selectedGroup !== this.props.id)) {
            style.cursor = "move";
          } else {
            style.cursor = "default";
          }
        } else if ((_b = widget.data) == null ? void 0 : _b.locked) {
          style.cursor = "default";
        } else if (this.props.selectedGroup !== this.props.id && !this.state.multiViewWidget) {
          style.cursor = "pointer";
        }
        if ((_c = this.props.tpl) == null ? void 0 : _c.toLowerCase().includes("image")) {
          classNames.push("vis-editmode-helper");
        }
      }
      const props = {
        className: "",
        overlayClassNames: classNames,
        style,
        id: `rx_${this.props.id}`,
        refService: this.refService,
        widget
      };
      let doNotTakeWidth = false;
      let doNotTakeHeight = false;
      if (this.visDynamicResizable && !this.isResizable()) {
        if (this.visDynamicResizable.desiredSize === false) {
          doNotTakeWidth = true;
          doNotTakeHeight = true;
          delete style.width;
          delete style.height;
        } else if (typeof this.visDynamicResizable.desiredSize === "object") {
          if (this.state.style.width) {
            style.width = VisBaseWidget.correctStylePxValue(this.visDynamicResizable.desiredSize.width);
          } else {
            doNotTakeWidth = true;
            delete style.width;
          }
          if (this.state.style.height) {
            style.height = VisBaseWidget.correctStylePxValue(this.visDynamicResizable.desiredSize.height);
          } else {
            doNotTakeHeight = true;
            delete style.height;
          }
        }
      }
      if (this.props.isRelative && isVarFinite((_d = this.props.context.views[this.props.view].settings) == null ? void 0 : _d.rowGap)) {
        style.marginBottom = parseFloat((_e = this.props.context.views[this.props.view].settings) == null ? void 0 : _e.rowGap) || 0;
      }
      const rxWidget = this.renderWidgetBody(props);
      if (doNotTakeWidth) {
        delete style.width;
      }
      if (doNotTakeHeight) {
        delete style.height;
      }
      if (this.props.id === this.props.selectedGroup) {
        style.top = 0;
        style.left = 0;
      }
      if (!this.props.isRelative) {
        style.top = style.top || 0;
        style.left = style.left || 0;
      }
      [
        "top",
        "left",
        "width",
        "height",
        "right",
        "bottom",
        "fontSize",
        "borderRadius",
        "paddingLeft",
        "paddingTop",
        "paddingRight",
        "paddingBottom",
        "marginTop",
        "marginBottom",
        "marginLeft",
        "marginRight",
        "borderWidth"
      ].forEach((attr) => {
        var _a2, _b2, _c2;
        const anyStyle = style;
        if (anyStyle[attr] !== void 0 && typeof anyStyle[attr] === "string") {
          if (isVarFinite(anyStyle[attr])) {
            anyStyle[attr] = parseFloat(anyStyle[attr]) || 0;
          } else if (anyStyle[attr].includes("{")) {
            const value = (_a2 = this.state.rxStyle) == null ? void 0 : _a2[attr];
            if (this.state.rxStyle && value !== void 0) {
              if (value && typeof value === "string" && !value.includes("{")) {
                anyStyle[attr] = VisBaseWidget.correctStylePxValue(value);
              }
            } else {
              const styleVal = (_c2 = (_b2 = this.props.context.allWidgets[this.props.id]) == null ? void 0 : _b2.style) == null ? void 0 : _c2[attr];
              if (styleVal !== void 0 && styleVal !== null) {
                if (!styleVal.toString().includes("{")) {
                  anyStyle[attr] = VisBaseWidget.correctStylePxValue(styleVal);
                }
              }
            }
          }
        }
      });
      classNames.push("vis-editmode-overlay");
      let widgetName = null;
      let widgetMoveButtons = null;
      const borderWidth = (typeof style.borderWidth === "number" ? `${style.borderWidth}px` : style.borderWidth) || "0px";
      if (this.state.widgetHint !== "hide" && !this.state.hideHelper && this.state.editMode && (!widget.groupid || this.props.selectedGroup) && this.props.selectedGroup !== this.props.id && this.props.context.showWidgetNames !== false) {
        const widgetNameBottom = !widget.usedInWidget && (((_f = this.refService.current) == null ? void 0 : _f.offsetTop) === 0 || ((_g = this.refService.current) == null ? void 0 : _g.offsetTop) && ((_h = this.refService.current) == null ? void 0 : _h.offsetTop) < 15);
        if (!this.refService.current) {
          setTimeout(() => this.forceUpdate(), 50);
        }
        let multiView = null;
        let multiId = null;
        if (this.state.multiViewWidget) {
          const lastUnderscore = this.props.id.lastIndexOf("_");
          multiView = this.props.id.substring(1, lastUnderscore);
          multiId = this.props.id.substring(lastUnderscore + 1);
        }
        const resizable = !widget.usedInWidget && this.isResizable();
        widgetName = jsxRuntimeExports.jsxs("div", {
          title: this.state.multiViewWidget ? __mf_2.t("Jump to widget by double click") : this.props.tpl === "_tplGroup" ? __mf_2.t("Switch to group edit mode by double click") : void 0,
          className: __mf_70.clsx("vis-editmode-widget-name", selected && "vis-editmode-widget-name-selected", this.state.widgetHint, widgetNameBottom && "vis-editmode-widget-name-bottom", this.props.isRelative && resizable && "vis-editmode-widget-name-long"),
          style: {
            top: widgetNameBottom ? void 0 : `calc(-14px - ${borderWidth})`
          },
          onMouseDown: (e) => {
            if (this.props.context.setSelectedWidgets) {
              this.onMouseDown(e);
            }
          },
          children: [
            jsxRuntimeExports.jsx("span", {
              children: this.state.multiViewWidget ? __mf_2.t("%s from %s", multiId, multiView) : ((_i = widget.data) == null ? void 0 : _i.name) || this.props.id
            }),
            this.state.multiViewWidget || widget.usedInWidget ? null : jsxRuntimeExports.jsx(__mf_410, {
              onMouseDown: (e) => this.onToggleRelative(e),
              className: __mf_70.clsx("vis-anchor", this.props.isRelative ? "vis-anchor-enabled" : "vis-anchor-disabled")
            }),
            this.state.multiViewWidget || !this.props.isRelative || !resizable || widget.usedInWidget ? null : jsxRuntimeExports.jsx(__mf_3181, {
              onMouseDown: (e) => this.onToggleWidth(e),
              className: __mf_70.clsx("vis-expand", widget.style.width === "100%" ? "vis-expand-enabled" : "vis-expand-disabled")
            }),
            this.state.multiViewWidget || !this.props.isRelative || widget.usedInWidget ? null : jsxRuntimeExports.jsx(__mf_4885, {
              onMouseDown: (e) => this.onToggleLineBreak(e),
              className: __mf_70.clsx("vis-new-line", widget.style.newLine ? "vis-new-line-enabled" : "vis-new-line-disabled")
            })
          ]
        });
        if (this.props.isRelative && !this.state.multiViewWidget && !widget.usedInWidget) {
          const pos = this.props.relativeWidgetOrder.indexOf(this.props.id);
          const showUp = !!pos;
          let showDown = pos !== this.props.relativeWidgetOrder.length - 1;
          if (showDown && this.props.selectedGroup) {
            const widget__ = this.props.context.views[this.props.view].widgets[this.props.relativeWidgetOrder[pos + 1]];
            if (widget__.style.position === "absolute") {
              showDown = false;
            }
          }
          if (showUp || showDown) {
            widgetMoveButtons = jsxRuntimeExports.jsxs("div", {
              className: __mf_70.clsx("vis-editmode-widget-move-buttons", this.state.widgetHint, widgetNameBottom && "vis-editmode-widget-name-bottom"),
              style: {
                width: !showUp || !showDown ? 30 : void 0
              },
              children: [
                jsxRuntimeExports.jsx("div", {
                  className: "vis-editmode-widget-number",
                  children: this.props.relativeWidgetOrder.indexOf(this.props.id) + 1
                }),
                showUp ? jsxRuntimeExports.jsx("div", {
                  className: "vis-editmode-move-button",
                  title: __mf_2.t("Move widget up or press longer to open re-order menu"),
                  children: jsxRuntimeExports.jsx(__mf_576, {
                    onMouseDown: (e) => {
                      e.stopPropagation();
                      e.preventDefault();
                      this.pressTimeout = setTimeout((target) => {
                        this.props.onIgnoreMouseEvents(true);
                        this.relativeMoveMenu = target;
                        this.setState({
                          showRelativeMoveMenu: true
                        });
                        this.pressTimeout = void 0;
                      }, 300, e.currentTarget);
                    },
                    onMouseUp: (e) => this.changeOrder(e, -1)
                  })
                }) : null,
                showDown ? jsxRuntimeExports.jsx("div", {
                  className: "vis-editmode-move-button",
                  style: {
                    left: showUp ? 30 : void 0
                  },
                  title: __mf_2.t("Move widget down or press longer to open re-order menu"),
                  children: jsxRuntimeExports.jsx(__mf_526, {
                    onMouseDown: (e) => {
                      e.stopPropagation();
                      e.preventDefault();
                      this.pressTimeout = setTimeout((target) => {
                        this.props.onIgnoreMouseEvents(true);
                        this.relativeMoveMenu = target;
                        this.setState({
                          showRelativeMoveMenu: true
                        });
                        this.pressTimeout = void 0;
                      }, 300, e.currentTarget);
                    },
                    onMouseUp: (e) => this.changeOrder(e, 1)
                  })
                }) : null
              ]
            });
          }
        }
        calculateOverflow(style);
      }
      if (!this.isCanWidget && this.state.multiViewWidget && this.state.editMode) {
        if (style.opacity === void 0 || style.opacity === null || style.opacity > 0.5) {
          style.opacity = 0.5;
        }
      }
      const overlay = !this.state.hideHelper && !widget.usedInWidget && this.state.editMode && !widget.data.locked && (!widget.groupid || this.props.selectedGroup) && this.props.selectedGroup !== this.props.id ? jsxRuntimeExports.jsx("div", {
        className: classNames.join(" "),
        onMouseDown: (e) => {
          if (this.props.context.setSelectedWidgets) {
            this.onMouseDown(e);
          }
        }
      }) : null;
      let groupInstructions = null;
      if (this.props.selectedGroup === this.props.id) {
        style.borderBottom = "1px dotted #888";
        style.borderRight = "1px dotted #888";
        groupInstructions = jsxRuntimeExports.jsx("div", {
          style: {
            position: "absolute",
            bottom: -24,
            left: 0,
            fontSize: 10,
            fontStyle: "italic",
            opacity: 0.5,
            width: 350,
            cursor: "pointer"
          },
          onClick: (e) => {
            e.stopPropagation();
            this.props.context.setSelectedWidgets([
              this.props.id
            ]);
          },
          children: __mf_2.t("group_size_hint")
        });
      }
      const signals = ((_j = this.renderSignals) == null ? void 0 : _j.call(this)) || null;
      const lastChange = ((_k = this.renderLastChange) == null ? void 0 : _k.call(this, style)) || null;
      return jsxRuntimeExports.jsxs("div", {
        id: props.id,
        className: props.className,
        ref: this.refService,
        style,
        children: [
          signals,
          lastChange,
          widgetName,
          widgetMoveButtons,
          overlay,
          this.getResizeHandlers(selected, widget, borderWidth),
          rxWidget,
          groupInstructions,
          this.state.showRelativeMoveMenu && this.renderRelativeMoveMenu()
        ]
      });
    }
  };
  const POSSIBLE_MUI_STYLES = [
    "background",
    "background-clip",
    "background-color",
    "background-image",
    "background-origin",
    "background-position",
    "background-repeat",
    "background-size",
    "border",
    "border-color",
    "border-radius",
    "border-style",
    "border-width",
    "box-shadow",
    "box-sizing",
    "color",
    "font-family",
    "font-size",
    "font-style",
    "font-variant",
    "font-weight",
    "letter-spacing",
    "line-height",
    "text-align",
    "text-shadow",
    "word-spacing"
  ];
  VisRxWidget = class extends VisBaseWidget {
    static POSSIBLE_MUI_STYLES = POSSIBLE_MUI_STYLES;
    linkContext;
    onStateChangedBind;
    newState;
    wrappedContent;
    updateTimer;
    ignoreMouseEvents;
    mouseDownOnView;
    bindingsTimer;
    informIncludedWidgets;
    filterDisplay;
    localStateChangeCb;
    constructor(props) {
      var _a;
      super(props);
      const options = this.getWidgetInfo();
      const widgetAttrInfo = {};
      if (Array.isArray(options.visAttrs)) {
        options.visAttrs.forEach((group) => {
          var _a2;
          return (_a2 = group.fields) == null ? void 0 : _a2.forEach((item) => {
            widgetAttrInfo[item.name] = {
              name: item.name,
              type: item.type
            };
            if (!widgetAttrInfo[item.name].type) {
              widgetAttrInfo[item.name].type = "";
            }
          });
        });
      }
      this.linkContext = {
        IDs: [],
        bindings: {},
        visibility: {},
        lastChanges: {},
        signals: {},
        widgetAttrInfo
      };
      getUsedObjectIDsInWidget(props.context.views, props.view, props.id, this.linkContext);
      this.onStateChangedBind = this.onStateChanged.bind(this);
      const newState = this.onStateChanged(null, null, true);
      if (newState) {
        newState.visible = this.checkVisibility((_a = newState.rxData) == null ? void 0 : _a["visibility-oid"], newState);
      }
      this.resizeLocked = !!options.visResizeLocked;
      const visResizable = VisRxWidget.findField(options, "visResizable");
      if (visResizable) {
        this.visDynamicResizable = {
          default: visResizable.default !== void 0 ? visResizable.default : true,
          desiredSize: visResizable.desiredSize
        };
      } else {
        this.visDynamicResizable = null;
      }
      this.state = {
        ...this.state,
        resizable: options.resizable === void 0 ? options.visResizable === void 0 ? true : options.visResizable : options.resizable,
        draggable: options.visDraggable === void 0 ? true : options.visDraggable,
        resizeHandles: options.resizeHandles === void 0 ? options.visResizeHandles === void 0 ? [
          "n",
          "e",
          "s",
          "w",
          "nw",
          "ne",
          "sw",
          "se"
        ] : options.visResizeHandles : options.resizeHandles,
        rxData: newState.rxData,
        rxStyle: newState.rxStyle,
        values: {},
        visible: newState.visible,
        disabled: false
      };
    }
    static findField(widgetInfo, name) {
      if (!widgetInfo.visAttrs) {
        return null;
      }
      for (let g = 0; g < widgetInfo.visAttrs.length; g++) {
        const group = widgetInfo.visAttrs[g];
        if (group.fields) {
          for (let f = 0; f < group.fields.length; f++) {
            if (group.fields[f].name === name) {
              return group.fields[f];
            }
          }
        }
      }
      return null;
    }
    static getI18nPrefix() {
      return "";
    }
    static getText(text) {
      if (typeof text === "object") {
        return text[__mf_2.getLanguage()] || text.en;
      }
      return text;
    }
    static t(key, ...args) {
      if (this.getI18nPrefix) {
        return __mf_2.t(`${this.getI18nPrefix()}${key}`, ...args);
      }
      return __mf_2.t(key);
    }
    static getLanguage() {
      return __mf_2.getLanguage();
    }
    onCommand(command, _option) {
      var _a;
      const result = super.onCommand(command);
      if (result === false) {
        if (command === "collectFilters") {
          return (_a = this.state.rxData) == null ? void 0 : _a.filterkey;
        }
        if (command === "changeFilter") {
          const visible = this.checkVisibility();
          if (visible !== this.state.visible) {
            this.setState({
              visible
            });
          }
        }
      }
      return result;
    }
    onStateUpdated(_id, _state) {
    }
    onIoBrokerStateChanged = (id, state) => {
      this.onStateChanged(id, state);
    };
    onStateChanged(id, state, doNotApplyState) {
      var _a;
      if (!this.newState) {
        this.newState = {
          values: deepClone(this.state.values || {}),
          rxData: {
            ...this.state.data
          },
          rxStyle: {
            ...this.state.style
          },
          editMode: this.props.editMode,
          applyBindings: false
        };
      }
      if (!this.newState) {
        return null;
      }
      if (this.newState.rxData) {
        delete this.newState.rxData._originalData;
      }
      if (this.newState.rxStyle) {
        delete this.newState.rxStyle._originalData;
      }
      if (id && state) {
        Object.keys(state).forEach((attr) => this.newState.values[`${id}.${attr}`] = state[attr]);
        setTimeout(() => this.onStateUpdated(id, state), 60);
      }
      Object.keys(this.linkContext.bindings).forEach((_id) => this.applyBinding(_id, this.newState));
      if (id === ((_a = this.newState.rxData) == null ? void 0 : _a["visibility-oid"])) {
        this.newState.visible = this.checkVisibility(id, this.newState);
      }
      if (this.newState.rxData) {
        const userGroups = this.newState.rxData["visibility-groups"];
        this.newState.disabled = false;
        if (this.newState.rxData.filterkey && typeof this.newState.rxData.filterkey === "string") {
          this.newState.rxData.filterkey = this.newState.rxData.filterkey.split(/[;,]+/).map((f) => f.trim()).filter((f) => f);
        }
        if ((userGroups == null ? void 0 : userGroups.length) && !this.isUserMemberOfGroup(this.props.context.user, userGroups)) {
          if (this.newState.rxData["visibility-groups-action"] === "disabled") {
            this.newState.disabled = true;
          } else {
            this.newState.visible = false;
          }
        }
      }
      if (doNotApplyState) {
        const newState = this.newState;
        this.newState = null;
        return newState;
      }
      if (this.updateTimer) {
        clearTimeout(this.updateTimer);
        this.updateTimer = null;
      }
      if (JSON.stringify(this.state.values) !== JSON.stringify(this.newState.values) || JSON.stringify(this.state.rxData) !== JSON.stringify(this.newState.rxData) || JSON.stringify(this.state.rxStyle) !== JSON.stringify(this.newState.rxStyle) || JSON.stringify(this.state.applyBindings) !== JSON.stringify(this.newState.applyBindings)) {
        this.updateTimer = setTimeout(() => {
          this.updateTimer = void 0;
          const newState = this.newState ?? null;
          this.newState = null;
          if (newState) {
            this.setState(newState);
          }
        }, 50);
      } else {
        this.newState = null;
      }
      return null;
    }
    applyBinding(stateId, newState) {
      var _a;
      (_a = this.linkContext.bindings[stateId]) == null ? void 0 : _a.forEach((item) => {
        const value = this.props.context.formatUtils.formatBinding({
          format: item.format,
          view: item.view,
          wid: this.props.id,
          widget: this.props.context.views[item.view].widgets[this.props.id],
          widgetData: newState.rxData,
          values: newState.values,
          moment: this.props.context.moment
        });
        if (item.type === "data") {
          newState.rxData[item.attr] = value;
        } else if (newState.rxStyle) {
          newState.rxStyle[item.attr] = value;
        }
      });
    }
    componentDidMount() {
      super.componentDidMount();
      const localStateIds = this.linkContext.IDs.filter((id) => isLocalStateId(id));
      if (localStateIds.length) {
        this.localStateChangeCb = (_arg, id, val, ack, ts) => {
          if (!localStateIds.includes(id)) {
            return;
          }
          this.onStateChanged(id, {
            val,
            ack,
            ts
          });
        };
        window.vis.registerOnChange(this.localStateChangeCb, "val", this.props.id);
      }
      if (this.linkContext.IDs.length) {
        this.props.context.socket.subscribeStateAsync(this.linkContext.IDs, this.onStateChangedBind).catch((e) => console.error(`Cannot subscribe on ${this.linkContext.IDs}: ${e}`));
      }
    }
    onRxDataChanged(_prevRxData) {
    }
    onRxStyleChanged(_prevRxStyle) {
    }
    componentDidUpdate(_prevProps, prevState) {
      if (prevState) {
        if (JSON.stringify(this.state.rxData) !== JSON.stringify(prevState.rxData)) {
          this.onRxDataChanged(prevState.rxData);
        }
        if (JSON.stringify(this.state.rxStyle) !== JSON.stringify(prevState.rxStyle)) {
          this.onRxStyleChanged(prevState.rxStyle);
        }
      }
    }
    componentWillUnmount() {
      if (this.linkContext.IDs.length) {
        this.props.context.socket.unsubscribeState(this.linkContext.IDs, this.onIoBrokerStateChanged);
      }
      if (this.localStateChangeCb) {
        window.vis.unregisterOnChange(this.localStateChangeCb, "val", this.props.id);
      }
      super.componentWillUnmount();
    }
    isWidgetVisibleForGroup(newState) {
      const userGroups = newState.rxData["visibility-groups"];
      if (newState.rxData["visibility-groups-action"] === "hide") {
        if ((userGroups == null ? void 0 : userGroups.length) && !this.isUserMemberOfGroup(this.props.context.user, userGroups)) {
          return false;
        }
      }
      return true;
    }
    checkVisibility(stateId, newState) {
      newState = newState || this.state;
      if (!this.isWidgetVisibleForGroup(newState)) {
        return false;
      }
      if (!this.state.editMode) {
        if (!this.isWidgetFilteredOut(newState.rxData)) {
          if (stateId) {
            if (this.linkContext.visibility[stateId]) {
              return !VisBaseWidget.isWidgetHidden(newState.rxData, newState.values, this.props.id);
            }
          } else {
            return !VisBaseWidget.isWidgetHidden(newState.rxData, newState.values, this.props.id);
          }
        } else {
          return false;
        }
      }
      return true;
    }
    onPropertiesUpdated() {
      const oldIDs = this.linkContext.IDs;
      this.linkContext = {
        IDs: [],
        bindings: {},
        visibility: {},
        lastChanges: {},
        signals: {},
        widgetAttrInfo: this.linkContext.widgetAttrInfo
      };
      const context = this.props.context;
      getUsedObjectIDsInWidget(context.views, this.props.view, this.props.id, this.linkContext);
      const unsubscribe = oldIDs.filter((id) => !this.linkContext.IDs.includes(id));
      if (unsubscribe.length) {
        context.socket.unsubscribeState(unsubscribe, this.onIoBrokerStateChanged);
      }
      const subscribe = this.linkContext.IDs.filter((id) => !oldIDs.includes(id));
      if (subscribe.length) {
        void context.socket.subscribeState(subscribe, this.onIoBrokerStateChanged);
      }
      this.onStateChanged();
    }
    formatValue(value, round) {
      var _a, _b;
      if (typeof value === "number") {
        if (round === 1) {
          value = Math.round(value * 10) / 10;
        } else if (round === 0) {
          value = Math.round(value);
        } else {
          value = Math.round(value * 100) / 100;
        }
        if ((_b = (_a = this.props.context.systemConfig) == null ? void 0 : _a.common) == null ? void 0 : _b.isFloatComma) {
          value = value.toString().replace(".", ",");
        }
      }
      return value === void 0 || value === null ? "" : value.toString();
    }
    wrapContent(content, addToHeader, cardContentStyle, headerStyle, onCardClick, components) {
      var _a, _b;
      if (this.props.context.views[this.props.view].widgets[this.props.id].usedInWidget) {
        return content;
      }
      const MyCard = (components == null ? void 0 : components.Card) || __mf_19;
      const MyCardContent = (components == null ? void 0 : components.CardContent) || __mf_22;
      const style = {
        width: "calc(100% - 8px)",
        height: "calc(100% - 8px)",
        margin: 4,
        boxSizing: "border-box",
        ...(_b = (_a = this.props.customSettings) == null ? void 0 : _a.viewStyle) == null ? void 0 : _b.visCard
      };
      Object.keys(this.state.rxStyle).forEach((attr) => {
        const value = this.state.rxStyle[attr];
        if (value !== null && value !== void 0 && POSSIBLE_MUI_STYLES.includes(attr)) {
          attr = attr.replace(/(-\w)/g, (text) => text[1].toUpperCase());
          style[attr] = value;
        }
      });
      this.wrappedContent = true;
      return jsxRuntimeExports.jsx(MyCard, {
        className: "vis_rx_widget_card",
        style,
        onClick: onCardClick,
        children: jsxRuntimeExports.jsxs(MyCardContent, {
          className: "vis_rx_widget_card_content",
          style: {
            display: "flex",
            flexDirection: "column",
            alignItems: "center",
            height: "calc(100% - 32px)",
            paddingBottom: 16,
            position: "relative",
            ...cardContentStyle
          },
          children: [
            this.state.rxData.widgetTitle ? jsxRuntimeExports.jsxs("div", {
              className: "vis_rx_widget_card_name",
              style: {
                display: "flex",
                justifyContent: "space-between",
                width: "100%",
                alignItems: "center"
              },
              children: [
                jsxRuntimeExports.jsx("div", {
                  className: "vis_rx_widget_card_name_div",
                  style: {
                    fontSize: 24,
                    paddingTop: 0,
                    paddingBottom: 4,
                    ...headerStyle
                  },
                  children: this.state.rxData.widgetTitle
                }),
                addToHeader || null
              ]
            }) : addToHeader || null,
            content
          ]
        })
      });
    }
    renderWidgetBody(props) {
      var _a;
      props.id = this.props.id;
      props.className = `vis-widget${this.state.rxData.class ? ` ${this.state.rxData.class}` : ""}`;
      if (!this.state.editMode && this.state.disabled) {
        props.className = addClass(props.className, "vis-user-disabled");
      }
      Object.keys(this.state.rxStyle).forEach((attr) => {
        const value = this.state.rxStyle[attr];
        if (value !== null && value !== void 0) {
          if (!this.wrappedContent || !POSSIBLE_MUI_STYLES.includes(attr)) {
            attr = attr.replace(/(-\w)/g, (text) => text[1].toUpperCase());
            props.style[attr] = value;
          }
        }
      });
      if (this.props.isRelative) {
        props.style.position = ((_a = this.state.rxStyle) == null ? void 0 : _a.position) || "relative";
        delete props.style.top;
        delete props.style.left;
      } else {
        props.style.position = "absolute";
      }
      if (this.state.editMode) {
        const zIndex = this.state.rxStyle ? parseInt(this.state.rxStyle["z-index"] || "0", 10) : 0;
        if (this.state.selected) {
          props.style.zIndex = 800 + zIndex;
        } else {
          props.style.zIndex = zIndex;
        }
      }
      return null;
    }
    getWidgetView(view, props) {
      const context = this.props.context;
      const VisViewComponent = context.VisView;
      props = props || {};
      return jsxRuntimeExports.jsx(VisViewComponent, {
        context: this.props.context,
        viewsActiveFilter: this.props.viewsActiveFilter,
        activeView: view,
        editMode: false,
        view,
        visInWidget: true,
        theme: this.props.context.theme,
        ...props
      }, `${this.props.id}_${view}`);
    }
    getWidgetInWidget(view, wid, props) {
      var _a;
      props = props || {};
      return this.props.context.VisView.getOneWidget(props.index || 0, this.props.context.views[view].widgets[wid], {
        context: this.props.context,
        editMode: this.state.editMode,
        id: wid,
        isRelative: props.isRelative !== void 0 ? props.isRelative : true,
        mouseDownOnView: this.mouseDownOnView,
        moveAllowed: false,
        ignoreMouseEvents: this.state.editMode ? true : this.ignoreMouseEvents,
        onIgnoreMouseEvents: this.props.onIgnoreMouseEvents,
        refParent: props.refParent,
        askView: this.props.askView,
        relativeWidgetOrder: [
          wid
        ],
        selectedGroup: this.props.selectedGroup,
        selectedWidgets: ((_a = this.movement) == null ? void 0 : _a.selectedWidgetsWithRectangle) || this.props.selectedWidgets,
        view,
        viewsActiveFilter: this.props.viewsActiveFilter,
        customSettings: this.props.customSettings
      });
    }
    isSignalVisible(index) {
      const oid = this.state.rxData[`signals-oid-${index}`];
      if (oid) {
        let val = this.state.values[`${oid}.val`];
        const condition = this.state.rxData[`signals-cond-${index}`] ?? "==";
        let targetValue = this.state.rxData[`signals-val-${index}`] ?? "true";
        if (val === void 0 || val === null) {
          return condition === "not exist";
        }
        if (!condition || targetValue === void 0 || targetValue === null) {
          return condition === "not exist";
        }
        if (val === "null" && condition !== "exist" && condition !== "not exist") {
          return false;
        }
        const valueType = typeof val;
        if (valueType === "boolean" || val === "false" || val === "true") {
          targetValue = targetValue === "true" || targetValue === true || targetValue === 1 || targetValue === "1";
        } else if (valueType === "number") {
          targetValue = parseFloat(targetValue);
        } else if (valueType === "object") {
          val = JSON.stringify(val);
        }
        switch (condition) {
          case "==":
            targetValue = targetValue.toString();
            val = val.toString();
            if (val === "1") {
              val = "true";
            }
            if (targetValue === "1") {
              targetValue = "true";
            }
            if (val === "0") {
              val = "false";
            }
            if (targetValue === "0") {
              targetValue = "false";
            }
            return targetValue === val;
          case "!=":
            targetValue = targetValue.toString();
            val = val.toString();
            if (val === "1") {
              val = "true";
            }
            if (targetValue === "1") {
              targetValue = "true";
            }
            if (val === "0") {
              val = "false";
            }
            if (targetValue === "0") {
              targetValue = "false";
            }
            return targetValue !== val;
          case ">=":
            return val >= targetValue;
          case "<=":
            return val <= targetValue;
          case ">":
            return val > targetValue;
          case "<":
            return val < targetValue;
          case "consist":
            targetValue = targetValue.toString();
            val = val.toString();
            return val.toString().includes(targetValue);
          case "not consist":
            targetValue = targetValue.toString();
            val = val.toString();
            return !val.toString().includes(targetValue);
          case "exist":
            return targetValue !== "null";
          case "not exist":
            return targetValue === "null";
          default:
            console.log(`Unknown signals condition for ${this.props.id}: ${condition}`);
            return false;
        }
      } else {
        return false;
      }
    }
    static text2style(textStyle, style) {
      if (textStyle) {
        style = style || {};
        const parts = textStyle.split(";");
        parts.forEach((part) => {
          const [attr, value] = part.split(":");
          if (attr && value) {
            const attrParts = attr.trim().split("-");
            for (let p = 1; p < attrParts.length; p++) {
              attrParts[p] = attrParts[p][0].toUpperCase() + attrParts[p].substring(1);
            }
            style[attrParts.join("")] = value.trim();
          }
        });
      }
      return style;
    }
    renderSignal(index) {
      const oid = this.state.rxData[`signals-oid-${index}`];
      if (!oid || oid === "nothing_selected") {
        return null;
      }
      if (this.props.editMode && this.state.rxData[`signals-hide-edit-${index}`]) {
        return null;
      }
      if (this.props.editMode || this.isSignalVisible(index)) {
        let icon = this.state.rxData[`signals-smallIcon-${index}`];
        let color;
        if (icon) {
          color = this.state.rxData[`signals-color-${index}`];
        } else {
          icon = this.state.rxData[`signals-icon-${index}`];
        }
        const style = {
          color,
          position: "absolute",
          top: `${parseInt(this.state.rxData[`signals-vert-${index}`], 10) || 0}%`,
          left: `${parseInt(this.state.rxData[`signals-horz-${index}`], 10) || 0}%`,
          zIndex: 10,
          textAlign: "center",
          pointerEvents: "none"
        };
        if (icon) {
          const imageStyle = {
            width: parseFloat(this.state.rxData[`signals-icon-size-${index}`]) || 32,
            height: "auto"
          };
          icon = jsxRuntimeExports.jsx(__mf_15, {
            src: icon,
            style: imageStyle,
            className: "vis-signal-icon"
          });
        }
        VisRxWidget.text2style(this.state.rxData[`signals-icon-style-${index}`], style);
        let text = this.state.rxData[`signals-text-${index}`];
        if (text) {
          const textStyle = {
            color: this.state.rxData[`signals-color-${index}`]
          };
          VisRxWidget.text2style(this.state.rxData[`signals-text-style-${index}`], textStyle);
          text = jsxRuntimeExports.jsx("div", {
            className: "vis-signal-text",
            style: textStyle,
            children: this.state.rxData[`signals-text-${index}`].replace("%s", (this.state.values[`${oid}.val`] ?? "").toString())
          });
        } else {
          text = null;
        }
        return jsxRuntimeExports.jsxs("div", {
          style,
          className: this.state.rxData[`signals-blink-${index}`] ? "vis-signals-blink" : null,
          children: [
            icon,
            text
          ]
        });
      }
      return null;
    }
    renderLastChange(widgetStyle) {
      const oid = this.state.rxData["lc-oid"];
      if (!oid || oid === "nothing_selected") {
        return null;
      }
      const border = parseInt(this.state.rxData["lc-border-radius"], 10) || 0;
      const style = {
        backgroundColor: "rgba(182, 182, 182, 0.6)",
        fontFamily: "Tahoma",
        position: "absolute",
        zIndex: 0,
        borderRadius: this.state.rxData["lc-position-horz"] === "left" ? `${border}px 0 0 ${border}px` : this.state.rxData["lc-position-horz"] === "right" ? `0 ${border}px ${border}px 0` : border,
        whiteSpace: "nowrap"
      };
      const fontSize = this.state.rxData["lc-font-size"];
      if (fontSize) {
        if (fontSize.match(/\D/)) {
          style.fontSize = this.state.rxData["lc-font-size"];
        } else {
          style.fontSize = parseFloat(this.state.rxData["lc-font-size"]);
        }
      }
      if (this.state.rxData["lc-font-style"]) {
        style.fontStyle = this.state.rxData["lc-font-style"];
      }
      if (this.state.rxData["lc-font-family"]) {
        style.fontFamily = this.state.rxData["lc-font-family"];
      }
      if (this.state.rxData["lc-bkg-color"]) {
        style.backgroundColor = this.state.rxData["lc-bkg-color"];
      }
      if (this.state.rxData["lc-color"]) {
        style.color = this.state.rxData["lc-color"];
      }
      if (this.state.rxData["lc-border-width"]) {
        style.borderWidth = parseInt(this.state.rxData["lc-border-width"], 10) || 0;
      }
      if (this.state.rxData["lc-border-style"]) {
        style.borderStyle = this.state.rxData["lc-border-style"];
      }
      if (this.state.rxData["lc-border-color"]) {
        style.borderColor = this.state.rxData["lc-border-color"];
      }
      const padding = parseInt(this.state.rxData["lc-padding"], 10);
      if (padding) {
        style.padding = padding;
      } else {
        style.paddingTop = 3;
        style.paddingBottom = 3;
      }
      if (this.state.rxData["lc-zindex"]) {
        style.zIndex = this.state.rxData["lc-zindex"];
      }
      if (this.state.rxData["lc-position-vert"] === "top") {
        style.top = parseInt(this.state.rxData["lc-offset-vert"], 10);
      } else if (this.state.rxData["lc-position-vert"] === "bottom") {
        style.bottom = parseInt(this.state.rxData["lc-offset-vert"], 10);
      } else if (this.state.rxData["lc-position-vert"] === "middle") {
        style.top = `calc(50% + ${parseInt(this.state.rxData["lc-offset-vert"], 10) - 10}px)`;
      }
      const offset = parseFloat(this.state.rxData["lc-offset-horz"]) || 0;
      if (this.state.rxData["lc-position-horz"] === "left") {
        style.right = `calc(100% - ${offset}px)`;
        if (!padding) {
          style.paddingRight = 10;
          style.paddingLeft = 10;
        }
      } else if (this.state.rxData["lc-position-horz"] === "right") {
        style.left = `calc(100% + ${offset}px)`;
        if (!padding) {
          style.paddingRight = 10;
          style.paddingLeft = 10;
        }
      } else if (this.state.rxData["lc-position-horz"] === "middle") {
        style.left = `calc(50% + ${offset}px)`;
      }
      const divLastChange = window.document.createElement("div");
      divLastChange.className = "";
      calculateOverflow(widgetStyle);
      return jsxRuntimeExports.jsx("div", {
        className: "vis-last-change",
        style,
        children: this.formatDate(this.state.values[`${this.state.rxData["lc-oid"]}.${this.state.rxData["lc-type"] === "last-change" ? "lc" : "ts"}`], this.state.rxData["lc-format"], this.state.rxData["lc-is-interval"], this.state.rxData["lc-is-moment"], true)
      });
    }
    renderSignals() {
      var _a;
      const count = parseInt((_a = this.state.rxData) == null ? void 0 : _a["signals-count"], 10) || 0;
      if (!count) {
        return null;
      }
      const result = [];
      for (let i = 0; i < count; i++) {
        result.push(this.renderSignal(i));
      }
      return result;
    }
    render() {
      if (!this.state.visible && !this.state.editMode) {
        return null;
      }
      if (this.state.applyBindings && !this.bindingsTimer) {
        this.bindingsTimer = setTimeout(() => {
          this.bindingsTimer = void 0;
          this.onPropertiesUpdated();
          const refs = [];
          const oWidget = this.props.context.views[this.props.view].widgets[this.props.id];
          const attrs = Object.keys(oWidget.data);
          attrs.forEach((attr) => {
            if (attr.startsWith("widget") && oWidget.data[attr]) {
              const ref = this.props.askView && this.props.askView("getRef", {
                id: oWidget.data[attr]
              });
              ref && refs.push(ref);
            }
          });
          this.informIncludedWidgets && clearTimeout(this.informIncludedWidgets);
          if (refs) {
            this.informIncludedWidgets = setTimeout(() => {
              this.informIncludedWidgets = void 0;
              refs.forEach((ref) => ref.onCommand("updatePosition"));
            }, 200);
          }
        }, 10);
      }
      if (this.state.editMode && this.filterDisplay !== void 0 && this.refService.current) {
        this.refService.current.style.display = this.filterDisplay;
        delete this.filterDisplay;
      }
      return super.render();
    }
    getWidgetInfo() {
      throw new Error("not implemented");
    }
  };
  visRxWidget = Object.freeze(Object.defineProperty({
    __proto__: null,
    POSSIBLE_MUI_STYLES,
    VisRxWidget,
    default: VisRxWidget
  }, Symbol.toStringTag, {
    value: "Module"
  }));
});
export {
  isVarFinite as A,
  replaceGroupAttr as B,
  selectView as C,
  DEFAULT_PERMISSIONS as D,
  parseDimension as E,
  hasWidgetAccess as F,
  visRxWidget as G,
  NOTHING_SELECTED as N,
  VisRxWidget as V,
  __tla,
  recalculateFields as a,
  selectWidget as b,
  getNewWidgetId as c,
  deepClone as d,
  extractBinding as e,
  findWidgetUsages as f,
  getNewWidgetIdNumber as g,
  hasViewAccess as h,
  isGroup as i,
  getNewGroupId as j,
  applyTitleAndIcon as k,
  isLocalStateId as l,
  getUrlParameter as m,
  updateProject as n,
  updateActiveUser as o,
  pasteGroup as p,
  hasProjectAccess as q,
  readFile as r,
  store as s,
  pasteSingleWidget as t,
  updateWidget as u,
  unsyncMultipleWidgets as v,
  VisBaseWidget as w,
  getUsedObjectIDsInWidget as x,
  addClass as y,
  calculateOverflow as z
};