/**
 * DevExtreme (renovation/viz/core/base_widget.js)
 * Version: 21.1.0 (build 21016-0316)
 * Build date: Sat Jan 16 2021
 *
 * Copyright (c) 2012 - 2021 Developer Express Inc. ALL RIGHTS RESERVED
 * Read about DevExtreme licensing here: https://js.devexpress.com/Licensing/
 */
"use strict";

function _typeof(obj) {
    if ("function" === typeof Symbol && "symbol" === typeof Symbol.iterator) {
        _typeof = function(obj) {
            return typeof obj
        }
    } else {
        _typeof = function(obj) {
            return obj && "function" === typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj
        }
    }
    return _typeof(obj)
}
exports.BaseWidget = exports.viewFunction = void 0;
var _type = require("../../../core/utils/type");
var _combine_classes = require("../../utils/combine_classes");
var _base_props = require("./base_props");
var _config_context = require("../../common/config_context");
var _config_provider = require("../../common/config_provider");
var _svg_root = require("./renderers/svg_root");
var _gray_scale_filter = require("./renderers/gray_scale_filter");
var _utils = require("./utils");
var _resolve_rtl = require("../../utils/resolve_rtl");
var _utils2 = require("./renderers/utils");
var Preact = _interopRequireWildcard(require("preact"));
var _hooks = require("preact/hooks");
var _compat = require("preact/compat");

function _getRequireWildcardCache() {
    if ("function" !== typeof WeakMap) {
        return null
    }
    var cache = new WeakMap;
    _getRequireWildcardCache = function() {
        return cache
    };
    return cache
}

function _interopRequireWildcard(obj) {
    if (obj && obj.__esModule) {
        return obj
    }
    if (null === obj || "object" !== _typeof(obj) && "function" !== typeof obj) {
        return {
            default: obj
        }
    }
    var cache = _getRequireWildcardCache();
    if (cache && cache.has(obj)) {
        return cache.get(obj)
    }
    var newObj = {};
    var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
    for (var key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
            var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
            if (desc && (desc.get || desc.set)) {
                Object.defineProperty(newObj, key, desc)
            } else {
                newObj[key] = obj[key]
            }
        }
    }
    newObj.default = obj;
    if (cache) {
        cache.set(obj, newObj)
    }
    return newObj
}

function _objectWithoutProperties(source, excluded) {
    if (null == source) {
        return {}
    }
    var target = _objectWithoutPropertiesLoose(source, excluded);
    var key, i;
    if (Object.getOwnPropertySymbols) {
        var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
        for (i = 0; i < sourceSymbolKeys.length; i++) {
            key = sourceSymbolKeys[i];
            if (excluded.indexOf(key) >= 0) {
                continue
            }
            if (!Object.prototype.propertyIsEnumerable.call(source, key)) {
                continue
            }
            target[key] = source[key]
        }
    }
    return target
}

function _objectWithoutPropertiesLoose(source, excluded) {
    if (null == source) {
        return {}
    }
    var target = {};
    var sourceKeys = Object.keys(source);
    var key, i;
    for (i = 0; i < sourceKeys.length; i++) {
        key = sourceKeys[i];
        if (excluded.indexOf(key) >= 0) {
            continue
        }
        target[key] = source[key]
    }
    return target
}

function _slicedToArray(arr, i) {
    return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest()
}

function _nonIterableRest() {
    throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")
}

function _unsupportedIterableToArray(o, minLen) {
    if (!o) {
        return
    }
    if ("string" === typeof o) {
        return _arrayLikeToArray(o, minLen)
    }
    var n = Object.prototype.toString.call(o).slice(8, -1);
    if ("Object" === n && o.constructor) {
        n = o.constructor.name
    }
    if ("Map" === n || "Set" === n) {
        return Array.from(o)
    }
    if ("Arguments" === n || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) {
        return _arrayLikeToArray(o, minLen)
    }
}

function _arrayLikeToArray(arr, len) {
    if (null == len || len > arr.length) {
        len = arr.length
    }
    for (var i = 0, arr2 = new Array(len); i < len; i++) {
        arr2[i] = arr[i]
    }
    return arr2
}

function _iterableToArrayLimit(arr, i) {
    if ("undefined" === typeof Symbol || !(Symbol.iterator in Object(arr))) {
        return
    }
    var _arr = [];
    var _n = true;
    var _d = false;
    var _e = void 0;
    try {
        for (var _s, _i = arr[Symbol.iterator](); !(_n = (_s = _i.next()).done); _n = true) {
            _arr.push(_s.value);
            if (i && _arr.length === i) {
                break
            }
        }
    } catch (err) {
        _d = true;
        _e = err
    } finally {
        try {
            if (!_n && null != _i.return) {
                _i.return()
            }
        } finally {
            if (_d) {
                throw _e
            }
        }
    }
    return _arr
}

function _arrayWithHoles(arr) {
    if (Array.isArray(arr)) {
        return arr
    }
}

function _extends() {
    _extends = Object.assign || function(target) {
        for (var i = 1; i < arguments.length; i++) {
            var source = arguments[i];
            for (var key in source) {
                if (Object.prototype.hasOwnProperty.call(source, key)) {
                    target[key] = source[key]
                }
            }
        }
        return target
    };
    return _extends.apply(this, arguments)
}

function ownKeys(object, enumerableOnly) {
    var keys = Object.keys(object);
    if (Object.getOwnPropertySymbols) {
        var symbols = Object.getOwnPropertySymbols(object);
        if (enumerableOnly) {
            symbols = symbols.filter((function(sym) {
                return Object.getOwnPropertyDescriptor(object, sym).enumerable
            }))
        }
        keys.push.apply(keys, symbols)
    }
    return keys
}

function _objectSpread(target) {
    for (var i = 1; i < arguments.length; i++) {
        var source = null != arguments[i] ? arguments[i] : {};
        if (i % 2) {
            ownKeys(Object(source), true).forEach((function(key) {
                _defineProperty(target, key, source[key])
            }))
        } else if (Object.getOwnPropertyDescriptors) {
            Object.defineProperties(target, Object.getOwnPropertyDescriptors(source))
        } else {
            ownKeys(Object(source)).forEach((function(key) {
                Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key))
            }))
        }
    }
    return target
}

function _defineProperty(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        })
    } else {
        obj[key] = value
    }
    return obj
}
var getCssClasses = function(model) {
    var containerClassesMap = _defineProperty({
        "dx-widget": true,
        "dx-visibility-change-handler": true
    }, String(model.className), !!model.className);
    return (0, _combine_classes.combineClasses)(containerClassesMap)
};
var calculateCanvas = function(model) {
    var _model$size, _model$margin, _model$defaultCanvas;
    var _ref = null !== (_model$size = model.size) && void 0 !== _model$size ? _model$size : {},
        height = _ref.height,
        width = _ref.width;
    var margin = null !== (_model$margin = model.margin) && void 0 !== _model$margin ? _model$margin : {};
    var defaultCanvas = null !== (_model$defaultCanvas = model.defaultCanvas) && void 0 !== _model$defaultCanvas ? _model$defaultCanvas : {};
    var elementWidth = !(0, _utils.sizeIsValid)(width) ? (0, _utils.getElementWidth)(model.containerRef) : 0;
    var elementHeight = !(0, _utils.sizeIsValid)(height) ? (0, _utils.getElementHeight)(model.containerRef) : 0;
    var canvas = {
        width: Number(width) <= 0 ? 0 : Math.floor((0, _utils.pickPositiveValue)([width, elementWidth, defaultCanvas.width])),
        height: Number(height) <= 0 ? 0 : Math.floor((0, _utils.pickPositiveValue)([height, elementHeight, defaultCanvas.height])),
        left: (0, _utils.pickPositiveValue)([margin.left, defaultCanvas.left]),
        top: (0, _utils.pickPositiveValue)([margin.top, defaultCanvas.top]),
        right: (0, _utils.pickPositiveValue)([margin.right, defaultCanvas.right]),
        bottom: (0, _utils.pickPositiveValue)([margin.bottom, defaultCanvas.bottom])
    };
    if (canvas.width - canvas.left - canvas.right <= 0 || canvas.height - canvas.top - canvas.bottom <= 0) {
        return _objectSpread({}, defaultCanvas)
    }
    return canvas
};
var viewFunction = function(viewModel) {
    var grayFilterId = viewModel.props.disabled ? (0, _utils2.getNextDefsSvgId)() : void 0;
    var canvas = viewModel.props.canvas || {};
    var widget = Preact.h("div", _extends({
        ref: viewModel.containerRef,
        className: viewModel.cssClasses
    }, viewModel.restAttributes), Preact.h(_svg_root.RootSvgElement, {
        rootElementRef: viewModel.svgElementRef,
        className: viewModel.props.classes,
        width: canvas.width,
        height: canvas.height,
        pointerEvents: viewModel.pointerEventsState,
        filter: grayFilterId ? (0, _utils2.getFuncIri)(grayFilterId) : void 0
    }, Preact.h(Preact.Fragment, null, Preact.h("defs", null, grayFilterId && Preact.h(_gray_scale_filter.GrayScaleFilter, {
        id: grayFilterId
    })), viewModel.props.children)));
    return viewModel.shouldRenderConfigProvider ? Preact.h(_config_provider.ConfigProvider, {
        rtlEnabled: viewModel.rtlEnabled
    }, widget) : widget
};
exports.viewFunction = viewFunction;
var BaseWidget = (0, _compat.forwardRef)((function(props, ref) {
    var __containerRef = (0, _hooks.useRef)();
    var __svgElementRef = (0, _hooks.useRef)();
    var _useState = (0, _hooks.useState)((function() {
            return void 0 !== props.canvas ? props.canvas : props.defaultCanvas
        })),
        _useState2 = _slicedToArray(_useState, 2),
        __state_canvas = _useState2[0],
        __state_setCanvas = _useState2[1];
    var config = (0, _hooks.useContext)(_config_context.ConfigContext);
    var __shouldRenderConfigProvider = (0, _hooks.useCallback)((function() {
        var rtlEnabled = props.rtlEnabled;
        return (0, _resolve_rtl.resolveRtlEnabledDefinition)(rtlEnabled, config)
    }), [props.rtlEnabled, config]);
    var __rtlEnabled = (0, _hooks.useCallback)((function() {
        var rtlEnabled = props.rtlEnabled;
        return (0, _resolve_rtl.resolveRtlEnabled)(rtlEnabled, config)
    }), [props.rtlEnabled, config]);
    var __pointerEventsState = (0, _hooks.useCallback)((function() {
        var disabled = props.disabled,
            pointerEvents = props.pointerEvents;
        return disabled ? "none" : pointerEvents
    }), [props.disabled, props.pointerEvents]);
    var __cssClasses = (0, _hooks.useCallback)((function() {
        var className = props.className;
        return getCssClasses({
            className: className
        })
    }), [props.className]);
    var __setCanvas = (0, _hooks.useCallback)((function() {
        var defaultCanvas = props.defaultCanvas,
            margin = props.margin,
            size = props.size;
        var newCanvas = calculateCanvas({
            containerRef: __containerRef.current,
            defaultCanvas: defaultCanvas,
            size: size,
            margin: margin
        });
        if ((0, _type.isDefined)(newCanvas.height) && (0, _type.isDefined)(newCanvas.width) && Object.keys(newCanvas).some((function(key) {
                var _ref2;
                return newCanvas[key] !== (null === (_ref2 = void 0 !== props.canvas ? props.canvas : __state_canvas) || void 0 === _ref2 ? void 0 : _ref2[key])
            }))) {
            __state_setCanvas((function(__state_canvas) {
                return newCanvas
            })), props.canvasChange(newCanvas)
        }
    }), [props.defaultCanvas, props.margin, props.size, props.canvas, __state_canvas, props.canvasChange]);
    var __restAttributes = (0, _hooks.useCallback)((function() {
        var _props$canvas = _objectSpread(_objectSpread({}, props), {}, {
                canvas: void 0 !== props.canvas ? props.canvas : __state_canvas
            }),
            restProps = (_props$canvas.canvas, _props$canvas.canvasChange, _props$canvas.children, _props$canvas.className, _props$canvas.classes, _props$canvas.defaultCanvas, _props$canvas.disabled, _props$canvas.margin, _props$canvas.onContentReady, _props$canvas.pointerEvents, _props$canvas.rtlEnabled, _props$canvas.size, _objectWithoutProperties(_props$canvas, ["canvas", "canvasChange", "children", "className", "classes", "defaultCanvas", "disabled", "margin", "onContentReady", "pointerEvents", "rtlEnabled", "size"]));
        return restProps
    }), [props, __state_canvas]);
    var __svg = (0, _hooks.useCallback)((function() {
        return __svgElementRef.current
    }), []);
    (0, _hooks.useEffect)((function() {
        var onContentReady = props.onContentReady;
        __setCanvas();
        null === onContentReady || void 0 === onContentReady ? void 0 : onContentReady({
            element: __svgElementRef.current
        })
    }), [props.onContentReady, props.defaultCanvas, props.margin, props.size, props.canvas, __state_canvas, props.canvasChange]);
    (0, _hooks.useImperativeHandle)(ref, (function() {
        return {
            svg: __svg
        }
    }), [__svg]);
    return viewFunction({
        props: _objectSpread(_objectSpread({}, props), {}, {
            canvas: void 0 !== props.canvas ? props.canvas : __state_canvas
        }),
        containerRef: __containerRef,
        svgElementRef: __svgElementRef,
        config: config,
        shouldRenderConfigProvider: __shouldRenderConfigProvider(),
        rtlEnabled: __rtlEnabled(),
        pointerEventsState: __pointerEventsState(),
        cssClasses: __cssClasses(),
        setCanvas: __setCanvas,
        restAttributes: __restAttributes()
    })
}));
exports.BaseWidget = BaseWidget;
BaseWidget.defaultProps = _objectSpread({}, _base_props.BaseWidgetProps);
