"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var react_1 = require("react");
var detectElementResize_1 = __importDefault(require("./vendor/detectElementResize"));
var reducer_1 = require("./reducer");
function useDetectElementResize(_a) {
    var id = _a.id, _b = _a.nonce, nonce = _b === void 0 ? "" : _b, _c = _a.onResize, onResize = _c === void 0 ? function () { } : _c, _d = _a.onExit, onExit = _d === void 0 ? function () { } : _d;
    // check if there is an element with the given id
    // otherise fallback to document.body
    var targetNode = document.getElementById(id) || document.body;
    // setup the state
    var _e = (0, react_1.useReducer)(reducer_1.reducer, {
        width: targetNode.offsetWidth,
        height: targetNode.offsetHeight,
        running: false
    }), state = _e[0], setState = _e[1];
    var width = state.width, height = state.height, running = state.running;
    var callOnResize = function (_a) {
        var width = _a.width, height = _a.height;
        return onResize({ width: width, height: height });
    };
    var callbacks = [setState, callOnResize];
    (0, react_1.useEffect)(function () {
        var _detectElementResize = (0, detectElementResize_1.default)(nonce);
        var raf = null;
        function _onResize() {
            if (!running) {
                setState({ running: true });
                if (window.requestAnimationFrame) {
                    raf = window.requestAnimationFrame(runCallbacks);
                }
                else {
                    raf = setTimeout(runCallbacks, 66);
                }
            }
        }
        function runCallbacks() {
            var _targetNode = document.getElementById(id) || document.body;
            var offsetWidth = _targetNode.offsetWidth, offsetHeight = _targetNode.offsetHeight;
            return callbacks.forEach(function (callback) {
                return callback({ width: offsetWidth, height: offsetHeight, running: false });
            });
        }
        _detectElementResize.addResizeListener(targetNode, _onResize);
        // force an initial run
        _onResize();
        return function () {
            if (window.cancelAnimationFrame) {
                window.cancelAnimationFrame(raf);
            }
            else {
                clearTimeout(raf);
            }
            _detectElementResize.removeResizeListener(targetNode, _onResize);
            onExit({ width: width, height: height });
        };
    }, []);
    return [width, height];
}
exports.default = useDetectElementResize;
//# sourceMappingURL=useDetectElementResize.js.map